code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/* Copyright 2012 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
'use strict';
/* Services */
angular.module('tour.services', []).
// Google Analytics
factory('analytics', ['$window',
function(win) {
var track = win.trackPageview || (function() {});
return {
trackView: track
};
}
]).
// Internationalization
factory('i18n', ['translation',
function(translation) {
return {
l: function(key) {
if (translation[key]) return translation[key];
return '(no translation for ' + key + ')';
}
};
}
]).
// Running code
factory('run', ['$window',
function(win) {
return function(code, output, options) {
// PlaygroundOutput is defined in playground.js which is prepended
// to the generated script.js in gotour/tour.go.
// The next line removes the jshint warning.
// global PlaygroundOutput
win.transport.Run(code, PlaygroundOutput(output), options);
};
}
]).
// Formatting code
factory('fmt', ['$http',
function($http) {
return function(body) {
var params = $.param({
'body': body
});
var headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
return $http.post('/fmt', params, {
headers: headers
});
};
}
]).
// Editor context service, kept through the whole app.
factory('editor', ['$window',
function(win) {
var ctx = {
syntax: false,
toggleSyntax: function() {
ctx.syntax = !ctx.syntax;
ctx.paint();
},
paint: function() {
var mode = ctx.syntax && 'text/x-go' || 'text/x-go-comment';
// Wait for codemirror to start.
var set = function() {
if ($('.CodeMirror').length > 0) {
var cm = $('.CodeMirror')[0].CodeMirror;
if (cm.getOption('mode') == mode) {
cm.refresh();
return;
}
cm.setOption('mode', mode);
}
win.setTimeout(set, 10);
};
set();
},
};
return ctx;
}
]).
// Table of contents management and navigation
factory('toc', ['$http', '$q', '$log', 'tableOfContents',
function($http, $q, $log, tableOfContents) {
var modules = tableOfContents;
var lessons = {};
var prevLesson = function(id) {
var mod = lessons[id].module;
var idx = mod.lessons.indexOf(id);
if (idx < 0) return '';
if (idx > 0) return mod.lessons[idx - 1];
idx = modules.indexOf(mod);
if (idx <= 0) return '';
mod = modules[idx - 1];
return mod.lessons[mod.lessons.length - 1];
};
var nextLesson = function(id) {
var mod = lessons[id].module;
var idx = mod.lessons.indexOf(id);
if (idx < 0) return '';
if (idx + 1 < mod.lessons.length) return mod.lessons[idx + 1];
idx = modules.indexOf(mod);
if (idx < 0 || modules.length <= idx + 1) return '';
mod = modules[idx + 1];
return mod.lessons[0];
};
$http.get('/lesson/').then(
function(data) {
lessons = data.data;
for (var m = 0; m < modules.length; m++) {
var module = modules[m];
module.lesson = {};
for (var l = 0; l < modules[m].lessons.length; l++) {
var lessonName = module.lessons[l];
var lesson = lessons[lessonName];
lesson.module = module;
module.lesson[lessonName] = lesson;
}
}
moduleQ.resolve(modules);
lessonQ.resolve(lessons);
}, function(error) {
$log.error('error loading lessons : ', error);
moduleQ.reject(error);
lessonQ.reject(error);
}
);
var moduleQ = $q.defer();
var lessonQ = $q.defer();
return {
modules: moduleQ.promise,
lessons: lessonQ.promise,
prevLesson: prevLesson,
nextLesson: nextLesson
};
}
]);
| JavaScript |
/* Copyright 2012 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
'use strict';
angular.module('tour.values', []).
// List of modules with description and lessons in it.
value('tableOfContents', [{
'id': 'mechanics',
'title': 'Using the tour',
'description': '<p>Welcome to a tour of the <a href="http://golang.org">Go programming language</a>. The tour covers the most important features of the language, mainly:</p>',
'lessons': ['welcome']
}, {
'id': 'basics',
'title': 'Basics',
'description': '<p>The starting point, learn all the basics of the language.</p><p>Declaring variables, calling functions, and all the things you need to know before moving to the next lessons.</p>',
'lessons': ['basics', 'flowcontrol', 'moretypes']
}, {
'id': 'methods',
'title': 'Methods and interfaces',
'description': '<p>Learn how to define methods on types, how to declare interfaces, and how to put everything together.</p>',
'lessons': ['methods']
}, {
'id': 'concurrency',
'title': 'Concurrency',
'description': '<p>Go provides concurrency features as part of the core language.</p><p>This module goes over goroutines and channels, and how they are used to implement different concurrency patterns.</p>',
'lessons': ['concurrency']
}]).
// translation
value('translation', {
'off': 'off',
'on': 'on',
'syntax': 'Syntax-Highlighting',
'lineno': 'Line-Numbers',
'reset': 'Reset Slide',
'format': 'Format Source Code',
'kill': 'Kill Program',
'run': 'Run',
'compile': 'Compile and Run',
'more': 'Options',
'toc': 'Table of Contents',
'prev': 'Previous',
'next': 'Next',
'waiting': 'Waiting for remote server...',
'errcomm': 'Error communicating with remote server.',
}).
// Config for codemirror plugin
value('ui.config', {
codemirror: {
mode: 'text/x-go',
matchBrackets: true,
lineNumbers: true,
autofocus: true,
indentWithTabs: true,
lineWrapping: true,
extraKeys: {
'Shift-Enter': function() {
$('#run').click();
},
'Ctrl-Enter': function() {
$('#format').click();
},
'PageDown': function() {
return false;
},
'PageUp': function() {
return false;
},
}
}
});
| JavaScript |
/* Copyright 2012 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
'use strict';
/* Directives */
angular.module('tour.directives', []).
// onpageup executes the given expression when Page Up is released.
directive('onpageup', function() {
return function(scope, elm, attrs) {
elm.attr('tabindex', 0);
elm.keyup(function(evt) {
var key = evt.key || evt.keyCode;
if (key == 33) {
scope.$apply(attrs.onpageup);
evt.preventDefault();
}
});
};
}).
// onpagedown executes the given expression when Page Down is released.
directive('onpagedown', function() {
return function(scope, elm, attrs) {
elm.attr('tabindex', 0);
elm.keyup(function(evt) {
var key = evt.key || evt.keyCode;
if (key == 34) {
scope.$apply(attrs.onpagedown);
evt.preventDefault();
}
});
};
}).
// autofocus sets the focus on the given element when the condition is true.
directive('autofocus', function() {
return function(scope, elm, attrs) {
elm.attr('tabindex', 0);
scope.$watch(function() {
return scope.$eval(attrs.autofocus);
}, function(val) {
if (val === true) $(elm).focus();
});
};
}).
// syntax-checkbox activates and deactivates
directive('syntaxCheckbox', ['editor',
function(editor) {
return function(scope, elm) {
elm.click(function() {
editor.toggleSyntax();
scope.$digest();
});
scope.editor = editor;
};
}
]).
// verticalSlide creates a sliding separator between the left and right elements.
// e.g.:
// <div id="header">Some content</div>
// <div vertical-slide top="#header" bottom="#footer"></div>
// <div id="footer">Some footer</div>
directive('verticalSlide', ['editor',
function(editor) {
return function(scope, elm, attrs) {
var moveTo = function(x) {
if (x < 0) {
x = 0;
}
if (x > $(window).width()) {
x = $(window).width();
}
elm.css('left', x);
$(attrs.left).width(x);
$(attrs.right).offset({
left: x
});
editor.x = x;
};
elm.draggable({
axis: 'x',
drag: function(event) {
moveTo(event.clientX);
return true;
},
containment: 'parent',
});
if (editor.x !== undefined) {
moveTo(editor.x);
}
};
}
]).
// horizontalSlide creates a sliding separator between the top and bottom elements.
// <div id="menu">Some menu</div>
// <div vertical-slide left="#menu" bottom="#content"></div>
// <div id="content">Some content</div>
directive('horizontalSlide', ['editor',
function(editor) {
return function(scope, elm, attrs) {
var moveTo = function(y) {
var top = $(attrs.top).offset().top;
if (y < top) {
y = top;
}
elm.css('top', y - top);
$(attrs.top).height(y - top);
$(attrs.bottom).offset({
top: y,
height: 0
});
editor.y = y;
};
elm.draggable({
axis: 'y',
drag: function(event) {
moveTo(event.clientY);
return true;
},
containment: 'parent',
});
if (editor.y !== undefined) {
moveTo(editor.y);
}
};
}
]).
directive('tableOfContentsButton', function() {
var speed = 250;
return {
restrict: 'A',
templateUrl: '/static/partials/toc-button.html',
link: function(scope, elm, attrs) {
elm.on('click', function() {
var toc = $(attrs.tableOfContentsButton);
// hide all non active lessons before displaying the toc.
var visible = toc.css('display') != 'none';
if (!visible) {
toc.find('.toc-lesson:not(.active) .toc-page').hide();
toc.find('.toc-lesson.active .toc-page').show();
}
toc.toggle('slide', {
direction: 'right'
}, speed);
// if fullscreen hide the rest of the content when showing the atoc.
var fullScreen = toc.width() == $(window).width();
if (fullScreen) $('#editor-container')[visible ? 'show' : 'hide']();
});
}
};
}).
// side bar with dynamic table of contents
directive('tableOfContents', ['$routeParams', 'toc',
function($routeParams, toc) {
var speed = 250;
return {
restrict: 'A',
templateUrl: '/static/partials/toc.html',
link: function(scope, elm) {
scope.toc = toc;
scope.params = $routeParams;
scope.toggleLesson = function(id) {
var l = $('#toc-l-' + id + ' .toc-page');
l[l.css('display') == 'none' ? 'slideDown' : 'slideUp']();
};
scope.$watch(function() {
return scope.params.lessonId + scope.params.lessonId;
}, function() {
$('.toc-lesson:not(#toc-l-' + scope.params.lessonId + ') .toc-page').slideUp(speed);
});
scope.hideTOC = function(fullScreenOnly) {
var fullScreen = elm.find('.toc').width() == $(window).width();
if (fullScreenOnly && !fullScreen) {
return;
}
$('.toc').toggle('slide', {
direction: 'right'
}, speed);
};
}
};
}
]); | JavaScript |
function isEmpty(target,changeTag){
if(target.val() == ''){
changeTag.html('<font style="color:red">You can\'t leave this empty</font>');
return true;
}
else{
changeTag.html('');
return false;
}
}
function checkUsername(){
if(!isEmpty($('#username'),$('#errorUsername'))){
$.post("check_username.php",{username: $('#username').val()},function(data){
if(data == 'false')
$('#errorUsername').html('<font style="color:red">Someone already has that username. Try anothor?</font>');
else
$('#errorUsername').html('');
});
}
}
function checkPassword(){
isEmpty($('#password'),$('#errorPassword'));
}
function checkConfirmPassword(){
if(!isEmpty($('#confirmPassword'),$('#errorPassword2'))){
if($('#password').val() != $('#confirmPassword').val())
$('#errorPassword2').html('<font style="color:red">It is not same as password</font>');
else
$('#errorPassword2').html('');
}
}
function checkSecurityQuestion(target,changeTag){
if(!isEmpty(target,changeTag)){
if(target.val() == '')
changeTag.html('<font style="color:red">Question is empty</font>');
else
changeTag.html('');
}
}
function checkSecurityAnswer(target,changeTag){
isEmpty(target,changeTag);
}
$(document).ready(function(){
$('#username').focusout(function(){
checkUsername();
});
$('#password').focusout(function(){
checkPassword();
});
$('#confirmPassword').focusout(function(){
checkConfirmPassword();
});
$('#securityQuestion1').focusout(function(){
checkSecurityQuestion($(this),$('#errorSQ1'));
});
$('#securityAnswer1').focusout(function(){
checkSecurityAnswer($(this),$('#errorSA1'));
});
$('#securityQuestion2').focusout(function(){
checkSecurityQuestion($(this),$('#errorSQ2'));
});
$('#securityAnswer2').focusout(function(){
checkSecurityAnswer($(this),$('#errorSA2'));
});
$('#agree').click(function(){
if(this.checked)
$('input[type="submit"]').removeAttr('disabled');
else
$('input[type="submit"]').attr('disabled','disabled');
});
}); | JavaScript |
$(document).ready(function(){
$('#addQuestion').click(function(){
var questionHtml = '<input type="hidden" name="choiceCount[]" value="0">';
questionHtml += '<div><select name="qTypes[]" style="width:100px">';
questionHtml += '<option value="open">Open</option>';
questionHtml += '<option value="mc">MC</option>';
questionHtml += '</select>';
questionHtml += ' <input type="text" class="question" name="question[]" placeholder="Enter your question here" size="50">';
questionHtml += ' <button type="button" class="minusQuestion" style="width:30px">-</button></div>';
questionHtml += '<div class="error"></div>';
$('<div>'+questionHtml+'</div><br>').appendTo($('#allQuestionBlock'));
});
$(document).delegate('.minusQuestion','click',function(){
var removeElement = $(this).parent().parent();
if($('.question').size() > 1){
removeElement.next().remove();
removeElement.remove();
}
});
$(document).delegate('select','change',function(){
var hidden = $(this).parent().siblings('input[type=hidden]').eq(0);
if($(this).val() == 'mc'){
var questionBlock = $(this).parent().parent();
var htmlContent='<div class="table"><div class="tr">';
htmlContent += '<div class="td"><div><div><input type="text" class="choice" name="choice[]" placeholder="Enter content of choice" size="30">';
htmlContent += ' <button type="button" class="minusChoice" style="width:30px">-</button></div>';
htmlContent += '<div class="error"></div></div></div>';
htmlContent += '<div class="td"><button type="button" class="addChoice" style="margin-left: 30px">+</button></div>';
htmlContent += '</div></div>';
hidden.val(parseInt(hidden.val())+1);
$(htmlContent).appendTo(questionBlock);
}
else{
$(this).parent().siblings('div').eq(1).remove();
hidden.val(0);
}
});
$(document).delegate('.addChoice','click',function(){
var choicesBlock = $(this).parent().siblings('div').eq(0);
var choiceBlock = choicesBlock.children('div').eq(0);
var htmlContent = '<div><div><input type="text" class="choice" name="choice[]" placeholder="Enter content of choice" size="30">';
htmlContent += ' <button type="button" class="minusChoice" style="width:30px">-</button></div>';
htmlContent += '<div class="error"></div></div>';
$(htmlContent).appendTo(choicesBlock);
var hidden = choicesBlock.parent().parent().siblings('input[type=hidden]').eq(0);
hidden.val(parseInt(hidden.val())+1);
});
$(document).delegate('.minusChoice','click',function(){
var removeElement = $(this).parent().parent();
if(removeElement.siblings('div').size() > 0){
var hidden = removeElement.parent().parent().parent().siblings('input[type=hidden]').eq(0);
hidden.val(parseInt(hidden.val())-1);
removeElement.remove();
}
});
$('#deadlineEnable').click(function(){
$('#deadlineError').html('');
$('#deadlineSetting').toggle(this.checked);
});
$('#passwordEnable').click(function(){
$('#passwordSetting').toggle(this.checked);
});
$('#groupsEnable').click(function(){
$('#groupsSetting').toggle(this.checked);
});
$(document).delegate('.minusGroup','click',function(){
if($('.group').size() > 1){
$(this).parent().remove();
}
});
$('#addGroup').click(function(){
var groupsBlock = $(this).parent().siblings('div').eq(0);
var groupHtml = groupsBlock.children('div').eq(0).html();
$('<div class="group">'+groupHtml+'</div>').appendTo(groupsBlock);
});
});
| JavaScript |
document.write('<div id="tester">an advertisement</div>'); | JavaScript |
//Document By JodJin 2011/11/07
var W,H,mW,mH;
var mapObj={
map:null,
dataDelay:null,
init:function(){
this.autoSize();
this.map=new mapApi(c,x,y,z);
},
autoSize:function(){
var mhDis=$("#mapheader").css("display");
var mhH=$("#mapheader").height()+15;
if(mhDis=="none"){mhH=0;}
W=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
H=window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
mW=W;
mH=H-mhH-($("#mapnoti").height()+1);
$("#"+c).css({width:""+mW+"px",height:""+mH+"px"});
},
inData:function(){
var me=this;
me.closeWin();
var bounds=me.map.getBound();
var paramsIt=mapPatch.objMerge(bounds,params);
var doParams=mapPatch.reParams(paramsIt);
alert(doParams);
$.ajax({
type:"post",
url:"../api.php?op=getdata",
data:doParams,
dataType:"html",
beforeSend:function(){
$("#is_loading").show();
$("#info_num").html("").hide();
},
success:function(msg){
me.map.clearMarkers();
var infoNum=0;
var infos = eval(msg);
if(typeof(infos)!="undefined"){
infoNum = infos.length;
if(infoNum>0){
me.showResult(infos);
}
}
$("#is_loading").hide();
$("#info_num").html("在这里找到了"+infoNum+"个楼盘").show();
},
error:function(){
alert("系统错误");
}
});
},
closeWin:function(){
this.map.closeWin();
},
showResult:function(metaMarkers){
this.map.drawMarkers(metaMarkers);
}
};
$(document).ready(function(){
mapPatch.loadAP();
mapObj.init();
var map=mapObj.map;
mapObj.inData();
map.dataTrig(function(){
if(null != mapObj.dataDelay){clearTimeout(mapObj.dataDelay);}
mapObj.dataDelay=setTimeout(function(){mapObj.inData();},500);
});
$(window).bind("resize",function(){
mapObj.autoSize();
});
$("#tab_m_views").click(function(){
var itcls=$(this).attr("class");
if(itcls=="m_fullp"){
$("#mapheader").hide();
$(this).removeClass().addClass("m_normp").html("退出全屏");
}
else{
$("#mapheader").show();
$(this).removeClass().addClass("m_fullp").html("全屏地图");
}
mapObj.autoSize();
});
$("#ksub").click(function(){
var keyVal=mapPatch.getItnVal("k");
if($.trim(keyVal)==""){alert("请输入楼盘名称或地址关键字");mapPatch.itN("k").focus();return;}
else{
params.k=encodeURIComponent(mapPatch.getItnVal("k"));
mapObj.inData();
map.setCenter(x,y,12);
}
});
}); | JavaScript |
//Document By JodJin 2011/11/07
var _id=function(e){return (typeof e == "string") ? document.getElementById(e) : e;}
var defNone='不限';
var defFt=["选择城区","选择片区","类型不限","价格不限","状态不限"];
var defPStr='<p>∧请先选择城区</p>';
var defFilter=["Districts","Plates","Protype","Prices","Sales"];
var mapPatch={
itN:function(itn){
return $("*[name='"+itn+"']");
},
setItnVal:function(itn,itv){
$("*[name='"+itn+"']").attr("value",itv);
},
getItnVal:function(itn){
var val=$.trim($("*[name='"+itn+"']").attr("value"));
return val;
},
loadAP:function(){
for(var i=0;i<defFilter.length;i++){
var _t=defFilter[i].toLowerCase();
this.hovTrig("#"+_t,"#"+_t+"Its","onhov");
var filterData=eval(defFilter[i]);
if(i==1){
var filterStr=defPStr;
}
else{
var filterStr='';
filterStr+='<a href="javascript:;" hidefocus>'+defNone+'</a>';
for(var k=0;k<filterData.length;k++){
var clas='';
if(_t=="sales"){clas='class="'+(_t+k)+'"';}
filterStr+='<a href="javascript:;" '+clas+' hidefocus>'+filterData[k].name+'</a>';
}
}
$("#"+_t+"Its").html(filterStr);
this.cikTrig(_t);
}
},
hovTrig:function(t,c,s){
$(t).hover(function(){
$(this).addClass(s);
$(c).show();
},function(){
$(this).removeClass(s);
$(c).hide();
});
$(c).hover(function(){
$(t).addClass(s);
$(this).show();
},function(){
$(t).removeClass(s);
$(this).hide();
});
},
cikTrig:function(t){
$("#"+t+"Its a").click(function(){
var j=$("#"+t+"Its a").index(this)-1;
$(this).parent().hide();
var aTxt=$(this).text();
$("#"+t+" a").html(aTxt);
var filterWidth=0;
for(var i=0;i<defFilter.length;i++){
if(t==defFilter[i].toLowerCase()){
if(aTxt==defNone){
j="";
var itv="";
$("#"+t+" a").html(defFt[i]);
}else{
var filterData=eval(defFilter[i]);
var itv=filterData[j].vit;
}
}
filterWidth+=$("#"+defFilter[i].toLowerCase()).width();
}
if(t=="protype"){params.protype=itv;}
if(t=="prices"){params.price=itv;}
if(t=="sales"){params.sale=itv;}
if(t=="districts"){
$("#plates a").html(defFt[1]);
if(aTxt==defNone){
params.district="";
params.plate="";
$("#platesIts").html(defPStr);
}else{
var Dist=eval(defFilter[0]);
var Did=Dist[j].aid;
mapObj.map.setCenter(Dist[j].x,Dist[j].y,z);
params.district=Did;
var itPlate=Plates[Did];
var filterStr='';
filterStr+='<a href="javascript:;">'+defNone+'</a>';
for(var k=0;k<itPlate.length;k++){
filterStr+='<a href="javascript:;">'+itPlate[k].name+'</a>';
}
$("#platesIts").html(filterStr);
$("#platesIts a").click(function(){
var aTxt=$(this).text();
var pInt=$("#platesIts a").index(this)-1;
$(this).parent().hide();
if(aTxt==defNone){
params.plate="";
$("#plates a").html(defFt[1]);
}else{
params.plate=itPlate[pInt].pid;
$("#plates a").html(aTxt);
}
mapObj.inData();
});
}
}
mapObj.inData();
$(".hovcont").css({width:(filterWidth+50)+"px"});
});
},
objMerge:function(){
var result={};
for(var i=0;i<arguments.length;i++){
if('object' != typeof(arguments[i])){
alert("参数错误");
break;
}
for(j in arguments[i]){
result[j] = arguments[i][j];
}
}
return result;
},
reParams:function(itpas){
var trigVal="";
for(var i in itpas){
trigVal += (trigVal?"&":"")+i+"="+itpas[i];
}
return trigVal;
},
getAbsPoint : function (e)
{
var x = e.offsetLeft;
var y = e.offsetTop;
while(e = e.offsetParent)
{
x += e.offsetLeft;
y += e.offsetTop;
}
return {'x': x, 'y': y};
},
getRealStyle : function(node)
{
var RealStyle;
if (node.currentStyle) /*先试 IE 的 简单API */
{
RealStyle = node.currentStyle;
}
else if (window.getComputedStyle) /* 再试 W3C API */
{
RealStyle = window.getComputedStyle(node, null);
}
return RealStyle;
},
getStyleNum:function(value)
{
var num = parseInt(value);
return ( num > 0) ? num : 0;
},
oldDocumentHeight:0,
getWindowWidth:function()
{
return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
},
getWindowHeight:function()
{
return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
},
getDocumentWidth:function() {
return document.documentElement.scrollWidth || document.body.scrollWidth;
},
getDocumentHeight:function() {
return document.documentElement.scrollHeight || document.body.scrollHeight;
},
drag: function(elementToDrag, event, container) {
var startX = event.clientX,
startY = event.clientY;
var container = container || null;
if (container) container = _id(container);
var origX = elementToDrag.offsetLeft,
origY = elementToDrag.offsetTop;
var deltaX = startX - origX,
deltaY = startY - origY;
if (document.addEventListener) {
document.addEventListener("mousemove", moveHandler, true);
document.addEventListener("mouseup", upHandler, true)
} else if (document.attachEvent) {
elementToDrag.setCapture();
elementToDrag.attachEvent("onmousemove", moveHandler);
elementToDrag.attachEvent("onmouseup", upHandler);
elementToDrag.attachEvent("onlosecapture", upHandler)
} else {
var oldmovehandler = document.onmousemove;
var olduphandler = document.onmouseup;
document.onmousemove = moveHandler;
document.onmouseup = upHandler
}
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
if (event.preventDefault) event.preventDefault();
else event.returnValue = false;
function moveHandler(e) {
if (!e) e = window.event;
var realStyle = mapPatch.getRealStyle(elementToDrag);
var dragWidth = elementToDrag.offsetWidth;
var dragHeight = elementToDrag.offsetHeight;
if (container) {
var contWidth = container.offsetWidth;
var contHeight = container.offsetHeight
} else {
var contWidth = mapPatch.getDocumentWidth();
var contHeight = mapPatch.oldDocumentHeight
}
var leftMin = e.clientX - deltaX;
var leftMax = contWidth - dragWidth;
var dragLeft = (leftMin < 0) ? 0: (leftMax < leftMin) ? leftMax: leftMin;
var topMin = e.clientY - deltaY;
var topMax = contHeight - dragHeight;
var dragTop = (topMin < 0) ? 0: (topMax < topMin) ? topMax: topMin;
elementToDrag.style.left = dragLeft + "px";
elementToDrag.style.top = dragTop + "px";
if (e.stopPropagation) e.stopPropagation();
else e.cancelBubble = true
}
function upHandler(e) {
if (!e) e = window.event;
if (document.removeEventListener) {
document.removeEventListener("mouseup", upHandler, true);
document.removeEventListener("mousemove", moveHandler, true)
} else if (document.detachEvent) {
elementToDrag.detachEvent("onlosecapture", upHandler);
elementToDrag.detachEvent("onmouseup", upHandler);
elementToDrag.detachEvent("onmousemove", moveHandler);
elementToDrag.releaseCapture()
} else {
document.onmouseup = olduphandler;
document.onmousemove = oldmovehandler
}
if (e.stopPropagation) e.stopPropagation();
else e.cancelBubble = true
}
}
}; | JavaScript |
//Document By JodJin 2011/11/07
var mapApi=function(){
var arg=arguments;
var cont="mapbody";
var lng=110.789228;//经度
var lat=32.615586;//纬度
var zoom=15;//缩放级别
var z={minZoom:10,maxZoom:18};
for(var i=0;i<arg.length;i++){
if(0==i){cont=arg[0];}
else if(1==i){lng=arg[1];}
else if(2==i){lat=arg[2];}
else if(3==i){zoom=arg[3];}
}
this._map=new BMap.Map(cont,z);
this.setCenter(lng,lat,zoom);
this._map.addControl(new BMap.NavigationControl());
this._map.addControl(new BMap.ScaleControl());
this._map.addControl(new BMap.OverviewMapControl({isOpen:false}));
this._map.enableScrollWheelZoom();
this._map.enableKeyboard();
this._map.enableContinuousZoom();
this._markerManager = new MarkerManager(this._map);
};
mapApi.prototype.setCenter=function(x,y,z){
if(!x || !y) return;
var z = z || this._map.getZoom();
this._map.centerAndZoom(new BMap.Point(x,y),z);
};
mapApi.prototype.dataTrig=function(motion){
var map=this._map;
map.addEventListener("moveend",motion);
map.addEventListener("zoomend",motion);
};
mapApi.prototype.getBound=function(){
var map=this._map;
var itBound=map.getBounds();
var itsw=itBound.getSouthWest();
var itne=itBound.getNorthEast();
var pointSw=map.pointToPixel(itsw);
var pointNe=map.pointToPixel(itne);
var sw=map.pixelToPoint(new BMap.Pixel(pointSw.x+8,pointSw.y-8));
var ne=map.pixelToPoint(new BMap.Pixel(pointNe.x-8,pointNe.y+8));
return {"x1":sw.lng,"x2":ne.lng,"y1":sw.lat,"y2":ne.lat};
};
mapApi.prototype.drawMarkers=function(metaMarkers){
var me=this;
var map=me._map;
var mm=me._markerManager;
for(var i=0;i<metaMarkers.length;i++){
var info=metaMarkers[i];
var marker=me.createMarker(info);
mm.addMarker(marker);
me.markerEvents(info);
}
};
mapApi.prototype.clearMarkers=function(){
this._markerManager.clearMarkers();
};
mapApi.prototype.markerCls=function(itsales){
switch(itsales){
case "1":
itClass="mBlue";
break;
case "2":
itClass="mGreen";
break;
case "3":
itClass="mPurple";
break;
case "4":
itClass="mRed";
break;
default:
itClass="mRed";
break;
}
return itClass;
};
mapApi.prototype.createMarker=function(info){
var me=this;
var map=me._map;
var mm=me._markerManager;
var point=new BMap.Point(info.x,info.y);
var clas=me.markerCls(info.sales);
var text='<span class="left"></span><span class="right" id="markerInfo_'+info.cid+'">'+info.cname+'</span><span class="bottom"></span>';
var marker=new popMarker(point,{mText:text,mClass:clas});
return marker;
};
mapApi.prototype.markerEvents=function(info){
var me=this;
var mIndex=BMap.Overlay.getZIndex(info.y);
var itMarker=$("#markerInfo_"+info.cid).parent();
itMarker.bind("mouseover",function(){
$("#markerInfo_"+info.cid).html(info.cname);
$(this).removeClass().addClass("mOrange").css({"z-index":500});
});
itMarker.bind("mouseout",function(){
$("#markerInfo_"+info.cid).html(info.cname);
$(this).removeClass().addClass(me.markerCls(info.sales)).css({"z-index":mIndex});
});
itMarker.bind("click",function(){
me.openWin(info);
});
}
mapApi.prototype.openWin=function(marker){
var me=this;
var node=_id("mapwin");
if('undefined' == typeof marker.cid) return;
if(marker.averprice==0 || !marker.averprice){var it_price='<b>待定</b>'}else{it_price='<b>'+marker.averprice+'</b> 元/平方米';}
var winStr='';
winStr+='<div id="winBox">';
winStr+='<div class="wintop" onmousedown="mapPatch.drag(this.parentNode.parentNode,event,\'mapmain\');"><a href="javascript:;" onclick="mapObj.closeWin();" class="winclose" title="关闭"></a><b><a href="'+marker.href+'" target="_blank">'+marker.cname+'</a></b><span class="wini">['+marker.saletype+']</span></div><div class="clear"></div>';
winStr+='<div class="wincont"><div class="win_c_r"><a href="'+marker.href+'" target="_blank"><img src="'+marker.imgsrc+'" width="160" height="120"></a><br /><a href="'+marker.href+'" target="_blank">查看楼盘详情»</a></div><div class="win_c_l"><ul><li>均价:'+it_price+'</li><li>物业类型:'+marker.protype+'</li><li>项目地址:'+marker.hseat+'</li><li>开发商:'+marker.emplor+'</li><li>销售电话:<b>'+marker.tel+'</b></li></ul></div></div>';
winStr+='</div>';
node.innerHTML=winStr;
node.style.display="block";
};
mapApi.prototype.closeWin=function(){
var node = _id("mapwin");
if(node){node.style.display="none";}
};
function MarkerManager(map){
this._markers=[];
this._map=map;
}
MarkerManager.prototype.addMarker=function(marker){
this._markers.push(marker);
this._map.addOverlay(marker);
};
MarkerManager.prototype.clearMarkers=function(marker){
while(this._markers.length>0){
this._map.removeOverlay(this._markers.shift());
}
};
function popMarker(point,opt_opts){
this._point=point;
this._text=opt_opts.mText||"";
this._class=opt_opts.mClass||"mBlue";
BMap.Marker.apply(this,arguments);
}
popMarker.prototype=new BMap.Marker(new BMap.Point(0,0));
popMarker.prototype.initialize=function(map){
this._map=map;
var div=this._div=document.createElement("div");
div.innerHTML=this._text;
div.className=this._class;
div.style.position="absolute";
div.style.cursor="pointer";
div.style.zIndex=BMap.Overlay.getZIndex(this._point.lat);
map.getPanes().markerPane.appendChild(div);
};
popMarker.prototype.draw=function(){
var map=this._map;
var pixel=map.pointToOverlayPixel(this._point);
this._div.style.left=pixel.x-15+"px";
this._div.style.top=pixel.y-33+"px";
};
popMarker.prototype.remove=function(){
if(typeof(HTMLElement)!="undefined" && !window.opera){
HTMLElement.prototype.__defineGetter__("outerHTML",function(){
var a=this.attributes, str="<"+this.tagName, i=0;for(;i<a.length;i++)
if(a[i].specified)
str+=" "+a[i].name+'="'+a[i].value+'"';
if(!this.canHaveChildren)
return str+" />";
return str+">"+this.innerHTML+"</"+this.tagName+">";
});
HTMLElement.prototype.__defineSetter__("outerHTML",function(s)
{
var r = this.ownerDocument.createRange();
r.setStartBefore(this);
var df = r.createContextualFragment(s);
this.parentNode.replaceChild(df, this);
return s;
});
HTMLElement.prototype.__defineGetter__("canHaveChildren",function()
{
return !/^(area|base|basefont|col|frame|hr|img|br|input|isindex|link|meta|param)$/.test(this.tagName.toLowerCase());
});
}
if(this._div.outerHTML){
this._div.outerHTML="";
}
this._div=null;
BMap.Marker.prototype.remove.apply(this,arguments);
}; | JavaScript |
function confirmurl(url,message)
{
if(confirm(message)) redirect(url);
}
function redirect(url) {
if(url.indexOf('://') == -1 && url.substr(0, 1) != '/' && url.substr(0, 1) != '?') url = $('base').attr('href')+url;
location.href = url;
}
//滚动条
$(function(){
//inputStyle
$(":text").addClass('input-text');
})
/**
* 全选checkbox,注意:标识checkbox id固定为为check_box
* @param string name 列表check名称,如 uid[]
*/
function selectall(name) {
if ($("#check_box").attr("checked")==false) {
$("input[name='"+name+"']").each(function() {
this.checked=false;
});
} else {
$("input[name='"+name+"']").each(function() {
this.checked=true;
});
}
} | JavaScript |
/* Copyright Mihai Bazon, 2002-2005 | www.bazon.net/mishoo
* The DHTML Calendar, version 1.0 "It is happening again"
* Details and latest version at:
* www.dynarch.com/projects/calendar
* This script is developed by Dynarch.com. Visit us at www.dynarch.com.
* This script is distributed under the GNU Lesser General Public License.
* Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
// $Id: calendar.js,v 1.51 2005/03/07 16:44:31 mishoo Exp $
/** The Calendar object constructor. */
//document.createStyleSheet('/images/js/calendar/calendar-blue.css');
var head = document.getElementsByTagName('HEAD').item(0);
var style = document.createElement('link');
style.href = '/statics/js/calendar/calendar-blue.css';
style.rel = 'stylesheet';
style.type = 'text/css';
head.appendChild(style);
Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) {this.activeDiv = null;this.currentDateEl = null;this.getDateStatus = null;
this.getDateToolTip = null;this.getDateText = null;
this.timeout = null;this.onSelected = onSelected || null;
this.onClose = onClose || null;
this.dragging = false;
this.hidden = false;
this.minYear = 1970;
this.maxYear = 2050;
this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"];
this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"];
this.isPopup = true;
this.weekNumbers = true;
this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD;
this.showsOtherMonths = false;
this.dateStr = dateStr;
this.ar_days = null;
this.showsTime = false;
this.time24 = true;
this.yearStep = 2;
this.hiliteToday = true;
this.multiple = null;this.table = null;
this.element = null;
this.tbody = null;this.firstdayname = null;this.monthsCombo = null;this.yearsCombo = null;this.hilitedMonth = null;this.activeMonth = null;this.hilitedYear = null;
this.activeYear = null;this.dateClicked = false;
if (typeof Calendar._SDN == "undefined") {if (typeof Calendar._SDN_len == "undefined")Calendar._SDN_len = 3;var ar = new Array();for (var i = 8; i > 0;) {ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len);}Calendar._SDN = ar;if (typeof Calendar._SMN_len == "undefined")Calendar._SMN_len = 3;ar = new Array();for (var i = 12; i > 0;) {ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len);}Calendar._SMN = ar;}};Calendar._C = null;Calendar.is_ie = ( /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) );Calendar.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) );Calendar.is_opera = /opera/i.test(navigator.userAgent);Calendar.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);Calendar.getAbsolutePos = function(el) {var SL = 0, ST = 0;var is_div = /^div$/i.test(el.tagName);if (is_div && el.scrollLeft)SL = el.scrollLeft;if (is_div && el.scrollTop)ST = el.scrollTop;var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };if (el.offsetParent) {var tmp = this.getAbsolutePos(el.offsetParent);r.x += tmp.x;r.y += tmp.y;}return r;};Calendar.isRelated = function (el, evt) {var related = evt.relatedTarget;if (!related) {var type = evt.type;if (type == "mouseover") {related = evt.fromElement;} else if (type == "mouseout") {related = evt.toElement;}}while (related) {if (related == el) {return true;}related = related.parentNode;}return false;};Calendar.removeClass = function(el, className) {if (!(el && el.className)) {return;}var cls = el.className.split(" ");var ar = new Array();for (var i = cls.length; i > 0;) {if (cls[--i] != className) {ar[ar.length] = cls[i];}}el.className = ar.join(" ");};Calendar.addClass = function(el, className) {Calendar.removeClass(el, className);el.className += " " + className;};Calendar.getElement = function(ev) {var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget;while (f.nodeType != 1 || /^div$/i.test(f.tagName))f = f.parentNode;return f;};Calendar.getTargetElement = function(ev) {var f = Calendar.is_ie ? window.event.srcElement : ev.target;while (f.nodeType != 1)f = f.parentNode;return f;};Calendar.stopEvent = function(ev) {ev || (ev = window.event);if (Calendar.is_ie) {ev.cancelBubble = true;ev.returnValue = false;} else {ev.preventDefault();ev.stopPropagation();}return false;};Calendar.addEvent = function(el, evname, func) {if (el.attachEvent) { el.attachEvent("on" + evname, func);} else if (el.addEventListener) { el.addEventListener(evname, func, true);} else {el["on" + evname] = func;}};Calendar.removeEvent = function(el, evname, func) {if (el.detachEvent) { el.detachEvent("on" + evname, func);} else if (el.removeEventListener) { el.removeEventListener(evname, func, true);} else {el["on" + evname] = null;}};Calendar.createElement = function(type, parent) {var el = null;if (document.createElementNS) {el = document.createElementNS("http://www.w3.org/1999/xhtml", type);} else {el = document.createElement(type);}if (typeof parent != "undefined") {parent.appendChild(el);}return el;};Calendar._add_evs = function(el) {with (Calendar) {addEvent(el, "mouseover", dayMouseOver);addEvent(el, "mousedown", dayMouseDown);addEvent(el, "mouseout", dayMouseOut);if (is_ie) {addEvent(el, "dblclick", dayMouseDblClick);el.setAttribute("unselectable", true);}}};Calendar.findMonth = function(el) {if (typeof el.month != "undefined") {return el;} else if (typeof el.parentNode.month != "undefined") {return el.parentNode;}return null;};Calendar.findYear = function(el) {if (typeof el.year != "undefined") {return el;} else if (typeof el.parentNode.year != "undefined") {return el.parentNode;}return null;};Calendar.showMonthsCombo = function () {var cal = Calendar._C;if (!cal) {return false;}var cal = cal;var cd = cal.activeDiv;var mc = cal.monthsCombo;if (cal.hilitedMonth) {Calendar.removeClass(cal.hilitedMonth, "hilite");}if (cal.activeMonth) {Calendar.removeClass(cal.activeMonth, "active");}var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()];Calendar.addClass(mon, "active");cal.activeMonth = mon;var s = mc.style;s.display = "block";if (cd.navtype < 0)s.left = cd.offsetLeft + "px";else {var mcw = mc.offsetWidth;if (typeof mcw == "undefined")mcw = 50;s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";}s.top = (cd.offsetTop + cd.offsetHeight) + "px";};Calendar.showYearsCombo = function (fwd) {var cal = Calendar._C;if (!cal) {return false;}var cal = cal;var cd = cal.activeDiv;var yc = cal.yearsCombo;if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}if (cal.activeYear) {Calendar.removeClass(cal.activeYear, "active");}cal.activeYear = null;var Y = cal.date.getFullYear() + (fwd ? 1 : -1);var yr = yc.firstChild;var show = false;for (var i = 12; i > 0; --i) {if (Y >= cal.minYear && Y <= cal.maxYear) {yr.innerHTML = Y;yr.year = Y;yr.style.display = "block";show = true;} else {yr.style.display = "none";}yr = yr.nextSibling;Y += fwd ? cal.yearStep : -cal.yearStep;}if (show) {var s = yc.style;s.display = "block";if (cd.navtype < 0)s.left = cd.offsetLeft + "px";else {var ycw = yc.offsetWidth;if (typeof ycw == "undefined")ycw = 50;s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";}s.top = (cd.offsetTop + cd.offsetHeight) + "px";}};Calendar.tableMouseUp = function(ev) {var cal = Calendar._C;if (!cal) {return false;}if (cal.timeout) {clearTimeout(cal.timeout);}var el = cal.activeDiv;if (!el) {return false;}var target = Calendar.getTargetElement(ev);ev || (ev = window.event);Calendar.removeClass(el, "active");if (target == el || target.parentNode == el) {Calendar.cellClick(el, ev);}var mon = Calendar.findMonth(target);var date = null;if (mon) {date = new Date(cal.date);if (mon.month != date.getMonth()) {date.setMonth(mon.month);cal.setDate(date);cal.dateClicked = false;cal.callHandler();}} else {var year = Calendar.findYear(target);if (year) {date = new Date(cal.date);if (year.year != date.getFullYear()) {date.setFullYear(year.year);cal.setDate(date);cal.dateClicked = false;cal.callHandler();}}}with (Calendar) {removeEvent(document, "mouseup", tableMouseUp);removeEvent(document, "mouseover", tableMouseOver);removeEvent(document, "mousemove", tableMouseOver);cal._hideCombos();_C = null;return stopEvent(ev);}};Calendar.tableMouseOver = function (ev) {var cal = Calendar._C;if (!cal) {return;}var el = cal.activeDiv;var target = Calendar.getTargetElement(ev);if (target == el || target.parentNode == el) {Calendar.addClass(el, "hilite active");Calendar.addClass(el.parentNode, "rowhilite");} else {if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2)))Calendar.removeClass(el, "active");Calendar.removeClass(el, "hilite");Calendar.removeClass(el.parentNode, "rowhilite");}ev || (ev = window.event);if (el.navtype == 50 && target != el) {var pos = Calendar.getAbsolutePos(el);var w = el.offsetWidth;var x = ev.clientX;var dx;var decrease = true;if (x > pos.x + w) {dx = x - pos.x - w;decrease = false;} elsedx = pos.x - x;if (dx < 0) dx = 0;var range = el._range;var current = el._current;var count = Math.floor(dx / 10) % range.length;for (var i = range.length; --i >= 0;)if (range[i] == current)
break;
while (count-- > 0)
if (decrease) {
if (--i < 0)
i = range.length - 1;
} else if ( ++i >= range.length )
i = 0;
var newval = range[i];
el.innerHTML = newval;cal.onUpdateTime();
}
var mon = Calendar.findMonth(target);
if (mon) {
if (mon.month != cal.date.getMonth()) {
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
Calendar.addClass(mon, "hilite");
cal.hilitedMonth = mon;
} else if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
} else {
if (cal.hilitedMonth) {Calendar.removeClass(cal.hilitedMonth, "hilite");}var year = Calendar.findYear(target);if (year) {if (year.year != cal.date.getFullYear()) {if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}Calendar.addClass(year, "hilite");cal.hilitedYear = year;} else if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}} else if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}}return Calendar.stopEvent(ev);};Calendar.tableMouseDown = function (ev) {if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) {return Calendar.stopEvent(ev);}};Calendar.calDragIt = function (ev) {var cal = Calendar._C;if (!(cal && cal.dragging)) {return false;}var posX;var posY;if (Calendar.is_ie) {posY = window.event.clientY + document.body.scrollTop;posX = window.event.clientX + document.body.scrollLeft;} else {posX = ev.pageX;posY = ev.pageY;}cal.hideShowCovered();var st = cal.element.style;st.left = (posX - cal.xOffs) + "px";st.top = (posY - cal.yOffs) + "px";return Calendar.stopEvent(ev);};Calendar.calDragEnd = function (ev) {var cal = Calendar._C;if (!cal) {return false;}cal.dragging = false;with (Calendar) {removeEvent(document, "mousemove", calDragIt);removeEvent(document, "mouseup", calDragEnd);tableMouseUp(ev);}cal.hideShowCovered();};Calendar.dayMouseDown = function(ev) {var el = Calendar.getElement(ev);
if (el.disabled) {
return false;
}
var cal = el.calendar;
cal.activeDiv = el;
Calendar._C = cal;
if (el.navtype != 300) with (Calendar) {
if (el.navtype == 50) {
el._current = el.innerHTML;
addEvent(document, "mousemove", tableMouseOver);
} else
addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver);
addClass(el, "hilite active");
addEvent(document, "mouseup", tableMouseUp);
} else if (cal.isPopup) {
cal._dragStart(ev);
}
if (el.navtype == -1 || el.navtype == 1) {
if (cal.timeout) clearTimeout(cal.timeout);
cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250);
} else if (el.navtype == -2 || el.navtype == 2) {
if (cal.timeout) clearTimeout(cal.timeout);
cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250);
} else {
cal.timeout = null;
}
return Calendar.stopEvent(ev);
};Calendar.dayMouseDblClick = function(ev) {
Calendar.cellClick(Calendar.getElement(ev), ev || window.event);
if (Calendar.is_ie) {
document.selection.empty();
}
};Calendar.dayMouseOver = function(ev) {
var el = Calendar.getElement(ev);
if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) {
return false;
}
if (el.ttip) {
if (el.ttip.substr(0, 1) == "_") {
el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1);
}
el.calendar.tooltips.innerHTML = el.ttip;
}
if (el.navtype != 300) {
Calendar.addClass(el, "hilite");
if (el.caldate) {
Calendar.addClass(el.parentNode, "rowhilite");
}
}
return Calendar.stopEvent(ev);
};Calendar.dayMouseOut = function(ev) {
with (Calendar) {
var el = getElement(ev);
if (isRelated(el, ev) || _C || el.disabled)
return false;
removeClass(el, "hilite");
if (el.caldate)
removeClass(el.parentNode, "rowhilite");
if (el.calendar)
el.calendar.tooltips.innerHTML = _TT["SEL_DATE"];
return stopEvent(ev);
}
};
Calendar.cellClick = function(el, ev) {
var cal = el.calendar;
var closing = false;
var newdate = false;
var date = null;
if (typeof el.navtype == "undefined") {
if (cal.currentDateEl) {
Calendar.removeClass(cal.currentDateEl, "selected");
Calendar.addClass(el, "selected");
closing = (cal.currentDateEl == el);
if (!closing) {
cal.currentDateEl = el;
}
}
cal.date.setDateOnly(el.caldate);
date = cal.date;
var other_month = !(cal.dateClicked = !el.otherMonth);
if (!other_month && !cal.currentDateEl)
cal._toggleMultipleDate(new Date(date));
else
newdate = !el.disabled;if (other_month)
cal._init(cal.firstDayOfWeek, date);
} else {
if (el.navtype == 200) {
Calendar.removeClass(el, "hilite");
cal.callCloseHandler();
return;
}
date = new Date(cal.date);
if (el.navtype == 0)
date.setDateOnly(new Date());
cal.dateClicked = false;
var year = date.getFullYear();
var mon = date.getMonth();
function setMonth(m) {
var day = date.getDate();
var max = date.getMonthDays(m);
if (day > max) {
date.setDate(max);
}
date.setMonth(m);
};
switch (el.navtype) {
case 400:
Calendar.removeClass(el, "hilite");
var text = Calendar._TT["ABOUT"];
if (typeof text != "undefined") {
text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : "";
} else {text = "Help and about box text is not translated into this language.\n" +
"If you know this language and you feel generous please update\n" +
"the corresponding file in \"lang\" subdir to match calendar-en.js\n" +
"and send it back to <mihai_bazon@yahoo.com> to get it into the distribution ;-)\n\n" +
"Thank you!\n" +
"http://dynarch.com/mishoo/calendar.epl\n";
}
alert(text);
return;
case -2:
if (year > cal.minYear) {
date.setFullYear(year - 1);
}
break;
case -1:
if (mon > 0) {
setMonth(mon - 1);
} else if (year-- > cal.minYear) {
date.setFullYear(year);
setMonth(11);
}
break;
case 1:
if (mon < 11) {
setMonth(mon + 1);
} else if (year < cal.maxYear) {
date.setFullYear(year + 1);
setMonth(0);
}
break;
case 2:
if (year < cal.maxYear) {
date.setFullYear(year + 1);
}
break;
case 100:
cal.setFirstDayOfWeek(el.fdow);
return;
case 50:
var range = el._range;
var current = el.innerHTML;
for (var i = range.length; --i >= 0;)
if (range[i] == current)
break;
if (ev && ev.shiftKey) {
if (--i < 0)
i = range.length - 1;
} else if ( ++i >= range.length )
i = 0;
var newval = range[i];
el.innerHTML = newval;
cal.onUpdateTime();
return;
case 0:if ((typeof cal.getDateStatus == "function") &&
cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) {
return false;
}
break;
}
if (!date.equalsTo(cal.date)) {
cal.setDate(date);
newdate = true;
} else if (el.navtype == 0)
newdate = closing = true;
}
if (newdate) {
ev && cal.callHandler();
}
if (closing) {
Calendar.removeClass(el, "hilite");
ev && cal.callCloseHandler();
}
};
Calendar.prototype.create = function (_par) {
var parent = null;
if (! _par) {
parent = document.getElementsByTagName("body")[0];
this.isPopup = true;
} else {
parent = _par;
this.isPopup = false;
}
this.date = this.dateStr ? new Date(this.dateStr) : new Date();var table = Calendar.createElement("table");
this.table = table;
table.cellSpacing = 0;
table.cellPadding = 0;
table.calendar = this;
Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown);var div = Calendar.createElement("div");
this.element = div;
div.className = "calendar";
if (this.isPopup) {
div.style.position = "absolute";
div.style.display = "none";
}
div.appendChild(table);var thead = Calendar.createElement("thead", table);
var cell = null;
var row = null;var cal = this;
var hh = function (text, cs, navtype) {
cell = Calendar.createElement("td", row);
cell.colSpan = cs;
cell.className = "button";
if (navtype != 0 && Math.abs(navtype) <= 2)
cell.className += " nav";
Calendar._add_evs(cell);
cell.calendar = cal;
cell.navtype = navtype;
cell.innerHTML = "<div unselectable='on'>" + text + "</div>";
return cell;
};row = Calendar.createElement("tr", thead);
var title_length = 6;
(this.isPopup) && --title_length;
(this.weekNumbers) && ++title_length;hh("<div>?</div>", 1, 400).ttip = Calendar._TT["INFO"];
this.title = hh("", title_length, 300);
this.title.className = "title";
if (this.isPopup) {
this.title.ttip = Calendar._TT["DRAG_TO_MOVE"];
this.title.style.cursor = "move";
hh("×", 1, 200).ttip = Calendar._TT["CLOSE"];
}row = Calendar.createElement("tr", thead);
row.className = "headrow";this._nav_py = hh("«", 1, -2);
this._nav_py.ttip = Calendar._TT["PREV_YEAR"];this._nav_pm = hh("‹", 1, -1);
this._nav_pm.ttip = Calendar._TT["PREV_MONTH"];this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0);
this._nav_now.ttip = Calendar._TT["GO_TODAY"];this._nav_nm = hh("›", 1, 1);
this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"];this._nav_ny = hh("»", 1, 2);
this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"];
row = Calendar.createElement("tr", thead);
row.className = "daynames";
if (this.weekNumbers) {
cell = Calendar.createElement("td", row);
cell.className = "name wn";
cell.innerHTML = "<div>"+Calendar._TT["WK"]+"</div>";
}
for (var i = 7; i > 0; --i) {
cell = Calendar.createElement("td", row);
if (!i) {
cell.navtype = 100;
cell.calendar = this;
Calendar._add_evs(cell);
}
}
this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild;
this._displayWeekdays();var tbody = Calendar.createElement("tbody", table);
this.tbody = tbody;for (i = 6; i > 0; --i) {
row = Calendar.createElement("tr", tbody);
if (this.weekNumbers) {
cell = Calendar.createElement("td", row);
}
for (var j = 7; j > 0; --j) {
cell = Calendar.createElement("td", row);
cell.calendar = this;
Calendar._add_evs(cell);
}
}if (this.showsTime) {
row = Calendar.createElement("tr", tbody);
row.className = "time";cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = 2;
cell.innerHTML = Calendar._TT["TIME"] || " ";cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = this.weekNumbers ? 4 : 3;(function(){
function makeTimePart(className, init, range_start, range_end) {
var part = Calendar.createElement("span", cell);
part.className = className;
part.innerHTML = init;
part.calendar = cal;
part.ttip = Calendar._TT["TIME_PART"];
part.navtype = 50;
part._range = [];
if (typeof range_start != "number")
part._range = range_start;
else {
for (var i = range_start; i <= range_end; ++i) {
var txt;
if (i < 10 && range_end >= 10) txt = '0' + i;
else txt = '' + i;
part._range[part._range.length] = txt;
}
}
Calendar._add_evs(part);
return part;
};
var hrs = cal.date.getHours();
var mins = cal.date.getMinutes();
var t12 = !cal.time24;
var pm = (hrs > 12);
if (t12 && pm) hrs -= 12;
var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23);
var span = Calendar.createElement("span", cell);
span.innerHTML = ":";
span.className = "colon";
var M = makeTimePart("minute", mins, 0, 59);
var AP = null;
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = 2;
if (t12)
AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]);
else
cell.innerHTML = " ";cal.onSetTime = function() {
var pm, hrs = this.date.getHours(),
mins = this.date.getMinutes();
if (t12) {
pm = (hrs >= 12);
if (pm) hrs -= 12;
if (hrs == 0) hrs = 12;
AP.innerHTML = pm ? "pm" : "am";
}
H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs;
M.innerHTML = (mins < 10) ? ("0" + mins) : mins;
};cal.onUpdateTime = function() {
var date = this.date;
var h = parseInt(H.innerHTML, 10);
if (t12) {
if (/pm/i.test(AP.innerHTML) && h < 12)
h += 12;
else if (/am/i.test(AP.innerHTML) && h == 12)
h = 0;
}
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
date.setHours(h);
date.setMinutes(parseInt(M.innerHTML, 10));
date.setFullYear(y);
date.setMonth(m);
date.setDate(d);
this.dateClicked = false;
this.callHandler();
};
})();
} else {
this.onSetTime = this.onUpdateTime = function() {};
}var tfoot = Calendar.createElement("tfoot", table);row = Calendar.createElement("tr", tfoot);
row.className = "footrow";cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300);
cell.className = "ttip";
if (this.isPopup) {
cell.ttip = Calendar._TT["DRAG_TO_MOVE"];
cell.style.cursor = "move";
}
this.tooltips = cell;div = Calendar.createElement("div", this.element);
this.monthsCombo = div;
div.className = "combo";
for (i = 0; i < Calendar._MN.length; ++i) {
var mn = Calendar.createElement("div");
mn.className = Calendar.is_ie ? "label-IEfix" : "label";
mn.month = i;
mn.innerHTML = Calendar._SMN[i];
div.appendChild(mn);
}div = Calendar.createElement("div", this.element);
this.yearsCombo = div;
div.className = "combo";
for (i = 12; i > 0; --i) {
var yr = Calendar.createElement("div");
yr.className = Calendar.is_ie ? "label-IEfix" : "label";
div.appendChild(yr);
}this._init(this.firstDayOfWeek, this.date);
parent.appendChild(this.element);
};
Calendar._keyEvent = function(ev) {
var cal = window._dynarch_popupCalendar;
if (!cal || cal.multiple)
return false;
(Calendar.is_ie) && (ev = window.event);
var act = (Calendar.is_ie || ev.type == "keypress"),
K = ev.keyCode;
if (ev.ctrlKey) {
switch (K) {
case 37:
act && Calendar.cellClick(cal._nav_pm);
break;
case 38:
act && Calendar.cellClick(cal._nav_py);
break;
case 39:
act && Calendar.cellClick(cal._nav_nm);
break;
case 40:
act && Calendar.cellClick(cal._nav_ny);
break;
default:
return false;
}
} else switch (K) {
case 32:
Calendar.cellClick(cal._nav_now);
break;
case 27:
act && cal.callCloseHandler();
break;
case 37:
case 38:
case 39:
case 40:
if (act) {
var prev, x, y, ne, el, step;
prev = K == 37 || K == 38;
step = (K == 37 || K == 39) ? 1 : 7;
function setVars() {
el = cal.currentDateEl;
var p = el.pos;
x = p & 15;
y = p >> 4;
ne = cal.ar_days[y][x];
};setVars();
function prevMonth() {
var date = new Date(cal.date);
date.setDate(date.getDate() - step);
cal.setDate(date);
};
function nextMonth() {
var date = new Date(cal.date);
date.setDate(date.getDate() + step);
cal.setDate(date);
};
while (1) {
switch (K) {
case 37:
if (--x >= 0)
ne = cal.ar_days[y][x];
else {
x = 6;
K = 38;
continue;
}
break;
case 38:
if (--y >= 0)
ne = cal.ar_days[y][x];
else {
prevMonth();
setVars();
}
break;
case 39:
if (++x < 7)
ne = cal.ar_days[y][x];
else {
x = 0;
K = 40;
continue;
}
break;
case 40:
if (++y < cal.ar_days.length)
ne = cal.ar_days[y][x];
else {
nextMonth();
setVars();
}
break;
}
break;
}
if (ne) {
if (!ne.disabled)
Calendar.cellClick(ne);
else if (prev)
prevMonth();
else
nextMonth();
}
}
break;
case 13:
if (act)
Calendar.cellClick(cal.currentDateEl, ev);
break;
default:
return false;
}
return Calendar.stopEvent(ev);
};
Calendar.prototype._init = function (firstDayOfWeek, date) {
var today = new Date(),
TY = today.getFullYear(),
TM = today.getMonth(),
TD = today.getDate();
this.table.style.visibility = "hidden";
var year = date.getFullYear();
if (year < this.minYear) {
year = this.minYear;
date.setFullYear(year);
} else if (year > this.maxYear) {
year = this.maxYear;
date.setFullYear(year);
}
this.firstDayOfWeek = firstDayOfWeek;
this.date = new Date(date);
var month = date.getMonth();
var mday = date.getDate();
var no_days = date.getMonthDays();
date.setDate(1);
var day1 = (date.getDay() - this.firstDayOfWeek) % 7;
if (day1 < 0)
day1 += 7;
date.setDate(-day1);
date.setDate(date.getDate() + 1);var row = this.tbody.firstChild;
var MN = Calendar._SMN[month];
var ar_days = this.ar_days = new Array();
var weekend = Calendar._TT["WEEKEND"];
var dates = this.multiple ? (this.datesCells = {}) : null;
for (var i = 0; i < 6; ++i, row = row.nextSibling) {
var cell = row.firstChild;
if (this.weekNumbers) {
cell.className = "day wn";
cell.innerHTML = "<div>"+date.getWeekNumber()+"</div>";
cell = cell.nextSibling;
}
row.className = "daysrow";
var hasdays = false, iday, dpos = ar_days[i] = [];
for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) {
iday = date.getDate();
var wday = date.getDay();
cell.className = "day";
cell.pos = i << 4 | j;
dpos[j] = cell;
var current_month = (date.getMonth() == month);
if (!current_month) {
if (this.showsOtherMonths) {
cell.className += " othermonth";
cell.otherMonth = true;
} else {
cell.className = "emptycell";
cell.innerHTML = " ";
cell.disabled = true;
continue;
}
} else {
cell.otherMonth = false;
hasdays = true;
}
cell.disabled = false;
cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday;
if (dates)
dates[date.print("%Y%m%d")] = cell;
if (this.getDateStatus) {
var status = this.getDateStatus(date, year, month, iday);
if (this.getDateToolTip) {
var toolTip = this.getDateToolTip(date, year, month, iday);
if (toolTip)
cell.title = toolTip;
}
if (status === true) {
cell.className += " disabled";
cell.disabled = true;
} else {
if (/disabled/i.test(status))
cell.disabled = true;
cell.className += " " + status;
}
}
if (!cell.disabled) {
cell.caldate = new Date(date);
cell.ttip = "_";
if (!this.multiple && current_month
&& iday == mday && this.hiliteToday) {
cell.className += " selected";
this.currentDateEl = cell;
}
if (date.getFullYear() == TY &&
date.getMonth() == TM &&
iday == TD) {
cell.className += " today";
cell.ttip += Calendar._TT["PART_TODAY"];
}
if (weekend.indexOf(wday.toString()) != -1)
cell.className += cell.otherMonth ? " oweekend" : " weekend";
}
}
if (!(hasdays || this.showsOtherMonths))
row.className = "emptyrow";
}
this.title.innerHTML = Calendar._MN[month] + ", " + year;
this.onSetTime();
this.table.style.visibility = "visible";
this._initMultipleDates();
};Calendar.prototype._initMultipleDates = function() {
if (this.multiple) {
for (var i in this.multiple) {
var cell = this.datesCells[i];
var d = this.multiple[i];
if (!d)
continue;
if (cell)
cell.className += " selected";
}
}
};Calendar.prototype._toggleMultipleDate = function(date) {
if (this.multiple) {
var ds = date.print("%Y%m%d");
var cell = this.datesCells[ds];
if (cell) {
var d = this.multiple[ds];
if (!d) {
Calendar.addClass(cell, "selected");
this.multiple[ds] = date;
} else {
Calendar.removeClass(cell, "selected");
delete this.multiple[ds];
}
}
}
};Calendar.prototype.setDateToolTipHandler = function (unaryFunction) {
this.getDateToolTip = unaryFunction;
};
Calendar.prototype.setDate = function (date) {
if (!date.equalsTo(this.date)) {
this._init(this.firstDayOfWeek, date);
}
};
Calendar.prototype.refresh = function () {
this._init(this.firstDayOfWeek, this.date);
};
Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {
this._init(firstDayOfWeek, this.date);
this._displayWeekdays();
};
Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) {
this.getDateStatus = unaryFunction;
};
Calendar.prototype.setRange = function (a, z) {
this.minYear = a;
this.maxYear = z;
};
Calendar.prototype.callHandler = function () {
if (this.onSelected) {
this.onSelected(this, this.date.print(this.dateFormat));
}
};
Calendar.prototype.callCloseHandler = function () {
if (this.onClose) {
this.onClose(this);
}
this.hideShowCovered();
};
Calendar.prototype.destroy = function () {
var el = this.element.parentNode;
el.removeChild(this.element);
Calendar._C = null;
window._dynarch_popupCalendar = null;
};
Calendar.prototype.reparent = function (new_parent) {
var el = this.element;
el.parentNode.removeChild(el);
new_parent.appendChild(el);
};
Calendar._checkCalendar = function(ev) {
var calendar = window._dynarch_popupCalendar;
if (!calendar) {
return false;
}
var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
for (; el != null && el != calendar.element; el = el.parentNode);
if (el == null) {window._dynarch_popupCalendar.callCloseHandler();
return Calendar.stopEvent(ev);
}
};
Calendar.prototype.show = function () {
var rows = this.table.getElementsByTagName("tr");
for (var i = rows.length; i > 0;) {
var row = rows[--i];
Calendar.removeClass(row, "rowhilite");
var cells = row.getElementsByTagName("td");
for (var j = cells.length; j > 0;) {
var cell = cells[--j];
Calendar.removeClass(cell, "hilite");
Calendar.removeClass(cell, "active");
}
}
this.element.style.display = "block";
this.hidden = false;
if (this.isPopup) {
window._dynarch_popupCalendar = this;
Calendar.addEvent(document, "keydown", Calendar._keyEvent);
Calendar.addEvent(document, "keypress", Calendar._keyEvent);
Calendar.addEvent(document, "mousedown", Calendar._checkCalendar);
}
this.hideShowCovered();
};
Calendar.prototype.hide = function () {
if (this.isPopup) {
Calendar.removeEvent(document, "keydown", Calendar._keyEvent);
Calendar.removeEvent(document, "keypress", Calendar._keyEvent);
Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar);
}
this.element.style.display = "none";
this.hidden = true;
this.hideShowCovered();
};Calendar.prototype.showAt = function (x, y) {
var s = this.element.style;
s.left = x + "px";
s.top = y + "px";
this.show();
};
Calendar.prototype.showAtElement = function (el, opts) {
var self = this;
var p = Calendar.getAbsolutePos(el);
if (!opts || typeof opts != "string") {
this.showAt(p.x, p.y + el.offsetHeight);
return true;
}
function fixPosition(box) {
if (box.x < 0)
box.x = 0;
if (box.y < 0)
box.y = 0;
var cp = document.createElement("div");
var s = cp.style;
s.position = "absolute";
s.right = s.bottom = s.width = s.height = "0px";
document.body.appendChild(cp);
var br = Calendar.getAbsolutePos(cp);
document.body.removeChild(cp);
if (Calendar.is_ie) {
br.y += document.body.scrollTop;
br.x += document.body.scrollLeft;
} else {
br.y += window.scrollY;
br.x += window.scrollX;
}
var tmp = box.x + box.width - br.x;
if (tmp > 0) box.x -= tmp;
tmp = box.y + box.height - br.y;
if (tmp > 0) box.y -= tmp;
};
this.element.style.display = "block";
Calendar.continuation_for_the_fucking_khtml_browser = function() {
var w = self.element.offsetWidth;
var h = self.element.offsetHeight;
self.element.style.display = "none";
var valign = opts.substr(0, 1);
var halign = "l";
if (opts.length > 1) {
halign = opts.substr(1, 1);
}switch (valign) {
case "T": p.y -= h; break;
case "B": p.y += el.offsetHeight; break;
case "C": p.y += (el.offsetHeight - h) / 2; break;
case "t": p.y += el.offsetHeight - h; break;
case "b": break;
}switch (halign) {
case "L": p.x -= w; break;
case "R": p.x += el.offsetWidth; break;
case "C": p.x += (el.offsetWidth - w) / 2; break;
case "l": p.x += el.offsetWidth - w; break;
case "r": break;
}
p.width = w;
p.height = h + 40;
self.monthsCombo.style.display = "none";
fixPosition(p);
self.showAt(p.x, p.y);
};
if (Calendar.is_khtml)
setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10);
else
Calendar.continuation_for_the_fucking_khtml_browser();
};
Calendar.prototype.setDateFormat = function (str) {
this.dateFormat = str;
};
Calendar.prototype.setTtDateFormat = function (str) {
this.ttDateFormat = str;
};
Calendar.prototype.parseDate = function(str, fmt) {
if (!fmt)
fmt = this.dateFormat;
this.setDate(Date.parseDate(str, fmt));
};
Calendar.prototype.hideShowCovered = function () {
if (!Calendar.is_ie && !Calendar.is_opera)
return;
function getVisib(obj){
var value = obj.style.visibility;
if (!value) {
if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") {
if (!Calendar.is_khtml)
value = document.defaultView.
getComputedStyle(obj, "").getPropertyValue("visibility");
else
value = '';
} else if (obj.currentStyle) {
value = obj.currentStyle.visibility;
} else
value = '';
}
return value;
};var tags = new Array("applet", "iframe", "select");
var el = this.element;var p = Calendar.getAbsolutePos(el);
var EX1 = p.x;
var EX2 = el.offsetWidth + EX1;
var EY1 = p.y;
var EY2 = el.offsetHeight + EY1;for (var k = tags.length; k > 0; ) {
var ar = document.getElementsByTagName(tags[--k]);
var cc = null;for (var i = ar.length; i > 0;) {
cc = ar[--i];p = Calendar.getAbsolutePos(cc);
var CX1 = p.x;
var CX2 = cc.offsetWidth + CX1;
var CY1 = p.y;
var CY2 = cc.offsetHeight + CY1;if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = cc.__msh_save_visibility;
} else {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = "hidden";
}
}
}
};
Calendar.prototype._displayWeekdays = function () {
var fdow = this.firstDayOfWeek;
var cell = this.firstdayname;
var weekend = Calendar._TT["WEEKEND"];
for (var i = 0; i < 7; ++i) {
cell.className = "day name";
var realday = (i + fdow) % 7;
if (i) {
cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]);
cell.navtype = 100;
cell.calendar = this;
cell.fdow = realday;
Calendar._add_evs(cell);
}
if (weekend.indexOf(realday.toString()) != -1) {
Calendar.addClass(cell, "weekend");
}
cell.innerHTML = Calendar._SDN[(i + fdow) % 7];
cell = cell.nextSibling;
}
};
Calendar.prototype._hideCombos = function () {
this.monthsCombo.style.display = "none";
this.yearsCombo.style.display = "none";
};
Calendar.prototype._dragStart = function (ev) {
if (this.dragging) {
return;
}
this.dragging = true;
var posX;
var posY;
if (Calendar.is_ie) {
posY = window.event.clientY + document.body.scrollTop;
posX = window.event.clientX + document.body.scrollLeft;
} else {
posY = ev.clientY + window.scrollY;
posX = ev.clientX + window.scrollX;
}
var st = this.element.style;
this.xOffs = posX - parseInt(st.left);
this.yOffs = posY - parseInt(st.top);
with (Calendar) {
addEvent(document, "mousemove", calDragIt);
addEvent(document, "mouseup", calDragEnd);
}
};
Date._MD = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
Date.SECOND = 1000 /* milliseconds */;
Date.MINUTE = 60 * Date.SECOND;
Date.HOUR = 60 * Date.MINUTE;
Date.DAY = 24 * Date.HOUR;
Date.WEEK = 7 * Date.DAY;Date.parseDate = function(str, fmt) {
var today = new Date();
var y = 0;
var m = -1;
var d = 0;
var a = str.split(/\W+/);
var b = fmt.match(/%./g);
var i = 0, j = 0;
var hr = 0;
var min = 0;
for (i = 0; i < a.length; ++i) {
if (!a[i])
continue;
switch (b[i]) {
case "%d":
case "%e":
d = parseInt(a[i], 10);
break; case "%m":
m = parseInt(a[i], 10) - 1;
break; case "%Y":
case "%y":
y = parseInt(a[i], 10);
(y < 100) && (y += (y > 29) ? 1900 : 2000);
break; case "%b":
case "%B":
for (j = 0; j < 12; ++j) {
if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
}
break; case "%H":
case "%I":
case "%k":
case "%l":
hr = parseInt(a[i], 10);
break; case "%P":
case "%p":
if (/pm/i.test(a[i]) && hr < 12)
hr += 12;
else if (/am/i.test(a[i]) && hr >= 12)
hr -= 12;
break; case "%M":
min = parseInt(a[i], 10);
break;
}
}
if (isNaN(y)) y = today.getFullYear();
if (isNaN(m)) m = today.getMonth();
if (isNaN(d)) d = today.getDate();
if (isNaN(hr)) hr = today.getHours();
if (isNaN(min)) min = today.getMinutes();
if (y != 0 && m != -1 && d != 0)
return new Date(y, m, d, hr, min, 0);
y = 0; m = -1; d = 0;
for (i = 0; i < a.length; ++i) {
if (a[i].search(/[a-zA-Z]+/) != -1) {
var t = -1;
for (j = 0; j < 12; ++j) {
if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
}
if (t != -1) {
if (m != -1) {
d = m+1;
}
m = t;
}
} else if (parseInt(a[i], 10) <= 12 && m == -1) {
m = a[i]-1;
} else if (parseInt(a[i], 10) > 31 && y == 0) {
y = parseInt(a[i], 10);
(y < 100) && (y += (y > 29) ? 1900 : 2000);
} else if (d == 0) {
d = a[i];
}
}
if (y == 0)
y = today.getFullYear();
if (m != -1 && d != 0)
return new Date(y, m, d, hr, min, 0);
return today;
};
Date.prototype.getMonthDays = function(month) {
var year = this.getFullYear();
if (typeof month == "undefined") {
month = this.getMonth();
}
if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) {
return 29;
} else {
return Date._MD[month];
}
};
Date.prototype.getDayOfYear = function() {
var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
var time = now - then;
return Math.floor(time / Date.DAY);
};
Date.prototype.getWeekNumber = function() {
var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
var DoW = d.getDay();
d.setDate(d.getDate() - (DoW + 6) % 7 + 3);
var ms = d.valueOf();
d.setMonth(0);
d.setDate(4);
return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};
Date.prototype.equalsTo = function(date) {
return ((this.getFullYear() == date.getFullYear()) &&
(this.getMonth() == date.getMonth()) &&
(this.getDate() == date.getDate()) &&
(this.getHours() == date.getHours()) &&
(this.getMinutes() == date.getMinutes()));
};
Date.prototype.setDateOnly = function(date) {
var tmp = new Date(date);
this.setDate(1);
this.setFullYear(tmp.getFullYear());
this.setMonth(tmp.getMonth());
this.setDate(tmp.getDate());
};
Date.prototype.print = function (str) {
var m = this.getMonth();
var d = this.getDate();
var y = this.getFullYear();
var wn = this.getWeekNumber();
var w = this.getDay();
var s = {};
var hr = this.getHours();
var pm = (hr >= 12);
var ir = (pm) ? (hr - 12) : hr;
var dy = this.getDayOfYear();
if (ir == 0)
ir = 12;
var min = this.getMinutes();
var sec = this.getSeconds();
s["%a"] = Calendar._SDN[w];s["%A"] = Calendar._DN[w];s["%b"] = Calendar._SMN[m];s["%B"] = Calendar._MN[m]; s["%C"] = 1 + Math.floor(y / 100);s["%d"] = (d < 10) ? ("0" + d) : d;s["%e"] = d;s["%H"] = (hr < 10) ? ("0" + hr) : hr;s["%I"] = (ir < 10) ? ("0" + ir) : ir;s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy;s["%k"] = hr;
s["%l"] = ir;
s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m);s["%M"] = (min < 10) ? ("0" + min) : min;s["%n"] = "\n";
s["%p"] = pm ? "PM" : "AM";
s["%P"] = pm ? "pm" : "am";
s["%s"] = Math.floor(this.getTime() / 1000);
s["%S"] = (sec < 10) ? ("0" + sec) : sec;s["%t"] = "\t";s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
s["%u"] = w + 1;
s["%w"] = w;
s["%y"] = ('' + y).substr(2, 2);s["%Y"] = y;
s["%%"] = "%";
var re = /%./g;
if (!Calendar.is_ie5 && !Calendar.is_khtml)
return str.replace(re, function (par) { return s[par] || par; });var a = str.match(re);
for (var i = 0; i < a.length; i++) {
var tmp = s[a[i]];
if (tmp) {
re = new RegExp(a[i], 'g');
str = str.replace(re, tmp);
}
}return str;
};Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear;
Date.prototype.setFullYear = function(y) {
var d = new Date(this);
d.__msh_oldSetFullYear(y);
if (d.getMonth() != this.getMonth())
this.setDate(28);
this.__msh_oldSetFullYear(y);
};window._dynarch_popupCalendar = null;
Calendar._DN = new Array
("星期日","星期一","星期二","星期三","星期四","星期五","星期六","星期日");
Calendar._SDN = new Array
("日","一","二","三","四","五","六","日");
Calendar._FD = 0;
Calendar._MN = new Array
("一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月");
Calendar._SMN = new Array
("一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月");
Calendar._TT = {};
Calendar._TT["INFO"] = "帮助";
Calendar._TT["ABOUT"] =
"选择日期:\n" +
"- 点击 \xab, \xbb 按钮选择年份\n" +
"- 点击 " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " 按钮选择月份\n" +
"- 长按以上按钮可从菜单中快速选择年份或月份";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"选择时间:\n" +
"- 点击小时或分钟可使改数值加一\n" +
"- 按住Shift键点击小时或分钟可使改数值减一\n" +
"- 点击拖动鼠标可进行快速选择";
Calendar._TT["PREV_YEAR"] = "上一年 (按住出菜单)";
Calendar._TT["PREV_MONTH"] = "上一月 (按住出菜单)";
Calendar._TT["GO_TODAY"] = "转到今日";
Calendar._TT["NEXT_MONTH"] = "下一月 (按住出菜单)";
Calendar._TT["NEXT_YEAR"] = "下一年 (按住出菜单)";
Calendar._TT["SEL_DATE"] = "选择日期";
Calendar._TT["DRAG_TO_MOVE"] = "拖动";
Calendar._TT["PART_TODAY"] = " (今日)";
Calendar._TT["DAY_FIRST"] = "最左边显示%s";
Calendar._TT["WEEKEND"] = "0,6";
Calendar._TT["CLOSE"] = "关闭";
Calendar._TT["TODAY"] = "今日";
Calendar._TT["TIME_PART"] = "(Shift-)点击鼠标或拖动改变值";
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%A, %b %e日";
Calendar._TT["WK"] = "周";
Calendar._TT["TIME"] = "时间:";
Calendar.setup = function (params) {
function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } };
param_default("inputField", null);
param_default("displayArea", null);
param_default("button", null);
param_default("eventName", "click");
param_default("ifFormat", "%Y/%m/%d");
param_default("daFormat", "%Y/%m/%d");
param_default("singleClick", true);
param_default("disableFunc", null);
param_default("dateStatusFunc", params["disableFunc"]); // takes precedence if both are defined
param_default("dateText", null);
param_default("firstDay", null);
param_default("align", "Br");
param_default("range", [1900, 2999]);
param_default("weekNumbers", true);
param_default("flat", null);
param_default("flatCallback", null);
param_default("onSelect", null);
param_default("onClose", null);
param_default("onUpdate", null);
param_default("date", null);
param_default("showsTime", false);
param_default("timeFormat", "24");
param_default("electric", true);
param_default("step", 2);
param_default("position", null);
param_default("cache", false);
param_default("showOthers", false);
param_default("multiple", null);
var tmp = ["inputField", "displayArea", "button"];
for (var i in tmp) {
if (typeof params[tmp[i]] == "string") {
params[tmp[i]] = document.getElementById(params[tmp[i]]);
}
}
if (!(params.flat || params.multiple || params.inputField || params.displayArea || params.button)) {
alert("Calendar.setup:\n Nothing to setup (no fields found). Please check your code");
return false;
}
function onSelect(cal) {
var p = cal.params;
var update = (cal.dateClicked || p.electric);
if (update && p.inputField) {
p.inputField.value = cal.date.print(p.ifFormat);
if (typeof p.inputField.onchange == "function")
p.inputField.onchange();
}
if (update && p.displayArea)
p.displayArea.innerHTML = cal.date.print(p.daFormat);
if (update && typeof p.onUpdate == "function")
p.onUpdate(cal);
if (update && p.flat) {
if (typeof p.flatCallback == "function")
p.flatCallback(cal);
}
if (update && p.singleClick && cal.dateClicked)
cal.callCloseHandler();
};
if (params.flat != null) {
if (typeof params.flat == "string")
params.flat = document.getElementById(params.flat);
if (!params.flat) {
alert("Calendar.setup:\n Flat specified but can't find parent.");
return false;
}
var cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect);
cal.showsOtherMonths = params.showOthers;
cal.showsTime = params.showsTime;
cal.time24 = (params.timeFormat == "24");
cal.params = params;
cal.weekNumbers = params.weekNumbers;
cal.setRange(params.range[0], params.range[1]);
cal.setDateStatusHandler(params.dateStatusFunc);
cal.getDateText = params.dateText;
if (params.ifFormat) {
cal.setDateFormat(params.ifFormat);
}
if (params.inputField && typeof params.inputField.value == "string") {
cal.parseDate(params.inputField.value);
}
cal.create(params.flat);
cal.show();
return false;
}
var triggerEl = params.button || params.displayArea || params.inputField;
triggerEl["on" + params.eventName] = function() {
var dateEl = params.inputField || params.displayArea;
var dateFmt = params.inputField ? params.ifFormat : params.daFormat;
var mustCreate = false;
var cal = window.calendar;
if (dateEl)
params.date = Date.parseDate(dateEl.value || dateEl.innerHTML, dateFmt);
if (!(cal && params.cache)) {
window.calendar = cal = new Calendar(params.firstDay,
params.date,
params.onSelect || onSelect,
params.onClose || function(cal) { cal.hide(); });
cal.showsTime = params.showsTime;
cal.time24 = (params.timeFormat == "24");
cal.weekNumbers = params.weekNumbers;
mustCreate = true;
} else {
if (params.date)
cal.setDate(params.date);
cal.hide();
}
if (params.multiple) {
cal.multiple = {};
for (var i = params.multiple.length; --i >= 0;) {
var d = params.multiple[i];
var ds = d.print("%Y%m%d");
cal.multiple[ds] = d;
}
}
cal.showsOtherMonths = params.showOthers;
cal.yearStep = params.step;
cal.setRange(params.range[0], params.range[1]);
cal.params = params;
cal.setDateStatusHandler(params.dateStatusFunc);
cal.getDateText = params.dateText;
cal.setDateFormat(dateFmt);
if (mustCreate)
cal.create();
cal.refresh();
if (!params.position)
cal.showAtElement(params.button || params.displayArea || params.inputField, params.align);
else
cal.showAt(params.position[0], params.position[1]);
return false;
};
return cal;
}; | JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
};
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add('uicolor',{requires:['dialog'],lang:['en'],init:function(a){if(CKEDITOR.env.ie6Compat)return;a.addCommand('uicolor',new CKEDITOR.dialogCommand('uicolor'));a.ui.addButton('UIColor',{label:a.lang.uicolor.title,command:'uicolor',icon:this.path+'uicolor.gif'});CKEDITOR.dialog.add('uicolor',this.path+'dialogs/uicolor.js');CKEDITOR.scriptLoader.load(CKEDITOR.getUrl('plugins/uicolor/yui/yui.js'));a.element.getDocument().appendStyleSheet(CKEDITOR.getUrl('plugins/uicolor/yui/assets/yui.css'));}});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
| JavaScript |
var regexEnum =
{
intege:"^-?[1-9]\\d*$", //整数
intege1:"^[1-9]\\d*$", //正整数
intege2:"^-[1-9]\\d*$", //负整数
num:"^([+-]?)\\d*\\.?\\d+$", //数字
num1:"^[1-9]\\d*|0$", //正数(正整数 + 0)
num2:"^-[1-9]\\d*|0$", //负数(负整数 + 0)
decmal:"^([+-]?)\\d*\\.\\d+$", //浮点数
decmal1:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*$", //正浮点数
decmal2:"^-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*)$", //负浮点数
decmal3:"^-?([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0)$", //浮点数
decmal4:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0$", //非负浮点数(正浮点数 + 0)
decmal5:"^(-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*))|0?.0+|0$", //非正浮点数(负浮点数 + 0)
email:"^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$", //邮件
color:"^[a-fA-F0-9]{6}$", //颜色
url:"^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$", //url
chinese:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$", //仅中文
ascii:"^[\\x00-\\xFF]+$", //仅ACSII字符
zipcode:"^\\d{6}$", //邮编
mobile:"^(13|15)[0-9]{9}$", //手机
ip4:"^(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)$", //ip地址
notempty:"^\\S+$", //非空
picture:"(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$", //图片
rar:"(.*)\\.(rar|zip|7zip|tgz)$", //压缩文件
date:"^\\d{4}(\\-|\\/|\.)\\d{1,2}\\1\\d{1,2}$", //日期
qq:"^[1-9]*[1-9][0-9]*$", //QQ号码
tel:"^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", //电话号码的函数(包括验证国内区号,国际区号,分机号)
username:"^\\w+$", //用来用户注册。匹配由数字、26个英文字母或者下划线组成的字符串
letter:"^[A-Za-z]+$", //字母
letter_u:"^[A-Z]+$", //大写字母
letter_l:"^[a-z]+$", //小写字母
idcard:"^[1-9]([0-9]{14}|[0-9]{17})$", //身份证
ps_username:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D_\\w]+$" //中文、字母、数字 _
}
function isCardID(sId){
var iSum=0 ;
var info="" ;
if(!/^\d{17}(\d|x)$/i.test(sId)) return "你输入的身份证长度或格式错误";
sId=sId.replace(/x$/i,"a");
if(aCity[parseInt(sId.substr(0,2))]==null) return "你的身份证地区非法";
sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2));
var d=new Date(sBirthday.replace(/-/g,"/")) ;
if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return "身份证上的出生日期非法";
for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11) ;
if(iSum%11!=1) return "你输入的身份证号非法";
return true;//aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女")
}
//短时间,形如 (13:04:06)
function isTime(str)
{
var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/);
if (a == null) {return false}
if (a[1]>24 || a[3]>60 || a[4]>60)
{
return false;
}
return true;
}
//短日期,形如 (2003-12-05)
function isDate(str)
{
var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
if(r==null)return false;
var d= new Date(r[1], r[3]-1, r[4]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
}
//长时间,形如 (2003-12-05 13:04:06)
function isDateTime(str)
{
var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
var r = str.match(reg);
if(r==null) return false;
var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);
} | JavaScript |
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject = function() {
var UNDEF = "undefined",
OBJECT = "object",
SHOCKWAVE_FLASH = "Shockwave Flash",
SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
FLASH_MIME_TYPE = "application/x-shockwave-flash",
EXPRESS_INSTALL_ID = "SWFObjectExprInst",
ON_READY_STATE_CHANGE = "onreadystatechange",
win = window,
doc = document,
nav = navigator,
plugin = false,
domLoadFnArr = [main],
regObjArr = [],
objIdArr = [],
listenersArr = [],
storedAltContent,
storedAltContentId,
storedCallbackFn,
storedCallbackObj,
isDomLoaded = false,
isExpressInstallActive = false,
dynamicStylesheet,
dynamicStylesheetMedia,
autoHideShow = true,
/* Centralized function for browser feature detection
- User agent string detection is only used when no good alternative is possible
- Is executed directly for optimal performance
*/
ua = function() {
var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
u = nav.userAgent.toLowerCase(),
p = nav.platform.toLowerCase(),
windows = p ? /win/.test(p) : /win/.test(u),
mac = p ? /mac/.test(p) : /mac/.test(u),
webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
playerVersion = [0,0,0],
d = null;
if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
d = nav.plugins[SHOCKWAVE_FLASH].description;
if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
plugin = true;
ie = false; // cascaded feature detection for Internet Explorer
d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
}
}
else if (typeof win.ActiveXObject != UNDEF) {
try {
var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
if (a) { // a will return null when ActiveX is disabled
d = a.GetVariable("$version");
if (d) {
ie = true; // cascaded feature detection for Internet Explorer
d = d.split(" ")[1].split(",");
playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
}
catch(e) {}
}
return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac };
}(),
/* Cross-browser onDomLoad
- Will fire an event as soon as the DOM of a web page is loaded
- Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/
- Regular onload serves as fallback
*/
onDomLoad = function() {
if (!ua.w3) { return; }
if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically
callDomLoadFunctions();
}
if (!isDomLoaded) {
if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false);
}
if (ua.ie && ua.win) {
doc.attachEvent(ON_READY_STATE_CHANGE, function() {
if (doc.readyState == "complete") {
doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee);
callDomLoadFunctions();
}
});
if (win == top) { // if not inside an iframe
(function(){
if (isDomLoaded) { return; }
try {
doc.documentElement.doScroll("left");
}
catch(e) {
setTimeout(arguments.callee, 0);
return;
}
callDomLoadFunctions();
})();
}
}
if (ua.wk) {
(function(){
if (isDomLoaded) { return; }
if (!/loaded|complete/.test(doc.readyState)) {
setTimeout(arguments.callee, 0);
return;
}
callDomLoadFunctions();
})();
}
addLoadEvent(callDomLoadFunctions);
}
}();
function callDomLoadFunctions() {
if (isDomLoaded) { return; }
try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early
var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span"));
t.parentNode.removeChild(t);
}
catch (e) { return; }
isDomLoaded = true;
var dl = domLoadFnArr.length;
for (var i = 0; i < dl; i++) {
domLoadFnArr[i]();
}
}
function addDomLoadEvent(fn) {
if (isDomLoaded) {
fn();
}
else {
domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
}
}
/* Cross-browser onload
- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
- Will fire an event as soon as a web page including all of its assets are loaded
*/
function addLoadEvent(fn) {
if (typeof win.addEventListener != UNDEF) {
win.addEventListener("load", fn, false);
}
else if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("load", fn, false);
}
else if (typeof win.attachEvent != UNDEF) {
addListener(win, "onload", fn);
}
else if (typeof win.onload == "function") {
var fnOld = win.onload;
win.onload = function() {
fnOld();
fn();
};
}
else {
win.onload = fn;
}
}
/* Main function
- Will preferably execute onDomLoad, otherwise onload (as a fallback)
*/
function main() {
if (plugin) {
testPlayerVersion();
}
else {
matchVersions();
}
}
/* Detect the Flash Player version for non-Internet Explorer browsers
- Detecting the plug-in version via the object element is more precise than using the plugins collection item's description:
a. Both release and build numbers can be detected
b. Avoid wrong descriptions by corrupt installers provided by Adobe
c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports
- Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available
*/
function testPlayerVersion() {
var b = doc.getElementsByTagName("body")[0];
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
var t = b.appendChild(o);
if (t) {
var counter = 0;
(function(){
if (typeof t.GetVariable != UNDEF) {
var d = t.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
else if (counter < 10) {
counter++;
setTimeout(arguments.callee, 10);
return;
}
b.removeChild(o);
t = null;
matchVersions();
})();
}
else {
matchVersions();
}
}
/* Perform Flash Player and SWF version matching; static publishing only
*/
function matchVersions() {
var rl = regObjArr.length;
if (rl > 0) {
for (var i = 0; i < rl; i++) { // for each registered object element
var id = regObjArr[i].id;
var cb = regObjArr[i].callbackFn;
var cbObj = {success:false, id:id};
if (ua.pv[0] > 0) {
var obj = getElementById(id);
if (obj) {
if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match!
setVisibility(id, true);
if (cb) {
cbObj.success = true;
cbObj.ref = getObjectById(id);
cb(cbObj);
}
}
else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported
var att = {};
att.data = regObjArr[i].expressInstall;
att.width = obj.getAttribute("width") || "0";
att.height = obj.getAttribute("height") || "0";
if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); }
if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); }
// parse HTML object param element's name-value pairs
var par = {};
var p = obj.getElementsByTagName("param");
var pl = p.length;
for (var j = 0; j < pl; j++) {
if (p[j].getAttribute("name").toLowerCase() != "movie") {
par[p[j].getAttribute("name")] = p[j].getAttribute("value");
}
}
showExpressInstall(att, par, id, cb);
}
else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF
displayAltContent(obj);
if (cb) { cb(cbObj); }
}
}
}
else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content)
setVisibility(id, true);
if (cb) {
var o = getObjectById(id); // test whether there is an HTML object element or not
if (o && typeof o.SetVariable != UNDEF) {
cbObj.success = true;
cbObj.ref = o;
}
cb(cbObj);
}
}
}
}
}
function getObjectById(objectIdStr) {
var r = null;
var o = getElementById(objectIdStr);
if (o && o.nodeName == "OBJECT") {
if (typeof o.SetVariable != UNDEF) {
r = o;
}
else {
var n = o.getElementsByTagName(OBJECT)[0];
if (n) {
r = n;
}
}
}
return r;
}
/* Requirements for Adobe Express Install
- only one instance can be active at a time
- fp 6.0.65 or higher
- Win/Mac OS only
- no Webkit engines older than version 312
*/
function canExpressInstall() {
return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312);
}
/* Show the Adobe Express Install dialog
- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
*/
function showExpressInstall(att, par, replaceElemIdStr, callbackFn) {
isExpressInstallActive = true;
storedCallbackFn = callbackFn || null;
storedCallbackObj = {success:false, id:replaceElemIdStr};
var obj = getElementById(replaceElemIdStr);
if (obj) {
if (obj.nodeName == "OBJECT") { // static publishing
storedAltContent = abstractAltContent(obj);
storedAltContentId = null;
}
else { // dynamic publishing
storedAltContent = obj;
storedAltContentId = replaceElemIdStr;
}
att.id = EXPRESS_INSTALL_ID;
if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; }
if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; }
doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
fv = "MMredirectURL=" + win.location.toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title;
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + fv;
}
else {
par.flashvars = fv;
}
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
if (ua.ie && ua.win && obj.readyState != 4) {
var newObj = createElement("div");
replaceElemIdStr += "SWFObjectNew";
newObj.setAttribute("id", replaceElemIdStr);
obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
createSWF(att, par, replaceElemIdStr);
}
}
/* Functions to abstract and display alternative content
*/
function displayAltContent(obj) {
if (ua.ie && ua.win && obj.readyState != 4) {
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
var el = createElement("div");
obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content
el.parentNode.replaceChild(abstractAltContent(obj), el);
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.replaceChild(abstractAltContent(obj), obj);
}
}
function abstractAltContent(obj) {
var ac = createElement("div");
if (ua.win && ua.ie) {
ac.innerHTML = obj.innerHTML;
}
else {
var nestedObj = obj.getElementsByTagName(OBJECT)[0];
if (nestedObj) {
var c = nestedObj.childNodes;
if (c) {
var cl = c.length;
for (var i = 0; i < cl; i++) {
if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
ac.appendChild(c[i].cloneNode(true));
}
}
}
}
}
return ac;
}
/* Cross-browser dynamic SWF creation
*/
function createSWF(attObj, parObj, id) {
var r, el = getElementById(id);
if (ua.wk && ua.wk < 312) { return r; }
if (el) {
if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
attObj.id = id;
}
if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML
var att = "";
for (var i in attObj) {
if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries
if (i.toLowerCase() == "data") {
parObj.movie = attObj[i];
}
else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
att += ' class="' + attObj[i] + '"';
}
else if (i.toLowerCase() != "classid") {
att += ' ' + i + '="' + attObj[i] + '"';
}
}
}
var par = "";
for (var j in parObj) {
if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries
par += '<param name="' + j + '" value="' + parObj[j] + '" />';
}
}
el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only)
r = getElementById(attObj.id);
}
else { // well-behaving browsers
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
for (var m in attObj) {
if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries
if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
o.setAttribute("class", attObj[m]);
}
else if (m.toLowerCase() != "classid") { // filter out IE specific attribute
o.setAttribute(m, attObj[m]);
}
}
}
for (var n in parObj) {
if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element
createObjParam(o, n, parObj[n]);
}
}
el.parentNode.replaceChild(o, el);
r = o;
}
}
return r;
}
function createObjParam(el, pName, pValue) {
var p = createElement("param");
p.setAttribute("name", pName);
p.setAttribute("value", pValue);
el.appendChild(p);
}
/* Cross-browser SWF removal
- Especially needed to safely and completely remove a SWF in Internet Explorer
*/
function removeSWF(id) {
var obj = getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (ua.ie && ua.win) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
removeObjectInIE(id);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.removeChild(obj);
}
}
}
function removeObjectInIE(id) {
var obj = getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
/* Functions to optimize JavaScript compression
*/
function getElementById(id) {
var el = null;
try {
el = doc.getElementById(id);
}
catch (e) {}
return el;
}
function createElement(el) {
return doc.createElement(el);
}
/* Updated attachEvent function for Internet Explorer
- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
*/
function addListener(target, eventType, fn) {
target.attachEvent(eventType, fn);
listenersArr[listenersArr.length] = [target, eventType, fn];
}
/* Flash Player and SWF content version matching
*/
function hasPlayerVersion(rv) {
var pv = ua.pv, v = rv.split(".");
v[0] = parseInt(v[0], 10);
v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
v[2] = parseInt(v[2], 10) || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
}
/* Cross-browser dynamic CSS creation
- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
*/
function createCSS(sel, decl, media, newStyle) {
if (ua.ie && ua.mac) { return; }
var h = doc.getElementsByTagName("head")[0];
if (!h) { return; } // to also support badly authored HTML pages that lack a head element
var m = (media && typeof media == "string") ? media : "screen";
if (newStyle) {
dynamicStylesheet = null;
dynamicStylesheetMedia = null;
}
if (!dynamicStylesheet || dynamicStylesheetMedia != m) {
// create dynamic stylesheet + get a global reference to it
var s = createElement("style");
s.setAttribute("type", "text/css");
s.setAttribute("media", m);
dynamicStylesheet = h.appendChild(s);
if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1];
}
dynamicStylesheetMedia = m;
}
// add style rule
if (ua.ie && ua.win) {
if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) {
dynamicStylesheet.addRule(sel, decl);
}
}
else {
if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) {
dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
}
}
}
function setVisibility(id, isVisible) {
if (!autoHideShow) { return; }
var v = isVisible ? "visible" : "hidden";
if (isDomLoaded && getElementById(id)) {
getElementById(id).style.visibility = v;
}
else {
createCSS("#" + id, "visibility:" + v);
}
}
/* Filter to avoid XSS attacks
*/
function urlEncodeIfNecessary(s) {
var regex = /[\\\"<>\.;]/;
var hasBadChars = regex.exec(s) != null;
return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s;
}
/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
*/
var cleanup = function() {
if (ua.ie && ua.win) {
window.attachEvent("onunload", function() {
// remove listeners to avoid memory leaks
var ll = listenersArr.length;
for (var i = 0; i < ll; i++) {
listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
}
// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
var il = objIdArr.length;
for (var j = 0; j < il; j++) {
removeSWF(objIdArr[j]);
}
// cleanup library's main closures to avoid memory leaks
for (var k in ua) {
ua[k] = null;
}
ua = null;
for (var l in swfobject) {
swfobject[l] = null;
}
swfobject = null;
});
}
}();
return {
/* Public API
- Reference: http://code.google.com/p/swfobject/wiki/documentation
*/
registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) {
if (ua.w3 && objectIdStr && swfVersionStr) {
var regObj = {};
regObj.id = objectIdStr;
regObj.swfVersion = swfVersionStr;
regObj.expressInstall = xiSwfUrlStr;
regObj.callbackFn = callbackFn;
regObjArr[regObjArr.length] = regObj;
setVisibility(objectIdStr, false);
}
else if (callbackFn) {
callbackFn({success:false, id:objectIdStr});
}
},
getObjectById: function(objectIdStr) {
if (ua.w3) {
return getObjectById(objectIdStr);
}
},
embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) {
var callbackObj = {success:false, id:replaceElemIdStr};
if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) {
setVisibility(replaceElemIdStr, false);
addDomLoadEvent(function() {
widthStr += ""; // auto-convert to string
heightStr += "";
var att = {};
if (attObj && typeof attObj === OBJECT) {
for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs
att[i] = attObj[i];
}
}
att.data = swfUrlStr;
att.width = widthStr;
att.height = heightStr;
var par = {};
if (parObj && typeof parObj === OBJECT) {
for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs
par[j] = parObj[j];
}
}
if (flashvarsObj && typeof flashvarsObj === OBJECT) {
for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + k + "=" + flashvarsObj[k];
}
else {
par.flashvars = k + "=" + flashvarsObj[k];
}
}
}
if (hasPlayerVersion(swfVersionStr)) { // create SWF
var obj = createSWF(att, par, replaceElemIdStr);
if (att.id == replaceElemIdStr) {
setVisibility(replaceElemIdStr, true);
}
callbackObj.success = true;
callbackObj.ref = obj;
}
else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install
att.data = xiSwfUrlStr;
showExpressInstall(att, par, replaceElemIdStr, callbackFn);
return;
}
else { // show alternative content
setVisibility(replaceElemIdStr, true);
}
if (callbackFn) { callbackFn(callbackObj); }
});
}
else if (callbackFn) { callbackFn(callbackObj); }
},
switchOffAutoHideShow: function() {
autoHideShow = false;
},
ua: ua,
getFlashPlayerVersion: function() {
return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
},
hasFlashPlayerVersion: hasPlayerVersion,
createSWF: function(attObj, parObj, replaceElemIdStr) {
if (ua.w3) {
return createSWF(attObj, parObj, replaceElemIdStr);
}
else {
return undefined;
}
},
showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) {
if (ua.w3 && canExpressInstall()) {
showExpressInstall(att, par, replaceElemIdStr, callbackFn);
}
},
removeSWF: function(objElemIdStr) {
if (ua.w3) {
removeSWF(objElemIdStr);
}
},
createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) {
if (ua.w3) {
createCSS(selStr, declStr, mediaStr, newStyleBoolean);
}
},
addDomLoadEvent: addDomLoadEvent,
addLoadEvent: addLoadEvent,
getQueryParamValue: function(param) {
var q = doc.location.search || doc.location.hash;
if (q) {
if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark
if (param == null) {
return urlEncodeIfNecessary(q);
}
var pairs = q.split("&");
for (var i = 0; i < pairs.length; i++) {
if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
}
}
}
return "";
},
// For internal usage only
expressInstallCallback: function() {
if (isExpressInstallActive) {
var obj = getElementById(EXPRESS_INSTALL_ID);
if (obj && storedAltContent) {
obj.parentNode.replaceChild(storedAltContent, obj);
if (storedAltContentId) {
setVisibility(storedAltContentId, true);
if (ua.ie && ua.win) { storedAltContent.style.display = "block"; }
}
if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); }
}
isExpressInstallActive = false;
}
}
};
}();
| JavaScript |
/*
* 在jquery.suggest 1.1基础上针对中文输入的特点做了部分修改,下载原版请到jquery插件库
* 修改者:wangshuai
*
* 修改部分已在文中标注
*
*
* jquery.suggest 1.1 - 2007-08-06
*
* Uses code and techniques from following libraries:
* 1. http://www.dyve.net/jquery/?autocomplete
* 2. http://dev.jquery.com/browser/trunk/plugins/interface/iautocompleter.js
*
* All the new stuff written by Peter Vulgaris (www.vulgarisoip.com)
* Feel free to do whatever you want with this file
*
*/
(function($) {
$.suggest = function(input, options) {
var $input = $(input).attr("autocomplete", "off");
var $results = $("#sr_infos");
var timeout = false; // hold timeout ID for suggestion results to appear
var prevLength = 0; // last recorded length of $input.val()
$input.blur(function() {
setTimeout(function() { $results.hide() }, 200);
});
$results.mouseover(function() {
$("#sr_infos ul li").removeClass(options.selectClass);
})
// help IE users if possible
try {
$results.bgiframe();
} catch(e) { }
// I really hate browser detection, but I don't see any other way
//修改开始
//下面部分在作者原来代码的基本上针对中文输入的特点做了些修改
if ($.browser.mozilla)
$input.keypress(processKey2); // onkeypress repeats arrow keys in Mozilla/Opera
else
$input.keydown(processKey2); // onkeydown repeats arrow keys in IE/Safari*/
//这里是自己改为keyup事件
$input.keyup(processKey);
//修改结束
function processKey(e) {
// handling up/down/escape requires results to be visible
// handling enter/tab requires that AND a result to be selected
if (/^32$|^9$/.test(e.keyCode) && getCurrentResult()) {
if (e.preventDefault)
e.preventDefault();
if (e.stopPropagation)
e.stopPropagation();
e.cancelBubble = true;
e.returnValue = false;
selectCurrentResult();
} else if ($input.val().length != prevLength) {
if (timeout)
clearTimeout(timeout);
timeout = setTimeout(suggest, options.delay);
prevLength = $input.val().length;
}
}
//此处针对上面介绍的修改增加的函数
function processKey2(e) {
// handling up/down/escape requires results to be visible
// handling enter/tab requires that AND a result to be selected
if (/27$|38$|40$|13$/.test(e.keyCode) && $results.is(':visible')) {
if (e.preventDefault)
e.preventDefault();
if (e.stopPropagation)
e.stopPropagation();
e.cancelBubble = true;
e.returnValue = false;
switch(e.keyCode) {
case 38: // up
prevResult();
break;
case 40: // down
nextResult();
break;
case 27: // escape
$results.hide();
break;
case 13: // enter
$currentResult = getCurrentResult();
if ($currentResult) {
$input.val($currentResult.text());
window.location.href='?m=search&c=index&a=init&q='+$currentResult.text();
}
break;
}
} else if ($input.val().length != prevLength) {
if (timeout)
clearTimeout(timeout);
timeout = setTimeout(suggest, options.delay);
prevLength = $input.val().length;
}
}
function suggest() {
var q = $input.val().replace(/ /g, '');
if (q.length >= options.minchars) {
$.getScript(options.source+'&q='+q, function(){
});
$results.hide();
//var items = parseTxt(txt, q);
//displayItems(items);
$results.show();
} else {
$results.hide();
}
}
function displayItems(items) {
if (!items)
return;
if (!items.length) {
$results.hide();
return;
}
var html = '';
for (var i = 0; i < items.length; i++)
html += '<li>' + items[i] + '</li>';
$results.html(html).show();
$results
.children('li')
.mouseover(function() {
$results.children('li').removeClass(options.selectClass);
$(this).addClass(options.selectClass);
})
.click(function(e) {
e.preventDefault();
e.stopPropagation();
selectCurrentResult();
});
}
function getCurrentResult() {
if (!$results.is(':visible'))
return false;
//var $currentResult = $results.children('li.' + options.selectClass);
var $currentResult = $("#sr_infos ul li."+ options.selectClass);
if (!$currentResult.length)
$currentResult = false;
return $currentResult;
}
function selectCurrentResult() {
$currentResult = getCurrentResult();
if ($currentResult) {
$input.val($currentResult.text());
$results.hide();
if (options.onSelect)
options.onSelect.apply($input[0]);
}
}
function nextResult() {
$currentResult = getCurrentResult();
if ($currentResult) {
$currentResult.removeClass(options.selectClass).next().addClass(options.selectClass);
} else {
$("#sr_infos ul li:first-child'").addClass(options.selectClass);
//$results.children('li:first-child').addClass(options.selectClass);
}
}
function prevResult() {
$currentResult = getCurrentResult();
if ($currentResult)
$currentResult.removeClass(options.selectClass).prev().addClass(options.selectClass);
else
//$results.children('li:last-child').addClass(options.selectClass);
$("#sr_infos ul li:last-child'").addClass(options.selectClass);
}
}
$.fn.suggest = function(source, options) {
if (!source)
return;
options = options || {};
options.source = source;
options.delay = options.delay || 100;
options.resultsClass = options.resultsClass || 'ac_results';
options.selectClass = options.selectClass || 'ac_over';
options.matchClass = options.matchClass || 'ac_match';
options.minchars = options.minchars || 1;
options.delimiter = options.delimiter || '\n';
options.onSelect = options.onSelect || false;
this.each(function() {
new $.suggest(this, options);
});
return this;
};
})(jQuery); | JavaScript |
function setmodel(value, id, siteid, q) {
$("#typeid").val(value);
$("#search a").removeClass();
id.addClass('on');
if(q!=null && q!='') {
window.location='?m=search&c=index&a=init&siteid='+siteid+'&typeid='+value+'&q='+q;
}
} | JavaScript |
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject = function() {
var UNDEF = "undefined",
OBJECT = "object",
SHOCKWAVE_FLASH = "Shockwave Flash",
SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
FLASH_MIME_TYPE = "application/x-shockwave-flash",
EXPRESS_INSTALL_ID = "SWFObjectExprInst",
ON_READY_STATE_CHANGE = "onreadystatechange",
win = window,
doc = document,
nav = navigator,
plugin = false,
domLoadFnArr = [main],
regObjArr = [],
objIdArr = [],
listenersArr = [],
storedAltContent,
storedAltContentId,
storedCallbackFn,
storedCallbackObj,
isDomLoaded = false,
isExpressInstallActive = false,
dynamicStylesheet,
dynamicStylesheetMedia,
autoHideShow = true,
/* Centralized function for browser feature detection
- User agent string detection is only used when no good alternative is possible
- Is executed directly for optimal performance
*/
ua = function() {
var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
u = nav.userAgent.toLowerCase(),
p = nav.platform.toLowerCase(),
windows = p ? /win/.test(p) : /win/.test(u),
mac = p ? /mac/.test(p) : /mac/.test(u),
webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
playerVersion = [0,0,0],
d = null;
if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
d = nav.plugins[SHOCKWAVE_FLASH].description;
if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
plugin = true;
ie = false; // cascaded feature detection for Internet Explorer
d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
}
}
else if (typeof win.ActiveXObject != UNDEF) {
try {
var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
if (a) { // a will return null when ActiveX is disabled
d = a.GetVariable("$version");
if (d) {
ie = true; // cascaded feature detection for Internet Explorer
d = d.split(" ")[1].split(",");
playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
}
catch(e) {}
}
return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac };
}(),
/* Cross-browser onDomLoad
- Will fire an event as soon as the DOM of a web page is loaded
- Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/
- Regular onload serves as fallback
*/
onDomLoad = function() {
if (!ua.w3) { return; }
if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically
callDomLoadFunctions();
}
if (!isDomLoaded) {
if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false);
}
if (ua.ie && ua.win) {
doc.attachEvent(ON_READY_STATE_CHANGE, function() {
if (doc.readyState == "complete") {
doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee);
callDomLoadFunctions();
}
});
if (win == top) { // if not inside an iframe
(function(){
if (isDomLoaded) { return; }
try {
doc.documentElement.doScroll("left");
}
catch(e) {
setTimeout(arguments.callee, 0);
return;
}
callDomLoadFunctions();
})();
}
}
if (ua.wk) {
(function(){
if (isDomLoaded) { return; }
if (!/loaded|complete/.test(doc.readyState)) {
setTimeout(arguments.callee, 0);
return;
}
callDomLoadFunctions();
})();
}
addLoadEvent(callDomLoadFunctions);
}
}();
function callDomLoadFunctions() {
if (isDomLoaded) { return; }
try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early
var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span"));
t.parentNode.removeChild(t);
}
catch (e) { return; }
isDomLoaded = true;
var dl = domLoadFnArr.length;
for (var i = 0; i < dl; i++) {
domLoadFnArr[i]();
}
}
function addDomLoadEvent(fn) {
if (isDomLoaded) {
fn();
}
else {
domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
}
}
/* Cross-browser onload
- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
- Will fire an event as soon as a web page including all of its assets are loaded
*/
function addLoadEvent(fn) {
if (typeof win.addEventListener != UNDEF) {
win.addEventListener("load", fn, false);
}
else if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("load", fn, false);
}
else if (typeof win.attachEvent != UNDEF) {
addListener(win, "onload", fn);
}
else if (typeof win.onload == "function") {
var fnOld = win.onload;
win.onload = function() {
fnOld();
fn();
};
}
else {
win.onload = fn;
}
}
/* Main function
- Will preferably execute onDomLoad, otherwise onload (as a fallback)
*/
function main() {
if (plugin) {
testPlayerVersion();
}
else {
matchVersions();
}
}
/* Detect the Flash Player version for non-Internet Explorer browsers
- Detecting the plug-in version via the object element is more precise than using the plugins collection item's description:
a. Both release and build numbers can be detected
b. Avoid wrong descriptions by corrupt installers provided by Adobe
c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports
- Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available
*/
function testPlayerVersion() {
var b = doc.getElementsByTagName("body")[0];
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
var t = b.appendChild(o);
if (t) {
var counter = 0;
(function(){
if (typeof t.GetVariable != UNDEF) {
var d = t.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
else if (counter < 10) {
counter++;
setTimeout(arguments.callee, 10);
return;
}
b.removeChild(o);
t = null;
matchVersions();
})();
}
else {
matchVersions();
}
}
/* Perform Flash Player and SWF version matching; static publishing only
*/
function matchVersions() {
var rl = regObjArr.length;
if (rl > 0) {
for (var i = 0; i < rl; i++) { // for each registered object element
var id = regObjArr[i].id;
var cb = regObjArr[i].callbackFn;
var cbObj = {success:false, id:id};
if (ua.pv[0] > 0) {
var obj = getElementById(id);
if (obj) {
if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match!
setVisibility(id, true);
if (cb) {
cbObj.success = true;
cbObj.ref = getObjectById(id);
cb(cbObj);
}
}
else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported
var att = {};
att.data = regObjArr[i].expressInstall;
att.width = obj.getAttribute("width") || "0";
att.height = obj.getAttribute("height") || "0";
if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); }
if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); }
// parse HTML object param element's name-value pairs
var par = {};
var p = obj.getElementsByTagName("param");
var pl = p.length;
for (var j = 0; j < pl; j++) {
if (p[j].getAttribute("name").toLowerCase() != "movie") {
par[p[j].getAttribute("name")] = p[j].getAttribute("value");
}
}
showExpressInstall(att, par, id, cb);
}
else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF
displayAltContent(obj);
if (cb) { cb(cbObj); }
}
}
}
else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content)
setVisibility(id, true);
if (cb) {
var o = getObjectById(id); // test whether there is an HTML object element or not
if (o && typeof o.SetVariable != UNDEF) {
cbObj.success = true;
cbObj.ref = o;
}
cb(cbObj);
}
}
}
}
}
function getObjectById(objectIdStr) {
var r = null;
var o = getElementById(objectIdStr);
if (o && o.nodeName == "OBJECT") {
if (typeof o.SetVariable != UNDEF) {
r = o;
}
else {
var n = o.getElementsByTagName(OBJECT)[0];
if (n) {
r = n;
}
}
}
return r;
}
/* Requirements for Adobe Express Install
- only one instance can be active at a time
- fp 6.0.65 or higher
- Win/Mac OS only
- no Webkit engines older than version 312
*/
function canExpressInstall() {
return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312);
}
/* Show the Adobe Express Install dialog
- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
*/
function showExpressInstall(att, par, replaceElemIdStr, callbackFn) {
isExpressInstallActive = true;
storedCallbackFn = callbackFn || null;
storedCallbackObj = {success:false, id:replaceElemIdStr};
var obj = getElementById(replaceElemIdStr);
if (obj) {
if (obj.nodeName == "OBJECT") { // static publishing
storedAltContent = abstractAltContent(obj);
storedAltContentId = null;
}
else { // dynamic publishing
storedAltContent = obj;
storedAltContentId = replaceElemIdStr;
}
att.id = EXPRESS_INSTALL_ID;
if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; }
if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; }
doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
fv = "MMredirectURL=" + encodeURI(window.location).toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title;
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + fv;
}
else {
par.flashvars = fv;
}
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
if (ua.ie && ua.win && obj.readyState != 4) {
var newObj = createElement("div");
replaceElemIdStr += "SWFObjectNew";
newObj.setAttribute("id", replaceElemIdStr);
obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
createSWF(att, par, replaceElemIdStr);
}
}
/* Functions to abstract and display alternative content
*/
function displayAltContent(obj) {
if (ua.ie && ua.win && obj.readyState != 4) {
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
var el = createElement("div");
obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content
el.parentNode.replaceChild(abstractAltContent(obj), el);
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.replaceChild(abstractAltContent(obj), obj);
}
}
function abstractAltContent(obj) {
var ac = createElement("div");
if (ua.win && ua.ie) {
ac.innerHTML = obj.innerHTML;
}
else {
var nestedObj = obj.getElementsByTagName(OBJECT)[0];
if (nestedObj) {
var c = nestedObj.childNodes;
if (c) {
var cl = c.length;
for (var i = 0; i < cl; i++) {
if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
ac.appendChild(c[i].cloneNode(true));
}
}
}
}
}
return ac;
}
/* Cross-browser dynamic SWF creation
*/
function createSWF(attObj, parObj, id) {
var r, el = getElementById(id);
if (ua.wk && ua.wk < 312) { return r; }
if (el) {
if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
attObj.id = id;
}
if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML
var att = "";
for (var i in attObj) {
if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries
if (i.toLowerCase() == "data") {
parObj.movie = attObj[i];
}
else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
att += ' class="' + attObj[i] + '"';
}
else if (i.toLowerCase() != "classid") {
att += ' ' + i + '="' + attObj[i] + '"';
}
}
}
var par = "";
for (var j in parObj) {
if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries
par += '<param name="' + j + '" value="' + parObj[j] + '" />';
}
}
el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only)
r = getElementById(attObj.id);
}
else { // well-behaving browsers
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
for (var m in attObj) {
if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries
if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
o.setAttribute("class", attObj[m]);
}
else if (m.toLowerCase() != "classid") { // filter out IE specific attribute
o.setAttribute(m, attObj[m]);
}
}
}
for (var n in parObj) {
if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element
createObjParam(o, n, parObj[n]);
}
}
el.parentNode.replaceChild(o, el);
r = o;
}
}
return r;
}
function createObjParam(el, pName, pValue) {
var p = createElement("param");
p.setAttribute("name", pName);
p.setAttribute("value", pValue);
el.appendChild(p);
}
/* Cross-browser SWF removal
- Especially needed to safely and completely remove a SWF in Internet Explorer
*/
function removeSWF(id) {
var obj = getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (ua.ie && ua.win) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
removeObjectInIE(id);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.removeChild(obj);
}
}
}
function removeObjectInIE(id) {
var obj = getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
/* Functions to optimize JavaScript compression
*/
function getElementById(id) {
var el = null;
try {
el = doc.getElementById(id);
}
catch (e) {}
return el;
}
function createElement(el) {
return doc.createElement(el);
}
/* Updated attachEvent function for Internet Explorer
- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
*/
function addListener(target, eventType, fn) {
target.attachEvent(eventType, fn);
listenersArr[listenersArr.length] = [target, eventType, fn];
}
/* Flash Player and SWF content version matching
*/
function hasPlayerVersion(rv) {
var pv = ua.pv, v = rv.split(".");
v[0] = parseInt(v[0], 10);
v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
v[2] = parseInt(v[2], 10) || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
}
/* Cross-browser dynamic CSS creation
- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
*/
function createCSS(sel, decl, media, newStyle) {
if (ua.ie && ua.mac) { return; }
var h = doc.getElementsByTagName("head")[0];
if (!h) { return; } // to also support badly authored HTML pages that lack a head element
var m = (media && typeof media == "string") ? media : "screen";
if (newStyle) {
dynamicStylesheet = null;
dynamicStylesheetMedia = null;
}
if (!dynamicStylesheet || dynamicStylesheetMedia != m) {
// create dynamic stylesheet + get a global reference to it
var s = createElement("style");
s.setAttribute("type", "text/css");
s.setAttribute("media", m);
dynamicStylesheet = h.appendChild(s);
if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1];
}
dynamicStylesheetMedia = m;
}
// add style rule
if (ua.ie && ua.win) {
if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) {
dynamicStylesheet.addRule(sel, decl);
}
}
else {
if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) {
dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
}
}
}
function setVisibility(id, isVisible) {
if (!autoHideShow) { return; }
var v = isVisible ? "visible" : "hidden";
if (isDomLoaded && getElementById(id)) {
getElementById(id).style.visibility = v;
}
else {
createCSS("#" + id, "visibility:" + v);
}
}
/* Filter to avoid XSS attacks
*/
function urlEncodeIfNecessary(s) {
var regex = /[\\\"<>\.;]/;
var hasBadChars = regex.exec(s) != null;
return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s;
}
/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
*/
var cleanup = function() {
if (ua.ie && ua.win) {
window.attachEvent("onunload", function() {
// remove listeners to avoid memory leaks
var ll = listenersArr.length;
for (var i = 0; i < ll; i++) {
listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
}
// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
var il = objIdArr.length;
for (var j = 0; j < il; j++) {
removeSWF(objIdArr[j]);
}
// cleanup library's main closures to avoid memory leaks
for (var k in ua) {
ua[k] = null;
}
ua = null;
for (var l in swfobject) {
swfobject[l] = null;
}
swfobject = null;
});
}
}();
return {
/* Public API
- Reference: http://code.google.com/p/swfobject/wiki/documentation
*/
registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) {
if (ua.w3 && objectIdStr && swfVersionStr) {
var regObj = {};
regObj.id = objectIdStr;
regObj.swfVersion = swfVersionStr;
regObj.expressInstall = xiSwfUrlStr;
regObj.callbackFn = callbackFn;
regObjArr[regObjArr.length] = regObj;
setVisibility(objectIdStr, false);
}
else if (callbackFn) {
callbackFn({success:false, id:objectIdStr});
}
},
getObjectById: function(objectIdStr) {
if (ua.w3) {
return getObjectById(objectIdStr);
}
},
embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) {
var callbackObj = {success:false, id:replaceElemIdStr};
if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) {
setVisibility(replaceElemIdStr, false);
addDomLoadEvent(function() {
widthStr += ""; // auto-convert to string
heightStr += "";
var att = {};
if (attObj && typeof attObj === OBJECT) {
for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs
att[i] = attObj[i];
}
}
att.data = swfUrlStr;
att.width = widthStr;
att.height = heightStr;
var par = {};
if (parObj && typeof parObj === OBJECT) {
for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs
par[j] = parObj[j];
}
}
if (flashvarsObj && typeof flashvarsObj === OBJECT) {
for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + k + "=" + flashvarsObj[k];
}
else {
par.flashvars = k + "=" + flashvarsObj[k];
}
}
}
if (hasPlayerVersion(swfVersionStr)) { // create SWF
var obj = createSWF(att, par, replaceElemIdStr);
if (att.id == replaceElemIdStr) {
setVisibility(replaceElemIdStr, true);
}
callbackObj.success = true;
callbackObj.ref = obj;
}
else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install
att.data = xiSwfUrlStr;
showExpressInstall(att, par, replaceElemIdStr, callbackFn);
return;
}
else { // show alternative content
setVisibility(replaceElemIdStr, true);
}
if (callbackFn) { callbackFn(callbackObj); }
});
}
else if (callbackFn) { callbackFn(callbackObj); }
},
switchOffAutoHideShow: function() {
autoHideShow = false;
},
ua: ua,
getFlashPlayerVersion: function() {
return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
},
hasFlashPlayerVersion: hasPlayerVersion,
createSWF: function(attObj, parObj, replaceElemIdStr) {
if (ua.w3) {
return createSWF(attObj, parObj, replaceElemIdStr);
}
else {
return undefined;
}
},
showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) {
if (ua.w3 && canExpressInstall()) {
showExpressInstall(att, par, replaceElemIdStr, callbackFn);
}
},
removeSWF: function(objElemIdStr) {
if (ua.w3) {
removeSWF(objElemIdStr);
}
},
createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) {
if (ua.w3) {
createCSS(selStr, declStr, mediaStr, newStyleBoolean);
}
},
addDomLoadEvent: addDomLoadEvent,
addLoadEvent: addLoadEvent,
getQueryParamValue: function(param) {
var q = doc.location.search || doc.location.hash;
if (q) {
if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark
if (param == null) {
return urlEncodeIfNecessary(q);
}
var pairs = q.split("&");
for (var i = 0; i < pairs.length; i++) {
if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
}
}
}
return "";
},
// For internal usage only
expressInstallCallback: function() {
if (isExpressInstallActive) {
var obj = getElementById(EXPRESS_INSTALL_ID);
if (obj && storedAltContent) {
obj.parentNode.replaceChild(storedAltContent, obj);
if (storedAltContentId) {
setVisibility(storedAltContentId, true);
if (ua.ie && ua.win) { storedAltContent.style.display = "block"; }
}
if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); }
}
isExpressInstallActive = false;
}
}
};
}();
| JavaScript |
var userAgent = navigator.userAgent.toLowerCase();
jQuery.browser = {
version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
safari: /webkit/.test( userAgent ),
opera: /opera/.test( userAgent ),
msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};
function thumb_images(uploadid,returnid) {
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
if(in_content=='') return false;
if(!IsImg(in_content)) {
alert('选择的类型必须为图片类型');
return false;
}
if($('#'+returnid+'_preview').attr('src')) {
$('#'+returnid+'_preview').attr('src',in_content);
}
$('#'+returnid).val(in_content);
}
function change_images(uploadid,returnid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
var in_filename = d.$("#att-name").html().substring(1);
var str = $('#'+returnid).html();
var contents = in_content.split('|');
var filenames = in_filename.split('|');
$('#'+returnid+'_tips').css('display','none');
if(contents=='') return true;
$.each( contents, function(i, n) {
var ids = parseInt(Math.random() * 10000 + 10*i);
var filename = filenames[i].substr(0,filenames[i].indexOf('.'));
str += "<li id='image"+ids+"'><input type='text' name='"+returnid+"_url[]' value='"+n+"' style='width:310px;' ondblclick='image_priview(this.value);' class='input-text'> <input type='text' name='"+returnid+"_alt[]' value='"+filename+"' style='width:160px;' class='input-text' onfocus=\"if(this.value == this.defaultValue) this.value = ''\" onblur=\"if(this.value.replace(' ','') == '') this.value = this.defaultValue;\"> <a href=\"javascript:remove_div('image"+ids+"')\">移除</a> </li>";
});
$('#'+returnid).html(str);
}
function change_videoes(uploadid, returnid) {
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#video-paths").html().substring(1);
var in_filename = d.$("#video-name").html().substring(1);
var in_vid = d.$("#video-ids").html().substring(1);
var video_num = parseInt($("#key").val());
var str = $('#'+returnid).html();
var contents = in_content.split('|');
var fields = uploadid.split('_');
var field = fields[0];
var filenames = in_filename.split('|');
var vids = in_vid.split('|');
$('#'+returnid+'_tips').css('display','none');
if(contents=='') return true;
$.each( contents, function(i, n) {
if ($("#thumb").val()==''){
$('#thumb').val(contents[i]);
$('#thumb_preview').attr('src', contents[i]);
}
var ids = parseInt(Math.random() * 10000 + 10*i);
video_num = video_num + 1;
var filename = filenames[i];
str += "<li id=\"video_"+field+"_"+video_num+"\"><div class=\"r1\"><img src=\""+contents[i]+"\" width=\"132\" height=\"75\"><input type=\"text\" name=\""+field+"_video["+video_num+"][title]\" value=\""+filename+"\" class=\"input-text\"><input type='hidden' name='"+field+"_video["+video_num+"][videoid]' value='"+vids[i]+"'><div class=\"r2\"><span class=\"l\"><label>排序</label><input type='text' name='"+field+"_video["+video_num+"][listorder]' value='"+video_num+"' class=\"input-text\"></span><span class=\"r\"> <a href=\"javascript:remove_div('video_"+field+"_"+video_num+"')\">移除</a></span></li>";
});
$('#key').val(video_num);
$('#'+returnid).html(str);
}
function change_multifile(uploadid,returnid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
var in_filename = d.$("#att-name").html().substring(1);
var str = '';
var contents = in_content.split('|');
var filenames = in_filename.split('|');
$('#'+returnid+'_tips').css('display','none');
if(contents=='') return true;
$.each( contents, function(i, n) {
var ids = parseInt(Math.random() * 10000 + 10*i);
var filename = filenames[i].substr(0,filenames[i].indexOf('.'));
str += "<li id='multifile"+ids+"'><input type='text' name='"+returnid+"_fileurl[]' value='"+n+"' style='width:310px;' class='input-text'> <input type='text' name='"+returnid+"_filename[]' value='"+filename+"' style='width:160px;' class='input-text' onfocus=\"if(this.value == this.defaultValue) this.value = ''\" onblur=\"if(this.value.replace(' ','') == '') this.value = this.defaultValue;\"> <a href=\"javascript:remove_div('multifile"+ids+"')\">移除</a> </li>";
});
$('#'+returnid).append(str);
}
function add_multifile(returnid) {
var ids = parseInt(Math.random() * 10000);
var str = "<li id='multifile"+ids+"'><input type='text' name='"+returnid+"_fileurl[]' value='' style='width:310px;' class='input-text'> <input type='text' name='"+returnid+"_filename[]' value='附件说明' style='width:160px;' class='input-text'> <a href=\"javascript:remove_div('multifile"+ids+"')\">移除</a> </li>";
$('#'+returnid).append(str);
}
function set_title_color(color) {
$('#title').css('color',color);
$('#style_color').val(color);
}
//-----------------------
function check_content(obj) {
if($.browser.msie) {
CKEDITOR.instances[obj].insertHtml('');
CKEDITOR.instances[obj].focusManager.hasFocus;
}
top.art.dialog({id:'check_content_id'}).close();
return true;
}
function image_priview(img) {
window.top.art.dialog({title:'图片查看',fixed:true, content:'<img src="'+img+'" />',id:'image_priview',time:5});
}
function remove_div(id) {
$('#'+id).remove();
}
function input_font_bold() {
if($('#title').css('font-weight') == '700' || $('#title').css('font-weight')=='bold') {
$('#title').css('font-weight','normal');
$('#style_font_weight').val('');
} else {
$('#title').css('font-weight','bold');
$('#style_font_weight').val('bold');
}
}
function ruselinkurl() {
if($('#islink').attr('checked')=='checked') {
$('#linkurl').attr('disabled',false);
var oEditor = CKEDITOR.instances.content;
oEditor.insertHtml(' ');
return false;
} else {
$('#linkurl').attr('disabled','true');
}
}
function close_window() {
if($('#title').val() !='') {
art.dialog({content:'内容已经录入,确定离开将不保存数据!', fixed:true,yesText:'我要关闭',noText:'返回保存数据',style:'confirm', id:'bnt4_test'}, function(){
window.close();
}, function(){
});
} else {
window.close();
}
return false;
}
function ChangeInput (objSelect,objInput) {
if (!objInput) return;
var str = objInput.value;
var arr = str.split(",");
for (var i=0; i<arr.length; i++){
if(objSelect.value==arr[i])return;
}
if(objInput.value=='' || objInput.value==0 || objSelect.value==0){
objInput.value=objSelect.value
}else{
objInput.value+=','+objSelect.value
}
}
//移除相关文章
function remove_relation(sid,id) {
var relation_ids = $('#relation').val();
if(relation_ids !='' ) {
$('#'+sid).remove();
var r_arr = relation_ids.split('|');
var newrelation_ids = '';
$.each(r_arr, function(i, n){
if(n!=id) {
if(i==0) {
newrelation_ids = n;
} else {
newrelation_ids = newrelation_ids+'|'+n;
}
}
});
$('#relation').val(newrelation_ids);
}
}
//显示相关文章
function show_relation(modelid,id) {
$.getJSON("?m=content&c=content&a=public_getjson_ids&modelid="+modelid+"&id="+id, function(json){
var newrelation_ids = '';
if(json==null) {
alert('没有添加相关文章');
return false;
}
$.each(json, function(i, n){
newrelation_ids += "<li id='"+n.sid+"'>·<span>"+n.title+"</span><a href='javascript:;' class='close' onclick=\"remove_relation('"+n.sid+"',"+n.id+")\"></a></li>";
});
$('#relation_text').html(newrelation_ids);
});
}
//移除ID
function remove_id(id) {
$('#'+id).remove();
}
function strlen_verify(obj, checklen, maxlen) {
var v = obj.value, charlen = 0, maxlen = !maxlen ? 200 : maxlen, curlen = maxlen, len = strlen(v);
for(var i = 0; i < v.length; i++) {
if(v.charCodeAt(i) < 0 || v.charCodeAt(i) > 255) {
curlen -= charset == 'utf-8' ? 2 : 1;
}
}
if(curlen >= len) {
$('#'+checklen).html(curlen - len);
} else {
obj.value = mb_cutstr(v, maxlen, true);
}
}
function mb_cutstr(str, maxlen, dot) {
var len = 0;
var ret = '';
var dot = !dot ? '...' : '';
maxlen = maxlen - dot.length;
for(var i = 0; i < str.length; i++) {
len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
if(len > maxlen) {
ret += dot;
break;
}
ret += str.substr(i, 1);
}
return ret;
}
function strlen(str) {
return ($.browser.msie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
} | JavaScript |
$(document).ready(function() {
var q = $("#q").val();
var typeid = $("#typeid").val();
search_history = getcookie('search_history');
if(search_history!=null && search_history!='') {
search_s = search_history.split(",");
var exists = in_array(q+'|'+typeid, search_s);
//不存在
if(exists==-1) {
if(search_s.length > 5) {
search_history = search_history.replace(search_s[0]+',', "");
}
search_history += ','+q+'|'+typeid;
}
//搜索历史
var history_html = '';
for(i=0;i<search_s.length;i++) {
var j = search_s.length - i - 1;
search_s_arr = search_s[j].split("|");
var keyword = search_s_arr[0];
var keywordtypeid = search_s_arr[1];
history_html += '<li><a href="?m=search&c=index&a=init&typeid='+keywordtypeid+'&q='+keyword+'">'+keyword+'</a></li>';
}
$('#history_ul').html(history_html);
} else {
search_history = q+'|'+typeid;
}
setcookie('search_history', search_history, '1000');
function in_array(v, a) {
var i;
for(i = 0; i < a.length; i++) {
if(v === a[i]) {
return i;
}
}
return -1;
}
}); | JavaScript |
/*
* Async Treeview 0.1 - Lazy-loading extension for Treeview
*
* http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
*
* Copyright (c) 2007 J枚rn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id$
*
*/
;(function($) {
function load(settings, root, child, container) {
function createNode(parent) {
var current = $("<li/>").attr("id", this.id || "").attr("class", this.liclass || "").html("<span>" + this.text + "</span>").appendTo(parent);
if (this.classes) {
current.children("span").addClass(this.classes);
}
if (this.expanded) {
current.addClass("open");
}
if (this.hasChildren || this.children && this.children.length) {
var branch = $("<ul/>").appendTo(current);
if (this.hasChildren) {
current.addClass("hasChildren");
createNode.call({
classes: "placeholder",
text: " ",
children:[]
}, branch);
}
if (this.children && this.children.length) {
$.each(this.children, createNode, [branch])
}
}
}
$.ajax($.extend(true, {
url: settings.url,
dataType: "json",
data: {
root: root
},
success: function(response) {
child.empty();
$.each(response, createNode, [child]);
$(container).treeview({add: child});
}
}, settings.ajax));
/*
$.getJSON(settings.url, {root: root}, function(response) {
function createNode(parent) {
var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent);
if (this.classes) {
current.children("span").addClass(this.classes);
}
if (this.expanded) {
current.addClass("open");
}
if (this.hasChildren || this.children && this.children.length) {
var branch = $("<ul/>").appendTo(current);
if (this.hasChildren) {
current.addClass("hasChildren");
createNode.call({
classes: "placeholder",
text: " ",
children:[]
}, branch);
}
if (this.children && this.children.length) {
$.each(this.children, createNode, [branch])
}
}
}
child.empty();
$.each(response, createNode, [child]);
$(container).treeview({add: child});
});
*/
}
var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
if (!settings.url) {
return proxied.apply(this, arguments);
}
var container = this;
if (!container.children().size())
load(settings, "source", this, container);
var userToggle = settings.toggle;
return proxied.call(this, $.extend({}, settings, {
collapsed: true,
toggle: function() {
var $this = $(this);
if ($this.hasClass("hasChildren")) {
var childList = $this.removeClass("hasChildren").find("ul");
load(settings, this.id, childList, container);
}
if (userToggle) {
userToggle.apply(this, arguments);
}
}
}));
};
})(jQuery); | JavaScript |
function confirmurl(url,message) {
url = url+'&pc_hash='+pc_hash;
if(confirm(message)) redirect(url);
}
function redirect(url) {
location.href = url;
}
//滚动条
$(function(){
$(":text").addClass('input-text');
})
/**
* 全选checkbox,注意:标识checkbox id固定为为check_box
* @param string name 列表check名称,如 uid[]
*/
function selectall(name) {
if ($("#check_box").attr("checked")=='checked') {
$("input[name='"+name+"']").each(function() {
$(this).attr("checked","checked");
});
} else {
$("input[name='"+name+"']").each(function() {
$(this).removeAttr("checked");
});
}
}
function openwinx(url,name,w,h) {
if(!w) w=screen.width-4;
if(!h) h=screen.height-95;
url = url+'&pc_hash='+pc_hash;
window.open(url,name,"top=100,left=400,width=" + w + ",height=" + h + ",toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
}
//弹出对话框
function omnipotent(id,linkurl,title,close_type,w,h) {
if(!w) w=700;
if(!h) h=500;
art.dialog({id:id,iframe:linkurl, title:title, width:w, height:h, lock:true},
function(){
if(close_type==1) {
art.dialog({id:id}).close()
} else {
var d = art.dialog({id:id}).data.iframe;
var form = d.document.getElementById('dosubmit');form.click();
}
return false;
},
function(){
art.dialog({id:id}).close()
});void(0);
} | JavaScript |
/**
* $.ld
* @extends jquery.1.4.2
* @fileOverview 创建一组联动选择框
* @author 明河共影
* @email mohaiguyan12@126.com
* @site wwww.36ria.com
* @version 0.2
* @date 2010-08-18
* Copyright (c) 2010-2010 明河共影
* @example
* $(".ld-select").ld();
*/
(function($){
$.fn.ld = function(options){
var opts;
var DATA_NAME = "ld";
//返回API
if(typeof options == 'string'){
if(options == 'api'){
return $(this).data(DATA_NAME);
}
}
else{
var options = options || {};
//覆盖参数
opts = $.extend(true, {}, $.fn.ld.defaults, options);
}
if($(this).size() > 0){
var ld = new yijs.Ld(opts);
ld.$applyTo = $(this);
ld.render();
$(this).data(DATA_NAME,ld);
}
return $(this);
}
var yijs = yijs || {};
yijs.Ld = function(options){
//参数
this.options = options;
//起作用的对象
this.$applyTo = this.options.applyTo && $(this.options.applyTo) || null;
//缓存前缀
this.cachePrefix = "data_";
//写入到选择框的option的样式名
this.OPTIONS_CLASS = "ld-option";
//缓存,为一个对象字面量。
this.cache = {};
}
yijs.Ld.prototype = {
/**
* 运行
* @return {Object} this
*/
render: function(){
var _that = this;
var _opts = this.options;
if (this.$applyTo != null && this.size() > 0) {
_opts.style != null && this.css(_opts.style);
//加载默认数据,向第一个选择框填充数据
this.load(_opts.defaultLoadSelectIndex,_opts.defaultParentId);
_opts.texts.length > 0 && this.selected(_opts.texts);
//给每个选择框绑定change事件
this.$applyTo.each(function(i){
i < _that.size()-1 && $(this).bind("change.ld",{target:_that,index:i},_that.onchange);
})
}
return this;
},
texts : function(ts){
var that = this;
var $select = this.$applyTo;
var _arr = [];
var txt = null;
var $options;
$select.each(function(){
txt = $(this).children('.'+that.OPTIONS_CLASS+':selected').text();
_arr.push(txt);
})
return _arr;
},
/**
* 获取联动选择框的数量
* @return {Number} 选择框的数量
*/
size : function(){
return this.$applyTo.size();
},
/**
* 设置选择框的样式
* @param {Object} style 样式
* @return {Object} this
*/
css : function(style){
style && this.$applyTo.css(style);
return this;
},
/**
* 读取数据,并写入到选择框
* @param {Number} selectIndex 选择框数组的索引值
* @param {String} parent_id 父级id
*/
load : function(selectIndex,parent_id,callback){
var _that = this;
//清理index以下的选择框的选项
for(var i = selectIndex ; i< _that.size();i++){
_that.removeOptions(i);
}
//存在缓存数据,直接使用缓存数据生成选择框的子项;不存在,则请求数据
if(_that.cache[parent_id]){
_that._create(_that.cache[parent_id],selectIndex);
_that.$applyTo.eq(selectIndex).trigger("afterLoad");
if(callback) callback.call(this);
}else{
var _ajaxOptions = this.options.ajaxOptions;
var _d = _ajaxOptions.data;
var _parentIdField = this.options.field['parent_id'];
_d[_parentIdField] = parent_id;
//传递给后台的参数
_ajaxOptions.data = _d;
//ajax获取数据成功后的回调函数
_ajaxOptions.success = function(data){
//遍历数据,获取html字符串
var _h = _that._getOptionsHtml(data);
_that._create(_h,selectIndex);
_that.cache[parent_id] = _h;
_that.$applyTo.eq(selectIndex).trigger("afterLoad.ld");
if(callback) callback.call(this);
}
$.ajax(_ajaxOptions);
}
},
/**
* 删除指定index索引值的选择框下的选择项
* @param {Number} index 选择框的索引值
* @return {Object} this
*/
removeOptions : function(index){
this.$applyTo.eq(index).children("."+this.OPTIONS_CLASS).remove();
return this;
},
selected : function(t,completeCallBack){
var _that = this;
if(t && typeof t == "object" && t.length > 0){
var $select = this.$applyTo;
_load(_that.options.defaultLoadSelectIndex,_that.options.defaultParentId);
}
/**
* 递归获取选择框数据
* @param {Number} selectIndex 选择框的索引值
* @param {Number} parent_id id
*/
function _load(selectIndex,parent_id){
_that.load(selectIndex,parent_id,function(){
var id = _selected(selectIndex,t[selectIndex]);
selectIndex ++;
if(selectIndex > _that.size()-1) {
if(completeCallBack) completeCallBack.call(this);
return;
}
_load(selectIndex,id);
});
}
/**
* 选中包含指定文本的选择项
* @param {Number} index 选择框的索引值
* @param {String} text 文本
* @return {Number} 该选择框的value值
*/
function _selected(index,text){
var id = 0;
_that.$applyTo.eq(index).children().each(function(){
var reg = new RegExp(text);
if(reg.test($(this).text())){
$(this).attr("selected",true);
id = $(this).val();
return;
}
})
return id;
}
return this;
},
/**
* 选择框的值改变后触发的事件
* @param {Object} e 事件
*/
onchange : function(e){
//实例化后的对象引用
var _that = e.data.target;
//选择框的索引值
var index = e.data.index;
//目标选择框
var $target = $(e.target);
var _parentId = $target.val();
var _i = index+1;
_that.load(_i,_parentId);
},
/**
* 将数据源(json或xml)转成html
* @param {Object} data
* @return {String} html代码字符串
*/
_getOptionsHtml : function(data){
var _that = this;
var ajaxOptions = this.options.ajaxOptions;
var dataType = ajaxOptions.dataType;
var field = this.options.field;
var _h = "";
_h = _getOptions(data,dataType,field).join("");;
/**
* 获取选择框项html代码数组
* @param {Object | Array} data 数据
* @param {String} dataType 数据类型
* @param {Object} field 字段
* @return {Array} aStr
*/
function _getOptions(data,dataType,field){
var optionClass = _that.OPTIONS_CLASS;
var aStr = [];
var id,name;
if (dataType == "json") {
$.each(data,function(i){
id = data[i][field.region_id];
name = data[i][field.region_name];
var _option = "<option value='"+id+"' class='"+optionClass+"'>"+name+"</option>";
aStr.push(_option);
})
}else if(dataType == "xml"){
$(data).children().children().each(function(){
id = $(this).find(field.region_id).text();
name = $(this).find(field.region_name).text();
var _option = "<option value='"+id+"' class='"+optionClass+"'>"+name+"</option>";
aStr.push(_option);
})
}
return aStr;
}
return _h;
},
/**
* 向选择框添加html
* @param {String} _h html代码
* @param {Number} index 选择框的索引值
*/
_create : function(_h,index){
var _that = this;
this.removeOptions(index);
this.$applyTo.eq(index).append(_h);
}
}
$.fn.ld.defaults = {
/**选择框对象数组*/
selects : null,
/**ajax配置*/
ajaxOptions : {
url : null,
type : 'get',
data : {},
dataType : 'json',
success : function(){},
beforeSend : function(){}
},
/**默认父级id*/
defaultParentId : 0,
/**默认读取数据的选择框*/
defaultLoadSelectIndex : 0,
/**默认选择框中的选中项*/
texts : [],
/**选择框的样式*/
style : null,
/**选择框值改变时的回调函数*/
change : function(){},
field : {
region_id : "region_id",
region_name : "region_name",
parent_id : "parent_id"
}
}
})(jQuery); | JavaScript |
function open_menu(id,name,container,file,path,title,key, func) {
returnid= id;
returnfile = file;
returnname = name;
returnfunc = func;
var content = '<div class="linkage-menu"><h6><a href="javascript:;" onclick="get_menu_parent(this,0,\''+path+'\', \''+title+'\', \''+key+'\')" class="rt"><<返回主菜单</a><span>'+name+'</span> <a href="javascript:;" onclick="get_menu_parent(this,\'\',\''+path+'\', \''+title+'\', \''+key+'\')" id="parent_'+id+'" parentid="0"><img src="statics/images/icon/old-edit-redo.png" width="16" height="16" alt="返回上一级" /></a></h6><div class="ib-a menu" id="ul_'+id+'">';
for (i=0; i < container.length; i++)
{
content += '<a href="javascript:;" onclick="get_menu_child(\''+container[i][0]+'\',\''+container[i][1]+'\',\''+container[i][2]+'\',\''+path+'\',\''+title+'\',\''+key+'\')">'+container[i][1]+'</a>';
}
content += '</div></div>';
art.dialog({title:name,id:'edit_'+id,content:content,width:'422',height:'200',style:'none_icon ui_content_m'});
}
var level = 0;
function get_menu_child(nodeid,nodename,parentid,path,title,key) {
var content = container = '';
var url = "api.php?op=get_menu&act=ajax_getlist&parentid="+nodeid+"&cachefile="+returnfile+"&path="+path+'&title='+title+'&key='+key;
$.getJSON(url+'&callback=?',function(data){
if(data) {
level = 1;
$.each(data, function(i,data){
container = data.split(',');
content += '<a href="javascript:;" onclick="get_menu_child(\''+container[0]+'\',\''+container[1]+'\',\''+container[2]+'\',\''+path+'\',\''+title+'\',\''+key+'\')">'+container[1]+'</a>';
})
$("#ul_"+returnid).html(content);
get_menu_path(container[2],returnid,path);
$("#parent_"+returnid).attr('parentid',parentid);
} else {
get_menu_val(nodename,nodeid,path);
$("input[name='info["+returnid+"]']").val(nodeid);
//$("#"+returnid).after('<input type="hidden" name="info['+returnid+']" value="'+nodeid+'">');
art.dialog({id:'edit_'+returnid}).close();
}
})
}
function get_menu_parent(obj,parentid,path,title,key) {
var linkageid = parentid ? parentid : $(obj).attr('parentid');
var content = container = '';
var url = "api.php?op=get_menu&act=ajax_getlist&parentid="+linkageid+"&cachefile="+returnfile+"&path="+path+'&title='+title+'&key='+key;
$.getJSON(url+'&callback=?',function(data){
if(data) {
$.each(data, function(i,data){
container = data.split(',');
content += '<a href="javascript:;" onclick="get_menu_child(\''+container[0]+'\',\''+container[1]+'\',\''+container[2]+'\',\''+path+'\',\''+title+'\',\''+key+'\')">'+container[1]+'</a>';
})
get_menu_path(container[2],returnid,path);
$("#parent_"+returnid).attr('parentid',container[4]);
$("#ul_"+returnid).html(content);
} else {
$("#"+returnid).val(nodename);
art.dialog({id:'edit_'+returnid}).close();
}
})
}
function get_menu_path(nodeid,returnid,path) {
var show_path = '';
var url = "api.php?op=get_menu&act=ajax_getpath&parentid="+nodeid+"&keyid="+returnfile+'&path='+path;
$.getJSON(url+'&callback=?',function(data){
if(data) {
$.each(data, function(i,data){
if (data) {
show_path += data+" > ";
} else {
show_path += returnname;
}
})
$("#parent_"+returnid).siblings('span').html(show_path);
}
})
}
function get_menu_val(nodename,nodeid,cachepath) {
var path = $("#parent_"+returnid).siblings('span').html();
if(level==0) $("#"+returnid).html(nodename);
else $("#"+returnid).html(path+nodename);
var url = "api.php?op=get_menu&act=ajax_gettopparent&id="+nodeid+"&keyid="+returnfile+'&path='+cachepath;
$.getJSON(url+'&callback=?',function(data){
if(data) {
}
if (returnfunc) {
obj=new Object();
obj.value = data;
get_additional(obj);
}
})
level = 0;
} | JavaScript |
(function($){
$.fn.mlnColsel=function(data,setting){
var dataObj={"Items":[
{"name":"mlnColsel","topid":"-1","colid":"-1","value":"-1","fun":function(){alert("undefined!");}}
]};
var settingObj={
title:"请选择",
value:"-1",
width:100
};
settingObj=$.extend(settingObj,setting);
dataObj=$.extend(dataObj,data);
var $this=$(this);
var $colselbox=$(document.createElement("a")).addClass("colselect").attr({"href":"javascript:;"});
var $colseltext=$(document.createElement("span")).text(settingObj.title);
var $coldrop=$(document.createElement("ul")).addClass("dropmenu");
var selectInput = $.browser.msie?document.createElement("<input name="+$this.attr("id")+" />"):document.createElement("input");
selectInput.type="hidden";
selectInput.value=settingObj.value;
selectInput.setAttribute("name",'info['+$this.attr("id")+']');
var ids=$this.attr("id");
$this.onselectstart=function(){return false;};
$this.onselect=function(){document.selection.empty()};
$colselbox.append($colseltext);
$this.addClass("colsel").append($colselbox).append($coldrop).append(selectInput);
$(dataObj.Items).each(function(i,n){
var $item=$(document.createElement("li"));
if(n.topid==0){
$coldrop.append($item);
$item.html("<span>"+n.name+"</span>").attr({"values":n.value,"id":"col_"+ids+"_"+n.colid});
}else{
if($("#col_"+ids+"_"+n.topid).find("ul").length<=0){
$("#col_"+ids+"_"+n.topid).append("<ul class=\"dropmenu rootmenu\"></ul>");
$("#col_"+ids+"_"+n.topid).find("ul:first").append($item);
$item.html("<span>"+n.name+"</span>").attr({"values":n.value,"id":"col_"+ids+"_"+n.colid});
}else{
$("#col_"+ids+"_"+n.topid).find("ul:first").append($item);
$item.html("<span>"+n.name+"</span>").attr({"values":n.value,"id":"col_"+ids+"_"+n.colid});
}
}
});
$this.find("li").each(function(){
$(this).click(function(event){
$colselbox.children("span").text($(this).find("span:first").text());
$(selectInput).val($(this).attr("values"));
hideMenu();
event.stopPropagation();
});
if($(this).find("ul").length>0){
$(this).addClass("menuout");
$(this).hover(function(){
$(this).removeClass("menuout");
$(this).addClass("menuhover");
$(this).find("ul:first").fadeIn("fast")
},function(){
$(this).removeClass("menuhover");
$(this).addClass("menuout");
$(this).find("ul").each(function(){
$(this).fadeOut("fast");
});
});
}else{
$(this).addClass("norout");
$(this).hover(function(){
$(this).removeClass("norout");
$(this).addClass("norhover");
},function(){
$(this).removeClass("norhover");
$(this).addClass("norout");
});
}
});
function hideMenu(){
$this.bOpen=0;
$(".rootmenu").hide();
$coldrop.slideUp("fast");
$(document).unbind("click",hideMenu);
}
function openMenu(){
$coldrop.slideDown("fast");
$this.bOpen=1;
}
$colselbox.click(function(event){
$(this).blur();
if($this.bOpen){
hideMenu();
}else{
openMenu();
$(document).bind("click",hideMenu);
}
event.stopPropagation();
});
$(".rootmenu").each(function(){
$(this).css({"left":135+"px"});
});
}
})(jQuery); | JavaScript |
function open_linkage(id,name,container,linkageid) {
returnid= id;
returnkeyid = linkageid;
var content = '<div class="linkage-menu"><h6><a href="javascript:;" onclick="get_parent(this,0)" class="rt"><<返回主菜单</a><span>'+name+'</span> <a href="javascript:;" onclick="get_parent(this)" id="parent_'+id+'" parentid="0"><img src="statics/images/icon/old-edit-redo.png" width="16" height="16" alt="返回上一级" /></a></h6><div class="ib-a menu" id="ul_'+id+'">';
for (i=0; i < container.length; i++)
{
content += '<a href="javascript:;" onclick="get_child(\''+container[i][0]+'\',\''+container[i][1]+'\',\''+container[i][2]+'\')">'+container[i][1]+'</a>';
}
content += '</div></div>';
art.dialog({title:name,id:'edit_'+id,content:content,width:'422',height:'200',style:'none_icon ui_content_m'});
}
var level = 0;
function get_child(nodeid,nodename,parentid) {
var content = container = '';
var url = "api.php?op=get_linkage&act=ajax_getlist&parentid="+nodeid+"&keyid="+returnkeyid;
$.getJSON(url+'&callback=?',function(data){
if(data) {
level = 1;
$.each(data, function(i,data){
container = data.split(',');
content += '<a href="javascript:;" onclick="get_child(\''+container[0]+'\',\''+container[1]+'\',\''+container[2]+'\')">'+container[1]+'</a>';
})
$("#ul_"+returnid).html(content);
get_path(container[2],returnid);
$("#parent_"+returnid).attr('parentid',container[2]);
} else {
set_val(nodename,nodeid);
$("input[name='info["+returnid+"]']").val(nodeid);
//$("#"+returnid).after('<input type="hidden" name="info['+returnid+']" value="'+nodeid+'">');
art.dialog({id:'edit_'+returnid}).close();
}
})
}
function get_parent(obj,parentid) {
var linkageid = parentid ? parentid : $(obj).attr('parentid');
var content = container = '';
var url = "api.php?op=get_linkage&act=ajax_getlist&linkageid="+linkageid+"&keyid="+returnkeyid;
$.getJSON(url+'&callback=?',function(data){
if(data) {
$.each(data, function(i,data){
container = data.split(',');
content += '<a href="javascript:;" onclick="get_child(\''+container[0]+'\',\''+container[1]+'\',\''+container[2]+'\')">'+container[1]+'</a>';
})
get_path(container[2],returnid);
$("#parent_"+returnid).attr('parentid',container[2]);
$("#ul_"+returnid).html(content);
} else {
$("#"+returnid).val(nodename);
art.dialog({id:'edit_'+returnid}).close();
}
})
}
function get_path(nodeid,returnid) {
var show_path = '';
var url = "api.php?op=get_linkage&act=ajax_getpath&parentid="+nodeid+"&keyid="+returnkeyid;
$.getJSON(url+'&callback=?',function(data){
if(data) {
$.each(data, function(i,data){
show_path += data+" > ";
})
$("#parent_"+returnid).siblings('span').html(show_path);
}
})
}
function set_val(nodename,nodeid) {
var path = $("#parent_"+returnid).siblings('span').html();
if(level==0) $("#"+returnid).html(nodename);
else $("#"+returnid).html(path+nodename);
var url = "api.php?op=get_linkage&act=ajax_gettopparent&linkageid="+nodeid+"&keyid="+returnkeyid;
$.getJSON(url+'&callback=?',function(data){
if(data) {
$("#city").val(data);
}
})
level = 0;
} | JavaScript |
Calendar.LANG("cn", "中文", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "今天",
today: "今天", // appears in bottom bar
wk: "周",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "AM",
PM: "PM",
mn : [ "一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月"],
smn : [ "一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月"],
dn : [ "日",
"一",
"二",
"三",
"四",
"五",
"六",
"日" ],
sdn : [ "日",
"一",
"二",
"三",
"四",
"五",
"六",
"日" ]
});
| JavaScript |
(function(a){
a.fn.webwidget_rating_sex=function(p){
var p=p||{};
var b=p&&p.rating_star_length?p.rating_star_length:"5";
var n=p&&p.rating_star_each?p.rating_star_each:"1";
var c=p&&p.rating_function_click?p.rating_function_click:"";
var h=p&&p.rating_function_hover?p.rating_function_hover:"";
var e=p&&p.rating_initial_value?p.rating_initial_value:"0";
var d=p&&p.directory?p.directory:"images";
var f=e;
var g=a(this);
b=parseInt(b);
init();
g.next("ul").children("li").hover(function(){
$(this).parent().children("li").css('background-position','0px 0px');
var a=$(this).parent().children("li").index($(this));
$(this).parent().children("li").slice(0,a+1).css('background-position','0px -28px')
},function(){});
g.next("ul").children("li").click(function(){
var a=$(this).parent().children("li").index($(this));
f=a+1;
g.val(f);
if(c!=""){
eval(c+"("+g.val()+","+n+")");
}
});
g.next("ul").children("li").bind("mouseenter",function(){
var thisul = $(this).parent();
var as=thisul.children("li").index($(this));
if(h!=""){
eval(h+"("+as+","+n+")");
}
}).bind("mouseleave",function(){
var tipid = $("#tip_"+n).attr("c");
if(Boolean(parseInt(tipid))!=true){
$("#tip_"+n).text('');
}else{
eval(c+"("+tipid+","+n+")");
}
});
g.next("ul").hover(function(){},function(){
if(f==""){
$(this).children("li").slice(0,f).css('background-position','0px 0px');
}else{
$(this).children("li").css('background-position','0px 0px');
$(this).children("li").slice(0,f).css('background-position','0px -28px');
}
});
function init(){
var a=$("<ul>");
a.addClass("webwidget_rating_sex");
for(var i=1;i<=b;i++){
a.append('<li style="background-image:url('+d+'/web_widget_star.gif)"><span>'+i+'</span></li>')
}
a.insertAfter(g);
if(e!=""){
f=e;
g.val(e);
g.next("ul").children("li").slice(0,f).css('background-position','0px -28px')
}
}
}
})(jQuery); | JavaScript |
/**
* Copyright (c) 2010 Anders Ekdahl (http://coffeescripter.com/)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version: 1.2.4
*
* Demo and documentation: http://coffeescripter.com/code/ad-gallery/
*/
(function($) {
$.fn.adGallery = function(options) {
var defaults = { loader_image: 'statics/images/yp/loader.gif',
start_at_index: 0,
description_wrapper: false,
thumb_opacity: 0.7,
animate_first_image: false,
animation_speed: 400,
width: false,
height: false,
display_next_and_prev: true,
display_back_and_forward: true,
scroll_jump: 0, // If 0, it jumps the width of the container
slideshow: {
enable: false,
autostart: false,
speed: 5000,
start_label: 'Start',
stop_label: 'Stop',
stop_on_scroll: true,
countdown_prefix: '(',
countdown_sufix: ')',
onStart: false,
onStop: false
},
effect: 'slide-hori', // or 'slide-vert', 'fade', or 'resize', 'none'
enable_keyboard_move: true,
cycle: true,
callbacks: {
init: false,
afterImageVisible: false,
beforeImageVisible: false
}
};
var settings = $.extend(false, defaults, options);
if(options && options.slideshow) {
settings.slideshow = $.extend(false, defaults.slideshow, options.slideshow);
};
if(!settings.slideshow.enable) {
settings.slideshow.autostart = false;
};
var galleries = [];
$(this).each(function() {
var gallery = new AdGallery(this, settings);
galleries[galleries.length] = gallery;
});
// Sorry, breaking the jQuery chain because the gallery instances
// are returned so you can fiddle with them
return galleries;
};
function VerticalSlideAnimation(img_container, direction, desc) {
var current_top = parseInt(img_container.css('top'), 10);
if(direction == 'left') {
var old_image_top = '-'+ this.image_wrapper_height +'px';
img_container.css('top', this.image_wrapper_height +'px');
} else {
var old_image_top = this.image_wrapper_height +'px';
img_container.css('top', '-'+ this.image_wrapper_height +'px');
};
if(desc) {
desc.css('bottom', '-'+ desc[0].offsetHeight +'px');
desc.animate({bottom: 0}, this.settings.animation_speed * 2);
};
if(this.current_description) {
this.current_description.animate({bottom: '-'+ this.current_description[0].offsetHeight +'px'}, this.settings.animation_speed * 2);
};
return {old_image: {top: old_image_top},
new_image: {top: current_top}};
};
function HorizontalSlideAnimation(img_container, direction, desc) {
var current_left = parseInt(img_container.css('left'), 10);
if(direction == 'left') {
var old_image_left = '-'+ this.image_wrapper_width +'px';
img_container.css('left',this.image_wrapper_width +'px');
} else {
var old_image_left = this.image_wrapper_width +'px';
img_container.css('left','-'+ this.image_wrapper_width +'px');
};
if(desc) {
desc.css('bottom', '-'+ desc[0].offsetHeight +'px');
desc.animate({bottom: 0}, this.settings.animation_speed * 2);
};
if(this.current_description) {
this.current_description.animate({bottom: '-'+ this.current_description[0].offsetHeight +'px'}, this.settings.animation_speed * 2);
};
return {old_image: {left: old_image_left},
new_image: {left: current_left}};
};
function ResizeAnimation(img_container, direction, desc) {
var image_width = img_container.width();
var image_height = img_container.height();
var current_left = parseInt(img_container.css('left'), 10);
var current_top = parseInt(img_container.css('top'), 10);
img_container.css({width: 0, height: 0, top: this.image_wrapper_height / 2, left: this.image_wrapper_width / 2});
return {old_image: {width: 0,
height: 0,
top: this.image_wrapper_height / 2,
left: this.image_wrapper_width / 2},
new_image: {width: image_width,
height: image_height,
top: current_top,
left: current_left}};
};
function FadeAnimation(img_container, direction, desc) {
img_container.css('opacity', 0);
return {old_image: {opacity: 0},
new_image: {opacity: 1}};
};
// Sort of a hack, will clean this up... eventually
function NoneAnimation(img_container, direction, desc) {
img_container.css('opacity', 0);
return {old_image: {opacity: 0},
new_image: {opacity: 1},
speed: 0};
};
function AdGallery(wrapper, settings) {
this.init(wrapper, settings);
};
AdGallery.prototype = {
// Elements
wrapper: false,
image_wrapper: false,
gallery_info: false,
nav: false,
loader: false,
preloads: false,
thumbs_wrapper: false,
scroll_back: false,
scroll_forward: false,
next_link: false,
prev_link: false,
slideshow: false,
image_wrapper_width: 0,
image_wrapper_height: 0,
current_index: 0,
current_image: false,
current_description: false,
nav_display_width: 0,
settings: false,
images: false,
in_transition: false,
animations: false,
init: function(wrapper, settings) {
var context = this;
this.wrapper = $(wrapper);
this.settings = settings;
this.setupElements();
this.setupAnimations();
if(this.settings.width) {
this.image_wrapper_width = this.settings.width;
this.image_wrapper.width(this.settings.width);
this.wrapper.width(this.settings.width);
} else {
this.image_wrapper_width = this.image_wrapper.width();
};
if(this.settings.height) {
this.image_wrapper_height = this.settings.height;
this.image_wrapper.height(this.settings.height);
} else {
this.image_wrapper_height = this.image_wrapper.height();
};
this.nav_display_width = this.nav.width();
this.current_index = 0;
this.current_image = false;
this.current_description = false;
this.in_transition = false;
this.findImages();
if(this.settings.display_next_and_prev) {
this.initNextAndPrev();
};
// The slideshow needs a callback to trigger the next image to be shown
// but we don't want to give it access to the whole gallery instance
var nextimage_callback = function(callback) {
return context.nextImage(callback);
};
this.slideshow = new AdGallerySlideshow(nextimage_callback, this.settings.slideshow);
this.controls.append(this.slideshow.create());
if(this.settings.slideshow.enable) {
this.slideshow.enable();
} else {
this.slideshow.disable();
};
if(this.settings.display_back_and_forward) {
this.initBackAndForward();
};
if(this.settings.enable_keyboard_move) {
this.initKeyEvents();
};
var start_at = parseInt(this.settings.start_at_index, 10);
if(window.location.hash && window.location.hash.indexOf('#ad-image') === 0) {
start_at = window.location.hash.replace(/[^0-9]+/g, '');
// Check if it's a number
if((start_at * 1) != start_at) {
start_at = this.settings.start_at_index;
};
};
this.loading(true);
this.showImage(start_at,
function() {
// We don't want to start the slideshow before the image has been
// displayed
if(context.settings.slideshow.autostart) {
context.preloadImage(start_at + 1);
context.slideshow.start();
};
}
);
this.fireCallback(this.settings.callbacks.init);
},
setupAnimations: function() {
this.animations = {
'slide-vert': VerticalSlideAnimation,
'slide-hori': HorizontalSlideAnimation,
'resize': ResizeAnimation,
'fade': FadeAnimation,
'none': NoneAnimation
};
},
setupElements: function() {
this.controls = this.wrapper.find('.ad-controls');
this.gallery_info = $('<p class="ad-info"></p>');
this.controls.append(this.gallery_info);
this.image_wrapper = this.wrapper.find('.ad-image-wrapper');
this.image_wrapper.empty();
this.nav = this.wrapper.find('.ad-nav');
this.thumbs_wrapper = this.nav.find('.ad-thumbs');
this.preloads = $('<div class="ad-preloads"></div>');
this.loader = $('<img class="ad-loader" src="'+ this.settings.loader_image +'">');
this.image_wrapper.append(this.loader);
this.loader.hide();
$(document.body).append(this.preloads);
},
loading: function(bool) {
if(bool) {
this.loader.show();
} else {
this.loader.hide();
};
},
addAnimation: function(name, fn) {
if($.isFunction(fn)) {
this.animations[name] = fn;
};
},
findImages: function() {
var context = this;
this.images = [];
var thumb_wrapper_width = 0;
var thumbs_loaded = 0;
var thumbs = this.thumbs_wrapper.find('a');
var thumb_count = thumbs.length;
if(this.settings.thumb_opacity < 1) {
thumbs.find('img').css('opacity', this.settings.thumb_opacity);
};
thumbs.each(
function(i) {
var link = $(this);
var image_src = link.attr('href');
var thumb = link.find('img');
// Check if the thumb has already loaded
if(!context.isImageLoaded(thumb[0])) {
thumb.load(
function() {
thumb_wrapper_width += this.parentNode.parentNode.offsetWidth;
thumbs_loaded++;
}
);
} else{
thumb_wrapper_width += thumb[0].parentNode.parentNode.offsetWidth;
thumbs_loaded++;
};
link.addClass('ad-thumb'+ i);
link.click(
function() {
context.showImage(i);
context.slideshow.stop();
return false;
}
).hover(
function() {
if(!$(this).is('.ad-active') && context.settings.thumb_opacity < 1) {
$(this).find('img').fadeTo(300, 1);
};
context.preloadImage(i);
},
function() {
if(!$(this).is('.ad-active') && context.settings.thumb_opacity < 1) {
$(this).find('img').fadeTo(300, context.settings.thumb_opacity);
};
}
);
var link = false;
if(thumb.data('ad-link')) {
link = thumb.data('ad-link');
} else if(thumb.attr('longdesc') && thumb.attr('longdesc').length) {
link = thumb.attr('longdesc');
};
var desc = false;
if(thumb.data('ad-desc')) {
desc = thumb.data('ad-desc');
} else if(thumb.attr('alt') && thumb.attr('alt').length) {
desc = thumb.attr('alt');
};
var title = false;
if(thumb.data('ad-title')) {
title = thumb.data('ad-title');
} else if(thumb.attr('title') && thumb.attr('title').length) {
title = thumb.attr('title');
};
context.images[i] = { thumb: thumb.attr('src'), image: image_src, error: false,
preloaded: false, desc: desc, title: title, size: false,
link: link };
}
);
// Wait until all thumbs are loaded, and then set the width of the ul
var inter = setInterval(
function() {
if(thumb_count == thumbs_loaded) {
thumb_wrapper_width -= 100;
var list = context.nav.find('.ad-thumb-list'),
list_num = list.children().length,
list_width = list.children().eq(0).width();
list.css('width', (list_width+5)*list_num +'px');
clearInterval(inter);
};
},
100
);
},
initKeyEvents: function() {
var context = this;
$(document).keydown(
function(e) {
if(e.keyCode == 39) {
// right arrow
context.nextImage();
context.slideshow.stop();
} else if(e.keyCode == 37) {
// left arrow
context.prevImage();
context.slideshow.stop();
};
}
);
},
initNextAndPrev: function() {
this.next_link = $('<div class="ad-next"><div class="ad-next-image"></div></div>');
this.prev_link = $('<div class="ad-prev"><div class="ad-prev-image"></div></div>');
this.image_wrapper.append(this.next_link);
this.image_wrapper.append(this.prev_link);
var context = this;
this.prev_link.add(this.next_link).mouseover(
function(e) {
// IE 6 hides the wrapper div, so we have to set it's width
$(this).css('height', context.image_wrapper_height);
$(this).find('div').show();
}
).mouseout(
function(e) {
$(this).find('div').hide();
}
).click(
function() {
if($(this).is('.ad-next')) {
context.nextImage();
context.slideshow.stop();
} else {
context.prevImage();
context.slideshow.stop();
};
}
).find('div').css('opacity', 0.7);
},
initBackAndForward: function() {
var context = this;
this.scroll_forward = $('<div class="ad-forward"></div>');
this.scroll_back = $('<div class="ad-back"></div>');
this.nav.append(this.scroll_forward);
this.nav.prepend(this.scroll_back);
var has_scrolled = 0;
var thumbs_scroll_interval = false;
$(this.scroll_back).add(this.scroll_forward).click(
function() {
// We don't want to jump the whole width, since an image
// might be cut at the edge
var width = context.nav_display_width - 50;
if(context.settings.scroll_jump > 0) {
var width = context.settings.scroll_jump;
};
if($(this).is('.ad-forward')) {
var left = context.thumbs_wrapper.scrollLeft() + width;
} else {
var left = context.thumbs_wrapper.scrollLeft() - width;
};
if(context.settings.slideshow.stop_on_scroll) {
context.slideshow.stop();
};
context.thumbs_wrapper.animate({scrollLeft: left +'px'});
return false;
}
).css('opacity', 0.6).hover(
function() {
var direction = 'left';
if($(this).is('.ad-forward')) {
direction = 'right';
};
thumbs_scroll_interval = setInterval(
function() {
has_scrolled++;
// Don't want to stop the slideshow just because we scrolled a pixel or two
if(has_scrolled > 30 && context.settings.slideshow.stop_on_scroll) {
context.slideshow.stop();
};
var left = context.thumbs_wrapper.scrollLeft() + 1;
if(direction == 'left') {
left = context.thumbs_wrapper.scrollLeft() - 1;
};
context.thumbs_wrapper.scrollLeft(left);
},
10
);
$(this).css('opacity', 1);
},
function() {
has_scrolled = 0;
clearInterval(thumbs_scroll_interval);
$(this).css('opacity', 0.6);
}
);
},
_afterShow: function() {
this.gallery_info.html((this.current_index + 1) +' / '+ this.images.length);
if(!this.settings.cycle) {
// Needed for IE
this.prev_link.show().css('height', this.image_wrapper_height);
this.next_link.show().css('height', this.image_wrapper_height);
if(this.current_index == (this.images.length - 1)) {
this.next_link.hide();
};
if(this.current_index == 0) {
this.prev_link.hide();
};
};
this.fireCallback(this.settings.callbacks.afterImageVisible);
},
/**
* Checks if the image is small enough to fit inside the container
* If it's not, shrink it proportionally
*/
_getContainedImageSize: function(image_width, image_height) {
if(image_height > this.image_wrapper_height) {
var ratio = image_width / image_height;
image_height = this.image_wrapper_height;
image_width = this.image_wrapper_height * ratio;
};
if(image_width > this.image_wrapper_width) {
var ratio = image_height / image_width;
image_width = this.image_wrapper_width;
image_height = this.image_wrapper_width * ratio;
};
return {width: image_width, height: image_height};
},
/**
* If the image dimensions are smaller than the wrapper, we position
* it in the middle anyway
*/
_centerImage: function(img_container, image_width, image_height) {
img_container.css('top', '0px');
if(image_height < this.image_wrapper_height) {
var dif = this.image_wrapper_height - image_height;
img_container.css('top', (dif / 2) +'px');
};
img_container.css('left', '0px');
if(image_width < this.image_wrapper_width) {
var dif = this.image_wrapper_width - image_width;
img_container.css('left', (dif / 2) +'px');
};
},
_getDescription: function(image) {
var desc = false;
if(image.desc.length || image.title.length) {
var title = '';
if(image.title.length) {
title = '<strong class="ad-description-title">'+ image.title +'</strong>';
};
var desc = '';
if(image.desc.length) {
desc = '<span>'+ image.desc +'</span>';
};
desc = $('<p class="ad-image-description">'+ title + desc +'</p>');
};
return desc;
},
/**
* @param function callback Gets fired when the image has loaded, is displaying
* and it's animation has finished
*/
showImage: function(index, callback) {
if(this.images[index] && !this.in_transition) {
var context = this;
var image = this.images[index];
this.in_transition = true;
if(!image.preloaded) {
this.loading(true);
this.preloadImage(index, function() {
context.loading(false);
context._showWhenLoaded(index, callback);
});
} else {
this._showWhenLoaded(index, callback);
};
};
},
/**
* @param function callback Gets fired when the image has loaded, is displaying
* and it's animation has finished
*/
_showWhenLoaded: function(index, callback) {
if(this.images[index]) {
var context = this;
var image = this.images[index];
var img_container = $(document.createElement('div')).addClass('ad-image');
var img = $(new Image()).attr('src', image.image);
if(image.link) {
var link = $('<a href="'+ image.link +'" target="_blank"></a>');
link.append(img);
img_container.append(link);
} else {
img_container.append(img);
}
this.image_wrapper.prepend(img_container);
var size = this._getContainedImageSize(image.size.width, image.size.height);
img.attr('width', size.width);
img.attr('height', size.height);
img_container.css({width: size.width +'px', height: size.height +'px'});
this._centerImage(img_container, size.width, size.height);
var desc = this._getDescription(image, img_container);
if(desc) {
if(!this.settings.description_wrapper) {
img_container.append(desc);
var width = size.width - parseInt(desc.css('padding-left'), 10) - parseInt(desc.css('padding-right'), 10);
desc.css('width', width +'px');
} else {
this.settings.description_wrapper.append(desc);
}
};
this.highLightThumb(this.nav.find('.ad-thumb'+ index));
var direction = 'right';
if(this.current_index < index) {
direction = 'left';
};
this.fireCallback(this.settings.callbacks.beforeImageVisible);
if(this.current_image || this.settings.animate_first_image) {
var animation_speed = this.settings.animation_speed;
var easing = 'swing';
var animation = this.animations[this.settings.effect].call(this, img_container, direction, desc);
if(typeof animation.speed != 'undefined') {
animation_speed = animation.speed;
};
if(typeof animation.easing != 'undefined') {
easing = animation.easing;
};
if(this.current_image) {
var old_image = this.current_image;
var old_description = this.current_description;
old_image.animate(animation.old_image, animation_speed, easing,
function() {
old_image.remove();
if(old_description) old_description.remove();
}
);
};
img_container.animate(animation.new_image, animation_speed, easing,
function() {
context.current_index = index;
context.current_image = img_container;
context.current_description = desc;
context.in_transition = false;
context._afterShow();
context.fireCallback(callback);
}
);
} else {
this.current_index = index;
this.current_image = img_container;
context.current_description = desc;
this.in_transition = false;
context._afterShow();
this.fireCallback(callback);
};
};
},
nextIndex: function() {
if(this.current_index == (this.images.length - 1)) {
if(!this.settings.cycle) {
return false;
};
var next = 0;
} else {
var next = this.current_index + 1;
};
return next;
},
nextImage: function(callback) {
var next = this.nextIndex();
if(next === false) return false;
this.preloadImage(next + 1);
this.showImage(next, callback);
return true;
},
prevIndex: function() {
if(this.current_index == 0) {
if(!this.settings.cycle) {
return false;
};
var prev = this.images.length - 1;
} else {
var prev = this.current_index - 1;
};
return prev;
},
prevImage: function(callback) {
var prev = this.prevIndex();
if(prev === false) return false;
this.preloadImage(prev - 1);
this.showImage(prev, callback);
return true;
},
preloadAll: function() {
var context = this;
var i = 0;
function preloadNext() {
if(i < context.images.length) {
i++;
context.preloadImage(i, preloadNext);
};
};
context.preloadImage(i, preloadNext);
},
preloadImage: function(index, callback) {
if(this.images[index]) {
var image = this.images[index];
if(!this.images[index].preloaded) {
var img = $(new Image());
img.attr('src', image.image);
if(!this.isImageLoaded(img[0])) {
this.preloads.append(img);
var context = this;
img.load(
function() {
image.preloaded = true;
image.size = { width: this.width, height: this.height };
context.fireCallback(callback);
}
).error(
function() {
image.error = true;
image.preloaded = false;
image.size = false;
}
);
} else {
image.preloaded = true;
image.size = { width: img[0].width, height: img[0].height };
this.fireCallback(callback);
};
} else {
this.fireCallback(callback);
};
};
},
isImageLoaded: function(img) {
if(typeof img.complete != 'undefined' && !img.complete) {
return false;
};
if(typeof img.naturalWidth != 'undefined' && img.naturalWidth == 0) {
return false;
};
return true;
},
highLightThumb: function(thumb) {
this.thumbs_wrapper.find('.ad-active').removeClass('ad-active');
thumb.addClass('ad-active');
if(this.settings.thumb_opacity < 1) {
this.thumbs_wrapper.find('a:not(.ad-active) img').fadeTo(300, this.settings.thumb_opacity);
thumb.find('img').fadeTo(300, 1);
};
var left = thumb[0].parentNode.offsetLeft;
left -= (this.nav_display_width / 2) - (thumb[0].offsetWidth / 2);
this.thumbs_wrapper.animate({scrollLeft: left +'px'});
},
fireCallback: function(fn) {
if($.isFunction(fn)) {
fn.call(this);
};
}
};
function AdGallerySlideshow(nextimage_callback, settings) {
this.init(nextimage_callback, settings);
};
AdGallerySlideshow.prototype = {
start_link: false,
stop_link: false,
countdown: false,
controls: false,
settings: false,
nextimage_callback: false,
enabled: false,
running: false,
countdown_interval: false,
init: function(nextimage_callback, settings) {
var context = this;
this.nextimage_callback = nextimage_callback;
this.settings = settings;
},
create: function() {
this.start_link = $('<span class="ad-slideshow-start">'+ this.settings.start_label +'</span>');
this.stop_link = $('<span class="ad-slideshow-stop">'+ this.settings.stop_label +'</span>');
this.countdown = $('<span class="ad-slideshow-countdown"></span>');
this.controls = $('<div class="ad-slideshow-controls"></div>');
this.controls.append(this.start_link).append(this.stop_link).append(this.countdown);
this.countdown.hide();
var context = this;
this.start_link.click(
function() {
context.start();
}
);
this.stop_link.click(
function() {
context.stop();
}
);
$(document).keydown(
function(e) {
if(e.keyCode == 83) {
// 's'
if(context.running) {
context.stop();
} else {
context.start();
};
};
}
);
return this.controls;
},
disable: function() {
this.enabled = false;
this.stop();
this.controls.hide();
},
enable: function() {
this.enabled = true;
this.controls.show();
},
toggle: function() {
if(this.enabled) {
this.disable();
} else {
this.enable();
};
},
start: function() {
if(this.running || !this.enabled) return false;
var context = this;
this.running = true;
this.controls.addClass('ad-slideshow-running');
this._next();
this.fireCallback(this.settings.onStart);
return true;
},
stop: function() {
if(!this.running) return false;
this.running = false;
this.countdown.hide();
this.controls.removeClass('ad-slideshow-running');
clearInterval(this.countdown_interval);
this.fireCallback(this.settings.onStop);
return true;
},
_next: function() {
var context = this;
var pre = this.settings.countdown_prefix;
var su = this.settings.countdown_sufix;
clearInterval(context.countdown_interval);
this.countdown.show().html(pre + (this.settings.speed / 1000) + su);
var slide_timer = 0;
this.countdown_interval = setInterval(
function() {
slide_timer += 1000;
if(slide_timer >= context.settings.speed) {
var whenNextIsShown = function() {
// A check so the user hasn't stoped the slideshow during the
// animation
if(context.running) {
context._next();
};
slide_timer = 0;
};
if(!context.nextimage_callback(whenNextIsShown)) {
context.stop();
};
slide_timer = 0;
};
var sec = parseInt(context.countdown.text().replace(/[^0-9]/g, ''), 10);
sec--;
if(sec > 0) {
context.countdown.html(pre + sec + su);
};
},
1000
);
},
fireCallback: function(fn) {
if($.isFunction(fn)) {
fn.call(this);
};
}
};
})(jQuery); | JavaScript |
/**
* Styleswitch stylesheet switcher built on jQuery
* Under an Attribution, Share Alike License
* Download by http://www.codefans.net
* By Kelvin Luck ( http://www.kelvinluck.com/ )
**/
(function($)
{
$(document).ready(function() {
$('.styleswitch').click(function()
{
switchStylestyle(this.getAttribute("rel"));
return false;
});
var c = readCookie('style');
if (c) switchStylestyle(c);
});
function switchStylestyle(styleName)
{
var ifrm = $("#rightMain").contents();
$('link[rel*=style][title]').each(function(i)
{
this.disabled = true;
if (this.getAttribute('title') == styleName) this.disabled = false;
});
ifrm.find('link[rel*=style][title]').each(function(i)
{
this.disabled = true;
if (this.getAttribute('title') == styleName) this.disabled = false;
});
createCookie('style', styleName, 365);
}
})(jQuery);
// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
if (days)
{
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++)
{
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name)
{
createCookie(name,"",-1);
}
// /cookie functions | JavaScript |
Array.prototype.in_array = function(e){
for(i=0;i<this.length && this[i]!=e;i++);
return !(i==this.length);
}
function remove_all(){
$("#checkbox :checkbox").attr("checked",false);
$("#relation_text").html("");
$.get(ajax_url, {m:'yp', c:'index', a:'pk', action:'remove', catid:catid, random:Math.random()});
$("#relation").val("");
c_sum();
};
$("#checkbox :checkbox").click(function (){
var q = $(this),
num = 4,
id = q.val(),
title = q.attr('title'),
img = q.attr('img'),
sid = 'v1'+id,
relation_ids = $('#relation').val(),
relation_ids = relation_ids.replace(/(^_*)|(_*$)/g, ""),
r_arr = relation_ids.split('-');
if($("#comparison").css("display")=="none"){
$("#comparison").fadeIn("slow");
}
if(q.attr("checked")==false){
$('#'+sid).remove();
$.get(ajax_url, {m:'yp', c:'index', a:'pk', action:'reduce', id:id, catid:catid, random:Math.random()});
if(relation_ids !='' ) {
var newrelation_ids = '';
$.each(r_arr, function(i, n){
if(n!=id) {
if(i==0) {
newrelation_ids = n;
} else {
newrelation_ids = newrelation_ids+'-'+n;
}
}
});
$('#relation').val(newrelation_ids);
}
c_sum();
}else{
if(r_arr.in_array(id)){
q.checked=false;
alert("抱歉,已经选择了该信息");
return false;
}
if(r_arr.length>=num){
q.checked=false;
alert("抱歉,您只能选择"+r_arr.length+"款商品对比");
return false;
}else{
$.get(ajax_url, {m:'yp', c:'index', a:'pk', action:'add', id:id, title:title, thumb:img, catid:catid, random:Math.random()});
var str = "<li style='display:none' id='"+sid+"'><img src="+img+" height='45'/><p>"+title+"</p><a href='javascript:;' class='close' onclick=\"remove_relation('"+sid+"',"+id+")\">X</a></li>";
$('#relation_text').append(str);
$("#"+sid).fadeIn("slow");
if(relation_ids =='' ){
$('#relation').val(id);
}else{
relation_ids = relation_ids+'-'+id;
$('#relation').val(relation_ids);
}
c_sum();
$('#'+sid+' img').LoadImage(true, 120, 60,'statics/images/s_nopic.gif');
}
}
});
function remove_relation(sid,id){
$('#'+sid).remove();
$.get(ajax_url, {m:'yp', c:'index', a:'pk', action:'reduce', id:id, catid:catid, random:Math.random()});
$("#c_"+id).attr("checked",false);
$("#c_h_"+id).attr("checked",false);
var relation_ids = $('#relation').val(),
r_arr = relation_ids.split('-'),
newrelation_ids = '';
if(relation_ids!=''){
$.each(r_arr, function(i, n){
if(n!=id) {
if(i==0) {
newrelation_ids = n;
} else {
newrelation_ids = newrelation_ids+'-'+n;
}
}
});
$('#relation').val(newrelation_ids);
}
c_sum();
return false;
}
function comp_btn() {
var relation_ids = $('#relation').val(),
_rel = relation_ids.replace(/(^_*)|(_*$)/g, "");
if($("#comp_num").text()>1){
//alert(_rel);
window.open(ajax_url+"?m=yp&c=index&a=pk&catid="+catid+"&modelid="+modelid+"&pk="+_rel);
}else{
alert("请选择2~4个需要对比的商品!");
}
};
function c_sum(){
var relation_ids = $('#relation').val(),
relation_ids = relation_ids.replace(/(^_*)|(_*$)/g, ""),
r_arr = relation_ids.split('-');
if(relation_ids){
$("#comp_num").text(r_arr.length);
}else{
$("#comp_num").text('0');
}
}
//浮动
(function($) {
$.fn.extend({
"followDiv": function(str) {
var _self = this,
_h = _self.height() ;
var pos;
switch (str) {
case "right":
pos = { "right": "0px", "top": "27px" };
break;
}
topIE6 = parseInt(pos.top) + $(window).scrollTop();
_self.animate({'top':topIE6},500);
/*FF和IE7可以通过position:fixed来定位,*/
//_self.css({ "position": "fixed", "z-index": "9999" }).css(pos);
/*ie6需要动态设置距顶端高度top.*/
// if ($.browser.msie && $.browser.version == 6) {
//_self.css('position', 'absolute');
$(window).scroll(function() {
topIE6 = parseInt(pos.top) + $(window).scrollTop();
//_self.css('top', topIE6);
$(_self).stop().animate({top:topIE6},300)
});
// }
return _self; //返回this,使方法可链。
}
});
})(jQuery);
$("body").append('<div id="comparison"><div class="title"><span id="comp_num">1</span>/4对比栏<a href="javascript:;" onclick="$(this).parent().parent().hide()" class="colse">X</a></div><input type="hidden" id="relation" value="" /><ul id="relation_text"></ul><center><a href="javascript:void(0);" onclick="comp_btn()" id="comp_btn">开始对比</a><br><a href="javascript:;" class="remove_all" onclick="remove_all();">清空对比栏</a></center></div>');
$("#comparison").followDiv("right"); | JavaScript |
$(function(){
SwapTab(".swap-tab","li",".swap-content","ul","on");//通用Tab切换
startmarquee('announ',22,1,500,3000);//头部滚动广告
slide("#yp-slide","cur",447,201,1);//首页焦点图
//通用select菜单
$(".mouseover").each(function(i){
var type = $(this).attr('type'),height = parseInt($(this).attr('heights')),position=parseInt($(this).attr('position')),
navSub = $('.sub'+type+'_'+i);
$(this).bind("mouseenter",function(){
var offset =$(this).offset();
if(navSub.css("display") == "none"){
if(position==true){
navSub.css({"position":"absolute","z-index":"100",left:offset.left,top:offset.top+height}).show();
}else{
navSub.show();
}
}
}).bind("mouseleave",function(){
navSub.hide();
});
navSub.bind({
mouseenter:function(){
navSub.show();
},
mouseleave:function(){
navSub.hide();
}
})
})
//首页产品目录ie6支持
if("\v"=="v") {
if (!window.XMLHttpRequest) {
var catitem = $(".cat-item");
catitem.hover(function(){
$(this).addClass("cat-item-hover");
},function(){
$(this).removeClass("cat-item-hover");
})
}
}
/*筛选菜单展开收起*/
$("#PropSingle dd.AttrBox").each(function(){
var len = $(this).children().length;
if(len >10){
$(this).before("<dd class='more cu'>全部展开</dd>");
var category = $(this).children('a:gt(9)'),moreBtn = $(this).siblings(".more");
category.hide();
moreBtn.click(function(){
if(category.is(":visible")){
category.hide();
moreBtn.removeClass("on").text("全部展开");
}else{
category.show();
moreBtn.addClass("on").text("精简显示");
}
})
}
})
$(".input").blur(function(){$(this).removeClass('input-focus');});
$(".input").focus(function(){$(this).addClass('input-focus')});
}) | JavaScript |
/**
* 会员中心公用js
*
*/
/**
* 隐藏html element
*/
function hide_element(name) {
$('#'+name+'').fadeOut("slow");
}
/**
* 显示html element
*/
function show_element(name) {
$('#'+name+'').fadeIn("slow");
}
$(document).ready(function(){
$("input.input-text").blur(function () { this.className='input-text'; } );
$(":text").focus(function(){this.className='input-focus';});
});
/**
* url跳转
*/
function redirect(url) {
if(url.indexOf('://') == -1 && url.substr(0, 1) != '/' && url.substr(0, 1) != '?') url = $('base').attr('href')+url;
location.href = url;
}
function thumb_images(uploadid,returnid) {
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
if(in_content=='') return false;
if($('#'+returnid+'_preview').attr('src')) {
$('#'+returnid+'_preview').attr('src',in_content);
}
$('#'+returnid).val(in_content);
}
function change_images(uploadid,returnid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
var str = $('#'+returnid).html();
var contents = in_content.split('|');
$('#'+returnid+'_tips').css('display','none');
$.each( contents, function(i, n) {
var ids = parseInt(Math.random() * 10000 + 10*i);
str += "<div id='image"+ids+"'><input type='text' name='"+returnid+"_url[]' value='"+n+"' style='width:360px;' ondblclick='image_priview(this.value);' class='input-text'> <input type='text' name='"+returnid+"_alt[]' value='图片说明"+(i+1)+"' style='width:100px;' class='input-text' onfocus=\"if(this.value == this.defaultValue) this.value = ''\" onblur=\"if(this.value.replace(' ','') == '') this.value = this.defaultValue;\"> <a href=\"javascript:remove_div('image"+ids+"')\">移除</a> </div><div class='bk10'></div>";
});
$('#'+returnid).html(str);
}
function image_priview(img) {
window.top.art.dialog({title:'图片查看',fixed:true, content:'<img src="'+img+'" />',id:'image_priview',time:5});
}
function remove_div(id) {
$('#'+id).html(' ');
}
function select_catids() {
$('#addbutton').attr('disabled',false);
}
//商业用户会添加 num,普通用户默认为5
function transact(update,fromfiled,tofiled, num) {
if(update=='delete') {
var fieldvalue = $('#'+tofiled).val();
$("#"+tofiled+" option").each(function() {
if($(this).val() == fieldvalue){
$(this).remove();
}
});
} else {
var fieldvalue = $('#'+fromfiled).val();
var have_exists = 0;
var len = $("#"+tofiled+" option").size();
if(len>=num) {
alert('最多添加 '+num+' 项');
return false;
}
$("#"+tofiled+" option").each(function() {
if($(this).val() == fieldvalue){
have_exists = 1;
alert('已经添加到列表中');
return false;
}
});
if(have_exists==0) {
obj = $('#'+fromfiled+' option:selected');
text = obj.text();
text = text.replace('│', '');
text = text.replace('├ ', '');
text = text.replace('└ ', '');
text = text.trim();
fieldvalue = "<option value='"+fieldvalue+"'>"+text+"</option>"
$('#'+tofiled).append(fieldvalue);
$('#deletebutton').attr('disabled','');
}
}
}
function omnipotent(id,linkurl,title,close_type,w,h) {
if(!w) w=700;
if(!h) h=500;
art.dialog({id:id,iframe:linkurl, title:title, width:w, height:h, lock:true},
function(){
if(close_type==1) {
art.dialog({id:id}).close()
} else {
var d = art.dialog({id:id}).data.iframe;
var form = d.document.getElementById('dosubmit');form.click();
}
return false;
},
function(){
art.dialog({id:id}).close()
});void(0);
}
String.prototype.trim = function() {
var str = this,
whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
for (var i = 0,len = str.length; i < len; i++) {
if (whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(i);
break;
}
}
for (i = str.length - 1; i >= 0; i--) {
if (whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(0, i + 1);
break;
}
}
return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
} | JavaScript |
function FileProgress(file, targetID) {
this.fileProgressID = file.id;
this.opacity = 100;
this.height = 0;
this.fileProgressWrapper = document.getElementById(this.fileProgressID);
if (!this.fileProgressWrapper) {
this.fileProgressWrapper = document.createElement("div");
this.fileProgressWrapper.className = "progressWrapper";
this.fileProgressWrapper.id = this.fileProgressID;
this.fileProgressElement = document.createElement("div");
this.fileProgressElement.className = "progressContainer";
var progressCancel = document.createElement("a");
progressCancel.className = "progressCancel";
progressCancel.href = "#";
progressCancel.style.visibility = "hidden";
progressCancel.appendChild(document.createTextNode(" "));
var progressText = document.createElement("div");
progressText.className = "progressName";
progressText.appendChild(document.createTextNode(file.name));
var progressBar = document.createElement("div");
progressBar.className = "progressBarInProgress";
var progressStatus = document.createElement("div");
progressStatus.className = "progressBarStatus";
progressStatus.innerHTML = " ";
this.fileProgressElement.appendChild(progressCancel);
this.fileProgressElement.appendChild(progressText);
this.fileProgressElement.appendChild(progressStatus);
this.fileProgressElement.appendChild(progressBar);
this.fileProgressWrapper.appendChild(this.fileProgressElement);
document.getElementById(targetID).appendChild(this.fileProgressWrapper);
} else {
this.fileProgressElement = this.fileProgressWrapper.firstChild;
this.reset();
}
this.height = this.fileProgressWrapper.offsetHeight;
this.setTimer(null);
}
FileProgress.prototype.setTimer = function (timer) {
this.fileProgressElement["FP_TIMER"] = timer;
};
FileProgress.prototype.getTimer = function (timer) {
return this.fileProgressElement["FP_TIMER"] || null;
};
FileProgress.prototype.reset = function () {
this.fileProgressElement.className = "progressContainer";
this.fileProgressElement.childNodes[2].innerHTML = " ";
this.fileProgressElement.childNodes[2].className = "progressBarStatus";
this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
this.fileProgressElement.childNodes[3].style.width = "0%";
this.appear();
};
FileProgress.prototype.setProgress = function (percentage) {
this.fileProgressElement.className = "progressContainer green";
this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
this.fileProgressElement.childNodes[3].style.width = percentage + "%";
this.appear();
};
FileProgress.prototype.setComplete = function () {
this.fileProgressElement.parentNode.className = "progresshidden";
var oSelf = this;
};
FileProgress.prototype.setError = function () {
this.fileProgressElement.className = "progressContainer red";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
var oSelf = this;
this.setTimer(setTimeout(function () {
oSelf.disappear();
}, 5000));
};
FileProgress.prototype.setCancelled = function () {
this.fileProgressElement.className = "progressContainer";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
var oSelf = this;
this.setTimer(setTimeout(function () {
oSelf.disappear();
}, 2000));
};
FileProgress.prototype.setStatus = function (status) {
this.fileProgressElement.childNodes[2].innerHTML = status;
};
// Show/Hide the cancel button
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
if (swfUploadInstance) {
var fileID = this.fileProgressID;
this.fileProgressElement.childNodes[0].onclick = function () {
swfUploadInstance.cancelUpload(fileID);
return false;
};
}
};
FileProgress.prototype.appear = function () {
if (this.getTimer() !== null) {
clearTimeout(this.getTimer());
this.setTimer(null);
}
if (this.fileProgressWrapper.filters) {
try {
this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=100)";
}
} else {
this.fileProgressWrapper.style.opacity = 1;
}
this.fileProgressWrapper.style.height = "";
this.height = this.fileProgressWrapper.offsetHeight;
this.opacity = 100;
this.fileProgressWrapper.style.display = "";
};
// Fades out and clips away the FileProgress box.
FileProgress.prototype.disappear = function () {
var reduceOpacityBy = 15;
var reduceHeightBy = 4;
var rate = 30; // 15 fps
if (this.opacity > 0) {
this.opacity -= reduceOpacityBy;
if (this.opacity < 0) {
this.opacity = 0;
}
if (this.fileProgressWrapper.filters) {
try {
this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")";
}
} else {
this.fileProgressWrapper.style.opacity = this.opacity / 100;
}
}
if (this.height > 0) {
this.height -= reduceHeightBy;
if (this.height < 0) {
this.height = 0;
}
this.fileProgressWrapper.style.height = this.height + "px";
}
if (this.height > 0 || this.opacity > 0) {
var oSelf = this;
this.setTimer(setTimeout(function () {
oSelf.disappear();
}, rate));
} else {
this.fileProgressWrapper.style.display = "none";
this.setTimer(null);
}
}; | JavaScript |
function att_show(serverData,file)
{
var serverData = serverData.replace(/<div.*?<\/div>/g,'');
var data = serverData.split(',');
var id = data[0];
var src = data[1];
var ext = data[2];
var filename = data[3];
if(id == 0) {
alert(src)
return false;
}
if(ext == 1) {
var img = '<a href="javascript:;" onclick="javascript:att_cancel(this,'+id+',\'upload\')" class="on"><div class="icon"></div><img src="'+src+'" width="80" imgid="'+id+'" path="'+src+'" title="'+filename+'"/></a>';
} else {
var img = '<a href="javascript:;" onclick="javascript:att_cancel(this,'+id+',\'upload\')" class="on"><div class="icon"></div><img src="statics/images/ext/'+ext+'.png" width="80" imgid="'+id+'" path="'+src+'" title="'+filename+'"/></a>';
}
$.get('index.php?m=attachment&c=attachments&a=swfupload_json&aid='+id+'&src='+src+'&filename='+filename);
$('#fsUploadProgress').append('<li><div id="attachment_'+id+'" class="img-wrap"></div></li>');
$('#attachment_'+id).html(img);
$('#att-status').append('|'+src);
$('#att-name').append('|'+filename);
}
function att_insert(obj,id)
{
var uploadfile = $("#attachment_"+id+"> img").attr('path');
$('#att-status').append('|'+uploadfile);
}
function att_cancel(obj,id,source){
var src = $(obj).children("img").attr("path");
var filename = $(obj).children("img").attr("title");
if($(obj).hasClass('on')){
$(obj).removeClass("on");
var imgstr = $("#att-status").html();
var length = $("a[class='on']").children("img").length;
var strs = filenames = '';
for(var i=0;i<length;i++){
strs += '|'+$("a[class='on']").children("img").eq(i).attr('path');
filenames += '|'+$("a[class='on']").children("img").eq(i).attr('title');
}
$('#att-status').html(strs);
$('#att-name').html(filenames);
if(source=='upload') $('#att-status-del').append('|'+id);
} else {
$(obj).addClass("on");
$('#att-status').append('|'+src);
$('#att-name').append('|'+filename);
var imgstr_del = $("#att-status-del").html();
var imgstr_del_obj = $("a[class!='on']").children("img")
var length_del = imgstr_del_obj.length;
var strs_del='';
for(var i=0;i<length_del;i++){strs_del += '|'+imgstr_del_obj.eq(i).attr('imgid');}
if(source=='upload') $('#att-status-del').html(strs_del);
}
}
//swfupload functions
function fileDialogStart() {
/* I don't need to do anything here */
}
function fileQueued(file) {
if(file!= null){
try {
var progress = new FileProgress(file, this.customSettings.progressTarget);
progress.toggleCancel(true, this);
} catch (ex) {
this.debug(ex);
}
}
}
function fileDialogComplete(numFilesSelected, numFilesQueued)
{
try {
if (this.getStats().files_queued > 0) {
document.getElementById(this.customSettings.cancelButtonId).disabled = false;
}
/* I want auto start and I can do that here */
//this.startUpload();
} catch (ex) {
this.debug(ex);
}
}
function uploadStart(file)
{
var progress = new FileProgress(file, this.customSettings.progressTarget);
progress.setStatus("正在上传请稍后...");
return true;
}
function uploadProgress(file, bytesLoaded, bytesTotal)
{
var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
var progress = new FileProgress(file, this.customSettings.progressTarget);
progress.setProgress(percent);
progress.setStatus("正在上传("+percent+" %)请稍后...");
}
function uploadSuccess(file, serverData)
{
att_show(serverData,file);
var progress = new FileProgress(file, this.customSettings.progressTarget);
progress.setComplete();
progress.setStatus("文件上传成功");
}
function uploadComplete(file)
{
if (this.getStats().files_queued > 0)
{
this.startUpload();
}
}
function uploadError(file, errorCode, message) {
var msg;
switch (errorCode)
{
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
msg = "上传错误: " + message;
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
msg = "上传错误";
break;
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
msg = "服务器 I/O 错误";
break;
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
msg = "服务器安全认证错误";
break;
case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
msg = "附件安全检测失败,上传终止";
break;
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
msg = '上传取消';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
msg = '上传终止';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
msg = '单次上传文件数限制为 '+swfu.settings.file_upload_limit+' 个';
break;
default:
msg = message;
break;
}
var progress = new FileProgress(file,this.customSettings.progressTarget);
progress.setError();
progress.setStatus(msg);
}
function fileQueueError(file, errorCode, message)
{
var errormsg;
switch (errorCode) {
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
errormsg = "请不要上传空文件";
break;
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
errormsg = "队列文件数量超过设定值";
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
errormsg = "文件尺寸超过设定值";
break;
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
errormsg = "文件类型不合法";
default:
errormsg = '上传错误,请与管理员联系!';
break;
}
var progress = new FileProgress('file',this.customSettings.progressTarget);
progress.setError();
progress.setStatus(errormsg);
}
| JavaScript |
var SWFUpload;
if (SWFUpload == undefined) {
SWFUpload = function (settings) {
this.initSWFUpload(settings);
};
}
SWFUpload.prototype.initSWFUpload = function (settings) {
try {
this.customSettings = {}; // A container where developers can place their own settings associated with this instance.
this.settings = settings;
this.eventQueue = [];
this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
this.movieElement = null;
// Setup global control tracking
SWFUpload.instances[this.movieName] = this;
// Load the settings. Load the Flash movie.
this.initSettings();
this.loadFlash();
this.displayDebugInfo();
} catch (ex) {
delete SWFUpload.instances[this.movieName];
throw ex;
}
};
/* *************** */
/* Static Members */
/* *************** */
SWFUpload.instances = {};
SWFUpload.movieCount = 0;
SWFUpload.version = "2.2.0 2009-03-25";
SWFUpload.QUEUE_ERROR = {
QUEUE_LIMIT_EXCEEDED : -100,
FILE_EXCEEDS_SIZE_LIMIT : -110,
ZERO_BYTE_FILE : -120,
INVALID_FILETYPE : -130
};
SWFUpload.UPLOAD_ERROR = {
HTTP_ERROR : -200,
MISSING_UPLOAD_URL : -210,
IO_ERROR : -220,
SECURITY_ERROR : -230,
UPLOAD_LIMIT_EXCEEDED : -240,
UPLOAD_FAILED : -250,
SPECIFIED_FILE_ID_NOT_FOUND : -260,
FILE_VALIDATION_FAILED : -270,
FILE_CANCELLED : -280,
UPLOAD_STOPPED : -290
};
SWFUpload.FILE_STATUS = {
QUEUED : -1,
IN_PROGRESS : -2,
ERROR : -3,
COMPLETE : -4,
CANCELLED : -5
};
SWFUpload.BUTTON_ACTION = {
SELECT_FILE : -100,
SELECT_FILES : -110,
START_UPLOAD : -120
};
SWFUpload.CURSOR = {
ARROW : -1,
HAND : -2
};
SWFUpload.WINDOW_MODE = {
WINDOW : "window",
TRANSPARENT : "transparent",
OPAQUE : "opaque"
};
// Private: takes a URL, determines if it is relative and converts to an absolute URL
// using the current site. Only processes the URL if it can, otherwise returns the URL untouched
SWFUpload.completeURL = function(url) {
if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
return url;
}
var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
var indexSlash = window.location.pathname.lastIndexOf("/");
if (indexSlash <= 0) {
path = "/";
} else {
path = window.location.pathname.substr(0, indexSlash) + "/";
}
return /*currentURL +*/ path + url;
};
/* ******************** */
/* Instance Members */
/* ******************** */
// Private: initSettings ensures that all the
// settings are set, getting a default value if one was not assigned.
SWFUpload.prototype.initSettings = function () {
this.ensureDefault = function (settingName, defaultValue) {
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
};
// Upload backend settings
this.ensureDefault("upload_url", "");
this.ensureDefault("preserve_relative_urls", false);
this.ensureDefault("file_post_name", "Filedata");
this.ensureDefault("post_params", {});
this.ensureDefault("use_query_string", false);
this.ensureDefault("requeue_on_error", false);
this.ensureDefault("http_success", []);
this.ensureDefault("assume_success_timeout", 0);
// File Settings
this.ensureDefault("file_types", "*.*");
this.ensureDefault("file_types_description", "All Files");
this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited"
this.ensureDefault("file_upload_limit", 0);
this.ensureDefault("file_queue_limit", 0);
// Flash Settings
this.ensureDefault("flash_url", "swfupload.swf");
this.ensureDefault("prevent_swf_caching", true);
// Button Settings
this.ensureDefault("button_image_url", "");
this.ensureDefault("button_width", 1);
this.ensureDefault("button_height", 1);
this.ensureDefault("button_text", "");
this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
this.ensureDefault("button_text_top_padding", 0);
this.ensureDefault("button_text_left_padding", 0);
this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
this.ensureDefault("button_disabled", false);
this.ensureDefault("button_placeholder_id", "");
this.ensureDefault("button_placeholder", null);
this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
// Debug Settings
this.ensureDefault("debug", false);
this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API
// Event Handlers
this.settings.return_upload_start_handler = this.returnUploadStart;
this.ensureDefault("swfupload_loaded_handler", null);
this.ensureDefault("file_dialog_start_handler", null);
this.ensureDefault("file_queued_handler", null);
this.ensureDefault("file_queue_error_handler", null);
this.ensureDefault("file_dialog_complete_handler", null);
this.ensureDefault("upload_start_handler", null);
this.ensureDefault("upload_progress_handler", null);
this.ensureDefault("upload_error_handler", null);
this.ensureDefault("upload_success_handler", null);
this.ensureDefault("upload_complete_handler", null);
this.ensureDefault("debug_handler", this.debugMessage);
this.ensureDefault("custom_settings", {});
// Other settings
this.customSettings = this.settings.custom_settings;
// Update the flash url if needed
if (!!this.settings.prevent_swf_caching) {
this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
}
if (!this.settings.preserve_relative_urls) {
//this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url); // Don't need to do this one since flash doesn't look at it
this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
}
delete this.ensureDefault;
};
// Private: loadFlash replaces the button_placeholder element with the flash movie.
SWFUpload.prototype.loadFlash = function () {
var targetElement, tempParent;
// Make sure an element with the ID we are going to use doesn't already exist
if (document.getElementById(this.movieName) !== null) {
throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
}
// Get the element where we will be placing the flash movie
targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;
if (targetElement == undefined) {
throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
}
// Append the container and load the flash
tempParent = document.createElement("div");
tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);
// Fix IE Flash/Form bug
if (window[this.movieName] == undefined) {
window[this.movieName] = this.getMovieElement();
}
};
// Private: getFlashHTML generates the object tag needed to embed the flash in to the document
SWFUpload.prototype.getFlashHTML = function () {
// Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
'<param name="wmode" value="', this.settings.button_window_mode, '" />',
'<param name="movie" value="', this.settings.flash_url, '" />',
'<param name="quality" value="high" />',
'<param name="menu" value="false" />',
'<param name="allowScriptAccess" value="always" />',
'<param name="flashvars" value="' + this.getFlashVars() + '" />',
'</object>'].join("");
};
// Private: getFlashVars builds the parameter string that will be passed
// to flash in the flashvars param.
SWFUpload.prototype.getFlashVars = function () {
// Build a string from the post param object
var paramString = this.buildParamString();
var httpSuccessString = this.settings.http_success.join(",");
// Build the parameter string
return ["movieName=", encodeURIComponent(this.movieName),
"&uploadURL=", encodeURIComponent(this.settings.upload_url),
"&useQueryString=", encodeURIComponent(this.settings.use_query_string),
"&requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
"&httpSuccess=", encodeURIComponent(httpSuccessString),
"&assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
"&params=", encodeURIComponent(paramString),
"&filePostName=", encodeURIComponent(this.settings.file_post_name),
"&fileTypes=", encodeURIComponent(this.settings.file_types),
"&fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
"&fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
"&fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
"&fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
"&debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
"&buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
"&buttonWidth=", encodeURIComponent(this.settings.button_width),
"&buttonHeight=", encodeURIComponent(this.settings.button_height),
"&buttonText=", encodeURIComponent(this.settings.button_text),
"&buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
"&buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
"&buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
"&buttonAction=", encodeURIComponent(this.settings.button_action),
"&buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
"&buttonCursor=", encodeURIComponent(this.settings.button_cursor)
].join("");
};
// Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
// The element is cached after the first lookup
SWFUpload.prototype.getMovieElement = function () {
if (this.movieElement == undefined) {
this.movieElement = document.getElementById(this.movieName);
}
if (this.movieElement === null) {
throw "Could not find Flash element";
}
return this.movieElement;
};
// Private: buildParamString takes the name/value pairs in the post_params setting object
// and joins them up in to a string formatted "name=value&name=value"
SWFUpload.prototype.buildParamString = function () {
var postParams = this.settings.post_params;
var paramStringPairs = [];
if (typeof(postParams) === "object") {
for (var name in postParams) {
if (postParams.hasOwnProperty(name)) {
paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
}
}
}
return paramStringPairs.join("&");
};
// Public: Used to remove a SWFUpload instance from the page. This method strives to remove
// all references to the SWF, and other objects so memory is properly freed.
// Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
// Credits: Major improvements provided by steffen
SWFUpload.prototype.destroy = function () {
try {
// Make sure Flash is done before we try to remove it
this.cancelUpload(null, false);
// Remove the SWFUpload DOM nodes
var movieElement = null;
movieElement = this.getMovieElement();
if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
// Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
for (var i in movieElement) {
try {
if (typeof(movieElement[i]) === "function") {
movieElement[i] = null;
}
} catch (ex1) {}
}
// Remove the Movie Element from the page
try {
movieElement.parentNode.removeChild(movieElement);
} catch (ex) {}
}
// Remove IE form fix reference
window[this.movieName] = null;
// Destroy other references
SWFUpload.instances[this.movieName] = null;
delete SWFUpload.instances[this.movieName];
this.movieElement = null;
this.settings = null;
this.customSettings = null;
this.eventQueue = null;
this.movieName = null;
return true;
} catch (ex2) {
return false;
}
};
// Public: displayDebugInfo prints out settings and configuration
// information about this SWFUpload instance.
// This function (and any references to it) can be deleted when placing
// SWFUpload in production.
SWFUpload.prototype.displayDebugInfo = function () {
this.debug(
[
"---SWFUpload Instance Info---\n",
"Version: ", SWFUpload.version, "\n",
"Movie Name: ", this.movieName, "\n",
"Settings:\n",
"\t", "upload_url: ", this.settings.upload_url, "\n",
"\t", "flash_url: ", this.settings.flash_url, "\n",
"\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n",
"\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n",
"\t", "http_success: ", this.settings.http_success.join(", "), "\n",
"\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n",
"\t", "file_post_name: ", this.settings.file_post_name, "\n",
"\t", "post_params: ", this.settings.post_params.toString(), "\n",
"\t", "file_types: ", this.settings.file_types, "\n",
"\t", "file_types_description: ", this.settings.file_types_description, "\n",
"\t", "file_size_limit: ", this.settings.file_size_limit, "\n",
"\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n",
"\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n",
"\t", "debug: ", this.settings.debug.toString(), "\n",
"\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n",
"\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n",
"\t", "button_placeholder: ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
"\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n",
"\t", "button_width: ", this.settings.button_width.toString(), "\n",
"\t", "button_height: ", this.settings.button_height.toString(), "\n",
"\t", "button_text: ", this.settings.button_text.toString(), "\n",
"\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n",
"\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n",
"\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
"\t", "button_action: ", this.settings.button_action.toString(), "\n",
"\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n",
"\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n",
"Event Handlers:\n",
"\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
"\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
"\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
"\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
"\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
"\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
"\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
"\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
"\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
"\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n"
].join("")
);
};
/* Note: addSetting and getSetting are no longer used by SWFUpload but are included
the maintain v2 API compatibility
*/
// Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
SWFUpload.prototype.addSetting = function (name, value, default_value) {
if (value == undefined) {
return (this.settings[name] = default_value);
} else {
return (this.settings[name] = value);
}
};
// Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
SWFUpload.prototype.getSetting = function (name) {
if (this.settings[name] != undefined) {
return this.settings[name];
}
return "";
};
// Private: callFlash handles function calls made to the Flash element.
// Calls are made with a setTimeout for some functions to work around
// bugs in the ExternalInterface library.
SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
argumentArray = argumentArray || [];
var movieElement = this.getMovieElement();
var returnValue, returnString;
// Flash's method if calling ExternalInterface methods (code adapted from MooTools).
try {
returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
returnValue = eval(returnString);
} catch (ex) {
throw "Call to " + functionName + " failed";
}
// Unescape file post param values
if (returnValue != undefined && typeof returnValue.post === "object") {
returnValue = this.unescapeFilePostParams(returnValue);
}
return returnValue;
};
/* *****************************
-- Flash control methods --
Your UI should use these
to operate SWFUpload
***************************** */
// WARNING: this function does not work in Flash Player 10
// Public: selectFile causes a File Selection Dialog window to appear. This
// dialog only allows 1 file to be selected.
SWFUpload.prototype.selectFile = function () {
this.callFlash("SelectFile");
};
// WARNING: this function does not work in Flash Player 10
// Public: selectFiles causes a File Selection Dialog window to appear/ This
// dialog allows the user to select any number of files
// Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
// If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around
// for this bug.
SWFUpload.prototype.selectFiles = function () {
this.callFlash("SelectFiles");
};
// Public: startUpload starts uploading the first file in the queue unless
// the optional parameter 'fileID' specifies the ID
SWFUpload.prototype.startUpload = function (fileID) {
this.callFlash("StartUpload", [fileID]);
};
// Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index.
// If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
// If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
if (triggerErrorEvent !== false) {
triggerErrorEvent = true;
}
this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
};
// Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
// If nothing is currently uploading then nothing happens.
SWFUpload.prototype.stopUpload = function () {
this.callFlash("StopUpload");
};
/* ************************
* Settings methods
* These methods change the SWFUpload settings.
* SWFUpload settings should not be changed directly on the settings object
* since many of the settings need to be passed to Flash in order to take
* effect.
* *********************** */
// Public: getStats gets the file statistics object.
SWFUpload.prototype.getStats = function () {
return this.callFlash("GetStats");
};
// Public: setStats changes the SWFUpload statistics. You shouldn't need to
// change the statistics but you can. Changing the statistics does not
// affect SWFUpload accept for the successful_uploads count which is used
// by the upload_limit setting to determine how many files the user may upload.
SWFUpload.prototype.setStats = function (statsObject) {
this.callFlash("SetStats", [statsObject]);
};
// Public: getFile retrieves a File object by ID or Index. If the file is
// not found then 'null' is returned.
SWFUpload.prototype.getFile = function (fileID) {
if (typeof(fileID) === "number") {
return this.callFlash("GetFileByIndex", [fileID]);
} else {
return this.callFlash("GetFile", [fileID]);
}
};
// Public: addFileParam sets a name/value pair that will be posted with the
// file specified by the Files ID. If the name already exists then the
// exiting value will be overwritten.
SWFUpload.prototype.addFileParam = function (fileID, name, value) {
return this.callFlash("AddFileParam", [fileID, name, value]);
};
// Public: removeFileParam removes a previously set (by addFileParam) name/value
// pair from the specified file.
SWFUpload.prototype.removeFileParam = function (fileID, name) {
this.callFlash("RemoveFileParam", [fileID, name]);
};
// Public: setUploadUrl changes the upload_url setting.
SWFUpload.prototype.setUploadURL = function (url) {
this.settings.upload_url = url.toString();
this.callFlash("SetUploadURL", [url]);
};
// Public: setPostParams changes the post_params setting
SWFUpload.prototype.setPostParams = function (paramsObject) {
this.settings.post_params = paramsObject;
this.callFlash("SetPostParams", [paramsObject]);
};
// Public: addPostParam adds post name/value pair. Each name can have only one value.
SWFUpload.prototype.addPostParam = function (name, value) {
this.settings.post_params[name] = value;
this.callFlash("SetPostParams", [this.settings.post_params]);
};
// Public: removePostParam deletes post name/value pair.
SWFUpload.prototype.removePostParam = function (name) {
delete this.settings.post_params[name];
this.callFlash("SetPostParams", [this.settings.post_params]);
};
// Public: setFileTypes changes the file_types setting and the file_types_description setting
SWFUpload.prototype.setFileTypes = function (types, description) {
this.settings.file_types = types;
this.settings.file_types_description = description;
this.callFlash("SetFileTypes", [types, description]);
};
// Public: setFileSizeLimit changes the file_size_limit setting
SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
this.settings.file_size_limit = fileSizeLimit;
this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
};
// Public: setFileUploadLimit changes the file_upload_limit setting
SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
this.settings.file_upload_limit = fileUploadLimit;
this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
};
// Public: setFileQueueLimit changes the file_queue_limit setting
SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
this.settings.file_queue_limit = fileQueueLimit;
this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
};
// Public: setFilePostName changes the file_post_name setting
SWFUpload.prototype.setFilePostName = function (filePostName) {
this.settings.file_post_name = filePostName;
this.callFlash("SetFilePostName", [filePostName]);
};
// Public: setUseQueryString changes the use_query_string setting
SWFUpload.prototype.setUseQueryString = function (useQueryString) {
this.settings.use_query_string = useQueryString;
this.callFlash("SetUseQueryString", [useQueryString]);
};
// Public: setRequeueOnError changes the requeue_on_error setting
SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
this.settings.requeue_on_error = requeueOnError;
this.callFlash("SetRequeueOnError", [requeueOnError]);
};
// Public: setHTTPSuccess changes the http_success setting
SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
if (typeof http_status_codes === "string") {
http_status_codes = http_status_codes.replace(" ", "").split(",");
}
this.settings.http_success = http_status_codes;
this.callFlash("SetHTTPSuccess", [http_status_codes]);
};
// Public: setHTTPSuccess changes the http_success setting
SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
this.settings.assume_success_timeout = timeout_seconds;
this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
};
// Public: setDebugEnabled changes the debug_enabled setting
SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
this.settings.debug_enabled = debugEnabled;
this.callFlash("SetDebugEnabled", [debugEnabled]);
};
// Public: setButtonImageURL loads a button image sprite
SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
if (buttonImageURL == undefined) {
buttonImageURL = "";
}
this.settings.button_image_url = buttonImageURL;
this.callFlash("SetButtonImageURL", [buttonImageURL]);
};
// Public: setButtonDimensions resizes the Flash Movie and button
SWFUpload.prototype.setButtonDimensions = function (width, height) {
this.settings.button_width = width;
this.settings.button_height = height;
var movie = this.getMovieElement();
if (movie != undefined) {
movie.style.width = width + "px";
movie.style.height = height + "px";
}
this.callFlash("SetButtonDimensions", [width, height]);
};
// Public: setButtonText Changes the text overlaid on the button
SWFUpload.prototype.setButtonText = function (html) {
this.settings.button_text = html;
this.callFlash("SetButtonText", [html]);
};
// Public: setButtonTextPadding changes the top and left padding of the text overlay
SWFUpload.prototype.setButtonTextPadding = function (left, top) {
this.settings.button_text_top_padding = top;
this.settings.button_text_left_padding = left;
this.callFlash("SetButtonTextPadding", [left, top]);
};
// Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
SWFUpload.prototype.setButtonTextStyle = function (css) {
this.settings.button_text_style = css;
this.callFlash("SetButtonTextStyle", [css]);
};
// Public: setButtonDisabled disables/enables the button
SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
this.settings.button_disabled = isDisabled;
this.callFlash("SetButtonDisabled", [isDisabled]);
};
// Public: setButtonAction sets the action that occurs when the button is clicked
SWFUpload.prototype.setButtonAction = function (buttonAction) {
this.settings.button_action = buttonAction;
this.callFlash("SetButtonAction", [buttonAction]);
};
// Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
SWFUpload.prototype.setButtonCursor = function (cursor) {
this.settings.button_cursor = cursor;
this.callFlash("SetButtonCursor", [cursor]);
};
/* *******************************
Flash Event Interfaces
These functions are used by Flash to trigger the various
events.
All these functions a Private.
Because the ExternalInterface library is buggy the event calls
are added to a queue and the queue then executed by a setTimeout.
This ensures that events are executed in a determinate order and that
the ExternalInterface bugs are avoided.
******************************* */
SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
// Warning: Don't call this.debug inside here or you'll create an infinite loop
if (argumentArray == undefined) {
argumentArray = [];
} else if (!(argumentArray instanceof Array)) {
argumentArray = [argumentArray];
}
var self = this;
if (typeof this.settings[handlerName] === "function") {
// Queue the event
this.eventQueue.push(function () {
this.settings[handlerName].apply(this, argumentArray);
});
// Execute the next queued event
setTimeout(function () {
self.executeNextEvent();
}, 0);
} else if (this.settings[handlerName] !== null) {
throw "Event handler " + handlerName + " is unknown or is not a function";
}
};
// Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout
// we must queue them in order to garentee that they are executed in order.
SWFUpload.prototype.executeNextEvent = function () {
// Warning: Don't call this.debug inside here or you'll create an infinite loop
var f = this.eventQueue ? this.eventQueue.shift() : null;
if (typeof(f) === "function") {
f.apply(this);
}
};
// Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
// properties that contain characters that are not valid for JavaScript identifiers. To work around this
// the Flash Component escapes the parameter names and we must unescape again before passing them along.
SWFUpload.prototype.unescapeFilePostParams = function (file) {
var reg = /[$]([0-9a-f]{4})/i;
var unescapedPost = {};
var uk;
if (file != undefined) {
for (var k in file.post) {
if (file.post.hasOwnProperty(k)) {
uk = k;
var match;
while ((match = reg.exec(uk)) !== null) {
uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
}
unescapedPost[uk] = file.post[k];
}
}
file.post = unescapedPost;
}
return file;
};
// Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working)
SWFUpload.prototype.testExternalInterface = function () {
try {
return this.callFlash("TestExternalInterface");
} catch (ex) {
return false;
}
};
// Private: This event is called by Flash when it has finished loading. Don't modify this.
// Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded.
SWFUpload.prototype.flashReady = function () {
// Check that the movie element is loaded correctly with its ExternalInterface methods defined
var movieElement = this.getMovieElement();
if (!movieElement) {
this.debug("Flash called back ready but the flash movie can't be found.");
return;
}
this.cleanUp(movieElement);
this.queueEvent("swfupload_loaded_handler");
};
// Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE.
// This function is called by Flash each time the ExternalInterface functions are created.
SWFUpload.prototype.cleanUp = function (movieElement) {
// Pro-actively unhook all the Flash functions
try {
if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
for (var key in movieElement) {
try {
if (typeof(movieElement[key]) === "function") {
movieElement[key] = null;
}
} catch (ex) {
}
}
}
} catch (ex1) {
}
// Fix Flashes own cleanup code so if the SWFMovie was removed from the page
// it doesn't display errors.
window["__flash__removeCallback"] = function (instance, name) {
try {
if (instance) {
instance[name] = null;
}
} catch (flashEx) {
}
};
};
/* This is a chance to do something before the browse window opens */
SWFUpload.prototype.fileDialogStart = function () {
this.queueEvent("file_dialog_start_handler");
};
/* Called when a file is successfully added to the queue. */
SWFUpload.prototype.fileQueued = function (file) {
file = this.unescapeFilePostParams(file);
this.queueEvent("file_queued_handler", file);
};
/* Handle errors that occur when an attempt to queue a file fails. */
SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
file = this.unescapeFilePostParams(file);
this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
};
/* Called after the file dialog has closed and the selected files have been queued.
You could call startUpload here if you want the queued files to begin uploading immediately. */
SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
};
SWFUpload.prototype.uploadStart = function (file) {
file = this.unescapeFilePostParams(file);
this.queueEvent("return_upload_start_handler", file);
};
SWFUpload.prototype.returnUploadStart = function (file) {
var returnValue;
if (typeof this.settings.upload_start_handler === "function") {
file = this.unescapeFilePostParams(file);
returnValue = this.settings.upload_start_handler.call(this, file);
} else if (this.settings.upload_start_handler != undefined) {
throw "upload_start_handler must be a function";
}
// Convert undefined to true so if nothing is returned from the upload_start_handler it is
// interpretted as 'true'.
if (returnValue === undefined) {
returnValue = true;
}
returnValue = !!returnValue;
this.callFlash("ReturnUploadStart", [returnValue]);
};
SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
};
SWFUpload.prototype.uploadError = function (file, errorCode, message) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_error_handler", [file, errorCode, message]);
};
SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
};
SWFUpload.prototype.uploadComplete = function (file) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_complete_handler", file);
};
/* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
internal debug console. You can override this event and have messages written where you want. */
SWFUpload.prototype.debug = function (message) {
this.queueEvent("debug_handler", message);
};
/* **********************************
Debug Console
The debug console is a self contained, in page location
for debug message to be sent. The Debug Console adds
itself to the body if necessary.
The console is automatically scrolled as messages appear.
If you are using your own debug handler or when you deploy to production and
have debug disabled you can remove these functions to reduce the file size
and complexity.
********************************** */
// Private: debugMessage is the default debug_handler. If you want to print debug messages
// call the debug() function. When overriding the function your own function should
// check to see if the debug setting is true before outputting debug information.
SWFUpload.prototype.debugMessage = function (message) {
if (this.settings.debug) {
var exceptionMessage, exceptionValues = [];
// Check for an exception object and print it nicely
if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
for (var key in message) {
if (message.hasOwnProperty(key)) {
exceptionValues.push(key + ": " + message[key]);
}
}
exceptionMessage = exceptionValues.join("\n") || "";
exceptionValues = exceptionMessage.split("\n");
exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
SWFUpload.Console.writeLine(exceptionMessage);
} else {
SWFUpload.Console.writeLine(message);
}
}
};
SWFUpload.Console = {};
SWFUpload.Console.writeLine = function (message) {
var console, documentForm;
try {
console = document.getElementById("SWFUpload_Console");
if (!console) {
documentForm = document.createElement("form");
document.getElementsByTagName("body")[0].appendChild(documentForm);
console = document.createElement("textarea");
console.id = "SWFUpload_Console";
console.style.fontFamily = "monospace";
console.setAttribute("wrap", "off");
console.wrap = "off";
console.style.overflow = "auto";
console.style.width = "700px";
console.style.height = "350px";
console.style.margin = "5px";
documentForm.appendChild(console);
}
console.value += message + "\n";
console.scrollTop = console.scrollHeight - console.clientHeight;
} catch (ex) {
alert("Exception: " + ex.name + " Message: " + ex.message);
}
};
| JavaScript |
function flashupload(uploadid, name, textareaid, funcName, args, module, catid, authkey) {
var args = args ? '&args='+args : '';
var setting = '&module='+module+'&catid='+catid+'&authkey='+authkey;
window.top.art.dialog({title:name,id:uploadid,iframe:'index.php?m=attachment&c=attachments&a=swfupload'+args+setting,width:'500',height:'420'}, function(){ if(funcName) {funcName.apply(this,[uploadid,textareaid]);}else {submit_ckeditor(uploadid,textareaid);}}, function(){window.top.art.dialog({id:uploadid}).close()});
}
function submit_ckeditor(uploadid,textareaid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html();
var del_content = d.$("#att-status-del").html();
insert2editor(textareaid,in_content,del_content)
}
function submit_images(uploadid,returnid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
var in_content = in_content.split('|');
IsImg(in_content[0]) ? $('#'+returnid).attr("value",in_content[0]) : alert('选择的类型必须为图片类型');
}
function submit_attachment(uploadid,returnid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
var in_content = in_content.split('|');
$('#'+returnid).attr("value",in_content[0]);
}
function submit_files(uploadid,returnid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
var in_content = in_content.split('|');
var new_filepath = in_content[0].replace(uploadurl,'/');
$('#'+returnid).attr("value",new_filepath);
}
function insert2editor(id,in_content,del_content) {
if(in_content == '') {return false;}
var data = in_content.substring(1).split('|');
var img = '';
for (var n in data) {
img += IsImg(data[n]) ? '<img src="'+data[n]+'" /><br />' : (IsSwf(data[n]) ? '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="quality" value="high" /><param name="movie" value="'+data[n]+'" /><embed pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="'+data[n]+'" type="application/x-shockwave-flash" width="460"></embed></object>' :'<a href="'+data[n]+'" />'+data[n]+'</a><br />') ;
}
$.get("index.php?m=attachment&c=attachments&a=swfdelete",{data: del_content},function(data){});
CKEDITOR.instances[id].insertHtml(img);
}
function IsImg(url){
var sTemp;
var b=false;
var opt="jpg|gif|png|bmp|jpeg";
var s=opt.toUpperCase().split("|");
for (var i=0;i<s.length ;i++ ){
sTemp=url.substr(url.length-s[i].length-1);
sTemp=sTemp.toUpperCase();
s[i]="."+s[i];
if (s[i]==sTemp){
b=true;
break;
}
}
return b;
}
function IsSwf(url){
var sTemp;
var b=false;
var opt="swf";
var s=opt.toUpperCase().split("|");
for (var i=0;i<s.length ;i++ ){
sTemp=url.substr(url.length-s[i].length-1);
sTemp=sTemp.toUpperCase();
s[i]="."+s[i];
if (s[i]==sTemp){
b=true;
break;
}
}
return b;
} | JavaScript |
/**
* jqPlot
* Pure JavaScript plotting plugin using jQuery
*
* Version: 1.0.0a_r701
*
* Copyright (c) 2009-2011 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
* version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* Although not required, the author would appreciate an email letting him
* know of any substantial use of jqPlot. You can reach the author at:
* chris at jqplot dot com or see http://www.jqplot.com/info.php .
*
* If you are feeling kind and generous, consider supporting the project by
* making a donation at: http://www.jqplot.com/donate.php .
*
* sprintf functions contained in jqplot.sprintf.js by Ash Searle:
*
* version 2007.04.27
* author Ash Searle
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
* The author (Ash Searle) has placed this code in the public domain:
* "This code is unrestricted: you are free to use it however you like."
*
*/
(function($) {
/**
* class: $.jqplot.CategoryAxisRenderer
* A plugin for jqPlot to render a category style axis, with equal pixel spacing between y data values of a series.
*
* To use this renderer, include the plugin in your source
* > <script type="text/javascript" language="javascript" src="plugins/jqplot.categoryAxisRenderer.js"></script>
*
* and supply the appropriate options to your plot
*
* > {axes:{xaxis:{renderer:$.jqplot.CategoryAxisRenderer}}}
**/
$.jqplot.CategoryAxisRenderer = function(options) {
$.jqplot.LinearAxisRenderer.call(this);
// prop: sortMergedLabels
// True to sort tick labels when labels are created by merging
// x axis values from multiple series. That is, say you have
// two series like:
// > line1 = [[2006, 4], [2008, 9], [2009, 16]];
// > line2 = [[2006, 3], [2007, 7], [2008, 6]];
// If no label array is specified, tick labels will be collected
// from the x values of the series. With sortMergedLabels
// set to true, tick labels will be:
// > [2006, 2007, 2008, 2009]
// With sortMergedLabels set to false, tick labels will be:
// > [2006, 2008, 2009, 2007]
//
// Note, this property is specified on the renderOptions for the
// axes when creating a plot:
// > axes:{xaxis:{renderer:$.jqplot.CategoryAxisRenderer, rendererOptions:{sortMergedLabels:true}}}
this.sortMergedLabels = false;
};
$.jqplot.CategoryAxisRenderer.prototype = new $.jqplot.LinearAxisRenderer();
$.jqplot.CategoryAxisRenderer.prototype.constructor = $.jqplot.CategoryAxisRenderer;
$.jqplot.CategoryAxisRenderer.prototype.init = function(options){
this.groups = 1;
this.groupLabels = [];
this._groupLabels = [];
this._grouped = false;
this._barsPerGroup = null;
// prop: tickRenderer
// A class of a rendering engine for creating the ticks labels displayed on the plot,
// See <$.jqplot.AxisTickRenderer>.
// this.tickRenderer = $.jqplot.AxisTickRenderer;
// this.labelRenderer = $.jqplot.AxisLabelRenderer;
$.extend(true, this, {tickOptions:{formatString:'%d'}}, options);
var db = this._dataBounds;
// Go through all the series attached to this axis and find
// the min/max bounds for this axis.
for (var i=0; i<this._series.length; i++) {
var s = this._series[i];
if (s.groups) {
this.groups = s.groups;
}
var d = s.data;
for (var j=0; j<d.length; j++) {
if (this.name == 'xaxis' || this.name == 'x2axis') {
if (d[j][0] < db.min || db.min == null) {
db.min = d[j][0];
}
if (d[j][0] > db.max || db.max == null) {
db.max = d[j][0];
}
}
else {
if (d[j][1] < db.min || db.min == null) {
db.min = d[j][1];
}
if (d[j][1] > db.max || db.max == null) {
db.max = d[j][1];
}
}
}
}
if (this.groupLabels.length) {
this.groups = this.groupLabels.length;
}
};
$.jqplot.CategoryAxisRenderer.prototype.createTicks = function() {
// we're are operating on an axis here
var ticks = this._ticks;
var userTicks = this.ticks;
var name = this.name;
// databounds were set on axis initialization.
var db = this._dataBounds;
var dim, interval;
var min, max;
var pos1, pos2;
var tt, i;
// if we already have ticks, use them.
if (userTicks.length) {
// adjust with blanks if we have groups
if (this.groups > 1 && !this._grouped) {
var l = userTicks.length;
var skip = parseInt(l/this.groups, 10);
var count = 0;
for (var i=skip; i<l; i+=skip) {
userTicks.splice(i+count, 0, ' ');
count++;
}
this._grouped = true;
}
this.min = 0.5;
this.max = userTicks.length + 0.5;
var range = this.max - this.min;
this.numberTicks = 2*userTicks.length + 1;
for (i=0; i<userTicks.length; i++){
tt = this.min + 2 * i * range / (this.numberTicks-1);
// need a marker before and after the tick
var t = new this.tickRenderer(this.tickOptions);
t.showLabel = false;
// t.showMark = true;
t.setTick(tt, this.name);
this._ticks.push(t);
var t = new this.tickRenderer(this.tickOptions);
t.label = userTicks[i];
// t.showLabel = true;
t.showMark = false;
t.showGridline = false;
t.setTick(tt+0.5, this.name);
this._ticks.push(t);
}
// now add the last tick at the end
var t = new this.tickRenderer(this.tickOptions);
t.showLabel = false;
// t.showMark = true;
t.setTick(tt+1, this.name);
this._ticks.push(t);
}
// we don't have any ticks yet, let's make some!
else {
if (name == 'xaxis' || name == 'x2axis') {
dim = this._plotDimensions.width;
}
else {
dim = this._plotDimensions.height;
}
// if min, max and number of ticks specified, user can't specify interval.
if (this.min != null && this.max != null && this.numberTicks != null) {
this.tickInterval = null;
}
// if max, min, and interval specified and interval won't fit, ignore interval.
if (this.min != null && this.max != null && this.tickInterval != null) {
if (parseInt((this.max-this.min)/this.tickInterval, 10) != (this.max-this.min)/this.tickInterval) {
this.tickInterval = null;
}
}
// find out how many categories are in the lines and collect labels
var labels = [];
var numcats = 0;
var min = 0.5;
var max, val;
var isMerged = false;
for (var i=0; i<this._series.length; i++) {
var s = this._series[i];
for (var j=0; j<s.data.length; j++) {
if (this.name == 'xaxis' || this.name == 'x2axis') {
val = s.data[j][0];
}
else {
val = s.data[j][1];
}
if ($.inArray(val, labels) == -1) {
isMerged = true;
numcats += 1;
labels.push(val);
}
}
}
if (isMerged && this.sortMergedLabels) {
labels.sort(function(a,b) { return a - b; });
}
// keep a reference to these tick labels to use for redrawing plot (see bug #57)
this.ticks = labels;
// now bin the data values to the right lables.
for (var i=0; i<this._series.length; i++) {
var s = this._series[i];
for (var j=0; j<s.data.length; j++) {
if (this.name == 'xaxis' || this.name == 'x2axis') {
val = s.data[j][0];
}
else {
val = s.data[j][1];
}
// for category axis, force the values into category bins.
// we should have the value in the label array now.
var idx = $.inArray(val, labels)+1;
if (this.name == 'xaxis' || this.name == 'x2axis') {
s.data[j][0] = idx;
}
else {
s.data[j][1] = idx;
}
}
}
// adjust with blanks if we have groups
if (this.groups > 1 && !this._grouped) {
var l = labels.length;
var skip = parseInt(l/this.groups, 10);
var count = 0;
for (var i=skip; i<l; i+=skip+1) {
labels[i] = ' ';
}
this._grouped = true;
}
max = numcats + 0.5;
if (this.numberTicks == null) {
this.numberTicks = 2*numcats + 1;
}
var range = max - min;
this.min = min;
this.max = max;
var track = 0;
// todo: adjust this so more ticks displayed.
var maxVisibleTicks = parseInt(3+dim/20, 10);
var skip = parseInt(numcats/maxVisibleTicks, 10);
if (this.tickInterval == null) {
this.tickInterval = range / (this.numberTicks-1);
}
// if tickInterval is specified, we will ignore any computed maximum.
for (var i=0; i<this.numberTicks; i++){
tt = this.min + i * this.tickInterval;
var t = new this.tickRenderer(this.tickOptions);
// if even tick, it isn't a category, it's a divider
if (i/2 == parseInt(i/2, 10)) {
t.showLabel = false;
t.showMark = true;
}
else {
if (skip>0 && track<skip) {
t.showLabel = false;
track += 1;
}
else {
t.showLabel = true;
track = 0;
}
t.label = t.formatter(t.formatString, labels[(i-1)/2]);
t.showMark = false;
t.showGridline = false;
}
t.setTick(tt, this.name);
this._ticks.push(t);
}
}
};
// called with scope of axis
$.jqplot.CategoryAxisRenderer.prototype.draw = function(ctx) {
if (this.show) {
// populate the axis label and value properties.
// createTicks is a method on the renderer, but
// call it within the scope of the axis.
this.renderer.createTicks.call(this);
// fill a div with axes labels in the right direction.
// Need to pregenerate each axis to get it's bounds and
// position it and the labels correctly on the plot.
var dim=0;
var temp;
// Added for theming.
if (this._elem) {
this._elem.empty();
}
this._elem = this._elem || $('<div class="jqplot-axis jqplot-'+this.name+'" style="position:absolute;"></div>');
if (this.name == 'xaxis' || this.name == 'x2axis') {
this._elem.width(this._plotDimensions.width);
}
else {
this._elem.height(this._plotDimensions.height);
}
// create a _label object.
this.labelOptions.axis = this.name;
this._label = new this.labelRenderer(this.labelOptions);
if (this._label.show) {
var elem = this._label.draw(ctx);
elem.appendTo(this._elem);
}
var t = this._ticks;
for (var i=0; i<t.length; i++) {
var tick = t[i];
if (tick.showLabel && (!tick.isMinorTick || this.showMinorTicks)) {
var elem = tick.draw(ctx);
elem.appendTo(this._elem);
}
}
this._groupLabels = [];
// now make group labels
for (var i=0; i<this.groupLabels.length; i++)
{
var elem = $('<div style="position:absolute;" class="jqplot-'+this.name+'-groupLabel"></div>');
elem.html(this.groupLabels[i]);
this._groupLabels.push(elem);
elem.appendTo(this._elem);
}
}
return this._elem;
};
// called with scope of axis
$.jqplot.CategoryAxisRenderer.prototype.set = function() {
var dim = 0;
var temp;
var w = 0;
var h = 0;
var lshow = (this._label == null) ? false : this._label.show;
if (this.show) {
var t = this._ticks;
for (var i=0; i<t.length; i++) {
var tick = t[i];
if (tick.showLabel && (!tick.isMinorTick || this.showMinorTicks)) {
if (this.name == 'xaxis' || this.name == 'x2axis') {
temp = tick._elem.outerHeight(true);
}
else {
temp = tick._elem.outerWidth(true);
}
if (temp > dim) {
dim = temp;
}
}
}
var dim2 = 0;
for (var i=0; i<this._groupLabels.length; i++) {
var l = this._groupLabels[i];
if (this.name == 'xaxis' || this.name == 'x2axis') {
temp = l.outerHeight(true);
}
else {
temp = l.outerWidth(true);
}
if (temp > dim2) {
dim2 = temp;
}
}
if (lshow) {
w = this._label._elem.outerWidth(true);
h = this._label._elem.outerHeight(true);
}
if (this.name == 'xaxis') {
dim += dim2 + h;
this._elem.css({'height':dim+'px', left:'0px', bottom:'0px'});
}
else if (this.name == 'x2axis') {
dim += dim2 + h;
this._elem.css({'height':dim+'px', left:'0px', top:'0px'});
}
else if (this.name == 'yaxis') {
dim += dim2 + w;
this._elem.css({'width':dim+'px', left:'0px', top:'0px'});
if (lshow && this._label.constructor == $.jqplot.AxisLabelRenderer) {
this._label._elem.css('width', w+'px');
}
}
else {
dim += dim2 + w;
this._elem.css({'width':dim+'px', right:'0px', top:'0px'});
if (lshow && this._label.constructor == $.jqplot.AxisLabelRenderer) {
this._label._elem.css('width', w+'px');
}
}
}
};
// called with scope of axis
$.jqplot.CategoryAxisRenderer.prototype.pack = function(pos, offsets) {
var ticks = this._ticks;
var max = this.max;
var min = this.min;
var offmax = offsets.max;
var offmin = offsets.min;
var lshow = (this._label == null) ? false : this._label.show;
for (var p in pos) {
this._elem.css(p, pos[p]);
}
this._offsets = offsets;
// pixellength will be + for x axes and - for y axes becasue pixels always measured from top left.
var pixellength = offmax - offmin;
var unitlength = max - min;
// point to unit and unit to point conversions references to Plot DOM element top left corner.
this.p2u = function(p){
return (p - offmin) * unitlength / pixellength + min;
};
this.u2p = function(u){
return (u - min) * pixellength / unitlength + offmin;
};
if (this.name == 'xaxis' || this.name == 'x2axis'){
this.series_u2p = function(u){
return (u - min) * pixellength / unitlength;
};
this.series_p2u = function(p){
return p * unitlength / pixellength + min;
};
}
else {
this.series_u2p = function(u){
return (u - max) * pixellength / unitlength;
};
this.series_p2u = function(p){
return p * unitlength / pixellength + max;
};
}
if (this.show) {
if (this.name == 'xaxis' || this.name == 'x2axis') {
for (i=0; i<ticks.length; i++) {
var t = ticks[i];
if (t.show && t.showLabel) {
var shim;
if (t.constructor == $.jqplot.CanvasAxisTickRenderer && t.angle) {
// will need to adjust auto positioning based on which axis this is.
var temp = (this.name == 'xaxis') ? 1 : -1;
switch (t.labelPosition) {
case 'auto':
// position at end
if (temp * t.angle < 0) {
shim = -t.getWidth() + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
}
// position at start
else {
shim = -t._textRenderer.height * Math.sin(t._textRenderer.angle) / 2;
}
break;
case 'end':
shim = -t.getWidth() + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
break;
case 'start':
shim = -t._textRenderer.height * Math.sin(t._textRenderer.angle) / 2;
break;
case 'middle':
shim = -t.getWidth()/2 + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
break;
default:
shim = -t.getWidth()/2 + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
break;
}
}
else {
shim = -t.getWidth()/2;
}
var val = this.u2p(t.value) + shim + 'px';
t._elem.css('left', val);
t.pack();
}
}
var labeledge=['bottom', 0];
if (lshow) {
var w = this._label._elem.outerWidth(true);
this._label._elem.css('left', offmin + pixellength/2 - w/2 + 'px');
if (this.name == 'xaxis') {
this._label._elem.css('bottom', '0px');
labeledge = ['bottom', this._label._elem.outerHeight(true)];
}
else {
this._label._elem.css('top', '0px');
labeledge = ['top', this._label._elem.outerHeight(true)];
}
this._label.pack();
}
// draw the group labels
var step = parseInt(this._ticks.length/this.groups, 10);
for (i=0; i<this._groupLabels.length; i++) {
var mid = 0;
var count = 0;
for (var j=i*step; j<=(i+1)*step; j++) {
if (this._ticks[j]._elem && this._ticks[j].label != " ") {
var t = this._ticks[j]._elem;
var p = t.position();
mid += p.left + t.outerWidth(true)/2;
count++;
}
}
mid = mid/count;
this._groupLabels[i].css({'left':(mid - this._groupLabels[i].outerWidth(true)/2)});
this._groupLabels[i].css(labeledge[0], labeledge[1]);
}
}
else {
for (i=0; i<ticks.length; i++) {
var t = ticks[i];
if (t.show && t.showLabel) {
var shim;
if (t.constructor == $.jqplot.CanvasAxisTickRenderer && t.angle) {
// will need to adjust auto positioning based on which axis this is.
var temp = (this.name == 'yaxis') ? 1 : -1;
switch (t.labelPosition) {
case 'auto':
// position at end
case 'end':
if (temp * t.angle < 0) {
shim = -t._textRenderer.height * Math.cos(-t._textRenderer.angle) / 2;
}
else {
shim = -t.getHeight() + t._textRenderer.height * Math.cos(t._textRenderer.angle) / 2;
}
break;
case 'start':
if (t.angle > 0) {
shim = -t._textRenderer.height * Math.cos(-t._textRenderer.angle) / 2;
}
else {
shim = -t.getHeight() + t._textRenderer.height * Math.cos(t._textRenderer.angle) / 2;
}
break;
case 'middle':
// if (t.angle > 0) {
// shim = -t.getHeight()/2 + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
// }
// else {
// shim = -t.getHeight()/2 - t._textRenderer.height * Math.sin(t._textRenderer.angle) / 2;
// }
shim = -t.getHeight()/2;
break;
default:
shim = -t.getHeight()/2;
break;
}
}
else {
shim = -t.getHeight()/2;
}
var val = this.u2p(t.value) + shim + 'px';
t._elem.css('top', val);
t.pack();
}
}
var labeledge=['left', 0];
if (lshow) {
var h = this._label._elem.outerHeight(true);
this._label._elem.css('top', offmax - pixellength/2 - h/2 + 'px');
if (this.name == 'yaxis') {
this._label._elem.css('left', '0px');
labeledge = ['left', this._label._elem.outerWidth(true)];
}
else {
this._label._elem.css('right', '0px');
labeledge = ['right', this._label._elem.outerWidth(true)];
}
this._label.pack();
}
// draw the group labels, position top here, do left after label position.
var step = parseInt(this._ticks.length/this.groups, 10);
for (i=0; i<this._groupLabels.length; i++) {
var mid = 0;
var count = 0;
for (var j=i*step; j<=(i+1)*step; j++) {
if (this._ticks[j]._elem && this._ticks[j].label != " ") {
var t = this._ticks[j]._elem;
var p = t.position();
mid += p.top + t.outerHeight()/2;
count++;
}
}
mid = mid/count;
this._groupLabels[i].css({'top':mid - this._groupLabels[i].outerHeight()/2});
this._groupLabels[i].css(labeledge[0], labeledge[1]);
}
}
}
};
})(jQuery); | JavaScript |
/**
* Title: jqPlot Charts
*
* Pure JavaScript plotting plugin for jQuery.
*
* About: Version
*
* 1.0.0a_r701
*
* About: Copyright & License
*
* Copyright (c) 2009-2011 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT and GPL version 2.0 licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* See <GPL Version 2> and <MIT License> contained within this distribution for further information.
*
* The author would appreciate an email letting him know of any substantial
* use of jqPlot. You can reach the author at: chris at jqplot dot com
* or see http://www.jqplot.com/info.php. This is, of course, not required.
*
* If you are feeling kind and generous, consider supporting the project by
* making a donation at: http://www.jqplot.com/donate.php.
*
* sprintf functions contained in jqplot.sprintf.js by Ash Searle:
*
* version 2007.04.27
* author Ash Searle
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
* The author (Ash Searle) has placed this code in the public domain:
* "This code is unrestricted: you are free to use it however you like."
*
*
* About: Introduction
*
* jqPlot requires jQuery (1.4+ required for certain features). jQuery 1.4.2 is included in the distribution.
* To use jqPlot include jQuery, the jqPlot jQuery plugin, the jqPlot css file and optionally
* the excanvas script for IE support in your web page:
*
* > <!--[if IE]><script language="javascript" type="text/javascript" src="excanvas.js"></script><![endif]-->
* > <script language="javascript" type="text/javascript" src="jquery-1.4.4.min.js"></script>
* > <script language="javascript" type="text/javascript" src="jquery.jqplot.min.js"></script>
* > <link rel="stylesheet" type="text/css" href="jquery.jqplot.css" />
*
* jqPlot can be customized by overriding the defaults of any of the objects which make
* up the plot. The general usage of jqplot is:
*
* > chart = $.jqplot('targetElemId', [dataArray,...], {optionsObject});
*
* The options available to jqplot are detailed in <jqPlot Options> in the jqPlotOptions.txt file.
*
* An actual call to $.jqplot() may look like the
* examples below:
*
* > chart = $.jqplot('chartdiv', [[[1, 2],[3,5.12],[5,13.1],[7,33.6],[9,85.9],[11,219.9]]]);
*
* or
*
* > dataArray = [34,12,43,55,77];
* > chart = $.jqplot('targetElemId', [dataArray, ...], {title:'My Plot', axes:{yaxis:{min:20, max:100}}});
*
* For more inforrmation, see <jqPlot Usage>.
*
* About: Usage
*
* See <jqPlot Usage>
*
* About: Available Options
*
* See <jqPlot Options> for a list of options available thorugh the options object (not complete yet!)
*
* About: Options Usage
*
* See <Options Tutorial>
*
* About: Changes
*
* See <Change Log>
*
*/
(function($) {
// make sure undefined is undefined
var undefined;
/**
* Class: $.jqplot
* jQuery function called by the user to create a plot.
*
* Parameters:
* target - ID of target element to render the plot into.
* data - an array of data series.
* options - user defined options object. See the individual classes for available options.
*
* Properties:
* config - object to hold configuration information for jqPlot plot object.
*
* attributes:
* enablePlugins - False to disable plugins by default. Plugins must then be explicitly
* enabled in the individual plot options. Default: false.
* This property sets the "show" property of certain plugins to true or false.
* Only plugins that can be immediately active upon loading are affected. This includes
* non-renderer plugins like cursor, dragable, highlighter, and trendline.
* defaultHeight - Default height for plots where no css height specification exists. This
* is a jqplot wide default.
* defaultWidth - Default height for plots where no css height specification exists. This
* is a jqplot wide default.
*/
$.jqplot = function(target, data, options) {
var _data, _options;
if (options == null) {
if (jQuery.isArray(data)) {
_data = data;
_options = null;
}
else if (typeof(data) === 'object') {
_data = null;
_options = data;
}
}
else {
_data = data;
_options = options;
}
var plot = new jqPlot();
// remove any error class that may be stuck on target.
$('#'+target).removeClass('jqplot-error');
if ($.jqplot.config.catchErrors) {
try {
plot.init(target, _data, _options);
plot.draw();
plot.themeEngine.init.call(plot);
return plot;
}
catch(e) {
var msg = $.jqplot.config.errorMessage || e.message;
$('#'+target).append('<div class="jqplot-error-message">'+msg+'</div>');
$('#'+target).addClass('jqplot-error');
document.getElementById(target).style.background = $.jqplot.config.errorBackground;
document.getElementById(target).style.border = $.jqplot.config.errorBorder;
document.getElementById(target).style.fontFamily = $.jqplot.config.errorFontFamily;
document.getElementById(target).style.fontSize = $.jqplot.config.errorFontSize;
document.getElementById(target).style.fontStyle = $.jqplot.config.errorFontStyle;
document.getElementById(target).style.fontWeight = $.jqplot.config.errorFontWeight;
}
}
else {
plot.init(target, _data, _options);
plot.draw();
plot.themeEngine.init.call(plot);
return plot;
}
};
// Convienence function that won't hang IE of FF without FireBug.
$.jqplot.log = function() {
if (window.console) {
console.log.apply(console, arguments);
}
};
$.jqplot.config = {
enablePlugins:false,
defaultHeight:300,
defaultWidth:400,
UTCAdjust:false,
timezoneOffset: new Date(new Date().getTimezoneOffset() * 60000),
errorMessage: '',
errorBackground: '',
errorBorder: '',
errorFontFamily: '',
errorFontSize: '',
errorFontStyle: '',
errorFontWeight: '',
catchErrors: false,
defaultTickFormatString: "%.1f"
};
$.jqplot.arrayMax = function( array ){
return Math.max.apply( Math, array );
};
$.jqplot.arrayMin = function( array ){
return Math.min.apply( Math, array );
};
$.jqplot.enablePlugins = $.jqplot.config.enablePlugins;
// canvas related tests taken from modernizer:
// Copyright © 2009ñ2010 Faruk Ates.
// http://www.modernizr.com
$.jqplot.support_canvas = function() {
return !!document.createElement('canvas').getContext;
};
$.jqplot.support_canvas_text = function() {
return !!(document.createElement('canvas').getContext && typeof document.createElement('canvas').getContext('2d').fillText == 'function');
};
$.jqplot.use_excanvas = ($.browser.msie && !$.jqplot.support_canvas()) ? true : false;
/**
*
* Hooks: jqPlot Pugin Hooks
*
* $.jqplot.preInitHooks - called before initialization.
* $.jqplot.postInitHooks - called after initialization.
* $.jqplot.preParseOptionsHooks - called before user options are parsed.
* $.jqplot.postParseOptionsHooks - called after user options are parsed.
* $.jqplot.preDrawHooks - called before plot draw.
* $.jqplot.postDrawHooks - called after plot draw.
* $.jqplot.preDrawSeriesHooks - called before each series is drawn.
* $.jqplot.postDrawSeriesHooks - called after each series is drawn.
* $.jqplot.preDrawLegendHooks - called before the legend is drawn.
* $.jqplot.addLegendRowHooks - called at the end of legend draw, so plugins
* can add rows to the legend table.
* $.jqplot.preSeriesInitHooks - called before series is initialized.
* $.jqplot.postSeriesInitHooks - called after series is initialized.
* $.jqplot.preParseSeriesOptionsHooks - called before series related options
* are parsed.
* $.jqplot.postParseSeriesOptionsHooks - called after series related options
* are parsed.
* $.jqplot.eventListenerHooks - called at the end of plot drawing, binds
* listeners to the event canvas which lays on top of the grid area.
* $.jqplot.preDrawSeriesShadowHooks - called before series shadows are drawn.
* $.jqplot.postDrawSeriesShadowHooks - called after series shadows are drawn.
*
*/
$.jqplot.preInitHooks = [];
$.jqplot.postInitHooks = [];
$.jqplot.preParseOptionsHooks = [];
$.jqplot.postParseOptionsHooks = [];
$.jqplot.preDrawHooks = [];
$.jqplot.postDrawHooks = [];
$.jqplot.preDrawSeriesHooks = [];
$.jqplot.postDrawSeriesHooks = [];
$.jqplot.preDrawLegendHooks = [];
$.jqplot.addLegendRowHooks = [];
$.jqplot.preSeriesInitHooks = [];
$.jqplot.postSeriesInitHooks = [];
$.jqplot.preParseSeriesOptionsHooks = [];
$.jqplot.postParseSeriesOptionsHooks = [];
$.jqplot.eventListenerHooks = [];
$.jqplot.preDrawSeriesShadowHooks = [];
$.jqplot.postDrawSeriesShadowHooks = [];
// A superclass holding some common properties and methods.
$.jqplot.ElemContainer = function() {
this._elem;
this._plotWidth;
this._plotHeight;
this._plotDimensions = {height:null, width:null};
};
$.jqplot.ElemContainer.prototype.createElement = function(el, offsets, clss, cssopts, attrib) {
this._offsets = offsets;
var klass = clss || 'jqplot';
var elem = document.createElement(el);
this._elem = $(elem);
this._elem.addClass(klass);
this._elem.css(cssopts);
this._elem.attr(attrib);
// avoid memory leak;
elem = null;
return this._elem;
};
$.jqplot.ElemContainer.prototype.getWidth = function() {
if (this._elem) {
return this._elem.outerWidth(true);
}
else {
return null;
}
};
$.jqplot.ElemContainer.prototype.getHeight = function() {
if (this._elem) {
return this._elem.outerHeight(true);
}
else {
return null;
}
};
$.jqplot.ElemContainer.prototype.getPosition = function() {
if (this._elem) {
return this._elem.position();
}
else {
return {top:null, left:null, bottom:null, right:null};
}
};
$.jqplot.ElemContainer.prototype.getTop = function() {
return this.getPosition().top;
};
$.jqplot.ElemContainer.prototype.getLeft = function() {
return this.getPosition().left;
};
$.jqplot.ElemContainer.prototype.getBottom = function() {
return this._elem.css('bottom');
};
$.jqplot.ElemContainer.prototype.getRight = function() {
return this._elem.css('right');
};
/**
* Class: Axis
* An individual axis object. Cannot be instantiated directly, but created
* by the Plot oject. Axis properties can be set or overriden by the
* options passed in from the user.
*
*/
function Axis(name) {
$.jqplot.ElemContainer.call(this);
// Group: Properties
//
// Axes options are specified within an axes object at the top level of the
// plot options like so:
// > {
// > axes: {
// > xaxis: {min: 5},
// > yaxis: {min: 2, max: 8, numberTicks:4},
// > x2axis: {pad: 1.5},
// > y2axis: {ticks:[22, 44, 66, 88]}
// > }
// > }
// There are 4 axes, 'xaxis', 'yaxis', 'x2axis', 'y2axis'. Any or all of
// which may be specified.
this.name = name;
this._series = [];
// prop: show
// Wether to display the axis on the graph.
this.show = false;
// prop: tickRenderer
// A class of a rendering engine for creating the ticks labels displayed on the plot,
// See <$.jqplot.AxisTickRenderer>.
this.tickRenderer = $.jqplot.AxisTickRenderer;
// prop: tickOptions
// Options that will be passed to the tickRenderer, see <$.jqplot.AxisTickRenderer> options.
this.tickOptions = {};
// prop: labelRenderer
// A class of a rendering engine for creating an axis label.
this.labelRenderer = $.jqplot.AxisLabelRenderer;
// prop: labelOptions
// Options passed to the label renderer.
this.labelOptions = {};
// prop: label
// Label for the axis
this.label = null;
// prop: showLabel
// true to show the axis label.
this.showLabel = true;
// prop: min
// minimum value of the axis (in data units, not pixels).
this.min=null;
// prop: max
// maximum value of the axis (in data units, not pixels).
this.max=null;
// prop: autoscale
// Autoscale the axis min and max values to provide sensible tick spacing.
// If axis min or max are set, autoscale will be turned off.
// The numberTicks, tickInterval and pad options do work with
// autoscale, although tickInterval has not been tested yet.
// padMin and padMax do nothing when autoscale is on.
this.autoscale = false;
// prop: pad
// Padding to extend the range above and below the data bounds.
// The data range is multiplied by this factor to determine minimum and maximum axis bounds.
// A value of 0 will be interpreted to mean no padding, and pad will be set to 1.0.
this.pad = 1.2;
// prop: padMax
// Padding to extend the range above data bounds.
// The top of the data range is multiplied by this factor to determine maximum axis bounds.
// A value of 0 will be interpreted to mean no padding, and padMax will be set to 1.0.
this.padMax = null;
// prop: padMin
// Padding to extend the range below data bounds.
// The bottom of the data range is multiplied by this factor to determine minimum axis bounds.
// A value of 0 will be interpreted to mean no padding, and padMin will be set to 1.0.
this.padMin = null;
// prop: ticks
// 1D [val, val, ...] or 2D [[val, label], [val, label], ...] array of ticks for the axis.
// If no label is specified, the value is formatted into an appropriate label.
this.ticks = [];
// prop: numberTicks
// Desired number of ticks. Default is to compute automatically.
this.numberTicks;
// prop: tickInterval
// number of units between ticks. Mutually exclusive with numberTicks.
this.tickInterval;
// prop: renderer
// A class of a rendering engine that handles tick generation,
// scaling input data to pixel grid units and drawing the axis element.
this.renderer = $.jqplot.LinearAxisRenderer;
// prop: rendererOptions
// renderer specific options. See <$.jqplot.LinearAxisRenderer> for options.
this.rendererOptions = {};
// prop: showTicks
// Wether to show the ticks (both marks and labels) or not.
// Will not override showMark and showLabel options if specified on the ticks themselves.
this.showTicks = true;
// prop: showTickMarks
// Wether to show the tick marks (line crossing grid) or not.
// Overridden by showTicks and showMark option of tick itself.
this.showTickMarks = true;
// prop: showMinorTicks
// Wether or not to show minor ticks. This is renderer dependent.
// The default <$.jqplot.LinearAxisRenderer> does not have minor ticks.
this.showMinorTicks = true;
// prop: useSeriesColor
// Use the color of the first series associated with this axis for the
// tick marks and line bordering this axis.
this.useSeriesColor = false;
// prop: borderWidth
// width of line stroked at the border of the axis. Defaults
// to the width of the grid boarder.
this.borderWidth = null;
// prop: borderColor
// color of the border adjacent to the axis. Defaults to grid border color.
this.borderColor = null;
// minimum and maximum values on the axis.
this._dataBounds = {min:null, max:null};
// statistics (min, max, mean) as well as actual data intervals for each series attached to axis.
// holds collection of {intervals:[], min:, max:, mean: } objects for each series on axis.
this._intervalStats = [];
// pixel position from the top left of the min value and max value on the axis.
this._offsets = {min:null, max:null};
this._ticks=[];
this._label = null;
// prop: syncTicks
// true to try and synchronize tick spacing across multiple axes so that ticks and
// grid lines line up. This has an impact on autoscaling algorithm, however.
// In general, autoscaling an individual axis will work better if it does not
// have to sync ticks.
this.syncTicks = null;
// prop: tickSpacing
// Approximate pixel spacing between ticks on graph. Used during autoscaling.
// This number will be an upper bound, actual spacing will be less.
this.tickSpacing = 75;
// Properties to hold the original values for min, max, ticks, tickInterval and numberTicks
// so they can be restored if altered by plugins.
this._min = null;
this._max = null;
this._tickInterval = null;
this._numberTicks = null;
this.__ticks = null;
}
Axis.prototype = new $.jqplot.ElemContainer();
Axis.prototype.constructor = Axis;
Axis.prototype.init = function() {
this.renderer = new this.renderer();
// set the axis name
this.tickOptions.axis = this.name;
// if showMark or showLabel tick options not specified, use value of axis option.
// showTicks overrides showTickMarks.
if (this.tickOptions.showMark == null) {
this.tickOptions.showMark = this.showTicks;
}
if (this.tickOptions.showMark == null) {
this.tickOptions.showMark = this.showTickMarks;
}
if (this.tickOptions.showLabel == null) {
this.tickOptions.showLabel = this.showTicks;
}
if (this.label == null || this.label == '') {
this.showLabel = false;
}
else {
this.labelOptions.label = this.label;
}
if (this.showLabel == false) {
this.labelOptions.show = false;
}
// set the default padMax, padMin if not specified
// special check, if no padding desired, padding
// should be set to 1.0
if (this.pad == 0) {
this.pad = 1.0;
}
if (this.padMax == 0) {
this.padMax = 1.0;
}
if (this.padMin == 0) {
this.padMin = 1.0;
}
if (this.padMax == null) {
this.padMax = (this.pad-1)/2 + 1;
}
if (this.padMin == null) {
this.padMin = (this.pad-1)/2 + 1;
}
// now that padMin and padMax are correctly set, reset pad in case user has supplied
// padMin and/or padMax
this.pad = this.padMax + this.padMin - 1;
if (this.min != null || this.max != null) {
this.autoscale = false;
}
// if not set, sync ticks for y axes but not x by default.
if (this.syncTicks == null && this.name.indexOf('y') > -1) {
this.syncTicks = true;
}
else if (this.syncTicks == null){
this.syncTicks = false;
}
this.renderer.init.call(this, this.rendererOptions);
};
Axis.prototype.draw = function(ctx) {
return this.renderer.draw.call(this, ctx);
};
Axis.prototype.set = function() {
this.renderer.set.call(this);
};
Axis.prototype.pack = function(pos, offsets) {
if (this.show) {
this.renderer.pack.call(this, pos, offsets);
}
// these properties should all be available now.
if (this._min == null) {
this._min = this.min;
this._max = this.max;
this._tickInterval = this.tickInterval;
this._numberTicks = this.numberTicks;
this.__ticks = this._ticks;
}
};
// reset the axis back to original values if it has been scaled, zoomed, etc.
Axis.prototype.reset = function() {
this.renderer.reset.call(this);
};
Axis.prototype.resetScale = function(opts) {
$.extend(true, this, {min: null, max: null, numberTicks: null, tickInterval: null, _ticks: [], ticks: []}, opts);
this.resetDataBounds();
};
Axis.prototype.resetDataBounds = function() {
// Go through all the series attached to this axis and find
// the min/max bounds for this axis.
var db = this._dataBounds;
db.min = null;
db.max = null;
for (var i=0; i<this._series.length; i++) {
var s = this._series[i];
var d = s._plotData;
for (var j=0; j<d.length; j++) {
if (this.name == 'xaxis' || this.name == 'x2axis') {
if ((d[j][0] != null && d[j][0] < db.min) || db.min == null) {
db.min = d[j][0];
}
if ((d[j][0] != null && d[j][0] > db.max) || db.max == null) {
db.max = d[j][0];
}
}
else {
if ((d[j][1] != null && d[j][1] < db.min) || db.min == null) {
db.min = d[j][1];
}
if ((d[j][1] != null && d[j][1] > db.max) || db.max == null) {
db.max = d[j][1];
}
}
}
}
};
/**
* Class: Legend
* Legend object. Cannot be instantiated directly, but created
* by the Plot oject. Legend properties can be set or overriden by the
* options passed in from the user.
*/
function Legend(options) {
$.jqplot.ElemContainer.call(this);
// Group: Properties
// prop: show
// Wether to display the legend on the graph.
this.show = false;
// prop: location
// Placement of the legend. one of the compass directions: nw, n, ne, e, se, s, sw, w
this.location = 'ne';
// prop: labels
// Array of labels to use. By default the renderer will look for labels on the series.
// Labels specified in this array will override labels specified on the series.
this.labels = [];
// prop: showLabels
// true to show the label text on the legend.
this.showLabels = true;
// prop: showSwatch
// true to show the color swatches on the legend.
this.showSwatches = true;
// prop: placement
// "insideGrid" places legend inside the grid area of the plot.
// "outsideGrid" places the legend outside the grid but inside the plot container,
// shrinking the grid to accomodate the legend.
// "inside" synonym for "insideGrid",
// "outside" places the legend ouside the grid area, but does not shrink the grid which
// can cause the legend to overflow the plot container.
this.placement = "insideGrid";
// prop: xoffset
// DEPRECATED. Set the margins on the legend using the marginTop, marginLeft, etc.
// properties or via CSS margin styling of the .jqplot-table-legend class.
this.xoffset = 0;
// prop: yoffset
// DEPRECATED. Set the margins on the legend using the marginTop, marginLeft, etc.
// properties or via CSS margin styling of the .jqplot-table-legend class.
this.yoffset = 0;
// prop: border
// css spec for the border around the legend box.
this.border;
// prop: background
// css spec for the background of the legend box.
this.background;
// prop: textColor
// css color spec for the legend text.
this.textColor;
// prop: fontFamily
// css font-family spec for the legend text.
this.fontFamily;
// prop: fontSize
// css font-size spec for the legend text.
this.fontSize ;
// prop: rowSpacing
// css padding-top spec for the rows in the legend.
this.rowSpacing = '0.5em';
// renderer
// A class that will create a DOM object for the legend,
// see <$.jqplot.TableLegendRenderer>.
this.renderer = $.jqplot.TableLegendRenderer;
// prop: rendererOptions
// renderer specific options passed to the renderer.
this.rendererOptions = {};
// prop: predraw
// Wether to draw the legend before the series or not.
// Used with series specific legend renderers for pie, donut, mekko charts, etc.
this.preDraw = false;
// prop: marginTop
// CSS margin for the legend DOM element. This will set an element
// CSS style for the margin which will override any style sheet setting.
// The default will be taken from the stylesheet.
this.marginTop = null;
// prop: marginRight
// CSS margin for the legend DOM element. This will set an element
// CSS style for the margin which will override any style sheet setting.
// The default will be taken from the stylesheet.
this.marginRight = null;
// prop: marginBottom
// CSS margin for the legend DOM element. This will set an element
// CSS style for the margin which will override any style sheet setting.
// The default will be taken from the stylesheet.
this.marginBottom = null;
// prop: marginLeft
// CSS margin for the legend DOM element. This will set an element
// CSS style for the margin which will override any style sheet setting.
// The default will be taken from the stylesheet.
this.marginLeft = null;
this.escapeHtml = false;
this._series = [];
$.extend(true, this, options);
}
Legend.prototype = new $.jqplot.ElemContainer();
Legend.prototype.constructor = Legend;
Legend.prototype.setOptions = function(options) {
$.extend(true, this, options);
// Try to emulate deprecated behaviour
// if user has specified xoffset or yoffset, copy these to
// the margin properties.
if (this.placement == 'inside') {
this.placement = 'insideGrid';
}
if (this.xoffset >0) {
if (this.placement == 'insideGrid') {
switch (this.location) {
case 'nw':
case 'w':
case 'sw':
if (this.marginLeft == null) {
this.marginLeft = this.xoffset + 'px';
}
this.marginRight = '0px';
break;
case 'ne':
case 'e':
case 'se':
default:
if (this.marginRight == null) {
this.marginRight = this.xoffset + 'px';
}
this.marginLeft = '0px';
break;
}
}
else if (this.placement == 'outside') {
switch (this.location) {
case 'nw':
case 'w':
case 'sw':
if (this.marginRight == null) {
this.marginRight = this.xoffset + 'px';
}
this.marginLeft = '0px';
break;
case 'ne':
case 'e':
case 'se':
default:
if (this.marginLeft == null) {
this.marginLeft = this.xoffset + 'px';
}
this.marginRight = '0px';
break;
}
}
this.xoffset = 0;
}
if (this.yoffset >0) {
if (this.placement == 'outside') {
switch (this.location) {
case 'sw':
case 's':
case 'se':
if (this.marginTop == null) {
this.marginTop = this.yoffset + 'px';
}
this.marginBottom = '0px';
break;
case 'ne':
case 'n':
case 'nw':
default:
if (this.marginBottom == null) {
this.marginBottom = this.yoffset + 'px';
}
this.marginTop = '0px';
break;
}
}
else if (this.placement == 'insideGrid') {
switch (this.location) {
case 'sw':
case 's':
case 'se':
if (this.marginBottom == null) {
this.marginBottom = this.yoffset + 'px';
}
this.marginTop = '0px';
break;
case 'ne':
case 'n':
case 'nw':
default:
if (this.marginTop == null) {
this.marginTop = this.yoffset + 'px';
}
this.marginBottom = '0px';
break;
}
}
this.yoffset = 0;
}
// TO-DO:
// Handle case where offsets are < 0.
//
};
Legend.prototype.init = function() {
this.renderer = new this.renderer();
this.renderer.init.call(this, this.rendererOptions);
};
Legend.prototype.draw = function(offsets) {
for (var i=0; i<$.jqplot.preDrawLegendHooks.length; i++){
$.jqplot.preDrawLegendHooks[i].call(this, offsets);
}
return this.renderer.draw.call(this, offsets);
};
Legend.prototype.pack = function(offsets) {
this.renderer.pack.call(this, offsets);
};
/**
* Class: Title
* Plot Title object. Cannot be instantiated directly, but created
* by the Plot oject. Title properties can be set or overriden by the
* options passed in from the user.
*
* Parameters:
* text - text of the title.
*/
function Title(text) {
$.jqplot.ElemContainer.call(this);
// Group: Properties
// prop: text
// text of the title;
this.text = text;
// prop: show
// wether or not to show the title
this.show = true;
// prop: fontFamily
// css font-family spec for the text.
this.fontFamily;
// prop: fontSize
// css font-size spec for the text.
this.fontSize ;
// prop: textAlign
// css text-align spec for the text.
this.textAlign;
// prop: textColor
// css color spec for the text.
this.textColor;
// prop: renderer
// A class for creating a DOM element for the title,
// see <$.jqplot.DivTitleRenderer>.
this.renderer = $.jqplot.DivTitleRenderer;
// prop: rendererOptions
// renderer specific options passed to the renderer.
this.rendererOptions = {};
}
Title.prototype = new $.jqplot.ElemContainer();
Title.prototype.constructor = Title;
Title.prototype.init = function() {
this.renderer = new this.renderer();
this.renderer.init.call(this, this.rendererOptions);
};
Title.prototype.draw = function(width) {
return this.renderer.draw.call(this, width);
};
Title.prototype.pack = function() {
this.renderer.pack.call(this);
};
/**
* Class: Series
* An individual data series object. Cannot be instantiated directly, but created
* by the Plot oject. Series properties can be set or overriden by the
* options passed in from the user.
*/
function Series() {
$.jqplot.ElemContainer.call(this);
// Group: Properties
// Properties will be assigned from a series array at the top level of the
// options. If you had two series and wanted to change the color and line
// width of the first and set the second to use the secondary y axis with
// no shadow and supply custom labels for each:
// > {
// > series:[
// > {color: '#ff4466', lineWidth: 5, label:'good line'},
// > {yaxis: 'y2axis', shadow: false, label:'bad line'}
// > ]
// > }
// prop: show
// wether or not to draw the series.
this.show = true;
// prop: xaxis
// which x axis to use with this series, either 'xaxis' or 'x2axis'.
this.xaxis = 'xaxis';
this._xaxis;
// prop: yaxis
// which y axis to use with this series, either 'yaxis' or 'y2axis'.
this.yaxis = 'yaxis';
this._yaxis;
this.gridBorderWidth = 2.0;
// prop: renderer
// A class of a renderer which will draw the series,
// see <$.jqplot.LineRenderer>.
this.renderer = $.jqplot.LineRenderer;
// prop: rendererOptions
// Options to pass on to the renderer.
this.rendererOptions = {};
this.data = [];
this.gridData = [];
// prop: label
// Line label to use in the legend.
this.label = '';
// prop: showLabel
// true to show label for this series in the legend.
this.showLabel = true;
// prop: color
// css color spec for the series
this.color;
// prop: lineWidth
// width of the line in pixels. May have different meanings depending on renderer.
this.lineWidth = 2.5;
// prop: shadow
// wether or not to draw a shadow on the line
this.shadow = true;
// prop: shadowAngle
// Shadow angle in degrees
this.shadowAngle = 45;
// prop: shadowOffset
// Shadow offset from line in pixels
this.shadowOffset = 1.25;
// prop: shadowDepth
// Number of times shadow is stroked, each stroke offset shadowOffset from the last.
this.shadowDepth = 3;
// prop: shadowAlpha
// Alpha channel transparency of shadow. 0 = transparent.
this.shadowAlpha = '0.1';
// prop: breakOnNull
// Not implemented. wether line segments should be be broken at null value.
// False will join point on either side of line.
this.breakOnNull = false;
// prop: markerRenderer
// A class of a renderer which will draw marker (e.g. circle, square, ...) at the data points,
// see <$.jqplot.MarkerRenderer>.
this.markerRenderer = $.jqplot.MarkerRenderer;
// prop: markerOptions
// renderer specific options to pass to the markerRenderer,
// see <$.jqplot.MarkerRenderer>.
this.markerOptions = {};
// prop: showLine
// wether to actually draw the line or not. Series will still be renderered, even if no line is drawn.
this.showLine = true;
// prop: showMarker
// wether or not to show the markers at the data points.
this.showMarker = true;
// prop: index
// 0 based index of this series in the plot series array.
this.index;
// prop: fill
// true or false, wether to fill under lines or in bars.
// May not be implemented in all renderers.
this.fill = false;
// prop: fillColor
// CSS color spec to use for fill under line. Defaults to line color.
this.fillColor;
// prop: fillAlpha
// Alpha transparency to apply to the fill under the line.
// Use this to adjust alpha separate from fill color.
this.fillAlpha;
// prop: fillAndStroke
// If true will stroke the line (with color this.color) as well as fill under it.
// Applies only when fill is true.
this.fillAndStroke = false;
// prop: disableStack
// true to not stack this series with other series in the plot.
// To render properly, non-stacked series must come after any stacked series
// in the plot's data series array. So, the plot's data series array would look like:
// > [stackedSeries1, stackedSeries2, ..., nonStackedSeries1, nonStackedSeries2, ...]
// disableStack will put a gap in the stacking order of series, and subsequent
// stacked series will not fill down through the non-stacked series and will
// most likely not stack properly on top of the non-stacked series.
this.disableStack = false;
// _stack is set by the Plot if the plot is a stacked chart.
// will stack lines or bars on top of one another to build a "mountain" style chart.
// May not be implemented in all renderers.
this._stack = false;
// prop: neighborThreshold
// how close or far (in pixels) the cursor must be from a point marker to detect the point.
this.neighborThreshold = 4;
// prop: fillToZero
// true will force bar and filled series to fill toward zero on the fill Axis.
this.fillToZero = false;
// prop: fillToValue
// fill a filled series to this value on the fill axis.
// Works in conjunction with fillToZero, so that must be true.
this.fillToValue = 0;
// prop: fillAxis
// Either 'x' or 'y'. Which axis to fill the line toward if fillToZero is true.
// 'y' means fill up/down to 0 on the y axis for this series.
this.fillAxis = 'y';
// prop: useNegativeColors
// true to color negative values differently in filled and bar charts.
this.useNegativeColors = true;
this._stackData = [];
// _plotData accounts for stacking. If plots not stacked, _plotData and data are same. If
// stacked, _plotData is accumulation of stacking data.
this._plotData = [];
// _plotValues hold the individual x and y values that will be plotted for this series.
this._plotValues = {x:[], y:[]};
// statistics about the intervals between data points. Used for auto scaling.
this._intervals = {x:{}, y:{}};
// data from the previous series, for stacked charts.
this._prevPlotData = [];
this._prevGridData = [];
this._stackAxis = 'y';
this._primaryAxis = '_xaxis';
// give each series a canvas to draw on. This should allow for redrawing speedups.
this.canvas = new $.jqplot.GenericCanvas();
this.shadowCanvas = new $.jqplot.GenericCanvas();
this.plugins = {};
// sum of y values in this series.
this._sumy = 0;
this._sumx = 0;
}
Series.prototype = new $.jqplot.ElemContainer();
Series.prototype.constructor = Series;
Series.prototype.init = function(index, gridbw, plot) {
// weed out any null values in the data.
this.index = index;
this.gridBorderWidth = gridbw;
var d = this.data;
var temp = [], i;
for (i=0; i<d.length; i++) {
if (! this.breakOnNull) {
if (d[i] == null || d[i][0] == null || d[i][1] == null) {
continue;
}
else {
temp.push(d[i]);
}
}
else {
// TODO: figure out what to do with null values
// probably involve keeping nulls in data array
// and then updating renderers to break line
// when it hits null value.
// For now, just keep value.
temp.push(d[i]);
}
}
this.data = temp;
if (!this.fillColor) {
this.fillColor = this.color;
}
if (this.fillAlpha) {
var comp = $.jqplot.normalize2rgb(this.fillColor);
var comp = $.jqplot.getColorComponents(comp);
this.fillColor = 'rgba('+comp[0]+','+comp[1]+','+comp[2]+','+this.fillAlpha+')';
}
this.renderer = new this.renderer();
this.renderer.init.call(this, this.rendererOptions, plot);
this.markerRenderer = new this.markerRenderer();
if (!this.markerOptions.color) {
this.markerOptions.color = this.color;
}
if (this.markerOptions.show == null) {
this.markerOptions.show = this.showMarker;
}
this.showMarker = this.markerOptions.show;
// the markerRenderer is called within it's own scaope, don't want to overwrite series options!!
this.markerRenderer.init(this.markerOptions);
};
// data - optional data point array to draw using this series renderer
// gridData - optional grid data point array to draw using this series renderer
// stackData - array of cumulative data for stacked plots.
Series.prototype.draw = function(sctx, opts, plot) {
var options = (opts == undefined) ? {} : opts;
sctx = (sctx == undefined) ? this.canvas._ctx : sctx;
var j, data, gridData;
// hooks get called even if series not shown
// we don't clear canvas here, it would wipe out all other series as well.
for (j=0; j<$.jqplot.preDrawSeriesHooks.length; j++) {
$.jqplot.preDrawSeriesHooks[j].call(this, sctx, options);
}
if (this.show) {
this.renderer.setGridData.call(this, plot);
if (!options.preventJqPlotSeriesDrawTrigger) {
$(sctx.canvas).trigger('jqplotSeriesDraw', [this.data, this.gridData]);
}
data = [];
if (options.data) {
data = options.data;
}
else if (!this._stack) {
data = this.data;
}
else {
data = this._plotData;
}
gridData = options.gridData || this.renderer.makeGridData.call(this, data, plot);
this.renderer.draw.call(this, sctx, gridData, options, plot);
}
for (j=0; j<$.jqplot.postDrawSeriesHooks.length; j++) {
$.jqplot.postDrawSeriesHooks[j].call(this, sctx, options);
}
sctx = opts = plot = j = data = gridData = null;
};
Series.prototype.drawShadow = function(sctx, opts, plot) {
var options = (opts == undefined) ? {} : opts;
sctx = (sctx == undefined) ? this.shadowCanvas._ctx : sctx;
var j, data, gridData;
// hooks get called even if series not shown
// we don't clear canvas here, it would wipe out all other series as well.
for (j=0; j<$.jqplot.preDrawSeriesShadowHooks.length; j++) {
$.jqplot.preDrawSeriesShadowHooks[j].call(this, sctx, options);
}
if (this.shadow) {
this.renderer.setGridData.call(this, plot);
data = [];
if (options.data) {
data = options.data;
}
else if (!this._stack) {
data = this.data;
}
else {
data = this._plotData;
}
gridData = options.gridData || this.renderer.makeGridData.call(this, data, plot);
this.renderer.drawShadow.call(this, sctx, gridData, options);
}
for (j=0; j<$.jqplot.postDrawSeriesShadowHooks.length; j++) {
$.jqplot.postDrawSeriesShadowHooks[j].call(this, sctx, options);
}
sctx = opts = plot = j = data = gridData = null;
};
// toggles series display on plot, e.g. show/hide series
Series.prototype.toggleDisplay = function(ev) {
var s, speed;
if (ev.data.series) {
s = ev.data.series;
}
else {
s = this;
}
if (ev.data.speed) {
speed = ev.data.speed;
}
if (speed) {
if (s.canvas._elem.is(':hidden')) {
if (s.shadowCanvas._elem) {
s.shadowCanvas._elem.fadeIn(speed);
}
s.canvas._elem.fadeIn(speed);
s.canvas._elem.nextAll('.jqplot-point-label.jqplot-series-'+s.index).fadeIn(speed);
}
else {
if (s.shadowCanvas._elem) {
s.shadowCanvas._elem.fadeOut(speed);
}
s.canvas._elem.fadeOut(speed);
s.canvas._elem.nextAll('.jqplot-point-label.jqplot-series-'+s.index).fadeOut(speed);
}
}
else {
if (s.canvas._elem.is(':hidden')) {
if (s.shadowCanvas._elem) {
s.shadowCanvas._elem.show();
}
s.canvas._elem.show();
s.canvas._elem.nextAll('.jqplot-point-label.jqplot-series-'+s.index).show();
}
else {
if (s.shadowCanvas._elem) {
s.shadowCanvas._elem.hide();
}
s.canvas._elem.hide();
s.canvas._elem.nextAll('.jqplot-point-label.jqplot-series-'+s.index).hide();
}
}
};
/**
* Class: Grid
*
* Object representing the grid on which the plot is drawn. The grid in this
* context is the area bounded by the axes, the area which will contain the series.
* Note, the series are drawn on their own canvas.
* The Grid object cannot be instantiated directly, but is created by the Plot oject.
* Grid properties can be set or overriden by the options passed in from the user.
*/
function Grid() {
$.jqplot.ElemContainer.call(this);
// Group: Properties
// prop: drawGridlines
// wether to draw the gridlines on the plot.
this.drawGridlines = true;
// prop: gridLineColor
// color of the grid lines.
this.gridLineColor = '#cccccc';
// prop: gridLineWidth
// width of the grid lines.
this.gridLineWidth = 1.0;
// prop: background
// css spec for the background color.
this.background = '#fffdf6';
// prop: borderColor
// css spec for the color of the grid border.
this.borderColor = '#999999';
// prop: borderWidth
// width of the border in pixels.
this.borderWidth = 2.0;
// prop: drawBorder
// True to draw border around grid.
this.drawBorder = true;
// prop: shadow
// wether to show a shadow behind the grid.
this.shadow = true;
// prop: shadowAngle
// shadow angle in degrees
this.shadowAngle = 45;
// prop: shadowOffset
// Offset of each shadow stroke from the border in pixels
this.shadowOffset = 1.5;
// prop: shadowWidth
// width of the stoke for the shadow
this.shadowWidth = 3;
// prop: shadowDepth
// Number of times shadow is stroked, each stroke offset shadowOffset from the last.
this.shadowDepth = 3;
// prop: shadowColor
// an optional css color spec for the shadow in 'rgba(n, n, n, n)' form
this.shadowColor = null;
// prop: shadowAlpha
// Alpha channel transparency of shadow. 0 = transparent.
this.shadowAlpha = '0.07';
this._left;
this._top;
this._right;
this._bottom;
this._width;
this._height;
this._axes = [];
// prop: renderer
// Instance of a renderer which will actually render the grid,
// see <$.jqplot.CanvasGridRenderer>.
this.renderer = $.jqplot.CanvasGridRenderer;
// prop: rendererOptions
// Options to pass on to the renderer,
// see <$.jqplot.CanvasGridRenderer>.
this.rendererOptions = {};
this._offsets = {top:null, bottom:null, left:null, right:null};
}
Grid.prototype = new $.jqplot.ElemContainer();
Grid.prototype.constructor = Grid;
Grid.prototype.init = function() {
this.renderer = new this.renderer();
this.renderer.init.call(this, this.rendererOptions);
};
Grid.prototype.createElement = function(offsets) {
this._offsets = offsets;
return this.renderer.createElement.call(this);
};
Grid.prototype.draw = function() {
this.renderer.draw.call(this);
};
$.jqplot.GenericCanvas = function() {
$.jqplot.ElemContainer.call(this);
this._ctx;
};
$.jqplot.GenericCanvas.prototype = new $.jqplot.ElemContainer();
$.jqplot.GenericCanvas.prototype.constructor = $.jqplot.GenericCanvas;
$.jqplot.GenericCanvas.prototype.createElement = function(offsets, clss, plotDimensions) {
this._offsets = offsets;
var klass = 'jqplot';
if (clss != undefined) {
klass = clss;
}
var elem;
// if this canvas already has a dom element, don't make a new one.
if (this._elem) {
elem = this._elem.get(0);
}
else {
elem = document.createElement('canvas');
}
// if new plotDimensions supplied, use them.
if (plotDimensions != undefined) {
this._plotDimensions = plotDimensions;
}
elem.width = this._plotDimensions.width - this._offsets.left - this._offsets.right;
elem.height = this._plotDimensions.height - this._offsets.top - this._offsets.bottom;
this._elem = $(elem);
this._elem.css({ position: 'absolute', left: this._offsets.left, top: this._offsets.top });
this._elem.addClass(klass);
if ($.jqplot.use_excanvas) {
window.G_vmlCanvasManager.init_(document);
elem = window.G_vmlCanvasManager.initElement(elem);
}
// avoid memory leak
elem = null;
return this._elem;
};
$.jqplot.GenericCanvas.prototype.setContext = function() {
this._ctx = this._elem.get(0).getContext("2d");
return this._ctx;
};
$.jqplot.HooksManager = function () {
this.hooks =[];
};
$.jqplot.HooksManager.prototype.addOnce = function(fn) {
var havehook = false, i;
for (i=0; i<this.hooks.length; i++) {
if (this.hooks[i][0] == fn) {
havehook = true;
}
}
if (!havehook) {
this.hooks.push(fn);
}
};
$.jqplot.HooksManager.prototype.add = function(fn) {
this.hooks.push(fn);
};
$.jqplot.EventListenerManager = function () {
this.hooks =[];
};
$.jqplot.EventListenerManager.prototype.addOnce = function(ev, fn) {
var havehook = false, h, i;
for (i=0; i<this.hooks.length; i++) {
h = this.hooks[i];
if (h[0] == ev && h[1] == fn) {
havehook = true;
}
}
if (!havehook) {
this.hooks.push([ev, fn]);
}
};
$.jqplot.EventListenerManager.prototype.add = function(ev, fn) {
this.hooks.push([ev, fn]);
};
/**
* Class: jqPlot
* Plot object returned by call to $.jqplot. Handles parsing user options,
* creating sub objects (Axes, legend, title, series) and rendering the plot.
*/
function jqPlot() {
// Group: Properties
// These properties are specified at the top of the options object
// like so:
// > {
// > axesDefaults:{min:0},
// > series:[{color:'#6633dd'}],
// > title: 'A Plot'
// > }
//
// prop: data
// user's data. Data should *NOT* be specified in the options object,
// but be passed in as the second argument to the $.jqplot() function.
// The data property is described here soley for reference.
// The data should be in the form of an array of 2D or 1D arrays like
// > [ [[x1, y1], [x2, y2],...], [y1, y2, ...] ].
this.data = [];
// prop dataRenderer
// A callable which can be used to preprocess data passed into the plot.
// Will be called with 2 arguments, the plot data and a reference to the plot.
this.dataRenderer;
// prop dataRendererOptions
// Options that will be passed to the dataRenderer.
// Can be of any type.
this.dataRendererOptions;
// prop noDataIndicator
// Options to set up a mock plot with a data loading indicator if no data is specified.
this.noDataIndicator = {
show: false,
indicator: 'Loading Data...',
axes: {
xaxis: {
min: 0,
max: 10,
tickInterval: 2,
show: true
},
yaxis: {
min: 0,
max: 12,
tickInterval: 3,
show: true
}
}
};
// The id of the dom element to render the plot into
this.targetId = null;
// the jquery object for the dom target.
this.target = null;
this.defaults = {
// prop: axesDefaults
// default options that will be applied to all axes.
// see <Axis> for axes options.
axesDefaults: {},
axes: {xaxis:{}, yaxis:{}, x2axis:{}, y2axis:{}, y3axis:{}, y4axis:{}, y5axis:{}, y6axis:{}, y7axis:{}, y8axis:{}, y9axis:{}},
// prop: seriesDefaults
// default options that will be applied to all series.
// see <Series> for series options.
seriesDefaults: {},
series:[]
};
// prop: series
// Array of series object options.
// see <Series> for series specific options.
this.series = [];
// prop: axes
// up to 4 axes are supported, each with it's own options,
// See <Axis> for axis specific options.
this.axes = {xaxis: new Axis('xaxis'), yaxis: new Axis('yaxis'), x2axis: new Axis('x2axis'), y2axis: new Axis('y2axis'), y3axis: new Axis('y3axis'), y4axis: new Axis('y4axis'), y5axis: new Axis('y5axis'), y6axis: new Axis('y6axis'), y7axis: new Axis('y7axis'), y8axis: new Axis('y8axis'), y9axis: new Axis('y9axis')};
// prop: grid
// See <Grid> for grid specific options.
this.grid = new Grid();
// prop: legend
// see <$.jqplot.TableLegendRenderer>
this.legend = new Legend();
this.baseCanvas = new $.jqplot.GenericCanvas();
// array of series indicies. Keep track of order
// which series canvases are displayed, lowest
// to highest, back to front.
this.seriesStack = [];
this.previousSeriesStack = [];
this.eventCanvas = new $.jqplot.GenericCanvas();
this._width = null;
this._height = null;
this._plotDimensions = {height:null, width:null};
this._gridPadding = {top:null, right:null, bottom:null, left:null};
this._defaultGridPadding = {top:10, right:10, bottom:23, left:10};
// a shortcut for axis syncTicks options. Not implemented yet.
this.syncXTicks = true;
// a shortcut for axis syncTicks options. Not implemented yet.
this.syncYTicks = true;
// prop: seriesColors
// Ann array of CSS color specifications that will be applied, in order,
// to the series in the plot. Colors will wrap around so, if their
// are more series than colors, colors will be reused starting at the
// beginning. For pie charts, this specifies the colors of the slices.
this.seriesColors = [ "#4bb2c5", "#EAA228", "#c5b47f", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc", "#c747a3", "#cddf54", "#FBD178", "#26B4E3", "#bd70c7"];
this.negativeSeriesColors = [ "#498991", "#C08840", "#9F9274", "#546D61", "#646C4A", "#6F6621", "#6E3F5F", "#4F64B0", "#A89050", "#C45923", "#187399", "#945381", "#959E5C", "#C7AF7B", "#478396", "#907294"];
// prop: sortData
// false to not sort the data passed in by the user.
// Many bar, stakced and other graphs as well as many plugins depend on
// having sorted data.
this.sortData = true;
var seriesColorsIndex = 0;
// prop textColor
// css spec for the css color attribute. Default for the entire plot.
this.textColor;
// prop; fontFamily
// css spec for the font-family attribute. Default for the entire plot.
this.fontFamily;
// prop: fontSize
// css spec for the font-size attribute. Default for the entire plot.
this.fontSize;
// prop: title
// Title object. See <Title> for specific options. As a shortcut, you
// can specify the title option as just a string like: title: 'My Plot'
// and this will create a new title object with the specified text.
this.title = new Title();
// container to hold all of the merged options. Convienence for plugins.
this.options = {};
// prop: stackSeries
// true or false, creates a stack or "mountain" plot.
// Not all series renderers may implement this option.
this.stackSeries = false;
// prop: defaultAxisStart
// 1-D data series are internally converted into 2-D [x,y] data point arrays
// by jqPlot. This is the default starting value for the missing x or y value.
// The added data will be a monotonically increasing series (e.g. [1, 2, 3, ...])
// starting at this value.
this.defaultAxisStart = 1;
// array to hold the cumulative stacked series data.
// used to ajust the individual series data, which won't have access to other
// series data.
this._stackData = [];
// array that holds the data to be plotted. This will be the series data
// merged with the the appropriate data from _stackData according to the stackAxis.
this._plotData = [];
// Namespece to hold plugins. Generally non-renderer plugins add themselves to here.
this.plugins = {};
// Count how many times the draw method has been called while the plot is visible.
// Mostly used to test if plot has never been dran (=0), has been successfully drawn
// into a visible container once (=1) or draw more than once into a visible container.
// Can use this in tests to see if plot has been visibly drawn at least one time.
// After plot has been visibly drawn once, it generally doesn't need redrawn if its
// container is hidden and shown.
this._drawCount = 0;
// this.doCustomEventBinding = true;
// prop: drawIfHidden
// True to execute the draw method even if the plot target is hidden.
// Generally, this should be false. Most plot elements will not be sized/
// positioned correclty if renderered into a hidden container. To render into
// a hidden container, call the replot method when the container is shown.
this.drawIfHidden = false;
// true to intercept right click events and fire a 'jqplotRightClick' event.
// this will also block the context menu.
this.captureRightClick = false;
this.themeEngine = new $.jqplot.ThemeEngine();
// sum of y values for all series in plot.
// used in mekko chart.
this._sumy = 0;
this._sumx = 0;
this.preInitHooks = new $.jqplot.HooksManager();
this.postInitHooks = new $.jqplot.HooksManager();
this.preParseOptionsHooks = new $.jqplot.HooksManager();
this.postParseOptionsHooks = new $.jqplot.HooksManager();
this.preDrawHooks = new $.jqplot.HooksManager();
this.postDrawHooks = new $.jqplot.HooksManager();
this.preDrawSeriesHooks = new $.jqplot.HooksManager();
this.postDrawSeriesHooks = new $.jqplot.HooksManager();
this.preDrawLegendHooks = new $.jqplot.HooksManager();
this.addLegendRowHooks = new $.jqplot.HooksManager();
this.preSeriesInitHooks = new $.jqplot.HooksManager();
this.postSeriesInitHooks = new $.jqplot.HooksManager();
this.preParseSeriesOptionsHooks = new $.jqplot.HooksManager();
this.postParseSeriesOptionsHooks = new $.jqplot.HooksManager();
this.eventListenerHooks = new $.jqplot.EventListenerManager();
this.preDrawSeriesShadowHooks = new $.jqplot.HooksManager();
this.postDrawSeriesShadowHooks = new $.jqplot.HooksManager();
this.colorGenerator = $.jqplot.ColorGenerator;
// Group: methods
//
// method: init
// sets the plot target, checks data and applies user
// options to plot.
this.init = function(target, data, options) {
options = options || {};
for (var i=0; i<$.jqplot.preInitHooks.length; i++) {
$.jqplot.preInitHooks[i].call(this, target, data, options);
}
for (var i=0; i<this.preInitHooks.hooks.length; i++) {
this.preInitHooks.hooks[i].call(this, target, data, options);
}
this.targetId = '#'+target;
this.target = $('#'+target);
// remove any error class that may be stuck on target.
this.target.removeClass('jqplot-error');
if (!this.target.get(0)) {
throw "No plot target specified";
}
// make sure the target is positioned by some means and set css
if (this.target.css('position') == 'static') {
this.target.css('position', 'relative');
}
if (!this.target.hasClass('jqplot-target')) {
this.target.addClass('jqplot-target');
}
// if no height or width specified, use a default.
if (!this.target.height()) {
var h;
if (options && options.height) {
h = parseInt(options.height, 10);
}
else if (this.target.attr('data-height')) {
h = parseInt(this.target.attr('data-height'), 10);
}
else {
h = parseInt($.jqplot.config.defaultHeight, 10);
}
this._height = h;
this.target.css('height', h+'px');
}
else {
this._height = h = this.target.height();
}
if (!this.target.width()) {
var w;
if (options && options.width) {
w = parseInt(options.width, 10);
}
else if (this.target.attr('data-width')) {
w = parseInt(this.target.attr('data-width'), 10);
}
else {
w = parseInt($.jqplot.config.defaultWidth, 10);
}
this._width = w;
this.target.css('width', w+'px');
}
else {
this._width = w = this.target.width();
}
this._plotDimensions.height = this._height;
this._plotDimensions.width = this._width;
this.grid._plotDimensions = this._plotDimensions;
this.title._plotDimensions = this._plotDimensions;
this.baseCanvas._plotDimensions = this._plotDimensions;
this.eventCanvas._plotDimensions = this._plotDimensions;
this.legend._plotDimensions = this._plotDimensions;
if (this._height <=0 || this._width <=0 || !this._height || !this._width) {
throw "Canvas dimension not set";
}
if (options.dataRenderer && jQuery.isFunction(options.dataRenderer)) {
if (options.dataRendererOptions) {
this.dataRendererOptions = options.dataRendererOptions;
}
this.dataRenderer = options.dataRenderer;
data = this.dataRenderer(data, this, this.dataRendererOptions);
}
if (options.noDataIndicator && jQuery.isPlainObject(options.noDataIndicator)) {
$.extend(true, this.noDataIndicator, options.noDataIndicator);
}
if (data == null) {
throw{
name: "DataError",
message: "No data to plot."
};
}
if (jQuery.isArray(data) == false || data.length == 0 || jQuery.isArray(data[0]) == false || data[0].length == 0) {
if (this.noDataIndicator.show == false) {
throw{
name: "DataError",
message: "No data to plot."
};
}
else {
for (ax in this.noDataIndicator.axes) {
for (prop in this.noDataIndicator.axes[ax]) {
this.axes[ax][prop] = this.noDataIndicator.axes[ax][prop];
}
}
this.postDrawHooks.add(function() {
var eh = this.eventCanvas.getHeight();
var ew = this.eventCanvas.getWidth();
var temp = $('<div class="jqplot-noData-container" style="position:absolute;"></div>');
this.target.append(temp);
temp.height(eh);
temp.width(ew);
temp.css('top', this.eventCanvas._offsets.top);
temp.css('left', this.eventCanvas._offsets.left);
temp2 = $('<div class="jqplot-noData-contents" style="text-align:center; position:relative; margin-left:auto; margin-right:auto;"></div>');
temp.append(temp2);
temp2.html(this.noDataIndicator.indicator);
var th = temp2.height();
var tw = temp2.width();
temp2.height(th);
temp2.width(tw);
temp2.css('top', (eh - th)/2 + 'px');
});
}
}
this.data = data;
this.parseOptions(options);
if (this.textColor) {
this.target.css('color', this.textColor);
}
if (this.fontFamily) {
this.target.css('font-family', this.fontFamily);
}
if (this.fontSize) {
this.target.css('font-size', this.fontSize);
}
this.title.init();
this.legend.init();
this._sumy = 0;
this._sumx = 0;
for (var i=0; i<this.series.length; i++) {
// set default stacking order for series canvases
this.seriesStack.push(i);
this.previousSeriesStack.push(i);
this.series[i].shadowCanvas._plotDimensions = this._plotDimensions;
this.series[i].canvas._plotDimensions = this._plotDimensions;
for (var j=0; j<$.jqplot.preSeriesInitHooks.length; j++) {
$.jqplot.preSeriesInitHooks[j].call(this.series[i], target, data, this.options.seriesDefaults, this.options.series[i], this);
}
for (var j=0; j<this.preSeriesInitHooks.hooks.length; j++) {
this.preSeriesInitHooks.hooks[j].call(this.series[i], target, data, this.options.seriesDefaults, this.options.series[i], this);
}
this.populatePlotData(this.series[i], i);
this.series[i]._plotDimensions = this._plotDimensions;
this.series[i].init(i, this.grid.borderWidth, this);
for (var j=0; j<$.jqplot.postSeriesInitHooks.length; j++) {
$.jqplot.postSeriesInitHooks[j].call(this.series[i], target, data, this.options.seriesDefaults, this.options.series[i], this);
}
for (var j=0; j<this.postSeriesInitHooks.hooks.length; j++) {
this.postSeriesInitHooks.hooks[j].call(this.series[i], target, data, this.options.seriesDefaults, this.options.series[i], this);
}
this._sumy += this.series[i]._sumy;
this._sumx += this.series[i]._sumx;
}
for (var name in this.axes) {
this.axes[name]._plotDimensions = this._plotDimensions;
this.axes[name].init();
}
if (this.sortData) {
sortData(this.series);
}
this.grid.init();
this.grid._axes = this.axes;
this.legend._series = this.series;
for (var i=0; i<$.jqplot.postInitHooks.length; i++) {
$.jqplot.postInitHooks[i].call(this, target, data, options);
}
for (var i=0; i<this.postInitHooks.hooks.length; i++) {
this.postInitHooks.hooks[i].call(this, target, data, options);
}
};
// method: resetAxesScale
// Reset the specified axes min, max, numberTicks and tickInterval properties to null
// or reset these properties on all axes if no list of axes is provided.
//
// Parameters:
// axes - Boolean to reset or not reset all axes or an array or object of axis names to reset.
this.resetAxesScale = function(axes, options) {
var opts = options || {};
var ax = axes || this.axes;
if (ax === true) {
ax = this.axes;
}
if (jQuery.isArray(ax)) {
for (var i = 0; i < ax.length; i++) {
this.axes[ax[i]].resetScale(opts[ax[i]]);
}
}
else if (typeof(ax) === 'object') {
for (var name in ax) {
this.axes[name].resetScale(opts[name]);
}
}
};
// method: reInitialize
// reinitialize plot for replotting.
// not called directly.
this.reInitialize = function () {
// Plot should be visible and have a height and width.
// If plot doesn't have height and width for some
// reason, set it by other means. Plot must not have
// a display:none attribute, however.
if (!this.target.height()) {
var h;
if (options && options.height) {
h = parseInt(options.height, 10);
}
else if (this.target.attr('data-height')) {
h = parseInt(this.target.attr('data-height'), 10);
}
else {
h = parseInt($.jqplot.config.defaultHeight, 10);
}
this._height = h;
this.target.css('height', h+'px');
}
else {
this._height = this.target.height();
}
if (!this.target.width()) {
var w;
if (options && options.width) {
w = parseInt(options.width, 10);
}
else if (this.target.attr('data-width')) {
w = parseInt(this.target.attr('data-width'), 10);
}
else {
w = parseInt($.jqplot.config.defaultWidth, 10);
}
this._width = w;
this.target.css('width', w+'px');
}
else {
this._width = this.target.width();
}
if (this._height <=0 || this._width <=0 || !this._height || !this._width) {
throw "Target dimension not set";
}
this._plotDimensions.height = this._height;
this._plotDimensions.width = this._width;
this.grid._plotDimensions = this._plotDimensions;
this.title._plotDimensions = this._plotDimensions;
this.baseCanvas._plotDimensions = this._plotDimensions;
this.eventCanvas._plotDimensions = this._plotDimensions;
this.legend._plotDimensions = this._plotDimensions;
for (var n in this.axes) {
this.axes[n]._plotWidth = this._width;
this.axes[n]._plotHeight = this._height;
}
this.title._plotWidth = this._width;
if (this.textColor) {
this.target.css('color', this.textColor);
}
if (this.fontFamily) {
this.target.css('font-family', this.fontFamily);
}
if (this.fontSize) {
this.target.css('font-size', this.fontSize);
}
this._sumy = 0;
this._sumx = 0;
for (var i=0; i<this.series.length; i++) {
this.populatePlotData(this.series[i], i);
this.series[i]._plotDimensions = this._plotDimensions;
this.series[i].canvas._plotDimensions = this._plotDimensions;
//this.series[i].init(i, this.grid.borderWidth);
this._sumy += this.series[i]._sumy;
this._sumx += this.series[i]._sumx;
}
for (var name in this.axes) {
this.axes[name]._plotDimensions = this._plotDimensions;
this.axes[name]._ticks = [];
this.axes[name].renderer.init.call(this.axes[name], {});
}
if (this.sortData) {
sortData(this.series);
}
this.grid._axes = this.axes;
this.legend._series = this.series;
};
// sort the series data in increasing order.
function sortData(series) {
var d, sd, pd, ppd, ret;
for (var i=0; i<series.length; i++) {
// d = series[i].data;
// sd = series[i]._stackData;
// pd = series[i]._plotData;
// ppd = series[i]._prevPlotData;
var check;
var bat = [series[i].data, series[i]._stackData, series[i]._plotData, series[i]._prevPlotData];
for (var n=0; n<4; n++) {
check = true;
d = bat[n];
if (series[i]._stackAxis == 'x') {
for (var j = 0; j < d.length; j++) {
if (typeof(d[j][1]) != "number") {
check = false;
break;
}
}
if (check) {
d.sort(function(a,b) { return a[1] - b[1]; });
// sd.sort(function(a,b) { return a[1] - b[1]; });
// pd.sort(function(a,b) { return a[1] - b[1]; });
// ppd.sort(function(a,b) { return a[1] - b[1]; });
}
}
else {
for (var j = 0; j < d.length; j++) {
if (typeof(d[j][0]) != "number") {
check = false;
break;
}
}
if (check) {
d.sort(function(a,b) { return a[0] - b[0]; });
// sd.sort(function(a,b) { return a[0] - b[0]; });
// pd.sort(function(a,b) { return a[0] - b[0]; });
// ppd.sort(function(a,b) { return a[0] - b[0]; });
}
}
}
}
}
// populate the _stackData and _plotData arrays for the plot and the series.
this.populatePlotData = function(series, index) {
// if a stacked chart, compute the stacked data
this._plotData = [];
this._stackData = [];
series._stackData = [];
series._plotData = [];
var plotValues = {x:[], y:[]};
if (this.stackSeries && !series.disableStack) {
series._stack = true;
var sidx = series._stackAxis == 'x' ? 0 : 1;
var idx = sidx ? 0 : 1;
// push the current data into stackData
//this._stackData.push(this.series[i].data);
var temp = $.extend(true, [], series.data);
// create the data that will be plotted for this series
var plotdata = $.extend(true, [], series.data);
// for first series, nothing to add to stackData.
for (var j=0; j<index; j++) {
var cd = this.series[j].data;
for (var k=0; k<cd.length; k++) {
temp[k][0] += cd[k][0];
temp[k][1] += cd[k][1];
// only need to sum up the stack axis column of data
plotdata[k][sidx] += cd[k][sidx];
}
}
for (var i=0; i<plotdata.length; i++) {
plotValues.x.push(plotdata[i][0]);
plotValues.y.push(plotdata[i][1]);
}
this._plotData.push(plotdata);
this._stackData.push(temp);
series._stackData = temp;
series._plotData = plotdata;
series._plotValues = plotValues;
}
else {
for (var i=0; i<series.data.length; i++) {
plotValues.x.push(series.data[i][0]);
plotValues.y.push(series.data[i][1]);
}
this._stackData.push(series.data);
this.series[index]._stackData = series.data;
this._plotData.push(series.data);
series._plotData = series.data;
series._plotValues = plotValues;
}
if (index>0) {
series._prevPlotData = this.series[index-1]._plotData;
}
series._sumy = 0;
series._sumx = 0;
for (i=series.data.length-1; i>-1; i--) {
series._sumy += series.data[i][1];
series._sumx += series.data[i][0];
}
};
// function to safely return colors from the color array and wrap around at the end.
this.getNextSeriesColor = (function(t) {
var idx = 0;
var sc = t.seriesColors;
return function () {
if (idx < sc.length) {
return sc[idx++];
}
else {
idx = 0;
return sc[idx++];
}
};
})(this);
this.parseOptions = function(options){
for (var i=0; i<this.preParseOptionsHooks.hooks.length; i++) {
this.preParseOptionsHooks.hooks[i].call(this, options);
}
for (var i=0; i<$.jqplot.preParseOptionsHooks.length; i++) {
$.jqplot.preParseOptionsHooks[i].call(this, options);
}
this.options = $.extend(true, {}, this.defaults, options);
this.stackSeries = this.options.stackSeries;
if (this.options.seriesColors) {
this.seriesColors = this.options.seriesColors;
}
if (this.options.negativeSeriesColors) {
this.negativeSeriesColors = this.options.negativeSeriesColors;
}
if (this.options.captureRightClick) {
this.captureRightClick = this.options.captureRightClick;
}
this.defaultAxisStart = (options && options.defaultAxisStart != null) ? options.defaultAxisStart : this.defaultAxisStart;
var cg = new this.colorGenerator(this.seriesColors);
// this._gridPadding = this.options.gridPadding;
$.extend(true, this._gridPadding, this.options.gridPadding);
this.sortData = (this.options.sortData != null) ? this.options.sortData : this.sortData;
for (var n in this.axes) {
var axis = this.axes[n];
$.extend(true, axis, this.options.axesDefaults, this.options.axes[n]);
axis._plotWidth = this._width;
axis._plotHeight = this._height;
}
if (this.data.length == 0) {
this.data = [];
for (var i=0; i<this.options.series.length; i++) {
this.data.push(this.options.series.data);
}
}
var normalizeData = function(data, dir, start) {
// return data as an array of point arrays,
// in form [[x1,y1...], [x2,y2...], ...]
var temp = [];
var i;
dir = dir || 'vertical';
if (!jQuery.isArray(data[0])) {
// we have a series of scalars. One line with just y values.
// turn the scalar list of data into a data array of form:
// [[1, data[0]], [2, data[1]], ...]
for (i=0; i<data.length; i++) {
if (dir == 'vertical') {
temp.push([start + i, data[i]]);
}
else {
temp.push([data[i], start+i]);
}
}
}
else {
// we have a properly formatted data series, copy it.
$.extend(true, temp, data);
}
return temp;
};
for (var i=0; i<this.data.length; i++) {
var temp = new Series();
for (var j=0; j<$.jqplot.preParseSeriesOptionsHooks.length; j++) {
$.jqplot.preParseSeriesOptionsHooks[j].call(temp, this.options.seriesDefaults, this.options.series[i]);
}
for (var j=0; j<this.preParseSeriesOptionsHooks.hooks.length; j++) {
this.preParseSeriesOptionsHooks.hooks[j].call(temp, this.options.seriesDefaults, this.options.series[i]);
}
$.extend(true, temp, {seriesColors:this.seriesColors, negativeSeriesColors:this.negativeSeriesColors}, this.options.seriesDefaults, this.options.series[i]);
var dir = 'vertical';
if (temp.renderer.constructor == $.jqplot.barRenderer && temp.rendererOptions && temp.rendererOptions.barDirection == 'horizontal') {
dir = 'horizontal';
}
temp.data = normalizeData(this.data[i], dir, this.defaultAxisStart);
switch (temp.xaxis) {
case 'xaxis':
temp._xaxis = this.axes.xaxis;
break;
case 'x2axis':
temp._xaxis = this.axes.x2axis;
break;
default:
break;
}
temp._yaxis = this.axes[temp.yaxis];
temp._xaxis._series.push(temp);
temp._yaxis._series.push(temp);
if (temp.show) {
temp._xaxis.show = true;
temp._yaxis.show = true;
}
// parse the renderer options and apply default colors if not provided
if (!temp.color && temp.show != false) {
temp.color = cg.next();
}
if (!temp.label) {
temp.label = 'Series '+ (i+1).toString();
}
// temp.rendererOptions.show = temp.show;
// $.extend(true, temp.renderer, {color:this.seriesColors[i]}, this.rendererOptions);
this.series.push(temp);
for (var j=0; j<$.jqplot.postParseSeriesOptionsHooks.length; j++) {
$.jqplot.postParseSeriesOptionsHooks[j].call(this.series[i], this.options.seriesDefaults, this.options.series[i]);
}
for (var j=0; j<this.postParseSeriesOptionsHooks.hooks.length; j++) {
this.postParseSeriesOptionsHooks.hooks[j].call(this.series[i], this.options.seriesDefaults, this.options.series[i]);
}
}
// copy the grid and title options into this object.
$.extend(true, this.grid, this.options.grid);
// if axis border properties aren't set, set default.
for (var n in this.axes) {
var axis = this.axes[n];
if (axis.borderWidth == null) {
axis.borderWidth =this.grid.borderWidth;
}
if (axis.borderColor == null) {
if (n != 'xaxis' && n != 'x2axis' && axis.useSeriesColor === true && axis.show) {
axis.borderColor = axis._series[0].color;
}
else {
axis.borderColor = this.grid.borderColor;
}
}
}
if (typeof this.options.title == 'string') {
this.title.text = this.options.title;
}
else if (typeof this.options.title == 'object') {
$.extend(true, this.title, this.options.title);
}
this.title._plotWidth = this._width;
this.legend.setOptions(this.options.legend);
for (var i=0; i<$.jqplot.postParseOptionsHooks.length; i++) {
$.jqplot.postParseOptionsHooks[i].call(this, options);
}
for (var i=0; i<this.postParseOptionsHooks.hooks.length; i++) {
this.postParseOptionsHooks.hooks[i].call(this, options);
}
};
// method: replot
// Does a reinitialization of the plot followed by
// a redraw. Method could be used to interactively
// change plot characteristics and then replot.
//
// Parameters:
// options - Options used for replotting.
//
// Properties:
// clear - false to not clear (empty) the plot container before replotting (default: true).
// resetAxes - true to reset all axes min, max, numberTicks and tickInterval setting so axes will rescale themselves.
// optionally pass in list of axes to reset (e.g. ['xaxis', 'y2axis']) (default: false).
this.replot = function(options) {
var opts = options || {};
var clear = opts.clear || true;
var resetAxes = opts.resetAxes || false;
this.target.trigger('jqplotPreReplot');
if (clear) {
// Couple of posts on Stack Overflow indicate that empty() doesn't
// always cear up the dom and release memory. Sometimes setting
// innerHTML property to null is needed. Particularly on IE, may
// have to directly set it to null, bypassing jQuery.
this.target.empty();
}
if (resetAxes) {
this.resetAxesScale(resetAxes, opts.axes);
}
this.reInitialize();
this.draw();
this.target.trigger('jqplotPostReplot');
};
// method: redraw
// Empties the plot target div and redraws the plot.
// This enables plot data and properties to be changed
// and then to comletely clear the plot and redraw.
// redraw *will not* reinitialize any plot elements.
// That is, axes will not be autoscaled and defaults
// will not be reapplied to any plot elements. redraw
// is used primarily with zooming.
//
// Parameters:
// clear - false to not clear (empty) the plot container before redrawing (default: true).
this.redraw = function(clear) {
clear = (clear != null) ? clear : true;
this.target.trigger('jqplotPreRedraw');
if (clear) {
// Couple of posts on Stack Overflow indicate that empty() doesn't
// always cear up the dom and release memory. Sometimes setting
// innerHTML property to null is needed. Particularly on IE, may
// have to directly set it to null, bypassing jQuery.
this.target.empty();
}
for (var ax in this.axes) {
this.axes[ax]._ticks = [];
}
for (var i=0; i<this.series.length; i++) {
this.populatePlotData(this.series[i], i);
}
this._sumy = 0;
this._sumx = 0;
for (i=0; i<this.series.length; i++) {
this._sumy += this.series[i]._sumy;
this._sumx += this.series[i]._sumx;
}
this.draw();
this.target.trigger('jqplotPostRedraw');
};
// method: draw
// Draws all elements of the plot into the container.
// Does not clear the container before drawing.
this.draw = function(){
if (this.drawIfHidden || this.target.is(':visible')) {
this.target.trigger('jqplotPreDraw');
var i, j;
for (i=0; i<$.jqplot.preDrawHooks.length; i++) {
$.jqplot.preDrawHooks[i].call(this);
}
for (i=0; i<this.preDrawHooks.hooks.length; i++) {
this.preDrawHooks.hooks[i].call(this);
}
// create an underlying canvas to be used for special features.
this.target.append(this.baseCanvas.createElement({left:0, right:0, top:0, bottom:0}, 'jqplot-base-canvas'));
this.baseCanvas.setContext();
this.target.append(this.title.draw());
this.title.pack({top:0, left:0});
// make room for the legend between the grid and the edge.
var legendElem = this.legend.draw();
var gridPadding = {top:0, left:0, bottom:0, right:0};
if (this.legend.placement == "outsideGrid") {
// temporarily append the legend to get dimensions
this.target.append(legendElem);
switch (this.legend.location) {
case 'n':
gridPadding.top += this.legend.getHeight();
break;
case 's':
gridPadding.bottom += this.legend.getHeight();
break;
case 'ne':
case 'e':
case 'se':
gridPadding.right += this.legend.getWidth();
break;
case 'nw':
case 'w':
case 'sw':
gridPadding.left += this.legend.getWidth();
break;
default: // same as 'ne'
gridPadding.right += this.legend.getWidth();
break;
}
legendElem = legendElem.detach();
}
var ax = this.axes;
for (var name in ax) {
this.target.append(ax[name].draw(this.baseCanvas._ctx));
ax[name].set();
}
if (ax.yaxis.show) {
gridPadding.left += ax.yaxis.getWidth();
}
var ra = ['y2axis', 'y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis'];
var rapad = [0, 0, 0, 0, 0, 0, 0, 0];
var gpr = 0;
var n;
for (n=0; n<8; n++) {
if (ax[ra[n]].show) {
gpr += ax[ra[n]].getWidth();
rapad[n] = gpr;
}
}
gridPadding.right += gpr;
if (ax.x2axis.show) {
gridPadding.top += ax.x2axis.getHeight();
}
if (this.title.show) {
gridPadding.top += this.title.getHeight();
}
if (ax.xaxis.show) {
gridPadding.bottom += ax.xaxis.getHeight();
}
// end of gridPadding adjustments.
var arr = ['top', 'bottom', 'left', 'right'];
for (var n in arr) {
if (this._gridPadding[arr[n]] == null && gridPadding[arr[n]] > 0) {
this._gridPadding[arr[n]] = gridPadding[arr[n]];
}
else if (this._gridPadding[arr[n]] == null) {
this._gridPadding[arr[n]] = this._defaultGridPadding[arr[n]];
}
}
var legendPadding = (this.legend.placement == 'outsideGrid') ? {top:this.title.getHeight(), left: 0, right: 0, bottom: 0} : this._gridPadding;
ax.xaxis.pack({position:'absolute', bottom:this._gridPadding.bottom - ax.xaxis.getHeight(), left:0, width:this._width}, {min:this._gridPadding.left, max:this._width - this._gridPadding.right});
ax.yaxis.pack({position:'absolute', top:0, left:this._gridPadding.left - ax.yaxis.getWidth(), height:this._height}, {min:this._height - this._gridPadding.bottom, max: this._gridPadding.top});
ax.x2axis.pack({position:'absolute', top:this._gridPadding.top - ax.x2axis.getHeight(), left:0, width:this._width}, {min:this._gridPadding.left, max:this._width - this._gridPadding.right});
for (i=8; i>0; i--) {
ax[ra[i-1]].pack({position:'absolute', top:0, right:this._gridPadding.right - rapad[i-1]}, {min:this._height - this._gridPadding.bottom, max: this._gridPadding.top});
}
// ax.y2axis.pack({position:'absolute', top:0, right:0}, {min:this._height - this._gridPadding.bottom, max: this._gridPadding.top});
this.target.append(this.grid.createElement(this._gridPadding));
this.grid.draw();
// put the shadow canvases behind the series canvases so shadows don't overlap on stacked bars.
for (i=0; i<this.series.length; i++) {
// draw series in order of stacking. This affects only
// order in which canvases are added to dom.
j = this.seriesStack[i];
this.target.append(this.series[j].shadowCanvas.createElement(this._gridPadding, 'jqplot-series-shadowCanvas'));
this.series[j].shadowCanvas.setContext();
this.series[j].shadowCanvas._elem.data('seriesIndex', j);
}
for (i=0; i<this.series.length; i++) {
// draw series in order of stacking. This affects only
// order in which canvases are added to dom.
j = this.seriesStack[i];
this.target.append(this.series[j].canvas.createElement(this._gridPadding, 'jqplot-series-canvas'));
this.series[j].canvas.setContext();
this.series[j].canvas._elem.data('seriesIndex', j);
}
// Need to use filled canvas to capture events in IE.
// Also, canvas seems to block selection of other elements in document on FF.
this.target.append(this.eventCanvas.createElement(this._gridPadding, 'jqplot-event-canvas'));
this.eventCanvas.setContext();
this.eventCanvas._ctx.fillStyle = 'rgba(0,0,0,0)';
this.eventCanvas._ctx.fillRect(0,0,this.eventCanvas._ctx.canvas.width, this.eventCanvas._ctx.canvas.height);
// bind custom event handlers to regular events.
this.bindCustomEvents();
// draw legend before series if the series needs to know the legend dimensions.
if (this.legend.preDraw) {
this.eventCanvas._elem.before(legendElem);
this.legend.pack(legendPadding);
if (this.legend._elem) {
this.drawSeries({legendInfo:{location:this.legend.location, placement:this.legend.placement, width:this.legend.getWidth(), height:this.legend.getHeight(), xoffset:this.legend.xoffset, yoffset:this.legend.yoffset}});
}
else {
this.drawSeries();
}
}
else { // draw series before legend
this.drawSeries();
if (this.series.length) {
$(this.series[this.series.length-1].canvas._elem).after(legendElem);
}
this.legend.pack(legendPadding);
}
// register event listeners on the overlay canvas
for (var i=0; i<$.jqplot.eventListenerHooks.length; i++) {
// in the handler, this will refer to the eventCanvas dom element.
// make sure there are references back into plot objects.
this.eventCanvas._elem.bind($.jqplot.eventListenerHooks[i][0], {plot:this}, $.jqplot.eventListenerHooks[i][1]);
}
// register event listeners on the overlay canvas
for (var i=0; i<this.eventListenerHooks.hooks.length; i++) {
// in the handler, this will refer to the eventCanvas dom element.
// make sure there are references back into plot objects.
this.eventCanvas._elem.bind(this.eventListenerHooks.hooks[i][0], {plot:this}, this.eventListenerHooks.hooks[i][1]);
}
for (var i=0; i<$.jqplot.postDrawHooks.length; i++) {
$.jqplot.postDrawHooks[i].call(this);
}
for (var i=0; i<this.postDrawHooks.hooks.length; i++) {
this.postDrawHooks.hooks[i].call(this);
}
if (this.target.is(':visible')) {
this._drawCount += 1;
}
this.target.trigger('jqplotPostDraw', [this]);
}
};
this.bindCustomEvents = function() {
this.eventCanvas._elem.bind('click', {plot:this}, this.onClick);
this.eventCanvas._elem.bind('dblclick', {plot:this}, this.onDblClick);
this.eventCanvas._elem.bind('mousedown', {plot:this}, this.onMouseDown);
this.eventCanvas._elem.bind('mousemove', {plot:this}, this.onMouseMove);
this.eventCanvas._elem.bind('mouseenter', {plot:this}, this.onMouseEnter);
this.eventCanvas._elem.bind('mouseleave', {plot:this}, this.onMouseLeave);
if (this.captureRightClick) {
this.eventCanvas._elem.bind('mouseup', {plot:this}, this.onRightClick);
this.eventCanvas._elem.get(0).oncontextmenu = function() {
return false;
};
}
else {
this.eventCanvas._elem.bind('mouseup', {plot:this}, this.onMouseUp);
}
};
function getEventPosition(ev) {
var plot = ev.data.plot;
var go = plot.eventCanvas._elem.offset();
var gridPos = {x:ev.pageX - go.left, y:ev.pageY - go.top};
var dataPos = {xaxis:null, yaxis:null, x2axis:null, y2axis:null, y3axis:null, y4axis:null, y5axis:null, y6axis:null, y7axis:null, y8axis:null, y9axis:null};
var an = ['xaxis', 'yaxis', 'x2axis', 'y2axis', 'y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis'];
var ax = plot.axes;
var n, axis;
for (n=11; n>0; n--) {
axis = an[n-1];
if (ax[axis].show) {
dataPos[axis] = ax[axis].series_p2u(gridPos[axis.charAt(0)]);
}
}
return {offsets:go, gridPos:gridPos, dataPos:dataPos};
}
// function to check if event location is over a area area
function checkIntersection(gridpos, plot) {
var series = plot.series;
var i, j, k, s, r, x, y, theta, sm, sa, minang, maxang;
var d0, d, p, pp, points, bw;
var threshold, t;
for (k=plot.seriesStack.length-1; k>=0; k--) {
i = plot.seriesStack[k];
s = series[i];
switch (s.renderer.constructor) {
case $.jqplot.BarRenderer:
x = gridpos.x;
y = gridpos.y;
for (j=0; j<s._barPoints.length; j++) {
points = s._barPoints[j];
if (x>points[0][0] && x<points[2][0] && y>points[2][1] && y<points[0][1]) {
return {seriesIndex:s.index, pointIndex:j, gridData:p, data:s.data[j], points:s._barPoints[j]};
}
}
break;
case $.jqplot.DonutRenderer:
sa = s.startAngle/180*Math.PI;
x = gridpos.x - s._center[0];
y = gridpos.y - s._center[1];
r = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
if (x > 0 && -y >= 0) {
theta = 2*Math.PI - Math.atan(-y/x);
}
else if (x > 0 && -y < 0) {
theta = -Math.atan(-y/x);
}
else if (x < 0) {
theta = Math.PI - Math.atan(-y/x);
}
else if (x == 0 && -y > 0) {
theta = 3*Math.PI/2;
}
else if (x == 0 && -y < 0) {
theta = Math.PI/2;
}
else if (x == 0 && y == 0) {
theta = 0;
}
if (sa) {
theta -= sa;
if (theta < 0) {
theta += 2*Math.PI;
}
else if (theta > 2*Math.PI) {
theta -= 2*Math.PI;
}
}
sm = s.sliceMargin/180*Math.PI;
if (r < s._radius && r > s._innerRadius) {
for (j=0; j<s.gridData.length; j++) {
minang = (j>0) ? s.gridData[j-1][1]+sm : sm;
maxang = s.gridData[j][1];
if (theta > minang && theta < maxang) {
return {seriesIndex:s.index, pointIndex:j, gridData:s.gridData[j], data:s.data[j]};
}
}
}
break;
case $.jqplot.PieRenderer:
sa = s.startAngle/180*Math.PI;
x = gridpos.x - s._center[0];
y = gridpos.y - s._center[1];
r = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
if (x > 0 && -y >= 0) {
theta = 2*Math.PI - Math.atan(-y/x);
}
else if (x > 0 && -y < 0) {
theta = -Math.atan(-y/x);
}
else if (x < 0) {
theta = Math.PI - Math.atan(-y/x);
}
else if (x == 0 && -y > 0) {
theta = 3*Math.PI/2;
}
else if (x == 0 && -y < 0) {
theta = Math.PI/2;
}
else if (x == 0 && y == 0) {
theta = 0;
}
if (sa) {
theta -= sa;
if (theta < 0) {
theta += 2*Math.PI;
}
else if (theta > 2*Math.PI) {
theta -= 2*Math.PI;
}
}
sm = s.sliceMargin/180*Math.PI;
if (r < s._radius) {
for (j=0; j<s.gridData.length; j++) {
minang = (j>0) ? s.gridData[j-1][1]+sm : sm;
maxang = s.gridData[j][1];
if (theta > minang && theta < maxang) {
return {seriesIndex:s.index, pointIndex:j, gridData:s.gridData[j], data:s.data[j]};
}
}
}
break;
case $.jqplot.BubbleRenderer:
x = gridpos.x;
y = gridpos.y;
var ret = null;
if (s.show) {
for (var j=0; j<s.gridData.length; j++) {
p = s.gridData[j];
d = Math.sqrt( (x-p[0]) * (x-p[0]) + (y-p[1]) * (y-p[1]) );
if (d <= p[2] && (d <= d0 || d0 == null)) {
d0 = d;
ret = {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
}
}
if (ret != null) {
return ret;
}
}
break;
case $.jqplot.FunnelRenderer:
x = gridpos.x;
y = gridpos.y;
var v = s._vertices,
vfirst = v[0],
vlast = v[v.length-1],
lex,
rex;
// equations of right and left sides, returns x, y values given height of section (y value and 2 points)
function findedge (l, p1 , p2) {
var m = (p1[1] - p2[1])/(p1[0] - p2[0]);
var b = p1[1] - m*p1[0];
var y = l + p1[1];
return [(y - b)/m, y];
}
// check each section
lex = findedge(y, vfirst[0], vlast[3]);
rex = findedge(y, vfirst[1], vlast[2]);
for (j=0; j<v.length; j++) {
cv = v[j];
if (y >= cv[0][1] && y <= cv[3][1] && x >= lex[0] && x <= rex[0]) {
return {seriesIndex:s.index, pointIndex:j, gridData:null, data:s.data[j]};
}
}
break;
case $.jqplot.LineRenderer:
x = gridpos.x;
y = gridpos.y;
r = s.renderer;
if (s.show) {
if (s.fill) {
// first check if it is in bounding box
var inside = false;
if (x>s._boundingBox[0][0] && x<s._boundingBox[1][0] && y>s._boundingBox[1][1] && y<s._boundingBox[0][1]) {
// now check the crossing number
var numPoints = s._areaPoints.length;
var ii;
var j = numPoints-1;
for(var ii=0; ii < numPoints; ii++) {
var vertex1 = [s._areaPoints[ii][0], s._areaPoints[ii][1]];
var vertex2 = [s._areaPoints[j][0], s._areaPoints[j][1]];
if (vertex1[1] < y && vertex2[1] >= y || vertex2[1] < y && vertex1[1] >= y) {
if (vertex1[0] + (y - vertex1[1]) / (vertex2[1] - vertex1[1]) * (vertex2[0] - vertex1[0]) < x) {
inside = !inside;
}
}
j = ii;
}
}
if (inside) {
return {seriesIndex:i, pointIndex:null, gridData:s.gridData, data:s.data, points:s._areaPoints};
}
break;
}
else {
t = s.markerRenderer.size/2+s.neighborThreshold;
threshold = (t > 0) ? t : 0;
for (var j=0; j<s.gridData.length; j++) {
p = s.gridData[j];
// neighbor looks different to OHLC chart.
if (r.constructor == $.jqplot.OHLCRenderer) {
if (r.candleStick) {
var yp = s._yaxis.series_u2p;
if (x >= p[0]-r._bodyWidth/2 && x <= p[0]+r._bodyWidth/2 && y >= yp(s.data[j][2]) && y <= yp(s.data[j][3])) {
return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
}
}
// if an open hi low close chart
else if (!r.hlc){
var yp = s._yaxis.series_u2p;
if (x >= p[0]-r._tickLength && x <= p[0]+r._tickLength && y >= yp(s.data[j][2]) && y <= yp(s.data[j][3])) {
return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
}
}
// a hi low close chart
else {
var yp = s._yaxis.series_u2p;
if (x >= p[0]-r._tickLength && x <= p[0]+r._tickLength && y >= yp(s.data[j][1]) && y <= yp(s.data[j][2])) {
return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
}
}
}
else if (p[0] != null && p[1] != null){
d = Math.sqrt( (x-p[0]) * (x-p[0]) + (y-p[1]) * (y-p[1]) );
if (d <= threshold && (d <= d0 || d0 == null)) {
d0 = d;
return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
}
}
}
}
}
break;
default:
x = gridpos.x;
y = gridpos.y;
r = s.renderer;
if (s.show) {
t = s.markerRenderer.size/2+s.neighborThreshold;
threshold = (t > 0) ? t : 0;
for (var j=0; j<s.gridData.length; j++) {
p = s.gridData[j];
// neighbor looks different to OHLC chart.
if (r.constructor == $.jqplot.OHLCRenderer) {
if (r.candleStick) {
var yp = s._yaxis.series_u2p;
if (x >= p[0]-r._bodyWidth/2 && x <= p[0]+r._bodyWidth/2 && y >= yp(s.data[j][2]) && y <= yp(s.data[j][3])) {
return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
}
}
// if an open hi low close chart
else if (!r.hlc){
var yp = s._yaxis.series_u2p;
if (x >= p[0]-r._tickLength && x <= p[0]+r._tickLength && y >= yp(s.data[j][2]) && y <= yp(s.data[j][3])) {
return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
}
}
// a hi low close chart
else {
var yp = s._yaxis.series_u2p;
if (x >= p[0]-r._tickLength && x <= p[0]+r._tickLength && y >= yp(s.data[j][1]) && y <= yp(s.data[j][2])) {
return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
}
}
}
else {
d = Math.sqrt( (x-p[0]) * (x-p[0]) + (y-p[1]) * (y-p[1]) );
if (d <= threshold && (d <= d0 || d0 == null)) {
d0 = d;
return {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};
}
}
}
}
break;
}
}
return null;
}
this.onClick = function(ev) {
// Event passed in is normalized and will have data attribute.
// Event passed out is unnormalized.
var positions = getEventPosition(ev);
var p = ev.data.plot;
var neighbor = checkIntersection(positions.gridPos, p);
var evt = jQuery.Event('jqplotClick');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
$(this).trigger(evt, [positions.gridPos, positions.dataPos, neighbor, p]);
};
this.onDblClick = function(ev) {
// Event passed in is normalized and will have data attribute.
// Event passed out is unnormalized.
var positions = getEventPosition(ev);
var p = ev.data.plot;
var neighbor = checkIntersection(positions.gridPos, p);
var evt = jQuery.Event('jqplotDblClick');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
$(this).trigger(evt, [positions.gridPos, positions.dataPos, neighbor, p]);
};
this.onMouseDown = function(ev) {
var positions = getEventPosition(ev);
var p = ev.data.plot;
var neighbor = checkIntersection(positions.gridPos, p);
var evt = jQuery.Event('jqplotMouseDown');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
$(this).trigger(evt, [positions.gridPos, positions.dataPos, neighbor, p]);
};
this.onMouseUp = function(ev) {
var positions = getEventPosition(ev);
var evt = jQuery.Event('jqplotMouseUp');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
$(this).trigger(evt, [positions.gridPos, positions.dataPos, null, ev.data.plot]);
};
this.onRightClick = function(ev) {
var positions = getEventPosition(ev);
var p = ev.data.plot;
var neighbor = checkIntersection(positions.gridPos, p);
if (p.captureRightClick) {
if (ev.which == 3) {
var evt = jQuery.Event('jqplotRightClick');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
$(this).trigger(evt, [positions.gridPos, positions.dataPos, neighbor, p]);
}
else {
var evt = jQuery.Event('jqplotMouseUp');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
$(this).trigger(evt, [positions.gridPos, positions.dataPos, neighbor, p]);
}
}
};
this.onMouseMove = function(ev) {
var positions = getEventPosition(ev);
var p = ev.data.plot;
var neighbor = checkIntersection(positions.gridPos, p);
var evt = jQuery.Event('jqplotMouseMove');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
$(this).trigger(evt, [positions.gridPos, positions.dataPos, neighbor, p]);
};
this.onMouseEnter = function(ev) {
var positions = getEventPosition(ev);
var p = ev.data.plot;
var evt = jQuery.Event('jqplotMouseEnter');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
$(this).trigger(evt, [positions.gridPos, positions.dataPos, null, p]);
};
this.onMouseLeave = function(ev) {
var positions = getEventPosition(ev);
var p = ev.data.plot;
var evt = jQuery.Event('jqplotMouseLeave');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
$(this).trigger(evt, [positions.gridPos, positions.dataPos, null, p]);
};
// method: drawSeries
// Redraws all or just one series on the plot. No axis scaling
// is performed and no other elements on the plot are redrawn.
// options is an options object to pass on to the series renderers.
// It can be an empty object {}. idx is the series index
// to redraw if only one series is to be redrawn.
this.drawSeries = function(options, idx){
var i, series, ctx;
// if only one argument passed in and it is a number, use it ad idx.
idx = (typeof(options) === "number" && idx == null) ? options : idx;
options = (typeof(options) === "object") ? options : {};
// draw specified series
if (idx != undefined) {
series = this.series[idx];
ctx = series.shadowCanvas._ctx;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
series.drawShadow(ctx, options, this);
ctx = series.canvas._ctx;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
series.draw(ctx, options, this);
if (series.renderer.constructor == $.jqplot.BezierCurveRenderer) {
if (idx < this.series.length - 1) {
this.drawSeries(idx+1);
}
}
}
else {
// if call series drawShadow method first, in case all series shadows
// should be drawn before any series. This will ensure, like for
// stacked bar plots, that shadows don't overlap series.
for (i=0; i<this.series.length; i++) {
// first clear the canvas
series = this.series[i];
ctx = series.shadowCanvas._ctx;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
series.drawShadow(ctx, options, this);
ctx = series.canvas._ctx;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
series.draw(ctx, options, this);
}
}
options = idx = i = series = ctx = null;
};
// method: moveSeriesToFront
// This method requires jQuery 1.4+
// Moves the specified series canvas in front of all other series canvases.
// This effectively "draws" the specified series on top of all other series,
// although it is performed through DOM manipulation, no redrawing is performed.
//
// Parameters:
// idx - 0 based index of the series to move. This will be the index of the series
// as it was first passed into the jqplot function.
this.moveSeriesToFront = function (idx) {
idx = parseInt(idx, 10);
var stackIndex = $.inArray(idx, this.seriesStack);
// if already in front, return
if (stackIndex == -1) {
return;
}
if (stackIndex == this.seriesStack.length -1) {
this.previousSeriesStack = this.seriesStack.slice(0);
return;
}
var opidx = this.seriesStack[this.seriesStack.length -1];
var serelem = this.series[idx].canvas._elem.detach();
var shadelem = this.series[idx].shadowCanvas._elem.detach();
this.series[opidx].shadowCanvas._elem.after(shadelem);
this.series[opidx].canvas._elem.after(serelem);
this.previousSeriesStack = this.seriesStack.slice(0);
this.seriesStack.splice(stackIndex, 1);
this.seriesStack.push(idx);
};
// method: moveSeriesToBack
// This method requires jQuery 1.4+
// Moves the specified series canvas behind all other series canvases.
//
// Parameters:
// idx - 0 based index of the series to move. This will be the index of the series
// as it was first passed into the jqplot function.
this.moveSeriesToBack = function (idx) {
idx = parseInt(idx, 10);
var stackIndex = $.inArray(idx, this.seriesStack);
// if already in back, return
if (stackIndex == 0 || stackIndex == -1) {
return;
}
var opidx = this.seriesStack[0];
var serelem = this.series[idx].canvas._elem.detach();
var shadelem = this.series[idx].shadowCanvas._elem.detach();
this.series[opidx].shadowCanvas._elem.before(shadelem);
this.series[opidx].canvas._elem.before(serelem);
this.previousSeriesStack = this.seriesStack.slice(0);
this.seriesStack.splice(stackIndex, 1);
this.seriesStack.unshift(idx);
};
// method: restorePreviousSeriesOrder
// This method requires jQuery 1.4+
// Restore the series canvas order to its previous state.
// Useful to put a series back where it belongs after moving
// it to the front.
this.restorePreviousSeriesOrder = function () {
var i, j, serelem, shadelem, temp;
// if no change, return.
if (this.seriesStack == this.previousSeriesStack) {
return;
}
for (i=1; i<this.previousSeriesStack.length; i++) {
move = this.previousSeriesStack[i];
keep = this.previousSeriesStack[i-1];
serelem = this.series[move].canvas._elem.detach();
shadelem = this.series[move].shadowCanvas._elem.detach();
this.series[keep].shadowCanvas._elem.after(shadelem);
this.series[keep].canvas._elem.after(serelem);
}
temp = this.seriesStack.slice(0);
this.seriesStack = this.previousSeriesStack.slice(0);
this.previousSeriesStack = temp;
};
// method: restoreOriginalSeriesOrder
// This method requires jQuery 1.4+
// Restore the series canvas order to its original order
// when the plot was created.
this.restoreOriginalSeriesOrder = function () {
var i, j, arr=[];
for (i=0; i<this.series.length; i++) {
arr.push(i);
}
if (this.seriesStack == arr) {
return;
}
this.previousSeriesStack = this.seriesStack.slice(0);
this.seriesStack = arr;
for (i=1; i<this.seriesStack.length; i++) {
serelem = this.series[i].canvas._elem.detach();
shadelem = this.series[i].shadowCanvas._elem.detach();
this.series[i-1].shadowCanvas._elem.after(shadelem);
this.series[i-1].canvas._elem.after(serelem);
}
};
this.activateTheme = function (name) {
this.themeEngine.activate(this, name);
};
}
// conpute a highlight color or array of highlight colors from given colors.
$.jqplot.computeHighlightColors = function(colors) {
var ret;
if (jQuery.isArray(colors)) {
ret = [];
for (var i=0; i<colors.length; i++){
var rgba = $.jqplot.getColorComponents(colors[i]);
var newrgb = [rgba[0], rgba[1], rgba[2]];
var sum = newrgb[0] + newrgb[1] + newrgb[2];
for (var j=0; j<3; j++) {
// when darkening, lowest color component can be is 60.
newrgb[j] = (sum > 570) ? newrgb[j] * 0.8 : newrgb[j] + 0.3 * (255 - newrgb[j]);
newrgb[j] = parseInt(newrgb[j], 10);
}
ret.push('rgb('+newrgb[0]+','+newrgb[1]+','+newrgb[2]+')');
}
}
else {
var rgba = $.jqplot.getColorComponents(colors);
var newrgb = [rgba[0], rgba[1], rgba[2]];
var sum = newrgb[0] + newrgb[1] + newrgb[2];
for (var j=0; j<3; j++) {
// when darkening, lowest color component can be is 60.
newrgb[j] = (sum > 570) ? newrgb[j] * 0.8 : newrgb[j] + 0.3 * (255 - newrgb[j]);
newrgb[j] = parseInt(newrgb[j], 10);
}
ret = 'rgb('+newrgb[0]+','+newrgb[1]+','+newrgb[2]+')';
}
return ret;
};
$.jqplot.ColorGenerator = function(colors) {
var idx = 0;
this.next = function () {
if (idx < colors.length) {
return colors[idx++];
}
else {
idx = 0;
return colors[idx++];
}
};
this.previous = function () {
if (idx > 0) {
return colors[idx--];
}
else {
idx = colors.length-1;
return colors[idx];
}
};
// get a color by index without advancing pointer.
this.get = function(i) {
var idx = i - colors.length * Math.floor(i/colors.length);
return colors[idx];
};
this.setColors = function(c) {
colors = c;
};
this.reset = function() {
idx = 0;
};
};
// convert a hex color string to rgb string.
// h - 3 or 6 character hex string, with or without leading #
// a - optional alpha
$.jqplot.hex2rgb = function(h, a) {
h = h.replace('#', '');
if (h.length == 3) {
h = h.charAt(0)+h.charAt(0)+h.charAt(1)+h.charAt(1)+h.charAt(2)+h.charAt(2);
}
var rgb;
rgb = 'rgba('+parseInt(h.slice(0,2), 16)+', '+parseInt(h.slice(2,4), 16)+', '+parseInt(h.slice(4,6), 16);
if (a) {
rgb += ', '+a;
}
rgb += ')';
return rgb;
};
// convert an rgb color spec to a hex spec. ignore any alpha specification.
$.jqplot.rgb2hex = function(s) {
var pat = /rgba?\( *([0-9]{1,3}\.?[0-9]*%?) *, *([0-9]{1,3}\.?[0-9]*%?) *, *([0-9]{1,3}\.?[0-9]*%?) *(?:, *[0-9.]*)?\)/;
var m = s.match(pat);
var h = '#';
for (i=1; i<4; i++) {
var temp;
if (m[i].search(/%/) != -1) {
temp = parseInt(255*m[i]/100, 10).toString(16);
if (temp.length == 1) {
temp = '0'+temp;
}
}
else {
temp = parseInt(m[i], 10).toString(16);
if (temp.length == 1) {
temp = '0'+temp;
}
}
h += temp;
}
return h;
};
// given a css color spec, return an rgb css color spec
$.jqplot.normalize2rgb = function(s, a) {
if (s.search(/^ *rgba?\(/) != -1) {
return s;
}
else if (s.search(/^ *#?[0-9a-fA-F]?[0-9a-fA-F]/) != -1) {
return $.jqplot.hex2rgb(s, a);
}
else {
throw 'invalid color spec';
}
};
// extract the r, g, b, a color components out of a css color spec.
$.jqplot.getColorComponents = function(s) {
// check to see if a color keyword.
s = $.jqplot.colorKeywordMap[s] || s;
var rgb = $.jqplot.normalize2rgb(s);
var pat = /rgba?\( *([0-9]{1,3}\.?[0-9]*%?) *, *([0-9]{1,3}\.?[0-9]*%?) *, *([0-9]{1,3}\.?[0-9]*%?) *,? *([0-9.]* *)?\)/;
var m = rgb.match(pat);
var ret = [];
for (i=1; i<4; i++) {
if (m[i].search(/%/) != -1) {
ret[i-1] = parseInt(255*m[i]/100, 10);
}
else {
ret[i-1] = parseInt(m[i], 10);
}
}
ret[3] = parseFloat(m[4]) ? parseFloat(m[4]) : 1.0;
return ret;
};
$.jqplot.colorKeywordMap = {aliceblue: 'rgb(240, 248, 255)', antiquewhite: 'rgb(250, 235, 215)', aqua: 'rgb( 0, 255, 255)', aquamarine: 'rgb(127, 255, 212)', azure: 'rgb(240, 255, 255)', beige: 'rgb(245, 245, 220)', bisque: 'rgb(255, 228, 196)', black: 'rgb( 0, 0, 0)', blanchedalmond: 'rgb(255, 235, 205)', blue: 'rgb( 0, 0, 255)', blueviolet: 'rgb(138, 43, 226)', brown: 'rgb(165, 42, 42)', burlywood: 'rgb(222, 184, 135)', cadetblue: 'rgb( 95, 158, 160)', chartreuse: 'rgb(127, 255, 0)', chocolate: 'rgb(210, 105, 30)', coral: 'rgb(255, 127, 80)', cornflowerblue: 'rgb(100, 149, 237)', cornsilk: 'rgb(255, 248, 220)', crimson: 'rgb(220, 20, 60)', cyan: 'rgb( 0, 255, 255)', darkblue: 'rgb( 0, 0, 139)', darkcyan: 'rgb( 0, 139, 139)', darkgoldenrod: 'rgb(184, 134, 11)', darkgray: 'rgb(169, 169, 169)', darkgreen: 'rgb( 0, 100, 0)', darkgrey: 'rgb(169, 169, 169)', darkkhaki: 'rgb(189, 183, 107)', darkmagenta: 'rgb(139, 0, 139)', darkolivegreen: 'rgb( 85, 107, 47)', darkorange: 'rgb(255, 140, 0)', darkorchid: 'rgb(153, 50, 204)', darkred: 'rgb(139, 0, 0)', darksalmon: 'rgb(233, 150, 122)', darkseagreen: 'rgb(143, 188, 143)', darkslateblue: 'rgb( 72, 61, 139)', darkslategray: 'rgb( 47, 79, 79)', darkslategrey: 'rgb( 47, 79, 79)', darkturquoise: 'rgb( 0, 206, 209)', darkviolet: 'rgb(148, 0, 211)', deeppink: 'rgb(255, 20, 147)', deepskyblue: 'rgb( 0, 191, 255)', dimgray: 'rgb(105, 105, 105)', dimgrey: 'rgb(105, 105, 105)', dodgerblue: 'rgb( 30, 144, 255)', firebrick: 'rgb(178, 34, 34)', floralwhite: 'rgb(255, 250, 240)', forestgreen: 'rgb( 34, 139, 34)', fuchsia: 'rgb(255, 0, 255)', gainsboro: 'rgb(220, 220, 220)', ghostwhite: 'rgb(248, 248, 255)', gold: 'rgb(255, 215, 0)', goldenrod: 'rgb(218, 165, 32)', gray: 'rgb(128, 128, 128)', grey: 'rgb(128, 128, 128)', green: 'rgb( 0, 128, 0)', greenyellow: 'rgb(173, 255, 47)', honeydew: 'rgb(240, 255, 240)', hotpink: 'rgb(255, 105, 180)', indianred: 'rgb(205, 92, 92)', indigo: 'rgb( 75, 0, 130)', ivory: 'rgb(255, 255, 240)', khaki: 'rgb(240, 230, 140)', lavender: 'rgb(230, 230, 250)', lavenderblush: 'rgb(255, 240, 245)', lawngreen: 'rgb(124, 252, 0)', lemonchiffon: 'rgb(255, 250, 205)', lightblue: 'rgb(173, 216, 230)', lightcoral: 'rgb(240, 128, 128)', lightcyan: 'rgb(224, 255, 255)', lightgoldenrodyellow: 'rgb(250, 250, 210)', lightgray: 'rgb(211, 211, 211)', lightgreen: 'rgb(144, 238, 144)', lightgrey: 'rgb(211, 211, 211)', lightpink: 'rgb(255, 182, 193)', lightsalmon: 'rgb(255, 160, 122)', lightseagreen: 'rgb( 32, 178, 170)', lightskyblue: 'rgb(135, 206, 250)', lightslategray: 'rgb(119, 136, 153)', lightslategrey: 'rgb(119, 136, 153)', lightsteelblue: 'rgb(176, 196, 222)', lightyellow: 'rgb(255, 255, 224)', lime: 'rgb( 0, 255, 0)', limegreen: 'rgb( 50, 205, 50)', linen: 'rgb(250, 240, 230)', magenta: 'rgb(255, 0, 255)', maroon: 'rgb(128, 0, 0)', mediumaquamarine: 'rgb(102, 205, 170)', mediumblue: 'rgb( 0, 0, 205)', mediumorchid: 'rgb(186, 85, 211)', mediumpurple: 'rgb(147, 112, 219)', mediumseagreen: 'rgb( 60, 179, 113)', mediumslateblue: 'rgb(123, 104, 238)', mediumspringgreen: 'rgb( 0, 250, 154)', mediumturquoise: 'rgb( 72, 209, 204)', mediumvioletred: 'rgb(199, 21, 133)', midnightblue: 'rgb( 25, 25, 112)', mintcream: 'rgb(245, 255, 250)', mistyrose: 'rgb(255, 228, 225)', moccasin: 'rgb(255, 228, 181)', navajowhite: 'rgb(255, 222, 173)', navy: 'rgb( 0, 0, 128)', oldlace: 'rgb(253, 245, 230)', olive: 'rgb(128, 128, 0)', olivedrab: 'rgb(107, 142, 35)', orange: 'rgb(255, 165, 0)', orangered: 'rgb(255, 69, 0)', orchid: 'rgb(218, 112, 214)', palegoldenrod: 'rgb(238, 232, 170)', palegreen: 'rgb(152, 251, 152)', paleturquoise: 'rgb(175, 238, 238)', palevioletred: 'rgb(219, 112, 147)', papayawhip: 'rgb(255, 239, 213)', peachpuff: 'rgb(255, 218, 185)', peru: 'rgb(205, 133, 63)', pink: 'rgb(255, 192, 203)', plum: 'rgb(221, 160, 221)', powderblue: 'rgb(176, 224, 230)', purple: 'rgb(128, 0, 128)', red: 'rgb(255, 0, 0)', rosybrown: 'rgb(188, 143, 143)', royalblue: 'rgb( 65, 105, 225)', saddlebrown: 'rgb(139, 69, 19)', salmon: 'rgb(250, 128, 114)', sandybrown: 'rgb(244, 164, 96)', seagreen: 'rgb( 46, 139, 87)', seashell: 'rgb(255, 245, 238)', sienna: 'rgb(160, 82, 45)', silver: 'rgb(192, 192, 192)', skyblue: 'rgb(135, 206, 235)', slateblue: 'rgb(106, 90, 205)', slategray: 'rgb(112, 128, 144)', slategrey: 'rgb(112, 128, 144)', snow: 'rgb(255, 250, 250)', springgreen: 'rgb( 0, 255, 127)', steelblue: 'rgb( 70, 130, 180)', tan: 'rgb(210, 180, 140)', teal: 'rgb( 0, 128, 128)', thistle: 'rgb(216, 191, 216)', tomato: 'rgb(255, 99, 71)', turquoise: 'rgb( 64, 224, 208)', violet: 'rgb(238, 130, 238)', wheat: 'rgb(245, 222, 179)', white: 'rgb(255, 255, 255)', whitesmoke: 'rgb(245, 245, 245)', yellow: 'rgb(255, 255, 0)', yellowgreen: 'rgb(154, 205, 50)'};
// class: $.jqplot.AxisLabelRenderer
// Renderer to place labels on the axes.
$.jqplot.AxisLabelRenderer = function(options) {
// Group: Properties
$.jqplot.ElemContainer.call(this);
// name of the axis associated with this tick
this.axis;
// prop: show
// wether or not to show the tick (mark and label).
this.show = true;
// prop: label
// The text or html for the label.
this.label = '';
this.fontFamily = null;
this.fontSize = null;
this.textColor = null;
this._elem;
// prop: escapeHTML
// true to escape HTML entities in the label.
this.escapeHTML = false;
$.extend(true, this, options);
};
$.jqplot.AxisLabelRenderer.prototype = new $.jqplot.ElemContainer();
$.jqplot.AxisLabelRenderer.prototype.constructor = $.jqplot.AxisLabelRenderer;
$.jqplot.AxisLabelRenderer.prototype.init = function(options) {
$.extend(true, this, options);
};
$.jqplot.AxisLabelRenderer.prototype.draw = function() {
this._elem = $('<div style="position:absolute;" class="jqplot-'+this.axis+'-label"></div>');
if (Number(this.label)) {
this._elem.css('white-space', 'nowrap');
}
if (!this.escapeHTML) {
this._elem.html(this.label);
}
else {
this._elem.text(this.label);
}
if (this.fontFamily) {
this._elem.css('font-family', this.fontFamily);
}
if (this.fontSize) {
this._elem.css('font-size', this.fontSize);
}
if (this.textColor) {
this._elem.css('color', this.textColor);
}
return this._elem;
};
$.jqplot.AxisLabelRenderer.prototype.pack = function() {
};
// class: $.jqplot.AxisTickRenderer
// A "tick" object showing the value of a tick/gridline on the plot.
$.jqplot.AxisTickRenderer = function(options) {
// Group: Properties
$.jqplot.ElemContainer.call(this);
// prop: mark
// tick mark on the axis. One of 'inside', 'outside', 'cross', '' or null.
this.mark = 'outside';
// name of the axis associated with this tick
this.axis;
// prop: showMark
// wether or not to show the mark on the axis.
this.showMark = true;
// prop: showGridline
// wether or not to draw the gridline on the grid at this tick.
this.showGridline = true;
// prop: isMinorTick
// if this is a minor tick.
this.isMinorTick = false;
// prop: size
// Length of the tick beyond the grid in pixels.
// DEPRECATED: This has been superceeded by markSize
this.size = 4;
// prop: markSize
// Length of the tick marks in pixels. For 'cross' style, length
// will be stoked above and below axis, so total length will be twice this.
this.markSize = 6;
// prop: show
// wether or not to show the tick (mark and label).
// Setting this to false requires more testing. It is recommended
// to set showLabel and showMark to false instead.
this.show = true;
// prop: showLabel
// wether or not to show the label.
this.showLabel = true;
this.label = '';
this.value = null;
this._styles = {};
// prop: formatter
// A class of a formatter for the tick text. sprintf by default.
this.formatter = $.jqplot.DefaultTickFormatter;
// prop: prefix
// string appended to the tick label if no formatString is specified.
this.prefix = '';
// prop: formatString
// string passed to the formatter.
this.formatString = '';
// prop: fontFamily
// css spec for the font-family css attribute.
this.fontFamily;
// prop: fontSize
// css spec for the font-size css attribute.
this.fontSize;
// prop: textColor
// css spec for the color attribute.
this.textColor;
this._elem;
this._breakTick = false;
$.extend(true, this, options);
};
$.jqplot.AxisTickRenderer.prototype.init = function(options) {
$.extend(true, this, options);
};
$.jqplot.AxisTickRenderer.prototype = new $.jqplot.ElemContainer();
$.jqplot.AxisTickRenderer.prototype.constructor = $.jqplot.AxisTickRenderer;
$.jqplot.AxisTickRenderer.prototype.setTick = function(value, axisName, isMinor) {
this.value = value;
this.axis = axisName;
if (isMinor) {
this.isMinorTick = true;
}
return this;
};
$.jqplot.AxisTickRenderer.prototype.draw = function() {
if (!this.label) {
this.label = this.formatter(this.formatString, this.value);
}
// add prefix if needed
if (this.prefix && !this.formatString) {
this.label = this.prefix + this.label;
}
style ='style="position:absolute;';
if (Number(this.label)) {
style +='white-space:nowrap;';
}
style += '"';
this._elem = $('<div '+style+' class="jqplot-'+this.axis+'-tick">'+this.label+'</div>');
for (var s in this._styles) {
this._elem.css(s, this._styles[s]);
}
if (this.fontFamily) {
this._elem.css('font-family', this.fontFamily);
}
if (this.fontSize) {
this._elem.css('font-size', this.fontSize);
}
if (this.textColor) {
this._elem.css('color', this.textColor);
}
if (this._breakTick) {
this._elem.addClass('jqplot-breakTick');
}
return this._elem;
};
$.jqplot.DefaultTickFormatter = function (format, val) {
if (typeof val == 'number') {
if (!format) {
format = $.jqplot.config.defaultTickFormatString;
}
return $.jqplot.sprintf(format, val);
}
else {
return String(val);
}
};
$.jqplot.AxisTickRenderer.prototype.pack = function() {
};
// Class: $.jqplot.CanvasGridRenderer
// The default jqPlot grid renderer, creating a grid on a canvas element.
// The renderer has no additional options beyond the <Grid> class.
$.jqplot.CanvasGridRenderer = function(){
this.shadowRenderer = new $.jqplot.ShadowRenderer();
};
// called with context of Grid object
$.jqplot.CanvasGridRenderer.prototype.init = function(options) {
this._ctx;
$.extend(true, this, options);
// set the shadow renderer options
var sopts = {lineJoin:'miter', lineCap:'round', fill:false, isarc:false, angle:this.shadowAngle, offset:this.shadowOffset, alpha:this.shadowAlpha, depth:this.shadowDepth, lineWidth:this.shadowWidth, closePath:false, strokeStyle:this.shadowColor};
this.renderer.shadowRenderer.init(sopts);
};
// called with context of Grid.
$.jqplot.CanvasGridRenderer.prototype.createElement = function() {
var elem = document.createElement('canvas');
var w = this._plotDimensions.width;
var h = this._plotDimensions.height;
elem.width = w;
elem.height = h;
this._elem = $(elem);
this._elem.addClass('jqplot-grid-canvas');
this._elem.css({ position: 'absolute', left: 0, top: 0 });
if ($.jqplot.use_excanvas) {
window.G_vmlCanvasManager.init_(document);
}
if ($.jqplot.use_excanvas) {
elem = window.G_vmlCanvasManager.initElement(elem);
}
this._top = this._offsets.top;
this._bottom = h - this._offsets.bottom;
this._left = this._offsets.left;
this._right = w - this._offsets.right;
this._width = this._right - this._left;
this._height = this._bottom - this._top;
// avoid memory leak
elem = null;
return this._elem;
};
$.jqplot.CanvasGridRenderer.prototype.draw = function() {
this._ctx = this._elem.get(0).getContext("2d");
var ctx = this._ctx;
var axes = this._axes;
// Add the grid onto the grid canvas. This is the bottom most layer.
ctx.save();
ctx.clearRect(0, 0, this._plotDimensions.width, this._plotDimensions.height);
ctx.fillStyle = this.backgroundColor || this.background;
ctx.fillRect(this._left, this._top, this._width, this._height);
if (true) {
ctx.save();
ctx.lineJoin = 'miter';
ctx.lineCap = 'butt';
ctx.lineWidth = this.gridLineWidth;
ctx.strokeStyle = this.gridLineColor;
var b, e;
var ax = ['xaxis', 'yaxis', 'x2axis', 'y2axis'];
for (var i=4; i>0; i--) {
var name = ax[i-1];
var axis = axes[name];
var ticks = axis._ticks;
if (axis.show) {
for (var j=ticks.length; j>0; j--) {
var t = ticks[j-1];
if (t.show) {
var pos = Math.round(axis.u2p(t.value)) + 0.5;
switch (name) {
case 'xaxis':
// draw the grid line
if (t.showGridline && this.drawGridlines) {
drawLine(pos, this._top, pos, this._bottom);
}
// draw the mark
if (t.showMark && t.mark) {
s = t.markSize;
m = t.mark;
var pos = Math.round(axis.u2p(t.value)) + 0.5;
switch (m) {
case 'outside':
b = this._bottom;
e = this._bottom+s;
break;
case 'inside':
b = this._bottom-s;
e = this._bottom;
break;
case 'cross':
b = this._bottom-s;
e = this._bottom+s;
break;
default:
b = this._bottom;
e = this._bottom+s;
break;
}
// draw the shadow
if (this.shadow) {
this.renderer.shadowRenderer.draw(ctx, [[pos,b],[pos,e]], {lineCap:'butt', lineWidth:this.gridLineWidth, offset:this.gridLineWidth*0.75, depth:2, fill:false, closePath:false});
}
// draw the line
drawLine(pos, b, pos, e);
}
break;
case 'yaxis':
// draw the grid line
if (t.showGridline && this.drawGridlines) {
drawLine(this._right, pos, this._left, pos);
}
// draw the mark
if (t.showMark && t.mark) {
s = t.markSize;
m = t.mark;
var pos = Math.round(axis.u2p(t.value)) + 0.5;
switch (m) {
case 'outside':
b = this._left-s;
e = this._left;
break;
case 'inside':
b = this._left;
e = this._left+s;
break;
case 'cross':
b = this._left-s;
e = this._left+s;
break;
default:
b = this._left-s;
e = this._left;
break;
}
// draw the shadow
if (this.shadow) {
this.renderer.shadowRenderer.draw(ctx, [[b, pos], [e, pos]], {lineCap:'butt', lineWidth:this.gridLineWidth*1.5, offset:this.gridLineWidth*0.75, fill:false, closePath:false});
}
drawLine(b, pos, e, pos, {strokeStyle:axis.borderColor});
}
break;
case 'x2axis':
// draw the grid line
if (t.showGridline && this.drawGridlines) {
drawLine(pos, this._bottom, pos, this._top);
}
// draw the mark
if (t.showMark && t.mark) {
s = t.markSize;
m = t.mark;
var pos = Math.round(axis.u2p(t.value)) + 0.5;
switch (m) {
case 'outside':
b = this._top-s;
e = this._top;
break;
case 'inside':
b = this._top;
e = this._top+s;
break;
case 'cross':
b = this._top-s;
e = this._top+s;
break;
default:
b = this._top-s;
e = this._top;
break;
}
// draw the shadow
if (this.shadow) {
this.renderer.shadowRenderer.draw(ctx, [[pos,b],[pos,e]], {lineCap:'butt', lineWidth:this.gridLineWidth, offset:this.gridLineWidth*0.75, depth:2, fill:false, closePath:false});
}
drawLine(pos, b, pos, e);
}
break;
case 'y2axis':
// draw the grid line
if (t.showGridline && this.drawGridlines) {
drawLine(this._left, pos, this._right, pos);
}
// draw the mark
if (t.showMark && t.mark) {
s = t.markSize;
m = t.mark;
var pos = Math.round(axis.u2p(t.value)) + 0.5;
switch (m) {
case 'outside':
b = this._right;
e = this._right+s;
break;
case 'inside':
b = this._right-s;
e = this._right;
break;
case 'cross':
b = this._right-s;
e = this._right+s;
break;
default:
b = this._right;
e = this._right+s;
break;
}
// draw the shadow
if (this.shadow) {
this.renderer.shadowRenderer.draw(ctx, [[b, pos], [e, pos]], {lineCap:'butt', lineWidth:this.gridLineWidth*1.5, offset:this.gridLineWidth*0.75, fill:false, closePath:false});
}
drawLine(b, pos, e, pos, {strokeStyle:axis.borderColor});
}
break;
default:
break;
}
}
}
t = null;
}
axis = null;
ticks = null;
}
// Now draw grid lines for additional y axes
ax = ['y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis'];
for (var i=7; i>0; i--) {
var axis = axes[ax[i-1]];
var ticks = axis._ticks;
if (axis.show) {
var tn = ticks[axis.numberTicks-1];
var t0 = ticks[0];
var left = axis.getLeft();
var points = [[left, tn.getTop() + tn.getHeight()/2], [left, t0.getTop() + t0.getHeight()/2 + 1.0]];
// draw the shadow
if (this.shadow) {
this.renderer.shadowRenderer.draw(ctx, points, {lineCap:'butt', fill:false, closePath:false});
}
// draw the line
drawLine(points[0][0], points[0][1], points[1][0], points[1][1], {lineCap:'butt', strokeStyle:axis.borderColor, lineWidth:axis.borderWidth});
// draw the tick marks
for (var j=ticks.length; j>0; j--) {
var t = ticks[j-1];
s = t.markSize;
m = t.mark;
var pos = Math.round(axis.u2p(t.value)) + 0.5;
if (t.showMark && t.mark) {
switch (m) {
case 'outside':
b = left;
e = left+s;
break;
case 'inside':
b = left-s;
e = left;
break;
case 'cross':
b = left-s;
e = left+s;
break;
default:
b = left;
e = left+s;
break;
}
points = [[b,pos], [e,pos]];
// draw the shadow
if (this.shadow) {
this.renderer.shadowRenderer.draw(ctx, points, {lineCap:'butt', lineWidth:this.gridLineWidth*1.5, offset:this.gridLineWidth*0.75, fill:false, closePath:false});
}
// draw the line
drawLine(b, pos, e, pos, {strokeStyle:axis.borderColor});
}
t = null;
}
t0 = null;
}
axis = null;
ticks = null;
}
ctx.restore();
}
function drawLine(bx, by, ex, ey, opts) {
ctx.save();
opts = opts || {};
if (opts.lineWidth == null || opts.lineWidth != 0){
$.extend(true, ctx, opts);
ctx.beginPath();
ctx.moveTo(bx, by);
ctx.lineTo(ex, ey);
ctx.stroke();
ctx.restore();
}
}
if (this.shadow) {
var points = [[this._left, this._bottom], [this._right, this._bottom], [this._right, this._top]];
this.renderer.shadowRenderer.draw(ctx, points);
}
// Now draw border around grid. Use axis border definitions. start at
// upper left and go clockwise.
if (this.borderWidth != 0 && this.drawBorder) {
drawLine (this._left, this._top, this._right, this._top, {lineCap:'round', strokeStyle:axes.x2axis.borderColor, lineWidth:axes.x2axis.borderWidth});
drawLine (this._right, this._top, this._right, this._bottom, {lineCap:'round', strokeStyle:axes.y2axis.borderColor, lineWidth:axes.y2axis.borderWidth});
drawLine (this._right, this._bottom, this._left, this._bottom, {lineCap:'round', strokeStyle:axes.xaxis.borderColor, lineWidth:axes.xaxis.borderWidth});
drawLine (this._left, this._bottom, this._left, this._top, {lineCap:'round', strokeStyle:axes.yaxis.borderColor, lineWidth:axes.yaxis.borderWidth});
}
// ctx.lineWidth = this.borderWidth;
// ctx.strokeStyle = this.borderColor;
// ctx.strokeRect(this._left, this._top, this._width, this._height);
ctx.restore();
ctx = null;
axes = null;
};
// Class: $.jqplot.DivTitleRenderer
// The default title renderer for jqPlot. This class has no options beyond the <Title> class.
$.jqplot.DivTitleRenderer = function() {
};
$.jqplot.DivTitleRenderer.prototype.init = function(options) {
$.extend(true, this, options);
};
$.jqplot.DivTitleRenderer.prototype.draw = function() {
var r = this.renderer;
if (!this.text) {
this.show = false;
this._elem = $('<div class="jqplot-title" style="height:0px;width:0px;"></div>');
}
else if (this.text) {
var color;
if (this.color) {
color = this.color;
}
else if (this.textColor) {
color = this.textColor;
}
// don't trust that a stylesheet is present, set the position.
var styletext = 'position:absolute;top:0px;left:0px;';
styletext += (this._plotWidth) ? 'width:'+this._plotWidth+'px;' : '';
styletext += (this.fontSize) ? 'font-size:'+this.fontSize+';' : '';
styletext += (this.textAlign) ? 'text-align:'+this.textAlign+';' : 'text-align:center;';
styletext += (color) ? 'color:'+color+';' : '';
styletext += (this.paddingBottom) ? 'padding-bottom:'+this.paddingBottom+';' : '';
this._elem = $('<div class="jqplot-title" style="'+styletext+'">'+this.text+'</div>');
if (this.fontFamily) {
this._elem.css('font-family', this.fontFamily);
}
}
return this._elem;
};
$.jqplot.DivTitleRenderer.prototype.pack = function() {
// nothing to do here
};
// Class: $.jqplot.LineRenderer
// The default line renderer for jqPlot, this class has no options beyond the <Series> class.
// Draws series as a line.
$.jqplot.LineRenderer = function(){
this.shapeRenderer = new $.jqplot.ShapeRenderer();
this.shadowRenderer = new $.jqplot.ShadowRenderer();
};
// called with scope of series.
$.jqplot.LineRenderer.prototype.init = function(options, plot) {
options = options || {};
var lopts = {highlightMouseOver: options.highlightMouseOver, highlightMouseDown: options.highlightMouseDown, highlightColor: options.highlightColor};
delete (options.highlightMouseOver);
delete (options.highlightMouseDown);
delete (options.highlightColor);
$.extend(true, this.renderer, options);
// set the shape renderer options
var opts = {lineJoin:'round', lineCap:'round', fill:this.fill, isarc:false, strokeStyle:this.color, fillStyle:this.fillColor, lineWidth:this.lineWidth, closePath:this.fill};
this.renderer.shapeRenderer.init(opts);
// set the shadow renderer options
// scale the shadowOffset to the width of the line.
if (this.lineWidth > 2.5) {
var shadow_offset = this.shadowOffset* (1 + (Math.atan((this.lineWidth/2.5))/0.785398163 - 1)*0.6);
// var shadow_offset = this.shadowOffset;
}
// for skinny lines, don't make such a big shadow.
else {
var shadow_offset = this.shadowOffset*Math.atan((this.lineWidth/2.5))/0.785398163;
}
var sopts = {lineJoin:'round', lineCap:'round', fill:this.fill, isarc:false, angle:this.shadowAngle, offset:shadow_offset, alpha:this.shadowAlpha, depth:this.shadowDepth, lineWidth:this.lineWidth, closePath:this.fill};
this.renderer.shadowRenderer.init(sopts);
this._areaPoints = [];
this._boundingBox = [[],[]];
if (!this.isTrendline && this.fill) {
// prop: highlightMouseOver
// True to highlight area on a filled plot when moused over.
// This must be false to enable highlightMouseDown to highlight when clicking on an area on a filled plot.
this.highlightMouseOver = true;
// prop: highlightMouseDown
// True to highlight when a mouse button is pressed over an area on a filled plot.
// This will be disabled if highlightMouseOver is true.
this.highlightMouseDown = false;
// prop: highlightColor
// color to use when highlighting an area on a filled plot.
this.highlightColor = null;
// if user has passed in highlightMouseDown option and not set highlightMouseOver, disable highlightMouseOver
if (lopts.highlightMouseDown && lopts.highlightMouseOver == null) {
lopts.highlightMouseOver = false;
}
$.extend(true, this, {highlightMouseOver: lopts.highlightMouseOver, highlightMouseDown: lopts.highlightMouseDown, highlightColor: lopts.highlightColor});
if (!this.highlightColor) {
this.highlightColor = $.jqplot.computeHighlightColors(this.fillColor);
}
// turn off (disable) the highlighter plugin
if (this.highlighter) {
this.highlighter.show = false;
}
}
if (!this.isTrendline && plot) {
plot.plugins.lineRenderer = {};
plot.postInitHooks.addOnce(postInit);
plot.postDrawHooks.addOnce(postPlotDraw);
plot.eventListenerHooks.addOnce('jqplotMouseMove', handleMove);
plot.eventListenerHooks.addOnce('jqplotMouseDown', handleMouseDown);
plot.eventListenerHooks.addOnce('jqplotMouseUp', handleMouseUp);
plot.eventListenerHooks.addOnce('jqplotClick', handleClick);
plot.eventListenerHooks.addOnce('jqplotRightClick', handleRightClick);
}
};
// Method: setGridData
// converts the user data values to grid coordinates and stores them
// in the gridData array.
// Called with scope of a series.
$.jqplot.LineRenderer.prototype.setGridData = function(plot) {
// recalculate the grid data
var xp = this._xaxis.series_u2p;
var yp = this._yaxis.series_u2p;
var data = this._plotData;
var pdata = this._prevPlotData;
this.gridData = [];
this._prevGridData = [];
for (var i=0; i<this.data.length; i++) {
// if not a line series or if no nulls in data, push the converted point onto the array.
if (data[i][0] != null && data[i][1] != null) {
this.gridData.push([xp.call(this._xaxis, data[i][0]), yp.call(this._yaxis, data[i][1])]);
}
// else if there is a null, preserve it.
else if (data[i][0] == null) {
this.gridData.push([null, yp.call(this._yaxis, data[i][1])]);
}
else if (data[i][1] == null) {
this.gridData.push([xp.call(this._xaxis, data[i][0]), null]);
}
// if not a line series or if no nulls in data, push the converted point onto the array.
if (pdata[i] != null && pdata[i][0] != null && pdata[i][1] != null) {
this._prevGridData.push([xp.call(this._xaxis, pdata[i][0]), yp.call(this._yaxis, pdata[i][1])]);
}
// else if there is a null, preserve it.
else if (pdata[i] != null && pdata[i][0] == null) {
this._prevGridData.push([null, yp.call(this._yaxis, pdata[i][1])]);
}
else if (pdata[i] != null && pdata[i][0] != null && pdata[i][1] == null) {
this._prevGridData.push([xp.call(this._xaxis, pdata[i][0]), null]);
}
}
};
// Method: makeGridData
// converts any arbitrary data values to grid coordinates and
// returns them. This method exists so that plugins can use a series'
// linerenderer to generate grid data points without overwriting the
// grid data associated with that series.
// Called with scope of a series.
$.jqplot.LineRenderer.prototype.makeGridData = function(data, plot) {
// recalculate the grid data
var xp = this._xaxis.series_u2p;
var yp = this._yaxis.series_u2p;
var gd = [];
var pgd = [];
for (var i=0; i<data.length; i++) {
// if not a line series or if no nulls in data, push the converted point onto the array.
if (data[i][0] != null && data[i][1] != null) {
gd.push([xp.call(this._xaxis, data[i][0]), yp.call(this._yaxis, data[i][1])]);
}
// else if there is a null, preserve it.
else if (data[i][0] == null) {
gd.push([null, yp.call(this._yaxis, data[i][1])]);
}
else if (data[i][1] == null) {
gd.push([xp.call(this._xaxis, data[i][0]), null]);
}
}
return gd;
};
// called within scope of series.
$.jqplot.LineRenderer.prototype.draw = function(ctx, gd, options) {
var i;
var opts = (options != undefined) ? options : {};
var shadow = (opts.shadow != undefined) ? opts.shadow : this.shadow;
var showLine = (opts.showLine != undefined) ? opts.showLine : this.showLine;
var fill = (opts.fill != undefined) ? opts.fill : this.fill;
var fillAndStroke = (opts.fillAndStroke != undefined) ? opts.fillAndStroke : this.fillAndStroke;
var xmin, ymin, xmax, ymax;
ctx.save();
if (gd.length) {
if (showLine) {
// if we fill, we'll have to add points to close the curve.
if (fill) {
if (this.fillToZero) {
// have to break line up into shapes at axis crossings
var negativeColors = new $.jqplot.ColorGenerator(this.negativeSeriesColors);
var negativeColor = negativeColors.get(this.index);
if (! this.useNegativeColors) {
negativeColor = opts.fillStyle;
}
var isnegative = false;
var posfs = opts.fillStyle;
// if stoking line as well as filling, get a copy of line data.
if (fillAndStroke) {
var fasgd = gd.slice(0);
}
// if not stacked, fill down to axis
if (this.index == 0 || !this._stack) {
var tempgd = [];
this._areaPoints = [];
var pyzero = this._yaxis.series_u2p(this.fillToValue);
var pxzero = this._xaxis.series_u2p(this.fillToValue);
if (this.fillAxis == 'y') {
tempgd.push([gd[0][0], pyzero]);
this._areaPoints.push([gd[0][0], pyzero]);
for (var i=0; i<gd.length-1; i++) {
tempgd.push(gd[i]);
this._areaPoints.push(gd[i]);
// do we have an axis crossing?
if (this._plotData[i][1] * this._plotData[i+1][1] < 0) {
if (this._plotData[i][1] < 0) {
isnegative = true;
opts.fillStyle = negativeColor;
}
else {
isnegative = false;
opts.fillStyle = posfs;
}
var xintercept = gd[i][0] + (gd[i+1][0] - gd[i][0]) * (pyzero-gd[i][1])/(gd[i+1][1] - gd[i][1]);
tempgd.push([xintercept, pyzero]);
this._areaPoints.push([xintercept, pyzero]);
// now draw this shape and shadow.
if (shadow) {
this.renderer.shadowRenderer.draw(ctx, tempgd, opts);
}
this.renderer.shapeRenderer.draw(ctx, tempgd, opts);
// now empty temp array and continue
tempgd = [[xintercept, pyzero]];
// this._areaPoints = [[xintercept, pyzero]];
}
}
if (this._plotData[gd.length-1][1] < 0) {
isnegative = true;
opts.fillStyle = negativeColor;
}
else {
isnegative = false;
opts.fillStyle = posfs;
}
tempgd.push(gd[gd.length-1]);
this._areaPoints.push(gd[gd.length-1]);
tempgd.push([gd[gd.length-1][0], pyzero]);
this._areaPoints.push([gd[gd.length-1][0], pyzero]);
}
// now draw this shape and shadow.
if (shadow) {
this.renderer.shadowRenderer.draw(ctx, tempgd, opts);
}
this.renderer.shapeRenderer.draw(ctx, tempgd, opts);
// var gridymin = this._yaxis.series_u2p(0);
// // IE doesn't return new length on unshift
// gd.unshift([gd[0][0], gridymin]);
// len = gd.length;
// gd.push([gd[len - 1][0], gridymin]);
}
// if stacked, fill to line below
else {
var prev = this._prevGridData;
for (var i=prev.length; i>0; i--) {
gd.push(prev[i-1]);
// this._areaPoints.push(prev[i-1]);
}
if (shadow) {
this.renderer.shadowRenderer.draw(ctx, gd, opts);
}
this._areaPoints = gd;
this.renderer.shapeRenderer.draw(ctx, gd, opts);
}
}
/////////////////////////
// Not filled to zero
////////////////////////
else {
// if stoking line as well as filling, get a copy of line data.
if (fillAndStroke) {
var fasgd = gd.slice(0);
}
// if not stacked, fill down to axis
if (this.index == 0 || !this._stack) {
// var gridymin = this._yaxis.series_u2p(this._yaxis.min) - this.gridBorderWidth / 2;
var gridymin = ctx.canvas.height;
// IE doesn't return new length on unshift
gd.unshift([gd[0][0], gridymin]);
len = gd.length;
gd.push([gd[len - 1][0], gridymin]);
}
// if stacked, fill to line below
else {
var prev = this._prevGridData;
for (var i=prev.length; i>0; i--) {
gd.push(prev[i-1]);
}
}
this._areaPoints = gd;
if (shadow) {
this.renderer.shadowRenderer.draw(ctx, gd, opts);
}
this.renderer.shapeRenderer.draw(ctx, gd, opts);
}
if (fillAndStroke) {
var fasopts = $.extend(true, {}, opts, {fill:false, closePath:false});
this.renderer.shapeRenderer.draw(ctx, fasgd, fasopts);
//////////
// TODO: figure out some way to do shadows nicely
// if (shadow) {
// this.renderer.shadowRenderer.draw(ctx, fasgd, fasopts);
// }
// now draw the markers
if (this.markerRenderer.show) {
for (i=0; i<fasgd.length; i++) {
this.markerRenderer.draw(fasgd[i][0], fasgd[i][1], ctx, opts.markerOptions);
}
}
}
}
else {
if (shadow) {
this.renderer.shadowRenderer.draw(ctx, gd, opts);
}
this.renderer.shapeRenderer.draw(ctx, gd, opts);
}
}
// calculate the bounding box
var xmin = xmax = ymin = ymax = null;
for (i=0; i<this._areaPoints.length; i++) {
var p = this._areaPoints[i];
if (xmin > p[0] || xmin == null) {
xmin = p[0];
}
if (ymax < p[1] || ymax == null) {
ymax = p[1];
}
if (xmax < p[0] || xmax == null) {
xmax = p[0];
}
if (ymin > p[1] || ymin == null) {
ymin = p[1];
}
}
this._boundingBox = [[xmin, ymax], [xmax, ymin]];
// now draw the markers
if (this.markerRenderer.show && !fill) {
for (i=0; i<gd.length; i++) {
if (gd[i][0] != null && gd[i][1] != null) {
this.markerRenderer.draw(gd[i][0], gd[i][1], ctx, opts.markerOptions);
}
}
}
}
ctx.restore();
};
$.jqplot.LineRenderer.prototype.drawShadow = function(ctx, gd, options) {
// This is a no-op, shadows drawn with lines.
};
// called with scope of plot.
// make sure to not leave anything highlighted.
function postInit(target, data, options) {
for (i=0; i<this.series.length; i++) {
if (this.series[i].renderer.constructor == $.jqplot.LineRenderer) {
// don't allow mouseover and mousedown at same time.
if (this.series[i].highlightMouseOver) {
this.series[i].highlightMouseDown = false;
}
}
}
this.target.bind('mouseout', {plot:this}, function (ev) { unhighlight(ev.data.plot); });
}
// called within context of plot
// create a canvas which we can draw on.
// insert it before the eventCanvas, so eventCanvas will still capture events.
function postPlotDraw() {
this.plugins.lineRenderer.highlightedSeriesIndex = null;
this.plugins.lineRenderer.highlightCanvas = new $.jqplot.GenericCanvas();
this.eventCanvas._elem.before(this.plugins.lineRenderer.highlightCanvas.createElement(this._gridPadding, 'jqplot-lineRenderer-highlight-canvas', this._plotDimensions));
this.plugins.lineRenderer.highlightCanvas.setContext();
}
function highlight (plot, sidx, pidx, points) {
var s = plot.series[sidx];
var canvas = plot.plugins.lineRenderer.highlightCanvas;
canvas._ctx.clearRect(0,0,canvas._ctx.canvas.width, canvas._ctx.canvas.height);
s._highlightedPoint = pidx;
plot.plugins.lineRenderer.highlightedSeriesIndex = sidx;
var opts = {fillStyle: s.highlightColor};
s.renderer.shapeRenderer.draw(canvas._ctx, points, opts);
canvas = null;
}
function unhighlight (plot) {
var canvas = plot.plugins.lineRenderer.highlightCanvas;
canvas._ctx.clearRect(0,0, canvas._ctx.canvas.width, canvas._ctx.canvas.height);
for (var i=0; i<plot.series.length; i++) {
plot.series[i]._highlightedPoint = null;
}
plot.plugins.lineRenderer.highlightedSeriesIndex = null;
plot.target.trigger('jqplotDataUnhighlight');
canvas = null;
}
function handleMove(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
var evt1 = jQuery.Event('jqplotDataMouseOver');
evt1.pageX = ev.pageX;
evt1.pageY = ev.pageY;
plot.target.trigger(evt1, ins);
if (plot.series[ins[0]].highlightMouseOver && !(ins[0] == plot.plugins.lineRenderer.highlightedSeriesIndex)) {
var evt = jQuery.Event('jqplotDataHighlight');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
highlight (plot, neighbor.seriesIndex, neighbor.pointIndex, neighbor.points);
}
}
else if (neighbor == null) {
unhighlight (plot);
}
}
function handleMouseDown(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
if (plot.series[ins[0]].highlightMouseDown && !(ins[0] == plot.plugins.lineRenderer.highlightedSeriesIndex)) {
var evt = jQuery.Event('jqplotDataHighlight');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
highlight (plot, neighbor.seriesIndex, neighbor.pointIndex, neighbor.points);
}
}
else if (neighbor == null) {
unhighlight (plot);
}
}
function handleMouseUp(ev, gridpos, datapos, neighbor, plot) {
var idx = plot.plugins.lineRenderer.highlightedSeriesIndex;
if (idx != null && plot.series[idx].highlightMouseDown) {
unhighlight(plot);
}
}
function handleClick(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
var evt = jQuery.Event('jqplotDataClick');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
}
}
function handleRightClick(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
var idx = plot.plugins.lineRenderer.highlightedSeriesIndex;
if (idx != null && plot.series[idx].highlightMouseDown) {
unhighlight(plot);
}
var evt = jQuery.Event('jqplotDataRightClick');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
}
}
// class: $.jqplot.LinearAxisRenderer
// The default jqPlot axis renderer, creating a numeric axis.
// The renderer has no additional options beyond the <Axis> object.
$.jqplot.LinearAxisRenderer = function() {
};
// called with scope of axis object.
$.jqplot.LinearAxisRenderer.prototype.init = function(options){
// prop: breakPoints
// EXPERIMENTAL!! Use at your own risk!
// Works only with linear axes and the default tick renderer.
// Array of [start, stop] points to create a broken axis.
// Broken axes have a "jump" in them, which is an immediate
// transition from a smaller value to a larger value.
// Currently, axis ticks MUST be manually assigned if using breakPoints
// by using the axis ticks array option.
this.breakPoints = null;
// prop: breakTickLabel
// Label to use at the axis break if breakPoints are specified.
this.breakTickLabel = "≈";
$.extend(true, this, options);
if (this.breakPoints) {
if (!$.isArray(this.breakPoints)) {
this.breakPoints = null;
}
else if (this.breakPoints.length < 2 || this.breakPoints[1] <= this.breakPoints[0]) {
this.breakPoints = null;
}
}
this.resetDataBounds();
};
// called with scope of axis
$.jqplot.LinearAxisRenderer.prototype.draw = function(ctx) {
if (this.show) {
// populate the axis label and value properties.
// createTicks is a method on the renderer, but
// call it within the scope of the axis.
this.renderer.createTicks.call(this);
// fill a div with axes labels in the right direction.
// Need to pregenerate each axis to get it's bounds and
// position it and the labels correctly on the plot.
var dim=0;
var temp;
// Added for theming.
if (this._elem) {
this._elem.empty();
}
this._elem = $('<div class="jqplot-axis jqplot-'+this.name+'" style="position:absolute;"></div>');
if (this.name == 'xaxis' || this.name == 'x2axis') {
this._elem.width(this._plotDimensions.width);
}
else {
this._elem.height(this._plotDimensions.height);
}
// create a _label object.
this.labelOptions.axis = this.name;
this._label = new this.labelRenderer(this.labelOptions);
var elem;
if (this._label.show) {
elem = this._label.draw(ctx);
elem.appendTo(this._elem);
}
var t = this._ticks;
for (var i=0; i<t.length; i++) {
var tick = t[i];
if (tick.show && tick.showLabel && (!tick.isMinorTick || this.showMinorTicks)) {
elem = tick.draw(ctx);
elem.appendTo(this._elem);
}
}
elem = null;
}
return this._elem;
};
// called with scope of an axis
$.jqplot.LinearAxisRenderer.prototype.reset = function() {
this.min = this._min;
this.max = this._max;
this.tickInterval = this._tickInterval;
this.numberTicks = this._numberTicks;
// this._ticks = this.__ticks;
};
// called with scope of axis
$.jqplot.LinearAxisRenderer.prototype.set = function() {
var dim = 0;
var temp;
var w = 0;
var h = 0;
var lshow = (this._label == null) ? false : this._label.show;
if (this.show) {
var t = this._ticks;
for (var i=0; i<t.length; i++) {
var tick = t[i];
if (!tick._breakTick && tick.show && tick.showLabel && (!tick.isMinorTick || this.showMinorTicks)) {
if (this.name == 'xaxis' || this.name == 'x2axis') {
temp = tick._elem.outerHeight(true);
}
else {
temp = tick._elem.outerWidth(true);
}
if (temp > dim) {
dim = temp;
}
}
}
if (lshow) {
w = this._label._elem.outerWidth(true);
h = this._label._elem.outerHeight(true);
}
if (this.name == 'xaxis') {
dim = dim + h;
this._elem.css({'height':dim+'px', left:'0px', bottom:'0px'});
}
else if (this.name == 'x2axis') {
dim = dim + h;
this._elem.css({'height':dim+'px', left:'0px', top:'0px'});
}
else if (this.name == 'yaxis') {
dim = dim + w;
this._elem.css({'width':dim+'px', left:'0px', top:'0px'});
if (lshow && this._label.constructor == $.jqplot.AxisLabelRenderer) {
this._label._elem.css('width', w+'px');
}
}
else {
dim = dim + w;
this._elem.css({'width':dim+'px', right:'0px', top:'0px'});
if (lshow && this._label.constructor == $.jqplot.AxisLabelRenderer) {
this._label._elem.css('width', w+'px');
}
}
}
};
// called with scope of axis
$.jqplot.LinearAxisRenderer.prototype.createTicks = function() {
// we're are operating on an axis here
var ticks = this._ticks;
var userTicks = this.ticks;
var name = this.name;
// databounds were set on axis initialization.
var db = this._dataBounds;
var dim, interval;
var min, max;
var pos1, pos2;
var tt, i;
// get a copy of user's settings for min/max.
var userMin = this.min;
var userMax = this.max;
var userNT = this.numberTicks;
var userTI = this.tickInterval;
// if we already have ticks, use them.
// ticks must be in order of increasing value.
if (userTicks.length) {
// ticks could be 1D or 2D array of [val, val, ,,,] or [[val, label], [val, label], ...] or mixed
for (i=0; i<userTicks.length; i++){
var ut = userTicks[i];
var t = new this.tickRenderer(this.tickOptions);
if (ut.constructor == Array) {
t.value = ut[0];
if (this.breakPoints) {
if (ut[0] == this.breakPoints[0]) {
t.label = this.breakTickLabel;
t._breakTick = true;
t.showGridline = false;
t.showMark = false;
}
else if (ut[0] > this.breakPoints[0] && ut[0] <= this.breakPoints[1]) {
t.show = false;
t.showGridline = false;
t.label = ut[1];
}
else {
t.label = ut[1];
}
}
else {
t.label = ut[1];
}
t.setTick(ut[0], this.name);
this._ticks.push(t);
}
else {
t.value = ut;
if (this.breakPoints) {
if (ut == this.breakPoints[0]) {
t.label = this.breakTickLabel;
t._breakTick = true;
t.showGridline = false;
t.showMark = false;
}
else if (ut > this.breakPoints[0] && ut <= this.breakPoints[1]) {
t.show = false;
t.showGridline = false;
}
}
t.setTick(ut, this.name);
this._ticks.push(t);
}
}
this.numberTicks = userTicks.length;
this.min = this._ticks[0].value;
this.max = this._ticks[this.numberTicks-1].value;
this.tickInterval = (this.max - this.min) / (this.numberTicks - 1);
}
// we don't have any ticks yet, let's make some!
else {
if (name == 'xaxis' || name == 'x2axis') {
dim = this._plotDimensions.width;
}
else {
dim = this._plotDimensions.height;
}
// if min, max and number of ticks specified, user can't specify interval.
if (!this.autoscale && this.min != null && this.max != null && this.numberTicks != null) {
this.tickInterval = null;
}
// if max, min, and interval specified and interval won't fit, ignore interval.
// if (this.min != null && this.max != null && this.tickInterval != null) {
// if (parseInt((this.max-this.min)/this.tickInterval, 10) != (this.max-this.min)/this.tickInterval) {
// this.tickInterval = null;
// }
// }
min = ((this.min != null) ? this.min : db.min);
max = ((this.max != null) ? this.max : db.max);
// if min and max are same, space them out a bit
if (min == max) {
var adj = 0.05;
if (min > 0) {
adj = Math.max(Math.log(min)/Math.LN10, 0.05);
}
min -= adj;
max += adj;
}
var range = max - min;
var rmin, rmax;
var temp;
// autoscale. Can't autoscale if min or max is supplied.
// Will use numberTicks and tickInterval if supplied. Ticks
// across multiple axes may not line up depending on how
// bars are to be plotted.
if (this.autoscale && this.min == null && this.max == null) {
var rrange, ti, margin;
var forceMinZero = false;
var forceZeroLine = false;
var intervals = {min:null, max:null, average:null, stddev:null};
// if any series are bars, or if any are fill to zero, and if this
// is the axis to fill toward, check to see if we can start axis at zero.
for (var i=0; i<this._series.length; i++) {
var s = this._series[i];
var faname = (s.fillAxis == 'x') ? s._xaxis.name : s._yaxis.name;
// check to see if this is the fill axis
if (this.name == faname) {
var vals = s._plotValues[s.fillAxis];
var vmin = vals[0];
var vmax = vals[0];
for (var j=1; j<vals.length; j++) {
if (vals[j] < vmin) {
vmin = vals[j];
}
else if (vals[j] > vmax) {
vmax = vals[j];
}
}
var dp = (vmax - vmin) / vmax;
// is this sries a bar?
if (s.renderer.constructor == $.jqplot.BarRenderer) {
// if no negative values and could also check range.
if (vmin >= 0 && (s.fillToZero || dp > 0.1)) {
forceMinZero = true;
}
else {
forceMinZero = false;
if (s.fill && s.fillToZero && vmin < 0 && vmax > 0) {
forceZeroLine = true;
}
else {
forceZeroLine = false;
}
}
}
// if not a bar and filling, use appropriate method.
else if (s.fill) {
if (vmin >= 0 && (s.fillToZero || dp > 0.1)) {
forceMinZero = true;
}
else if (vmin < 0 && vmax > 0 && s.fillToZero) {
forceMinZero = false;
forceZeroLine = true;
}
else {
forceMinZero = false;
forceZeroLine = false;
}
}
// if not a bar and not filling, only change existing state
// if it doesn't make sense
else if (vmin < 0) {
forceMinZero = false;
}
}
}
// check if we need make axis min at 0.
if (forceMinZero) {
// compute number of ticks
this.numberTicks = 2 + Math.ceil((dim-(this.tickSpacing-1))/this.tickSpacing);
this.min = 0;
userMin = 0;
// what order is this range?
// what tick interval does that give us?
ti = max/(this.numberTicks-1);
temp = Math.pow(10, Math.abs(Math.floor(Math.log(ti)/Math.LN10)));
if (ti/temp == parseInt(ti/temp, 10)) {
ti += temp;
}
this.tickInterval = Math.ceil(ti/temp) * temp;
this.max = this.tickInterval * (this.numberTicks - 1);
}
// check if we need to make sure there is a tick at 0.
else if (forceZeroLine) {
// compute number of ticks
this.numberTicks = 2 + Math.ceil((dim-(this.tickSpacing-1))/this.tickSpacing);
var ntmin = Math.ceil(Math.abs(min)/range*(this.numberTicks-1));
var ntmax = this.numberTicks - 1 - ntmin;
ti = Math.max(Math.abs(min/ntmin), Math.abs(max/ntmax));
temp = Math.pow(10, Math.abs(Math.floor(Math.log(ti)/Math.LN10)));
this.tickInterval = Math.ceil(ti/temp) * temp;
this.max = this.tickInterval * ntmax;
this.min = -this.tickInterval * ntmin;
}
// if nothing else, do autoscaling which will try to line up ticks across axes.
else {
if (this.numberTicks == null){
if (this.tickInterval) {
this.numberTicks = 3 + Math.ceil(range / this.tickInterval);
}
else {
this.numberTicks = 2 + Math.ceil((dim-(this.tickSpacing-1))/this.tickSpacing);
}
}
if (this.tickInterval == null) {
// get a tick interval
ti = range/(this.numberTicks - 1);
if (ti < 1) {
temp = Math.pow(10, Math.abs(Math.floor(Math.log(ti)/Math.LN10)));
}
else {
temp = 1;
}
this.tickInterval = Math.ceil(ti*temp*this.pad)/temp;
}
else {
temp = 1 / this.tickInterval;
}
// try to compute a nicer, more even tick interval
// temp = Math.pow(10, Math.floor(Math.log(ti)/Math.LN10));
// this.tickInterval = Math.ceil(ti/temp) * temp;
rrange = this.tickInterval * (this.numberTicks - 1);
margin = (rrange - range)/2;
if (this.min == null) {
this.min = Math.floor(temp*(min-margin))/temp;
}
if (this.max == null) {
this.max = this.min + rrange;
}
}
}
// Use the default algorithm which pads each axis to make the chart
// centered nicely on the grid.
else {
rmin = (this.min != null) ? this.min : min - range*(this.padMin - 1);
rmax = (this.max != null) ? this.max : max + range*(this.padMax - 1);
this.min = rmin;
this.max = rmax;
range = this.max - this.min;
if (this.numberTicks == null){
// if tickInterval is specified by user, we will ignore computed maximum.
// max will be equal or greater to fit even # of ticks.
if (this.tickInterval != null) {
this.numberTicks = Math.ceil((this.max - this.min)/this.tickInterval)+1;
this.max = this.min + this.tickInterval*(this.numberTicks-1);
}
else if (dim > 100) {
this.numberTicks = parseInt(3+(dim-100)/75, 10);
}
else {
this.numberTicks = 2;
}
}
if (this.tickInterval == null) {
this.tickInterval = range / (this.numberTicks-1);
}
}
if (this.renderer.constructor == $.jqplot.LinearAxisRenderer) {
// fix for misleading tick display with small range and low precision.
range = this.max - this.min;
// figure out precision
var temptick = new this.tickRenderer(this.tickOptions);
// use the tick formatString or, the default.
var fs = temptick.formatString || $.jqplot.config.defaultTickFormatString;
var fs = fs.match($.jqplot.sprintf.regex)[0];
var precision = 0;
if (fs) {
if (fs.search(/[fFeEgGpP]/) > -1) {
var m = fs.match(/\%\.(\d{0,})?[eEfFgGpP]/);
if (m) {
precision = parseInt(m[1], 10);
}
else {
precision = 6;
}
}
else if (fs.search(/[di]/) > -1) {
precision = 0;
}
// fact will be <= 1;
var fact = Math.pow(10, -precision);
if (this.tickInterval < fact) {
// need to correct underrange
if (userNT == null && userTI == null) {
this.tickInterval = fact;
if (userMax == null && userMin == null) {
// this.min = Math.floor((this._dataBounds.min - this.tickInterval)/fact) * fact;
this.min = Math.floor(this._dataBounds.min/fact) * fact;
if (this.min == this._dataBounds.min) {
this.min = this._dataBounds.min - this.tickInterval;
}
// this.max = Math.ceil((this._dataBounds.max + this.tickInterval)/fact) * fact;
this.max = Math.ceil(this._dataBounds.max/fact) * fact;
if (this.max == this._dataBounds.max) {
this.max = this._dataBounds.max + this.tickInterval;
}
var n = (this.max - this.min)/this.tickInterval;
n = n.toFixed(11);
n = Math.ceil(n);
this.numberTicks = n + 1;
}
else if (userMax == null) {
// add one tick for top of range.
var n = (this._dataBounds.max - this.min) / this.tickInterval;
n = n.toFixed(11);
this.numberTicks = Math.ceil(n) + 2;
this.max = this.min + this.tickInterval * (this.numberTicks-1);
}
else if (userMin == null) {
// add one tick for bottom of range.
var n = (this.max - this._dataBounds.min) / this.tickInterval;
n = n.toFixed(11);
this.numberTicks = Math.ceil(n) + 2;
this.min = this.max - this.tickInterval * (this.numberTicks-1);
}
else {
// calculate a number of ticks so max is within axis scale
this.numberTicks = Math.ceil((userMax - userMin)/this.tickInterval) + 1;
// if user's min and max don't fit evenly in ticks, adjust.
// This takes care of cases such as user min set to 0, max set to 3.5 but tick
// format string set to %d (integer ticks)
this.min = Math.floor(userMin*Math.pow(10, precision))/Math.pow(10, precision);
this.max = Math.ceil(userMax*Math.pow(10, precision))/Math.pow(10, precision);
// this.max = this.min + this.tickInterval*(this.numberTicks-1);
this.numberTicks = Math.ceil((this.max - this.min)/this.tickInterval) + 1;
}
}
}
}
}
for (var i=0; i<this.numberTicks; i++){
tt = this.min + i * this.tickInterval;
var t = new this.tickRenderer(this.tickOptions);
// var t = new $.jqplot.AxisTickRenderer(this.tickOptions);
t.setTick(tt, this.name);
this._ticks.push(t);
}
}
};
// Used to reset just the values of the ticks and then repack, which will
// recalculate the positioning functions. It is assuemd that the
// number of ticks is the same and the values of the new array are at the
// proper interval.
// This method needs to be called with the scope of an axis object, like:
//
// > plot.axes.yaxis.renderer.resetTickValues.call(plot.axes.yaxis, yarr);
//
$.jqplot.LinearAxisRenderer.prototype.resetTickValues = function(opts) {
if ($.isArray(opts) && opts.length == this._ticks.length) {
var t;
for (var i=0; i<opts.length; i++) {
t = this._ticks[i];
t.value = opts[i];
t.label = t.formatter(t.formatString, opts[i]);
// add prefix if needed
if (t.prefix && !t.formatString) {
t.label = t.prefix + t.label;
}
t._elem.html(t.label);
}
this.min = $.jqplot.arrayMin(opts);
this.max = $.jqplot.arrayMax(opts);
this.pack();
}
// Not implemented yet.
// else if ($.isPlainObject(opts)) {
//
// }
};
// called with scope of axis
$.jqplot.LinearAxisRenderer.prototype.pack = function(pos, offsets) {
// Add defaults for repacking from resetTickValues function.
pos = pos || {};
offsets = offsets || this._offsets;
var ticks = this._ticks;
var max = this.max;
var min = this.min;
var offmax = offsets.max;
var offmin = offsets.min;
var lshow = (this._label == null) ? false : this._label.show;
for (var p in pos) {
this._elem.css(p, pos[p]);
}
this._offsets = offsets;
// pixellength will be + for x axes and - for y axes becasue pixels always measured from top left.
var pixellength = offmax - offmin;
var unitlength = max - min;
// point to unit and unit to point conversions references to Plot DOM element top left corner.
if (this.breakPoints) {
unitlength = unitlength - this.breakPoints[1] + this.breakPoints[0];
this.p2u = function(p){
return (p - offmin) * unitlength / pixellength + min;
};
this.u2p = function(u){
if (u > this.breakPoints[0] && u < this.breakPoints[1]){
u = this.breakPoints[0];
}
if (u <= this.breakPoints[0]) {
return (u - min) * pixellength / unitlength + offmin;
}
else {
return (u - this.breakPoints[1] + this.breakPoints[0] - min) * pixellength / unitlength + offmin;
}
};
if (this.name.charAt(0) == 'x'){
this.series_u2p = function(u){
if (u > this.breakPoints[0] && u < this.breakPoints[1]){
u = this.breakPoints[0];
}
if (u <= this.breakPoints[0]) {
return (u - min) * pixellength / unitlength;
}
else {
return (u - this.breakPoints[1] + this.breakPoints[0] - min) * pixellength / unitlength;
}
};
this.series_p2u = function(p){
return p * unitlength / pixellength + min;
};
}
else {
this.series_u2p = function(u){
if (u > this.breakPoints[0] && u < this.breakPoints[1]){
u = this.breakPoints[0];
}
if (u >= this.breakPoints[1]) {
return (u - max) * pixellength / unitlength;
}
else {
return (u + this.breakPoints[1] - this.breakPoints[0] - max) * pixellength / unitlength;
}
};
this.series_p2u = function(p){
return p * unitlength / pixellength + max;
};
}
}
else {
this.p2u = function(p){
return (p - offmin) * unitlength / pixellength + min;
};
this.u2p = function(u){
return (u - min) * pixellength / unitlength + offmin;
};
if (this.name == 'xaxis' || this.name == 'x2axis'){
this.series_u2p = function(u){
return (u - min) * pixellength / unitlength;
};
this.series_p2u = function(p){
return p * unitlength / pixellength + min;
};
}
else {
this.series_u2p = function(u){
return (u - max) * pixellength / unitlength;
};
this.series_p2u = function(p){
return p * unitlength / pixellength + max;
};
}
}
if (this.show) {
if (this.name == 'xaxis' || this.name == 'x2axis') {
for (i=0; i<ticks.length; i++) {
var t = ticks[i];
if (t.show && t.showLabel) {
var shim;
if (t.constructor == $.jqplot.CanvasAxisTickRenderer && t.angle) {
// will need to adjust auto positioning based on which axis this is.
var temp = (this.name == 'xaxis') ? 1 : -1;
switch (t.labelPosition) {
case 'auto':
// position at end
if (temp * t.angle < 0) {
shim = -t.getWidth() + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
}
// position at start
else {
shim = -t._textRenderer.height * Math.sin(t._textRenderer.angle) / 2;
}
break;
case 'end':
shim = -t.getWidth() + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
break;
case 'start':
shim = -t._textRenderer.height * Math.sin(t._textRenderer.angle) / 2;
break;
case 'middle':
shim = -t.getWidth()/2 + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
break;
default:
shim = -t.getWidth()/2 + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
break;
}
}
else {
shim = -t.getWidth()/2;
}
var val = this.u2p(t.value) + shim + 'px';
t._elem.css('left', val);
t.pack();
}
}
if (lshow) {
var w = this._label._elem.outerWidth(true);
this._label._elem.css('left', offmin + pixellength/2 - w/2 + 'px');
if (this.name == 'xaxis') {
this._label._elem.css('bottom', '0px');
}
else {
this._label._elem.css('top', '0px');
}
this._label.pack();
}
}
else {
for (i=0; i<ticks.length; i++) {
var t = ticks[i];
if (t.show && t.showLabel) {
var shim;
if (t.constructor == $.jqplot.CanvasAxisTickRenderer && t.angle) {
// will need to adjust auto positioning based on which axis this is.
var temp = (this.name == 'yaxis') ? 1 : -1;
switch (t.labelPosition) {
case 'auto':
// position at end
case 'end':
if (temp * t.angle < 0) {
shim = -t._textRenderer.height * Math.cos(-t._textRenderer.angle) / 2;
}
else {
shim = -t.getHeight() + t._textRenderer.height * Math.cos(t._textRenderer.angle) / 2;
}
break;
case 'start':
if (t.angle > 0) {
shim = -t._textRenderer.height * Math.cos(-t._textRenderer.angle) / 2;
}
else {
shim = -t.getHeight() + t._textRenderer.height * Math.cos(t._textRenderer.angle) / 2;
}
break;
case 'middle':
// if (t.angle > 0) {
// shim = -t.getHeight()/2 + t._textRenderer.height * Math.sin(-t._textRenderer.angle) / 2;
// }
// else {
// shim = -t.getHeight()/2 - t._textRenderer.height * Math.sin(t._textRenderer.angle) / 2;
// }
shim = -t.getHeight()/2;
break;
default:
shim = -t.getHeight()/2;
break;
}
}
else {
shim = -t.getHeight()/2;
}
var val = this.u2p(t.value) + shim + 'px';
t._elem.css('top', val);
t.pack();
}
}
if (lshow) {
var h = this._label._elem.outerHeight(true);
this._label._elem.css('top', offmax - pixellength/2 - h/2 + 'px');
if (this.name == 'yaxis') {
this._label._elem.css('left', '0px');
}
else {
this._label._elem.css('right', '0px');
}
this._label.pack();
}
}
}
};
// class: $.jqplot.MarkerRenderer
// The default jqPlot marker renderer, rendering the points on the line.
$.jqplot.MarkerRenderer = function(options){
// Group: Properties
// prop: show
// wether or not to show the marker.
this.show = true;
// prop: style
// One of diamond, circle, square, x, plus, dash, filledDiamond, filledCircle, filledSquare
this.style = 'filledCircle';
// prop: lineWidth
// size of the line for non-filled markers.
this.lineWidth = 2;
// prop: size
// Size of the marker (diameter or circle, length of edge of square, etc.)
this.size = 9.0;
// prop: color
// color of marker. Will be set to color of series by default on init.
this.color = '#666666';
// prop: shadow
// wether or not to draw a shadow on the line
this.shadow = true;
// prop: shadowAngle
// Shadow angle in degrees
this.shadowAngle = 45;
// prop: shadowOffset
// Shadow offset from line in pixels
this.shadowOffset = 1;
// prop: shadowDepth
// Number of times shadow is stroked, each stroke offset shadowOffset from the last.
this.shadowDepth = 3;
// prop: shadowAlpha
// Alpha channel transparency of shadow. 0 = transparent.
this.shadowAlpha = '0.07';
// prop: shadowRenderer
// Renderer that will draws the shadows on the marker.
this.shadowRenderer = new $.jqplot.ShadowRenderer();
// prop: shapeRenderer
// Renderer that will draw the marker.
this.shapeRenderer = new $.jqplot.ShapeRenderer();
$.extend(true, this, options);
};
$.jqplot.MarkerRenderer.prototype.init = function(options) {
$.extend(true, this, options);
var sdopt = {angle:this.shadowAngle, offset:this.shadowOffset, alpha:this.shadowAlpha, lineWidth:this.lineWidth, depth:this.shadowDepth, closePath:true};
if (this.style.indexOf('filled') != -1) {
sdopt.fill = true;
}
if (this.style.indexOf('ircle') != -1) {
sdopt.isarc = true;
sdopt.closePath = false;
}
this.shadowRenderer.init(sdopt);
var shopt = {fill:false, isarc:false, strokeStyle:this.color, fillStyle:this.color, lineWidth:this.lineWidth, closePath:true};
if (this.style.indexOf('filled') != -1) {
shopt.fill = true;
}
if (this.style.indexOf('ircle') != -1) {
shopt.isarc = true;
shopt.closePath = false;
}
this.shapeRenderer.init(shopt);
};
$.jqplot.MarkerRenderer.prototype.drawDiamond = function(x, y, ctx, fill, options) {
var stretch = 1.2;
var dx = this.size/2/stretch;
var dy = this.size/2*stretch;
var points = [[x-dx, y], [x, y+dy], [x+dx, y], [x, y-dy]];
if (this.shadow) {
this.shadowRenderer.draw(ctx, points);
}
this.shapeRenderer.draw(ctx, points, options);
};
$.jqplot.MarkerRenderer.prototype.drawPlus = function(x, y, ctx, fill, options) {
var stretch = 1.0;
var dx = this.size/2*stretch;
var dy = this.size/2*stretch;
var points1 = [[x, y-dy], [x, y+dy]];
var points2 = [[x+dx, y], [x-dx, y]];
var opts = $.extend(true, {}, this.options, {closePath:false});
if (this.shadow) {
this.shadowRenderer.draw(ctx, points1, {closePath:false});
this.shadowRenderer.draw(ctx, points2, {closePath:false});
}
this.shapeRenderer.draw(ctx, points1, opts);
this.shapeRenderer.draw(ctx, points2, opts);
};
$.jqplot.MarkerRenderer.prototype.drawX = function(x, y, ctx, fill, options) {
var stretch = 1.0;
var dx = this.size/2*stretch;
var dy = this.size/2*stretch;
var opts = $.extend(true, {}, this.options, {closePath:false});
var points1 = [[x-dx, y-dy], [x+dx, y+dy]];
var points2 = [[x-dx, y+dy], [x+dx, y-dy]];
if (this.shadow) {
this.shadowRenderer.draw(ctx, points1, {closePath:false});
this.shadowRenderer.draw(ctx, points2, {closePath:false});
}
this.shapeRenderer.draw(ctx, points1, opts);
this.shapeRenderer.draw(ctx, points2, opts);
};
$.jqplot.MarkerRenderer.prototype.drawDash = function(x, y, ctx, fill, options) {
var stretch = 1.0;
var dx = this.size/2*stretch;
var dy = this.size/2*stretch;
var points = [[x-dx, y], [x+dx, y]];
if (this.shadow) {
this.shadowRenderer.draw(ctx, points);
}
this.shapeRenderer.draw(ctx, points, options);
};
$.jqplot.MarkerRenderer.prototype.drawLine = function(p1, p2, ctx, fill, options) {
var points = [p1, p2];
if (this.shadow) {
this.shadowRenderer.draw(ctx, points);
}
this.shapeRenderer.draw(ctx, points, options);
};
$.jqplot.MarkerRenderer.prototype.drawSquare = function(x, y, ctx, fill, options) {
var stretch = 1.0;
var dx = this.size/2/stretch;
var dy = this.size/2*stretch;
var points = [[x-dx, y-dy], [x-dx, y+dy], [x+dx, y+dy], [x+dx, y-dy]];
if (this.shadow) {
this.shadowRenderer.draw(ctx, points);
}
this.shapeRenderer.draw(ctx, points, options);
};
$.jqplot.MarkerRenderer.prototype.drawCircle = function(x, y, ctx, fill, options) {
var radius = this.size/2;
var end = 2*Math.PI;
var points = [x, y, radius, 0, end, true];
if (this.shadow) {
this.shadowRenderer.draw(ctx, points);
}
this.shapeRenderer.draw(ctx, points, options);
};
$.jqplot.MarkerRenderer.prototype.draw = function(x, y, ctx, options) {
options = options || {};
// hack here b/c shape renderer uses canvas based color style options
// and marker uses css style names.
if (options.show == null || options.show != false) {
if (options.color && !options.fillStyle) {
options.fillStyle = options.color;
}
if (options.color && !options.strokeStyle) {
options.strokeStyle = options.color;
}
switch (this.style) {
case 'diamond':
this.drawDiamond(x,y,ctx, false, options);
break;
case 'filledDiamond':
this.drawDiamond(x,y,ctx, true, options);
break;
case 'circle':
this.drawCircle(x,y,ctx, false, options);
break;
case 'filledCircle':
this.drawCircle(x,y,ctx, true, options);
break;
case 'square':
this.drawSquare(x,y,ctx, false, options);
break;
case 'filledSquare':
this.drawSquare(x,y,ctx, true, options);
break;
case 'x':
this.drawX(x,y,ctx, true, options);
break;
case 'plus':
this.drawPlus(x,y,ctx, true, options);
break;
case 'dash':
this.drawDash(x,y,ctx, true, options);
break;
case 'line':
this.drawLine(x, y, ctx, false, options);
break;
default:
this.drawDiamond(x,y,ctx, false, options);
break;
}
}
};
// class: $.jqplot.shadowRenderer
// The default jqPlot shadow renderer, rendering shadows behind shapes.
$.jqplot.ShadowRenderer = function(options){
// Group: Properties
// prop: angle
// Angle of the shadow in degrees. Measured counter-clockwise from the x axis.
this.angle = 45;
// prop: offset
// Pixel offset at the given shadow angle of each shadow stroke from the last stroke.
this.offset = 1;
// prop: alpha
// alpha transparency of shadow stroke.
this.alpha = 0.07;
// prop: lineWidth
// width of the shadow line stroke.
this.lineWidth = 1.5;
// prop: lineJoin
// How line segments of the shadow are joined.
this.lineJoin = 'miter';
// prop: lineCap
// how ends of the shadow line are rendered.
this.lineCap = 'round';
// prop; closePath
// whether line path segment is closed upon itself.
this.closePath = false;
// prop: fill
// whether to fill the shape.
this.fill = false;
// prop: depth
// how many times the shadow is stroked. Each stroke will be offset by offset at angle degrees.
this.depth = 3;
this.strokeStyle = 'rgba(0,0,0,0.1)';
// prop: isarc
// wether the shadow is an arc or not.
this.isarc = false;
$.extend(true, this, options);
};
$.jqplot.ShadowRenderer.prototype.init = function(options) {
$.extend(true, this, options);
};
// function: draw
// draws an transparent black (i.e. gray) shadow.
//
// ctx - canvas drawing context
// points - array of points or [x, y, radius, start angle (rad), end angle (rad)]
$.jqplot.ShadowRenderer.prototype.draw = function(ctx, points, options) {
ctx.save();
var opts = (options != null) ? options : {};
var fill = (opts.fill != null) ? opts.fill : this.fill;
var closePath = (opts.closePath != null) ? opts.closePath : this.closePath;
var offset = (opts.offset != null) ? opts.offset : this.offset;
var alpha = (opts.alpha != null) ? opts.alpha : this.alpha;
var depth = (opts.depth != null) ? opts.depth : this.depth;
var isarc = (opts.isarc != null) ? opts.isarc : this.isarc;
ctx.lineWidth = (opts.lineWidth != null) ? opts.lineWidth : this.lineWidth;
ctx.lineJoin = (opts.lineJoin != null) ? opts.lineJoin : this.lineJoin;
ctx.lineCap = (opts.lineCap != null) ? opts.lineCap : this.lineCap;
ctx.strokeStyle = opts.strokeStyle || this.strokeStyle || 'rgba(0,0,0,'+alpha+')';
ctx.fillStyle = opts.fillStyle || this.fillStyle || 'rgba(0,0,0,'+alpha+')';
for (var j=0; j<depth; j++) {
ctx.translate(Math.cos(this.angle*Math.PI/180)*offset, Math.sin(this.angle*Math.PI/180)*offset);
ctx.beginPath();
if (isarc) {
ctx.arc(points[0], points[1], points[2], points[3], points[4], true);
}
else if (points && points.length){
var move = true;
for (var i=0; i<points.length; i++) {
// skip to the first non-null point and move to it.
if (points[i][0] != null && points[i][1] != null) {
if (move) {
ctx.moveTo(points[i][0], points[i][1]);
move = false;
}
else {
ctx.lineTo(points[i][0], points[i][1]);
}
}
else {
move = true;
}
}
}
if (closePath) {
ctx.closePath();
}
if (fill) {
ctx.fill();
}
else {
ctx.stroke();
}
}
ctx.restore();
};
// class: $.jqplot.shapeRenderer
// The default jqPlot shape renderer. Given a set of points will
// plot them and either stroke a line (fill = false) or fill them (fill = true).
// If a filled shape is desired, closePath = true must also be set to close
// the shape.
$.jqplot.ShapeRenderer = function(options){
this.lineWidth = 1.5;
// prop: lineJoin
// How line segments of the shadow are joined.
this.lineJoin = 'miter';
// prop: lineCap
// how ends of the shadow line are rendered.
this.lineCap = 'round';
// prop; closePath
// whether line path segment is closed upon itself.
this.closePath = false;
// prop: fill
// whether to fill the shape.
this.fill = false;
// prop: isarc
// wether the shadow is an arc or not.
this.isarc = false;
// prop: fillRect
// true to draw shape as a filled rectangle.
this.fillRect = false;
// prop: strokeRect
// true to draw shape as a stroked rectangle.
this.strokeRect = false;
// prop: clearRect
// true to cear a rectangle.
this.clearRect = false;
// prop: strokeStyle
// css color spec for the stoke style
this.strokeStyle = '#999999';
// prop: fillStyle
// css color spec for the fill style.
this.fillStyle = '#999999';
$.extend(true, this, options);
};
$.jqplot.ShapeRenderer.prototype.init = function(options) {
$.extend(true, this, options);
};
// function: draw
// draws the shape.
//
// ctx - canvas drawing context
// points - array of points for shapes or
// [x, y, width, height] for rectangles or
// [x, y, radius, start angle (rad), end angle (rad)] for circles and arcs.
$.jqplot.ShapeRenderer.prototype.draw = function(ctx, points, options) {
ctx.save();
var opts = (options != null) ? options : {};
var fill = (opts.fill != null) ? opts.fill : this.fill;
var closePath = (opts.closePath != null) ? opts.closePath : this.closePath;
var fillRect = (opts.fillRect != null) ? opts.fillRect : this.fillRect;
var strokeRect = (opts.strokeRect != null) ? opts.strokeRect : this.strokeRect;
var clearRect = (opts.clearRect != null) ? opts.clearRect : this.clearRect;
var isarc = (opts.isarc != null) ? opts.isarc : this.isarc;
ctx.lineWidth = opts.lineWidth || this.lineWidth;
ctx.lineJoin = opts.lineJoing || this.lineJoin;
ctx.lineCap = opts.lineCap || this.lineCap;
ctx.strokeStyle = (opts.strokeStyle || opts.color) || this.strokeStyle;
ctx.fillStyle = opts.fillStyle || this.fillStyle;
ctx.beginPath();
if (isarc) {
ctx.arc(points[0], points[1], points[2], points[3], points[4], true);
if (closePath) {
ctx.closePath();
}
if (fill) {
ctx.fill();
}
else {
ctx.stroke();
}
ctx.restore();
return;
}
else if (clearRect) {
ctx.clearRect(points[0], points[1], points[2], points[3]);
ctx.restore();
return;
}
else if (fillRect || strokeRect) {
if (fillRect) {
ctx.fillRect(points[0], points[1], points[2], points[3]);
}
if (strokeRect) {
ctx.strokeRect(points[0], points[1], points[2], points[3]);
ctx.restore();
return;
}
}
else if (points && points.length){
var move = true;
for (var i=0; i<points.length; i++) {
// skip to the first non-null point and move to it.
if (points[i][0] != null && points[i][1] != null) {
if (move) {
ctx.moveTo(points[i][0], points[i][1]);
move = false;
}
else {
ctx.lineTo(points[i][0], points[i][1]);
}
}
else {
move = true;
}
}
if (closePath) {
ctx.closePath();
}
if (fill) {
ctx.fill();
}
else {
ctx.stroke();
}
}
ctx.restore();
};
// class $.jqplot.TableLegendRenderer
// The default legend renderer for jqPlot.
$.jqplot.TableLegendRenderer = function(){
//
};
$.jqplot.TableLegendRenderer.prototype.init = function(options) {
$.extend(true, this, options);
};
$.jqplot.TableLegendRenderer.prototype.addrow = function (label, color, pad, reverse) {
var rs = (pad) ? this.rowSpacing : '0';
var tr,
elem;
if (reverse){
tr = $('<tr class="jqplot-table-legend"></tr>').prependTo(this._elem);
}
else{
tr = $('<tr class="jqplot-table-legend"></tr>').appendTo(this._elem);
}
if (this.showSwatches) {
$('<td class="jqplot-table-legend" style="text-align:center;padding-top:'+rs+';">'+
'<div><div class="jqplot-table-legend-swatch" style="background-color:'+color+';border-color:'+color+';"></div>'+
'</div></td>').appendTo(tr);
}
if (this.showLabels) {
elem = $('<td class="jqplot-table-legend" style="padding-top:'+rs+';"></td>');
elem.appendTo(tr);
if (this.escapeHtml) {
elem.text(label);
}
else {
elem.html(label);
}
}
tr = null;
elem = null;
};
// called with scope of legend
$.jqplot.TableLegendRenderer.prototype.draw = function() {
var legend = this;
if (this.show) {
var series = this._series;
// make a table. one line label per row.
var ss = 'position:absolute;';
ss += (this.background) ? 'background:'+this.background+';' : '';
ss += (this.border) ? 'border:'+this.border+';' : '';
ss += (this.fontSize) ? 'font-size:'+this.fontSize+';' : '';
ss += (this.fontFamily) ? 'font-family:'+this.fontFamily+';' : '';
ss += (this.textColor) ? 'color:'+this.textColor+';' : '';
ss += (this.marginTop != null) ? 'margin-top:'+this.marginTop+';' : '';
ss += (this.marginBottom != null) ? 'margin-bottom:'+this.marginBottom+';' : '';
ss += (this.marginLeft != null) ? 'margin-left:'+this.marginLeft+';' : '';
ss += (this.marginRight != null) ? 'margin-right:'+this.marginRight+';' : '';
this._elem = $('<table class="jqplot-table-legend" style="'+ss+'"></table>');
var pad = false,
reverse = false;
for (var i = 0; i< series.length; i++) {
s = series[i];
if (s._stack || s.renderer.constructor == $.jqplot.BezierCurveRenderer){
reverse = true;
}
if (s.show && s.showLabel) {
var lt = this.labels[i] || s.label.toString();
if (lt) {
var color = s.color;
if (reverse && i < series.length - 1){
pad = true;
}
else if (reverse && i == series.length - 1){
pad = false;
}
this.renderer.addrow.call(this, lt, color, pad, reverse);
pad = true;
}
// let plugins add more rows to legend. Used by trend line plugin.
for (var j=0; j<$.jqplot.addLegendRowHooks.length; j++) {
var item = $.jqplot.addLegendRowHooks[j].call(this, s);
if (item) {
this.renderer.addrow.call(this, item.label, item.color, pad);
pad = true;
}
}
lt = null;
}
}
}
return this._elem;
};
$.jqplot.TableLegendRenderer.prototype.pack = function(offsets) {
if (this.show) {
if (this.placement == 'insideGrid') {
switch (this.location) {
case 'nw':
var a = offsets.left;
var b = offsets.top;
this._elem.css('left', a);
this._elem.css('top', b);
break;
case 'n':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
var b = offsets.top;
this._elem.css('left', a);
this._elem.css('top', b);
break;
case 'ne':
var a = offsets.right;
var b = offsets.top;
this._elem.css({right:a, top:b});
break;
case 'e':
var a = offsets.right;
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({right:a, top:b});
break;
case 'se':
var a = offsets.right;
var b = offsets.bottom;
this._elem.css({right:a, bottom:b});
break;
case 's':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
var b = offsets.bottom;
this._elem.css({left:a, bottom:b});
break;
case 'sw':
var a = offsets.left;
var b = offsets.bottom;
this._elem.css({left:a, bottom:b});
break;
case 'w':
var a = offsets.left;
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({left:a, top:b});
break;
default: // same as 'se'
var a = offsets.right;
var b = offsets.bottom;
this._elem.css({right:a, bottom:b});
break;
}
}
else if (this.placement == 'outside'){
switch (this.location) {
case 'nw':
var a = this._plotDimensions.width - offsets.left;
var b = offsets.top;
this._elem.css('right', a);
this._elem.css('top', b);
break;
case 'n':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
var b = this._plotDimensions.height - offsets.top;
this._elem.css('left', a);
this._elem.css('bottom', b);
break;
case 'ne':
var a = this._plotDimensions.width - offsets.right;
var b = offsets.top;
this._elem.css({left:a, top:b});
break;
case 'e':
var a = this._plotDimensions.width - offsets.right;
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({left:a, top:b});
break;
case 'se':
var a = this._plotDimensions.width - offsets.right;
var b = offsets.bottom;
this._elem.css({left:a, bottom:b});
break;
case 's':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
var b = this._plotDimensions.height - offsets.bottom;
this._elem.css({left:a, top:b});
break;
case 'sw':
var a = this._plotDimensions.width - offsets.left;
var b = offsets.bottom;
this._elem.css({right:a, bottom:b});
break;
case 'w':
var a = this._plotDimensions.width - offsets.left;
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({right:a, top:b});
break;
default: // same as 'se'
var a = offsets.right;
var b = offsets.bottom;
this._elem.css({right:a, bottom:b});
break;
}
}
else {
switch (this.location) {
case 'nw':
this._elem.css({left:0, top:offsets.top});
break;
case 'n':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
this._elem.css({left: a, top:offsets.top});
break;
case 'ne':
this._elem.css({right:0, top:offsets.top});
break;
case 'e':
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({right:offsets.right, top:b});
break;
case 'se':
this._elem.css({right:offsets.right, bottom:offsets.bottom});
break;
case 's':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
this._elem.css({left: a, bottom:offsets.bottom});
break;
case 'sw':
this._elem.css({left:offsets.left, bottom:offsets.bottom});
break;
case 'w':
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({left:offsets.left, top:b});
break;
default: // same as 'se'
this._elem.css({right:offsets.right, bottom:offsets.bottom});
break;
}
}
}
};
/**
* Class: $.jqplot.ThemeEngine
* Theme Engine provides a programatic way to change some of the more
* common jqplot styling options such as fonts, colors and grid options.
* A theme engine instance is created with each plot. The theme engine
* manages a collection of themes which can be modified, added to, or
* applied to the plot.
*
* The themeEngine class is not instantiated directly.
* When a plot is initialized, the current plot options are scanned
* an a default theme named "Default" is created. This theme is
* used as the basis for other themes added to the theme engine and
* is always available.
*
* A theme is a simple javascript object with styling parameters for
* various entities of the plot. A theme has the form:
*
*
* > {
* > _name:f "Default",
* > target: {
* > backgroundColor: "transparent"
* > },
* > legend: {
* > textColor: null,
* > fontFamily: null,
* > fontSize: null,
* > border: null,
* > background: null
* > },
* > title: {
* > textColor: "rgb(102, 102, 102)",
* > fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif",
* > fontSize: "19.2px",
* > textAlign: "center"
* > },
* > seriesStyles: {},
* > series: [{
* > color: "#4bb2c5",
* > lineWidth: 2.5,
* > shadow: true,
* > fillColor: "#4bb2c5",
* > showMarker: true,
* > markerOptions: {
* > color: "#4bb2c5",
* > show: true,
* > style: 'filledCircle',
* > lineWidth: 1.5,
* > size: 4,
* > shadow: true
* > }
* > }],
* > grid: {
* > drawGridlines: true,
* > gridLineColor: "#cccccc",
* > gridLineWidth: 1,
* > backgroundColor: "#fffdf6",
* > borderColor: "#999999",
* > borderWidth: 2,
* > shadow: true
* > },
* > axesStyles: {
* > label: {},
* > ticks: {}
* > },
* > axes: {
* > xaxis: {
* > borderColor: "#999999",
* > borderWidth: 2,
* > ticks: {
* > show: true,
* > showGridline: true,
* > showLabel: true,
* > showMark: true,
* > size: 4,
* > textColor: "",
* > whiteSpace: "nowrap",
* > fontSize: "12px",
* > fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif"
* > },
* > label: {
* > textColor: "rgb(102, 102, 102)",
* > whiteSpace: "normal",
* > fontSize: "14.6667px",
* > fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif",
* > fontWeight: "400"
* > }
* > },
* > yaxis: {
* > borderColor: "#999999",
* > borderWidth: 2,
* > ticks: {
* > show: true,
* > showGridline: true,
* > showLabel: true,
* > showMark: true,
* > size: 4,
* > textColor: "",
* > whiteSpace: "nowrap",
* > fontSize: "12px",
* > fontFamily: "'Trebuchet MS',Arial,Helvetica,sans-serif"
* > },
* > label: {
* > textColor: null,
* > whiteSpace: null,
* > fontSize: null,
* > fontFamily: null,
* > fontWeight: null
* > }
* > },
* > x2axis: {...
* > },
* > ...
* > y9axis: {...
* > }
* > }
* > }
*
* "seriesStyles" is a style object that will be applied to all series in the plot.
* It will forcibly override any styles applied on the individual series. "axesStyles" is
* a style object that will be applied to all axes in the plot. It will also forcibly
* override any styles on the individual axes.
*
* The example shown above has series options for a line series. Options for other
* series types are shown below:
*
* Bar Series:
*
* > {
* > color: "#4bb2c5",
* > seriesColors: ["#4bb2c5", "#EAA228", "#c5b47f", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc", "#c747a3", "#cddf54", "#FBD178", "#26B4E3", "#bd70c7"],
* > lineWidth: 2.5,
* > shadow: true,
* > barPadding: 2,
* > barMargin: 10,
* > barWidth: 15.09375,
* > highlightColors: ["rgb(129,201,214)", "rgb(129,201,214)", "rgb(129,201,214)", "rgb(129,201,214)", "rgb(129,201,214)", "rgb(129,201,214)", "rgb(129,201,214)", "rgb(129,201,214)"]
* > }
*
* Pie Series:
*
* > {
* > seriesColors: ["#4bb2c5", "#EAA228", "#c5b47f", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc", "#c747a3", "#cddf54", "#FBD178", "#26B4E3", "#bd70c7"],
* > padding: 20,
* > sliceMargin: 0,
* > fill: true,
* > shadow: true,
* > startAngle: 0,
* > lineWidth: 2.5,
* > highlightColors: ["rgb(129,201,214)", "rgb(240,189,104)", "rgb(214,202,165)", "rgb(137,180,158)", "rgb(168,180,137)", "rgb(180,174,89)", "rgb(180,113,161)", "rgb(129,141,236)", "rgb(227,205,120)", "rgb(255,138,76)", "rgb(76,169,219)", "rgb(215,126,190)", "rgb(220,232,135)", "rgb(200,167,96)", "rgb(103,202,235)", "rgb(208,154,215)"]
* > }
*
* Funnel Series:
*
* > {
* > color: "#4bb2c5",
* > lineWidth: 2,
* > shadow: true,
* > padding: {
* > top: 20,
* > right: 20,
* > bottom: 20,
* > left: 20
* > },
* > sectionMargin: 6,
* > seriesColors: ["#4bb2c5", "#EAA228", "#c5b47f", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc", "#c747a3", "#cddf54", "#FBD178", "#26B4E3", "#bd70c7"],
* > highlightColors: ["rgb(147,208,220)", "rgb(242,199,126)", "rgb(220,210,178)", "rgb(154,191,172)", "rgb(180,191,154)", "rgb(191,186,112)", "rgb(191,133,174)", "rgb(147,157,238)", "rgb(231,212,139)", "rgb(255,154,102)", "rgb(102,181,224)", "rgb(221,144,199)", "rgb(225,235,152)", "rgb(200,167,96)", "rgb(124,210,238)", "rgb(215,169,221)"]
* > }
*
*/
$.jqplot.ThemeEngine = function(){
// Group: Properties
//
// prop: themes
// hash of themes managed by the theme engine.
// Indexed by theme name.
this.themes = {};
// prop: activeTheme
// Pointer to currently active theme
this.activeTheme=null;
};
// called with scope of plot
$.jqplot.ThemeEngine.prototype.init = function() {
// get the Default theme from the current plot settings.
var th = new $.jqplot.Theme({_name:'Default'});
var n, i;
for (n in th.target) {
if (n == "textColor") {
th.target[n] = this.target.css('color');
}
else {
th.target[n] = this.target.css(n);
}
}
if (this.title.show && this.title._elem) {
for (n in th.title) {
if (n == "textColor") {
th.title[n] = this.title._elem.css('color');
}
else {
th.title[n] = this.title._elem.css(n);
}
}
}
for (n in th.grid) {
th.grid[n] = this.grid[n];
}
if (th.grid.backgroundColor == null && this.grid.background != null) {
th.grid.backgroundColor = this.grid.background;
}
if (this.legend.show && this.legend._elem) {
for (n in th.legend) {
if (n == 'textColor') {
th.legend[n] = this.legend._elem.css('color');
}
else {
th.legend[n] = this.legend._elem.css(n);
}
}
}
var s;
for (i=0; i<this.series.length; i++) {
s = this.series[i];
if (s.renderer.constructor == $.jqplot.LineRenderer) {
th.series.push(new LineSeriesProperties());
}
else if (s.renderer.constructor == $.jqplot.BarRenderer) {
th.series.push(new BarSeriesProperties());
}
else if (s.renderer.constructor == $.jqplot.PieRenderer) {
th.series.push(new PieSeriesProperties());
}
else if (s.renderer.constructor == $.jqplot.DonutRenderer) {
th.series.push(new DonutSeriesProperties());
}
else if (s.renderer.constructor == $.jqplot.FunnelRenderer) {
th.series.push(new FunnelSeriesProperties());
}
else if (s.renderer.constructor == $.jqplot.MeterGaugeRenderer) {
th.series.push(new MeterSeriesProperties());
}
else {
th.series.push({});
}
for (n in th.series[i]) {
th.series[i][n] = s[n];
}
}
var a, ax;
for (n in this.axes) {
ax = this.axes[n];
a = th.axes[n] = new AxisProperties();
a.borderColor = ax.borderColor;
a.borderWidth = ax.borderWidth;
if (ax._ticks && ax._ticks[0]) {
for (nn in a.ticks) {
if (ax._ticks[0].hasOwnProperty(nn)) {
a.ticks[nn] = ax._ticks[0][nn];
}
else if (ax._ticks[0]._elem){
a.ticks[nn] = ax._ticks[0]._elem.css(nn);
}
}
}
if (ax._label && ax._label.show) {
for (nn in a.label) {
// a.label[nn] = ax._label._elem.css(nn);
if (ax._label[nn]) {
a.label[nn] = ax._label[nn];
}
else if (ax._label._elem){
if (nn == 'textColor') {
a.label[nn] = ax._label._elem.css('color');
}
else {
a.label[nn] = ax._label._elem.css(nn);
}
}
}
}
}
this.themeEngine._add(th);
this.themeEngine.activeTheme = this.themeEngine.themes[th._name];
};
/**
* Group: methods
*
* method: get
*
* Get and return the named theme or the active theme if no name given.
*
* parameter:
*
* name - name of theme to get.
*
* returns:
*
* Theme instance of given name.
*/
$.jqplot.ThemeEngine.prototype.get = function(name) {
if (!name) {
// return the active theme
return this.activeTheme;
}
else {
return this.themes[name];
}
};
function numericalOrder(a,b) { return a-b; }
/**
* method: getThemeNames
*
* Return the list of theme names in this manager in alpha-numerical order.
*
* parameter:
*
* None
*
* returns:
*
* A the list of theme names in this manager in alpha-numerical order.
*/
$.jqplot.ThemeEngine.prototype.getThemeNames = function() {
var tn = [];
for (var n in this.themes) {
tn.push(n);
}
return tn.sort(numericalOrder);
};
/**
* method: getThemes
*
* Return a list of themes in alpha-numerical order by name.
*
* parameter:
*
* None
*
* returns:
*
* A list of themes in alpha-numerical order by name.
*/
$.jqplot.ThemeEngine.prototype.getThemes = function() {
var tn = [];
var themes = [];
for (var n in this.themes) {
tn.push(n);
}
tn.sort(numericalOrder);
for (var i=0; i<tn.length; i++) {
themes.push(this.themes[tn[i]]);
}
return themes;
};
$.jqplot.ThemeEngine.prototype.activate = function(plot, name) {
// sometimes need to redraw whole plot.
var redrawPlot = false;
if (!name && this.activeTheme && this.activeTheme._name) {
name = this.activeTheme._name;
}
if (!this.themes.hasOwnProperty(name)) {
throw new Error("No theme of that name");
}
else {
var th = this.themes[name];
this.activeTheme = th;
var val, checkBorderColor = false, checkBorderWidth = false;
var arr = ['xaxis', 'x2axis', 'yaxis', 'y2axis'];
for (i=0; i<arr.length; i++) {
var ax = arr[i];
if (th.axesStyles.borderColor != null) {
plot.axes[ax].borderColor = th.axesStyles.borderColor;
}
if (th.axesStyles.borderWidth != null) {
plot.axes[ax].borderWidth = th.axesStyles.borderWidth;
}
}
for (axname in plot.axes) {
var axis = plot.axes[axname];
if (axis.show) {
var thaxis = th.axes[axname] || {};
var thaxstyle = th.axesStyles;
var thax = $.jqplot.extend(true, {}, thaxis, thaxstyle);
val = (th.axesStyles.borderColor != null) ? th.axesStyles.borderColor : thax.borderColor;
if (thax.borderColor != null) {
axis.borderColor = thax.borderColor;
redrawPlot = true;
}
val = (th.axesStyles.borderWidth != null) ? th.axesStyles.borderWidth : thax.borderWidth;
if (thax.borderWidth != null) {
axis.borderWidth = thax.borderWidth;
redrawPlot = true;
}
if (axis._ticks && axis._ticks[0]) {
for (nn in thax.ticks) {
// val = null;
// if (th.axesStyles.ticks && th.axesStyles.ticks[nn] != null) {
// val = th.axesStyles.ticks[nn];
// }
// else if (thax.ticks[nn] != null){
// val = thax.ticks[nn]
// }
val = thax.ticks[nn];
if (val != null) {
axis.tickOptions[nn] = val;
axis._ticks = [];
redrawPlot = true;
}
}
}
if (axis._label && axis._label.show) {
for (nn in thax.label) {
// val = null;
// if (th.axesStyles.label && th.axesStyles.label[nn] != null) {
// val = th.axesStyles.label[nn];
// }
// else if (thax.label && thax.label[nn] != null){
// val = thax.label[nn]
// }
val = thax.label[nn];
if (val != null) {
axis.labelOptions[nn] = val;
redrawPlot = true;
}
}
}
}
}
for (var n in th.grid) {
if (th.grid[n] != null) {
plot.grid[n] = th.grid[n];
}
}
if (!redrawPlot) {
plot.grid.draw();
}
if (plot.legend.show) {
for (n in th.legend) {
if (th.legend[n] != null) {
plot.legend[n] = th.legend[n];
}
}
}
if (plot.title.show) {
for (n in th.title) {
if (th.title[n] != null) {
plot.title[n] = th.title[n];
}
}
}
var i;
for (i=0; i<th.series.length; i++) {
var opts = {};
var redrawSeries = false;
for (n in th.series[i]) {
val = (th.seriesStyles[n] != null) ? th.seriesStyles[n] : th.series[i][n];
if (val != null) {
opts[n] = val;
if (n == 'color') {
plot.series[i].renderer.shapeRenderer.fillStyle = val;
plot.series[i].renderer.shapeRenderer.strokeStyle = val;
plot.series[i][n] = val;
}
else if (n == 'lineWidth') {
plot.series[i].renderer.shapeRenderer.lineWidth = val;
plot.series[i][n] = val;
}
else if (n == 'markerOptions') {
merge (plot.series[i].markerOptions, val);
merge (plot.series[i].markerRenderer, val);
}
else {
plot.series[i][n] = val;
}
redrawPlot = true;
}
}
}
if (redrawPlot) {
plot.target.empty();
plot.draw();
}
for (n in th.target) {
if (th.target[n] != null) {
plot.target.css(n, th.target[n]);
}
}
}
};
$.jqplot.ThemeEngine.prototype._add = function(theme, name) {
if (name) {
theme._name = name;
}
if (!theme._name) {
theme._name = Date.parse(new Date());
}
if (!this.themes.hasOwnProperty(theme._name)) {
this.themes[theme._name] = theme;
}
else {
throw new Error("jqplot.ThemeEngine Error: Theme already in use");
}
};
// method remove
// Delete the named theme, return true on success, false on failure.
/**
* method: remove
*
* Remove the given theme from the themeEngine.
*
* parameters:
*
* name - name of the theme to remove.
*
* returns:
*
* true on success, false on failure.
*/
$.jqplot.ThemeEngine.prototype.remove = function(name) {
if (name == 'Default') {
return false;
}
return delete this.themes[name];
};
/**
* method: newTheme
*
* Create a new theme based on the default theme, adding it the themeEngine.
*
* parameters:
*
* name - name of the new theme.
* obj - optional object of styles to be applied to this new theme.
*
* returns:
*
* new Theme object.
*/
$.jqplot.ThemeEngine.prototype.newTheme = function(name, obj) {
if (typeof(name) == 'object') {
obj = obj || name;
name = null;
}
if (obj && obj._name) {
name = obj._name;
}
else {
name = name || Date.parse(new Date());
}
// var th = new $.jqplot.Theme(name);
var th = this.copy(this.themes['Default']._name, name);
$.jqplot.extend(th, obj);
return th;
};
// function clone(obj) {
// return eval(obj.toSource());
// }
function clone(obj){
if(obj == null || typeof(obj) != 'object'){
return obj;
}
var temp = new obj.constructor();
for(var key in obj){
temp[key] = clone(obj[key]);
}
return temp;
}
$.jqplot.clone = clone;
function merge(obj1, obj2) {
if (obj2 == null || typeof(obj2) != 'object') {
return;
}
for (var key in obj2) {
if (key == 'highlightColors') {
obj1[key] = clone(obj2[key]);
}
if (obj2[key] != null && typeof(obj2[key]) == 'object') {
if (!obj1.hasOwnProperty(key)) {
obj1[key] = {};
}
merge(obj1[key], obj2[key]);
}
else {
obj1[key] = obj2[key];
}
}
}
$.jqplot.merge = merge;
// Use the jQuery 1.3.2 extend function since behaviour in jQuery 1.4 seems problematic
$.jqplot.extend = function() {
// copy reference to target object
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !toString.call(target) === "[object Function]" ) {
target = {};
}
for ( ; i < length; i++ ){
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( var name in options ) {
var src = target[ name ], copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging object values
if ( deep && copy && typeof copy === "object" && !copy.nodeType ) {
target[ name ] = $.jqplot.extend( deep,
// Never move original objects, clone them
src || ( copy.length != null ? [ ] : { } )
, copy );
}
// Don't bring in undefined values
else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
/**
* method: rename
*
* Rename a theme.
*
* parameters:
*
* oldName - current name of the theme.
* newName - desired name of the theme.
*
* returns:
*
* new Theme object.
*/
$.jqplot.ThemeEngine.prototype.rename = function (oldName, newName) {
if (oldName == 'Default' || newName == 'Default') {
throw new Error ("jqplot.ThemeEngine Error: Cannot rename from/to Default");
}
if (this.themes.hasOwnProperty(newName)) {
throw new Error ("jqplot.ThemeEngine Error: New name already in use.");
}
else if (this.themes.hasOwnProperty(oldName)) {
var th = this.copy (oldName, newName);
this.remove(oldName);
return th;
}
throw new Error("jqplot.ThemeEngine Error: Old name or new name invalid");
};
/**
* method: copy
*
* Create a copy of an existing theme in the themeEngine, adding it the themeEngine.
*
* parameters:
*
* sourceName - name of the existing theme.
* targetName - name of the copy.
* obj - optional object of style parameter to apply to the new theme.
*
* returns:
*
* new Theme object.
*/
$.jqplot.ThemeEngine.prototype.copy = function (sourceName, targetName, obj) {
if (targetName == 'Default') {
throw new Error ("jqplot.ThemeEngine Error: Cannot copy over Default theme");
}
if (!this.themes.hasOwnProperty(sourceName)) {
var s = "jqplot.ThemeEngine Error: Source name invalid";
throw new Error(s);
}
if (this.themes.hasOwnProperty(targetName)) {
var s = "jqplot.ThemeEngine Error: Target name invalid";
throw new Error(s);
}
else {
var th = clone(this.themes[sourceName]);
th._name = targetName;
$.jqplot.extend(true, th, obj);
this._add(th);
return th;
}
};
$.jqplot.Theme = function(name, obj) {
if (typeof(name) == 'object') {
obj = obj || name;
name = null;
}
name = name || Date.parse(new Date());
this._name = name;
this.target = {
backgroundColor: null
};
this.legend = {
textColor: null,
fontFamily: null,
fontSize: null,
border: null,
background: null
};
this.title = {
textColor: null,
fontFamily: null,
fontSize: null,
textAlign: null
};
this.seriesStyles = {};
this.series = [];
this.grid = {
drawGridlines: null,
gridLineColor: null,
gridLineWidth: null,
backgroundColor: null,
borderColor: null,
borderWidth: null,
shadow: null
};
this.axesStyles = {label:{}, ticks:{}};
this.axes = {};
if (typeof(obj) == 'string') {
this._name = obj;
}
else if(typeof(obj) == 'object') {
$.jqplot.extend(true, this, obj);
}
};
var AxisProperties = function() {
this.borderColor = null;
this.borderWidth = null;
this.ticks = new AxisTicks();
this.label = new AxisLabel();
};
var AxisTicks = function() {
this.show = null;
this.showGridline = null;
this.showLabel = null;
this.showMark = null;
this.size = null;
this.textColor = null;
this.whiteSpace = null;
this.fontSize = null;
this.fontFamily = null;
};
var AxisLabel = function() {
this.textColor = null;
this.whiteSpace = null;
this.fontSize = null;
this.fontFamily = null;
this.fontWeight = null;
};
var LineSeriesProperties = function() {
this.color=null;
this.lineWidth=null;
this.shadow=null;
this.fillColor=null;
this.showMarker=null;
this.markerOptions = new MarkerOptions();
};
var MarkerOptions = function() {
this.show = null;
this.style = null;
this.lineWidth = null;
this.size = null;
this.color = null;
this.shadow = null;
};
var BarSeriesProperties = function() {
this.color=null;
this.seriesColors=null;
this.lineWidth=null;
this.shadow=null;
this.barPadding=null;
this.barMargin=null;
this.barWidth=null;
this.highlightColors=null;
};
var PieSeriesProperties = function() {
this.seriesColors=null;
this.padding=null;
this.sliceMargin=null;
this.fill=null;
this.shadow=null;
this.startAngle=null;
this.lineWidth=null;
this.highlightColors=null;
};
var DonutSeriesProperties = function() {
this.seriesColors=null;
this.padding=null;
this.sliceMargin=null;
this.fill=null;
this.shadow=null;
this.startAngle=null;
this.lineWidth=null;
this.innerDiameter=null;
this.thickness=null;
this.ringMargin=null;
this.highlightColors=null;
};
var FunnelSeriesProperties = function() {
this.color=null;
this.lineWidth=null;
this.shadow=null;
this.padding=null;
this.sectionMargin=null;
this.seriesColors=null;
this.highlightColors=null;
};
var MeterSeriesProperties = function() {
this.padding=null;
this.backgroundColor=null;
this.ringColor=null;
this.tickColor=null;
this.ringWidth=null;
this.intervalColors=null;
this.intervalInnerRadius=null;
this.intervalOuterRadius=null;
this.hubRadius=null;
this.needleThickness=null;
this.needlePad=null;
};
/**
* @description
* <p>Object with extended date parsing and formatting capabilities.
* This library borrows many concepts and ideas from the Date Instance
* Methods by Ken Snyder along with some parts of Ken's actual code.</p>
*
* <p>jsDate takes a different approach by not extending the built-in
* Date Object, improving date parsing, allowing for multiple formatting
* syntaxes and multiple and more easily expandable localization.</p>
*
* @author Chris Leonello
* @date #date#
* @version #VERSION#
* @copyright (c) 2010 Chris Leonello
* jsDate is currently available for use in all personal or commercial projects
* under both the MIT and GPL version 2.0 licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* <p>Ken's origianl Date Instance Methods and copyright notice:</p>
* <pre>
* Ken Snyder (ken d snyder at gmail dot com)
* 2008-09-10
* version 2.0.2 (http://kendsnyder.com/sandbox/date/)
* Creative Commons Attribution License 3.0 (http://creativecommons.org/licenses/by/3.0/)
* </pre>
*
* @class
* @name jsDate
* @param {String | Number | Array | Date Object | Options Object} arguments Optional arguments, either a parsable date/time string,
* a JavaScript timestamp, an array of numbers of form [year, month, day, hours, minutes, seconds, milliseconds],
* a Date object, or an options object of form {syntax: "perl", date:some Date} where all options are optional.
*/
var jsDate = function () {
this.syntax = jsDate.config.syntax;
this._type = "jsDate";
this.utcOffset = new Date().getTimezoneOffset * 60000;
this.proxy = new Date();
this.options = {};
this.locale = jsDate.regional.getLocale();
this.formatString = '';
this.defaultCentury = jsDate.config.defaultCentury;
switch ( arguments.length ) {
case 0:
break;
case 1:
// other objects either won't have a _type property or,
// if they do, it shouldn't be set to "jsDate", so
// assume it is an options argument.
if (get_type(arguments[0]) == "[object Object]" && arguments[0]._type != "jsDate") {
var opts = this.options = arguments[0];
this.syntax = opts.syntax || this.syntax;
this.defaultCentury = opts.defaultCentury || this.defaultCentury;
this.proxy = jsDate.createDate(opts.date);
}
else {
this.proxy = jsDate.createDate(arguments[0]);
}
break;
default:
var a = [];
for ( var i=0; i<arguments.length; i++ ) {
a.push(arguments[i]);
}
this.proxy = new Date( this.utcOffset );
this.proxy.setFullYear.apply( this.proxy, a.slice(0,3) );
if ( a.slice(3).length ) {
this.proxy.setHours.apply( this.proxy, a.slice(3) );
}
break;
}
};
/**
* @namespace Configuration options that will be used as defaults for all instances on the page.
* @property {String} defaultLocale The default locale to use [en].
* @property {String} syntax The default syntax to use [perl].
*/
jsDate.config = {
defaultLocale: 'en',
syntax: 'perl',
defaultCentury: 1900
};
/**
* Add an arbitrary amount to the currently stored date
*
* @param {Number} number
* @param {String} unit
* @returns {jsDate}
*/
jsDate.prototype.add = function(number, unit) {
var factor = multipliers[unit] || multipliers.day;
if (typeof factor == 'number') {
this.proxy.setTime(this.proxy.getTime() + (factor * number));
} else {
factor.add(this, number);
}
return this;
};
/**
* Create a new jqplot.date object with the same date
*
* @returns {jsDate}
*/
jsDate.prototype.clone = function() {
return new jsDate(this.proxy.getTime());
};
/**
* Find the difference between this jsDate and another date.
*
* @param {String| Number| Array| jsDate Object| Date Object} dateObj
* @param {String} unit
* @param {Boolean} allowDecimal
* @returns {Number} Number of units difference between dates.
*/
jsDate.prototype.diff = function(dateObj, unit, allowDecimal) {
// ensure we have a Date object
dateObj = new jsDate(dateObj);
if (dateObj === null) {
return null;
}
// get the multiplying factor integer or factor function
var factor = multipliers[unit] || multipliers.day;
if (typeof factor == 'number') {
// multiply
var unitDiff = (this.proxy.getTime() - dateObj.proxy.getTime()) / factor;
} else {
// run function
var unitDiff = factor.diff(this.proxy, dateObj.proxy);
}
// if decimals are not allowed, round toward zero
return (allowDecimal ? unitDiff : Math[unitDiff > 0 ? 'floor' : 'ceil'](unitDiff));
};
/**
* Get the abbreviated name of the current week day
*
* @returns {String}
*/
jsDate.prototype.getAbbrDayName = function() {
return jsDate.regional[this.locale]["dayNamesShort"][this.proxy.getDay()];
};
/**
* Get the abbreviated name of the current month
*
* @returns {String}
*/
jsDate.prototype.getAbbrMonthName = function() {
return jsDate.regional[this.locale]["monthNamesShort"][this.proxy.getMonth()];
};
/**
* Get UPPER CASE AM or PM for the current time
*
* @returns {String}
*/
jsDate.prototype.getAMPM = function() {
return this.proxy.getHours() >= 12 ? 'PM' : 'AM';
};
/**
* Get lower case am or pm for the current time
*
* @returns {String}
*/
jsDate.prototype.getAmPm = function() {
return this.proxy.getHours() >= 12 ? 'pm' : 'am';
};
/**
* Get the century (19 for 20th Century)
*
* @returns {Integer} Century (19 for 20th century).
*/
jsDate.prototype.getCentury = function() {
return parseInt(this.proxy.getFullYear()/100, 10);
};
/**
* Implements Date functionality
*/
jsDate.prototype.getDate = function() {
return this.proxy.getDate();
};
/**
* Implements Date functionality
*/
jsDate.prototype.getDay = function() {
return this.proxy.getDay();
};
/**
* Get the Day of week 1 (Monday) thru 7 (Sunday)
*
* @returns {Integer} Day of week 1 (Monday) thru 7 (Sunday)
*/
jsDate.prototype.getDayOfWeek = function() {
var dow = this.proxy.getDay();
return dow===0?7:dow;
};
/**
* Get the day of the year
*
* @returns {Integer} 1 - 366, day of the year
*/
jsDate.prototype.getDayOfYear = function() {
var d = this.proxy;
var ms = d - new Date('' + d.getFullYear() + '/1/1 GMT');
ms += d.getTimezoneOffset()*60000;
d = null;
return parseInt(ms/60000/60/24, 10)+1;
};
/**
* Get the name of the current week day
*
* @returns {String}
*/
jsDate.prototype.getDayName = function() {
return jsDate.regional[this.locale]["dayNames"][this.proxy.getDay()];
};
/**
* Get the week number of the given year, starting with the first Sunday as the first week
* @returns {Integer} Week number (13 for the 13th full week of the year).
*/
jsDate.prototype.getFullWeekOfYear = function() {
var d = this.proxy;
var doy = this.getDayOfYear();
var rdow = 6-d.getDay();
var woy = parseInt((doy+rdow)/7, 10);
return woy;
};
/**
* Implements Date functionality
*/
jsDate.prototype.getFullYear = function() {
return this.proxy.getFullYear();
};
/**
* Get the GMT offset in hours and minutes (e.g. +06:30)
*
* @returns {String}
*/
jsDate.prototype.getGmtOffset = function() {
// divide the minutes offset by 60
var hours = this.proxy.getTimezoneOffset() / 60;
// decide if we are ahead of or behind GMT
var prefix = hours < 0 ? '+' : '-';
// remove the negative sign if any
hours = Math.abs(hours);
// add the +/- to the padded number of hours to : to the padded minutes
return prefix + addZeros(Math.floor(hours), 2) + ':' + addZeros((hours % 1) * 60, 2);
};
/**
* Implements Date functionality
*/
jsDate.prototype.getHours = function() {
return this.proxy.getHours();
};
/**
* Get the current hour on a 12-hour scheme
*
* @returns {Integer}
*/
jsDate.prototype.getHours12 = function() {
var hours = this.proxy.getHours();
return hours > 12 ? hours - 12 : (hours == 0 ? 12 : hours);
};
jsDate.prototype.getIsoWeek = function() {
var d = this.proxy;
var woy = d.getWeekOfYear();
var dow1_1 = (new Date('' + d.getFullYear() + '/1/1')).getDay();
// First week is 01 and not 00 as in the case of %U and %W,
// so we add 1 to the final result except if day 1 of the year
// is a Monday (then %W returns 01).
// We also need to subtract 1 if the day 1 of the year is
// Friday-Sunday, so the resulting equation becomes:
var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1);
if(idow == 53 && (new Date('' + d.getFullYear() + '/12/31')).getDay() < 4)
{
idow = 1;
}
else if(idow === 0)
{
d = new jsDate(new Date('' + (d.getFullYear()-1) + '/12/31'));
idow = d.getIsoWeek();
}
d = null;
return idow;
};
/**
* Implements Date functionality
*/
jsDate.prototype.getMilliseconds = function() {
return this.proxy.getMilliseconds();
};
/**
* Implements Date functionality
*/
jsDate.prototype.getMinutes = function() {
return this.proxy.getMinutes();
};
/**
* Implements Date functionality
*/
jsDate.prototype.getMonth = function() {
return this.proxy.getMonth();
};
/**
* Get the name of the current month
*
* @returns {String}
*/
jsDate.prototype.getMonthName = function() {
return jsDate.regional[this.locale]["monthNames"][this.proxy.getMonth()];
};
/**
* Get the number of the current month, 1-12
*
* @returns {Integer}
*/
jsDate.prototype.getMonthNumber = function() {
return this.proxy.getMonth() + 1;
};
/**
* Implements Date functionality
*/
jsDate.prototype.getSeconds = function() {
return this.proxy.getSeconds();
};
/**
* Return a proper two-digit year integer
*
* @returns {Integer}
*/
jsDate.prototype.getShortYear = function() {
return this.proxy.getYear() % 100;
};
/**
* Implements Date functionality
*/
jsDate.prototype.getTime = function() {
return this.proxy.getTime();
};
/**
* Get the timezone abbreviation
*
* @returns {String} Abbreviation for the timezone
*/
jsDate.prototype.getTimezoneAbbr = function() {
return this.proxy.toString().replace(/^.*\(([^)]+)\)$/, '$1');
};
/**
* Get the browser-reported name for the current timezone (e.g. MDT, Mountain Daylight Time)
*
* @returns {String}
*/
jsDate.prototype.getTimezoneName = function() {
var match = /(?:\((.+)\)$| ([A-Z]{3}) )/.exec(this.toString());
return match[1] || match[2] || 'GMT' + this.getGmtOffset();
};
/**
* Implements Date functionality
*/
jsDate.prototype.getTimezoneOffset = function() {
return this.proxy.getTimezoneOffset();
};
/**
* Get the week number of the given year, starting with the first Monday as the first week
* @returns {Integer} Week number (13 for the 13th week of the year).
*/
jsDate.prototype.getWeekOfYear = function() {
var doy = this.getDayOfYear();
var rdow = 7 - this.getDayOfWeek();
var woy = parseInt((doy+rdow)/7, 10);
return woy;
};
/**
* Get the current date as a Unix timestamp
*
* @returns {Integer}
*/
jsDate.prototype.getUnix = function() {
return Math.round(this.proxy.getTime() / 1000, 0);
};
/**
* Implements Date functionality
*/
jsDate.prototype.getYear = function() {
return this.proxy.getYear();
};
/**
* Return a date one day ahead (or any other unit)
*
* @param {String} unit Optional, year | month | day | week | hour | minute | second | millisecond
* @returns {jsDate}
*/
jsDate.prototype.next = function(unit) {
unit = unit || 'day';
return this.clone().add(1, unit);
};
/**
* Set the jsDate instance to a new date.
*
* @param {String | Number | Array | Date Object | jsDate Object | Options Object} arguments Optional arguments,
* either a parsable date/time string,
* a JavaScript timestamp, an array of numbers of form [year, month, day, hours, minutes, seconds, milliseconds],
* a Date object, jsDate Object or an options object of form {syntax: "perl", date:some Date} where all options are optional.
*/
jsDate.prototype.set = function() {
switch ( arguments.length ) {
case 0:
this.proxy = new Date();
break;
case 1:
// other objects either won't have a _type property or,
// if they do, it shouldn't be set to "jsDate", so
// assume it is an options argument.
if (get_type(arguments[0]) == "[object Object]" && arguments[0]._type != "jsDate") {
var opts = this.options = arguments[0];
this.syntax = opts.syntax || this.syntax;
this.defaultCentury = opts.defaultCentury || this.defaultCentury;
this.proxy = jsDate.createDate(opts.date);
}
else {
this.proxy = jsDate.createDate(arguments[0]);
}
break;
default:
var a = [];
for ( var i=0; i<arguments.length; i++ ) {
a.push(arguments[i]);
}
this.proxy = new Date( this.utcOffset );
this.proxy.setFullYear.apply( this.proxy, a.slice(0,3) );
if ( a.slice(3).length ) {
this.proxy.setHours.apply( this.proxy, a.slice(3) );
}
break;
}
};
/**
* Sets the day of the month for a specified date according to local time.
* @param {Integer} dayValue An integer from 1 to 31, representing the day of the month.
*/
jsDate.prototype.setDate = function(n) {
return this.proxy.setDate(n);
};
/**
* Sets the full year for a specified date according to local time.
* @param {Integer} yearValue The numeric value of the year, for example, 1995.
* @param {Integer} monthValue Optional, between 0 and 11 representing the months January through December.
* @param {Integer} dayValue Optional, between 1 and 31 representing the day of the month. If you specify the dayValue parameter, you must also specify the monthValue.
*/
jsDate.prototype.setFullYear = function() {
return this.proxy.setFullYear.apply(this.proxy, arguments);
};
/**
* Sets the hours for a specified date according to local time.
*
* @param {Integer} hoursValue An integer between 0 and 23, representing the hour.
* @param {Integer} minutesValue Optional, An integer between 0 and 59, representing the minutes.
* @param {Integer} secondsValue Optional, An integer between 0 and 59, representing the seconds.
* If you specify the secondsValue parameter, you must also specify the minutesValue.
* @param {Integer} msValue Optional, A number between 0 and 999, representing the milliseconds.
* If you specify the msValue parameter, you must also specify the minutesValue and secondsValue.
*/
jsDate.prototype.setHours = function() {
return this.proxy.setHours.apply(this.proxy, arguments);
};
/**
* Implements Date functionality
*/
jsDate.prototype.setMilliseconds = function(n) {
return this.proxy.setMilliseconds(n);
};
/**
* Implements Date functionality
*/
jsDate.prototype.setMinutes = function() {
return this.proxy.setMinutes.apply(this.proxy, arguments);
};
/**
* Implements Date functionality
*/
jsDate.prototype.setMonth = function() {
return this.proxy.setMonth.apply(this.proxy, arguments);
};
/**
* Implements Date functionality
*/
jsDate.prototype.setSeconds = function() {
return this.proxy.setSeconds.apply(this.proxy, arguments);
};
/**
* Implements Date functionality
*/
jsDate.prototype.setTime = function(n) {
return this.proxy.setTime(n);
};
/**
* Implements Date functionality
*/
jsDate.prototype.setYear = function() {
return this.proxy.setYear.apply(this.proxy, arguments);
};
/**
* Provide a formatted string representation of this date.
*
* @param {String} formatString A format string.
* See: {@link jsDate.formats}.
* @returns {String} Date String.
*/
jsDate.prototype.strftime = function(formatString) {
formatString = formatString || this.formatString || jsDate.regional[this.locale]['formatString'];
return jsDate.strftime(this, formatString, this.syntax);
};
/**
* Return a String representation of this jsDate object.
* @returns {String} Date string.
*/
jsDate.prototype.toString = function() {
return this.proxy.toString();
};
/**
* Convert the current date to an 8-digit integer (%Y%m%d)
*
* @returns {Integer}
*/
jsDate.prototype.toYmdInt = function() {
return (this.proxy.getFullYear() * 10000) + (this.getMonthNumber() * 100) + this.proxy.getDate();
};
/**
* @namespace Holds localizations for month/day names.
* <p>jsDate attempts to detect locale when loaded and defaults to 'en'.
* If a localization is detected which is not available, jsDate defaults to 'en'.
* Additional localizations can be added after jsDate loads. After adding a localization,
* call the jsDate.regional.getLocale() method. Currently, en, fr and de are defined.</p>
*
* <p>Localizations must be an object and have the following properties defined: monthNames, monthNamesShort, dayNames, dayNamesShort and Localizations are added like:</p>
* <pre class="code">
* jsDate.regional['en'] = {
* monthNames : 'January February March April May June July August September October November December'.split(' '),
* monthNamesShort : 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' '),
* dayNames : 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday'.split(' '),
* dayNamesShort : 'Sun Mon Tue Wed Thu Fri Sat'.split(' ')
* };
* </pre>
* <p>After adding localizations, call <code>jsDate.regional.getLocale();</code> to update the locale setting with the
* new localizations.</p>
*/
jsDate.regional = {
'en': {
monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'],
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'fr': {
monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun','Jul','Aoû','Sep','Oct','Nov','Déc'],
dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'de': {
monthNames: ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'es': {
monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio', 'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun', 'Jul','Ago','Sep','Oct','Nov','Dic'],
dayNames: ['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'],
dayNamesShort: ['Dom','Lun','Mar','Mié','Juv','Vie','Sáb'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'ru': {
monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн','Июл','Авг','Сен','Окт','Ноя','Дек'],
dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'ar': {
monthNames: ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'آذار', 'حزيران','تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'],
monthNamesShort: ['1','2','3','4','5','6','7','8','9','10','11','12'],
dayNames: ['السبت', 'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة'],
dayNamesShort: ['سبت', 'أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'pt': {
monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
dayNames: ['Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado'],
dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'],
formatString: '%Y-%m-%d %H:%M:%S'
},
'pt-BR': {
monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho', 'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
dayNames: ['Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado'],
dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'],
formatString: '%Y-%m-%d %H:%M:%S'
}
};
// Set english variants to 'en'
jsDate.regional['en-US'] = jsDate.regional['en-GB'] = jsDate.regional['en'];
/**
* Try to determine the users locale based on the lang attribute of the html page. Defaults to 'en'
* if it cannot figure out a locale of if the locale does not have a localization defined.
* @returns {String} locale
*/
jsDate.regional.getLocale = function () {
var l = jsDate.config.defaultLocale;
if ( document && document.getElementsByTagName('html') && document.getElementsByTagName('html')[0].lang ) {
l = document.getElementsByTagName('html')[0].lang;
if (!jsDate.regional.hasOwnProperty(l)) {
l = jsDate.config.defaultLocale;
}
}
return l;
};
// ms in day
var day = 24 * 60 * 60 * 1000;
// padd a number with zeros
var addZeros = function(num, digits) {
num = String(num);
var i = digits - num.length;
var s = String(Math.pow(10, i)).slice(1);
return s.concat(num);
};
// representations used for calculating differences between dates.
// This borrows heavily from Ken Snyder's work.
var multipliers = {
millisecond: 1,
second: 1000,
minute: 60 * 1000,
hour: 60 * 60 * 1000,
day: day,
week: 7 * day,
month: {
// add a number of months
add: function(d, number) {
// add any years needed (increments of 12)
multipliers.year.add(d, Math[number > 0 ? 'floor' : 'ceil'](number / 12));
// ensure that we properly wrap betwen December and January
var prevMonth = d.getMonth() + (number % 12);
if (prevMonth == 12) {
prevMonth = 0;
d.setYear(d.getFullYear() + 1);
} else if (prevMonth == -1) {
prevMonth = 11;
d.setYear(d.getFullYear() - 1);
}
d.setMonth(prevMonth);
},
// get the number of months between two Date objects (decimal to the nearest day)
diff: function(d1, d2) {
// get the number of years
var diffYears = d1.getFullYear() - d2.getFullYear();
// get the number of remaining months
var diffMonths = d1.getMonth() - d2.getMonth() + (diffYears * 12);
// get the number of remaining days
var diffDays = d1.getDate() - d2.getDate();
// return the month difference with the days difference as a decimal
return diffMonths + (diffDays / 30);
}
},
year: {
// add a number of years
add: function(d, number) {
d.setYear(d.getFullYear() + Math[number > 0 ? 'floor' : 'ceil'](number));
},
// get the number of years between two Date objects (decimal to the nearest day)
diff: function(d1, d2) {
return multipliers.month.diff(d1, d2) / 12;
}
}
};
//
// Alias each multiplier with an 's' to allow 'year' and 'years' for example.
// This comes from Ken Snyders work.
//
for (var unit in multipliers) {
if (unit.substring(unit.length - 1) != 's') { // IE will iterate newly added properties :|
multipliers[unit + 's'] = multipliers[unit];
}
}
//
// take a jsDate instance and a format code and return the formatted value.
// This is a somewhat modified version of Ken Snyder's method.
//
var format = function(d, code, syntax) {
// if shorcut codes are used, recursively expand those.
if (jsDate.formats[syntax]["shortcuts"][code]) {
return jsDate.strftime(d, jsDate.formats[syntax]["shortcuts"][code], syntax);
} else {
// get the format code function and addZeros() argument
var getter = (jsDate.formats[syntax]["codes"][code] || '').split('.');
var nbr = d['get' + getter[0]] ? d['get' + getter[0]]() : '';
if (getter[1]) {
nbr = addZeros(nbr, getter[1]);
}
return nbr;
}
};
/**
* @static
* Static function for convert a date to a string according to a given format. Also acts as namespace for strftime format codes.
* <p>strftime formatting can be accomplished without creating a jsDate object by calling jsDate.strftime():</p>
* <pre class="code">
* var formattedDate = jsDate.strftime('Feb 8, 2006 8:48:32', '%Y-%m-%d %H:%M:%S');
* </pre>
* @param {String | Number | Array | jsDate Object | Date Object} date A parsable date string, JavaScript time stamp, Array of form [year, month, day, hours, minutes, seconds, milliseconds], jsDate Object or Date object.
* @param {String} formatString String with embedded date formatting codes.
* See: {@link jsDate.formats}.
* @param {String} syntax Optional syntax to use [default perl].
* @param {String} locale Optional locale to use.
* @returns {String} Formatted representation of the date.
*/
//
// Logic as implemented here is very similar to Ken Snyder's Date Instance Methods.
//
jsDate.strftime = function(d, formatString, syntax, locale) {
var syn = 'perl';
var loc = jsDate.regional.getLocale();
// check if syntax and locale are available or reversed
if (syntax && jsDate.formats.hasOwnProperty(syntax)) {
syn = syntax;
}
else if (syntax && jsDate.regional.hasOwnProperty(syntax)) {
loc = syntax;
}
if (locale && jsDate.formats.hasOwnProperty(locale)) {
syn = locale;
}
else if (locale && jsDate.regional.hasOwnProperty(locale)) {
loc = locale;
}
if (get_type(d) != "[object Object]" || d._type != "jsDate") {
d = new jsDate(d);
d.locale = loc;
}
if (!formatString) {
formatString = d.formatString || jsDate.regional[loc]['formatString'];
}
// default the format string to year-month-day
var source = formatString || '%Y-%m-%d',
result = '',
match;
// replace each format code
while (source.length > 0) {
if (match = source.match(jsDate.formats[syn].codes.matcher)) {
result += source.slice(0, match.index);
result += (match[1] || '') + format(d, match[2], syn);
source = source.slice(match.index + match[0].length);
} else {
result += source;
source = '';
}
}
return result;
};
/**
* @namespace
* Namespace to hold format codes and format shortcuts. "perl" and "php" format codes
* and shortcuts are defined by default. Additional codes and shortcuts can be
* added like:
*
* <pre class="code">
* jsDate.formats["perl"] = {
* "codes": {
* matcher: /someregex/,
* Y: "fullYear", // name of "get" method without the "get",
* ..., // more codes
* },
* "shortcuts": {
* F: '%Y-%m-%d',
* ..., // more shortcuts
* }
* };
* </pre>
*
* <p>Additionally, ISO and SQL shortcuts are defined and can be accesses via:
* <code>jsDate.formats.ISO</code> and <code>jsDate.formats.SQL</code>
*/
jsDate.formats = {
ISO:'%Y-%m-%dT%H:%M:%S.%N%G',
SQL:'%Y-%m-%d %H:%M:%S'
};
/**
* Perl format codes and shortcuts for strftime.
*
* A hash (object) of codes where each code must be an array where the first member is
* the name of a Date.prototype or jsDate.prototype function to call
* and optionally a second member indicating the number to pass to addZeros()
*
* <p>The following format codes are defined:</p>
*
* <pre class="code">
* Code Result Description
* == Years ==
* %Y 2008 Four-digit year
* %y 08 Two-digit year
*
* == Months ==
* %m 09 Two-digit month
* %#m 9 One or two-digit month
* %B September Full month name
* %b Sep Abbreviated month name
*
* == Days ==
* %d 05 Two-digit day of month
* %#d 5 One or two-digit day of month
* %e 5 One or two-digit day of month
* %A Sunday Full name of the day of the week
* %a Sun Abbreviated name of the day of the week
* %w 0 Number of the day of the week (0 = Sunday, 6 = Saturday)
*
* == Hours ==
* %H 23 Hours in 24-hour format (two digits)
* %#H 3 Hours in 24-hour integer format (one or two digits)
* %I 11 Hours in 12-hour format (two digits)
* %#I 3 Hours in 12-hour integer format (one or two digits)
* %p PM AM or PM
*
* == Minutes ==
* %M 09 Minutes (two digits)
* %#M 9 Minutes (one or two digits)
*
* == Seconds ==
* %S 02 Seconds (two digits)
* %#S 2 Seconds (one or two digits)
* %s 1206567625723 Unix timestamp (Seconds past 1970-01-01 00:00:00)
*
* == Milliseconds ==
* %N 008 Milliseconds (three digits)
* %#N 8 Milliseconds (one to three digits)
*
* == Timezone ==
* %O 360 difference in minutes between local time and GMT
* %Z Mountain Standard Time Name of timezone as reported by browser
* %G 06:00 Hours and minutes between GMT
*
* == Shortcuts ==
* %F 2008-03-26 %Y-%m-%d
* %T 05:06:30 %H:%M:%S
* %X 05:06:30 %H:%M:%S
* %x 03/26/08 %m/%d/%y
* %D 03/26/08 %m/%d/%y
* %#c Wed Mar 26 15:31:00 2008 %a %b %e %H:%M:%S %Y
* %v 3-Sep-2008 %e-%b-%Y
* %R 15:31 %H:%M
* %r 03:31:00 PM %I:%M:%S %p
*
* == Characters ==
* %n \n Newline
* %t \t Tab
* %% % Percent Symbol
* </pre>
*
* <p>Formatting shortcuts that will be translated into their longer version.
* Be sure that format shortcuts do not refer to themselves: this will cause an infinite loop.</p>
*
* <p>Format codes and format shortcuts can be redefined after the jsDate
* module is imported.</p>
*
* <p>Note that if you redefine the whole hash (object), you must supply a "matcher"
* regex for the parser. The default matcher is:</p>
*
* <code>/()%(#?(%|[a-z]))/i</code>
*
* <p>which corresponds to the Perl syntax used by default.</p>
*
* <p>By customizing the matcher and format codes, nearly any strftime functionality is possible.</p>
*/
jsDate.formats.perl = {
codes: {
//
// 2-part regex matcher for format codes
//
// first match must be the character before the code (to account for escaping)
// second match must be the format code character(s)
//
matcher: /()%(#?(%|[a-z]))/i,
// year
Y: 'FullYear',
y: 'ShortYear.2',
// month
m: 'MonthNumber.2',
'#m': 'MonthNumber',
B: 'MonthName',
b: 'AbbrMonthName',
// day
d: 'Date.2',
'#d': 'Date',
e: 'Date',
A: 'DayName',
a: 'AbbrDayName',
w: 'Day',
// hours
H: 'Hours.2',
'#H': 'Hours',
I: 'Hours12.2',
'#I': 'Hours12',
p: 'AMPM',
// minutes
M: 'Minutes.2',
'#M': 'Minutes',
// seconds
S: 'Seconds.2',
'#S': 'Seconds',
s: 'Unix',
// milliseconds
N: 'Milliseconds.3',
'#N': 'Milliseconds',
// timezone
O: 'TimezoneOffset',
Z: 'TimezoneName',
G: 'GmtOffset'
},
shortcuts: {
// date
F: '%Y-%m-%d',
// time
T: '%H:%M:%S',
X: '%H:%M:%S',
// local format date
x: '%m/%d/%y',
D: '%m/%d/%y',
// local format extended
'#c': '%a %b %e %H:%M:%S %Y',
// local format short
v: '%e-%b-%Y',
R: '%H:%M',
r: '%I:%M:%S %p',
// tab and newline
t: '\t',
n: '\n',
'%': '%'
}
};
/**
* PHP format codes and shortcuts for strftime.
*
* A hash (object) of codes where each code must be an array where the first member is
* the name of a Date.prototype or jsDate.prototype function to call
* and optionally a second member indicating the number to pass to addZeros()
*
* <p>The following format codes are defined:</p>
*
* <pre class="code">
* Code Result Description
* === Days ===
* %a Sun through Sat An abbreviated textual representation of the day
* %A Sunday - Saturday A full textual representation of the day
* %d 01 to 31 Two-digit day of the month (with leading zeros)
* %e 1 to 31 Day of the month, with a space preceding single digits.
* %j 001 to 366 Day of the year, 3 digits with leading zeros
* %u 1 - 7 (Mon - Sun) ISO-8601 numeric representation of the day of the week
* %w 0 - 6 (Sun - Sat) Numeric representation of the day of the week
*
* === Week ===
* %U 13 Full Week number, starting with the first Sunday as the first week
* %V 01 through 53 ISO-8601:1988 week number, starting with the first week of the year
* with at least 4 weekdays, with Monday being the start of the week
* %W 46 A numeric representation of the week of the year,
* starting with the first Monday as the first week
* === Month ===
* %b Jan through Dec Abbreviated month name, based on the locale
* %B January - December Full month name, based on the locale
* %h Jan through Dec Abbreviated month name, based on the locale (an alias of %b)
* %m 01 - 12 (Jan - Dec) Two digit representation of the month
*
* === Year ===
* %C 19 Two digit century (year/100, truncated to an integer)
* %y 09 for 2009 Two digit year
* %Y 2038 Four digit year
*
* === Time ===
* %H 00 through 23 Two digit representation of the hour in 24-hour format
* %I 01 through 12 Two digit representation of the hour in 12-hour format
* %l 1 through 12 Hour in 12-hour format, with a space preceeding single digits
* %M 00 through 59 Two digit representation of the minute
* %p AM/PM UPPER-CASE 'AM' or 'PM' based on the given time
* %P am/pm lower-case 'am' or 'pm' based on the given time
* %r 09:34:17 PM Same as %I:%M:%S %p
* %R 00:35 Same as %H:%M
* %S 00 through 59 Two digit representation of the second
* %T 21:34:17 Same as %H:%M:%S
* %X 03:59:16 Preferred time representation based on locale, without the date
* %z -0500 or EST Either the time zone offset from UTC or the abbreviation
* %Z -0500 or EST The time zone offset/abbreviation option NOT given by %z
*
* === Time and Date ===
* %D 02/05/09 Same as %m/%d/%y
* %F 2009-02-05 Same as %Y-%m-%d (commonly used in database datestamps)
* %s 305815200 Unix Epoch Time timestamp (same as the time() function)
* %x 02/05/09 Preferred date representation, without the time
*
* === Miscellaneous ===
* %n --- A newline character (\n)
* %t --- A Tab character (\t)
* %% --- A literal percentage character (%)
* </pre>
*/
jsDate.formats.php = {
codes: {
//
// 2-part regex matcher for format codes
//
// first match must be the character before the code (to account for escaping)
// second match must be the format code character(s)
//
matcher: /()%((%|[a-z]))/i,
// day
a: 'AbbrDayName',
A: 'DayName',
d: 'Date.2',
e: 'Date',
j: 'DayOfYear.3',
u: 'DayOfWeek',
w: 'Day',
// week
U: 'FullWeekOfYear.2',
V: 'IsoWeek.2',
W: 'WeekOfYear.2',
// month
b: 'AbbrMonthName',
B: 'MonthName',
m: 'MonthNumber.2',
h: 'AbbrMonthName',
// year
C: 'Century.2',
y: 'ShortYear.2',
Y: 'FullYear',
// time
H: 'Hours.2',
I: 'Hours12.2',
l: 'Hours12',
p: 'AMPM',
P: 'AmPm',
M: 'Minutes.2',
S: 'Seconds.2',
s: 'Unix',
O: 'TimezoneOffset',
z: 'GmtOffset',
Z: 'TimezoneAbbr'
},
shortcuts: {
D: '%m/%d/%y',
F: '%Y-%m-%d',
T: '%H:%M:%S',
X: '%H:%M:%S',
x: '%m/%d/%y',
R: '%H:%M',
r: '%I:%M:%S %p',
t: '\t',
n: '\n',
'%': '%'
}
};
//
// Conceptually, the logic implemented here is similar to Ken Snyder's Date Instance Methods.
// I use his idea of a set of parsers which can be regular expressions or functions,
// iterating through those, and then seeing if Date.parse() will create a date.
// The parser expressions and functions are a little different and some bugs have been
// worked out. Also, a lot of "pre-parsing" is done to fix implementation
// variations of Date.parse() between browsers.
//
jsDate.createDate = function(date) {
// if passing in multiple arguments, try Date constructor
if (date == null) {
return new Date();
}
// If the passed value is already a date object, return it
if (date instanceof Date) {
return date;
}
// if (typeof date == 'number') return new Date(date * 1000);
// If the passed value is an integer, interpret it as a javascript timestamp
if (typeof date == 'number') {
return new Date(date);
}
// Before passing strings into Date.parse(), have to normalize them for certain conditions.
// If strings are not formatted staccording to the EcmaScript spec, results from Date parse will be implementation dependent.
//
// For example:
// * FF and Opera assume 2 digit dates are pre y2k, Chome assumes <50 is pre y2k, 50+ is 21st century.
// * Chrome will correctly parse '1984-1-25' into localtime, FF and Opera will not parse.
// * Both FF, Chrome and Opera will parse '1984/1/25' into localtime.
// remove leading and trailing spaces
var parsable = String(date).replace(/^\s*(.+)\s*$/g, '$1');
// replace dahses (-) with slashes (/) in dates like n[nnn]/n[n]/n[nnn]
parsable = parsable.replace(/^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,4})/, "$1/$2/$3");
/////////
// Need to check for '15-Dec-09' also.
// FF will not parse, but Chrome will.
// Chrome will set date to 2009 as well.
/////////
// first check for 'dd-mmm-yyyy' or 'dd/mmm/yyyy' like '15-Dec-2010'
parsable = parsable.replace(/^(3[01]|[0-2]?\d)[-\/]([a-z]{3,})[-\/](\d{4})/i, "$1 $2 $3");
// Now check for 'dd-mmm-yy' or 'dd/mmm/yy' and normalize years to default century.
var match = parsable.match(/^(3[01]|[0-2]?\d)[-\/]([a-z]{3,})[-\/](\d{2})\D*/i);
if (match && match.length > 3) {
var m3 = parseFloat(match[3]);
var ny = jsDate.config.defaultCentury + m3;
ny = String(ny);
// now replace 2 digit year with 4 digit year
parsable = parsable.replace(/^(3[01]|[0-2]?\d)[-\/]([a-z]{3,})[-\/](\d{2})\D*/i, match[1] +' '+ match[2] +' '+ ny);
}
// Check for '1/19/70 8:14PM'
// where starts with mm/dd/yy or yy/mm/dd and have something after
// Check if 1st postiion is greater than 31, assume it is year.
// Assme all 2 digit years are 1900's.
// Finally, change them into US style mm/dd/yyyy representations.
match = parsable.match(/^([0-9]{1,2})[-\/]([0-9]{1,2})[-\/]([0-9]{1,2})[^0-9]/);
function h1(parsable, match) {
var m1 = parseFloat(match[1]);
var m2 = parseFloat(match[2]);
var m3 = parseFloat(match[3]);
var cent = jsDate.config.defaultCentury;
var ny, nd, nm, str;
if (m1 > 31) { // first number is a year
nd = m3;
nm = m2;
ny = cent + m1;
}
else { // last number is the year
nd = m2;
nm = m1;
ny = cent + m3;
}
str = nm+'/'+nd+'/'+ny;
// now replace 2 digit year with 4 digit year
return parsable.replace(/^([0-9]{1,2})[-\/]([0-9]{1,2})[-\/]([0-9]{1,2})/, str);
}
if (match && match.length > 3) {
parsable = h1(parsable, match);
}
// Now check for '1/19/70' with nothing after and do as above
var match = parsable.match(/^([0-9]{1,2})[-\/]([0-9]{1,2})[-\/]([0-9]{1,2})$/);
if (match && match.length > 3) {
parsable = h1(parsable, match);
}
var i = 0;
var length = jsDate.matchers.length;
var pattern;
var current = parsable;
while (i < length) {
ms = Date.parse(current);
if (!isNaN(ms)) {
return new Date(ms);
}
pattern = jsDate.matchers[i];
if (typeof pattern == 'function') {
obj = pattern.call(jsDate, current);
if (obj instanceof Date) {
return obj;
}
} else {
current = parsable.replace(pattern[0], pattern[1]);
}
i++;
}
return NaN;
};
/**
* @static
* Handy static utility function to return the number of days in a given month.
* @param {Integer} year Year
* @param {Integer} month Month (1-12)
* @returns {Integer} Number of days in the month.
*/
//
// handy utility method Borrowed right from Ken Snyder's Date Instance Mehtods.
//
jsDate.daysInMonth = function(year, month) {
if (month == 2) {
return new Date(year, 1, 29).getDate() == 29 ? 29 : 28;
}
return [undefined,31,undefined,31,30,31,30,31,31,30,31,30,31][month];
};
//
// An Array of regular expressions or functions that will attempt to match the date string.
// Functions are called with scope of a jsDate instance.
//
jsDate.matchers = [
// convert dd.mmm.yyyy to mm/dd/yyyy (world date to US date).
[/(3[01]|[0-2]\d)\s*\.\s*(1[0-2]|0\d)\s*\.\s*([1-9]\d{3})/, '$2/$1/$3'],
// convert yyyy-mm-dd to mm/dd/yyyy (ISO date to US date).
[/([1-9]\d{3})\s*-\s*(1[0-2]|0\d)\s*-\s*(3[01]|[0-2]\d)/, '$2/$3/$1'],
// Handle 12 hour or 24 hour time with milliseconds am/pm and optional date part.
function(str) {
var match = str.match(/^(?:(.+)\s+)?([012]?\d)(?:\s*\:\s*(\d\d))?(?:\s*\:\s*(\d\d(\.\d*)?))?\s*(am|pm)?\s*$/i);
// opt. date hour opt. minute opt. second opt. msec opt. am or pm
if (match) {
if (match[1]) {
var d = this.createDate(match[1]);
if (isNaN(d)) {
return;
}
} else {
var d = new Date();
d.setMilliseconds(0);
}
var hour = parseFloat(match[2]);
if (match[6]) {
hour = match[6].toLowerCase() == 'am' ? (hour == 12 ? 0 : hour) : (hour == 12 ? 12 : hour + 12);
}
d.setHours(hour, parseInt(match[3] || 0, 10), parseInt(match[4] || 0, 10), ((parseFloat(match[5] || 0)) || 0)*1000);
return d;
}
else {
return str;
}
},
// Handle ISO timestamp with time zone.
function(str) {
var match = str.match(/^(?:(.+))[T|\s+]([012]\d)(?:\:(\d\d))(?:\:(\d\d))(?:\.\d+)([\+\-]\d\d\:\d\d)$/i);
if (match) {
if (match[1]) {
var d = this.createDate(match[1]);
if (isNaN(d)) {
return;
}
} else {
var d = new Date();
d.setMilliseconds(0);
}
var hour = parseFloat(match[2]);
d.setHours(hour, parseInt(match[3], 10), parseInt(match[4], 10), parseFloat(match[5])*1000);
return d;
}
else {
return str;
}
},
// Try to match ambiguous strings like 12/8/22.
// Use FF date assumption that 2 digit years are 20th century (i.e. 1900's).
// This may be redundant with pre processing of date already performed.
function(str) {
var match = str.match(/^([0-3]?\d)\s*[-\/.\s]{1}\s*([a-zA-Z]{3,9})\s*[-\/.\s]{1}\s*([0-3]?\d)$/);
if (match) {
var d = new Date();
var cent = jsDate.config.defaultCentury;
var m1 = parseFloat(match[1]);
var m3 = parseFloat(match[3]);
var ny, nd, nm;
if (m1 > 31) { // first number is a year
nd = m3;
ny = cent + m1;
}
else { // last number is the year
nd = m1;
ny = cent + m3;
}
var nm = inArray(match[2], jsDate.regional[this.locale]["monthNamesShort"]);
if (nm == -1) {
nm = inArray(match[2], jsDate.regional[this.locale]["monthNames"]);
}
d.setFullYear(ny, nm, nd);
d.setHours(0,0,0,0);
return d;
}
else {
return str;
}
}
];
//
// I think John Reisig published this method on his blog, ejohn.
//
function inArray( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
}
//
// Thanks to Kangax, Christian Sciberras and Stack Overflow for this method.
//
function get_type(thing){
if(thing===null) return "[object Null]"; // special case
return Object.prototype.toString.call(thing);
}
$.jsDate = jsDate;
/**
* JavaScript printf/sprintf functions.
*
* This code has been adapted from the publicly available sprintf methods
* by Ash Searle. His original header follows:
*
* This code is unrestricted: you are free to use it however you like.
*
* The functions should work as expected, performing left or right alignment,
* truncating strings, outputting numbers with a required precision etc.
*
* For complex cases, these functions follow the Perl implementations of
* (s)printf, allowing arguments to be passed out-of-order, and to set the
* precision or length of the output based on arguments instead of fixed
* numbers.
*
* See http://perldoc.perl.org/functions/sprintf.html for more information.
*
* Implemented:
* - zero and space-padding
* - right and left-alignment,
* - base X prefix (binary, octal and hex)
* - positive number prefix
* - (minimum) width
* - precision / truncation / maximum width
* - out of order arguments
*
* Not implemented (yet):
* - vector flag
* - size (bytes, words, long-words etc.)
*
* Will not implement:
* - %n or %p (no pass-by-reference in JavaScript)
*
* @version 2007.04.27
* @author Ash Searle
*
* You can see the original work and comments on his blog:
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
*/
/**
* @Modifications 2009.05.26
* @author Chris Leonello
*
* Added %p %P specifier
* Acts like %g or %G but will not add more significant digits to the output than present in the input.
* Example:
* Format: '%.3p', Input: 0.012, Output: 0.012
* Format: '%.3g', Input: 0.012, Output: 0.0120
* Format: '%.4p', Input: 12.0, Output: 12.0
* Format: '%.4g', Input: 12.0, Output: 12.00
* Format: '%.4p', Input: 4.321e-5, Output: 4.321e-5
* Format: '%.4g', Input: 4.321e-5, Output: 4.3210e-5
*/
$.jqplot.sprintf = function() {
function pad(str, len, chr, leftJustify) {
var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
return leftJustify ? str + padding : padding + str;
}
function thousand_separate(value) {
value_str = new String(value);
for (var i=10; i>0; i--) {
if (value_str == (value_str = value_str.replace(/^(\d+)(\d{3})/, "$1"+$.jqplot.sprintf.thousandsSeparator+"$2"))) break;
}
return value_str;
}
function justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace) {
var diff = minWidth - value.length;
if (diff > 0) {
var spchar = ' ';
if (htmlSpace) { spchar = ' '; }
if (leftJustify || !zeroPad) {
value = pad(value, minWidth, spchar, leftJustify);
} else {
value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
}
}
return value;
}
function formatBaseX(value, base, prefix, leftJustify, minWidth, precision, zeroPad, htmlSpace) {
// Note: casts negative numbers to positive ones
var number = value >>> 0;
prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
value = prefix + pad(number.toString(base), precision || 0, '0', false);
return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace);
}
function formatString(value, leftJustify, minWidth, precision, zeroPad, htmlSpace) {
if (precision != null) {
value = value.slice(0, precision);
}
return justify(value, '', leftJustify, minWidth, zeroPad, htmlSpace);
}
var a = arguments, i = 0, format = a[i++];
return format.replace($.jqplot.sprintf.regex, function(substring, valueIndex, flags, minWidth, _, precision, type) {
if (substring == '%%') { return '%'; }
// parse flags
var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, htmlSpace = false, thousandSeparation = false;
for (var j = 0; flags && j < flags.length; j++) switch (flags.charAt(j)) {
case ' ': positivePrefix = ' '; break;
case '+': positivePrefix = '+'; break;
case '-': leftJustify = true; break;
case '0': zeroPad = true; break;
case '#': prefixBaseX = true; break;
case '&': htmlSpace = true; break;
case '\'': thousandSeparation = true; break;
}
// parameters may be null, undefined, empty-string or real valued
// we want to ignore null, undefined and empty-string values
if (!minWidth) {
minWidth = 0;
}
else if (minWidth == '*') {
minWidth = +a[i++];
}
else if (minWidth.charAt(0) == '*') {
minWidth = +a[minWidth.slice(1, -1)];
}
else {
minWidth = +minWidth;
}
// Note: undocumented perl feature:
if (minWidth < 0) {
minWidth = -minWidth;
leftJustify = true;
}
if (!isFinite(minWidth)) {
throw new Error('$.jqplot.sprintf: (minimum-)width must be finite');
}
if (!precision) {
precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : void(0);
}
else if (precision == '*') {
precision = +a[i++];
}
else if (precision.charAt(0) == '*') {
precision = +a[precision.slice(1, -1)];
}
else {
precision = +precision;
}
// grab value using valueIndex if required?
var value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
switch (type) {
case 's': {
if (value == null) {
return '';
}
return formatString(String(value), leftJustify, minWidth, precision, zeroPad, htmlSpace);
}
case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad, htmlSpace);
case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad,htmlSpace);
case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad, htmlSpace);
case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad, htmlSpace);
case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad, htmlSpace).toUpperCase();
case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad, htmlSpace);
case 'i': {
var number = parseInt(+value, 10);
if (isNaN(number)) {
return '';
}
var prefix = number < 0 ? '-' : positivePrefix;
number_str = thousandSeparation ? thousand_separate(String(Math.abs(number))): String(Math.abs(number));
value = prefix + pad(number_str, precision, '0', false);
//value = prefix + pad(String(Math.abs(number)), precision, '0', false);
return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace);
}
case 'd': {
var number = Math.round(+value);
if (isNaN(number)) {
return '';
}
var prefix = number < 0 ? '-' : positivePrefix;
number_str = thousandSeparation ? thousand_separate(String(Math.abs(number))): String(Math.abs(number));
value = prefix + pad(number_str, precision, '0', false);
return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace);
}
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G':
{
var number = +value;
if (isNaN(number)) {
return '';
}
var prefix = number < 0 ? '-' : positivePrefix;
var method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
var textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
number_str = Math.abs(number)[method](precision);
number_str = thousandSeparation ? thousand_separate(number_str): number_str;
value = prefix + number_str;
return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace)[textTransform]();
}
case 'p':
case 'P':
{
// make sure number is a number
var number = +value;
if (isNaN(number)) {
return '';
}
var prefix = number < 0 ? '-' : positivePrefix;
var parts = String(Number(Math.abs(number)).toExponential()).split(/e|E/);
var sd = (parts[0].indexOf('.') != -1) ? parts[0].length - 1 : parts[0].length;
var zeros = (parts[1] < 0) ? -parts[1] - 1 : 0;
if (Math.abs(number) < 1) {
if (sd + zeros <= precision) {
value = prefix + Math.abs(number).toPrecision(sd);
}
else {
if (sd <= precision - 1) {
value = prefix + Math.abs(number).toExponential(sd-1);
}
else {
value = prefix + Math.abs(number).toExponential(precision-1);
}
}
}
else {
var prec = (sd <= precision) ? sd : precision;
value = prefix + Math.abs(number).toPrecision(prec);
}
var textTransform = ['toString', 'toUpperCase']['pP'.indexOf(type) % 2];
return justify(value, prefix, leftJustify, minWidth, zeroPad, htmlSpace)[textTransform]();
}
case 'n': return '';
default: return substring;
}
});
};
$.jqplot.sprintf.thousandsSeparator = ',';
$.jqplot.sprintf.regex = /%%|%(\d+\$)?([-+#0&\' ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([nAscboxXuidfegpEGP])/g;
})(jQuery);
| JavaScript |
/**
* jqPlot
* Pure JavaScript plotting plugin using jQuery
*
* Version: 1.0.0a_r701
*
* Copyright (c) 2009-2011 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
* version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* Although not required, the author would appreciate an email letting him
* know of any substantial use of jqPlot. You can reach the author at:
* chris at jqplot dot com or see http://www.jqplot.com/info.php .
*
* If you are feeling kind and generous, consider supporting the project by
* making a donation at: http://www.jqplot.com/donate.php .
*
* sprintf functions contained in jqplot.sprintf.js by Ash Searle:
*
* version 2007.04.27
* author Ash Searle
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
* The author (Ash Searle) has placed this code in the public domain:
* "This code is unrestricted: you are free to use it however you like."
*
*/
(function($) {
// Class: $.jqplot.BarRenderer
// A plugin renderer for jqPlot to draw a bar plot.
// Draws series as a line.
$.jqplot.BarRenderer = function(){
$.jqplot.LineRenderer.call(this);
};
$.jqplot.BarRenderer.prototype = new $.jqplot.LineRenderer();
$.jqplot.BarRenderer.prototype.constructor = $.jqplot.BarRenderer;
// called with scope of series.
$.jqplot.BarRenderer.prototype.init = function(options, plot) {
// Group: Properties
//
// prop: barPadding
// Number of pixels between adjacent bars at the same axis value.
this.barPadding = 8;
// prop: barMargin
// Number of pixels between groups of bars at adjacent axis values.
this.barMargin = 10;
// prop: barDirection
// 'vertical' = up and down bars, 'horizontal' = side to side bars
this.barDirection = 'vertical';
// prop: barWidth
// Width of the bar in pixels (auto by devaul). null = calculated automatically.
this.barWidth = null;
// prop: shadowOffset
// offset of the shadow from the slice and offset of
// each succesive stroke of the shadow from the last.
this.shadowOffset = 2;
// prop: shadowDepth
// number of strokes to apply to the shadow,
// each stroke offset shadowOffset from the last.
this.shadowDepth = 5;
// prop: shadowAlpha
// transparency of the shadow (0 = transparent, 1 = opaque)
this.shadowAlpha = 0.08;
// prop: waterfall
// true to enable waterfall plot.
this.waterfall = false;
// prop: groups
// group bars into this many groups
this.groups = 1;
// prop: varyBarColor
// true to color each bar of a series separately rather than
// have every bar of a given series the same color.
// If used for non-stacked multiple series bar plots, user should
// specify a separate 'seriesColors' array for each series.
// Otherwise, each series will set their bars to the same color array.
// This option has no Effect for stacked bar charts and is disabled.
this.varyBarColor = false;
// prop: highlightMouseOver
// True to highlight slice when moused over.
// This must be false to enable highlightMouseDown to highlight when clicking on a slice.
this.highlightMouseOver = true;
// prop: highlightMouseDown
// True to highlight when a mouse button is pressed over a slice.
// This will be disabled if highlightMouseOver is true.
this.highlightMouseDown = false;
// prop: highlightColors
// an array of colors to use when highlighting a bar.
this.highlightColors = [];
// if user has passed in highlightMouseDown option and not set highlightMouseOver, disable highlightMouseOver
if (options.highlightMouseDown && options.highlightMouseOver == null) {
options.highlightMouseOver = false;
}
$.extend(true, this, options);
// fill is still needed to properly draw the legend.
// bars have to be filled.
this.fill = true;
if (this.waterfall) {
this.fillToZero = false;
this.disableStack = true;
}
if (this.barDirection == 'vertical' ) {
this._primaryAxis = '_xaxis';
this._stackAxis = 'y';
this.fillAxis = 'y';
}
else {
this._primaryAxis = '_yaxis';
this._stackAxis = 'x';
this.fillAxis = 'x';
}
// index of the currenty highlighted point, if any
this._highlightedPoint = null;
// total number of values for all bar series, total number of bar series, and position of this series
this._plotSeriesInfo = null;
// Array of actual data colors used for each data point.
this._dataColors = [];
this._barPoints = [];
// set the shape renderer options
var opts = {lineJoin:'miter', lineCap:'round', fill:true, isarc:false, strokeStyle:this.color, fillStyle:this.color, closePath:this.fill};
this.renderer.shapeRenderer.init(opts);
// set the shadow renderer options
var sopts = {lineJoin:'miter', lineCap:'round', fill:true, isarc:false, angle:this.shadowAngle, offset:this.shadowOffset, alpha:this.shadowAlpha, depth:this.shadowDepth, closePath:this.fill};
this.renderer.shadowRenderer.init(sopts);
plot.postInitHooks.addOnce(postInit);
plot.postDrawHooks.addOnce(postPlotDraw);
plot.eventListenerHooks.addOnce('jqplotMouseMove', handleMove);
plot.eventListenerHooks.addOnce('jqplotMouseDown', handleMouseDown);
plot.eventListenerHooks.addOnce('jqplotMouseUp', handleMouseUp);
plot.eventListenerHooks.addOnce('jqplotClick', handleClick);
plot.eventListenerHooks.addOnce('jqplotRightClick', handleRightClick);
};
// called with scope of series
function barPreInit(target, data, seriesDefaults, options) {
if (this.rendererOptions.barDirection == 'horizontal') {
this._stackAxis = 'x';
this._primaryAxis = '_yaxis';
}
if (this.rendererOptions.waterfall == true) {
this._data = $.extend(true, [], this.data);
var sum = 0;
var pos = (!this.rendererOptions.barDirection || this.rendererOptions.barDirection == 'vertical') ? 1 : 0;
for(var i=0; i<this.data.length; i++) {
sum += this.data[i][pos];
if (i>0) {
this.data[i][pos] += this.data[i-1][pos];
}
}
this.data[this.data.length] = (pos == 1) ? [this.data.length+1, sum] : [sum, this.data.length+1];
this._data[this._data.length] = (pos == 1) ? [this._data.length+1, sum] : [sum, this._data.length+1];
}
if (this.rendererOptions.groups > 1) {
this.breakOnNull = true;
var l = this.data.length;
var skip = parseInt(l/this.rendererOptions.groups, 10);
var count = 0;
for (var i=skip; i<l; i+=skip) {
this.data.splice(i+count, 0, [null, null]);
count++;
}
for (i=0; i<this.data.length; i++) {
if (this._primaryAxis == '_xaxis') {
this.data[i][0] = i+1;
}
else {
this.data[i][1] = i+1;
}
}
}
}
$.jqplot.preSeriesInitHooks.push(barPreInit);
// needs to be called with scope of series, not renderer.
$.jqplot.BarRenderer.prototype.calcSeriesNumbers = function() {
var nvals = 0;
var nseries = 0;
var paxis = this[this._primaryAxis];
var s, series, pos;
// loop through all series on this axis
for (var i=0; i < paxis._series.length; i++) {
series = paxis._series[i];
if (series === this) {
pos = i;
}
// is the series rendered as a bar?
if (series.renderer.constructor == $.jqplot.BarRenderer) {
// gridData may not be computed yet, use data length insted
nvals += series.data.length;
nseries += 1;
}
}
// return total number of values for all bar series, total number of bar series, and position of this series
return [nvals, nseries, pos];
};
$.jqplot.BarRenderer.prototype.setBarWidth = function() {
// need to know how many data values we have on the approprate axis and figure it out.
var i;
var nvals = 0;
var nseries = 0;
var paxis = this[this._primaryAxis];
var s, series, pos;
var temp = this._plotSeriesInfo = this.renderer.calcSeriesNumbers.call(this);
nvals = temp[0];
nseries = temp[1];
var nticks = paxis.numberTicks;
var nbins = (nticks-1)/2;
// so, now we have total number of axis values.
if (paxis.name == 'xaxis' || paxis.name == 'x2axis') {
if (this._stack) {
this.barWidth = (paxis._offsets.max - paxis._offsets.min) / nvals * nseries - this.barMargin;
}
else {
this.barWidth = ((paxis._offsets.max - paxis._offsets.min)/nbins - this.barPadding * (nseries-1) - this.barMargin*2)/nseries;
// this.barWidth = (paxis._offsets.max - paxis._offsets.min) / nvals - this.barPadding - this.barMargin/nseries;
}
}
else {
if (this._stack) {
this.barWidth = (paxis._offsets.min - paxis._offsets.max) / nvals * nseries - this.barMargin;
}
else {
this.barWidth = ((paxis._offsets.min - paxis._offsets.max)/nbins - this.barPadding * (nseries-1) - this.barMargin*2)/nseries;
// this.barWidth = (paxis._offsets.min - paxis._offsets.max) / nvals - this.barPadding - this.barMargin/nseries;
}
}
return [nvals, nseries];
};
function computeHighlightColors (colors) {
var ret = [];
for (var i=0; i<colors.length; i++){
var rgba = $.jqplot.getColorComponents(colors[i]);
var newrgb = [rgba[0], rgba[1], rgba[2]];
var sum = newrgb[0] + newrgb[1] + newrgb[2];
for (var j=0; j<3; j++) {
// when darkening, lowest color component can be is 60.
newrgb[j] = (sum > 570) ? newrgb[j] * 0.8 : newrgb[j] + 0.3 * (255 - newrgb[j]);
newrgb[j] = parseInt(newrgb[j], 10);
}
ret.push('rgb('+newrgb[0]+','+newrgb[1]+','+newrgb[2]+')');
}
return ret;
}
$.jqplot.BarRenderer.prototype.draw = function(ctx, gridData, options) {
var i;
var opts = (options != undefined) ? options : {};
var shadow = (opts.shadow != undefined) ? opts.shadow : this.shadow;
var showLine = (opts.showLine != undefined) ? opts.showLine : this.showLine;
var fill = (opts.fill != undefined) ? opts.fill : this.fill;
var xaxis = this.xaxis;
var yaxis = this.yaxis;
var xp = this._xaxis.series_u2p;
var yp = this._yaxis.series_u2p;
var pointx, pointy, nvals, nseries, pos;
// clear out data colors.
this._dataColors = [];
this._barPoints = [];
if (this.barWidth == null) {
this.renderer.setBarWidth.call(this);
}
var temp = this._plotSeriesInfo = this.renderer.calcSeriesNumbers.call(this);
nvals = temp[0];
nseries = temp[1];
pos = temp[2];
if (this._stack) {
this._barNudge = 0;
}
else {
this._barNudge = (-Math.abs(nseries/2 - 0.5) + pos) * (this.barWidth + this.barPadding);
}
if (showLine) {
var negativeColors = new $.jqplot.ColorGenerator(this.negativeSeriesColors);
var positiveColors = new $.jqplot.ColorGenerator(this.seriesColors);
var negativeColor = negativeColors.get(this.index);
if (! this.useNegativeColors) {
negativeColor = opts.fillStyle;
}
var positiveColor = opts.fillStyle;
if (this.barDirection == 'vertical') {
for (var i=0; i<gridData.length; i++) {
if (this.data[i][1] == null) {
continue;
}
points = [];
var base = gridData[i][0] + this._barNudge;
var ystart;
// stacked
if (this._stack && this._prevGridData.length) {
ystart = this._prevGridData[i][1];
}
// not stacked and first series in stack
else {
if (this.fillToZero) {
ystart = this._yaxis.series_u2p(0);
}
else if (this.waterfall && i > 0 && i < this.gridData.length-1) {
ystart = this.gridData[i-1][1];
}
else {
ystart = ctx.canvas.height;
}
}
if ((this.fillToZero && this._plotData[i][1] < 0) || (this.waterfall && this._data[i][1] < 0)) {
if (this.varyBarColor && !this._stack) {
if (this.useNegativeColors) {
opts.fillStyle = negativeColors.next();
}
else {
opts.fillStyle = positiveColors.next();
}
}
else {
opts.fillStyle = negativeColor;
}
}
else {
if (this.varyBarColor && !this._stack) {
opts.fillStyle = positiveColors.next();
}
else {
opts.fillStyle = positiveColor;
}
}
points.push([base-this.barWidth/2, ystart]);
points.push([base-this.barWidth/2, gridData[i][1]]);
points.push([base+this.barWidth/2, gridData[i][1]]);
points.push([base+this.barWidth/2, ystart]);
this._barPoints.push(points);
// now draw the shadows if not stacked.
// for stacked plots, they are predrawn by drawShadow
if (shadow && !this._stack) {
var sopts = $.extend(true, {}, opts);
// need to get rid of fillStyle on shadow.
delete sopts.fillStyle;
this.renderer.shadowRenderer.draw(ctx, points, sopts);
}
var clr = opts.fillStyle || this.color;
this._dataColors.push(clr);
this.renderer.shapeRenderer.draw(ctx, points, opts);
}
}
else if (this.barDirection == 'horizontal'){
for (var i=0; i<gridData.length; i++) {
if (this.data[i][0] == null) {
continue;
}
points = [];
var base = gridData[i][1] - this._barNudge;
var xstart;
if (this._stack && this._prevGridData.length) {
xstart = this._prevGridData[i][0];
}
// not stacked and first series in stack
else {
if (this.fillToZero) {
xstart = this._xaxis.series_u2p(0);
}
else if (this.waterfall && i > 0 && i < this.gridData.length-1) {
xstart = this.gridData[i-1][1];
}
else {
xstart = 0;
}
}
if ((this.fillToZero && this._plotData[i][1] < 0) || (this.waterfall && this._data[i][1] < 0)) {
if (this.varyBarColor && !this._stack) {
if (this.useNegativeColors) {
opts.fillStyle = negativeColors.next();
}
else {
opts.fillStyle = positiveColors.next();
}
}
}
else {
if (this.varyBarColor && !this._stack) {
opts.fillStyle = positiveColors.next();
}
else {
opts.fillStyle = positiveColor;
}
}
points.push([xstart, base+this.barWidth/2]);
points.push([xstart, base-this.barWidth/2]);
points.push([gridData[i][0], base-this.barWidth/2]);
points.push([gridData[i][0], base+this.barWidth/2]);
this._barPoints.push(points);
// now draw the shadows if not stacked.
// for stacked plots, they are predrawn by drawShadow
if (shadow && !this._stack) {
var sopts = $.extend(true, {}, opts);
delete sopts.fillStyle;
this.renderer.shadowRenderer.draw(ctx, points, sopts);
}
var clr = opts.fillStyle || this.color;
this._dataColors.push(clr);
this.renderer.shapeRenderer.draw(ctx, points, opts);
}
}
}
if (this.highlightColors.length == 0) {
this.highlightColors = computeHighlightColors(this._dataColors);
}
else if (typeof(this.highlightColors) == 'string') {
var temp = this.highlightColors;
this.highlightColors = [];
for (var i=0; i<this._dataColors.length; i++) {
this.highlightColors.push(temp);
}
}
};
// for stacked plots, shadows will be pre drawn by drawShadow.
$.jqplot.BarRenderer.prototype.drawShadow = function(ctx, gridData, options) {
var i;
var opts = (options != undefined) ? options : {};
var shadow = (opts.shadow != undefined) ? opts.shadow : this.shadow;
var showLine = (opts.showLine != undefined) ? opts.showLine : this.showLine;
var fill = (opts.fill != undefined) ? opts.fill : this.fill;
var xaxis = this.xaxis;
var yaxis = this.yaxis;
var xp = this._xaxis.series_u2p;
var yp = this._yaxis.series_u2p;
var pointx, pointy, nvals, nseries, pos;
if (this._stack && this.shadow) {
if (this.barWidth == null) {
this.renderer.setBarWidth.call(this);
}
var temp = this._plotSeriesInfo = this.renderer.calcSeriesNumbers.call(this);
nvals = temp[0];
nseries = temp[1];
pos = temp[2];
if (this._stack) {
this._barNudge = 0;
}
else {
this._barNudge = (-Math.abs(nseries/2 - 0.5) + pos) * (this.barWidth + this.barPadding);
}
if (showLine) {
if (this.barDirection == 'vertical') {
for (var i=0; i<gridData.length; i++) {
if (this.data[i][1] == null) {
continue;
}
points = [];
var base = gridData[i][0] + this._barNudge;
var ystart;
if (this._stack && this._prevGridData.length) {
ystart = this._prevGridData[i][1];
}
else {
if (this.fillToZero) {
ystart = this._yaxis.series_u2p(0);
}
else {
ystart = ctx.canvas.height;
}
}
points.push([base-this.barWidth/2, ystart]);
points.push([base-this.barWidth/2, gridData[i][1]]);
points.push([base+this.barWidth/2, gridData[i][1]]);
points.push([base+this.barWidth/2, ystart]);
this.renderer.shadowRenderer.draw(ctx, points, opts);
}
}
else if (this.barDirection == 'horizontal'){
for (var i=0; i<gridData.length; i++) {
if (this.data[i][0] == null) {
continue;
}
points = [];
var base = gridData[i][1] - this._barNudge;
var xstart;
if (this._stack && this._prevGridData.length) {
xstart = this._prevGridData[i][0];
}
else {
xstart = 0;
}
points.push([xstart, base+this.barWidth/2]);
points.push([gridData[i][0], base+this.barWidth/2]);
points.push([gridData[i][0], base-this.barWidth/2]);
points.push([xstart, base-this.barWidth/2]);
this.renderer.shadowRenderer.draw(ctx, points, opts);
}
}
}
}
};
function postInit(target, data, options) {
for (i=0; i<this.series.length; i++) {
if (this.series[i].renderer.constructor == $.jqplot.BarRenderer) {
// don't allow mouseover and mousedown at same time.
if (this.series[i].highlightMouseOver) {
this.series[i].highlightMouseDown = false;
}
}
}
this.target.bind('mouseout', {plot:this}, function (ev) { unhighlight(ev.data.plot); });
}
// called within context of plot
// create a canvas which we can draw on.
// insert it before the eventCanvas, so eventCanvas will still capture events.
function postPlotDraw() {
this.plugins.barRenderer = {highlightedSeriesIndex:null};
this.plugins.barRenderer.highlightCanvas = new $.jqplot.GenericCanvas();
this.eventCanvas._elem.before(this.plugins.barRenderer.highlightCanvas.createElement(this._gridPadding, 'jqplot-barRenderer-highlight-canvas', this._plotDimensions));
this.plugins.barRenderer.highlightCanvas.setContext();
}
function highlight (plot, sidx, pidx, points) {
var s = plot.series[sidx];
var canvas = plot.plugins.barRenderer.highlightCanvas;
canvas._ctx.clearRect(0,0,canvas._ctx.canvas.width, canvas._ctx.canvas.height);
s._highlightedPoint = pidx;
plot.plugins.barRenderer.highlightedSeriesIndex = sidx;
var opts = {fillStyle: s.highlightColors[pidx]};
s.renderer.shapeRenderer.draw(canvas._ctx, points, opts);
canvas = null;
}
function unhighlight (plot) {
var canvas = plot.plugins.barRenderer.highlightCanvas;
canvas._ctx.clearRect(0,0, canvas._ctx.canvas.width, canvas._ctx.canvas.height);
for (var i=0; i<plot.series.length; i++) {
plot.series[i]._highlightedPoint = null;
}
plot.plugins.barRenderer.highlightedSeriesIndex = null;
plot.target.trigger('jqplotDataUnhighlight');
canvas = null;
}
function handleMove(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
var evt1 = jQuery.Event('jqplotDataMouseOver');
evt1.pageX = ev.pageX;
evt1.pageY = ev.pageY;
plot.target.trigger(evt1, ins);
if (plot.series[ins[0]].highlightMouseOver && !(ins[0] == plot.plugins.barRenderer.highlightedSeriesIndex && ins[1] == plot.series[ins[0]]._highlightedPoint)) {
var evt = jQuery.Event('jqplotDataHighlight');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
highlight (plot, neighbor.seriesIndex, neighbor.pointIndex, neighbor.points);
}
}
else if (neighbor == null) {
unhighlight (plot);
}
}
function handleMouseDown(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
if (plot.series[ins[0]].highlightMouseDown && !(ins[0] == plot.plugins.barRenderer.highlightedSeriesIndex && ins[1] == plot.series[ins[0]]._highlightedPoint)) {
var evt = jQuery.Event('jqplotDataHighlight');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
highlight (plot, neighbor.seriesIndex, neighbor.pointIndex, neighbor.points);
}
}
else if (neighbor == null) {
unhighlight (plot);
}
}
function handleMouseUp(ev, gridpos, datapos, neighbor, plot) {
var idx = plot.plugins.barRenderer.highlightedSeriesIndex;
if (idx != null && plot.series[idx].highlightMouseDown) {
unhighlight(plot);
}
}
function handleClick(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
var evt = jQuery.Event('jqplotDataClick');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
}
}
function handleRightClick(ev, gridpos, datapos, neighbor, plot) {
if (neighbor) {
var ins = [neighbor.seriesIndex, neighbor.pointIndex, neighbor.data];
var idx = plot.plugins.barRenderer.highlightedSeriesIndex;
if (idx != null && plot.series[idx].highlightMouseDown) {
unhighlight(plot);
}
var evt = jQuery.Event('jqplotDataRightClick');
evt.pageX = ev.pageX;
evt.pageY = ev.pageY;
plot.target.trigger(evt, ins);
}
}
})(jQuery); | JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.lang} object for the
* Persian language.
*/
/**#@+
@type String
@example
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKEDITOR.lang['fa'] =
{
/**
* The language reading direction. Possible values are "rtl" for
* Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right
* languages (like English).
* @default 'ltr'
*/
dir : 'rtl',
/*
* Screenreader titles. Please note that screenreaders are not always capable
* of reading non-English words. So be careful while translating it.
*/
editorTitle : 'ویرایشگر متن غنی, %1',
editorHelp : 'کلید Alt+0 را برای راهنمایی بفشارید',
// ARIA descriptions.
toolbars : 'نوار ابزار',
editor : 'ویرایشگر متن غنی',
// Toolbar buttons without dialogs.
source : 'منبع',
newPage : 'برگهٴ تازه',
save : 'ذخیره',
preview : 'پیشنمایش',
cut : 'برش',
copy : 'کپی',
paste : 'چسباندن',
print : 'چاپ',
underline : 'زیرخطدار',
bold : 'درشت',
italic : 'خمیده',
selectAll : 'گزینش همه',
removeFormat : 'برداشتن فرمت',
strike : 'میانخط',
subscript : 'زیرنویس',
superscript : 'بالانویس',
horizontalrule : 'گنجاندن خط افقی',
pagebreak : 'گنجاندن شکستگی پایان برگه',
pagebreakAlt : 'شکستن صفحه',
unlink : 'برداشتن پیوند',
undo : 'واچیدن',
redo : 'بازچیدن',
// Common messages and labels.
common :
{
browseServer : 'فهرستنمایی سرور',
url : 'URL',
protocol : 'پروتکل',
upload : 'انتقال به سرور',
uploadSubmit : 'به سرور بفرست',
image : 'تصویر',
flash : 'فلش',
form : 'فرم',
checkbox : 'خانهٴ گزینهای',
radio : 'دکمهٴ رادیویی',
textField : 'فیلد متنی',
textarea : 'ناحیهٴ متنی',
hiddenField : 'فیلد پنهان',
button : 'دکمه',
select : 'فیلد چندگزینهای',
imageButton : 'دکمهٴ تصویری',
notSet : '<تعین نشده>',
id : 'شناسه',
name : 'نام',
langDir : 'جهتنمای زبان',
langDirLtr : 'چپ به راست (LTR)',
langDirRtl : 'راست به چپ (RTL)',
langCode : 'کد زبان',
longDescr : 'URL توصیف طولانی',
cssClass : 'کلاسهای شیوهنامه(Stylesheet)',
advisoryTitle : 'عنوان کمکی',
cssStyle : 'شیوه(style)',
ok : 'پذیرش',
cancel : 'انصراف',
close : 'بستن',
preview : 'پیشنمایش',
generalTab : 'عمومی',
advancedTab : 'پیشرفته',
validateNumberFailed : 'این مقدار یک عدد نیست.',
confirmNewPage : 'هر تغییر ایجاد شدهی ذخیره نشده از بین خواهد رفت. آیا اطمینان دارید که قصد بارگیری صفحه جدیدی را دارید؟',
confirmCancel : 'برخی از گزینهها تغییر کردهاند. آیا واقعا قصد بستن این پنجره را دارید؟',
options : 'گزینهها',
target : 'مسیر',
targetNew : 'پنجره جدید (_blank)',
targetTop : 'بالاترین پنجره (_top)',
targetSelf : 'همان پنجره (_self)',
targetParent : 'پنجره والد (_parent)',
langDirLTR : 'چپ به راست (LTR)',
langDirRTL : 'راست به چپ (RTL)',
styles : 'سبک',
cssClasses : 'کلاسهای شیوهنامه',
width : 'پهنا',
height : 'درازا',
align : 'چینش',
alignLeft : 'چپ',
alignRight : 'راست',
alignCenter : 'وسط',
alignTop : 'بالا',
alignMiddle : 'وسط',
alignBottom : 'پائین',
invalidValue : 'Invalid value.', // MISSING
invalidHeight : 'ارتفاع باید یک عدد باشد.',
invalidWidth : 'پهنا باید یک عدد باشد.',
invalidCssLength : 'عدد تعیین شده برای فیلد "%1" باید یک عدد مثبت با یا بدون یک واحد اندازه گیری CSS معتبر باشد (px, %, in, cm, mm, em, ex, pt, or pc).',
invalidHtmlLength : 'عدد تعیین شده برای فیلد "%1" باید یک عدد مثبت با یا بدون یک واحد اندازه گیری HTML معتبر باشد (px or %).',
invalidInlineStyle : 'عدد تعیین شده برای سبک درونخطی(Inline Style) باید دارای یک یا چند چندتایی با شکلی شبیه "name : value" که باید با یک ","(semi-colons) از هم جدا شوند.',
cssLengthTooltip : 'یک عدد برای یک مقدار بر حسب پیکسل و یا یک عدد با یک واحد CSS معتبر وارد کنید (px, %, in, cm, mm, em, ex, pt, or pc).',
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">، غیر قابل دسترس</span>'
},
contextmenu :
{
options : 'گزینههای منوی زمینه'
},
// Special char dialog.
specialChar :
{
toolbar : 'گنجاندن نویسهٴ ویژه',
title : 'گزینش نویسهٴ ویژه',
options : 'گزینههای نویسههای ویژه'
},
// Link dialog.
link :
{
toolbar : 'گنجاندن/ویرایش پیوند',
other : '<سایر>',
menu : 'ویرایش پیوند',
title : 'پیوند',
info : 'اطلاعات پیوند',
target : 'مقصد',
upload : 'انتقال به سرور',
advanced : 'پیشرفته',
type : 'نوع پیوند',
toUrl : 'URL',
toAnchor : 'لنگر در همین صفحه',
toEmail : 'پست الکترونیکی',
targetFrame : '<فریم>',
targetPopup : '<پنجرهٴ پاپاپ>',
targetFrameName : 'نام فریم مقصد',
targetPopupName : 'نام پنجرهٴ پاپاپ',
popupFeatures : 'ویژگیهای پنجرهٴ پاپاپ',
popupResizable : 'قابل تغییر اندازه',
popupStatusBar : 'نوار وضعیت',
popupLocationBar: 'نوار موقعیت',
popupToolbar : 'نوارابزار',
popupMenuBar : 'نوار منو',
popupFullScreen : 'تمامصفحه (IE)',
popupScrollBars : 'میلههای پیمایش',
popupDependent : 'وابسته (Netscape)',
popupLeft : 'موقعیت چپ',
popupTop : 'موقعیت بالا',
id : 'شناسه',
langDir : 'جهتنمای زبان',
langDirLTR : 'چپ به راست (LTR)',
langDirRTL : 'راست به چپ (RTL)',
acccessKey : 'کلید دستیابی',
name : 'نام',
langCode : 'جهتنمای زبان',
tabIndex : 'نمایهٴ دسترسی با برگه',
advisoryTitle : 'عنوان کمکی',
advisoryContentType : 'نوع محتوای کمکی',
cssClasses : 'کلاسهای شیوهنامه(Stylesheet)',
charset : 'نویسهگان منبع پیوند شده',
styles : 'شیوه(style)',
rel : 'وابستگی',
selectAnchor : 'یک لنگر برگزینید',
anchorName : 'با نام لنگر',
anchorId : 'با شناسهٴ المان',
emailAddress : 'نشانی پست الکترونیکی',
emailSubject : 'موضوع پیام',
emailBody : 'متن پیام',
noAnchors : '(در این سند لنگری دردسترس نیست)',
noUrl : 'لطفا URL پیوند را بنویسید',
noEmail : 'لطفا نشانی پست الکترونیکی را بنویسید'
},
// Anchor dialog
anchor :
{
toolbar : 'گنجاندن/ویرایش لنگر',
menu : 'ویژگیهای لنگر',
title : 'ویژگیهای لنگر',
name : 'نام لنگر',
errorName : 'لطفا نام لنگر را بنویسید',
remove : 'حذف لنگر'
},
// List style dialog
list:
{
numberedTitle : 'ویژگیهای فهرست شمارهدار',
bulletedTitle : 'ویژگیهای فهرست گلولهدار',
type : 'نوع',
start : 'شروع',
validateStartNumber :'فهرست شماره شروع باید یک عدد صحیح باشد.',
circle : 'دایره',
disc : 'صفحه گرد',
square : 'چهارگوش',
none : 'هیچ',
notset : '<تنظیم نشده>',
armenian : 'شمارهگذاری ارمنی',
georgian : 'شمارهگذاری گریگورین (an, ban, gan, etc.)',
lowerRoman : 'پانویس رومی (i, ii, iii, iv, v, etc.)',
upperRoman : 'بالانویس رومی (I, II, III, IV, V, etc.)',
lowerAlpha : 'پانویس الفبایی (a, b, c, d, e, etc.)',
upperAlpha : 'بالانویس الفبایی (A, B, C, D, E, etc.)',
lowerGreek : 'پانویس یونانی (alpha, beta, gamma, etc.)',
decimal : 'دهدهی (1, 2, 3, etc.)',
decimalLeadingZero : 'دهدهی همراه با صفر (01, 02, 03, etc.)'
},
// Find And Replace Dialog
findAndReplace :
{
title : 'جستجو و جایگزینی',
find : 'جستجو',
replace : 'جایگزینی',
findWhat : 'چه چیز را مییابید:',
replaceWith : 'جایگزینی با:',
notFoundMsg : 'متن موردنظر یافت نشد.',
findOptions : 'گزینههای جستجو',
matchCase : 'همسانی در بزرگی و کوچکی نویسهها',
matchWord : 'همسانی با واژهٴ کامل',
matchCyclic : 'همسانی با چرخه',
replaceAll : 'جایگزینی همهٴ یافتهها',
replaceSuccessMsg : '%1 رخداد جایگزین شد.'
},
// Table Dialog
table :
{
toolbar : 'جدول',
title : 'ویژگیهای جدول',
menu : 'ویژگیهای جدول',
deleteTable : 'پاک کردن جدول',
rows : 'سطرها',
columns : 'ستونها',
border : 'اندازهٴ لبه',
widthPx : 'پیکسل',
widthPc : 'درصد',
widthUnit : 'واحد پهنا',
cellSpace : 'فاصلهٴ میان سلولها',
cellPad : 'فاصلهٴ پرشده در سلول',
caption : 'عنوان',
summary : 'خلاصه',
headers : 'سرنویسها',
headersNone : 'هیچ',
headersColumn : 'اولین ستون',
headersRow : 'اولین ردیف',
headersBoth : 'هردو',
invalidRows : 'تعداد ردیفها باید یک عدد بزرگتر از 0 باشد.',
invalidCols : 'تعداد ستونها باید یک عدد بزرگتر از 0 باشد.',
invalidBorder : 'مقدار اندازه خطوط باید یک عدد باشد.',
invalidWidth : 'مقدار پهنای جدول باید یک عدد باشد.',
invalidHeight : 'مقدار ارتفاع جدول باید یک عدد باشد.',
invalidCellSpacing : 'مقدار فاصلهگذاری سلول باید یک عدد باشد.',
invalidCellPadding : 'بالشتک سلول باید یک عدد باشد.',
cell :
{
menu : 'سلول',
insertBefore : 'افزودن سلول قبل از',
insertAfter : 'افزودن سلول بعد از',
deleteCell : 'حذف سلولها',
merge : 'ادغام سلولها',
mergeRight : 'ادغام به راست',
mergeDown : 'ادغام به پایین',
splitHorizontal : 'جدا کردن افقی سلول',
splitVertical : 'جدا کردن عمودی سلول',
title : 'ویژگیهای سلول',
cellType : 'نوع سلول',
rowSpan : 'محدوده ردیفها',
colSpan : 'محدوده ستونها',
wordWrap : 'شکستن کلمه',
hAlign : 'چینش افقی',
vAlign : 'چینش عمودی',
alignBaseline : 'خط مبنا',
bgColor : 'رنگ زمینه',
borderColor : 'رنگ خطوط',
data : 'اطلاعات',
header : 'سرنویس',
yes : 'بله',
no : 'خیر',
invalidWidth : 'عرض سلول باید یک عدد باشد.',
invalidHeight : 'ارتفاع سلول باید عدد باشد.',
invalidRowSpan : 'مقدار محدوده ردیفها باید یک عدد باشد.',
invalidColSpan : 'مقدار محدوده ستونها باید یک عدد باشد.',
chooseColor : 'انتخاب'
},
row :
{
menu : 'سطر',
insertBefore : 'افزودن سطر قبل از',
insertAfter : 'افزودن سطر بعد از',
deleteRow : 'حذف سطرها'
},
column :
{
menu : 'ستون',
insertBefore : 'افزودن ستون قبل از',
insertAfter : 'افزودن ستون بعد از',
deleteColumn : 'حذف ستونها'
}
},
// Button Dialog.
button :
{
title : 'ویژگیهای دکمه',
text : 'متن (مقدار)',
type : 'نوع',
typeBtn : 'دکمه',
typeSbm : 'ثبت',
typeRst : 'بازنشانی (Reset)'
},
// Checkbox and Radio Button Dialogs.
checkboxAndRadio :
{
checkboxTitle : 'ویژگیهای خانهٴ گزینهای',
radioTitle : 'ویژگیهای دکمهٴ رادیویی',
value : 'مقدار',
selected : 'برگزیده'
},
// Form Dialog.
form :
{
title : 'ویژگیهای فرم',
menu : 'ویژگیهای فرم',
action : 'رویداد',
method : 'متد',
encoding : 'رمزنگاری'
},
// Select Field Dialog.
select :
{
title : 'ویژگیهای فیلد چندگزینهای',
selectInfo : 'اطلاعات',
opAvail : 'گزینههای دردسترس',
value : 'مقدار',
size : 'اندازه',
lines : 'خطوط',
chkMulti : 'گزینش چندگانه فراهم باشد',
opText : 'متن',
opValue : 'مقدار',
btnAdd : 'افزودن',
btnModify : 'ویرایش',
btnUp : 'بالا',
btnDown : 'پائین',
btnSetValue : 'تنظیم به عنوان مقدار برگزیده',
btnDelete : 'پاککردن'
},
// Textarea Dialog.
textarea :
{
title : 'ویژگیهای ناحیهٴ متنی',
cols : 'ستونها',
rows : 'سطرها'
},
// Text Field Dialog.
textfield :
{
title : 'ویژگیهای فیلد متنی',
name : 'نام',
value : 'مقدار',
charWidth : 'پهنای نویسه',
maxChars : 'بیشینهٴ نویسهها',
type : 'نوع',
typeText : 'متن',
typePass : 'گذرواژه'
},
// Hidden Field Dialog.
hidden :
{
title : 'ویژگیهای فیلد پنهان',
name : 'نام',
value : 'مقدار'
},
// Image Dialog.
image :
{
title : 'ویژگیهای تصویر',
titleButton : 'ویژگیهای دکمهٴ تصویری',
menu : 'ویژگیهای تصویر',
infoTab : 'اطلاعات تصویر',
btnUpload : 'به سرور بفرست',
upload : 'انتقال به سرور',
alt : 'متن جایگزین',
lockRatio : 'قفل کردن نسبت',
resetSize : 'بازنشانی اندازه',
border : 'لبه',
hSpace : 'فاصلهٴ افقی',
vSpace : 'فاصلهٴ عمودی',
alertUrl : 'لطفا URL تصویر را بنویسید',
linkTab : 'پیوند',
button2Img : 'آیا مایلید از یک تصویر ساده روی دکمه تصویری انتخاب شده استفاده کنید؟',
img2Button : 'آیا مایلید از یک دکمه تصویری روی تصویر انتخاب شده استفاده کنید؟',
urlMissing : 'آدرس URL اصلی تصویر یافت نشد.',
validateBorder : 'مقدار خطوط باید یک عدد باشد.',
validateHSpace : 'مقدار فاصلهگذاری افقی باید یک عدد باشد.',
validateVSpace : 'مقدار فاصلهگذاری عمودی باید یک عدد باشد.'
},
// Flash Dialog
flash :
{
properties : 'ویژگیهای فلش',
propertiesTab : 'ویژگیها',
title : 'ویژگیهای فلش',
chkPlay : 'آغاز خودکار',
chkLoop : 'اجرای پیاپی',
chkMenu : 'در دسترس بودن منوی فلش',
chkFull : 'اجازه تمام صفحه',
scale : 'مقیاس',
scaleAll : 'نمایش همه',
scaleNoBorder : 'بدون کران',
scaleFit : 'جایگیری کامل',
access : 'دسترسی به اسکریپت',
accessAlways : 'همیشه',
accessSameDomain: 'همان دامنه',
accessNever : 'هرگز',
alignAbsBottom : 'پائین مطلق',
alignAbsMiddle : 'وسط مطلق',
alignBaseline : 'خط پایه',
alignTextTop : 'متن بالا',
quality : 'کیفیت',
qualityBest : 'بهترین',
qualityHigh : 'بالا',
qualityAutoHigh : 'بالا - خودکار',
qualityMedium : 'متوسط',
qualityAutoLow : 'پایین - خودکار',
qualityLow : 'پایین',
windowModeWindow: 'پنجره',
windowModeOpaque: 'مات',
windowModeTransparent : 'شفاف',
windowMode : 'حالت پنجره',
flashvars : 'مقادیر برای فلش',
bgcolor : 'رنگ پسزمینه',
hSpace : 'فاصلهٴ افقی',
vSpace : 'فاصلهٴ عمودی',
validateSrc : 'لطفا URL پیوند را بنویسید',
validateHSpace : 'مقدار فاصلهگذاری افقی باید یک عدد باشد.',
validateVSpace : 'مقدار فاصلهگذاری عمودی باید یک عدد باشد.'
},
// Speller Pages Dialog
spellCheck :
{
toolbar : 'بررسی املا',
title : 'بررسی املا',
notAvailable : 'با عرض پوزش خدمات الان در دسترس نیستند.',
errorLoading : 'خطا در بارگیری برنامه خدمات میزبان: %s.',
notInDic : 'در واژه~نامه یافت نشد',
changeTo : 'تغییر به',
btnIgnore : 'چشمپوشی',
btnIgnoreAll : 'چشمپوشی همه',
btnReplace : 'جایگزینی',
btnReplaceAll : 'جایگزینی همه',
btnUndo : 'واچینش',
noSuggestions : '- پیشنهادی نیست -',
progress : 'بررسی املا در حال انجام...',
noMispell : 'بررسی املا انجام شد. هیچ غلط املائی یافت نشد',
noChanges : 'بررسی املا انجام شد. هیچ واژهای تغییر نیافت',
oneChange : 'بررسی املا انجام شد. یک واژه تغییر یافت',
manyChanges : 'بررسی املا انجام شد. %1 واژه تغییر یافت',
ieSpellDownload : 'بررسی کنندهٴ املا نصب نشده است. آیا میخواهید آن را هماکنون دریافت کنید؟'
},
smiley :
{
toolbar : 'خندانک',
title : 'گنجاندن خندانک',
options : 'گزینههای خندانک'
},
elementsPath :
{
eleLabel : 'مسیر عناصر',
eleTitle : '%1 عنصر'
},
numberedlist : 'فهرست شمارهدار',
bulletedlist : 'فهرست نقطهای',
indent : 'افزایش تورفتگی',
outdent : 'کاهش تورفتگی',
justify :
{
left : 'چپچین',
center : 'میانچین',
right : 'راستچین',
block : 'بلوکچین'
},
blockquote : 'بلوک نقل قول',
clipboard :
{
title : 'چسباندن',
cutError : 'تنظیمات امنیتی مرورگر شما اجازه نمیدهد که ویرایشگر به طور خودکار عملکردهای برش را انجام دهد. لطفا با دکمههای صفحه کلید این کار را انجام دهید (Ctrl/Cmd+X).',
copyError : 'تنظیمات امنیتی مرورگر شما اجازه نمیدهد که ویرایشگر به طور خودکار عملکردهای کپی کردن را انجام دهد. لطفا با دکمههای صفحه کلید این کار را انجام دهید (Ctrl/Cmd+C).',
pasteMsg : 'لطفا متن را با کلیدهای (<STRONG>Ctrl/Cmd+V</STRONG>) در این جعبهٴ متنی بچسبانید و <STRONG>پذیرش</STRONG> را بزنید.',
securityMsg : 'به خاطر تنظیمات امنیتی مرورگر شما، ویرایشگر نمیتواند دسترسی مستقیم به دادههای clipboard داشته باشد. شما باید دوباره آنرا در این پنجره بچسبانید.',
pasteArea : 'محل چسباندن'
},
pastefromword :
{
confirmCleanup : 'متنی که میخواهید بچسبانید به نظر میرسد که از Word کپی شده است. آیا میخواهید قبل از چسباندن آن را پاکسازی کنید؟',
toolbar : 'چسباندن از Word',
title : 'چسباندن از Word',
error : 'به دلیل بروز خطای داخلی امکان پاکسازی اطلاعات بازنشانی شده وجود ندارد.'
},
pasteText :
{
button : 'چسباندن به عنوان متن ِساده',
title : 'چسباندن به عنوان متن ِساده'
},
templates :
{
button : 'الگوها',
title : 'الگوهای محتویات',
options : 'گزینههای الگو',
insertOption : 'محتویات کنونی جایگزین شوند',
selectPromptMsg : 'لطفا الگوی موردنظر را برای بازکردن در ویرایشگر برگزینید<br>(محتویات کنونی از دست خواهند رفت):',
emptyListMsg : '(الگوئی تعریف نشده است)'
},
showBlocks : 'نمایش بلوکها',
stylesCombo :
{
label : 'سبک',
panelTitle : 'سبکهای قالببندی',
panelTitle1 : 'سبکهای بلوک',
panelTitle2 : 'سبکهای درونخطی',
panelTitle3 : 'سبکهای شیء'
},
format :
{
label : 'فرمت',
panelTitle : 'فرمت',
tag_p : 'نرمال',
tag_pre : 'فرمت شده',
tag_address : 'آدرس',
tag_h1 : 'سرنویس 1',
tag_h2 : 'سرنویس 2',
tag_h3 : 'سرنویس 3',
tag_h4 : 'سرنویس 4',
tag_h5 : 'سرنویس 5',
tag_h6 : 'سرنویس 6',
tag_div : 'بند'
},
div :
{
title : 'ایجاد یک محل DIV',
toolbar : 'ایجاد یک محل DIV',
cssClassInputLabel : 'کلاسهای شیوهنامه',
styleSelectLabel : 'سبک',
IdInputLabel : 'شناسه',
languageCodeInputLabel : ' کد زبان',
inlineStyleInputLabel : 'سبک درونخطی(Inline Style)',
advisoryTitleInputLabel : 'عنوان مشاوره',
langDirLabel : 'جهت نوشتاری زبان',
langDirLTRLabel : 'چپ به راست (LTR)',
langDirRTLLabel : 'راست به چپ (RTL)',
edit : 'ویرایش Div',
remove : 'حذف Div'
},
iframe :
{
title : 'ویژگیهای IFrame',
toolbar : 'IFrame',
noUrl : 'لطفا مسیر URL iframe را درج کنید',
scrolling : 'نمایش خطکشها',
border : 'نمایش خطوط frame'
},
font :
{
label : 'قلم',
voiceLabel : 'قلم',
panelTitle : 'قلم'
},
fontSize :
{
label : 'اندازه',
voiceLabel : 'اندازه قلم',
panelTitle : 'اندازه'
},
colorButton :
{
textColorTitle : 'رنگ متن',
bgColorTitle : 'رنگ پسزمینه',
panelTitle : 'رنگها',
auto : 'خودکار',
more : 'رنگهای بیشتر...'
},
colors :
{
'000' : 'سیاه',
'800000' : 'خرمایی',
'8B4513' : 'قهوهای شکلاتی',
'2F4F4F' : 'ارغوانی مایل به خاکستری',
'008080' : 'آبی مایل به خاکستری',
'000080' : 'آبی سیر',
'4B0082' : 'نیلی',
'696969' : 'خاکستری تیره',
'B22222' : 'آتش آجری',
'A52A2A' : 'قهوهای',
'DAA520' : 'میلهی طلایی',
'006400' : 'سبز تیره',
'40E0D0' : 'فیروزهای',
'0000CD' : 'آبی روشن',
'800080' : 'ارغوانی',
'808080' : 'خاکستری',
'F00' : 'قرمز',
'FF8C00' : 'نارنجی پررنگ',
'FFD700' : 'طلایی',
'008000' : 'سبز',
'0FF' : 'آبی مایل به سبز',
'00F' : 'آبی',
'EE82EE' : 'بنفش',
'A9A9A9' : 'خاکستری مات',
'FFA07A' : 'صورتی کدر روشن',
'FFA500' : 'نارنجی',
'FFFF00' : 'زرد',
'00FF00' : 'فسفری',
'AFEEEE' : 'فیروزهای رنگ پریده',
'ADD8E6' : 'آبی کمرنگ',
'DDA0DD' : 'آلویی',
'D3D3D3' : 'خاکستری روشن',
'FFF0F5' : 'بنفش کمرنگ',
'FAEBD7' : 'عتیقه سفید',
'FFFFE0' : 'زرد روشن',
'F0FFF0' : 'عسلی',
'F0FFFF' : 'لاجوردی',
'F0F8FF' : 'آبی براق',
'E6E6FA' : 'بنفش کمرنگ',
'FFF' : 'سفید'
},
scayt :
{
title : 'بررسی املای تایپ شما',
opera_title : 'توسط اپرا پشتیبانی نمیشود',
enable : 'فعالسازی SCAYT',
disable : 'غیرفعالسازی SCAYT',
about : 'درباره SCAYT',
toggle : 'ضامن SCAYT',
options : 'گزینهها',
langs : 'زبانها',
moreSuggestions : 'پیشنهادهای بیشتر',
ignore : 'عبور کردن',
ignoreAll : 'عبور کردن از همه',
addWord : 'افزودن Word',
emptyDic : 'نام دیکشنری نباید خالی باشد.',
optionsTab : 'گزینهها',
allCaps : 'نادیده گرفتن همه کلاه-واژهها',
ignoreDomainNames : 'عبور از نامهای دامنه',
mixedCase : 'عبور از کلماتی مرکب از حروف بزرگ و کوچک',
mixedWithDigits : 'عبور از کلمات به همراه عدد',
languagesTab : 'زبانها',
dictionariesTab : 'دیکشنریها',
dic_field_name : 'نام دیکشنری',
dic_create : 'ایجاد',
dic_restore : 'بازیافت',
dic_delete : 'حذف',
dic_rename : 'تغییر نام',
dic_info : 'در ابتدا دیکشنری کاربر در کوکی ذخیره میشود. با این حال، کوکیها در اندازه محدود شدهاند. وقتی که دیکشنری کاربری بزرگ میشود و به نقطهای که نمیتواند در کوکی ذخیره شود، پس از آن دیکشنری ممکن است بر روی سرور ما ذخیره شود. برای ذخیره دیکشنری شخصی شما بر روی سرور ما، باید یک نام برای دیکشنری خود مشخص نمایید. اگر شما قبلا یک دیکشنری روی سرور ما ذخیره کردهاید، لطفا نام آنرا درج و روی دکمه بازیافت کلیک نمایید.',
aboutTab : 'درباره'
},
about :
{
title : 'درباره CKEditor',
dlgTitle : 'درباره CKEditor',
help : 'بررسی $1 برای راهنمایی.',
userGuide : 'راهنمای کاربران CKEditor',
moreInfo : 'برای کسب اطلاعات مجوز لطفا به وب سایت ما مراجعه کنید:',
copy : 'حق نشر © $1. کلیه حقوق محفوظ است.'
},
maximize : 'حداکثر کردن',
minimize : 'حداقل کردن',
fakeobjects :
{
anchor : 'لنگر',
flash : 'انیمشن فلش',
iframe : 'IFrame',
hiddenfield : 'فیلد پنهان',
unknown : 'شیء ناشناخته'
},
resize : 'کشیدن برای تغییر اندازه',
colordialog :
{
title : 'انتخاب رنگ',
options : 'گزینههای رنگ',
highlight : 'متمایز',
selected : 'رنگ انتخاب شده',
clear : 'پاک کردن'
},
toolbarCollapse : 'بستن نوار ابزار',
toolbarExpand : 'بازکردن نوار ابزار',
toolbarGroups :
{
document : 'سند',
clipboard : 'حافظه موقت/برگشت',
editing : 'در حال ویرایش',
forms : 'فرمها',
basicstyles : 'شیوههای پایه',
paragraph : 'بند',
links : 'پیوندها',
insert : 'ورود',
styles : 'شیوهها',
colors : 'رنگها',
tools : 'ابزارها'
},
bidi :
{
ltr : 'نوشتار متن از چپ به راست',
rtl : 'نوشتار متن از راست به چپ'
},
docprops :
{
label : 'ویژگیهای سند',
title : 'ویژگیهای سند',
design : 'طراحی',
meta : 'فراداده',
chooseColor : 'انتخاب',
other : '<سایر>',
docTitle : 'عنوان صفحه',
charset : 'رمزگذاری نویسهگان',
charsetOther : 'رمزگذاری نویسهگان دیگر',
charsetASCII : 'ASCII',
charsetCE : 'اروپای مرکزی',
charsetCT : 'چینی رسمی (Big5)',
charsetCR : 'سیریلیک',
charsetGR : 'یونانی',
charsetJP : 'ژاپنی',
charsetKR : 'کرهای',
charsetTR : 'ترکی',
charsetUN : 'یونیکُد (UTF-8)',
charsetWE : 'اروپای غربی',
docType : 'عنوان نوع سند',
docTypeOther : 'عنوان نوع سند دیگر',
xhtmlDec : 'شامل تعاریف XHTML',
bgColor : 'رنگ پسزمینه',
bgImage : 'URL تصویر پسزمینه',
bgFixed : 'پسزمینهٴ پیمایش ناپذیر',
txtColor : 'رنگ متن',
margin : 'حاشیههای صفحه',
marginTop : 'بالا',
marginLeft : 'چپ',
marginRight : 'راست',
marginBottom : 'پایین',
metaKeywords : 'کلیدواژگان نمایهگذاری سند (با کاما جدا شوند)',
metaDescription : 'توصیف سند',
metaAuthor : 'نویسنده',
metaCopyright : 'حق انتشار',
previewHtml : '<p>این یک <strong>متن نمونه</strong> است. شما در حال استفاده از <a href="javascript:void(0)">CKEditor</a> هستید.</p>'
}
};
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview
*/
/**#@+
@type String
@example
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKEDITOR.lang['ku'] =
{
/**
* The language reading direction. Possible values are "rtl" for
* Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right
* languages (like English).
* @default 'ltr'
*/
dir : 'rtl',
/*
* Screenreader titles. Please note that screenreaders are not always capable
* of reading non-English words. So be careful while translating it.
*/
editorTitle : 'دهسکاریکهری ناونیشان',
editorHelp : 'کلیکی ALT لهگهڵ 0 بکه بۆ یارمهتی',
// ARIA descriptions.
toolbars : 'تووڵاەرازی دەسکاریکەر',
editor : 'سەرنووسەی دەقی بەپیت',
// Toolbar buttons without dialogs.
source : 'سەرچاوە',
newPage : 'پەڕەیەکی نوێ',
save : 'پاشکەوتکردن',
preview : 'پێشبینین',
cut : 'بڕین',
copy : 'لەبەرگرنتەوه',
paste : 'لکاندن',
print : 'چاپکردن',
underline : 'ژێرهێڵ',
bold : 'قەڵەو',
italic : 'لار',
selectAll : 'نیشانکردنی هەمووی',
removeFormat : 'لابردنی داڕشتەکە',
strike : 'لێدان',
subscript : 'ژێرنووس',
superscript : 'سەرنووس',
horizontalrule : 'دانانی هێلی ئاسۆیی',
pagebreak : 'دانانی پشووی پەڕە بۆ چاپکردن',
pagebreakAlt : 'پشووی پەڕە',
unlink : 'لابردنی بەستەر',
undo : 'پووچکردنەوه',
redo : 'هەڵگەڕاندنەوه',
// Common messages and labels.
common :
{
browseServer : 'هێنانی ڕاژە',
url : 'ناونیشانی بەستەر',
protocol : 'پڕۆتۆکۆڵ',
upload : 'بارکردن',
uploadSubmit : 'ناردنی بۆ ڕاژە',
image : 'وێنە',
flash : 'فلاش',
form : 'داڕشتە',
checkbox : 'خانەی نیشانکردن',
radio : 'جێگرەوەی دوگمە',
textField : 'خانەی دەق',
textarea : 'ڕووبەری دەق',
hiddenField : 'شاردنەوی خانە',
button : 'دوگمە',
select : 'هەڵبژاردەی خانە',
imageButton : 'دوگمەی وێنە',
notSet : '<هیچ دانەدراوە>',
id : 'ناسنامە',
name : 'ناو',
langDir : 'ئاراستەی زمان',
langDirLtr : 'چەپ بۆ ڕاست (LTR)',
langDirRtl : 'ڕاست بۆ چەپ (RTL)',
langCode : 'هێمای زمان',
longDescr : 'پێناسەی درێژی بەستەر',
cssClass : 'شێوازی چینی پهڕە',
advisoryTitle : 'ڕاوێژکاری سەردێڕ',
cssStyle : 'شێواز',
ok : 'باشە',
cancel : 'هەڵوەشاندن',
close : 'داخستن',
preview : 'پێشبینین',
generalTab : 'گشتی',
advancedTab : 'پهرهسهندوو',
validateNumberFailed : 'ئەم نرخە ژمارە نیه، تکایە نرخێکی ژمارە بنووسە.',
confirmNewPage : 'سەرجەم گۆڕانکاریەکان و پێکهاتەکانی ناوەووە لەدەست دەدەی گەر بێتوو پاشکەوتی نەکەی یەکەم جار، تۆ هەر دڵنیایی لەکردنەوەی پەنجەرەکی نوێ؟',
confirmCancel : 'هەندێك هەڵبژاردە گۆڕدراوە. تۆ دڵنیایی لهداخستنی ئەم دیالۆگە؟',
options : 'هەڵبژاردە',
target : 'ئامانج',
targetNew : 'پەنجەرەیهکی نوێ (_blank)',
targetTop : 'لووتکەی پەنجەرە (_top)',
targetSelf : 'لەهەمان پەنجەرە (_self)',
targetParent : 'پەنجەرەی باوان (_parent)',
langDirLTR : 'چەپ بۆ ڕاست (LTR)',
langDirRTL : 'ڕاست بۆ چەپ (RTL)',
styles : 'شێواز',
cssClasses : 'شێوازی چینی پەڕە',
width : 'پانی',
height : 'درێژی',
align : 'ڕێککەرەوە',
alignLeft : 'چەپ',
alignRight : 'ڕاست',
alignCenter : 'ناوەڕاست',
alignTop : 'سەرەوە',
alignMiddle : 'ناوەند',
alignBottom : 'ژێرەوە',
invalidValue : 'نرخێکی نادرووست.',
invalidHeight : 'درێژی دەبێت ژمارە بێت.',
invalidWidth : 'پانی دەبێت ژمارە بێت.',
invalidCssLength : 'ئەم نرخەی دراوە بۆ خانەی "%1" دەبێت ژمارەکی درووست بێت یان بێ ناونیشانی ئامرازی (px, %, in, cm, mm, em, ex, pt, یان pc).',
invalidHtmlLength : 'ئەم نرخەی دراوە بۆ خانەی "%1" دەبێت ژمارەکی درووست بێت یان بێ ناونیشانی ئامرازی HTML (px یان %).',
invalidInlineStyle : 'دانهی نرخی شێوازی ناوهێڵ دهبێت پێکهاتبێت لهیهك یان زیاتری داڕشته "ناو : نرخ", جیاکردنهوهی بهفاریزهوخاڵ',
cssLengthTooltip : 'ژمارهیهك بنووسه بۆ نرخی piksel یان ئامرازێکی درووستی CSS (px, %, in, cm, mm, em, ex, pt, یان pc).',
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, ئامادە نیە</span>'
},
contextmenu :
{
options : 'هەڵبژاردەی لیستەی کلیکی دەستی ڕاست'
},
// Special char dialog.
specialChar :
{
toolbar : 'دانانەی نووسەی تایبەتی',
title : 'هەڵبژاردنی نووسەی تایبەتی',
options : 'هەڵبژاردەی نووسەی تایبەتی'
},
// Link dialog.
link :
{
toolbar : 'دانان/ڕێکخستنی بەستەر',
other : '<هیتر>',
menu : 'چاکسازی بەستەر',
title : 'بەستەر',
info : 'زانیاری بەستەر',
target : 'ئامانج',
upload : 'بارکردن',
advanced : 'پێشکهوتوو',
type : 'جۆری بهستهر',
toUrl : 'ناونیشانی بهستهر',
toAnchor : 'بهستهر بۆ لهنگهر له دهق',
toEmail : 'ئیمهیل',
targetFrame : '<چووارچێوه>',
targetPopup : '<پهنجهرهی سهرههڵدهر>',
targetFrameName : 'ناوی ئامانجی چووارچێوه',
targetPopupName : 'ناوی پهنجهرهی سهرههڵدهر',
popupFeatures : 'خاسیهتی پهنجهرهی سهرههڵدهر',
popupResizable : 'توانای گۆڕینی قهباره',
popupStatusBar : 'هێڵی دۆخ',
popupLocationBar: 'هێڵی ناونیشانی بهستهر',
popupToolbar : 'هێڵی تووڵامراز',
popupMenuBar : 'هێڵی لیسته',
popupFullScreen : 'پڕ بهپڕی شاشه (IE)',
popupScrollBars : 'هێڵی هاتووچۆپێکردن',
popupDependent : 'پێوهبهستراو (Netscape)',
popupLeft : 'جێگای چهپ',
popupTop : 'جێگای سهرهوه',
id : 'ناسنامه',
langDir : 'ئاراستهی زمان',
langDirLTR : 'چهپ بۆ ڕاست (LTR)',
langDirRTL : 'ڕاست بۆ چهپ (RTL)',
acccessKey : 'کلیلی دهستپێگهیشتن',
name : 'ناو',
langCode : 'هێمای زمان',
tabIndex : 'بازدهری تابی ئیندێکس',
advisoryTitle : 'ڕاوێژکاری سهردێڕ',
advisoryContentType : 'جۆری ناوهڕۆکی ڕاویژکار',
cssClasses : 'شێوازی چینی پهڕه',
charset : 'بەستەری سەرچاوەی نووسه',
styles : 'شێواز',
rel : 'پهیوهندی (rel)',
selectAnchor : 'ههڵبژاردنی لهنگهرێك',
anchorName : 'بهپێی ناوی لهنگهر',
anchorId : 'بهپێی ناسنامهی توخم',
emailAddress : 'ناونیشانی ئیمهیل',
emailSubject : 'بابهتی نامه',
emailBody : 'ناوهڕۆکی نامه',
noAnchors : '(هیچ جۆرێکی لهنگهر ئاماده نیه لهم پهڕهیه)',
noUrl : 'تکایه ناونیشانی بهستهر بنووسه',
noEmail : 'تکایه ناونیشانی ئیمهیل بنووسه'
},
// Anchor dialog
anchor :
{
toolbar : 'دانان/چاکسازی لهنگهر',
menu : 'چاکسازی لهنگهر',
title : 'خاسیهتی لهنگهر',
name : 'ناوی لهنگهر',
errorName : 'تکایه ناوی لهنگهر بنووسه',
remove : 'لابردنی لهنگهر'
},
// List style dialog
list:
{
numberedTitle : 'خاسیهتی لیستی ژمارهیی',
bulletedTitle : 'خاسیهتی لیستی خاڵی',
type : 'جۆر',
start : 'دهستپێکردن',
validateStartNumber :'دهستپێکهری لیستی ژمارهیی دهبێت تهنها ژماره بێت.',
circle : 'بازنه',
disc : 'پهپکه',
square : 'چووراگۆشه',
none : 'هیچ',
notset : '<دانهندراوه>',
armenian : 'ئاراستهی ژمارهی ئهرمهنی',
georgian : 'ئاراستهی ژمارهی جۆڕجی (an, ban, gan, وههیتر.)',
lowerRoman : 'ژمارهی ڕۆمی بچووك (i, ii, iii, iv, v, وههیتر.)',
upperRoman : 'ژمارهی ڕۆمی گهوره (I, II, III, IV, V, وههیتر.)',
lowerAlpha : 'ئهلفابێی بچووك (a, b, c, d, e, وههیتر.)',
upperAlpha : 'ئهلفابێی گهوره (A, B, C, D, E, وههیتر.)',
lowerGreek : 'یۆنانی بچووك (alpha, beta, gamma, وههیتر.)',
decimal : 'ژماره (1, 2, 3, وههیتر.)',
decimalLeadingZero : 'ژماره سفڕی لهپێشهوه (01, 02, 03, وههیتر.)'
},
// Find And Replace Dialog
findAndReplace :
{
title : 'گهڕان وه لهبریدانان',
find : 'گهڕان',
replace : 'لهبریدانان',
findWhat : 'گهڕان بهدووای:',
replaceWith : 'لهبریدانان به:',
notFoundMsg : 'هیچ دهقه گهڕانێك نهدۆزراوه.',
findOptions : 'ههڵبژاردهکانی گهڕان',
matchCase : 'جیاکردنهوه لهنێوان پیتی گهورهو بچووك',
matchWord : 'تهنها ههموو وشهکه',
matchCyclic : 'گهڕان لهههموو پهڕهکه',
replaceAll : 'لهبریدانانی ههمووی',
replaceSuccessMsg : ' پێشهاته(ی) لهبری دانرا. %1'
},
// Table Dialog
table :
{
toolbar : 'خشته',
title : 'خاسیهتی خشته',
menu : 'خاسیهتی خشته',
deleteTable : 'سڕینهوهی خشته',
rows : 'ڕیز',
columns : 'ستوونهکان',
border : 'گهورهیی پهراوێز',
widthPx : 'وێنهخاڵ - پیکسل',
widthPc : 'لهسهدا',
widthUnit : 'پانی یهکه',
cellSpace : 'بۆشایی خانه',
cellPad : 'بۆشایی ناوپۆش',
caption : 'سهردێڕ',
summary : 'کورته',
headers : 'سهرپهڕه',
headersNone : 'هیچ',
headersColumn : 'یهکهم ئهستوون',
headersRow : 'یهکهم ڕیز',
headersBoth : 'ههردووك',
invalidRows : 'ژمارهی ڕیز دهبێت گهورهتر بێت لهژمارهی 0.',
invalidCols : 'ژمارهی ئهستوونی دهبێت گهورهتر بێت لهژمارهی 0.',
invalidBorder : 'ژمارهی پهراوێز دهبێت تهنها ژماره بێت.',
invalidWidth : 'پانی خشته دهبێت تهنها ژماره بێت.',
invalidHeight : 'درێژی خشته دهبێت تهنها ژماره بێت.',
invalidCellSpacing : 'بۆشایی خانه دهبێت ژمارهکی درووست بێت.',
invalidCellPadding : 'ناوپۆشی خانه دهبێت ژمارهکی درووست بێت.',
cell :
{
menu : 'خانه',
insertBefore : 'دانانی خانه لهپێش',
insertAfter : 'دانانی خانه لهپاش',
deleteCell : 'سڕینهوهی خانه',
merge : 'تێکهڵکردنی خانه',
mergeRight : 'تێکهڵکردنی لهگهڵ ڕاست',
mergeDown : 'تێکهڵکردنی لهگهڵ خوارهوه',
splitHorizontal : 'دابهشکردنی خانهی ئاسۆیی',
splitVertical : 'دابهشکردنی خانهی ئهستونی',
title : 'خاسیهتی خانه',
cellType : 'جۆری خانه',
rowSpan : 'ماوهی نێوان ڕیز',
colSpan : 'بستی ئهستونی',
wordWrap : 'پێچانهوهی وشه',
hAlign : 'ڕیزکردنی ئاسۆیی',
vAlign : 'ڕیزکردنی ئهستونی',
alignBaseline : 'هێڵهبنهڕهت',
bgColor : 'ڕهنگی پاشبنهما',
borderColor : 'ڕهنگی پهراوێز',
data : 'داتا',
header : 'سهرپهڕه',
yes : 'بهڵێ',
no : 'نهخێر',
invalidWidth : 'پانی خانه دهبێت بهتهواوی ژماره بێت.',
invalidHeight : 'درێژی خانه بهتهواوی دهبێت ژماره بێت.',
invalidRowSpan : 'ماوهی نێوان ڕیز بهتهواوی دهبێت ژماره بێت.',
invalidColSpan : 'ماوهی نێوان ئهستونی بهتهواوی دهبێت ژماره بێت.',
chooseColor : 'ههڵبژاردن'
},
row :
{
menu : 'ڕیز',
insertBefore : 'دانانی ڕیز لهپێش',
insertAfter : 'دانانی ڕیز لهپاش',
deleteRow : 'سڕینهوهی ڕیز'
},
column :
{
menu : 'ئهستون',
insertBefore : 'دانانی ئهستون لهپێش',
insertAfter : 'دانانی ئهستوون لهپاش',
deleteColumn : 'سڕینهوهی ئهستوون'
}
},
// Button Dialog.
button :
{
title : 'خاسیهتی دوگمه',
text : '(نرخی) دهق',
type : 'جۆر',
typeBtn : 'دوگمه',
typeSbm : 'ناردن',
typeRst : 'ڕێکخستنهوه'
},
// Checkbox and Radio Button Dialogs.
checkboxAndRadio :
{
checkboxTitle : 'خاسیهتی چووارگۆشی پشکنین',
radioTitle : 'خاسیهتی جێگرهوهی دوگمه',
value : 'نرخ',
selected : 'ههڵبژاردرا'
},
// Form Dialog.
form :
{
title : 'خاسیهتی داڕشته',
menu : 'خاسیهتی داڕشته',
action : 'کردار',
method : 'ڕێگه',
encoding : 'بهکۆدکهر'
},
// Select Field Dialog.
select :
{
title : 'ههڵبژاردهی خاسیهتی خانه',
selectInfo : 'زانیاری',
opAvail : 'ههڵبژاردهی ههبوو',
value : 'نرخ',
size : 'گهورهیی',
lines : 'هێڵهکان',
chkMulti : 'ڕێدان بهفره ههڵبژارده',
opText : 'دهق',
opValue : 'نرخ',
btnAdd : 'زیادکردن',
btnModify : 'گۆڕانکاری',
btnUp : 'سهرهوه',
btnDown : 'خوارهوه',
btnSetValue : 'دابنێ وهك نرخێکی ههڵبژێردراو',
btnDelete : 'سڕینهوه'
},
// Textarea Dialog.
textarea :
{
title : 'خاسیهتی ڕووبهری دهق',
cols : 'ئهستونیهکان',
rows : 'ڕیزهکان'
},
// Text Field Dialog.
textfield :
{
title : 'خاسیهتی خانهی دهق',
name : 'ناو',
value : 'نرخ',
charWidth : 'پانی نووسه',
maxChars : 'ئهوپهڕی نووسه',
type : 'جۆر',
typeText : 'دهق',
typePass : 'پێپهڕهوشه'
},
// Hidden Field Dialog.
hidden :
{
title : 'خاسیهتی خانهی شاردراوه',
name : 'ناو',
value : 'نرخ'
},
// Image Dialog.
image :
{
title : 'خاسیهتی وێنه',
titleButton : 'خاسیهتی دوگمهی وێنه',
menu : 'خاسیهتی وێنه',
infoTab : 'زانیاری وێنه',
btnUpload : 'ناردنی بۆ ڕاژه',
upload : 'بارکردن',
alt : 'جێگرهوهی دهق',
lockRatio : 'داخستنی ڕێژه',
resetSize : 'ڕێکخستنهوهی قهباره',
border : 'پهراوێز',
hSpace : 'بۆشایی ئاسۆیی',
vSpace : 'بۆشایی ئهستونی',
alertUrl : 'تکایه ناونیشانی بهستهری وێنه بنووسه',
linkTab : 'بهستهر',
button2Img : 'تۆ دهتهوێت دوگمهی وێنهی دیاریکراو بگۆڕیت بۆ وێنهکی ئاسایی؟',
img2Button : 'تۆ دهتهوێت وێنهی دیاریکراو بگۆڕیت بۆ دوگمهی وێنه؟',
urlMissing : 'سهرچاوهی بهستهری وێنه بزره',
validateBorder : 'پهراوێز دهبێت بهتهواوی تهنها ژماره بێت.',
validateHSpace : 'بۆشایی ئاسۆیی دهبێت بهتهواوی تهنها ژماره بێت.',
validateVSpace : 'بۆشایی ئهستونی دهبێت بهتهواوی تهنها ژماره بێت.'
},
// Flash Dialog
flash :
{
properties : 'خاسیهتی فلاش',
propertiesTab : 'خاسیهت',
title : 'خاسیهتی فلاش',
chkPlay : 'پێکردنی یان لێدانی خۆکار',
chkLoop : 'گرێ',
chkMenu : 'چالاککردنی لیستهی فلاش',
chkFull : 'ڕێپێدان به پڕ بهپڕی شاشه',
scale : 'پێوانه',
scaleAll : 'نیشاندانی ههموو',
scaleNoBorder : 'بێ پهراوێز',
scaleFit : 'بهوردی بگونجێت',
access : 'دهستپێگهیشتنی نووسراو',
accessAlways : 'ههمیشه',
accessSameDomain: 'ههمان دۆمهین',
accessNever : 'ههرگیز',
alignAbsBottom : 'له ژێرهوه',
alignAbsMiddle : 'لهناوهند',
alignBaseline : 'هێڵەبنەڕەت',
alignTextTop : 'دهق لهسهرهوه',
quality : 'جۆرایهتی',
qualityBest : 'باشترین',
qualityHigh : 'بهرزی',
qualityAutoHigh : 'بهرزی خۆکار',
qualityMedium : 'مامناوهند',
qualityAutoLow : 'نزمی خۆکار',
qualityLow : 'نزم',
windowModeWindow: 'پهنجهره',
windowModeOpaque: 'ناڕوون',
windowModeTransparent : 'ڕۆشن',
windowMode : 'شێوازی پهنجهره',
flashvars : 'گۆڕاوهکان بۆ فلاش',
bgcolor : 'ڕهنگی پاشبنهما',
hSpace : 'بۆشایی ئاسۆیی',
vSpace : 'بۆشایی ئهستونی',
validateSrc : 'ناونیشانی بهستهر نابێت خاڵی بێت',
validateHSpace : 'بۆشایی ئاسۆیی دهبێت ژماره بێت.',
validateVSpace : 'بۆشایی ئهستونی دهبێت ژماره بێت.'
},
// Speller Pages Dialog
spellCheck :
{
toolbar : 'پشکنینی ڕێنووس',
title : 'پشکنینی ڕێنووس',
notAvailable : 'ببووره، لهمکاتهدا ڕاژهکه لهبهردهستا نیه.',
errorLoading : 'ههڵه لههێنانی داخوازینامهی خانهخۆێی ڕاژه: %s.',
notInDic : 'لهفهرههنگ دانیه',
changeTo : 'گۆڕینی بۆ',
btnIgnore : 'پشتگوێ کردن',
btnIgnoreAll : 'پشتگوێکردنی ههمووی',
btnReplace : 'لهبریدانن',
btnReplaceAll : 'لهبریدانانی ههمووی',
btnUndo : 'پووچکردنهوه',
noSuggestions : '- هیچ پێشنیارێك -',
progress : 'پشکنینی ڕێنووس لهبهردهوامبوون دایه...',
noMispell : 'پشکنینی ڕێنووس کۆتای هات: هیچ ههڵهیهکی ڕێنووس نهدۆزراوه',
noChanges : 'پشکنینی ڕێنووس کۆتای هات: هیچ وشهیهك نۆگۆڕدرا',
oneChange : 'پشکنینی ڕێنووس کۆتای هات: یهك وشه گۆڕدرا',
manyChanges : 'پشکنینی ڕێنووس کۆتای هات: لهسهدا %1 ی وشهکان گۆڕدرا',
ieSpellDownload : 'پشکنینی ڕێنووس دانهمزراوه. دهتهوێت ئێستا دایبگریت?'
},
smiley :
{
toolbar : 'زهردهخهنه',
title : 'دانانی زهردهخهنهیهك',
options : 'ههڵبژاردهی زهردهخهنه'
},
elementsPath :
{
eleLabel : 'ڕێڕهوی توخمهکان',
eleTitle : '%1 توخم'
},
numberedlist : 'دانان/لابردنی ژمارەی لیست',
bulletedlist : 'دانان/لابردنی خاڵی لیست',
indent : 'زیادکردنی بۆشایی',
outdent : 'کەمکردنەوەی بۆشایی',
justify :
{
left : 'بههێڵ کردنی چهپ',
center : 'ناوهڕاست',
right : 'بههێڵ کردنی ڕاست',
block : 'هاوستوونی'
},
blockquote : 'بەربەستکردنی وتەی وەرگیراو',
clipboard :
{
title : 'لکاندن',
cutError : 'پارێزی وێبگەڕەکەت ڕێگهنادات بە سەرنووسەکە لهبڕینی خۆکار. تکایە لەبری ئەمە ئەم فەرمانە بەکاربهێنە بەداگرتنی کلیلی (Ctrl/Cmd+X).',
copyError : 'پارێزی وێبگەڕەکەت ڕێگهنادات بەسەرنووسەکە لە لکاندنی دەقی خۆکار. تکایە لەبری ئەمە ئەم فەرمانە بەکاربهێنە بەداگرتنی کلیلی (Ctrl/Cmd+C).',
pasteMsg : 'تکایه بیلکێنه لهناوهوهی ئهم سنوقه لهڕێی تهختهکلیلهکهت بهباکارهێنانی کلیلی (<STRONG>Ctrl/Cmd+V</STRONG>) دووای کلیکی باشه بکه.',
securityMsg : 'بههۆی شێوهپێدانی پارێزی وێبگهڕهکهت، سهرنووسهکه ناتوانێت دهستبگهیهنێت بهههڵگیراوهکه ڕاستهوخۆ. بۆیه پێویسته دووباره بیلکێنیت لهم پهنجهرهیه.',
pasteArea : 'ناوچهی لکاندن'
},
pastefromword :
{
confirmCleanup : 'ئهم دهقهی بهتهمای بیلکێنی پێدهچێت له word هێنرابێت. دهتهوێت پاکی بکهیوه پێش ئهوهی بیلکێنی؟',
toolbar : 'لکاندنی لهڕێی Word',
title : 'لکاندنی لهلایهن Word',
error : 'هیچ ڕێگهیهك نهبوو لهلکاندنی دهقهکه بههۆی ههڵهکی ناوهخۆیی'
},
pasteText :
{
button : 'لکاندنی وهك دهقی ڕوون',
title : 'لکاندنی وهك دهقی ڕوون'
},
templates :
{
button : 'ڕووکار',
title : 'پێکهاتهی ڕووکار',
options : 'ههڵبژاردهکانی ڕووکار',
insertOption : 'لهشوێن دانانی ئهم پێکهاتانهی ئێستا',
selectPromptMsg : 'ڕووکارێك ههڵبژێره بۆ کردنهوهی له سهرنووسهر:',
emptyListMsg : '(هیچ ڕووکارێك دیارینهکراوه)'
},
showBlocks : 'نیشاندانی بەربەستەکان',
stylesCombo :
{
label : 'شێواز',
panelTitle : 'شێوازی ڕازاندنهوه',
panelTitle1 : 'شێوازی خشت',
panelTitle2 : 'شێوازی ناوهێڵ',
panelTitle3 : 'شێوازی بهرکار'
},
format :
{
label : 'ڕازاندنهوه',
panelTitle : 'بهشی ڕازاندنهوه',
tag_p : 'ئاسایی',
tag_pre : 'شێوازکراو',
tag_address : 'ناونیشان',
tag_h1 : 'سهرنووسهی ١',
tag_h2 : 'سهرنووسهی ٢',
tag_h3 : 'سهرنووسهی ٣',
tag_h4 : 'سهرنووسهی ٤',
tag_h5 : 'سهرنووسهی ٥',
tag_h6 : 'سهرنووسهی ٦',
tag_div : '(DIV)-ی ئاسایی'
},
div :
{
title : 'دانانی لهخۆگری Div',
toolbar : 'دانانی لهخۆگری Div',
cssClassInputLabel : 'شێوازی چینی پهڕه',
styleSelectLabel : 'شێواز',
IdInputLabel : 'ناسنامه',
languageCodeInputLabel : 'هێمای زمان',
inlineStyleInputLabel : 'شێوازی ناوهێڵ',
advisoryTitleInputLabel : 'سهردێڕ',
langDirLabel : 'ئاراستهی زمان',
langDirLTRLabel : 'چهپ بۆ ڕاست (LTR)',
langDirRTLLabel : 'ڕاست بۆ چهپ (RTL)',
edit : 'چاکسازی Div',
remove : 'لابردنی Div'
},
iframe :
{
title : 'دیالۆگی چووارچێوه',
toolbar : 'چووارچێوه',
noUrl : 'تکایه ناونیشانی بهستهر بنووسه بۆ چووارچێوه',
scrolling : 'چالاککردنی هاتووچۆپێکردن',
border : 'نیشاندانی لاکێشه بهچوواردهوری چووارچێوه'
},
font :
{
label : 'فۆنت',
voiceLabel : 'فۆنت',
panelTitle : 'ناوی فۆنت'
},
fontSize :
{
label : 'گهورهیی',
voiceLabel : 'گهورهیی فۆنت',
panelTitle : 'گهورهیی فۆنت'
},
colorButton :
{
textColorTitle : 'ڕهنگی دهق',
bgColorTitle : 'ڕهنگی پاشبنهما',
panelTitle : 'ڕهنگهکان',
auto : 'خۆکار',
more : 'ڕهنگی زیاتر...'
},
colors :
{
'000' : 'ڕهش',
'800000' : 'سۆرو ماڕوونی',
'8B4513' : 'ماڕوونی',
'2F4F4F' : 'سهوزی تاریك',
'008080' : 'سهوزو شین',
'000080' : 'شینی تۆخ',
'4B0082' : 'مۆری تۆخ',
'696969' : 'ڕهساسی تۆخ',
'B22222' : 'سۆری تۆخ',
'A52A2A' : 'قاوهیی',
'DAA520' : 'قاوهیی بریسکهدار',
'006400' : 'سهوزی تۆخ',
'40E0D0' : 'شینی ناتۆخی بریسکهدار',
'0000CD' : 'شینی مامناوهند',
'800080' : 'پهمبهیی',
'808080' : 'ڕهساسی',
'F00' : 'سۆر',
'FF8C00' : 'نارهنجی تۆخ',
'FFD700' : 'زهرد',
'008000' : 'سهوز',
'0FF' : 'شینی ئاسمانی',
'00F' : 'شین',
'EE82EE' : 'پهمهیی',
'A9A9A9' : 'ڕهساسی ناتۆخ',
'FFA07A' : 'نارهنجی ناتۆخ',
'FFA500' : 'نارهنجی',
'FFFF00' : 'زهرد',
'00FF00' : 'سهوز',
'AFEEEE' : 'شینی ناتۆخ',
'ADD8E6' : 'شینی زۆر ناتۆخ',
'DDA0DD' : 'پهمهیی ناتۆخ',
'D3D3D3' : 'ڕهساسی بریسکهدار',
'FFF0F5' : 'جهرگی زۆر ناتۆخ',
'FAEBD7' : 'جهرگی ناتۆخ',
'FFFFE0' : 'سپی ناتۆخ',
'F0FFF0' : 'ههنگوینی ناتۆخ',
'F0FFFF' : 'شینێکی زۆر ناتۆخ',
'F0F8FF' : 'شینێکی ئاسمانی زۆر ناتۆخ',
'E6E6FA' : 'شیری',
'FFF' : 'سپی'
},
scayt :
{
title : 'پشکنینی نووسه لهکاتی نووسین',
opera_title : 'پشتیوانی نهکراوه لهلایهن Opera',
enable : 'چالاککردنی SCAYT',
disable : 'ناچالاککردنی SCAYT',
about : 'دهربارهی SCAYT',
toggle : 'گۆڕینی SCAYT',
options : 'ههڵبژارده',
langs : 'زمانهکان',
moreSuggestions : 'پێشنیاری زیاتر',
ignore : 'پشتگوێخستن',
ignoreAll : 'پشتگوێخستنی ههمووی',
addWord : 'زیادکردنی ووشه',
emptyDic : 'ناوی فهرههنگ نابێت خاڵی بێت.',
optionsTab : 'ههڵبژارده',
allCaps : 'پشتگوێخستنی وشانهی پێکهاتووه لهپیتی گهوره',
ignoreDomainNames : 'پشتگوێخستنی دۆمهین',
mixedCase : 'پشتگوێخستنی وشانهی پێکهاتووه لهپیتی گهورهو بچووك',
mixedWithDigits : 'پشتگوێخستنی وشانهی پێکهاتووه لهژماره',
languagesTab : 'زمانهکان',
dictionariesTab : 'فهرههنگهکان',
dic_field_name : 'ناوی فهرههنگ',
dic_create : 'درووستکردن',
dic_restore : 'گهڕاندنهوه',
dic_delete : 'سڕینهوه',
dic_rename : 'گۆڕینی ناو',
dic_info : 'لهبنچینهدا فهرههنگی بهکارهێنهر کۆگاکردن کراوه له شهکرۆکه Cookie, ههرچۆنێك بێت شهکۆرکه سنووردار کراوه له قهباره کۆگاکردن.کاتێك فهرههنگی بهکارهێنهر گهیشته ئهم خاڵهی کهناتوانرێت زیاتر کۆگاکردن بکرێت له شهکرۆکه، ئهوسا فهرههنگهکه پێویسته کۆگابکرێت له ڕاژهکهی ئێمه. بۆ کۆگاکردنی زانیاری تایبهتی فهرههنگهکه له ڕاژهکهی ئێمه, پێویسته ناوێك ههڵبژێریت بۆ فهرههنگهکه. گهر تۆ فهرههنگێکی کۆگاکراوت ههیه, تکایه ناوی فهرههنگهکه بنووسه وه کلیکی دوگمهی گهڕاندنهوه بکه.',
aboutTab : 'دهربارهی'
},
about :
{
title : 'دهربارهی CKEditor',
dlgTitle : 'دهربارهی CKEditor',
help : 'سهیری $1 بکه بۆ یارمهتی.',
userGuide : 'ڕێپیشاندهری CKEditors',
moreInfo : 'بۆ زانیاری زیاتری مۆڵهت, تکایه سهردانی ماڵپهڕهکهمان بکه:',
copy : 'مافی لهبهرگرتنهوهی © $1. گشتی پارێزراوه.'
},
maximize : 'ئەوپهڕی گەورەیی',
minimize : 'ئەوپەڕی بچووکی',
fakeobjects :
{
anchor : 'لهنگهر',
flash : 'فلاش',
iframe : 'لهچوارچێوه',
hiddenfield : 'شاردنهوهی خانه',
unknown : 'بهرکارێکی نهناسراو'
},
resize : 'ڕابکێشە بۆ گۆڕینی قەبارەکەی',
colordialog :
{
title : 'ههڵبژاردنی ڕهنگ',
options : 'ههڵبژاردهی ڕهنگهکان',
highlight : 'نیشانکردن',
selected : 'ههڵبژاردرا',
clear : 'پاککردنهوه'
},
toolbarCollapse : 'شاردنەوی هێڵی تووڵامراز',
toolbarExpand : 'نیشاندانی هێڵی تووڵامراز',
toolbarGroups :
{
document : 'پهڕه',
clipboard : 'بڕین/پووچکردنهوه',
editing : 'چاکسازی',
forms : 'داڕشته',
basicstyles : 'شێوازی بنچینهیی',
paragraph : 'بڕگه',
links : 'بهستهر',
insert : 'خستنه ناو',
styles : 'شێواز',
colors : 'ڕهنگهکان',
tools : 'ئامرازهکان'
},
bidi :
{
ltr : 'ئاراستهی نووسه لهچهپ بۆ ڕاست',
rtl : 'ئاراستهی نووسه لهڕاست بۆ چهپ'
},
docprops :
{
label : 'خاسییهتی پهڕه',
title : 'خاسییهتی پهڕه',
design : 'شێوهکار',
meta : 'زانیاری مێتا',
chooseColor : 'ههڵبژێره',
other : 'هیتر...',
docTitle : 'سهردێڕی پهڕه',
charset : 'دهستهی نووسهی بهکۆدهکهر',
charsetOther : 'دهستهی نووسهی بهکۆدهکهری تر',
charsetASCII : 'ASCII',
charsetCE : 'ناوهڕاست ئهوروپا',
charsetCT : 'چینی(Big5)',
charsetCR : 'سیریلیك',
charsetGR : 'یۆنانی',
charsetJP : 'ژاپۆن',
charsetKR : 'کۆریا',
charsetTR : 'تورکیا',
charsetUN : 'Unicode (UTF-8)',
charsetWE : 'ڕۆژئاوای ئهوروپا',
docType : 'سهرپهڕهی جۆری پهڕه',
docTypeOther : 'سهرپهڕهی جۆری پهڕهی تر',
xhtmlDec : 'بهیاننامهکانی XHTML لهگهڵدابێت',
bgColor : 'ڕهنگی پاشبنهما',
bgImage : 'ناونیشانی بهستهری وێنهی پاشبنهما',
bgFixed : 'بێ هاتووچوپێکردنی (چهسپاو) پاشبنهمای وێنه',
txtColor : 'ڕهنگی دهق',
margin : 'تهنیشت پهڕه',
marginTop : 'سهرهوه',
marginLeft : 'چهپ',
marginRight : 'ڕاست',
marginBottom : 'ژێرهوه',
metaKeywords : 'بهڵگهنامهی وشهی کاریگهر(به کۆما لێکیان جیابکهوه)',
metaDescription : 'پێناسهی لاپهڕه',
metaAuthor : 'نووسهر',
metaCopyright : 'مافی بڵاوکردنهوهی',
previewHtml : '<p>ئهمه وهك نموونهی <strong>دهقه</strong>. تۆ بهکاردههێنیت <a href="javascript:void(0)">CKEditor</a>.</p>'
}
};
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
config.uiColor = '#f7f5f4';
config.width = '';
config.removePlugins = 'elementspath,scayt';
config.disableNativeSpellChecker = false;
config.resize_dir = 'vertical';
config.keystrokes =[[ CKEDITOR.CTRL + 13 /*Enter*/, 'maximize' ]];
config.extraPlugins = 'capture,videoforpc';
config.enterMode = CKEDITOR.ENTER_BR;
config.shiftEnterMode = CKEDITOR.ENTER_P;
config.font_names='宋体/宋体;黑体/黑体;仿宋/仿宋_GB2312;楷体/楷体_GB2312;隶书/隶书;幼圆/幼圆;微软雅黑/微软雅黑;'+ config.font_names;
};
CKEDITOR.on( 'instanceReady', function( ev ){ with (ev.editor.dataProcessor.writer) { setRules("p", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); setRules("h1", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); setRules("h2", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); setRules("h3", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); setRules("h4", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); setRules("h5", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); setRules("div", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); setRules("table", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); setRules("tr", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); setRules("td", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); setRules("iframe", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); setRules("li", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); setRules("ul", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); setRules("ol", {indent : false, breakAfterOpen : false, breakBeforeClose : false} ); } });
//CKEDITOR.plugins.load('pgrfilemanager');
function insert_page(editorid)
{
var editor = CKEDITOR.instances[editorid];
editor.insertHtml('[page]');
if($('#paginationtype').val()) {
$('#paginationtype').val(2);
$('#paginationtype').css("color","red");
}
}
function insert_page_title(editorid,insertdata)
{
if(insertdata)
{
var editor = CKEDITOR.instances[editorid];
var data = editor.getData();
var page_title_value = $("#page_title_value").val();
if(page_title_value=='')
{
$("#msg_page_title_value").html("<font color='red'>请输入子标题</font>");
return false;
}
page_title_value = '[page]'+page_title_value+'[/page]';
editor.insertHtml(page_title_value);
$("#page_title_value").val('');
$("#msg_page_title_value").html('');
if($('#paginationtype').val()) {
$('#paginationtype').val(2);
$('#paginationtype').css("color","red");
}
}
else
{
$("#page_title_div").slideDown("fast");
}
}
var objid = MM_objid = key = 0;
function file_list(fn,url,obj) {
$('#MM_file_list_editor1').append('<div id="MM_file_list_'+fn+'">'+url+' <a href=\'#\' onMouseOver=\'javascript:FilePreview("'+url+'", 1);\' onMouseout=\'javascript:FilePreview("", 0);\'>查看</a> | <a href="javascript:insertHTMLToEditor(\'<img src='+url+'>\',\''+fn+'\')">插入</A> | <a href="javascript:del_file(\''+fn+'\',\''+url+'\','+fn+')">删除</a><br>');
}
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','nl',{placeholder:{title:'Eigenschappen placeholder',toolbar:'Placeholder aanmaken',text:'Placeholder tekst',edit:'Placeholder wijzigen',textMissing:'De placeholder moet tekst bevatten.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','ug',{placeholder:{title:'ئورۇن بەلگە خاسلىقى',toolbar:'ئورۇن بەلگە قۇر',text:'ئورۇن بەلگە تېكىستى',edit:'ئورۇن بەلگە تەھرىر',textMissing:'ئورۇن بەلگىسىدە چوقۇم تېكىست بولۇشى لازىم'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','it',{placeholder:{title:'Proprietà segnaposto',toolbar:'Crea segnaposto',text:'Testo segnaposto',edit:'Modifica segnaposto',textMissing:'Il segnaposto deve contenere del testo.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','de',{placeholder:{title:'Platzhalter Einstellungen',toolbar:'Platzhalter erstellen',text:'Platzhalter Text',edit:'Platzhalter bearbeiten',textMissing:'Der Platzhalter muss einen Text beinhalten.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','pl',{placeholder:{title:'Właściwości wypełniacza',toolbar:'Utwórz wypełniacz',text:'Tekst wypełnienia',edit:'Edytuj wypełnienie',textMissing:'Wypełnienie musi posiadać jakiś tekst.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','vi',{placeholder:{title:'Thuộc tính đặt chỗ',toolbar:'Tạo đặt chỗ',text:'Văn bản đặt chỗ',edit:'Chỉnh sửa ',textMissing:'The placeholder must contain text.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','hr',{placeholder:{title:'Svojstva rezerviranog mjesta',toolbar:'Napravi rezervirano mjesto',text:'Tekst rezerviranog mjesta',edit:'Uredi rezervirano mjesto',textMissing:'Rezervirano mjesto mora sadržavati tekst.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','tr',{placeholder:{title:'Yer tutucu özellikleri',toolbar:'Yer tutucu oluşturun',text:'Yer tutucu metini',edit:'Yer tutucuyu düzenle',textMissing:'Yer tutucu metin içermelidir.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','fr',{placeholder:{title:"Propriétés de l'Espace réservé",toolbar:"Créer l'Espace réservé",text:"Texte de l'Espace réservé",edit:"Modifier l'Espace réservé",textMissing:"L'Espace réservé doit contenir du texte."}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','zh-cn',{placeholder:{title:'占位符属性',toolbar:'创建占位符',text:'占位符文字',edit:'编辑占位符',textMissing:'占位符必须包含文字。'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','eo',{placeholder:{title:'Atributoj de la rezervita spaco',toolbar:'Krei la rezervitan spacon',text:'Texto de la rezervita spaco',edit:'Modifi la rezervitan spacon',textMissing:'La rezervita spaco devas enteni tekston.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','sk',{placeholder:{title:'Vlastnosti placeholdera',toolbar:'Vytvoriť placeholder',text:'Text placeholdera',edit:'Upraviť placeholder',textMissing:'Placeholder musí obsahovať text.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','en',{placeholder:{title:'Placeholder Properties',toolbar:'Create Placeholder',text:'Placeholder Text',edit:'Edit Placeholder',textMissing:'The placeholder must contain text.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','da',{placeholder:{title:'Egenskaber for pladsholder',toolbar:'Opret pladsholder',text:'Tekst til pladsholder',edit:'Redigér pladsholder',textMissing:'Pladsholder skal indeholde tekst'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','nb',{placeholder:{title:'Egenskaper for plassholder',toolbar:'Opprett plassholder',text:'Tekst for plassholder',edit:'Rediger plassholder',textMissing:'Plassholderen må inneholde tekst.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','bg',{placeholder:{title:'Настройки на контейнера',toolbar:'Нов контейнер',text:'Текст за контейнера',edit:'Промяна на контейнер',textMissing:'Контейнера трябва да съдържа текст.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','el',{placeholder:{title:'Ιδιότητες Υποκατάστατου Κειμένου',toolbar:'Δημιουργία Υποκατάσταστου Κειμένου',text:'Υποκαθιστόμενο Κείμενο',edit:'Επεξεργασία Υποκατάσταστου Κειμένου',textMissing:'Πρέπει να υπάρχει υποκαθιστόμενο κείμενο.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','fi',{placeholder:{title:'Paikkamerkin ominaisuudet',toolbar:'Luo paikkamerkki',text:'Paikkamerkin teksti',edit:'Muokkaa paikkamerkkiä',textMissing:'Paikkamerkin täytyy sisältää tekstiä'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','cy',{placeholder:{title:"Priodweddau'r Daliwr Geiriau",toolbar:'Creu Daliwr Geiriau',text:'Testun y Daliwr Geiriau',edit:"Golygu'r Dailwr Geiriau",textMissing:"Mae'n rhaid i'r daliwr geiriau gynnwys testun."}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','no',{placeholder:{title:'Egenskaper for plassholder',toolbar:'Opprett plassholder',text:'Tekst for plassholder',edit:'Rediger plassholder',textMissing:'Plassholderen må inneholde tekst.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'placeholder', 'fa',
{
placeholder :
{
title : 'ویژگیهای محل نگهداری',
toolbar : 'ایجاد یک محل نگهداری',
text : 'متن محل نگهداری',
edit : 'ویرایش محل نگهداری',
textMissing : 'محل نگهداری باید محتوی متن باشد.'
}
});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','et',{placeholder:{title:'Kohahoidja omadused',toolbar:'Kohahoidja loomine',text:'Kohahoidja tekst',edit:'Kohahoidja muutmine',textMissing:'Kohahoidja peab sisaldama teksti.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','he',{placeholder:{title:'מאפייני שומר מקום',toolbar:'צור שומר מקום',text:'תוכן שומר המקום',edit:'ערוך שומר מקום',textMissing:'שומר המקום חייב להכיל טקסט.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','uk',{placeholder:{title:'Налаштування Заповнювача',toolbar:'Створити Заповнювач',text:'Текст Заповнювача',edit:'Редагувати Заповнювач',textMissing:'Заповнювач повинен містити текст.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','cs',{placeholder:{title:'Vlastnosti vyhrazeného prostoru',toolbar:'Vytvořit vyhrazený prostor',text:'Vyhrazený text',edit:'Upravit vyhrazený prostor',textMissing:'Vyhrazený prostor musí obsahovat text.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'placeholder', 'ku',
{
placeholder :
{
title : 'خاسیهتی شوێن ههڵگر',
toolbar : 'درووستکردنی شوێن ههڵگر',
text : 'دهق بۆ شوێن ههڵگڕ',
edit : 'چاکسازی شوێن ههڵگڕ',
textMissing : 'شوێن ههڵگڕ دهبێت لهدهق پێکهاتبێت.'
}
});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','pt-br',{placeholder:{title:'Propriedades do Espaço Reservado',toolbar:'Criar Espaço Reservado',text:'Texto do Espaço Reservado',edit:'Editar Espaço Reservado',textMissing:'O espaço reservado deve conter texto.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('capture','zh-cn',{capture:{title:'PHPCMS在线截图',notice:'PHPCMS在线截图控件安装',notice_tips:'<p id="Capture">你还没有安装截图插件!<br />请使用 <a href="http://www.phpcms.cn/capture/" id="CaptureDownWeb" target="_blank">在线安装</a><font>(荐)</font> 或者 <a href="http://www.phpcms.cn/capture/capture.exe" id="CaptureDown" target="_blank">立即下载</a> 方式来安装插件。</p>',unsport_tips:'对不起,本功能暂时只支持IE浏览器'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','nl',{uicolor:{title:'UI Kleurenkiezer',preview:'Live voorbeeld',config:'Plak deze tekst in jouw config.js bestand',predefined:'Voorgedefinieerde kleurensets'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','ug',{uicolor:{title:'ئىشلەتكۈچى ئارايۈزى رەڭ تاللىغۇچ',preview:'شۇئان ئالدىن كۆزىتىش',config:'بۇ ھەرپ تىزىقىنى config.js ھۆججەتكە چاپلايدۇ',predefined:'ئالدىن بەلگىلەنگەن رەڭلەر'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','it',{uicolor:{title:'Selettore Colore UI',preview:'Anteprima Live',config:'Incolla questa stringa nel tuo file config.js',predefined:'Set di colori predefiniti'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','de',{uicolor:{title:'UI Pipette',preview:'Live-Vorschau',config:"Fügen Sie diese Zeichenfolge in die 'config.js' Datei.",predefined:'Vordefinierte Farbsätze'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','pl',{uicolor:{title:'Wybór koloru interfejsu',preview:'Podgląd na żywo',config:'Wklej poniższy łańcuch znaków do pliku config.js:',predefined:'Predefiniowane zestawy kolorów'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','vi',{uicolor:{title:'Giao diện người dùng Color Picker',preview:'Xem trước trực tiếp',config:'Dán chuỗi này vào tập tin config.js của bạn',predefined:'Tập màu định nghĩa sẵn'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','hr',{uicolor:{title:'UI odabir boja',preview:'Pregled uživo',config:'Zalijepite ovaj tekst u Vašu config.js datoteku.',predefined:'Već postavljeni setovi boja'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','tr',{uicolor:{title:'UI Renk Seçicisi',preview:'Canlı önizleme',config:'Bu dizeyi config.js dosyasının içine yapıştırın',predefined:'Önceden tanımlanmış renk kümeleri'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','fr',{uicolor:{title:'UI Sélecteur de couleur',preview:'Aperçu',config:'Collez cette chaîne de caractères dans votre fichier config.js',predefined:'Palettes de couleurs prédéfinies'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','zh-cn',{uicolor:{title:'用户界面颜色选择器',preview:'即时预览',config:'粘贴此字符串到您的 config.js 文件',predefined:'预定义颜色集'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','eo',{uicolor:{title:'UI Kolorselektilo',preview:'Vidigi la aspekton',config:'Gluu tiun signoĉenon en vian dosieron config.js',predefined:'Antaŭdifinita koloraro'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','sk',{uicolor:{title:'UI výber farby',preview:'Živý náhľad',config:'Vložte tento reťazec do vášho config.js súboru',predefined:'Preddefinované sady farieb'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','da',{uicolor:{title:'Brugerflade på farvevælger',preview:'Vis liveeksempel',config:'Indsæt denne streng i din config.js fil',predefined:'Prædefinerede farveskemaer'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','nb',{uicolor:{title:'Fargevelger for brukergrensesnitt',preview:'Forhåndsvisning i sanntid',config:'Lim inn følgende tekst i din config.js-fil',predefined:'Forhåndsdefinerte fargesett'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','bg',{uicolor:{title:'ПИ избор на цвят',preview:'Преглед',config:'Вмъкнете този низ във Вашия config.js fajl',predefined:'Предефинирани цветови палитри'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','el',{uicolor:{title:'Διεπαφή Επιλογέα Χρωμάτων',preview:'Ζωντανή Προεπισκόπηση',config:'Επικολλήστε αυτό το κείμενο στο αρχείο config.js',predefined:'Προκαθορισμένα σύνολα χρωμάτων'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','fi',{uicolor:{title:'Käyttöliittymän värivalitsin',preview:'Esikatsele',config:'Liitä tämä merkkijono config.js tiedostoosi',predefined:'Esimääritellyt värijoukot'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','cy',{uicolor:{title:"Dewisydd Lliwiau'r UI",preview:'Rhagolwg Byw',config:"Gludwch y llinyn hwn i'ch ffeil config.js",predefined:"Setiau lliw wedi'u cyn-ddiffinio"}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','no',{uicolor:{title:'Fargevelger for brukergrensesnitt',preview:'Forhåndsvisning i sanntid',config:'Lim inn følgende tekst i din config.js-fil',predefined:'Forhåndsdefinerte fargesett'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','mk',{uicolor:{title:'Палета со бои',preview:'Преглед',config:'Залепи го овој текст во config.js датотеката',predefined:'Предефинирани множества на бои'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'fa',
{
uicolor :
{
title : 'انتخاب رنگ UI',
preview : 'پیشنمایش زنده',
config : 'این رشته را در فایل config.js خود بچسبانید.',
predefined : 'مجموعه رنگ از پیش تعریف شده'
}
});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','et',{uicolor:{title:'Värvivalija kasutajaliides',preview:'Automaatne eelvaade',config:'Aseta see sõne oma config.js faili.',predefined:'Eelmääratud värvikomplektid'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','uk',{uicolor:{title:'Color Picker Інтерфейс',preview:'Перегляд наживо',config:'Вставте цей рядок у файл config.js',predefined:'Стандартний набір кольорів'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','cs',{uicolor:{title:'Výběr barvy rozhraní',preview:'Živý náhled',config:'Vložte tento řetězec do Vašeho souboru config.js',predefined:'Přednastavené sady barev'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'ku',
{
uicolor :
{
title : 'ههڵگری ڕهنگ بۆ ڕووکاری بهکارهێنهر',
preview : 'پێشبینین به زیندوویی',
config : 'ئهم دهقانه بلکێنه به پهڕگهی config.js-fil',
predefined : 'کۆمهڵه ڕهنگه دیاریکراوهکانی پێشوو'
}
});
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.