<!DOCTYPE html>
<html>
<head>
<!-- jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js" type="text/javascript"></script>
<!-- Wijmo CSS and script -->
<link href="http://cdn.wijmo.com/themes/metro/jquery-wijmo.css" rel="stylesheet" title="metro-jqueryui" type="text/css" />
<link href="http://cdn.wijmo.com/jquery.wijmo-pro.all.3.20132.9.min.css" rel="stylesheet" type="text/css" />
<!--<script src="http://cdn.wijmo.com/jquery.wijmo-open.all.3.20132.9.min.js" type="text/javascript"></script>-->
<script src="wijmo-open.js"></script>
<!--<script src="http://cdn.wijmo.com/jquery.wijmo-pro.all.3.20132.9.min.js" type="text/javascript"></script>-->
<script src="wijmo-pro.js"></script>
<!-- Angular (after jQuery) -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>
<!--<script src="http://cdn.wijmo.com/interop/angular.wijmo.3.20132.9.js"></script>-->
<script src="angular-wijmo.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="myCtrl">
<h1>AngularJS + wijmo</h1>
<form name="testForm">
<h2>Date picker</h2>
<div>
<input type="text" id="calendar"></div>
<wij-inputdate name="birthDate" id="birthDate" date-format="dd/MM/yyyy" min-date="model.minDate" max-date="model.maxDate"
show-trigger="true" dateChanged="dateChanged" date="model.selectedDate"></wij-inputdate>
<span data-ng-show="testForm.birthDate.$error.required" class="help-inline">*</span>
</div>
<h2>Numeric box</h2>
<div>
<p>
<input type="number" step="1" ng-model="model.min" />
<br/>
<input type="number" step="1" ng-model="model.max" />
<br/>
<input type="number" step="1" max="{{model.max}}" min="{{model.min}}" ng-model="model.val" />
</p>
<!-- no readonly by properties, only by method -->
<wij-inputnumber min-value="{{model.min}}" max-value="{{model.max}}" increment="1" value="model.val" show-spinner="true"></wij-inputnumeric>
<span data-ng-show="testForm.val.$error.required" class="help-inline">*</span>
</div>
<div>selected date:{{model.selectedDate}}</div>
<div>selected val:{{model.val}}</div>
<button ng-click="setToday()">Today</button>
<button data-ng-click="reset()">reset</button>
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
$("#calendar").wijinputdate({
minDate: new Date("2013-08-01T00:00:00.000Z"),
maxDate: new Date("2013-08-31T00:00:00.000Z"),
dateFormat:"dd/MM/yyyy",
showTrigger:true
});
});
</script>
// Code goes here
var app = angular.module('app', ['wijmo']);
app.controller("myCtrl",['$scope','$log', function ($scope,$log) {
$scope.model={};
$scope.model.selectedDate=new Date();
$scope.model.minDate="08/01/13";//new Date("2013-08-01T00:00:00.000Z");
$scope.model.maxDate="08/31/13";//new Date("2013-08-31T00:00:00.000Z");
$scope.model.max=10;
$scope.model.min=1;
$scope.model.val=5;
$scope.dateChanged=function(e, data){
$log.info('date changed');
$log.info(data);
}
$scope.setToday=function(){
$scope.model.selectedDate=new Date();
$log.info('date changed to '+ $scope.model.selectedDate);
}
$scope.reset=function(){
$scope.model.selectedDate=new Date("2013-07-18T00:00:00.000Z");
$scope.model.max=10;
$scope.model.min=1;
$scope.model.val=5;
}
}]);
/* Styles go here */
/*!
* Globalize
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function(z,y){var a,x,t,s,w,c,j,r,k,v,p,e,b,q,f,h,m,n,u,l,g,i,o,d;a=function(b){return new a.prototype.init(b)};if(typeof require!=="undefined"&&typeof exports!=="undefined"&&typeof module!=="undefined")module.exports=a;else z.Globalize=a;a.cultures={};a.prototype={constructor:a,init:function(b){this.cultures=a.cultures;this.cultureSelector=b;return this}};a.prototype.init.prototype=a.prototype;a.cultures["default"]={name:"en",englishName:"English",nativeName:"English",isRTL:false,language:"en",numberFormat:{pattern:["-n"],decimals:2,",":",",".":".",groupSizes:[3],"+":"+","-":"-",NaN:"NaN",negativeInfinity:"-Infinity",positiveInfinity:"Infinity",percent:{pattern:["-n %","n %"],decimals:2,groupSizes:[3],",":",",".":".",symbol:"%"},currency:{pattern:["($n)","$n"],decimals:2,groupSizes:[3],",":",",".":".",symbol:"$"}},calendars:{standard:{name:"Gregorian_USEnglish","/":"/",":":":",firstDay:0,days:{names:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],namesAbbr:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],namesShort:["Su","Mo","Tu","We","Th","Fr","Sa"]},months:{names:["January","February","March","April","May","June","July","August","September","October","November","December",""],namesAbbr:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""]},AM:["AM","am","AM"],PM:["PM","pm","PM"],eras:[{name:"A.D.",start:null,offset:0}],twoDigitYearMax:2029,patterns:{d:"M/d/yyyy",D:"dddd, MMMM dd, yyyy",t:"h:mm tt",T:"h:mm:ss tt",f:"dddd, MMMM dd, yyyy h:mm tt",F:"dddd, MMMM dd, yyyy h:mm:ss tt",M:"MMMM dd",Y:"yyyy MMMM",S:"yyyy'-'MM'-'dd'T'HH':'mm':'ss"}}},messages:{}};a.cultures["default"].calendar=a.cultures["default"].calendars.standard;a.cultures.en=a.cultures["default"];a.cultureSelector="en";x=/^0x[a-f0-9]+$/i;t=/^[+-]?infinity$/i;s=/^[+-]?\d*\.?\d*(e[+-]?\d+)?$/;w=/^\s+|\s+$/g;c=function(a,c){if(a.indexOf)return a.indexOf(c);for(var b=0,d=a.length;b<d;b++)if(a[b]===c)return b;return-1};j=function(b,a){return b.substr(b.length-a.length)===a};r=function(i){var g,d,c,b,f,h,a=arguments[0]||{},e=1,j=arguments.length,i=false;if(typeof a==="boolean"){i=a;a=arguments[1]||{};e=2}if(typeof a!=="object"&&!v(a))a={};for(;e<j;e++)if((g=arguments[e])!=null)for(d in g){c=a[d];b=g[d];if(a===b)continue;if(i&&b&&(p(b)||(f=k(b)))){if(f){f=false;h=c&&k(c)?c:[]}else h=c&&p(c)?c:{};a[d]=r(i,h,b)}else if(b!==y)a[d]=b}return a};k=Array.isArray||function(a){return Object.prototype.toString.call(a)==="[object Array]"};v=function(a){return Object.prototype.toString.call(a)==="[object Function]"};p=function(a){return Object.prototype.toString.call(a)==="[object Object]"};e=function(b,a){return b.indexOf(a)===0};b=function(a){return(a+"").replace(w,"")};q=function(a){return isNaN(a)?NaN:a|0};f=function(a,c,d){for(var b=a.length;b<c;b+=1)a=d?"0"+a:a+"0";return a};h=function(e,b){for(var d=0,a=false,c=0,g=e.length;c<g;c++){var f=e.charAt(c);switch(f){case"'":if(a)b.push("'");else d++;a=false;break;case"\\":a&&b.push("\\");a=!a;break;default:b.push(f);a=false}}return d};m=function(e,a){a=a||"F";var b,d=e.patterns,c=a.length;if(c===1){b=d[a];if(!b)throw"Invalid date format string '"+a+"'.";a=b}else if(c===2&&a.charAt(0)==="%")a=a.charAt(1);return a};n=function(b,f,r){var c=r.calendar,s=c.convert;if(!f||!f.length||f==="i"){var a;if(r&&r.name.length)if(s)a=n(b,c.patterns.F,r);else{var z=new Date(b.getTime()),H=g(b,c.eras);z.setFullYear(i(b,c,H));a=z.toLocaleString()}else a=b.toString();return a}var A=c.eras,y=f==="s";f=m(c,f);a=[];var j,G=["0","00","000"],p,w,B=/([^d]|^)(d|dd)([^d]|$)/g,x=0,v=l(),o;function e(d,a){var b,c=d+"";if(a>1&&c.length<a){b=G[a-2]+c;return b.substr(b.length-a,a)}else b=c;return b}function D(){if(p||w)return p;p=B.test(f);w=true;return p}function u(a,b){if(o)return o[b];switch(b){case 0:return a.getFullYear();case 1:return a.getMonth();case 2:return a.getDate()}}if(!y&&s)o=s.fromGregorian(b);for(;;){var E=v.lastIndex,q=v.exec(f),C=f.slice(E,q?q.index:f.length);x+=h(C,a);if(!q)break;if(x%2){a.push(q[0]);continue}var t=q[0],d=t.length;switch(t){case"ddd":case"dddd":var F=d===3?c.days.namesAbbr:c.days.names;a.push(F[b.getDay()]);break;case"d":case"dd":p=true;a.push(e(u(b,2),d));break;case"MMM":case"MMMM":var k=u(b,1);a.push(c.monthsGenitive&&D()?c.monthsGenitive[d===3?"namesAbbr":"names"][k]:c.months[d===3?"namesAbbr":"names"][k]);break;case"M":case"MM":a.push(e(u(b,1)+1,d));break;case"y":case"yy":case"yyyy":k=o?o[0]:i(b,c,g(b,A),y);if(d<4)k=k%100;a.push(e(k,d));break;case"h":case"hh":j=b.getHours()%12;if(j===0)j=12;a.push(e(j,d));break;case"H":case"HH":a.push(e(b.getHours(),d));break;case"m":case"mm":a.push(e(b.getMinutes(),d));break;case"s":case"ss":a.push(e(b.getSeconds(),d));break;case"t":case"tt":k=b.getHours()<12?c.AM?c.AM[0]:" ":c.PM?c.PM[0]:" ";a.push(d===1?k.charAt(0):k);break;case"f":case"ff":case"fff":a.push(e(b.getMilliseconds(),3).substr(0,d));break;case"z":case"zz":j=b.getTimezoneOffset()/60;a.push((j<=0?"+":"-")+e(Math.floor(Math.abs(j)),d));break;case"zzz":j=b.getTimezoneOffset()/60;a.push((j<=0?"+":"-")+e(Math.floor(Math.abs(j)),2)+":"+e(Math.abs(b.getTimezoneOffset()%60),2));break;case"g":case"gg":c.eras&&a.push(c.eras[g(b,A)].name);break;case"/":a.push(c["/"]);break;default:throw"Invalid date format pattern '"+t+"'.";}}return a.join("")};(function(){var a;a=function(j,h,l){var m=l.groupSizes,i=m[0],k=1,p=Math.pow(10,h),n=Math.round(j*p)/p;if(!isFinite(n))n=j;j=n;var b=j+"",a="",e=b.split(/e/i),c=e.length>1?parseInt(e[1],10):0;b=e[0];e=b.split(".");b=e[0];a=e.length>1?e[1]:"";var q;if(c>0){a=f(a,c,false);b+=a.slice(0,c);a=a.substr(c)}else if(c<0){c=-c;b=f(b,c+1);a=b.slice(-c,b.length)+a;b=b.slice(0,-c)}if(h>0)a=l["."]+(a.length>h?a.slice(0,h):f(a,h));else a="";var d=b.length-1,o=l[","],g="";while(d>=0){if(i===0||i>d)return b.slice(0,d+1)+(g.length?o+g+a:a);g=b.slice(d-i+1,d+1)+(g.length?o+g:"");d-=i;if(k<m.length){i=m[k];k++}}return b.slice(0,d+1)+o+g+a};u=function(d,e,j){if(!isFinite(d))return d===Infinity?j.numberFormat.positiveInfinity:d===-Infinity?j.numberFormat.negativeInfinity:j.numberFormat.NaN;if(!e||e==="i")return j.name.length?d.toLocaleString():d.toString();e=e||"D";var i=j.numberFormat,b=Math.abs(d),g=-1,k;if(e.length>1)g=parseInt(e.slice(1),10);var m=e.charAt(0).toUpperCase(),c;switch(m){case"D":k="n";b=q(b);if(g!==-1)b=f(""+b,g,true);if(d<0)b="-"+b;break;case"N":c=i;case"C":c=c||i.currency;case"P":c=c||i.percent;k=d<0?c.pattern[0]:c.pattern[1]||"n";if(g===-1)g=c.decimals;b=a(b*(m==="P"?100:1),g,c);break;default:throw"Bad number format specifier: "+m;}for(var n=/n|\$|-|%/g,h="";;){var o=n.lastIndex,l=n.exec(k);h+=k.slice(o,l?l.index:k.length);if(!l)break;switch(l[0]){case"n":h+=b;break;case"$":h+=i.currency.symbol;break;case"-":if(/[1-9]/.test(b))h+=i["-"];break;case"%":h+=i.percent.symbol}}return h}})();l=function(){return/\/|dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z|gg|g/g};g=function(e,c){if(!c)return 0;for(var b,d=e.getTime(),a=0,f=c.length;a<f;a++){b=c[a].start;if(b===null||d>=b)return a}return 0};i=function(d,b,e,c){var a=d.getFullYear();if(!c&&b.eras)a-=b.eras[e].offset;return a};(function(){var p,n,k,j,a,f,d;p=function(d,b){if(b<100){var e=new Date,f=g(e),c=i(e,d,f),a=d.twoDigitYearMax;a=typeof a==="string"?(new Date).getFullYear()%100+parseInt(a,10):a;b+=c-c%100;if(b>a)b-=100}return b};n=function(h,b,i){var e,g=h.days,a=h._upperDays;if(!a)h._upperDays=a=[d(g.names),d(g.namesAbbr),d(g.namesShort)];b=f(b);if(i){e=c(a[1],b);if(e===-1)e=c(a[2],b)}else e=c(a[0],b);return e};k=function(a,e,k){var j=a.months,i=a.monthsGenitive||a.months,b=a._upperMonths,g=a._upperMonthsGen;if(!b){a._upperMonths=b=[d(j.names),d(j.namesAbbr)];a._upperMonthsGen=g=[d(i.names),d(i.namesAbbr)]}e=f(e);var h=c(k?b[1]:b[0],e);if(h<0)h=c(k?g[1]:g[0],e);return h};j=function(d,g){var e=d._parseRegExp;if(!e)d._parseRegExp=e={};else{var o=e[g];if(o)return o}var f=m(d,g).replace(/([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g,"\\\\$1"),b=["^"],p=[],i=0,n=0,k=l(),c;while((c=k.exec(f))!==null){var s=f.slice(i,c.index);i=k.lastIndex;n+=h(s,b);if(n%2){b.push(c[0]);continue}var j=c[0],t=j.length,a;switch(j){case"dddd":case"ddd":case"MMMM":case"MMM":case"gg":case"g":a="(\\D+)";break;case"tt":case"t":a="(\\D*)";break;case"yyyy":case"fff":case"ff":case"f":a="(\\d{"+t+"})";break;case"dd":case"d":case"MM":case"M":case"yy":case"y":case"HH":case"H":case"hh":case"h":case"mm":case"m":case"ss":case"s":a="(\\d\\d?)";break;case"zzz":a="([+-]?\\d\\d?:\\d{2})";break;case"zz":case"z":a="([+-]?\\d\\d?)";break;case"/":a="(\\"+d["/"]+")";break;default:throw"Invalid date format pattern '"+j+"'.";}a&&b.push(a);p.push(c[0])}h(f.slice(i),b);b.push("$");var r=b.join("").replace(/\s+/g,"\\s+"),q={regExp:r,groups:p};return e[g]=q};a=function(a,c,b){return a<c||a>b};f=function(a){return a.split("\u00a0").join(" ").toUpperCase()};d=function(c){for(var b=[],a=0,d=c.length;a<d;a++)b[a]=f(c[a]);return b};o=function(A,M,L){A=b(A);var c=L.calendar,H=j(c,M),K=new RegExp(H.regExp).exec(A);if(K===null)return null;for(var J=H.groups,C=null,m=null,i=null,l=null,u=null,h=0,o,D=0,E=0,B=0,q=null,z=false,w=0,N=J.length;w<N;w++){var d=K[w+1];if(d){var I=J[w],r=I.length,g=parseInt(d,10);switch(I){case"dd":case"d":l=g;if(a(l,1,31))return null;break;case"MMM":case"MMMM":i=k(c,d,r===3);if(a(i,0,11))return null;break;case"M":case"MM":i=g-1;if(a(i,0,11))return null;break;case"y":case"yy":case"yyyy":m=r<4?p(c,g):g;if(a(m,0,9999))return null;break;case"h":case"hh":h=g;if(h===12)h=0;if(a(h,0,11))return null;break;case"H":case"HH":h=g;if(a(h,0,23))return null;break;case"m":case"mm":D=g;if(a(D,0,59))return null;break;case"s":case"ss":E=g;if(a(E,0,59))return null;break;case"tt":case"t":z=c.PM&&(d===c.PM[0]||d===c.PM[1]||d===c.PM[2]);if(!z&&(!c.AM||d!==c.AM[0]&&d!==c.AM[1]&&d!==c.AM[2]))return null;break;case"f":case"ff":case"fff":B=g*Math.pow(10,3-r);if(a(B,0,999))return null;break;case"ddd":case"dddd":u=n(c,d,r===3);if(a(u,0,6))return null;break;case"zzz":var y=d.split(/:/);if(y.length!==2)return null;o=parseInt(y[0],10);if(a(o,-12,13))return null;var x=parseInt(y[1],10);if(a(x,0,59))return null;q=o*60+(e(d,"-")?-x:x);break;case"z":case"zz":o=g;if(a(o,-12,13))return null;q=o*60;break;case"g":case"gg":var t=d;if(!t||!c.eras)return null;t=b(t.toLowerCase());for(var v=0,O=c.eras.length;v<O;v++)if(t===c.eras[v].name.toLowerCase()){C=v;break}if(C===null)return null}}}var f=new Date,G,s=c.convert;G=s?s.fromGregorian(f)[0]:f.getFullYear();if(m===null)m=G;else if(c.eras)m+=c.eras[C||0].offset;if(i===null)i=0;if(l===null)l=1;if(s){f=s.toGregorian(m,i,l);if(f===null)return null}else{f.setFullYear(m,i,l);if(f.getDate()!==l)return null;if(u!==null&&f.getDay()!==u)return null}if(z&&h<12)h+=12;f.setHours(h,D,E,B);if(q!==null){var F=f.getMinutes()-(q+f.getTimezoneOffset());f.setHours(f.getHours()+parseInt(F/60,10),F%60)}return f}})();d=function(a,f,g){var b=f["-"],c=f["+"],d;switch(g){case"n -":b=" "+b;c=" "+c;case"n-":if(j(a,b))d=["-",a.substr(0,a.length-b.length)];else if(j(a,c))d=["+",a.substr(0,a.length-c.length)];break;case"- n":b+=" ";c+=" ";case"-n":if(e(a,b))d=["-",a.substr(b.length)];else if(e(a,c))d=["+",a.substr(c.length)];break;case"(n)":if(e(a,"(")&&j(a,")"))d=["-",a.substr(1,a.length-2)]}return d||["",a]};a.prototype.findClosestCulture=function(b){return a.findClosestCulture.call(this,b)};a.prototype.format=function(d,c,b){return a.format.call(this,d,c,b)};a.prototype.localize=function(c,b){return a.localize.call(this,c,b)};a.prototype.parseInt=function(d,c,b){return a.parseInt.call(this,d,c,b)};a.prototype.parseFloat=function(d,c,b){return a.parseFloat.call(this,d,c,b)};a.prototype.culture=function(b){return a.culture.call(this,b)};a.addCultureInfo=function(a,c,e){var b={},d=false;if(typeof a!=="string"){e=a;a=this.culture().name;b=this.cultures[a]}else if(typeof c!=="string"){e=c;d=this.cultures[a]==null;b=this.cultures[a]||this.cultures["default"]}else{d=true;b=this.cultures[c]}this.cultures[a]=r(true,{},b,e);if(d)this.cultures[a].calendar=this.cultures[a].calendars.standard};a.findClosestCulture=function(a){var e;if(!a)return this.cultures[this.cultureSelector]||this.cultures["default"];if(typeof a==="string")a=a.split(",");if(k(a)){for(var d,h=this.cultures,n=a,i=n.length,g=[],c=0;c<i;c++){a=b(n[c]);var f,j=a.split(";");d=b(j[0]);if(j.length===1)f=1;else{a=b(j[1]);if(a.indexOf("q=")===0){a=a.substr(2);f=parseFloat(a);f=isNaN(f)?0:f}else f=1}g.push({lang:d,pri:f})}g.sort(function(a,b){return a.pri<b.pri?1:-1});for(c=0;c<i;c++){d=g[c].lang;e=h[d];if(e)return e}for(c=0;c<i;c++){d=g[c].lang;do{var m=d.lastIndexOf("-");if(m===-1)break;d=d.substr(0,m);e=h[d];if(e)return e}while(1)}for(c=0;c<i;c++){d=g[c].lang;for(var o in h){var l=h[o];if(l.language==d)return l}}}else if(typeof a==="object")return a;return e||null};a.format=function(a,b,c){culture=this.findClosestCulture(c);if(a instanceof Date)a=n(a,b,culture);else if(typeof a==="number")a=u(a,b,culture);return a};a.localize=function(a,b){return this.findClosestCulture(b).messages[a]||this.cultures["default"].messages[a]};a.parseDate=function(g,a,b){b=this.findClosestCulture(b);var c,h,d;if(a){if(typeof a==="string")a=[a];if(a.length)for(var e=0,i=a.length;e<i;e++){var f=a[e];if(f){c=o(g,f,b);if(c)break}}}else{d=b.calendar.patterns;for(h in d){c=o(g,d[h],b);if(c)break}}return c||null};a.parseInt=function(d,c,b){return q(a.parseFloat(d,c,b))};a.parseFloat=function(a,n,u){if(typeof n!=="number"){u=n;n=10}var k=this.findClosestCulture(u),o=NaN,c=k.numberFormat;if(a.indexOf(k.numberFormat.currency.symbol)>-1){a=a.replace(k.numberFormat.currency.symbol,"");a=a.replace(k.numberFormat.currency["."],k.numberFormat["."])}a=b(a);if(t.test(a))o=parseFloat(a);else if(!n&&x.test(a))o=parseInt(a,16);else{var e=d(a,c,c.pattern[0]),g=e[0],h=e[1];if(g===""&&c.pattern[0]!=="(n)"){e=d(a,c,"(n)");g=e[0];h=e[1]}if(g===""&&c.pattern[0]!=="-n"){e=d(a,c,"-n");g=e[0];h=e[1]}g=g||"+";var l,i,j=h.indexOf("e");if(j<0)j=h.indexOf("E");if(j<0){i=h;l=null}else{i=h.substr(0,j);l=h.substr(j+1)}var f,m,y=c["."],q=i.indexOf(y);if(q<0){f=i;m=null}else{f=i.substr(0,q);m=i.substr(q+y.length)}var r=c[","];f=f.split(r).join("");var v=r.replace(/\u00A0/g," ");if(r!==v)f=f.split(v).join("");var p=g+f;if(m!==null)p+="."+m;if(l!==null){var w=d(l,c,"-n");p+="e"+(w[0]||"+")+w[1]}if(s.test(p))o=parseFloat(p)}return o};a.culture=function(a){if(typeof a!=="undefined")this.cultureSelector=a;return this.findClosestCulture(a)||this.culture["default"]}})(this);
/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Version 3.0.0
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
$.fn.bgiframe = function (s) {
s = $.extend({
top: 'auto', // auto == borderTopWidth
left: 'auto', // auto == borderLeftWidth
width: 'auto', // auto == offsetWidth
height: 'auto', // auto == offsetHeight
opacity: true,
src: 'javascript:false;',
conditional: /MSIE 6.0/.test(navigator.userAgent) // expresion or function. return false to prevent iframe insertion
}, s);
// wrap conditional in a function if it isn't already
if (!$.isFunction(s.conditional)) {
var condition = s.conditional;
s.conditional = function () { return condition; };
}
var $iframe = $('<iframe class="bgiframe"frameborder="0"tabindex="-1"src="' + s.src + '"' +
'style="display:block;position:absolute;z-index:-1;"/>');
return this.each(function () {
var $this = $(this);
if (s.conditional(this) === false) { return; }
var existing = $this.children('iframe.bgiframe');
var $el = existing.length === 0 ? $iframe.clone() : existing;
$el.css({
'top': s.top == 'auto' ?
((parseInt($this.css('borderTopWidth'), 10) || 0) * -1) + 'px' : prop(s.top),
'left': s.left == 'auto' ?
((parseInt($this.css('borderLeftWidth'), 10) || 0) * -1) + 'px' : prop(s.left),
'width': s.width == 'auto' ? (this.offsetWidth + 'px') : prop(s.width),
'height': s.height == 'auto' ? (this.offsetHeight + 'px') : prop(s.height),
'opacity': s.opacity === true ? 0 : undefined
});
if (existing.length === 0) {
$this.prepend($el);
}
});
};
// old alias
$.fn.bgIframe = $.fn.bgiframe;
function prop(n) {
return n && n.constructor === Number ? n + 'px' : n;
}
}));;
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.0.6
*
* Requires: 1.2.2+
*/
(function(a){function d(b){var c=b||window.event,d=[].slice.call(arguments,1),e=0,f=!0,g=0,h=0;return b=a.event.fix(c),b.type="mousewheel",c.wheelDelta&&(e=c.wheelDelta/120),c.detail&&(e=-c.detail/3),h=e,c.axis!==undefined&&c.axis===c.HORIZONTAL_AXIS&&(h=0,g=-1*e),c.wheelDeltaY!==undefined&&(h=c.wheelDeltaY/120),c.wheelDeltaX!==undefined&&(g=-1*c.wheelDeltaX/120),d.unshift(b,e,g,h),(a.event.dispatch||a.event.handle).apply(this,d)}var b=["DOMMouseScroll","mousewheel"];if(a.event.fixHooks)for(var c=b.length;c;)a.event.fixHooks[b[--c]]=a.event.mouseHooks;a.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=b.length;a;)this.addEventListener(b[--a],d,!1);else this.onmousewheel=d},teardown:function(){if(this.removeEventListener)for(var a=b.length;a;)this.removeEventListener(b[--a],d,!1);else this.onmousewheel=null}},a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery)
;
/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
* used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
// CAUTION: Needed to parenthesize options.path and options.domain
// in the following expressions, otherwise they evaluate to undefined
// in the packed version for some reason...
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};;
// ┌─────────────────────────────────────────────────────────────────────┐ \\
// │ Raphaël 2.0.1 - JavaScript Vector Library │ \\
// ├─────────────────────────────────────────────────────────────────────┤ \\
// │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\
// │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\
// │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
// └─────────────────────────────────────────────────────────────────────┘ \\
(function (a) { var b = "0.4.0", c = "hasOwnProperty", d = /[\.\/]/, e = "*", f = function () { }, g = function (a, b) { return a - b }, h, i, j = { n: {} }, k = function (a, b) { var c = j, d = i, e = Array.prototype.slice.call(arguments, 2), f = k.listeners(a), l = 0, m = !1, n, o = [], p = {}, q = [], r = []; h = a, i = 0; for (var s = 0, t = f.length; s < t; s++) "zIndex" in f[s] && (o.push(f[s].zIndex), f[s].zIndex < 0 && (p[f[s].zIndex] = f[s])); o.sort(g); while (o[l] < 0) { n = p[o[l++]], q.push(n.apply(b, e)); if (i) { i = d; return q } } for (s = 0; s < t; s++) { n = f[s]; if ("zIndex" in n) if (n.zIndex == o[l]) { q.push(n.apply(b, e)); if (i) { i = d; return q } do { l++, n = p[o[l]], n && q.push(n.apply(b, e)); if (i) { i = d; return q } } while (n) } else p[n.zIndex] = n; else { q.push(n.apply(b, e)); if (i) { i = d; return q } } } i = d; return q.length ? q : null }; k.listeners = function (a) { var b = a.split(d), c = j, f, g, h, i, k, l, m, n, o = [c], p = []; for (i = 0, k = b.length; i < k; i++) { n = []; for (l = 0, m = o.length; l < m; l++) { c = o[l].n, g = [c[b[i]], c[e]], h = 2; while (h--) f = g[h], f && (n.push(f), p = p.concat(f.f || [])) } o = n } return p }, k.on = function (a, b) { var c = a.split(d), e = j; for (var g = 0, h = c.length; g < h; g++) e = e.n, !e[c[g]] && (e[c[g]] = { n: {} }), e = e[c[g]]; e.f = e.f || []; for (g = 0, h = e.f.length; g < h; g++) if (e.f[g] == b) return f; e.f.push(b); return function (a) { +a == +a && (b.zIndex = +a) } }, k.stop = function () { i = 1 }, k.nt = function (a) { if (a) return (new RegExp("(?:\\.|\\/|^)" + a + "(?:\\.|\\/|$)")).test(h); return h }, k.unbind = function (a, b) { var f = a.split(d), g, h, i, k, l, m, n, o = [j]; for (k = 0, l = f.length; k < l; k++) for (m = 0; m < o.length; m += i.length - 2) { i = [m, 1], g = o[m].n; if (f[k] != e) g[f[k]] && i.push(g[f[k]]); else for (h in g) g[c](h) && i.push(g[h]); o.splice.apply(o, i) } for (k = 0, l = o.length; k < l; k++) { g = o[k]; while (g.n) { if (b) { if (g.f) { for (m = 0, n = g.f.length; m < n; m++) if (g.f[m] == b) { g.f.splice(m, 1); break } !g.f.length && delete g.f } for (h in g.n) if (g.n[c](h) && g.n[h].f) { var p = g.n[h].f; for (m = 0, n = p.length; m < n; m++) if (p[m] == b) { p.splice(m, 1); break } !p.length && delete g.n[h].f } } else { delete g.f; for (h in g.n) g.n[c](h) && g.n[h].f && delete g.n[h].f } g = g.n } } }, k.once = function (a, b) { var c = function () { b.apply(this, arguments), k.unbind(a, c) }; return k.on(a, c) }, k.version = b, k.toString = function () { return "You are running Eve " + b }, typeof module != "undefined" && module.exports ? module.exports = k : a.eve = k })(this), function () { function cr(b, d, e, f, h, i) { e = Q(e); var j, k, l, m = [], o, p, q, t = b.ms, u = {}, v = {}, w = {}; if (f) for (y = 0, z = cl.length; y < z; y++) { var x = cl[y]; if (x.el.id == d.id && x.anim == b) { x.percent != e ? (cl.splice(y, 1), l = 1) : k = x, d.attr(x.totalOrigin); break } } else f = +v; for (var y = 0, z = b.percents.length; y < z; y++) { if (b.percents[y] == e || b.percents[y] > f * b.top) { e = b.percents[y], p = b.percents[y - 1] || 0, t = t / b.top * (e - p), o = b.percents[y + 1], j = b.anim[e]; break } f && d.attr(b.anim[b.percents[y]]) } if (!!j) { if (!k) { for (var A in j) if (j[g](A)) if (U[g](A) || d.paper.customAttributes[g](A)) { u[A] = d.attr(A), u[A] == null && (u[A] = T[A]), v[A] = j[A]; switch (U[A]) { case C: w[A] = (v[A] - u[A]) / t; break; case "colour": u[A] = a.getRGB(u[A]); var B = a.getRGB(v[A]); w[A] = { r: (B.r - u[A].r) / t, g: (B.g - u[A].g) / t, b: (B.b - u[A].b) / t }; break; case "path": var D = bG(u[A], v[A]), E = D[1]; u[A] = D[0], w[A] = []; for (y = 0, z = u[A].length; y < z; y++) { w[A][y] = [0]; for (var F = 1, G = u[A][y].length; F < G; F++) w[A][y][F] = (E[y][F] - u[A][y][F]) / t } break; case "transform": var H = d._, I = bP(H[A], v[A]); if (I) { u[A] = I.from, v[A] = I.to, w[A] = [], w[A].real = !0; for (y = 0, z = u[A].length; y < z; y++) { w[A][y] = [u[A][y][0]]; for (F = 1, G = u[A][y].length; F < G; F++) w[A][y][F] = (v[A][y][F] - u[A][y][F]) / t } } else { var J = d.matrix || new bQ, K = { _: { transform: H.transform }, getBBox: function () { return d.getBBox(1) } }; u[A] = [J.a, J.b, J.c, J.d, J.e, J.f], bN(K, v[A]), v[A] = K._.transform, w[A] = [(K.matrix.a - J.a) / t, (K.matrix.b - J.b) / t, (K.matrix.c - J.c) / t, (K.matrix.d - J.d) / t, (K.matrix.e - J.e) / t, (K.matrix.e - J.f) / t] } break; case "csv": var L = r(j[A])[s](c), M = r(u[A])[s](c); if (A == "clip-rect") { u[A] = M, w[A] = [], y = M.length; while (y--) w[A][y] = (L[y] - u[A][y]) / t } v[A] = L; break; default: L = [][n](j[A]), M = [][n](u[A]), w[A] = [], y = d.paper.customAttributes[A].length; while (y--) w[A][y] = ((L[y] || 0) - (M[y] || 0)) / t } } var O = j.easing, P = a.easing_formulas[O]; if (!P) { P = r(O).match(N); if (P && P.length == 5) { var R = P; P = function (a) { return cp(a, +R[1], +R[2], +R[3], +R[4], t) } } else P = be } q = j.start || b.start || +(new Date), x = { anim: b, percent: e, timestamp: q, start: q + (b.del || 0), status: 0, initstatus: f || 0, stop: !1, ms: t, easing: P, from: u, diff: w, to: v, el: d, callback: j.callback, prev: p, next: o, repeat: i || b.times, origin: d.attr(), totalOrigin: h }, cl.push(x); if (f && !k && !l) { x.stop = !0, x.start = new Date - t * f; if (cl.length == 1) return cn() } l && (x.start = new Date - x.ms * f), cl.length == 1 && cm(cn) } else k.initstatus = f, k.start = new Date - k.ms * f; eve("anim.start." + d.id, d, b) } } function cq(a, b) { var c = [], d = {}; this.ms = b, this.times = 1; if (a) { for (var e in a) a[g](e) && (d[Q(e)] = a[e], c.push(Q(e))); c.sort(bc) } this.anim = d, this.top = c[c.length - 1], this.percents = c } function cp(a, b, c, d, e, f) { function o(a, b) { var c, d, e, f, j, k; for (e = a, k = 0; k < 8; k++) { f = m(e) - a; if (z(f) < b) return e; j = (3 * i * e + 2 * h) * e + g; if (z(j) < 1e-6) break; e = e - f / j } c = 0, d = 1, e = a; if (e < c) return c; if (e > d) return d; while (c < d) { f = m(e); if (z(f - a) < b) return e; a > f ? c = e : d = e, e = (d - c) / 2 + c } return e } function n(a, b) { var c = o(a, b); return ((l * c + k) * c + j) * c } function m(a) { return ((i * a + h) * a + g) * a } var g = 3 * b, h = 3 * (d - b) - g, i = 1 - g - h, j = 3 * c, k = 3 * (e - c) - j, l = 1 - j - k; return n(a, 1 / (200 * f)) } function cd() { return this.x + q + this.y + q + this.width + " × " + this.height } function cc() { return this.x + q + this.y } function bQ(a, b, c, d, e, f) { a != null ? (this.a = +a, this.b = +b, this.c = +c, this.d = +d, this.e = +e, this.f = +f) : (this.a = 1, this.b = 0, this.c = 0, this.d = 1, this.e = 0, this.f = 0) } function bw(a) { var b = []; for (var c = 0, d = a.length; d - 2 > c; c += 2) { var e = [{ x: +a[c], y: +a[c + 1] }, { x: +a[c], y: +a[c + 1] }, { x: +a[c + 2], y: +a[c + 3] }, { x: +a[c + 4], y: +a[c + 5]}]; d - 4 == c ? (e[0] = { x: +a[c - 2], y: +a[c - 1] }, e[3] = e[2]) : c && (e[0] = { x: +a[c - 2], y: +a[c - 1] }), b.push(["C", (-e[0].x + 6 * e[1].x + e[2].x) / 6, (-e[0].y + 6 * e[1].y + e[2].y) / 6, (e[1].x + 6 * e[2].x - e[3].x) / 6, (e[1].y + 6 * e[2].y - e[3].y) / 6, e[2].x, e[2].y]) } return b } function bv() { return this.hex } function bt(a, b, c) { function d() { var e = Array.prototype.slice.call(arguments, 0), f = e.join("␀"), h = d.cache = d.cache || {}, i = d.count = d.count || []; if (h[g](f)) { bs(i, f); return c ? c(h[f]) : h[f] } i.length >= 1e3 && delete h[i.shift()], i.push(f), h[f] = a[m](b, e); return c ? c(h[f]) : h[f] } return d } function bs(a, b) { for (var c = 0, d = a.length; c < d; c++) if (a[c] === b) return a.push(a.splice(c, 1)[0]) } function a(c) { if (a.is(c, "function")) return b ? c() : eve.on("DOMload", c); if (a.is(c, E)) return a._engine.create[m](a, c.splice(0, 3 + a.is(c[0], C))).add(c); var d = Array.prototype.slice.call(arguments, 0); if (a.is(d[d.length - 1], "function")) { var e = d.pop(); return b ? e.call(a._engine.create[m](a, d)) : eve.on("DOMload", function () { e.call(a._engine.create[m](a, d)) }) } return a._engine.create[m](a, arguments) } a.version = "2.0.1", a.eve = eve; var b, c = /[, ]+/, d = { circle: 1, rect: 1, path: 1, ellipse: 1, text: 1, image: 1 }, e = /\{(\d+)\}/g, f = "prototype", g = "hasOwnProperty", h = { doc: document, win: window }, i = { was: Object.prototype[g].call(h.win, "Raphael"), is: h.win.Raphael }, j = function () { this.ca = this.customAttributes = {} }, k, l = "appendChild", m = "apply", n = "concat", o = "createTouch" in h.doc, p = "", q = " ", r = String, s = "split", t = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel"[s](q), u = { mousedown: "touchstart", mousemove: "touchmove", mouseup: "touchend" }, v = r.prototype.toLowerCase, w = Math, x = w.max, y = w.min, z = w.abs, A = w.pow, B = w.PI, C = "number", D = "string", E = "array", F = "toString", G = "fill", H = Object.prototype.toString, I = {}, J = "push", K = a._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i, L = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i, M = { NaN: 1, Infinity: 1, "-Infinity": 1 }, N = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/, O = w.round, P = "setAttribute", Q = parseFloat, R = parseInt, S = r.prototype.toUpperCase, T = a._availableAttrs = { "arrow-end": "none", "arrow-start": "none", blur: 0, "clip-rect": "0 0 1e9 1e9", cursor: "default", cx: 0, cy: 0, fill: "#fff", "fill-opacity": 1, font: '10px "Arial"', "font-family": '"Arial"', "font-size": "10", "font-style": "normal", "font-weight": 400, gradient: 0, height: 0, href: "http://raphaeljs.com/", "letter-spacing": 0, opacity: 1, path: "M0,0", r: 0, rx: 0, ry: 0, src: "", stroke: "#000", "stroke-dasharray": "", "stroke-linecap": "butt", "stroke-linejoin": "butt", "stroke-miterlimit": 0, "stroke-opacity": 1, "stroke-width": 1, target: "_blank", "text-anchor": "middle", title: "Raphael", transform: "", width: 0, x: 0, y: 0 }, U = a._availableAnimAttrs = { blur: C, "clip-rect": "csv", cx: C, cy: C, fill: "colour", "fill-opacity": C, "font-size": C, height: C, opacity: C, path: "path", r: C, rx: C, ry: C, stroke: "colour", "stroke-opacity": C, "stroke-width": C, transform: "transform", width: C, x: C, y: C }, V = /\s*,\s*/, W = { hs: 1, rg: 1 }, X = /,?([achlmqrstvxz]),?/gi, Y = /([achlmrqstvz])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig, Z = /([rstm])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig, $ = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)\s*,?\s*/ig, _ = a._radial_gradient = /^r(?:\(([^,]+?)\s*,\s*([^\)]+?)\))?/, ba = {}, bb = function (a, b) { return a.key - b.key }, bc = function (a, b) { return Q(a) - Q(b) }, bd = function () { }, be = function (a) { return a }, bf = a._rectPath = function (a, b, c, d, e) { if (e) return [["M", a + e, b], ["l", c - e * 2, 0], ["a", e, e, 0, 0, 1, e, e], ["l", 0, d - e * 2], ["a", e, e, 0, 0, 1, -e, e], ["l", e * 2 - c, 0], ["a", e, e, 0, 0, 1, -e, -e], ["l", 0, e * 2 - d], ["a", e, e, 0, 0, 1, e, -e], ["z"]]; return [["M", a, b], ["l", c, 0], ["l", 0, d], ["l", -c, 0], ["z"]] }, bg = function (a, b, c, d) { d == null && (d = c); return [["M", a, b], ["m", 0, -d], ["a", c, d, 0, 1, 1, 0, 2 * d], ["a", c, d, 0, 1, 1, 0, -2 * d], ["z"]] }, bh = a._getPath = { path: function (a) { return a.attr("path") }, circle: function (a) { var b = a.attrs; return bg(b.cx, b.cy, b.r) }, ellipse: function (a) { var b = a.attrs; return bg(b.cx, b.cy, b.rx, b.ry) }, rect: function (a) { var b = a.attrs; return bf(b.x, b.y, b.width, b.height, b.r) }, image: function (a) { var b = a.attrs; return bf(b.x, b.y, b.width, b.height) }, text: function (a) { var b = a._getBBox(); return bf(b.x, b.y, b.width, b.height) } }, bi = a.mapPath = function (a, b) { if (!b) return a; var c, d, e, f, g, h, i; a = bG(a); for (e = 0, g = a.length; e < g; e++) { i = a[e]; for (f = 1, h = i.length; f < h; f += 2) c = b.x(i[f], i[f + 1]), d = b.y(i[f], i[f + 1]), i[f] = c, i[f + 1] = d } return a }; a._g = h, a.type = h.win.SVGAngle || h.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML"; if (a.type == "VML") { var bj = h.doc.createElement("div"), bk; bj.innerHTML = '<v:shape adj="1"/>', bk = bj.firstChild, bk.style.behavior = "url(#default#VML)"; if (!bk || typeof bk.adj != "object") return a.type = p; bj = null } a.svg = !(a.vml = a.type == "VML"), a._Paper = j, a.fn = k = j.prototype = a.prototype, a._id = 0, a._oid = 0, a.is = function (a, b) { b = v.call(b); if (b == "finite") return !M[g](+a); if (b == "array") return a instanceof Array; return b == "null" && a === null || b == typeof a && a !== null || b == "object" && a === Object(a) || b == "array" && Array.isArray && Array.isArray(a) || H.call(a).slice(8, -1).toLowerCase() == b }, a.angle = function (b, c, d, e, f, g) { if (f == null) { var h = b - d, i = c - e; if (!h && !i) return 0; return (180 + w.atan2(-i, -h) * 180 / B + 360) % 360 } return a.angle(b, c, f, g) - a.angle(d, e, f, g) }, a.rad = function (a) { return a % 360 * B / 180 }, a.deg = function (a) { return a * 180 / B % 360 }, a.snapTo = function (b, c, d) { d = a.is(d, "finite") ? d : 10; if (a.is(b, E)) { var e = b.length; while (e--) if (z(b[e] - c) <= d) return b[e] } else { b = +b; var f = c % b; if (f < d) return c - f; if (f > b - d) return c - f + b } return c }; var bl = a.createUUID = function (a, b) { return function () { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(a, b).toUpperCase() } } (/[xy]/g, function (a) { var b = w.random() * 16 | 0, c = a == "x" ? b : b & 3 | 8; return c.toString(16) }); a.setWindow = function (b) { eve("setWindow", a, h.win, b), h.win = b, h.doc = h.win.document, a._engine.initWin && a._engine.initWin(h.win) }; var bm = function (b) { if (a.vml) { var c = /^\s+|\s+$/g, d; try { var e = new ActiveXObject("htmlfile"); e.write("<body>"), e.close(), d = e.body } catch (f) { d = createPopup().document.body } var g = d.createTextRange(); bm = bt(function (a) { try { d.style.color = r(a).replace(c, p); var b = g.queryCommandValue("ForeColor"); b = (b & 255) << 16 | b & 65280 | (b & 16711680) >>> 16; return "#" + ("000000" + b.toString(16)).slice(-6) } catch (e) { return "none" } }) } else { var i = h.doc.createElement("i"); i.title = "Raphaël Colour Picker", i.style.display = "none", h.doc.body.appendChild(i), bm = bt(function (a) { i.style.color = a; return h.doc.defaultView.getComputedStyle(i, p).getPropertyValue("color") }) } return bm(b) }, bn = function () { return "hsb(" + [this.h, this.s, this.b] + ")" }, bo = function () { return "hsl(" + [this.h, this.s, this.l] + ")" }, bp = function () { return this.hex }, bq = function (b, c, d) { c == null && a.is(b, "object") && "r" in b && "g" in b && "b" in b && (d = b.b, c = b.g, b = b.r); if (c == null && a.is(b, D)) { var e = a.getRGB(b); b = e.r, c = e.g, d = e.b } if (b > 1 || c > 1 || d > 1) b /= 255, c /= 255, d /= 255; return [b, c, d] }, br = function (b, c, d, e) { b *= 255, c *= 255, d *= 255; var f = { r: b, g: c, b: d, hex: a.rgb(b, c, d), toString: bp }; a.is(e, "finite") && (f.opacity = e); return f }; a.color = function (b) { var c; a.is(b, "object") && "h" in b && "s" in b && "b" in b ? (c = a.hsb2rgb(b), b.r = c.r, b.g = c.g, b.b = c.b, b.hex = c.hex) : a.is(b, "object") && "h" in b && "s" in b && "l" in b ? (c = a.hsl2rgb(b), b.r = c.r, b.g = c.g, b.b = c.b, b.hex = c.hex) : (a.is(b, "string") && (b = a.getRGB(b)), a.is(b, "object") && "r" in b && "g" in b && "b" in b ? (c = a.rgb2hsl(b), b.h = c.h, b.s = c.s, b.l = c.l, c = a.rgb2hsb(b), b.v = c.b) : (b = { hex: "none" }, b.r = b.g = b.b = b.h = b.s = b.v = b.l = -1)), b.toString = bp; return b }, a.hsb2rgb = function (a, b, c, d) { this.is(a, "object") && "h" in a && "s" in a && "b" in a && (c = a.b, b = a.s, a = a.h, d = a.o), a *= 360; var e, f, g, h, i; a = a % 360 / 60, i = c * b, h = i * (1 - z(a % 2 - 1)), e = f = g = c - i, a = ~ ~a, e += [i, h, 0, 0, h, i][a], f += [h, i, i, h, 0, 0][a], g += [0, 0, h, i, i, h][a]; return br(e, f, g, d) }, a.hsl2rgb = function (a, b, c, d) { this.is(a, "object") && "h" in a && "s" in a && "l" in a && (c = a.l, b = a.s, a = a.h); if (a > 1 || b > 1 || c > 1) a /= 360, b /= 100, c /= 100; a *= 360; var e, f, g, h, i; a = a % 360 / 60, i = 2 * b * (c < .5 ? c : 1 - c), h = i * (1 - z(a % 2 - 1)), e = f = g = c - i / 2, a = ~ ~a, e += [i, h, 0, 0, h, i][a], f += [h, i, i, h, 0, 0][a], g += [0, 0, h, i, i, h][a]; return br(e, f, g, d) }, a.rgb2hsb = function (a, b, c) { c = bq(a, b, c), a = c[0], b = c[1], c = c[2]; var d, e, f, g; f = x(a, b, c), g = f - y(a, b, c), d = g == 0 ? null : f == a ? (b - c) / g : f == b ? (c - a) / g + 2 : (a - b) / g + 4, d = (d + 360) % 6 * 60 / 360, e = g == 0 ? 0 : g / f; return { h: d, s: e, b: f, toString: bn} }, a.rgb2hsl = function (a, b, c) { c = bq(a, b, c), a = c[0], b = c[1], c = c[2]; var d, e, f, g, h, i; g = x(a, b, c), h = y(a, b, c), i = g - h, d = i == 0 ? null : g == a ? (b - c) / i : g == b ? (c - a) / i + 2 : (a - b) / i + 4, d = (d + 360) % 6 * 60 / 360, f = (g + h) / 2, e = i == 0 ? 0 : f < .5 ? i / (2 * f) : i / (2 - 2 * f); return { h: d, s: e, l: f, toString: bo} }, a._path2string = function () { return this.join(",").replace(X, "$1") }; var bu = a._preload = function (a, b) { var c = h.doc.createElement("img"); c.style.cssText = "position:absolute;left:-9999em;top:-9999em", c.onload = function () { b.call(this), this.onload = null, h.doc.body.removeChild(this) }, c.onerror = function () { h.doc.body.removeChild(this) }, h.doc.body.appendChild(c), c.src = a }; a.getRGB = bt(function (b) { if (!b || !!((b = r(b)).indexOf("-") + 1)) return { r: -1, g: -1, b: -1, hex: "none", error: 1, toString: bv }; if (b == "none") return { r: -1, g: -1, b: -1, hex: "none", toString: bv }; !W[g](b.toLowerCase().substring(0, 2)) && b.charAt() != "#" && (b = bm(b)); var c, d, e, f, h, i, j, k = b.match(L); if (k) { k[2] && (f = R(k[2].substring(5), 16), e = R(k[2].substring(3, 5), 16), d = R(k[2].substring(1, 3), 16)), k[3] && (f = R((i = k[3].charAt(3)) + i, 16), e = R((i = k[3].charAt(2)) + i, 16), d = R((i = k[3].charAt(1)) + i, 16)), k[4] && (j = k[4][s](V), d = Q(j[0]), j[0].slice(-1) == "%" && (d *= 2.55), e = Q(j[1]), j[1].slice(-1) == "%" && (e *= 2.55), f = Q(j[2]), j[2].slice(-1) == "%" && (f *= 2.55), k[1].toLowerCase().slice(0, 4) == "rgba" && (h = Q(j[3])), j[3] && j[3].slice(-1) == "%" && (h /= 100)); if (k[5]) { j = k[5][s](V), d = Q(j[0]), j[0].slice(-1) == "%" && (d *= 2.55), e = Q(j[1]), j[1].slice(-1) == "%" && (e *= 2.55), f = Q(j[2]), j[2].slice(-1) == "%" && (f *= 2.55), (j[0].slice(-3) == "deg" || j[0].slice(-1) == "°") && (d /= 360), k[1].toLowerCase().slice(0, 4) == "hsba" && (h = Q(j[3])), j[3] && j[3].slice(-1) == "%" && (h /= 100); return a.hsb2rgb(d, e, f, h) } if (k[6]) { j = k[6][s](V), d = Q(j[0]), j[0].slice(-1) == "%" && (d *= 2.55), e = Q(j[1]), j[1].slice(-1) == "%" && (e *= 2.55), f = Q(j[2]), j[2].slice(-1) == "%" && (f *= 2.55), (j[0].slice(-3) == "deg" || j[0].slice(-1) == "°") && (d /= 360), k[1].toLowerCase().slice(0, 4) == "hsla" && (h = Q(j[3])), j[3] && j[3].slice(-1) == "%" && (h /= 100); return a.hsl2rgb(d, e, f, h) } k = { r: d, g: e, b: f, toString: bv }, k.hex = "#" + (16777216 | f | e << 8 | d << 16).toString(16).slice(1), a.is(h, "finite") && (k.opacity = h); return k } return { r: -1, g: -1, b: -1, hex: "none", error: 1, toString: bv} }, a), a.hsb = bt(function (b, c, d) { return a.hsb2rgb(b, c, d).hex }), a.hsl = bt(function (b, c, d) { return a.hsl2rgb(b, c, d).hex }), a.rgb = bt(function (a, b, c) { return "#" + (16777216 | c | b << 8 | a << 16).toString(16).slice(1) }), a.getColor = function (a) { var b = this.getColor.start = this.getColor.start || { h: 0, s: 1, b: a || .75 }, c = this.hsb2rgb(b.h, b.s, b.b); b.h += .075, b.h > 1 && (b.h = 0, b.s -= .2, b.s <= 0 && (this.getColor.start = { h: 0, s: 1, b: b.b })); return c.hex }, a.getColor.reset = function () { delete this.start }, a.parsePathString = bt(function (b) { if (!b) return null; var c = { a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0 }, d = []; a.is(b, E) && a.is(b[0], E) && (d = by(b)), d.length || r(b).replace(Y, function (a, b, e) { var f = [], g = b.toLowerCase(); e.replace($, function (a, b) { b && f.push(+b) }), g == "m" && f.length > 2 && (d.push([b][n](f.splice(0, 2))), g = "l", b = b == "m" ? "l" : "L"); if (g == "r") d.push([b][n](f)); else while (f.length >= c[g]) { d.push([b][n](f.splice(0, c[g]))); if (!c[g]) break } }), d.toString = a._path2string; return d }), a.parseTransformString = bt(function (b) { if (!b) return null; var c = { r: 3, s: 4, t: 2, m: 6 }, d = []; a.is(b, E) && a.is(b[0], E) && (d = by(b)), d.length || r(b).replace(Z, function (a, b, c) { var e = [], f = v.call(b); c.replace($, function (a, b) { b && e.push(+b) }), d.push([b][n](e)) }), d.toString = a._path2string; return d }), a.findDotsAtSegment = function (a, b, c, d, e, f, g, h, i) { var j = 1 - i, k = A(j, 3), l = A(j, 2), m = i * i, n = m * i, o = k * a + l * 3 * i * c + j * 3 * i * i * e + n * g, p = k * b + l * 3 * i * d + j * 3 * i * i * f + n * h, q = a + 2 * i * (c - a) + m * (e - 2 * c + a), r = b + 2 * i * (d - b) + m * (f - 2 * d + b), s = c + 2 * i * (e - c) + m * (g - 2 * e + c), t = d + 2 * i * (f - d) + m * (h - 2 * f + d), u = j * a + i * c, v = j * b + i * d, x = j * e + i * g, y = j * f + i * h, z = 90 - w.atan2(q - s, r - t) * 180 / B; (q > s || r < t) && (z += 180); return { x: o, y: p, m: { x: q, y: r }, n: { x: s, y: t }, start: { x: u, y: v }, end: { x: x, y: y }, alpha: z} }, a._removedFactory = function (a) { return function () { throw new Error("Raphaël: you are calling to method “" + a + "” of removed object") } }; var bx = bt(function (a) { if (!a) return { x: 0, y: 0, width: 0, height: 0 }; a = bG(a); var b = 0, c = 0, d = [], e = [], f; for (var g = 0, h = a.length; g < h; g++) { f = a[g]; if (f[0] == "M") b = f[1], c = f[2], d.push(b), e.push(c); else { var i = bF(b, c, f[1], f[2], f[3], f[4], f[5], f[6]); d = d[n](i.min.x, i.max.x), e = e[n](i.min.y, i.max.y), b = f[5], c = f[6] } } var j = y[m](0, d), k = y[m](0, e); return { x: j, y: k, width: x[m](0, d) - j, height: x[m](0, e) - k} }, null, function (a) { return { x: a.x, y: a.y, width: a.width, height: a.height} }), by = function (b) { var c = []; if (!a.is(b, E) || !a.is(b && b[0], E)) b = a.parsePathString(b); for (var d = 0, e = b.length; d < e; d++) { c[d] = []; for (var f = 0, g = b[d].length; f < g; f++) c[d][f] = b[d][f] } c.toString = a._path2string; return c }, bz = a._pathToRelative = bt(function (b) { if (!a.is(b, E) || !a.is(b && b[0], E)) b = a.parsePathString(b); var c = [], d = 0, e = 0, f = 0, g = 0, h = 0; b[0][0] == "M" && (d = b[0][1], e = b[0][2], f = d, g = e, h++, c.push(["M", d, e])); for (var i = h, j = b.length; i < j; i++) { var k = c[i] = [], l = b[i]; if (l[0] != v.call(l[0])) { k[0] = v.call(l[0]); switch (k[0]) { case "a": k[1] = l[1], k[2] = l[2], k[3] = l[3], k[4] = l[4], k[5] = l[5], k[6] = +(l[6] - d).toFixed(3), k[7] = +(l[7] - e).toFixed(3); break; case "v": k[1] = +(l[1] - e).toFixed(3); break; case "m": f = l[1], g = l[2]; default: for (var m = 1, n = l.length; m < n; m++) k[m] = +(l[m] - (m % 2 ? d : e)).toFixed(3) } } else { k = c[i] = [], l[0] == "m" && (f = l[1] + d, g = l[2] + e); for (var o = 0, p = l.length; o < p; o++) c[i][o] = l[o] } var q = c[i].length; switch (c[i][0]) { case "z": d = f, e = g; break; case "h": d += +c[i][q - 1]; break; case "v": e += +c[i][q - 1]; break; default: d += +c[i][q - 2], e += +c[i][q - 1] } } c.toString = a._path2string; return c }, 0, by), bA = a._pathToAbsolute = bt(function (b) { if (!a.is(b, E) || !a.is(b && b[0], E)) b = a.parsePathString(b); if (!b || !b.length) return [["M", 0, 0]]; var c = [], d = 0, e = 0, f = 0, g = 0, h = 0; b[0][0] == "M" && (d = +b[0][1], e = +b[0][2], f = d, g = e, h++, c[0] = ["M", d, e]); for (var i, j, k = h, l = b.length; k < l; k++) { c.push(i = []), j = b[k]; if (j[0] != S.call(j[0])) { i[0] = S.call(j[0]); switch (i[0]) { case "A": i[1] = j[1], i[2] = j[2], i[3] = j[3], i[4] = j[4], i[5] = j[5], i[6] = +(j[6] + d), i[7] = +(j[7] + e); break; case "V": i[1] = +j[1] + e; break; case "H": i[1] = +j[1] + d; break; case "R": var m = [d, e][n](j.slice(1)); for (var o = 2, p = m.length; o < p; o++) m[o] = +m[o] + d, m[++o] = +m[o] + e; c.pop(), c = c[n](bw(m)); break; case "M": f = +j[1] + d, g = +j[2] + e; default: for (o = 1, p = j.length; o < p; o++) i[o] = +j[o] + (o % 2 ? d : e) } } else if (j[0] == "R") m = [d, e][n](j.slice(1)), c.pop(), c = c[n](bw(m)), i = ["R"][n](j.slice(-2)); else for (var q = 0, r = j.length; q < r; q++) i[q] = j[q]; switch (i[0]) { case "Z": d = f, e = g; break; case "H": d = i[1]; break; case "V": e = i[1]; break; case "M": f = i[i.length - 2], g = i[i.length - 1]; default: d = i[i.length - 2], e = i[i.length - 1] } } c.toString = a._path2string; return c }, null, by), bB = function (a, b, c, d) { return [a, b, c, d, c, d] }, bC = function (a, b, c, d, e, f) { var g = 1 / 3, h = 2 / 3; return [g * a + h * c, g * b + h * d, g * e + h * c, g * f + h * d, e, f] }, bD = function (a, b, c, d, e, f, g, h, i, j) { var k = B * 120 / 180, l = B / 180 * (+e || 0), m = [], o, p = bt(function (a, b, c) { var d = a * w.cos(c) - b * w.sin(c), e = a * w.sin(c) + b * w.cos(c); return { x: d, y: e} }); if (!j) { o = p(a, b, -l), a = o.x, b = o.y, o = p(h, i, -l), h = o.x, i = o.y; var q = w.cos(B / 180 * e), r = w.sin(B / 180 * e), t = (a - h) / 2, u = (b - i) / 2, v = t * t / (c * c) + u * u / (d * d); v > 1 && (v = w.sqrt(v), c = v * c, d = v * d); var x = c * c, y = d * d, A = (f == g ? -1 : 1) * w.sqrt(z((x * y - x * u * u - y * t * t) / (x * u * u + y * t * t))), C = A * c * u / d + (a + h) / 2, D = A * -d * t / c + (b + i) / 2, E = w.asin(((b - D) / d).toFixed(9)), F = w.asin(((i - D) / d).toFixed(9)); E = a < C ? B - E : E, F = h < C ? B - F : F, E < 0 && (E = B * 2 + E), F < 0 && (F = B * 2 + F), g && E > F && (E = E - B * 2), !g && F > E && (F = F - B * 2) } else E = j[0], F = j[1], C = j[2], D = j[3]; var G = F - E; if (z(G) > k) { var H = F, I = h, J = i; F = E + k * (g && F > E ? 1 : -1), h = C + c * w.cos(F), i = D + d * w.sin(F), m = bD(h, i, c, d, e, 0, g, I, J, [F, H, C, D]) } G = F - E; var K = w.cos(E), L = w.sin(E), M = w.cos(F), N = w.sin(F), O = w.tan(G / 4), P = 4 / 3 * c * O, Q = 4 / 3 * d * O, R = [a, b], S = [a + P * L, b - Q * K], T = [h + P * N, i - Q * M], U = [h, i]; S[0] = 2 * R[0] - S[0], S[1] = 2 * R[1] - S[1]; if (j) return [S, T, U][n](m); m = [S, T, U][n](m).join()[s](","); var V = []; for (var W = 0, X = m.length; W < X; W++) V[W] = W % 2 ? p(m[W - 1], m[W], l).y : p(m[W], m[W + 1], l).x; return V }, bE = function (a, b, c, d, e, f, g, h, i) { var j = 1 - i; return { x: A(j, 3) * a + A(j, 2) * 3 * i * c + j * 3 * i * i * e + A(i, 3) * g, y: A(j, 3) * b + A(j, 2) * 3 * i * d + j * 3 * i * i * f + A(i, 3) * h} }, bF = bt(function (a, b, c, d, e, f, g, h) { var i = e - 2 * c + a - (g - 2 * e + c), j = 2 * (c - a) - 2 * (e - c), k = a - c, l = (-j + w.sqrt(j * j - 4 * i * k)) / 2 / i, n = (-j - w.sqrt(j * j - 4 * i * k)) / 2 / i, o = [b, h], p = [a, g], q; z(l) > "1e12" && (l = .5), z(n) > "1e12" && (n = .5), l > 0 && l < 1 && (q = bE(a, b, c, d, e, f, g, h, l), p.push(q.x), o.push(q.y)), n > 0 && n < 1 && (q = bE(a, b, c, d, e, f, g, h, n), p.push(q.x), o.push(q.y)), i = f - 2 * d + b - (h - 2 * f + d), j = 2 * (d - b) - 2 * (f - d), k = b - d, l = (-j + w.sqrt(j * j - 4 * i * k)) / 2 / i, n = (-j - w.sqrt(j * j - 4 * i * k)) / 2 / i, z(l) > "1e12" && (l = .5), z(n) > "1e12" && (n = .5), l > 0 && l < 1 && (q = bE(a, b, c, d, e, f, g, h, l), p.push(q.x), o.push(q.y)), n > 0 && n < 1 && (q = bE(a, b, c, d, e, f, g, h, n), p.push(q.x), o.push(q.y)); return { min: { x: y[m](0, p), y: y[m](0, o) }, max: { x: x[m](0, p), y: x[m](0, o)}} }), bG = a._path2curve = bt(function (a, b) { var c = bA(a), d = b && bA(b), e = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }, f = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }, g = function (a, b) { var c, d; if (!a) return ["C", b.x, b.y, b.x, b.y, b.x, b.y]; !(a[0] in { T: 1, Q: 1 }) && (b.qx = b.qy = null); switch (a[0]) { case "M": b.X = a[1], b.Y = a[2]; break; case "A": a = ["C"][n](bD[m](0, [b.x, b.y][n](a.slice(1)))); break; case "S": c = b.x + (b.x - (b.bx || b.x)), d = b.y + (b.y - (b.by || b.y)), a = ["C", c, d][n](a.slice(1)); break; case "T": b.qx = b.x + (b.x - (b.qx || b.x)), b.qy = b.y + (b.y - (b.qy || b.y)), a = ["C"][n](bC(b.x, b.y, b.qx, b.qy, a[1], a[2])); break; case "Q": b.qx = a[1], b.qy = a[2], a = ["C"][n](bC(b.x, b.y, a[1], a[2], a[3], a[4])); break; case "L": a = ["C"][n](bB(b.x, b.y, a[1], a[2])); break; case "H": a = ["C"][n](bB(b.x, b.y, a[1], b.y)); break; case "V": a = ["C"][n](bB(b.x, b.y, b.x, a[1])); break; case "Z": a = ["C"][n](bB(b.x, b.y, b.X, b.Y)) } return a }, h = function (a, b) { if (a[b].length > 7) { a[b].shift(); var e = a[b]; while (e.length) a.splice(b++, 0, ["C"][n](e.splice(0, 6))); a.splice(b, 1), k = x(c.length, d && d.length || 0) } }, i = function (a, b, e, f, g) { a && b && a[g][0] == "M" && b[g][0] != "M" && (b.splice(g, 0, ["M", f.x, f.y]), e.bx = 0, e.by = 0, e.x = a[g][1], e.y = a[g][2], k = x(c.length, d && d.length || 0)) }; for (var j = 0, k = x(c.length, d && d.length || 0); j < k; j++) { c[j] = g(c[j], e), h(c, j), d && (d[j] = g(d[j], f)), d && h(d, j), i(c, d, e, f, j), i(d, c, f, e, j); var l = c[j], o = d && d[j], p = l.length, q = d && o.length; e.x = l[p - 2], e.y = l[p - 1], e.bx = Q(l[p - 4]) || e.x, e.by = Q(l[p - 3]) || e.y, f.bx = d && (Q(o[q - 4]) || f.x), f.by = d && (Q(o[q - 3]) || f.y), f.x = d && o[q - 2], f.y = d && o[q - 1] } return d ? [c, d] : c }, null, by), bH = a._parseDots = bt(function (b) { var c = []; for (var d = 0, e = b.length; d < e; d++) { var f = {}, g = b[d].match(/^([^:]*):?([\d\.]*)/); f.color = a.getRGB(g[1]); if (f.color.error) return null; f.color = f.color.hex, g[2] && (f.offset = g[2] + "%"), c.push(f) } for (d = 1, e = c.length - 1; d < e; d++) if (!c[d].offset) { var h = Q(c[d - 1].offset || 0), i = 0; for (var j = d + 1; j < e; j++) if (c[j].offset) { i = c[j].offset; break } i || (i = 100, j = e), i = Q(i); var k = (i - h) / (j - d + 1); for (; d < j; d++) h += k, c[d].offset = h + "%" } return c }), bI = a._tear = function (a, b) { a == b.top && (b.top = a.prev), a == b.bottom && (b.bottom = a.next), a.next && (a.next.prev = a.prev), a.prev && (a.prev.next = a.next) }, bJ = a._tofront = function (a, b) { b.top !== a && (bI(a, b), a.next = null, a.prev = b.top, b.top.next = a, b.top = a) }, bK = a._toback = function (a, b) { b.bottom !== a && (bI(a, b), a.next = b.bottom, a.prev = null, b.bottom.prev = a, b.bottom = a) }, bL = a._insertafter = function (a, b, c) { bI(a, c), b == c.top && (c.top = a), b.next && (b.next.prev = a), a.next = b.next, a.prev = b, b.next = a }, bM = a._insertbefore = function (a, b, c) { bI(a, c), b == c.bottom && (c.bottom = a), b.prev && (b.prev.next = a), a.prev = b.prev, b.prev = a, a.next = b }, bN = a._extractTransform = function (b, c) { if (c == null) return b._.transform; c = r(c).replace(/\.{3}|\u2026/g, b._.transform || p); var d = a.parseTransformString(c), e = 0, f = 0, g = 0, h = 1, i = 1, j = b._, k = new bQ; j.transform = d || []; if (d) for (var l = 0, m = d.length; l < m; l++) { var n = d[l], o = n.length, q = r(n[0]).toLowerCase(), s = n[0] != q, t = s ? k.invert() : 0, u, v, w, x, y; q == "t" && o == 3 ? s ? (u = t.x(0, 0), v = t.y(0, 0), w = t.x(n[1], n[2]), x = t.y(n[1], n[2]), k.translate(w - u, x - v)) : k.translate(n[1], n[2]) : q == "r" ? o == 2 ? (y = y || b.getBBox(1), k.rotate(n[1], y.x + y.width / 2, y.y + y.height / 2), e += n[1]) : o == 4 && (s ? (w = t.x(n[2], n[3]), x = t.y(n[2], n[3]), k.rotate(n[1], w, x)) : k.rotate(n[1], n[2], n[3]), e += n[1]) : q == "s" ? o == 2 || o == 3 ? (y = y || b.getBBox(1), k.scale(n[1], n[o - 1], y.x + y.width / 2, y.y + y.height / 2), h *= n[1], i *= n[o - 1]) : o == 5 && (s ? (w = t.x(n[3], n[4]), x = t.y(n[3], n[4]), k.scale(n[1], n[2], w, x)) : k.scale(n[1], n[2], n[3], n[4]), h *= n[1], i *= n[2]) : q == "m" && o == 7 && k.add(n[1], n[2], n[3], n[4], n[5], n[6]), j.dirtyT = 1, b.matrix = k } b.matrix = k, j.sx = h, j.sy = i, j.deg = e, j.dx = f = k.e, j.dy = g = k.f, h == 1 && i == 1 && !e && j.bbox ? (j.bbox.x += +f, j.bbox.y += +g) : j.dirtyT = 1 }, bO = function (a) { var b = a[0]; switch (b.toLowerCase()) { case "t": return [b, 0, 0]; case "m": return [b, 1, 0, 0, 1, 0, 0]; case "r": return a.length == 4 ? [b, 0, a[2], a[3]] : [b, 0]; case "s": return a.length == 5 ? [b, 1, 1, a[3], a[4]] : a.length == 3 ? [b, 1, 1] : [b, 1] } }, bP = a._equaliseTransform = function (b, c) { c = r(c).replace(/\.{3}|\u2026/g, b), b = a.parseTransformString(b) || [], c = a.parseTransformString(c) || []; var d = x(b.length, c.length), e = [], f = [], g = 0, h, i, j, k; for (; g < d; g++) { j = b[g] || bO(c[g]), k = c[g] || bO(j); if (j[0] != k[0] || j[0].toLowerCase() == "r" && (j[2] != k[2] || j[3] != k[3]) || j[0].toLowerCase() == "s" && (j[3] != k[3] || j[4] != k[4])) return; e[g] = [], f[g] = []; for (h = 0, i = x(j.length, k.length); h < i; h++) h in j && (e[g][h] = j[h]), h in k && (f[g][h] = k[h]) } return { from: e, to: f} }; a._getContainer = function (b, c, d, e) { var f; f = e == null && !a.is(b, "object") ? h.doc.getElementById(b) : b; if (f != null) { if (f.tagName) return c == null ? { container: f, width: f.style.pixelWidth || f.offsetWidth, height: f.style.pixelHeight || f.offsetHeight} : { container: f, width: c, height: d }; return { container: 1, x: b, y: c, width: d, height: e} } }, a.pathToRelative = bz, a._engine = {}, a.path2curve = bG, a.matrix = function (a, b, c, d, e, f) { return new bQ(a, b, c, d, e, f) }, function (b) { function d(a) { var b = w.sqrt(c(a)); a[0] && (a[0] /= b), a[1] && (a[1] /= b) } function c(a) { return a[0] * a[0] + a[1] * a[1] } b.add = function (a, b, c, d, e, f) { var g = [[], [], []], h = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]], i = [[a, c, e], [b, d, f], [0, 0, 1]], j, k, l, m; a && a instanceof bQ && (i = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]]); for (j = 0; j < 3; j++) for (k = 0; k < 3; k++) { m = 0; for (l = 0; l < 3; l++) m += h[j][l] * i[l][k]; g[j][k] = m } this.a = g[0][0], this.b = g[1][0], this.c = g[0][1], this.d = g[1][1], this.e = g[0][2], this.f = g[1][2] }, b.invert = function () { var a = this, b = a.a * a.d - a.b * a.c; return new bQ(a.d / b, -a.b / b, -a.c / b, a.a / b, (a.c * a.f - a.d * a.e) / b, (a.b * a.e - a.a * a.f) / b) }, b.clone = function () { return new bQ(this.a, this.b, this.c, this.d, this.e, this.f) }, b.translate = function (a, b) { this.add(1, 0, 0, 1, a, b) }, b.scale = function (a, b, c, d) { b == null && (b = a), (c || d) && this.add(1, 0, 0, 1, c, d), this.add(a, 0, 0, b, 0, 0), (c || d) && this.add(1, 0, 0, 1, -c, -d) }, b.rotate = function (b, c, d) { b = a.rad(b), c = c || 0, d = d || 0; var e = +w.cos(b).toFixed(9), f = +w.sin(b).toFixed(9); this.add(e, f, -f, e, c, d), this.add(1, 0, 0, 1, -c, -d) }, b.x = function (a, b) { return a * this.a + b * this.c + this.e }, b.y = function (a, b) { return a * this.b + b * this.d + this.f }, b.get = function (a) { return +this[r.fromCharCode(97 + a)].toFixed(4) }, b.toString = function () { return a.svg ? "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" : [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join() }, b.toFilter = function () { return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) + ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) + ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')" }, b.offset = function () { return [this.e.toFixed(4), this.f.toFixed(4)] }, b.split = function () { var b = {}; b.dx = this.e, b.dy = this.f; var e = [[this.a, this.c], [this.b, this.d]]; b.scalex = w.sqrt(c(e[0])), d(e[0]), b.shear = e[0][0] * e[1][0] + e[0][1] * e[1][1], e[1] = [e[1][0] - e[0][0] * b.shear, e[1][1] - e[0][1] * b.shear], b.scaley = w.sqrt(c(e[1])), d(e[1]), b.shear /= b.scaley; var f = -e[0][1], g = e[1][1]; g < 0 ? (b.rotate = a.deg(w.acos(g)), f < 0 && (b.rotate = 360 - b.rotate)) : b.rotate = a.deg(w.asin(f)), b.isSimple = ! +b.shear.toFixed(9) && (b.scalex.toFixed(9) == b.scaley.toFixed(9) || !b.rotate), b.isSuperSimple = ! +b.shear.toFixed(9) && b.scalex.toFixed(9) == b.scaley.toFixed(9) && !b.rotate, b.noRotation = ! +b.shear.toFixed(9) && !b.rotate; return b }, b.toTransformString = function (a) { var b = a || this[s](); if (b.isSimple) { b.scalex = +b.scalex.toFixed(4), b.scaley = +b.scaley.toFixed(4), b.rotate = +b.rotate.toFixed(4); return (b.dx && b.dy ? "t" + [b.dx, b.dy] : p) + (b.scalex != 1 || b.scaley != 1 ? "s" + [b.scalex, b.scaley, 0, 0] : p) + (b.rotate ? "r" + [b.rotate, 0, 0] : p) } return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)] } } (bQ.prototype); var bR = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/); navigator.vendor == "Apple Computer, Inc." && (bR && bR[1] < 4 || navigator.platform.slice(0, 2) == "iP") || navigator.vendor == "Google Inc." && bR && bR[1] < 8 ? k.safari = function () { var a = this.rect(-99, -99, this.width + 99, this.height + 99).attr({ stroke: "none" }); setTimeout(function () { a.remove() }) } : k.safari = bd; var bS = function () { this.returnValue = !1 }, bT = function () { return this.originalEvent.preventDefault() }, bU = function () { this.cancelBubble = !0 }, bV = function () { return this.originalEvent.stopPropagation() }, bW = function () { if (h.doc.addEventListener) return function (a, b, c, d) { var e = o && u[b] ? u[b] : b, f = function (e) { var f = h.doc.documentElement.scrollTop || h.doc.body.scrollTop, i = h.doc.documentElement.scrollLeft || h.doc.body.scrollLeft, j = e.clientX + i, k = e.clientY + f; if (o && u[g](b)) for (var l = 0, m = e.targetTouches && e.targetTouches.length; l < m; l++) if (e.targetTouches[l].target == a) { var n = e; e = e.targetTouches[l], e.originalEvent = n, e.preventDefault = bT, e.stopPropagation = bV; break } return c.call(d, e, j, k) }; a.addEventListener(e, f, !1); return function () { a.removeEventListener(e, f, !1); return !0 } }; if (h.doc.attachEvent) return function (a, b, c, d) { var e = function (a) { a = a || h.win.event; var b = h.doc.documentElement.scrollTop || h.doc.body.scrollTop, e = h.doc.documentElement.scrollLeft || h.doc.body.scrollLeft, f = a.clientX + e, g = a.clientY + b; a.preventDefault = a.preventDefault || bS, a.stopPropagation = a.stopPropagation || bU; return c.call(d, a, f, g) }; a.attachEvent("on" + b, e); var f = function () { a.detachEvent("on" + b, e); return !0 }; return f } } (), bX = [], bY = function (a) { var b = a.clientX, c = a.clientY, d = h.doc.documentElement.scrollTop || h.doc.body.scrollTop, e = h.doc.documentElement.scrollLeft || h.doc.body.scrollLeft, f, g = bX.length; while (g--) { f = bX[g]; if (o) { var i = a.touches.length, j; while (i--) { j = a.touches[i]; if (j.identifier == f.el._drag.id) { b = j.clientX, c = j.clientY, (a.originalEvent ? a.originalEvent : a).preventDefault(); break } } } else a.preventDefault(); var k = f.el.node, l, m = k.nextSibling, n = k.parentNode, p = k.style.display; h.win.opera && n.removeChild(k), k.style.display = "none", l = f.el.paper.getElementByPoint(b, c), k.style.display = p, h.win.opera && (m ? n.insertBefore(k, m) : n.appendChild(k)), l && eve("drag.over." + f.el.id, f.el, l), b += e, c += d, eve("drag.move." + f.el.id, f.move_scope || f.el, b - f.el._drag.x, c - f.el._drag.y, b, c, a) } }, bZ = function (b) { a.unmousemove(bY).unmouseup(bZ); var c = bX.length, d; while (c--) d = bX[c], d.el._drag = {}, eve("drag.end." + d.el.id, d.end_scope || d.start_scope || d.move_scope || d.el, b); bX = [] }, b$ = a.el = {}; for (var b_ = t.length; b_--; ) (function (b) { a[b] = b$[b] = function (c, d) { a.is(c, "function") && (this.events = this.events || [], this.events.push({ name: b, f: c, unbind: bW(this.shape || this.node || h.doc, b, c, d || this) })); return this }, a["un" + b] = b$["un" + b] = function (a) { var c = this.events, d = c.length; while (d--) if (c[d].name == b && c[d].f == a) { c[d].unbind(), c.splice(d, 1), !c.length && delete this.events; return this } return this } })(t[b_]); b$.data = function (b, c) { var d = ba[this.id] = ba[this.id] || {}; if (arguments.length == 1) { if (a.is(b, "object")) { for (var e in b) b[g](e) && this.data(e, b[e]); return this } eve("data.get." + this.id, this, d[b], b); return d[b] } d[b] = c, eve("data.set." + this.id, this, c, b); return this }, b$.removeData = function (a) { a == null ? ba[this.id] = {} : ba[this.id] && delete ba[this.id][a]; return this }, b$.hover = function (a, b, c, d) { return this.mouseover(a, c).mouseout(b, d || c) }, b$.unhover = function (a, b) { return this.unmouseover(a).unmouseout(b) }; var ca = []; b$.drag = function (b, c, d, e, f, g) { function i(i) { (i.originalEvent || i).preventDefault(); var j = h.doc.documentElement.scrollTop || h.doc.body.scrollTop, k = h.doc.documentElement.scrollLeft || h.doc.body.scrollLeft; this._drag.x = i.clientX + k, this._drag.y = i.clientY + j, this._drag.id = i.identifier, !bX.length && a.mousemove(bY).mouseup(bZ), bX.push({ el: this, move_scope: e, start_scope: f, end_scope: g }), c && eve.on("drag.start." + this.id, c), b && eve.on("drag.move." + this.id, b), d && eve.on("drag.end." + this.id, d), eve("drag.start." + this.id, f || e || this, i.clientX + k, i.clientY + j, i) } this._drag = {}, ca.push({ el: this, start: i }), this.mousedown(i); return this }, b$.onDragOver = function (a) { a ? eve.on("drag.over." + this.id, a) : eve.unbind("drag.over." + this.id) }, b$.undrag = function () { var b = ca.length; while (b--) ca[b].el == this && (this.unmousedown(ca[b].start), ca.splice(b, 1), eve.unbind("drag.*." + this.id)); !ca.length && a.unmousemove(bY).unmouseup(bZ) }, k.circle = function (b, c, d) { var e = a._engine.circle(this, b || 0, c || 0, d || 0); this.__set__ && this.__set__.push(e); return e }, k.rect = function (b, c, d, e, f) { var g = a._engine.rect(this, b || 0, c || 0, d || 0, e || 0, f || 0); this.__set__ && this.__set__.push(g); return g }, k.ellipse = function (b, c, d, e) { var f = a._engine.ellipse(this, b || 0, c || 0, d || 0, e || 0); this.__set__ && this.__set__.push(f); return f }, k.path = function (b) { b && !a.is(b, D) && !a.is(b[0], E) && (b += p); var c = a._engine.path(a.format[m](a, arguments), this); this.__set__ && this.__set__.push(c); return c }, k.image = function (b, c, d, e, f) { var g = a._engine.image(this, b || "about:blank", c || 0, d || 0, e || 0, f || 0); this.__set__ && this.__set__.push(g); return g }, k.text = function (b, c, d) { var e = a._engine.text(this, b || 0, c || 0, r(d)); this.__set__ && this.__set__.push(e); return e }, k.set = function (b) { !a.is(b, "array") && (b = Array.prototype.splice.call(arguments, 0, arguments.length)); var c = new cs(b); this.__set__ && this.__set__.push(c); return c }, k.setStart = function (a) { this.__set__ = a || this.set() }, k.setFinish = function (a) { var b = this.__set__; delete this.__set__; return b }, k.setSize = function (b, c) { return a._engine.setSize.call(this, b, c) }, k.setViewBox = function (b, c, d, e, f) { return a._engine.setViewBox.call(this, b, c, d, e, f) }, k.top = k.bottom = null, k.raphael = a; var cb = function (a) { var b = a.getBoundingClientRect(), c = a.ownerDocument, d = c.body, e = c.documentElement, f = e.clientTop || d.clientTop || 0, g = e.clientLeft || d.clientLeft || 0, i = b.top + (h.win.pageYOffset || e.scrollTop || d.scrollTop) - f, j = b.left + (h.win.pageXOffset || e.scrollLeft || d.scrollLeft) - g; return { y: i, x: j} }; k.getElementByPoint = function (a, b) { var c = this, d = c.canvas, e = h.doc.elementFromPoint(a, b); if (h.win.opera && e.tagName == "svg") { var f = cb(d), g = d.createSVGRect(); g.x = a - f.x, g.y = b - f.y, g.width = g.height = 1; var i = d.getIntersectionList(g, null); i.length && (e = i[i.length - 1]) } if (!e) return null; while (e.parentNode && e != d.parentNode && !e.raphael) e = e.parentNode; e == c.canvas.parentNode && (e = d), e = e && e.raphael ? c.getById(e.raphaelid) : null; return e }, k.getById = function (a) { var b = this.bottom; while (b) { if (b.id == a) return b; b = b.next } return null }, k.forEach = function (a, b) { var c = this.bottom; while (c) { if (a.call(b, c) === !1) return this; c = c.next } return this }, b$.getBBox = function (a) { if (this.removed) return {}; var b = this._; if (a) { if (b.dirty || !b.bboxwt) this.realPath = bh[this.type](this), b.bboxwt = bx(this.realPath), b.bboxwt.toString = cd, b.dirty = 0; return b.bboxwt } if (b.dirty || b.dirtyT || !b.bbox) { if (b.dirty || !this.realPath) b.bboxwt = 0, this.realPath = bh[this.type](this); b.bbox = bx(bi(this.realPath, this.matrix)), b.bbox.toString = cd, b.dirty = b.dirtyT = 0 } return b.bbox }, b$.clone = function () { if (this.removed) return null; var a = this.paper[this.type]().attr(this.attr()); this.__set__ && this.__set__.push(a); return a }, b$.glow = function (a) { if (this.type == "text") return null; a = a || {}; var b = { width: (a.width || 10) + (+this.attr("stroke-width") || 1), fill: a.fill || !1, opacity: a.opacity || .5, offsetx: a.offsetx || 0, offsety: a.offsety || 0, color: a.color || "#000" }, c = b.width / 2, d = this.paper, e = d.set(), f = this.realPath || bh[this.type](this); f = this.matrix ? bi(f, this.matrix) : f; for (var g = 1; g < c + 1; g++) e.push(d.path(f).attr({ stroke: b.color, fill: b.fill ? b.color : "none", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": +(b.width / c * g).toFixed(3), opacity: +(b.opacity / c).toFixed(3) })); return e.insertBefore(this).translate(b.offsetx, b.offsety) }; var ce = {}, cf = function (b, c, d, e, f, g, h, i, j) { var k = 0, l = 100, m = [b, c, d, e, f, g, h, i].join(), n = ce[m], o, p; !n && (ce[m] = n = { data: [] }), n.timer && clearTimeout(n.timer), n.timer = setTimeout(function () { delete ce[m] }, 2e3); if (j != null && !n.precision) { var q = cf(b, c, d, e, f, g, h, i); n.precision = ~ ~q * 10, n.data = [] } l = n.precision || l; for (var r = 0; r < l + 1; r++) { n.data[r * l] ? p = n.data[r * l] : (p = a.findDotsAtSegment(b, c, d, e, f, g, h, i, r / l), n.data[r * l] = p), r && (k += A(A(o.x - p.x, 2) + A(o.y - p.y, 2), .5)); if (j != null && k >= j) return p; o = p } if (j == null) return k }, cg = function (b, c) { return function (d, e, f) { d = bG(d); var g, h, i, j, k = "", l = {}, m, n = 0; for (var o = 0, p = d.length; o < p; o++) { i = d[o]; if (i[0] == "M") g = +i[1], h = +i[2]; else { j = cf(g, h, i[1], i[2], i[3], i[4], i[5], i[6]); if (n + j > e) { if (c && !l.start) { m = cf(g, h, i[1], i[2], i[3], i[4], i[5], i[6], e - n), k += ["C" + m.start.x, m.start.y, m.m.x, m.m.y, m.x, m.y]; if (f) return k; l.start = k, k = ["M" + m.x, m.y + "C" + m.n.x, m.n.y, m.end.x, m.end.y, i[5], i[6]].join(), n += j, g = +i[5], h = +i[6]; continue } if (!b && !c) { m = cf(g, h, i[1], i[2], i[3], i[4], i[5], i[6], e - n); return { x: m.x, y: m.y, alpha: m.alpha} } } n += j, g = +i[5], h = +i[6] } k += i.shift() + i } l.end = k, m = b ? n : c ? l : a.findDotsAtSegment(g, h, i[0], i[1], i[2], i[3], i[4], i[5], 1), m.alpha && (m = { x: m.x, y: m.y, alpha: m.alpha }); return m } }, ch = cg(1), ci = cg(), cj = cg(0, 1); a.getTotalLength = ch, a.getPointAtLength = ci, a.getSubpath = function (a, b, c) { if (this.getTotalLength(a) - c < 1e-6) return cj(a, b).end; var d = cj(a, c, 1); return b ? cj(d, b).end : d }, b$.getTotalLength = function () { if (this.type == "path") { if (this.node.getTotalLength) return this.node.getTotalLength(); return ch(this.attrs.path) } }, b$.getPointAtLength = function (a) { if (this.type == "path") return ci(this.attrs.path, a) }, b$.getSubpath = function (b, c) { if (this.type == "path") return a.getSubpath(this.attrs.path, b, c) }; var ck = a.easing_formulas = { linear: function (a) { return a }, "<": function (a) { return A(a, 1.7) }, ">": function (a) { return A(a, .48) }, "<>": function (a) { var b = .48 - a / 1.04, c = w.sqrt(.1734 + b * b), d = c - b, e = A(z(d), 1 / 3) * (d < 0 ? -1 : 1), f = -c - b, g = A(z(f), 1 / 3) * (f < 0 ? -1 : 1), h = e + g + .5; return (1 - h) * 3 * h * h + h * h * h }, backIn: function (a) { var b = 1.70158; return a * a * ((b + 1) * a - b) }, backOut: function (a) { a = a - 1; var b = 1.70158; return a * a * ((b + 1) * a + b) + 1 }, elastic: function (a) { if (a == !!a) return a; return A(2, -10 * a) * w.sin((a - .075) * 2 * B / .3) + 1 }, bounce: function (a) { var b = 7.5625, c = 2.75, d; a < 1 / c ? d = b * a * a : a < 2 / c ? (a -= 1.5 / c, d = b * a * a + .75) : a < 2.5 / c ? (a -= 2.25 / c, d = b * a * a + .9375) : (a -= 2.625 / c, d = b * a * a + .984375); return d } }; ck.easeIn = ck["ease-in"] = ck["<"], ck.easeOut = ck["ease-out"] = ck[">"], ck.easeInOut = ck["ease-in-out"] = ck["<>"], ck["back-in"] = ck.backIn, ck["back-out"] = ck.backOut; var cl = [], cm = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (a) { setTimeout(a, 16) }, cn = function () { var b = +(new Date), c = 0; for (; c < cl.length; c++) { var d = cl[c]; if (d.el.removed || d.paused) continue; var e = b - d.start, f = d.ms, h = d.easing, i = d.from, j = d.diff, k = d.to, l = d.t, m = d.el, o = {}, p, r = {}, s; d.initstatus ? (e = (d.initstatus * d.anim.top - d.prev) / (d.percent - d.prev) * f, d.status = d.initstatus, delete d.initstatus, d.stop && cl.splice(c--, 1)) : d.status = (d.prev + (d.percent - d.prev) * (e / f)) / d.anim.top; if (e < 0) continue; if (e < f) { var t = h(e / f); for (var u in i) if (i[g](u)) { switch (U[u]) { case C: p = +i[u] + t * f * j[u]; break; case "colour": p = "rgb(" + [co(O(i[u].r + t * f * j[u].r)), co(O(i[u].g + t * f * j[u].g)), co(O(i[u].b + t * f * j[u].b))].join(",") + ")"; break; case "path": p = []; for (var v = 0, w = i[u].length; v < w; v++) { p[v] = [i[u][v][0]]; for (var x = 1, y = i[u][v].length; x < y; x++) p[v][x] = +i[u][v][x] + t * f * j[u][v][x]; p[v] = p[v].join(q) } p = p.join(q); break; case "transform": if (j[u].real) { p = []; for (v = 0, w = i[u].length; v < w; v++) { p[v] = [i[u][v][0]]; for (x = 1, y = i[u][v].length; x < y; x++) p[v][x] = i[u][v][x] + t * f * j[u][v][x] } } else { var z = function (a) { return +i[u][a] + t * f * j[u][a] }; p = [["m", z(0), z(1), z(2), z(3), z(4), z(5)]] } break; case "csv": if (u == "clip-rect") { p = [], v = 4; while (v--) p[v] = +i[u][v] + t * f * j[u][v] } break; default: var A = [][n](i[u]); p = [], v = m.paper.customAttributes[u].length; while (v--) p[v] = +A[v] + t * f * j[u][v] } o[u] = p } m.attr(o), function (a, b, c) { setTimeout(function () { eve("anim.frame." + a, b, c) }) } (m.id, m, d.anim) } else { (function (b, c, d) { setTimeout(function () { eve("anim.frame." + c.id, c, d), eve("anim.finish." + c.id, c, d), a.is(b, "function") && b.call(c) }) })(d.callback, m, d.anim), m.attr(k), cl.splice(c--, 1); if (d.repeat > 1 && !d.next) { for (s in k) k[g](s) && (r[s] = d.totalOrigin[s]); d.el.attr(r), cr(d.anim, d.el, d.anim.percents[0], null, d.totalOrigin, d.repeat - 1) } d.next && !d.stop && cr(d.anim, d.el, d.next, null, d.totalOrigin, d.repeat) } } a.svg && m && m.paper && m.paper.safari(), cl.length && cm(cn) }, co = function (a) { return a > 255 ? 255 : a < 0 ? 0 : a }; b$.animateWith = function (b, c, d, e, f, g) { var h = d ? a.animation(d, e, f, g) : c, i = b.status(c); return this.animate(h).status(h, i * c.ms / h.ms) }, b$.onAnimation = function (a) { a ? eve.on("anim.frame." + this.id, a) : eve.unbind("anim.frame." + this.id); return this }, cq.prototype.delay = function (a) { var b = new cq(this.anim, this.ms); b.times = this.times, b.del = +a || 0; return b }, cq.prototype.repeat = function (a) { var b = new cq(this.anim, this.ms); b.del = this.del, b.times = w.floor(x(a, 0)) || 1; return b }, a.animation = function (b, c, d, e) { if (b instanceof cq) return b; if (a.is(d, "function") || !d) e = e || d || null, d = null; b = Object(b), c = +c || 0; var f = {}, h, i; for (i in b) b[g](i) && Q(i) != i && Q(i) + "%" != i && (h = !0, f[i] = b[i]); if (!h) return new cq(b, c); d && (f.easing = d), e && (f.callback = e); return new cq({ 100: f }, c) }, b$.animate = function (b, c, d, e) { var f = this; if (f.removed) { e && e.call(f); return f } var g = b instanceof cq ? b : a.animation(b, c, d, e); cr(g, f, g.percents[0], null, f.attr()); return f }, b$.setTime = function (a, b) { a && b != null && this.status(a, y(b, a.ms) / a.ms); return this }, b$.status = function (a, b) { var c = [], d = 0, e, f; if (b != null) { cr(a, this, -1, y(b, 1)); return this } e = cl.length; for (; d < e; d++) { f = cl[d]; if (f.el.id == this.id && (!a || f.anim == a)) { if (a) return f.status; c.push({ anim: f.anim, status: f.status }) } } if (a) return 0; return c }, b$.pause = function (a) { for (var b = 0; b < cl.length; b++) cl[b].el.id == this.id && (!a || cl[b].anim == a) && eve("anim.pause." + this.id, this, cl[b].anim) !== !1 && (cl[b].paused = !0); return this }, b$.resume = function (a) { for (var b = 0; b < cl.length; b++) if (cl[b].el.id == this.id && (!a || cl[b].anim == a)) { var c = cl[b]; eve("anim.resume." + this.id, this, c.anim) !== !1 && (delete c.paused, this.status(c.anim, c.status)) } return this }, b$.stop = function (a) { for (var b = 0; b < cl.length; b++) cl[b].el.id == this.id && (!a || cl[b].anim == a) && eve("anim.stop." + this.id, this, cl[b].anim) !== !1 && cl.splice(b--, 1); return this }, b$.toString = function () { return "Raphaël’s object" }; var cs = function (a) { this.items = [], this.length = 0, this.type = "set"; if (a) for (var b = 0, c = a.length; b < c; b++) a[b] && (a[b].constructor == b$.constructor || a[b].constructor == cs) && (this[this.items.length] = this.items[this.items.length] = a[b], this.length++) }, ct = cs.prototype; ct.push = function () { var a, b; for (var c = 0, d = arguments.length; c < d; c++) a = arguments[c], a && (a.constructor == b$.constructor || a.constructor == cs) && (b = this.items.length, this[b] = this.items[b] = a, this.length++); return this }, ct.pop = function () { this.length && delete this[this.length--]; return this.items.pop() }, ct.forEach = function (a, b) { for (var c = 0, d = this.items.length; c < d; c++) if (a.call(b, this.items[c], c) === !1) return this; return this }; for (var cu in b$) b$[g](cu) && (ct[cu] = function (a) { return function () { var b = arguments; return this.forEach(function (c) { c[a][m](c, b) }) } } (cu)); ct.attr = function (b, c) { if (b && a.is(b, E) && a.is(b[0], "object")) for (var d = 0, e = b.length; d < e; d++) this.items[d].attr(b[d]); else for (var f = 0, g = this.items.length; f < g; f++) this.items[f].attr(b, c); return this }, ct.clear = function () { while (this.length) this.pop() }, ct.splice = function (a, b, c) { a = a < 0 ? x(this.length + a, 0) : a, b = x(0, y(this.length - a, b)); var d = [], e = [], f = [], g; for (g = 2; g < arguments.length; g++) f.push(arguments[g]); for (g = 0; g < b; g++) e.push(this[a + g]); for (; g < this.length - a; g++) d.push(this[a + g]); var h = f.length; for (g = 0; g < h + d.length; g++) this.items[a + g] = this[a + g] = g < h ? f[g] : d[g - h]; g = this.items.length = this.length -= b - h; while (this[g]) delete this[g++]; return new cs(e) }, ct.exclude = function (a) { for (var b = 0, c = this.length; b < c; b++) if (this[b] == a) { this.splice(b, 1); return !0 } }, ct.animate = function (b, c, d, e) { (a.is(d, "function") || !d) && (e = d || null); var f = this.items.length, g = f, h, i = this, j; if (!f) return this; e && (j = function () { ! --f && e.call(i) }), d = a.is(d, D) ? d : j; var k = a.animation(b, c, d, j); h = this.items[--g].animate(k); while (g--) this.items[g] && !this.items[g].removed && this.items[g].animateWith(h, k); return this }, ct.insertAfter = function (a) { var b = this.items.length; while (b--) this.items[b].insertAfter(a); return this }, ct.getBBox = function () { var a = [], b = [], c = [], d = []; for (var e = this.items.length; e--; ) if (!this.items[e].removed) { var f = this.items[e].getBBox(); a.push(f.x), b.push(f.y), c.push(f.x + f.width), d.push(f.y + f.height) } a = y[m](0, a), b = y[m](0, b); return { x: a, y: b, width: x[m](0, c) - a, height: x[m](0, d) - b} }, ct.clone = function (a) { a = new cs; for (var b = 0, c = this.items.length; b < c; b++) a.push(this.items[b].clone()); return a }, ct.toString = function () { return "Raphaël‘s set" }, a.registerFont = function (a) { if (!a.face) return a; this.fonts = this.fonts || {}; var b = { w: a.w, face: {}, glyphs: {} }, c = a.face["font-family"]; for (var d in a.face) a.face[g](d) && (b.face[d] = a.face[d]); this.fonts[c] ? this.fonts[c].push(b) : this.fonts[c] = [b]; if (!a.svg) { b.face["units-per-em"] = R(a.face["units-per-em"], 10); for (var e in a.glyphs) if (a.glyphs[g](e)) { var f = a.glyphs[e]; b.glyphs[e] = { w: f.w, k: {}, d: f.d && "M" + f.d.replace(/[mlcxtrv]/g, function (a) { return { l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[a] || "M" }) + "z" }; if (f.k) for (var h in f.k) f[g](h) && (b.glyphs[e].k[h] = f.k[h]) } } return a }, k.getFont = function (b, c, d, e) { e = e || "normal", d = d || "normal", c = +c || { normal: 400, bold: 700, lighter: 300, bolder: 800}[c] || 400; if (!!a.fonts) { var f = a.fonts[b]; if (!f) { var h = new RegExp("(^|\\s)" + b.replace(/[^\w\d\s+!~.:_-]/g, p) + "(\\s|$)", "i"); for (var i in a.fonts) if (a.fonts[g](i) && h.test(i)) { f = a.fonts[i]; break } } var j; if (f) for (var k = 0, l = f.length; k < l; k++) { j = f[k]; if (j.face["font-weight"] == c && (j.face["font-style"] == d || !j.face["font-style"]) && j.face["font-stretch"] == e) break } return j } }, k.print = function (b, d, e, f, g, h, i) { h = h || "middle", i = x(y(i || 0, 1), -1); var j = this.set(), k = r(e)[s](p), l = 0, m = p, n; a.is(f, e) && (f = this.getFont(f)); if (f) { n = (g || 16) / f.face["units-per-em"]; var o = f.face.bbox[s](c), q = +o[0], t = +o[1] + (h == "baseline" ? o[3] - o[1] + +f.face.descent : (o[3] - o[1]) / 2); for (var u = 0, v = k.length; u < v; u++) { var w = u && f.glyphs[k[u - 1]] || {}, z = f.glyphs[k[u]]; l += u ? (w.w || f.w) + (w.k && w.k[k[u]] || 0) + f.w * i : 0, z && z.d && j.push(this.path(z.d).attr({ fill: "#000", stroke: "none", transform: [["t", l * n, 0]] })) } j.transform(["...s", n, n, q, t, "t", (b - q) / n, (d - t) / n]) } return j }, k.add = function (b) { if (a.is(b, "array")) { var c = this.set(), e = 0, f = b.length, h; for (; e < f; e++) h = b[e] || {}, d[g](h.type) && c.push(this[h.type]().attr(h)) } return c }, a.format = function (b, c) { var d = a.is(c, E) ? [0][n](c) : arguments; b && a.is(b, D) && d.length - 1 && (b = b.replace(e, function (a, b) { return d[++b] == null ? p : d[b] })); return b || p }, a.fullfill = function () { var a = /\{([^\}]+)\}/g, b = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g, c = function (a, c, d) { var e = d; c.replace(b, function (a, b, c, d, f) { b = b || d, e && (b in e && (e = e[b]), typeof e == "function" && f && (e = e())) }), e = (e == null || e == d ? a : e) + ""; return e }; return function (b, d) { return String(b).replace(a, function (a, b) { return c(a, b, d) }) } } (), a.ninja = function () { i.was ? h.win.Raphael = i.is : delete Raphael; return a }, a.st = ct, function (b, c, d) { function e() { /in/.test(b.readyState) ? setTimeout(e, 9) : a.eve("DOMload") } b.readyState == null && b.addEventListener && (b.addEventListener(c, d = function () { b.removeEventListener(c, d, !1), b.readyState = "complete" }, !1), b.readyState = "loading"), e() } (document, "DOMContentLoaded"), i.was ? h.win.Raphael = a : Raphael = a, eve.on("DOMload", function () { b = !0 }) } (), window.Raphael.svg && function (a) { var b = "hasOwnProperty", c = String, d = parseFloat, e = parseInt, f = Math, g = f.max, h = f.abs, i = f.pow, j = /[, ]+/, k = a.eve, l = "", m = " ", n = "http://www.w3.org/1999/xlink", o = { block: "M5,0 0,2.5 5,5z", classic: "M5,0 0,2.5 5,5 3.5,3 3.5,2z", diamond: "M2.5,0 5,2.5 2.5,5 0,2.5z", open: "M6,1 1,3.5 6,6", oval: "M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z" }, p = {}; a.toString = function () { return "Your browser supports SVG.\nYou are running Raphaël " + this.version }; var q = function (d, e) { if (e) { typeof d == "string" && (d = q(d)); for (var f in e) e[b](f) && (f.substring(0, 6) == "xlink:" ? d.setAttributeNS(n, f.substring(6), c(e[f])) : d.setAttribute(f, c(e[f]))) } else d = a._g.doc.createElementNS("http://www.w3.org/2000/svg", d), d.style && (d.style.webkitTapHighlightColor = "rgba(0,0,0,0)"); return d }, r = function (b, e) { var j = "linear", k = b.id + e, m = .5, n = .5, o = b.node, p = b.paper, r = o.style, s = a._g.doc.getElementById(k); if (!s) { e = c(e).replace(a._radial_gradient, function (a, b, c) { j = "radial"; if (b && c) { m = d(b), n = d(c); var e = (n > .5) * 2 - 1; i(m - .5, 2) + i(n - .5, 2) > .25 && (n = f.sqrt(.25 - i(m - .5, 2)) * e + .5) && n != .5 && (n = n.toFixed(5) - 1e-5 * e) } return l }), e = e.split(/\s*\-\s*/); if (j == "linear") { var t = e.shift(); t = -d(t); if (isNaN(t)) return null; var u = [0, 0, f.cos(a.rad(t)), f.sin(a.rad(t))], v = 1 / (g(h(u[2]), h(u[3])) || 1); u[2] *= v, u[3] *= v, u[2] < 0 && (u[0] = -u[2], u[2] = 0), u[3] < 0 && (u[1] = -u[3], u[3] = 0) } var w = a._parseDots(e); if (!w) return null; k = k.replace(/[\(\)\s,\xb0#]/g, "_"), b.gradient && k != b.gradient.id && (p.defs.removeChild(b.gradient), delete b.gradient); if (!b.gradient) { s = q(j + "Gradient", { id: k }), b.gradient = s, q(s, j == "radial" ? { fx: m, fy: n} : { x1: u[0], y1: u[1], x2: u[2], y2: u[3], gradientTransform: b.matrix.invert() }), p.defs.appendChild(s); for (var x = 0, y = w.length; x < y; x++) s.appendChild(q("stop", { offset: w[x].offset ? w[x].offset : x ? "100%" : "0%", "stop-color": w[x].color || "#fff" })) } } q(o, { fill: "url(#" + k + ")", opacity: 1, "fill-opacity": 1 }), r.fill = l, r.opacity = 1, r.fillOpacity = 1; return 1 }, s = function (a) { var b = a.getBBox(1); q(a.pattern, { patternTransform: a.matrix.invert() + " translate(" + b.x + "," + b.y + ")" }) }, t = function (d, e, f) { if (d.type == "path") { var g = c(e).toLowerCase().split("-"), h = d.paper, i = f ? "end" : "start", j = d.node, k = d.attrs, l = k["stroke-width"], n = g.length, r = "classic", s, t, u, v, w, x = 3, y = 3, z = 5; while (n--) switch (g[n]) { case "block": case "classic": case "oval": case "diamond": case "open": case "none": r = g[n]; break; case "wide": y = 5; break; case "narrow": y = 2; break; case "long": x = 5; break; case "short": x = 2 } r == "open" ? (x += 2, y += 2, z += 2, u = 1, v = f ? 4 : 1, w = { fill: "none", stroke: k.stroke }) : (v = u = x / 2, w = { fill: k.stroke, stroke: "none" }), d._.arrows ? f ? (d._.arrows.endPath && p[d._.arrows.endPath]--, d._.arrows.endMarker && p[d._.arrows.endMarker]--) : (d._.arrows.startPath && p[d._.arrows.startPath]--, d._.arrows.startMarker && p[d._.arrows.startMarker]--) : d._.arrows = {}; if (r != "none") { var A = "raphael-marker-" + r, B = "raphael-marker-" + i + r + x + y; a._g.doc.getElementById(A) ? p[A]++ : (h.defs.appendChild(q(q("path"), { "stroke-linecap": "round", d: o[r], id: A })), p[A] = 1); var C = a._g.doc.getElementById(B), D; C ? (p[B]++, D = C.getElementsByTagName("use")[0]) : (C = q(q("marker"), { id: B, markerHeight: y, markerWidth: x, orient: "auto", refX: v, refY: y / 2 }), D = q(q("use"), { "xlink:href": "#" + A, transform: (f ? " rotate(180 " + x / 2 + " " + y / 2 + ") " : m) + "scale(" + x / z + "," + y / z + ")", "stroke-width": 1 / ((x / z + y / z) / 2) }), C.appendChild(D), h.defs.appendChild(C), p[B] = 1), q(D, w); var E = u * (r != "diamond" && r != "oval"); f ? (s = d._.arrows.startdx * l || 0, t = a.getTotalLength(k.path) - E * l) : (s = E * l, t = a.getTotalLength(k.path) - (d._.arrows.enddx * l || 0)), w = {}, w["marker-" + i] = "url(#" + B + ")"; if (t || s) w.d = Raphael.getSubpath(k.path, s, t); q(j, w), d._.arrows[i + "Path"] = A, d._.arrows[i + "Marker"] = B, d._.arrows[i + "dx"] = E, d._.arrows[i + "Type"] = r, d._.arrows[i + "String"] = e } else f ? (s = d._.arrows.startdx * l || 0, t = a.getTotalLength(k.path) - s) : (s = 0, t = a.getTotalLength(k.path) - (d._.arrows.enddx * l || 0)), d._.arrows[i + "Path"] && q(j, { d: Raphael.getSubpath(k.path, s, t) }), delete d._.arrows[i + "Path"], delete d._.arrows[i + "Marker"], delete d._.arrows[i + "dx"], delete d._.arrows[i + "Type"], delete d._.arrows[i + "String"]; for (w in p) if (p[b](w) && !p[w]) { var F = a._g.doc.getElementById(w); F && F.parentNode.removeChild(F) } } }, u = { "": [0], none: [0], "-": [3, 1], ".": [1, 1], "-.": [3, 1, 1, 1], "-..": [3, 1, 1, 1, 1, 1], ". ": [1, 3], "- ": [4, 3], "--": [8, 3], "- .": [4, 3, 1, 3], "--.": [8, 3, 1, 3], "--..": [8, 3, 1, 3, 1, 3] }, v = function (a, b, d) { b = u[c(b).toLowerCase()]; if (b) { var e = a.attrs["stroke-width"] || "1", f = { round: e, square: e, butt: 0}[a.attrs["stroke-linecap"] || d["stroke-linecap"]] || 0, g = [], h = b.length; while (h--) g[h] = b[h] * e + (h % 2 ? 1 : -1) * f; q(a.node, { "stroke-dasharray": g.join(",") }) } }, w = function (d, f) { var i = d.node, k = d.attrs, m = i.style.visibility; i.style.visibility = "hidden"; for (var o in f) if (f[b](o)) { if (!a._availableAttrs[b](o)) continue; var p = f[o]; k[o] = p; switch (o) { case "blur": d.blur(p); break; case "href": case "title": case "target": var u = i.parentNode; if (u.tagName.toLowerCase() != "a") { var w = q("a"); u.insertBefore(w, i), w.appendChild(i), u = w } o == "target" && p == "blank" ? u.setAttributeNS(n, "show", "new") : u.setAttributeNS(n, o, p); break; case "cursor": i.style.cursor = p; break; case "transform": d.transform(p); break; case "arrow-start": t(d, p); break; case "arrow-end": t(d, p, 1); break; case "clip-rect": var x = c(p).split(j); if (x.length == 4) { d.clip && d.clip.parentNode.parentNode.removeChild(d.clip.parentNode); var z = q("clipPath"), A = q("rect"); z.id = a.createUUID(), q(A, { x: x[0], y: x[1], width: x[2], height: x[3] }), z.appendChild(A), d.paper.defs.appendChild(z), q(i, { "clip-path": "url(#" + z.id + ")" }), d.clip = A } if (!p) { var B = i.getAttribute("clip-path"); if (B) { var C = a._g.doc.getElementById(B.replace(/(^url\(#|\)$)/g, l)); C && C.parentNode.removeChild(C), q(i, { "clip-path": l }), delete d.clip } } break; case "path": d.type == "path" && (q(i, { d: p ? k.path = a._pathToAbsolute(p) : "M0,0" }), d._.dirty = 1, d._.arrows && ("startString" in d._.arrows && t(d, d._.arrows.startString), "endString" in d._.arrows && t(d, d._.arrows.endString, 1))); break; case "width": i.setAttribute(o, p), d._.dirty = 1; if (k.fx) o = "x", p = k.x; else break; case "x": k.fx && (p = -k.x - (k.width || 0)); case "rx": if (o == "rx" && d.type == "rect") break; case "cx": i.setAttribute(o, p), d.pattern && s(d), d._.dirty = 1; break; case "height": i.setAttribute(o, p), d._.dirty = 1; if (k.fy) o = "y", p = k.y; else break; case "y": k.fy && (p = -k.y - (k.height || 0)); case "ry": if (o == "ry" && d.type == "rect") break; case "cy": i.setAttribute(o, p), d.pattern && s(d), d._.dirty = 1; break; case "r": d.type == "rect" ? q(i, { rx: p, ry: p }) : i.setAttribute(o, p), d._.dirty = 1; break; case "src": d.type == "image" && i.setAttributeNS(n, "href", p); break; case "stroke-width": if (d._.sx != 1 || d._.sy != 1) p /= g(h(d._.sx), h(d._.sy)) || 1; d.paper._vbSize && (p *= d.paper._vbSize), i.setAttribute(o, p), k["stroke-dasharray"] && v(d, k["stroke-dasharray"], f), d._.arrows && ("startString" in d._.arrows && t(d, d._.arrows.startString), "endString" in d._.arrows && t(d, d._.arrows.endString, 1)); break; case "stroke-dasharray": v(d, p, f); break; case "fill": var D = c(p).match(a._ISURL); if (D) { z = q("pattern"); var F = q("image"); z.id = a.createUUID(), q(z, { x: 0, y: 0, patternUnits: "userSpaceOnUse", height: 1, width: 1 }), q(F, { x: 0, y: 0, "xlink:href": D[1] }), z.appendChild(F), function (b) { a._preload(D[1], function () { var a = this.offsetWidth, c = this.offsetHeight; q(b, { width: a, height: c }), q(F, { width: a, height: c }), d.paper.safari() }) } (z), d.paper.defs.appendChild(z), i.style.fill = "url(#" + z.id + ")", q(i, { fill: "url(#" + z.id + ")" }), d.pattern = z, d.pattern && s(d); break } var G = a.getRGB(p); if (!G.error) delete f.gradient, delete k.gradient, !a.is(k.opacity, "undefined") && a.is(f.opacity, "undefined") && q(i, { opacity: k.opacity }), !a.is(k["fill-opacity"], "undefined") && a.is(f["fill-opacity"], "undefined") && q(i, { "fill-opacity": k["fill-opacity"] }); else if ((d.type == "circle" || d.type == "ellipse" || c(p).charAt() != "r") && r(d, p)) { if ("opacity" in k || "fill-opacity" in k) { var H = a._g.doc.getElementById(i.getAttribute("fill").replace(/^url\(#|\)$/g, l)); if (H) { var I = H.getElementsByTagName("stop"); q(I[I.length - 1], { "stop-opacity": ("opacity" in k ? k.opacity : 1) * ("fill-opacity" in k ? k["fill-opacity"] : 1) }) } } k.gradient = p, k.fill = "none"; break } G[b]("opacity") && q(i, { "fill-opacity": G.opacity > 1 ? G.opacity / 100 : G.opacity }); case "stroke": G = a.getRGB(p), i.setAttribute(o, G.hex), o == "stroke" && G[b]("opacity") && q(i, { "stroke-opacity": G.opacity > 1 ? G.opacity / 100 : G.opacity }), o == "stroke" && d._.arrows && ("startString" in d._.arrows && t(d, d._.arrows.startString), "endString" in d._.arrows && t(d, d._.arrows.endString, 1)); break; case "gradient": (d.type == "circle" || d.type == "ellipse" || c(p).charAt() != "r") && r(d, p); break; case "opacity": k.gradient && !k[b]("stroke-opacity") && q(i, { "stroke-opacity": p > 1 ? p / 100 : p }); case "fill-opacity": if (k.gradient) { H = a._g.doc.getElementById(i.getAttribute("fill").replace(/^url\(#|\)$/g, l)), H && (I = H.getElementsByTagName("stop"), q(I[I.length - 1], { "stop-opacity": p })); break }; default: o == "font-size" && (p = e(p, 10) + "px"); var J = o.replace(/(\-.)/g, function (a) { return a.substring(1).toUpperCase() }); i.style[J] = p, d._.dirty = 1, i.setAttribute(o, p) } } y(d, f), i.style.visibility = m }, x = 1.2, y = function (d, f) { if (d.type == "text" && !!(f[b]("text") || f[b]("font") || f[b]("font-size") || f[b]("x") || f[b]("y"))) { var g = d.attrs, h = d.node, i = h.firstChild ? e(a._g.doc.defaultView.getComputedStyle(h.firstChild, l).getPropertyValue("font-size"), 10) : 10; if (f[b]("text")) { g.text = f.text; while (h.firstChild) h.removeChild(h.firstChild); var j = c(f.text).split("\n"), k = [], m; for (var n = 0, o = j.length; n < o; n++) m = q("tspan"), n && q(m, { dy: i * x, x: g.x }), m.appendChild(a._g.doc.createTextNode(j[n])), h.appendChild(m), k[n] = m } else { k = h.getElementsByTagName("tspan"); for (n = 0, o = k.length; n < o; n++) n ? q(k[n], { dy: i * x, x: g.x }) : q(k[0], { dy: 0 }) } q(h, { x: g.x, y: g.y }), d._.dirty = 1; var p = d._getBBox(), r = g.y - (p.y + p.height / 2); r && a.is(r, "finite") && q(k[0], { dy: r }) } }, z = function (b, c) { var d = 0, e = 0; this[0] = this.node = b, b.raphael = !0, this.id = a._oid++, b.raphaelid = this.id, this.matrix = a.matrix(), this.realPath = null, this.paper = c, this.attrs = this.attrs || {}, this._ = { transform: [], sx: 1, sy: 1, deg: 0, dx: 0, dy: 0, dirty: 1 }, !c.bottom && (c.bottom = this), this.prev = c.top, c.top && (c.top.next = this), c.top = this, this.next = null }, A = a.el; z.prototype = A, A.constructor = z, a._engine.path = function (a, b) { var c = q("path"); b.canvas && b.canvas.appendChild(c); var d = new z(c, b); d.type = "path", w(d, { fill: "none", stroke: "#000", path: a }); return d }, A.rotate = function (a, b, e) { if (this.removed) return this; a = c(a).split(j), a.length - 1 && (b = d(a[1]), e = d(a[2])), a = d(a[0]), e == null && (b = e); if (b == null || e == null) { var f = this.getBBox(1); b = f.x + f.width / 2, e = f.y + f.height / 2 } this.transform(this._.transform.concat([["r", a, b, e]])); return this }, A.scale = function (a, b, e, f) { if (this.removed) return this; a = c(a).split(j), a.length - 1 && (b = d(a[1]), e = d(a[2]), f = d(a[3])), a = d(a[0]), b == null && (b = a), f == null && (e = f); if (e == null || f == null) var g = this.getBBox(1); e = e == null ? g.x + g.width / 2 : e, f = f == null ? g.y + g.height / 2 : f, this.transform(this._.transform.concat([["s", a, b, e, f]])); return this }, A.translate = function (a, b) { if (this.removed) return this; a = c(a).split(j), a.length - 1 && (b = d(a[1])), a = d(a[0]) || 0, b = +b || 0, this.transform(this._.transform.concat([["t", a, b]])); return this }, A.transform = function (c) { var d = this._; if (c == null) return d.transform; a._extractTransform(this, c), this.clip && q(this.clip, { transform: this.matrix.invert() }), this.pattern && s(this), this.node && q(this.node, { transform: this.matrix }); if (d.sx != 1 || d.sy != 1) { var e = this.attrs[b]("stroke-width") ? this.attrs["stroke-width"] : 1; this.attr({ "stroke-width": e }) } return this }, A.hide = function () { !this.removed && this.paper.safari(this.node.style.display = "none"); return this }, A.show = function () { !this.removed && this.paper.safari(this.node.style.display = ""); return this }, A.remove = function () { if (!this.removed) { var b = this.paper; b.__set__ && b.__set__.exclude(this), k.unbind("*.*." + this.id), this.gradient && b.defs.removeChild(this.gradient), a._tear(this, b), this.node.parentNode.removeChild(this.node); for (var c in this) this[c] = typeof this[c] == "function" ? a._removedFactory(c) : null; this.removed = !0 } }, A._getBBox = function () { if (this.node.style.display == "none") { this.show(); var a = !0 } var b = {}; try { b = this.node.getBBox() } catch (c) { } finally { b = b || {} } a && this.hide(); return b }, A.attr = function (c, d) { if (this.removed) return this; if (c == null) { var e = {}; for (var f in this.attrs) this.attrs[b](f) && (e[f] = this.attrs[f]); e.gradient && e.fill == "none" && (e.fill = e.gradient) && delete e.gradient, e.transform = this._.transform; return e } if (d == null && a.is(c, "string")) { if (c == "fill" && this.attrs.fill == "none" && this.attrs.gradient) return this.attrs.gradient; if (c == "transform") return this._.transform; var g = c.split(j), h = {}; for (var i = 0, l = g.length; i < l; i++) c = g[i], c in this.attrs ? h[c] = this.attrs[c] : a.is(this.paper.customAttributes[c], "function") ? h[c] = this.paper.customAttributes[c].def : h[c] = a._availableAttrs[c]; return l - 1 ? h : h[g[0]] } if (d == null && a.is(c, "array")) { h = {}; for (i = 0, l = c.length; i < l; i++) h[c[i]] = this.attr(c[i]); return h } if (d != null) { var m = {}; m[c] = d } else c != null && a.is(c, "object") && (m = c); for (var n in m) k("attr." + n + "." + this.id, this, m[n]); for (n in this.paper.customAttributes) if (this.paper.customAttributes[b](n) && m[b](n) && a.is(this.paper.customAttributes[n], "function")) { var o = this.paper.customAttributes[n].apply(this, [].concat(m[n])); this.attrs[n] = m[n]; for (var p in o) o[b](p) && (m[p] = o[p]) } w(this, m); return this }, A.toFront = function () { if (this.removed) return this; this.node.parentNode.tagName.toLowerCase() == "a" ? this.node.parentNode.parentNode.appendChild(this.node.parentNode) : this.node.parentNode.appendChild(this.node); var b = this.paper; b.top != this && a._tofront(this, b); return this }, A.toBack = function () { if (this.removed) return this; var b = this.node.parentNode; b.tagName.toLowerCase() == "a" ? b.parentNode.insertBefore(this.node.parentNode, this.node.parentNode.parentNode.firstChild) : b.firstChild != this.node && b.insertBefore(this.node, this.node.parentNode.firstChild), a._toback(this, this.paper); var c = this.paper; return this }, A.insertAfter = function (b) { if (this.removed) return this; var c = b.node || b[b.length - 1].node; c.nextSibling ? c.parentNode.insertBefore(this.node, c.nextSibling) : c.parentNode.appendChild(this.node), a._insertafter(this, b, this.paper); return this }, A.insertBefore = function (b) { if (this.removed) return this; var c = b.node || b[0].node; c.parentNode.insertBefore(this.node, c), a._insertbefore(this, b, this.paper); return this }, A.blur = function (b) { var c = this; if (+b !== 0) { var d = q("filter"), e = q("feGaussianBlur"); c.attrs.blur = b, d.id = a.createUUID(), q(e, { stdDeviation: +b || 1.5 }), d.appendChild(e), c.paper.defs.appendChild(d), c._blur = d, q(c.node, { filter: "url(#" + d.id + ")" }) } else c._blur && (c._blur.parentNode.removeChild(c._blur), delete c._blur, delete c.attrs.blur), c.node.removeAttribute("filter") }, a._engine.circle = function (a, b, c, d) { var e = q("circle"); a.canvas && a.canvas.appendChild(e); var f = new z(e, a); f.attrs = { cx: b, cy: c, r: d, fill: "none", stroke: "#000" }, f.type = "circle", q(e, f.attrs); return f }, a._engine.rect = function (a, b, c, d, e, f) { var g = q("rect"); a.canvas && a.canvas.appendChild(g); var h = new z(g, a); h.attrs = { x: b, y: c, width: d, height: e, r: f || 0, rx: f || 0, ry: f || 0, fill: "none", stroke: "#000" }, h.type = "rect", q(g, h.attrs); return h }, a._engine.ellipse = function (a, b, c, d, e) { var f = q("ellipse"); a.canvas && a.canvas.appendChild(f); var g = new z(f, a); g.attrs = { cx: b, cy: c, rx: d, ry: e, fill: "none", stroke: "#000" }, g.type = "ellipse", q(f, g.attrs); return g }, a._engine.image = function (a, b, c, d, e, f) { var g = q("image"); q(g, { x: c, y: d, width: e, height: f, preserveAspectRatio: "none" }), g.setAttributeNS(n, "href", b), a.canvas && a.canvas.appendChild(g); var h = new z(g, a); h.attrs = { x: c, y: d, width: e, height: f, src: b }, h.type = "image"; return h }, a._engine.text = function (b, c, d, e) { var f = q("text"); b.canvas && b.canvas.appendChild(f); var g = new z(f, b); g.attrs = { x: c, y: d, "text-anchor": "middle", text: e, font: a._availableAttrs.font, stroke: "none", fill: "#000" }, g.type = "text", w(g, g.attrs); return g }, a._engine.setSize = function (a, b) { this.width = a || this.width, this.height = b || this.height, this.canvas.setAttribute("width", this.width), this.canvas.setAttribute("height", this.height), this._viewBox && this.setViewBox.apply(this, this._viewBox); return this }, a._engine.create = function () { var b = a._getContainer.apply(0, arguments), c = b && b.container, d = b.x, e = b.y, f = b.width, g = b.height; if (!c) throw new Error("SVG container not found."); var h = q("svg"), i = "overflow:hidden;", j; d = d || 0, e = e || 0, f = f || 512, g = g || 342, q(h, { height: g, version: 1.1, width: f, xmlns: "http://www.w3.org/2000/svg" }), c == 1 ? (h.style.cssText = i + "position:absolute;left:" + d + "px;top:" + e + "px", a._g.doc.body.appendChild(h), j = 1) : (h.style.cssText = i + "position:relative", c.firstChild ? c.insertBefore(h, c.firstChild) : c.appendChild(h)), c = new a._Paper, c.width = f, c.height = g, c.canvas = h, c.clear(), c._left = c._top = 0, j && (c.renderfix = function () { }), c.renderfix(); return c }, a._engine.setViewBox = function (a, b, c, d, e) { k("setViewBox", this, this._viewBox, [a, b, c, d, e]); var f = g(c / this.width, d / this.height), h = this.top, i = e ? "meet" : "xMinYMin", j, l; a == null ? (this._vbSize && (f = 1), delete this._vbSize, j = "0 0 " + this.width + m + this.height) : (this._vbSize = f, j = a + m + b + m + c + m + d), q(this.canvas, { viewBox: j, preserveAspectRatio: i }); while (f && h) l = "stroke-width" in h.attrs ? h.attrs["stroke-width"] : 1, h.attr({ "stroke-width": l }), h._.dirty = 1, h._.dirtyT = 1, h = h.prev; this._viewBox = [a, b, c, d, !!e]; return this }, a.prototype.renderfix = function () { var a = this.canvas, b = a.style, c; try { c = a.getScreenCTM() || a.createSVGMatrix() } catch (d) { c = a.createSVGMatrix() } var e = -c.e % 1, f = -c.f % 1; if (e || f) e && (this._left = (this._left + e) % 1, b.left = this._left + "px"), f && (this._top = (this._top + f) % 1, b.top = this._top + "px") }, a.prototype.clear = function () { a.eve("clear", this); var b = this.canvas; while (b.firstChild) b.removeChild(b.firstChild); this.bottom = this.top = null, (this.desc = q("desc")).appendChild(a._g.doc.createTextNode("Created with Raphaël " + a.version)), b.appendChild(this.desc), b.appendChild(this.defs = q("defs")) }, a.prototype.remove = function () { k("remove", this), this.canvas.parentNode && this.canvas.parentNode.removeChild(this.canvas); for (var b in this) this[b] = typeof this[b] == "function" ? a._removedFactory(b) : null }; var B = a.st; for (var C in A) A[b](C) && !B[b](C) && (B[C] = function (a) { return function () { var b = arguments; return this.forEach(function (c) { c[a].apply(c, b) }) } } (C)) } (window.Raphael), window.Raphael.vml && function (a) { var b = "hasOwnProperty", c = String, d = parseFloat, e = Math, f = e.round, g = e.max, h = e.min, i = e.abs, j = "fill", k = /[, ]+/, l = a.eve, m = " progid:DXImageTransform.Microsoft", n = " ", o = "", p = { M: "m", L: "l", C: "c", Z: "x", m: "t", l: "r", c: "v", z: "x" }, q = /([clmz]),?([^clmz]*)/gi, r = / progid:\S+Blur\([^\)]+\)/g, s = /-?[^,\s-]+/g, t = "position:absolute;left:0;top:0;width:1px;height:1px", u = 21600, v = { path: 1, rect: 1, image: 1 }, w = { circle: 1, ellipse: 1 }, x = function (b) { var d = /[ahqstv]/ig, e = a._pathToAbsolute; c(b).match(d) && (e = a._path2curve), d = /[clmz]/g; if (e == a._pathToAbsolute && !c(b).match(d)) { var g = c(b).replace(q, function (a, b, c) { var d = [], e = b.toLowerCase() == "m", g = p[b]; c.replace(s, function (a) { e && d.length == 2 && (g += d + p[b == "m" ? "l" : "L"], d = []), d.push(f(a * u)) }); return g + d }); return g } var h = e(b), i, j; g = []; for (var k = 0, l = h.length; k < l; k++) { i = h[k], j = h[k][0].toLowerCase(), j == "z" && (j = "x"); for (var m = 1, r = i.length; m < r; m++) j += f(i[m] * u) + (m != r - 1 ? "," : o); g.push(j) } return g.join(n) }, y = function (b, c, d) { var e = a.matrix(); e.rotate(-b, .5, .5); return { dx: e.x(c, d), dy: e.y(c, d)} }, z = function (a, b, c, d, e, f) { var g = a._, h = a.matrix, k = g.fillpos, l = a.node, m = l.style, o = 1, p = "", q, r = u / b, s = u / c; m.visibility = "hidden"; if (!!b && !!c) { l.coordsize = i(r) + n + i(s), m.rotation = f * (b * c < 0 ? -1 : 1); if (f) { var t = y(f, d, e); d = t.dx, e = t.dy } b < 0 && (p += "x"), c < 0 && (p += " y") && (o = -1), m.flip = p, l.coordorigin = d * -r + n + e * -s; if (k || g.fillsize) { var v = l.getElementsByTagName(j); v = v && v[0], l.removeChild(v), k && (t = y(f, h.x(k[0], k[1]), h.y(k[0], k[1])), v.position = t.dx * o + n + t.dy * o), g.fillsize && (v.size = g.fillsize[0] * i(b) + n + g.fillsize[1] * i(c)), l.appendChild(v) } m.visibility = "visible" } }; a.toString = function () { return "Your browser doesn’t support SVG. Falling down to VML.\nYou are running Raphaël " + this.version }; var A = function (a, b, d) { var e = c(b).toLowerCase().split("-"), f = d ? "end" : "start", g = e.length, h = "classic", i = "medium", j = "medium"; while (g--) switch (e[g]) { case "block": case "classic": case "oval": case "diamond": case "open": case "none": h = e[g]; break; case "wide": case "narrow": j = e[g]; break; case "long": case "short": i = e[g] } var k = a.node.getElementsByTagName("stroke")[0]; k[f + "arrow"] = h, k[f + "arrowlength"] = i, k[f + "arrowwidth"] = j }, B = function (e, i) { e.attrs = e.attrs || {}; var l = e.node, m = e.attrs, p = l.style, q, r = v[e.type] && (i.x != m.x || i.y != m.y || i.width != m.width || i.height != m.height || i.cx != m.cx || i.cy != m.cy || i.rx != m.rx || i.ry != m.ry || i.r != m.r), s = w[e.type] && (m.cx != i.cx || m.cy != i.cy || m.r != i.r || m.rx != i.rx || m.ry != i.ry), t = e; for (var y in i) i[b](y) && (m[y] = i[y]); r && (m.path = a._getPath[e.type](e), e._.dirty = 1), i.href && (l.href = i.href), i.title && (l.title = i.title), i.target && (l.target = i.target), i.cursor && (p.cursor = i.cursor), "blur" in i && e.blur(i.blur); if (i.path && e.type == "path" || r) l.path = x(~c(m.path).toLowerCase().indexOf("r") ? a._pathToAbsolute(m.path) : m.path), e.type == "image" && (e._.fillpos = [m.x, m.y], e._.fillsize = [m.width, m.height], z(e, 1, 1, 0, 0, 0)); "transform" in i && e.transform(i.transform); if (s) { var B = +m.cx, D = +m.cy, E = +m.rx || +m.r || 0, G = +m.ry || +m.r || 0; l.path = a.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x", f((B - E) * u), f((D - G) * u), f((B + E) * u), f((D + G) * u), f(B * u)) } if ("clip-rect" in i) { var H = c(i["clip-rect"]).split(k); if (H.length == 4) { H[2] = +H[2] + +H[0], H[3] = +H[3] + +H[1]; var I = l.clipRect || a._g.doc.createElement("div"), J = I.style; J.clip = a.format("rect({1}px {2}px {3}px {0}px)", H), l.clipRect || (J.position = "absolute", J.top = 0, J.left = 0, J.width = e.paper.width + "px", J.height = e.paper.height + "px", l.parentNode.insertBefore(I, l), I.appendChild(l), l.clipRect = I) } i["clip-rect"] || l.clipRect && (l.clipRect.style.clip = "auto") } if (e.textpath) { var K = e.textpath.style; i.font && (K.font = i.font), i["font-family"] && (K.fontFamily = '"' + i["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, o) + '"'), i["font-size"] && (K.fontSize = i["font-size"]), i["font-weight"] && (K.fontWeight = i["font-weight"]), i["font-style"] && (K.fontStyle = i["font-style"]) } "arrow-start" in i && A(t, i["arrow-start"]), "arrow-end" in i && A(t, i["arrow-end"], 1); if (i.opacity != null || i["stroke-width"] != null || i.fill != null || i.src != null || i.stroke != null || i["stroke-width"] != null || i["stroke-opacity"] != null || i["fill-opacity"] != null || i["stroke-dasharray"] != null || i["stroke-miterlimit"] != null || i["stroke-linejoin"] != null || i["stroke-linecap"] != null) { var L = l.getElementsByTagName(j), M = !1; L = L && L[0], !L && (M = L = F(j)), e.type == "image" && i.src && (L.src = i.src), i.fill && (L.on = !0); if (L.on == null || i.fill == "none" || i.fill === null) L.on = !1; if (L.on && i.fill) { var N = c(i.fill).match(a._ISURL); if (N) { L.parentNode == l && l.removeChild(L), L.rotate = !0, L.src = N[1], L.type = "tile"; var O = e.getBBox(1); L.position = O.x + n + O.y, e._.fillpos = [O.x, O.y], a._preload(N[1], function () { e._.fillsize = [this.offsetWidth, this.offsetHeight] }) } else L.color = a.getRGB(i.fill).hex, L.src = o, L.type = "solid", a.getRGB(i.fill).error && (t.type in { circle: 1, ellipse: 1} || c(i.fill).charAt() != "r") && C(t, i.fill, L) && (m.fill = "none", m.gradient = i.fill, L.rotate = !1) } if ("fill-opacity" in i || "opacity" in i) { var P = ((+m["fill-opacity"] + 1 || 2) - 1) * ((+m.opacity + 1 || 2) - 1) * ((+a.getRGB(i.fill).o + 1 || 2) - 1); P = h(g(P, 0), 1), L.opacity = P, L.src && (L.color = "none") } l.appendChild(L); var Q = l.getElementsByTagName("stroke") && l.getElementsByTagName("stroke")[0], T = !1; !Q && (T = Q = F("stroke")); if (i.stroke && i.stroke != "none" || i["stroke-width"] || i["stroke-opacity"] != null || i["stroke-dasharray"] || i["stroke-miterlimit"] || i["stroke-linejoin"] || i["stroke-linecap"]) Q.on = !0; (i.stroke == "none" || i.stroke === null || Q.on == null || i.stroke == 0 || i["stroke-width"] == 0) && (Q.on = !1); var U = a.getRGB(i.stroke); Q.on && i.stroke && (Q.color = U.hex), P = ((+m["stroke-opacity"] + 1 || 2) - 1) * ((+m.opacity + 1 || 2) - 1) * ((+U.o + 1 || 2) - 1); var V = (d(i["stroke-width"]) || 1) * .75; P = h(g(P, 0), 1), i["stroke-width"] == null && (V = m["stroke-width"]), i["stroke-width"] && (Q.weight = V), V && V < 1 && (P *= V) && (Q.weight = 1), Q.opacity = P, i["stroke-linejoin"] && (Q.joinstyle = i["stroke-linejoin"] || "miter"), Q.miterlimit = i["stroke-miterlimit"] || 8, i["stroke-linecap"] && (Q.endcap = i["stroke-linecap"] == "butt" ? "flat" : i["stroke-linecap"] == "square" ? "square" : "round"); if (i["stroke-dasharray"]) { var W = { "-": "shortdash", ".": "shortdot", "-.": "shortdashdot", "-..": "shortdashdotdot", ". ": "dot", "- ": "dash", "--": "longdash", "- .": "dashdot", "--.": "longdashdot", "--..": "longdashdotdot" }; Q.dashstyle = W[b](i["stroke-dasharray"]) ? W[i["stroke-dasharray"]] : o } T && l.appendChild(Q) } if (t.type == "text") { t.paper.canvas.style.display = o; var X = t.paper.span, Y = 100, Z = m.font && m.font.match(/\d+(?:\.\d*)?(?=px)/); p = X.style, m.font && (p.font = m.font), m["font-family"] && (p.fontFamily = m["font-family"]), m["font-weight"] && (p.fontWeight = m["font-weight"]), m["font-style"] && (p.fontStyle = m["font-style"]), Z = d(m["font-size"] || Z && Z[0]) || 10, p.fontSize = Z * Y + "px", t.textpath.string && (X.innerHTML = c(t.textpath.string).replace(/</g, "<").replace(/&/g, "&").replace(/\n/g, "<br>")); var $ = X.getBoundingClientRect(); t.W = m.w = ($.right - $.left) / Y, t.H = m.h = ($.bottom - $.top) / Y, t.X = m.x, t.Y = m.y + t.H / 2, ("x" in i || "y" in i) && (t.path.v = a.format("m{0},{1}l{2},{1}", f(m.x * u), f(m.y * u), f(m.x * u) + 1)); var _ = ["x", "y", "text", "font", "font-family", "font-weight", "font-style", "font-size"]; for (var ba = 0, bb = _.length; ba < bb; ba++) if (_[ba] in i) { t._.dirty = 1; break } switch (m["text-anchor"]) { case "start": t.textpath.style["v-text-align"] = "left", t.bbx = t.W / 2; break; case "end": t.textpath.style["v-text-align"] = "right", t.bbx = -t.W / 2; break; default: t.textpath.style["v-text-align"] = "center", t.bbx = 0 } t.textpath.style["v-text-kern"] = !0 } }, C = function (b, f, g) { b.attrs = b.attrs || {}; var h = b.attrs, i = Math.pow, j, k, l = "linear", m = ".5 .5"; b.attrs.gradient = f, f = c(f).replace(a._radial_gradient, function (a, b, c) { l = "radial", b && c && (b = d(b), c = d(c), i(b - .5, 2) + i(c - .5, 2) > .25 && (c = e.sqrt(.25 - i(b - .5, 2)) * ((c > .5) * 2 - 1) + .5), m = b + n + c); return o }), f = f.split(/\s*\-\s*/); if (l == "linear") { var p = f.shift(); p = -d(p); if (isNaN(p)) return null } var q = a._parseDots(f); if (!q) return null; b = b.shape || b.node; if (q.length) { b.removeChild(g), g.on = !0, g.method = "none", g.color = q[0].color, g.color2 = q[q.length - 1].color; var r = []; for (var s = 0, t = q.length; s < t; s++) q[s].offset && r.push(q[s].offset + n + q[s].color); g.colors = r.length ? r.join() : "0% " + g.color, l == "radial" ? (g.type = "gradientTitle", g.focus = "100%", g.focussize = "0 0", g.focusposition = m, g.angle = 0) : (g.type = "gradient", g.angle = (270 - p) % 360), b.appendChild(g) } return 1 }, D = function (b, c) { this[0] = this.node = b, b.raphael = !0, this.id = a._oid++, b.raphaelid = this.id, this.X = 0, this.Y = 0, this.attrs = {}, this.paper = c, this.matrix = a.matrix(), this._ = { transform: [], sx: 1, sy: 1, dx: 0, dy: 0, deg: 0, dirty: 1, dirtyT: 1 }, !c.bottom && (c.bottom = this), this.prev = c.top, c.top && (c.top.next = this), c.top = this, this.next = null }, E = a.el; D.prototype = E, E.constructor = D, E.transform = function (b) { if (b == null) return this._.transform; var d = this.paper._viewBoxShift, e = d ? "s" + [d.scale, d.scale] + "-1-1t" + [d.dx, d.dy] : o, f; d && (f = b = c(b).replace(/\.{3}|\u2026/g, this._.transform || o)), a._extractTransform(this, e + b); var g = this.matrix.clone(), h = this.skew, i = this.node, j, k = ~c(this.attrs.fill).indexOf("-"), l = !c(this.attrs.fill).indexOf("url("); g.translate(-0.5, -0.5); if (l || k || this.type == "image") { h.matrix = "1 0 0 1", h.offset = "0 0", j = g.split(); if (k && j.noRotation || !j.isSimple) { i.style.filter = g.toFilter(); var m = this.getBBox(), p = this.getBBox(1), q = m.x - p.x, r = m.y - p.y; i.coordorigin = q * -u + n + r * -u, z(this, 1, 1, q, r, 0) } else i.style.filter = o, z(this, j.scalex, j.scaley, j.dx, j.dy, j.rotate) } else i.style.filter = o, h.matrix = c(g), h.offset = g.offset(); f && (this._.transform = f); return this }, E.rotate = function (a, b, e) { if (this.removed) return this; if (a != null) { a = c(a).split(k), a.length - 1 && (b = d(a[1]), e = d(a[2])), a = d(a[0]), e == null && (b = e); if (b == null || e == null) { var f = this.getBBox(1); b = f.x + f.width / 2, e = f.y + f.height / 2 } this._.dirtyT = 1, this.transform(this._.transform.concat([["r", a, b, e]])); return this } }, E.translate = function (a, b) { if (this.removed) return this; a = c(a).split(k), a.length - 1 && (b = d(a[1])), a = d(a[0]) || 0, b = +b || 0, this._.bbox && (this._.bbox.x += a, this._.bbox.y += b), this.transform(this._.transform.concat([["t", a, b]])); return this }, E.scale = function (a, b, e, f) { if (this.removed) return this; a = c(a).split(k), a.length - 1 && (b = d(a[1]), e = d(a[2]), f = d(a[3]), isNaN(e) && (e = null), isNaN(f) && (f = null)), a = d(a[0]), b == null && (b = a), f == null && (e = f); if (e == null || f == null) var g = this.getBBox(1); e = e == null ? g.x + g.width / 2 : e, f = f == null ? g.y + g.height / 2 : f, this.transform(this._.transform.concat([["s", a, b, e, f]])), this._.dirtyT = 1; return this }, E.hide = function () { !this.removed && (this.node.style.display = "none"); return this }, E.show = function () { !this.removed && (this.node.style.display = o); return this }, E._getBBox = function () { if (this.removed) return {}; return { x: this.X + (this.bbx || 0) - this.W / 2, y: this.Y - this.H, width: this.W, height: this.H} }, E.remove = function () { if (!this.removed) { this.paper.__set__ && this.paper.__set__.exclude(this), a.eve.unbind("*.*." + this.id), a._tear(this, this.paper), this.node.parentNode.removeChild(this.node), this.shape && this.shape.parentNode.removeChild(this.shape); for (var b in this) this[b] = typeof this[b] == "function" ? a._removedFactory(b) : null; this.removed = !0 } }, E.attr = function (c, d) { if (this.removed) return this; if (c == null) { var e = {}; for (var f in this.attrs) this.attrs[b](f) && (e[f] = this.attrs[f]); e.gradient && e.fill == "none" && (e.fill = e.gradient) && delete e.gradient, e.transform = this._.transform; return e } if (d == null && a.is(c, "string")) { if (c == j && this.attrs.fill == "none" && this.attrs.gradient) return this.attrs.gradient; var g = c.split(k), h = {}; for (var i = 0, m = g.length; i < m; i++) c = g[i], c in this.attrs ? h[c] = this.attrs[c] : a.is(this.paper.customAttributes[c], "function") ? h[c] = this.paper.customAttributes[c].def : h[c] = a._availableAttrs[c]; return m - 1 ? h : h[g[0]] } if (this.attrs && d == null && a.is(c, "array")) { h = {}; for (i = 0, m = c.length; i < m; i++) h[c[i]] = this.attr(c[i]); return h } var n; d != null && (n = {}, n[c] = d), d == null && a.is(c, "object") && (n = c); for (var o in n) l("attr." + o + "." + this.id, this, n[o]); if (n) { for (o in this.paper.customAttributes) if (this.paper.customAttributes[b](o) && n[b](o) && a.is(this.paper.customAttributes[o], "function")) { var p = this.paper.customAttributes[o].apply(this, [].concat(n[o])); this.attrs[o] = n[o]; for (var q in p) p[b](q) && (n[q] = p[q]) } n.text && this.type == "text" && (this.textpath.string = n.text), B(this, n) } return this }, E.toFront = function () { !this.removed && this.node.parentNode.appendChild(this.node), this.paper && this.paper.top != this && a._tofront(this, this.paper); return this }, E.toBack = function () { if (this.removed) return this; this.node.parentNode.firstChild != this.node && (this.node.parentNode.insertBefore(this.node, this.node.parentNode.firstChild), a._toback(this, this.paper)); return this }, E.insertAfter = function (b) { if (this.removed) return this; b.constructor == a.st.constructor && (b = b[b.length - 1]), b.node.nextSibling ? b.node.parentNode.insertBefore(this.node, b.node.nextSibling) : b.node.parentNode.appendChild(this.node), a._insertafter(this, b, this.paper); return this }, E.insertBefore = function (b) { if (this.removed) return this; b.constructor == a.st.constructor && (b = b[0]), b.node.parentNode.insertBefore(this.node, b.node), a._insertbefore(this, b, this.paper); return this }, E.blur = function (b) { var c = this.node.runtimeStyle, d = c.filter; d = d.replace(r, o), +b !== 0 ? (this.attrs.blur = b, c.filter = d + n + m + ".Blur(pixelradius=" + (+b || 1.5) + ")", c.margin = a.format("-{0}px 0 0 -{0}px", f(+b || 1.5))) : (c.filter = d, c.margin = 0, delete this.attrs.blur) }, a._engine.path = function (a, b) { var c = F("shape"); c.style.cssText = t, c.coordsize = u + n + u, c.coordorigin = b.coordorigin; var d = new D(c, b), e = { fill: "none", stroke: "#000" }; a && (e.path = a), d.type = "path", d.path = [], d.Path = o, B(d, e), b.canvas.appendChild(c); var f = F("skew"); f.on = !0, c.appendChild(f), d.skew = f, d.transform(o); return d }, a._engine.rect = function (b, c, d, e, f, g) { var h = a._rectPath(c, d, e, f, g), i = b.path(h), j = i.attrs; i.X = j.x = c, i.Y = j.y = d, i.W = j.width = e, i.H = j.height = f, j.r = g, j.path = h, i.type = "rect"; return i }, a._engine.ellipse = function (a, b, c, d, e) { var f = a.path(), g = f.attrs; f.X = b - d, f.Y = c - e, f.W = d * 2, f.H = e * 2, f.type = "ellipse", B(f, { cx: b, cy: c, rx: d, ry: e }); return f }, a._engine.circle = function (a, b, c, d) { var e = a.path(), f = e.attrs; e.X = b - d, e.Y = c - d, e.W = e.H = d * 2, e.type = "circle", B(e, { cx: b, cy: c, r: d }); return e }, a._engine.image = function (b, c, d, e, f, g) { var h = a._rectPath(d, e, f, g), i = b.path(h).attr({ stroke: "none" }), k = i.attrs, l = i.node, m = l.getElementsByTagName(j)[0]; k.src = c, i.X = k.x = d, i.Y = k.y = e, i.W = k.width = f, i.H = k.height = g, k.path = h, i.type = "image", m.parentNode == l && l.removeChild(m), m.rotate = !0, m.src = c, m.type = "tile", i._.fillpos = [d, e], i._.fillsize = [f, g], l.appendChild(m), z(i, 1, 1, 0, 0, 0); return i }, a._engine.text = function (b, d, e, g) { var h = F("shape"), i = F("path"), j = F("textpath"); d = d || 0, e = e || 0, g = g || "", i.v = a.format("m{0},{1}l{2},{1}", f(d * u), f(e * u), f(d * u) + 1), i.textpathok = !0, j.string = c(g), j.on = !0, h.style.cssText = t, h.coordsize = u + n + u, h.coordorigin = "0 0"; var k = new D(h, b), l = { fill: "#000", stroke: "none", font: a._availableAttrs.font, text: g }; k.shape = h, k.path = i, k.textpath = j, k.type = "text", k.attrs.text = c(g), k.attrs.x = d, k.attrs.y = e, k.attrs.w = 1, k.attrs.h = 1, B(k, l), h.appendChild(j), h.appendChild(i), b.canvas.appendChild(h); var m = F("skew"); m.on = !0, h.appendChild(m), k.skew = m, k.transform(o); return k }, a._engine.setSize = function (b, c) { var d = this.canvas.style; this.width = b, this.height = c, b == +b && (b += "px"), c == +c && (c += "px"), d.width = b, d.height = c, d.clip = "rect(0 " + b + " " + c + " 0)", this._viewBox && a._engine.setViewBox.apply(this, this._viewBox); return this }, a._engine.setViewBox = function (b, c, d, e, f) { a.eve("setViewBox", this, this._viewBox, [b, c, d, e, f]); var h = this.width, i = this.height, j = 1 / g(d / h, e / i), k, l; f && (k = i / e, l = h / d, d * k < h && (b -= (h - d * k) / 2 / k), e * l < i && (c -= (i - e * l) / 2 / l)), this._viewBox = [b, c, d, e, !!f], this._viewBoxShift = { dx: -b, dy: -c, scale: j }, this.forEach(function (a) { a.transform("...") }); return this }; var F; a._engine.initWin = function (a) { var b = a.document; b.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)"); try { !b.namespaces.rvml && b.namespaces.add("rvml", "urn:schemas-microsoft-com:vml"), F = function (a) { return b.createElement("<rvml:" + a + ' class="rvml">') } } catch (c) { F = function (a) { return b.createElement("<" + a + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">') } } }, a._engine.initWin(a._g.win), a._engine.create = function () { var b = a._getContainer.apply(0, arguments), c = b.container, d = b.height, e, f = b.width, g = b.x, h = b.y; if (!c) throw new Error("VML container not found."); var i = new a._Paper, j = i.canvas = a._g.doc.createElement("div"), k = j.style; g = g || 0, h = h || 0, f = f || 512, d = d || 342, i.width = f, i.height = d, f == +f && (f += "px"), d == +d && (d += "px"), i.coordsize = u * 1e3 + n + u * 1e3, i.coordorigin = "0 0", i.span = a._g.doc.createElement("span"), i.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;", j.appendChild(i.span), k.cssText = a.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden", f, d), c == 1 ? (a._g.doc.body.appendChild(j), k.left = g + "px", k.top = h + "px", k.position = "absolute") : c.firstChild ? c.insertBefore(j, c.firstChild) : c.appendChild(j), i.renderfix = function () { }; return i }, a.prototype.clear = function () { a.eve("clear", this), this.canvas.innerHTML = o, this.span = a._g.doc.createElement("span"), this.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;", this.canvas.appendChild(this.span), this.bottom = this.top = null }, a.prototype.remove = function () { a.eve("remove", this), this.canvas.parentNode.removeChild(this.canvas); for (var b in this) this[b] = typeof this[b] == "function" ? a._removedFactory(b) : null; return !0 }; var G = a.st; for (var H in E) E[b](H) && !G[b](H) && (G[H] = function (a) { return function () { var b = arguments; return this.forEach(function (c) { c[a].apply(c, b) }) } } (H)) } (window.Raphael);
/*! jQuery UI - v1.9.2 - 2012-12-14
* http://jqueryui.com
* Includes: jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js
* Copyright (c) 2012 jQuery Foundation and other contributors Licensed MIT */
jQuery.effects||function(e,t){var n=e.uiBackCompat!==!1,r="ui-effects-";e.effects={effect:{}},function(t,n){function p(e,t,n){var r=a[t.type]||{};return e==null?n||!t.def?null:t.def:(e=r.floor?~~e:parseFloat(e),isNaN(e)?t.def:r.mod?(e+r.mod)%r.mod:0>e?0:r.max<e?r.max:e)}function d(e){var n=o(),r=n._rgba=[];return e=e.toLowerCase(),h(s,function(t,i){var s,o=i.re.exec(e),a=o&&i.parse(o),f=i.space||"rgba";if(a)return s=n[f](a),n[u[f].cache]=s[u[f].cache],r=n._rgba=s._rgba,!1}),r.length?(r.join()==="0,0,0,0"&&t.extend(r,c.transparent),n):c[e]}function v(e,t,n){return n=(n+1)%1,n*6<1?e+(t-e)*n*6:n*2<1?t:n*3<2?e+(t-e)*(2/3-n)*6:e}var r="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor".split(" "),i=/^([\-+])=\s*(\d+\.?\d*)/,s=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,parse:function(e){return[e[1],e[2],e[3],e[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,parse:function(e){return[e[1]*2.55,e[2]*2.55,e[3]*2.55,e[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(e){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(e){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(e){return[e[1],e[2]/100,e[3]/100,e[4]]}}],o=t.Color=function(e,n,r,i){return new t.Color.fn.parse(e,n,r,i)},u={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},a={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},f=o.support={},l=t("<p>")[0],c,h=t.each;l.style.cssText="background-color:rgba(1,1,1,.5)",f.rgba=l.style.backgroundColor.indexOf("rgba")>-1,h(u,function(e,t){t.cache="_"+e,t.props.alpha={idx:3,type:"percent",def:1}}),o.fn=t.extend(o.prototype,{parse:function(r,i,s,a){if(r===n)return this._rgba=[null,null,null,null],this;if(r.jquery||r.nodeType)r=t(r).css(i),i=n;var f=this,l=t.type(r),v=this._rgba=[];i!==n&&(r=[r,i,s,a],l="array");if(l==="string")return this.parse(d(r)||c._default);if(l==="array")return h(u.rgba.props,function(e,t){v[t.idx]=p(r[t.idx],t)}),this;if(l==="object")return r instanceof o?h(u,function(e,t){r[t.cache]&&(f[t.cache]=r[t.cache].slice())}):h(u,function(t,n){var i=n.cache;h(n.props,function(e,t){if(!f[i]&&n.to){if(e==="alpha"||r[e]==null)return;f[i]=n.to(f._rgba)}f[i][t.idx]=p(r[e],t,!0)}),f[i]&&e.inArray(null,f[i].slice(0,3))<0&&(f[i][3]=1,n.from&&(f._rgba=n.from(f[i])))}),this},is:function(e){var t=o(e),n=!0,r=this;return h(u,function(e,i){var s,o=t[i.cache];return o&&(s=r[i.cache]||i.to&&i.to(r._rgba)||[],h(i.props,function(e,t){if(o[t.idx]!=null)return n=o[t.idx]===s[t.idx],n})),n}),n},_space:function(){var e=[],t=this;return h(u,function(n,r){t[r.cache]&&e.push(n)}),e.pop()},transition:function(e,t){var n=o(e),r=n._space(),i=u[r],s=this.alpha()===0?o("transparent"):this,f=s[i.cache]||i.to(s._rgba),l=f.slice();return n=n[i.cache],h(i.props,function(e,r){var i=r.idx,s=f[i],o=n[i],u=a[r.type]||{};if(o===null)return;s===null?l[i]=o:(u.mod&&(o-s>u.mod/2?s+=u.mod:s-o>u.mod/2&&(s-=u.mod)),l[i]=p((o-s)*t+s,r))}),this[r](l)},blend:function(e){if(this._rgba[3]===1)return this;var n=this._rgba.slice(),r=n.pop(),i=o(e)._rgba;return o(t.map(n,function(e,t){return(1-r)*i[t]+r*e}))},toRgbaString:function(){var e="rgba(",n=t.map(this._rgba,function(e,t){return e==null?t>2?1:0:e});return n[3]===1&&(n.pop(),e="rgb("),e+n.join()+")"},toHslaString:function(){var e="hsla(",n=t.map(this.hsla(),function(e,t){return e==null&&(e=t>2?1:0),t&&t<3&&(e=Math.round(e*100)+"%"),e});return n[3]===1&&(n.pop(),e="hsl("),e+n.join()+")"},toHexString:function(e){var n=this._rgba.slice(),r=n.pop();return e&&n.push(~~(r*255)),"#"+t.map(n,function(e){return e=(e||0).toString(16),e.length===1?"0"+e:e}).join("")},toString:function(){return this._rgba[3]===0?"transparent":this.toRgbaString()}}),o.fn.parse.prototype=o.fn,u.hsla.to=function(e){if(e[0]==null||e[1]==null||e[2]==null)return[null,null,null,e[3]];var t=e[0]/255,n=e[1]/255,r=e[2]/255,i=e[3],s=Math.max(t,n,r),o=Math.min(t,n,r),u=s-o,a=s+o,f=a*.5,l,c;return o===s?l=0:t===s?l=60*(n-r)/u+360:n===s?l=60*(r-t)/u+120:l=60*(t-n)/u+240,f===0||f===1?c=f:f<=.5?c=u/a:c=u/(2-a),[Math.round(l)%360,c,f,i==null?1:i]},u.hsla.from=function(e){if(e[0]==null||e[1]==null||e[2]==null)return[null,null,null,e[3]];var t=e[0]/360,n=e[1],r=e[2],i=e[3],s=r<=.5?r*(1+n):r+n-r*n,o=2*r-s;return[Math.round(v(o,s,t+1/3)*255),Math.round(v(o,s,t)*255),Math.round(v(o,s,t-1/3)*255),i]},h(u,function(e,r){var s=r.props,u=r.cache,a=r.to,f=r.from;o.fn[e]=function(e){a&&!this[u]&&(this[u]=a(this._rgba));if(e===n)return this[u].slice();var r,i=t.type(e),l=i==="array"||i==="object"?e:arguments,c=this[u].slice();return h(s,function(e,t){var n=l[i==="object"?e:t.idx];n==null&&(n=c[t.idx]),c[t.idx]=p(n,t)}),f?(r=o(f(c)),r[u]=c,r):o(c)},h(s,function(n,r){if(o.fn[n])return;o.fn[n]=function(s){var o=t.type(s),u=n==="alpha"?this._hsla?"hsla":"rgba":e,a=this[u](),f=a[r.idx],l;return o==="undefined"?f:(o==="function"&&(s=s.call(this,f),o=t.type(s)),s==null&&r.empty?this:(o==="string"&&(l=i.exec(s),l&&(s=f+parseFloat(l[2])*(l[1]==="+"?1:-1))),a[r.idx]=s,this[u](a)))}})}),h(r,function(e,n){t.cssHooks[n]={set:function(e,r){var i,s,u="";if(t.type(r)!=="string"||(i=d(r))){r=o(i||r);if(!f.rgba&&r._rgba[3]!==1){s=n==="backgroundColor"?e.parentNode:e;while((u===""||u==="transparent")&&s&&s.style)try{u=t.css(s,"backgroundColor"),s=s.parentNode}catch(a){}r=r.blend(u&&u!=="transparent"?u:"_default")}r=r.toRgbaString()}try{e.style[n]=r}catch(l){}}},t.fx.step[n]=function(e){e.colorInit||(e.start=o(e.elem,n),e.end=o(e.end),e.colorInit=!0),t.cssHooks[n].set(e.elem,e.start.transition(e.end,e.pos))}}),t.cssHooks.borderColor={expand:function(e){var t={};return h(["Top","Right","Bottom","Left"],function(n,r){t["border"+r+"Color"]=e}),t}},c=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(jQuery),function(){function i(){var t=this.ownerDocument.defaultView?this.ownerDocument.defaultView.getComputedStyle(this,null):this.currentStyle,n={},r,i;if(t&&t.length&&t[0]&&t[t[0]]){i=t.length;while(i--)r=t[i],typeof t[r]=="string"&&(n[e.camelCase(r)]=t[r])}else for(r in t)typeof t[r]=="string"&&(n[r]=t[r]);return n}function s(t,n){var i={},s,o;for(s in n)o=n[s],t[s]!==o&&!r[s]&&(e.fx.step[s]||!isNaN(parseFloat(o)))&&(i[s]=o);return i}var n=["add","remove","toggle"],r={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};e.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(t,n){e.fx.step[n]=function(e){if(e.end!=="none"&&!e.setAttr||e.pos===1&&!e.setAttr)jQuery.style(e.elem,n,e.end),e.setAttr=!0}}),e.effects.animateClass=function(t,r,o,u){var a=e.speed(r,o,u);return this.queue(function(){var r=e(this),o=r.attr("class")||"",u,f=a.children?r.find("*").andSelf():r;f=f.map(function(){var t=e(this);return{el:t,start:i.call(this)}}),u=function(){e.each(n,function(e,n){t[n]&&r[n+"Class"](t[n])})},u(),f=f.map(function(){return this.end=i.call(this.el[0]),this.diff=s(this.start,this.end),this}),r.attr("class",o),f=f.map(function(){var t=this,n=e.Deferred(),r=jQuery.extend({},a,{queue:!1,complete:function(){n.resolve(t)}});return this.el.animate(this.diff,r),n.promise()}),e.when.apply(e,f.get()).done(function(){u(),e.each(arguments,function(){var t=this.el;e.each(this.diff,function(e){t.css(e,"")})}),a.complete.call(r[0])})})},e.fn.extend({_addClass:e.fn.addClass,addClass:function(t,n,r,i){return n?e.effects.animateClass.call(this,{add:t},n,r,i):this._addClass(t)},_removeClass:e.fn.removeClass,removeClass:function(t,n,r,i){return n?e.effects.animateClass.call(this,{remove:t},n,r,i):this._removeClass(t)},_toggleClass:e.fn.toggleClass,toggleClass:function(n,r,i,s,o){return typeof r=="boolean"||r===t?i?e.effects.animateClass.call(this,r?{add:n}:{remove:n},i,s,o):this._toggleClass(n,r):e.effects.animateClass.call(this,{toggle:n},r,i,s)},switchClass:function(t,n,r,i,s){return e.effects.animateClass.call(this,{add:n,remove:t},r,i,s)}})}(),function(){function i(t,n,r,i){e.isPlainObject(t)&&(n=t,t=t.effect),t={effect:t},n==null&&(n={}),e.isFunction(n)&&(i=n,r=null,n={});if(typeof n=="number"||e.fx.speeds[n])i=r,r=n,n={};return e.isFunction(r)&&(i=r,r=null),n&&e.extend(t,n),r=r||n.duration,t.duration=e.fx.off?0:typeof r=="number"?r:r in e.fx.speeds?e.fx.speeds[r]:e.fx.speeds._default,t.complete=i||n.complete,t}function s(t){return!t||typeof t=="number"||e.fx.speeds[t]?!0:typeof t=="string"&&!e.effects.effect[t]?n&&e.effects[t]?!1:!0:!1}e.extend(e.effects,{version:"1.9.2",save:function(e,t){for(var n=0;n<t.length;n++)t[n]!==null&&e.data(r+t[n],e[0].style[t[n]])},restore:function(e,n){var i,s;for(s=0;s<n.length;s++)n[s]!==null&&(i=e.data(r+n[s]),i===t&&(i=""),e.css(n[s],i))},setMode:function(e,t){return t==="toggle"&&(t=e.is(":hidden")?"show":"hide"),t},getBaseline:function(e,t){var n,r;switch(e[0]){case"top":n=0;break;case"middle":n=.5;break;case"bottom":n=1;break;default:n=e[0]/t.height}switch(e[1]){case"left":r=0;break;case"center":r=.5;break;case"right":r=1;break;default:r=e[1]/t.width}return{x:r,y:n}},createWrapper:function(t){if(t.parent().is(".ui-effects-wrapper"))return t.parent();var n={width:t.outerWidth(!0),height:t.outerHeight(!0),"float":t.css("float")},r=e("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),i={width:t.width(),height:t.height()},s=document.activeElement;try{s.id}catch(o){s=document.body}return t.wrap(r),(t[0]===s||e.contains(t[0],s))&&e(s).focus(),r=t.parent(),t.css("position")==="static"?(r.css({position:"relative"}),t.css({position:"relative"})):(e.extend(n,{position:t.css("position"),zIndex:t.css("z-index")}),e.each(["top","left","bottom","right"],function(e,r){n[r]=t.css(r),isNaN(parseInt(n[r],10))&&(n[r]="auto")}),t.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),t.css(i),r.css(n).show()},removeWrapper:function(t){var n=document.activeElement;return t.parent().is(".ui-effects-wrapper")&&(t.parent().replaceWith(t),(t[0]===n||e.contains(t[0],n))&&e(n).focus()),t},setTransition:function(t,n,r,i){return i=i||{},e.each(n,function(e,n){var s=t.cssUnit(n);s[0]>0&&(i[n]=s[0]*r+s[1])}),i}}),e.fn.extend({effect:function(){function a(n){function u(){e.isFunction(i)&&i.call(r[0]),e.isFunction(n)&&n()}var r=e(this),i=t.complete,s=t.mode;(r.is(":hidden")?s==="hide":s==="show")?u():o.call(r[0],t,u)}var t=i.apply(this,arguments),r=t.mode,s=t.queue,o=e.effects.effect[t.effect],u=!o&&n&&e.effects[t.effect];return e.fx.off||!o&&!u?r?this[r](t.duration,t.complete):this.each(function(){t.complete&&t.complete.call(this)}):o?s===!1?this.each(a):this.queue(s||"fx",a):u.call(this,{options:t,duration:t.duration,callback:t.complete,mode:t.mode})},_show:e.fn.show,show:function(e){if(s(e))return this._show.apply(this,arguments);var t=i.apply(this,arguments);return t.mode="show",this.effect.call(this,t)},_hide:e.fn.hide,hide:function(e){if(s(e))return this._hide.apply(this,arguments);var t=i.apply(this,arguments);return t.mode="hide",this.effect.call(this,t)},__toggle:e.fn.toggle,toggle:function(t){if(s(t)||typeof t=="boolean"||e.isFunction(t))return this.__toggle.apply(this,arguments);var n=i.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)},cssUnit:function(t){var n=this.css(t),r=[];return e.each(["em","px","%","pt"],function(e,t){n.indexOf(t)>0&&(r=[parseFloat(n),t])}),r}})}(),function(){var t={};e.each(["Quad","Cubic","Quart","Quint","Expo"],function(e,n){t[n]=function(t){return Math.pow(t,e+2)}}),e.extend(t,{Sine:function(e){return 1-Math.cos(e*Math.PI/2)},Circ:function(e){return 1-Math.sqrt(1-e*e)},Elastic:function(e){return e===0||e===1?e:-Math.pow(2,8*(e-1))*Math.sin(((e-1)*80-7.5)*Math.PI/15)},Back:function(e){return e*e*(3*e-2)},Bounce:function(e){var t,n=4;while(e<((t=Math.pow(2,--n))-1)/11);return 1/Math.pow(4,3-n)-7.5625*Math.pow((t*3-2)/22-e,2)}}),e.each(t,function(t,n){e.easing["easeIn"+t]=n,e.easing["easeOut"+t]=function(e){return 1-n(1-e)},e.easing["easeInOut"+t]=function(e){return e<.5?n(e*2)/2:1-n(e*-2+2)/2}})}()}(jQuery);(function(e,t){var n=/up|down|vertical/,r=/up|left|vertical|horizontal/;e.effects.effect.blind=function(t,i){var s=e(this),o=["position","top","bottom","left","right","height","width"],u=e.effects.setMode(s,t.mode||"hide"),a=t.direction||"up",f=n.test(a),l=f?"height":"width",c=f?"top":"left",h=r.test(a),p={},d=u==="show",v,m,g;s.parent().is(".ui-effects-wrapper")?e.effects.save(s.parent(),o):e.effects.save(s,o),s.show(),v=e.effects.createWrapper(s).css({overflow:"hidden"}),m=v[l](),g=parseFloat(v.css(c))||0,p[l]=d?m:0,h||(s.css(f?"bottom":"right",0).css(f?"top":"left","auto").css({position:"absolute"}),p[c]=d?g:m+g),d&&(v.css(l,0),h||v.css(c,g+m)),v.animate(p,{duration:t.duration,easing:t.easing,queue:!1,complete:function(){u==="hide"&&s.hide(),e.effects.restore(s,o),e.effects.removeWrapper(s),i()}})}})(jQuery);(function(e,t){e.effects.effect.bounce=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"effect"),o=s==="hide",u=s==="show",a=t.direction||"up",f=t.distance,l=t.times||5,c=l*2+(u||o?1:0),h=t.duration/c,p=t.easing,d=a==="up"||a==="down"?"top":"left",v=a==="up"||a==="left",m,g,y,b=r.queue(),w=b.length;(u||o)&&i.push("opacity"),e.effects.save(r,i),r.show(),e.effects.createWrapper(r),f||(f=r[d==="top"?"outerHeight":"outerWidth"]()/3),u&&(y={opacity:1},y[d]=0,r.css("opacity",0).css(d,v?-f*2:f*2).animate(y,h,p)),o&&(f/=Math.pow(2,l-1)),y={},y[d]=0;for(m=0;m<l;m++)g={},g[d]=(v?"-=":"+=")+f,r.animate(g,h,p).animate(y,h,p),f=o?f*2:f/2;o&&(g={opacity:0},g[d]=(v?"-=":"+=")+f,r.animate(g,h,p)),r.queue(function(){o&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}),w>1&&b.splice.apply(b,[1,0].concat(b.splice(w,c+1))),r.dequeue()}})(jQuery);(function(e,t){e.effects.effect.clip=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=t.direction||"vertical",a=u==="vertical",f=a?"height":"width",l=a?"top":"left",c={},h,p,d;e.effects.save(r,i),r.show(),h=e.effects.createWrapper(r).css({overflow:"hidden"}),p=r[0].tagName==="IMG"?h:r,d=p[f](),o&&(p.css(f,0),p.css(l,d/2)),c[f]=o?d:0,c[l]=o?0:d/2,p.animate(c,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){o||r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}})}})(jQuery);(function(e,t){e.effects.effect.drop=function(t,n){var r=e(this),i=["position","top","bottom","left","right","opacity","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=t.direction||"left",a=u==="up"||u==="down"?"top":"left",f=u==="up"||u==="left"?"pos":"neg",l={opacity:o?1:0},c;e.effects.save(r,i),r.show(),e.effects.createWrapper(r),c=t.distance||r[a==="top"?"outerHeight":"outerWidth"](!0)/2,o&&r.css("opacity",0).css(a,f==="pos"?-c:c),l[a]=(o?f==="pos"?"+=":"-=":f==="pos"?"-=":"+=")+c,r.animate(l,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){s==="hide"&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}})}})(jQuery);(function(e,t){e.effects.effect.explode=function(t,n){function y(){c.push(this),c.length===r*i&&b()}function b(){s.css({visibility:"visible"}),e(c).remove(),u||s.hide(),n()}var r=t.pieces?Math.round(Math.sqrt(t.pieces)):3,i=r,s=e(this),o=e.effects.setMode(s,t.mode||"hide"),u=o==="show",a=s.show().css("visibility","hidden").offset(),f=Math.ceil(s.outerWidth()/i),l=Math.ceil(s.outerHeight()/r),c=[],h,p,d,v,m,g;for(h=0;h<r;h++){v=a.top+h*l,g=h-(r-1)/2;for(p=0;p<i;p++)d=a.left+p*f,m=p-(i-1)/2,s.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-p*f,top:-h*l}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:f,height:l,left:d+(u?m*f:0),top:v+(u?g*l:0),opacity:u?0:1}).animate({left:d+(u?0:m*f),top:v+(u?0:g*l),opacity:u?1:0},t.duration||500,t.easing,y)}}})(jQuery);(function(e,t){e.effects.effect.fade=function(t,n){var r=e(this),i=e.effects.setMode(r,t.mode||"toggle");r.animate({opacity:i},{queue:!1,duration:t.duration,easing:t.easing,complete:n})}})(jQuery);(function(e,t){e.effects.effect.fold=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=s==="hide",a=t.size||15,f=/([0-9]+)%/.exec(a),l=!!t.horizFirst,c=o!==l,h=c?["width","height"]:["height","width"],p=t.duration/2,d,v,m={},g={};e.effects.save(r,i),r.show(),d=e.effects.createWrapper(r).css({overflow:"hidden"}),v=c?[d.width(),d.height()]:[d.height(),d.width()],f&&(a=parseInt(f[1],10)/100*v[u?0:1]),o&&d.css(l?{height:0,width:a}:{height:a,width:0}),m[h[0]]=o?v[0]:a,g[h[1]]=o?v[1]:0,d.animate(m,p,t.easing).animate(g,p,t.easing,function(){u&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()})}})(jQuery);(function(e,t){e.effects.effect.highlight=function(t,n){var r=e(this),i=["backgroundImage","backgroundColor","opacity"],s=e.effects.setMode(r,t.mode||"show"),o={backgroundColor:r.css("backgroundColor")};s==="hide"&&(o.opacity=0),e.effects.save(r,i),r.show().css({backgroundImage:"none",backgroundColor:t.color||"#ffff99"}).animate(o,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){s==="hide"&&r.hide(),e.effects.restore(r,i),n()}})}})(jQuery);(function(e,t){e.effects.effect.pulsate=function(t,n){var r=e(this),i=e.effects.setMode(r,t.mode||"show"),s=i==="show",o=i==="hide",u=s||i==="hide",a=(t.times||5)*2+(u?1:0),f=t.duration/a,l=0,c=r.queue(),h=c.length,p;if(s||!r.is(":visible"))r.css("opacity",0).show(),l=1;for(p=1;p<a;p++)r.animate({opacity:l},f,t.easing),l=1-l;r.animate({opacity:l},f,t.easing),r.queue(function(){o&&r.hide(),n()}),h>1&&c.splice.apply(c,[1,0].concat(c.splice(h,a+1))),r.dequeue()}})(jQuery);(function(e,t){e.effects.effect.puff=function(t,n){var r=e(this),i=e.effects.setMode(r,t.mode||"hide"),s=i==="hide",o=parseInt(t.percent,10)||150,u=o/100,a={height:r.height(),width:r.width(),outerHeight:r.outerHeight(),outerWidth:r.outerWidth()};e.extend(t,{effect:"scale",queue:!1,fade:!0,mode:i,complete:n,percent:s?o:100,from:s?a:{height:a.height*u,width:a.width*u,outerHeight:a.outerHeight*u,outerWidth:a.outerWidth*u}}),r.effect(t)},e.effects.effect.scale=function(t,n){var r=e(this),i=e.extend(!0,{},t),s=e.effects.setMode(r,t.mode||"effect"),o=parseInt(t.percent,10)||(parseInt(t.percent,10)===0?0:s==="hide"?0:100),u=t.direction||"both",a=t.origin,f={height:r.height(),width:r.width(),outerHeight:r.outerHeight(),outerWidth:r.outerWidth()},l={y:u!=="horizontal"?o/100:1,x:u!=="vertical"?o/100:1};i.effect="size",i.queue=!1,i.complete=n,s!=="effect"&&(i.origin=a||["middle","center"],i.restore=!0),i.from=t.from||(s==="show"?{height:0,width:0,outerHeight:0,outerWidth:0}:f),i.to={height:f.height*l.y,width:f.width*l.x,outerHeight:f.outerHeight*l.y,outerWidth:f.outerWidth*l.x},i.fade&&(s==="show"&&(i.from.opacity=0,i.to.opacity=1),s==="hide"&&(i.from.opacity=1,i.to.opacity=0)),r.effect(i)},e.effects.effect.size=function(t,n){var r,i,s,o=e(this),u=["position","top","bottom","left","right","width","height","overflow","opacity"],a=["position","top","bottom","left","right","overflow","opacity"],f=["width","height","overflow"],l=["fontSize"],c=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],h=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=e.effects.setMode(o,t.mode||"effect"),d=t.restore||p!=="effect",v=t.scale||"both",m=t.origin||["middle","center"],g=o.css("position"),y=d?u:a,b={height:0,width:0,outerHeight:0,outerWidth:0};p==="show"&&o.show(),r={height:o.height(),width:o.width(),outerHeight:o.outerHeight(),outerWidth:o.outerWidth()},t.mode==="toggle"&&p==="show"?(o.from=t.to||b,o.to=t.from||r):(o.from=t.from||(p==="show"?b:r),o.to=t.to||(p==="hide"?b:r)),s={from:{y:o.from.height/r.height,x:o.from.width/r.width},to:{y:o.to.height/r.height,x:o.to.width/r.width}};if(v==="box"||v==="both")s.from.y!==s.to.y&&(y=y.concat(c),o.from=e.effects.setTransition(o,c,s.from.y,o.from),o.to=e.effects.setTransition(o,c,s.to.y,o.to)),s.from.x!==s.to.x&&(y=y.concat(h),o.from=e.effects.setTransition(o,h,s.from.x,o.from),o.to=e.effects.setTransition(o,h,s.to.x,o.to));(v==="content"||v==="both")&&s.from.y!==s.to.y&&(y=y.concat(l).concat(f),o.from=e.effects.setTransition(o,l,s.from.y,o.from),o.to=e.effects.setTransition(o,l,s.to.y,o.to)),e.effects.save(o,y),o.show(),e.effects.createWrapper(o),o.css("overflow","hidden").css(o.from),m&&(i=e.effects.getBaseline(m,r),o.from.top=(r.outerHeight-o.outerHeight())*i.y,o.from.left=(r.outerWidth-o.outerWidth())*i.x,o.to.top=(r.outerHeight-o.to.outerHeight)*i.y,o.to.left=(r.outerWidth-o.to.outerWidth)*i.x),o.css(o.from);if(v==="content"||v==="both")c=c.concat(["marginTop","marginBottom"]).concat(l),h=h.concat(["marginLeft","marginRight"]),f=u.concat(c).concat(h),o.find("*[width]").each(function(){var n=e(this),r={height:n.height(),width:n.width(),outerHeight:n.outerHeight(),outerWidth:n.outerWidth()};d&&e.effects.save(n,f),n.from={height:r.height*s.from.y,width:r.width*s.from.x,outerHeight:r.outerHeight*s.from.y,outerWidth:r.outerWidth*s.from.x},n.to={height:r.height*s.to.y,width:r.width*s.to.x,outerHeight:r.height*s.to.y,outerWidth:r.width*s.to.x},s.from.y!==s.to.y&&(n.from=e.effects.setTransition(n,c,s.from.y,n.from),n.to=e.effects.setTransition(n,c,s.to.y,n.to)),s.from.x!==s.to.x&&(n.from=e.effects.setTransition(n,h,s.from.x,n.from),n.to=e.effects.setTransition(n,h,s.to.x,n.to)),n.css(n.from),n.animate(n.to,t.duration,t.easing,function(){d&&e.effects.restore(n,f)})});o.animate(o.to,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){o.to.opacity===0&&o.css("opacity",o.from.opacity),p==="hide"&&o.hide(),e.effects.restore(o,y),d||(g==="static"?o.css({position:"relative",top:o.to.top,left:o.to.left}):e.each(["top","left"],function(e,t){o.css(t,function(t,n){var r=parseInt(n,10),i=e?o.to.left:o.to.top;return n==="auto"?i+"px":r+i+"px"})})),e.effects.removeWrapper(o),n()}})}})(jQuery);(function(e,t){e.effects.effect.shake=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"effect"),o=t.direction||"left",u=t.distance||20,a=t.times||3,f=a*2+1,l=Math.round(t.duration/f),c=o==="up"||o==="down"?"top":"left",h=o==="up"||o==="left",p={},d={},v={},m,g=r.queue(),y=g.length;e.effects.save(r,i),r.show(),e.effects.createWrapper(r),p[c]=(h?"-=":"+=")+u,d[c]=(h?"+=":"-=")+u*2,v[c]=(h?"-=":"+=")+u*2,r.animate(p,l,t.easing);for(m=1;m<a;m++)r.animate(d,l,t.easing).animate(v,l,t.easing);r.animate(d,l,t.easing).animate(p,l/2,t.easing).queue(function(){s==="hide"&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}),y>1&&g.splice.apply(g,[1,0].concat(g.splice(y,f+1))),r.dequeue()}})(jQuery);(function(e,t){e.effects.effect.slide=function(t,n){var r=e(this),i=["position","top","bottom","left","right","width","height"],s=e.effects.setMode(r,t.mode||"show"),o=s==="show",u=t.direction||"left",a=u==="up"||u==="down"?"top":"left",f=u==="up"||u==="left",l,c={};e.effects.save(r,i),r.show(),l=t.distance||r[a==="top"?"outerHeight":"outerWidth"](!0),e.effects.createWrapper(r).css({overflow:"hidden"}),o&&r.css(a,f?isNaN(l)?"-"+l:-l:l),c[a]=(o?f?"+=":"-=":f?"-=":"+=")+l,r.animate(c,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){s==="hide"&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}})}})(jQuery);(function(e,t){e.effects.effect.transfer=function(t,n){var r=e(this),i=e(t.to),s=i.css("position")==="fixed",o=e("body"),u=s?o.scrollTop():0,a=s?o.scrollLeft():0,f=i.offset(),l={top:f.top-u,left:f.left-a,height:i.innerHeight(),width:i.innerWidth()},c=r.offset(),h=e('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(t.className).css({top:c.top-u,left:c.left-a,height:r.innerHeight(),width:r.innerWidth(),position:s?"fixed":"absolute"}).animate(l,t.duration,t.easing,function(){h.remove(),n()})}})(jQuery);;
/*!
* jQuery UI Position 1.10.1
* http://jqueryui.com
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/position/
*/
(function( $, undefined ) {
$.ui = $.ui || {};
var cachedScrollbarWidth,
max = Math.max,
abs = Math.abs,
round = Math.round,
rhorizontal = /left|center|right/,
rvertical = /top|center|bottom/,
roffset = /[\+\-]\d+(\.[\d]+)?%?/,
rposition = /^\w+/,
rpercent = /%$/,
_position = $.fn.position;
function getOffsets( offsets, width, height ) {
return [
parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
];
}
function parseCss( element, property ) {
return parseInt( $.css( element, property ), 10 ) || 0;
}
function getDimensions( elem ) {
var raw = elem[0];
if ( raw.nodeType === 9 ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: 0, left: 0 }
};
}
if ( $.isWindow( raw ) ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
};
}
if ( raw.preventDefault ) {
return {
width: 0,
height: 0,
offset: { top: raw.pageY, left: raw.pageX }
};
}
return {
width: elem.outerWidth(),
height: elem.outerHeight(),
offset: elem.offset()
};
}
$.position = {
scrollbarWidth: function() {
if ( cachedScrollbarWidth !== undefined ) {
return cachedScrollbarWidth;
}
var w1, w2,
div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
innerDiv = div.children()[0];
$( "body" ).append( div );
w1 = innerDiv.offsetWidth;
div.css( "overflow", "scroll" );
w2 = innerDiv.offsetWidth;
if ( w1 === w2 ) {
w2 = div[0].clientWidth;
}
div.remove();
return (cachedScrollbarWidth = w1 - w2);
},
getScrollInfo: function( within ) {
var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ),
overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ),
hasOverflowX = overflowX === "scroll" ||
( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
hasOverflowY = overflowY === "scroll" ||
( overflowY === "auto" && within.height < within.element[0].scrollHeight );
return {
width: hasOverflowX ? $.position.scrollbarWidth() : 0,
height: hasOverflowY ? $.position.scrollbarWidth() : 0
};
},
getWithinInfo: function( element ) {
var withinElement = $( element || window ),
isWindow = $.isWindow( withinElement[0] );
return {
element: withinElement,
isWindow: isWindow,
offset: withinElement.offset() || { left: 0, top: 0 },
scrollLeft: withinElement.scrollLeft(),
scrollTop: withinElement.scrollTop(),
width: isWindow ? withinElement.width() : withinElement.outerWidth(),
height: isWindow ? withinElement.height() : withinElement.outerHeight()
};
}
};
$.fn.position = function( options ) {
if ( !options || !options.of ) {
return _position.apply( this, arguments );
}
// make a copy, we don't want to modify arguments
options = $.extend( {}, options );
var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
target = $( options.of ),
within = $.position.getWithinInfo( options.within ),
scrollInfo = $.position.getScrollInfo( within ),
collision = ( options.collision || "flip" ).split( " " ),
offsets = {};
dimensions = getDimensions( target );
if ( target[0].preventDefault ) {
// force left top to allow flipping
options.at = "left top";
}
targetWidth = dimensions.width;
targetHeight = dimensions.height;
targetOffset = dimensions.offset;
// clone to reuse original targetOffset later
basePosition = $.extend( {}, targetOffset );
// force my and at to have valid horizontal and vertical positions
// if a value is missing or invalid, it will be converted to center
$.each( [ "my", "at" ], function() {
var pos = ( options[ this ] || "" ).split( " " ),
horizontalOffset,
verticalOffset;
if ( pos.length === 1) {
pos = rhorizontal.test( pos[ 0 ] ) ?
pos.concat( [ "center" ] ) :
rvertical.test( pos[ 0 ] ) ?
[ "center" ].concat( pos ) :
[ "center", "center" ];
}
pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
// calculate offsets
horizontalOffset = roffset.exec( pos[ 0 ] );
verticalOffset = roffset.exec( pos[ 1 ] );
offsets[ this ] = [
horizontalOffset ? horizontalOffset[ 0 ] : 0,
verticalOffset ? verticalOffset[ 0 ] : 0
];
// reduce to just the positions without the offsets
options[ this ] = [
rposition.exec( pos[ 0 ] )[ 0 ],
rposition.exec( pos[ 1 ] )[ 0 ]
];
});
// normalize collision option
if ( collision.length === 1 ) {
collision[ 1 ] = collision[ 0 ];
}
if ( options.at[ 0 ] === "right" ) {
basePosition.left += targetWidth;
} else if ( options.at[ 0 ] === "center" ) {
basePosition.left += targetWidth / 2;
}
if ( options.at[ 1 ] === "bottom" ) {
basePosition.top += targetHeight;
} else if ( options.at[ 1 ] === "center" ) {
basePosition.top += targetHeight / 2;
}
atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
basePosition.left += atOffset[ 0 ];
basePosition.top += atOffset[ 1 ];
return this.each(function() {
var collisionPosition, using,
elem = $( this ),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseCss( this, "marginLeft" ),
marginTop = parseCss( this, "marginTop" ),
collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
position = $.extend( {}, basePosition ),
myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
if ( options.my[ 0 ] === "right" ) {
position.left -= elemWidth;
} else if ( options.my[ 0 ] === "center" ) {
position.left -= elemWidth / 2;
}
if ( options.my[ 1 ] === "bottom" ) {
position.top -= elemHeight;
} else if ( options.my[ 1 ] === "center" ) {
position.top -= elemHeight / 2;
}
position.left += myOffset[ 0 ];
position.top += myOffset[ 1 ];
// if the browser doesn't support fractions, then round for consistent results
if ( !$.support.offsetFractions ) {
position.left = round( position.left );
position.top = round( position.top );
}
collisionPosition = {
marginLeft: marginLeft,
marginTop: marginTop
};
$.each( [ "left", "top" ], function( i, dir ) {
if ( $.ui.position[ collision[ i ] ] ) {
$.ui.position[ collision[ i ] ][ dir ]( position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
my: options.my,
at: options.at,
within: within,
elem : elem
});
}
});
if ( options.using ) {
// adds feedback as second argument to using callback, if present
using = function( props ) {
var left = targetOffset.left - position.left,
right = left + targetWidth - elemWidth,
top = targetOffset.top - position.top,
bottom = top + targetHeight - elemHeight,
feedback = {
target: {
element: target,
left: targetOffset.left,
top: targetOffset.top,
width: targetWidth,
height: targetHeight
},
element: {
element: elem,
left: position.left,
top: position.top,
width: elemWidth,
height: elemHeight
},
horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
};
if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
feedback.horizontal = "center";
}
if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
feedback.vertical = "middle";
}
if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
feedback.important = "horizontal";
} else {
feedback.important = "vertical";
}
options.using.call( this, props, feedback );
};
}
elem.offset( $.extend( position, { using: using } ) );
});
};
$.ui.position = {
fit: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
outerWidth = within.width,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = withinOffset - collisionPosLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
newOverRight;
// element is wider than within
if ( data.collisionWidth > outerWidth ) {
// element is initially over the left side of within
if ( overLeft > 0 && overRight <= 0 ) {
newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
position.left += overLeft - newOverRight;
// element is initially over right side of within
} else if ( overRight > 0 && overLeft <= 0 ) {
position.left = withinOffset;
// element is initially over both left and right sides of within
} else {
if ( overLeft > overRight ) {
position.left = withinOffset + outerWidth - data.collisionWidth;
} else {
position.left = withinOffset;
}
}
// too far left -> align with left edge
} else if ( overLeft > 0 ) {
position.left += overLeft;
// too far right -> align with right edge
} else if ( overRight > 0 ) {
position.left -= overRight;
// adjust based on position and margin
} else {
position.left = max( position.left - collisionPosLeft, position.left );
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
outerHeight = data.within.height,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = withinOffset - collisionPosTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
newOverBottom;
// element is taller than within
if ( data.collisionHeight > outerHeight ) {
// element is initially over the top of within
if ( overTop > 0 && overBottom <= 0 ) {
newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
position.top += overTop - newOverBottom;
// element is initially over bottom of within
} else if ( overBottom > 0 && overTop <= 0 ) {
position.top = withinOffset;
// element is initially over both top and bottom of within
} else {
if ( overTop > overBottom ) {
position.top = withinOffset + outerHeight - data.collisionHeight;
} else {
position.top = withinOffset;
}
}
// too far up -> align with top
} else if ( overTop > 0 ) {
position.top += overTop;
// too far down -> align with bottom edge
} else if ( overBottom > 0 ) {
position.top -= overBottom;
// adjust based on position and margin
} else {
position.top = max( position.top - collisionPosTop, position.top );
}
}
},
flip: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.offset.left + within.scrollLeft,
outerWidth = within.width,
offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = collisionPosLeft - offsetLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
data.at[ 0 ] === "right" ?
-data.targetWidth :
0,
offset = -2 * data.offset[ 0 ],
newOverRight,
newOverLeft;
if ( overLeft < 0 ) {
newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
position.left += myOffset + atOffset + offset;
}
}
else if ( overRight > 0 ) {
newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
position.left += myOffset + atOffset + offset;
}
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.offset.top + within.scrollTop,
outerHeight = within.height,
offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = collisionPosTop - offsetTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
top = data.my[ 1 ] === "top",
myOffset = top ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
data.at[ 1 ] === "bottom" ?
-data.targetHeight :
0,
offset = -2 * data.offset[ 1 ],
newOverTop,
newOverBottom;
if ( overTop < 0 ) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
position.top += myOffset + atOffset + offset;
}
}
else if ( overBottom > 0 ) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
position.top += myOffset + atOffset + offset;
}
}
}
},
flipfit: {
left: function() {
$.ui.position.flip.left.apply( this, arguments );
$.ui.position.fit.left.apply( this, arguments );
},
top: function() {
$.ui.position.flip.top.apply( this, arguments );
$.ui.position.fit.top.apply( this, arguments );
}
}
};
// fraction support test
(function () {
var testElement, testElementParent, testElementStyle, offsetLeft, i,
body = document.getElementsByTagName( "body" )[ 0 ],
div = document.createElement( "div" );
//Create a "fake body" for testing based on method used in jQuery.support
testElement = document.createElement( body ? "div" : "body" );
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
};
if ( body ) {
$.extend( testElementStyle, {
position: "absolute",
left: "-1000px",
top: "-1000px"
});
}
for ( i in testElementStyle ) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild( div );
testElementParent = body || document.documentElement;
testElementParent.insertBefore( testElement, testElementParent.firstChild );
div.style.cssText = "position: absolute; left: 10.7432222px;";
offsetLeft = $( div ).offset().left;
$.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;
testElement.innerHTML = "";
testElementParent.removeChild( testElement );
})();
}( jQuery ) );
/*
*
* Wijmo Library 3.20132.8
* http://wijmo.com/
*
* Copyright(c) GrapeCity, Inc. All rights reserved.
*
* Dual licensed under the MIT or GPL Version 2 licenses.
* licensing@wijmo.com
* http://wijmo.com/widgets/license/
*
*/
/// <reference path="../External/declarations/jquery.d.ts"/>
/// <reference path="../External/declarations/jquery.ui.d.ts"/>
/// <reference path="../Base/wijmo.d.ts"/>
/*
*
* Depends:
* jquery.ui.core.js
*
*/
var wijmo;
(function (wijmo) {
$.fn.extend({
wijContent: function (url) {
return this.each(function () {
this.innerHTML = '<iframe frameborder="0" style="width: 100%; height: 100%;" src="' + url + '">"';
});
},
wijAddVisibilityObserver: /* Visibility observer */
function (h, namespace) {
return this.each(function () {
var _this = this;
$(this).addClass("wijmo-wijobserver-visibility");
$(this).bind("wijmovisibilitychanged" + (namespace ? ("." + namespace) : ""), function (e) {
//fixed an issue that if an visiblity Objerver element inside another visiblity Objerver element,
// when trigger inside the element's event, it will propagate. It's not we wanted, So stop the propagation.
h.apply(_this, arguments);
e.stopPropagation();
});
});
},
wijRemoveVisibilityObserver: function (h) {
return this.each(function () {
$(this).removeClass("wijmo-wijobserver-visibility");
if(!h) {
$(this).unbind("wijmovisibilitychanged");
} else if(jQuery.isFunction(h)) {
$(this).unbind("wijmovisibilitychanged", h);
} else {
$(this).unbind("wijmovisibilitychanged." + h);
}
});
},
wijTriggerVisibility: function () {
return this.each(function () {
var $el = $(this);
if($el.hasClass("wijmo-wijobserver-visibility")) {
$el.trigger("wijmovisibilitychanged");
}
$el.find(".wijmo-wijobserver-visibility").trigger("wijmovisibilitychanged");
});
},
leftBorderWidth: function () {
var blw = parseFloat($(this).css("borderLeftWidth"));
var pl = parseFloat($(this).css("padding-left"));
var ml = 0;
if($(this).css("margin-left") !== "auto") {
ml = parseFloat($(this).css("margin-left"));
}
return naNTest(blw) + naNTest(pl) + naNTest(ml);
},
rightBorderWidth: function () {
var brw = parseFloat($(this).css("borderRightWidth"));
var pr = parseFloat($(this).css("padding-right"));
var mr = 0;
if($(this).css("margin-right") !== "auto") {
mr = parseFloat($(this).css("margin-right"));
}
return naNTest(brw) + naNTest(pr) + naNTest(mr);
},
topBorderWidth: function () {
var blw = parseFloat($(this).css("borderTopWidth"));
var pl = parseFloat($(this).css("padding-top"));
var ml = 0;
if($(this).css("margin-top") !== "auto") {
ml = parseFloat($(this).css("margin-top"));
}
return naNTest(blw) + naNTest(pl) + naNTest(ml);
},
bottomBorderWidth: function () {
var brw = parseFloat($(this).css("borderBottomWidth"));
var pr = parseFloat($(this).css("padding-bottom"));
var mr = 0;
if($(this).css("margin-bottom") !== "auto") {
mr = parseFloat($(this).css("margin-bottom"));
}
return naNTest(brw) + naNTest(pr) + naNTest(mr);
},
borderSize: function () {
var bw = $(this).leftBorderWidth() + $(this).rightBorderWidth();
var bh = $(this).topBorderWidth() + $(this).bottomBorderWidth();
var b = {
width: bw,
height: bh
};
return b;
},
setOutWidth: function (width) {
var bw = $(this).leftBorderWidth() + $(this).rightBorderWidth();
$(this).width(width - bw);
return this;
},
setOutHeight: function (height) {
var bh = $(this).topBorderWidth() + $(this).bottomBorderWidth();
$(this).height(height - bh);
return this;
},
getWidget: function () {
var widgetName = this.data("widgetName");
if(widgetName && widgetName !== "") {
return this.data(widgetName);
}
return null;
},
wijshow: function (animation, customAnimations, customAnimationOptions, showing, shown) {
var animated = animation.animated || false, duration = animation.duration || 400, easing = animation.easing, option = animation.option || {
};
if(showing && $.isFunction(showing)) {
showing.call(this);
}
if(animated) {
if(customAnimations && customAnimations[animated]) {
customAnimations[animated](animation, $.extend(customAnimationOptions, {
complete: shown
}));
return;
}
//individual effects in jqueryui 1.9 are now defined on $.effects.effect
//rather than directly on $.effects.
if($.effects) {
if($.effects[animated] || ($.effects.effect && $.effects.effect[animated])) {
this.show(animated, $.extend(option, {
easing: easing
}), duration, shown);
return;
}
}
}
this.show();
if(shown && $.isFunction(shown)) {
shown.call(this);
}
},
wijhide: function (animation, customAnimations, customAnimationOptions, hiding, hidden) {
var animated = animation.animated || false, duration = animation.duration || 400, easing = animation.easing, option = animation.option || {
};
if(hiding && $.isFunction(hiding)) {
hiding.call(this);
}
if(animated) {
if(customAnimations && customAnimations[animated]) {
customAnimations[animated](animation, $.extend(customAnimationOptions, {
complete: hidden
}));
return;
}
//individual effects in jqueryui 1.9 are now defined on $.effects.effect
//rather than directly on $.effects.
if($.effects) {
if($.effects[animated] || ($.effects.effect && $.effects.effect[animated])) {
this.hide(animated, $.extend(option, {
easing: easing
}), duration, hidden);
return;
}
}
}
this.hide();
if(hidden && $.isFunction(hidden)) {
hidden.call(this);
}
}
});
function naNTest(num) {
return isNaN(num) ? 0 : num;
}
//Saves a set of properties in a data storage
$.save = function (element, set) {
if($.effects) {
return $.effects.save(element, set);
}
for(var i = 0; i < set.length; i++) {
if(set[i] !== null) {
element.data("ec.storage." + set[i], element[0].style[set[i]]);
}
}
};
// Restores a set of previously saved properties from a data storage
$.restore = function (element, set) {
if($.effects) {
return $.effects.restore(element, set);
}
for(var i = 0; i < set.length; i++) {
if(set[i] !== null) {
element.css(set[i], element.data("ec.storage." + set[i]));
}
}
};
// Wraps the element around a wrapper that copies position properties
$.createWrapper = function (element) {
if($.effects) {
return $.effects.createWrapper(element);
}
// if the element is already wrapped, return it
if(element.parent().is('.ui-effects-wrapper')) {
return element.parent();
}
// wrap the element
var props = {
width: element.outerWidth(true),
height: element.outerHeight(true),
'float': element.css('float')
}, wrapper = $('<div></div>').addClass('ui-effects-wrapper').css({
fontSize: '100%',
background: 'transparent',
border: 'none',
margin: 0,
padding: 0
}), active = document.activeElement;
element.wrap(wrapper);
// Fixes #7595 - Elements lose focus when wrapped.
if(element[0] === active || $.contains(element[0], active)) {
$(active).focus();
}
wrapper = element.parent()//Hotfix for jQuery 1.4 since some change in wrap() seems to actually loose the reference to the wrapped element
;
// transfer positioning properties to the wrapper
if(element.css('position') == 'static') {
wrapper.css({
position: 'relative'
});
element.css({
position: 'relative'
});
} else {
$.extend(props, {
position: element.css('position'),
zIndex: element.css('z-index')
});
$.each([
'top',
'left',
'bottom',
'right'
], function (i, pos) {
props[pos] = element.css(pos);
if(isNaN(parseInt(props[pos], 10))) {
props[pos] = 'auto';
}
});
element.css({
position: 'relative',
top: 0,
left: 0,
right: 'auto',
bottom: 'auto'
});
}
return wrapper.css(props).show();
};
$.removeWrapper = function (element) {
if($.effects) {
return $.effects.removeWrapper(element);
}
var parent, active = document.activeElement;
if(element.parent().is('.ui-effects-wrapper')) {
parent = element.parent().replaceWith(element);
// Fixes #7595 - Elements lose focus when wrapped.
if(element[0] === active || $.contains(element[0], active)) {
$(active).focus();
}
return parent;
}
return element;
};
$.setMode = function (el, mode) {
if($.effects) {
return $.effects.setMode(el, mode);
}
if(mode === "toggle") {
mode = el.is(":hidden") ? "show" : "hide";
}
return mode;
};
var wijCharValidator = function () {
};
$.extend(wijCharValidator.prototype, {
_UTFPunctuationsString: ' ! \" # % & \' ( ) * , - . / : ; ? @ [ \\ ] { } \u00a1 \u00ab \u00ad \u00b7 \u00bb \u00bf \u037e \u0387 \u055a \u055b \u055c \u055d \u055e \u055f \u0589 \u058a \u05be \u05c0 \u05c3 \u05f3 \u05f4 \u060c \u061b \u061f \u066a \u066b \u066c \u066d \u06d4 \u0700 \u0701 \u0702 \u0703 \u0704 \u0705 \u0706 \u0707 \u0708 \u0709 \u070a \u070b \u070c \u070d \u0964 \u0965 \u0970 \u0df4 \u0e4f \u0e5a \u0e5b \u0f04 \u0f05 \u0f06 \u0f07 \u0f08 \u0f09 \u0f0a \u0f0b \u0f0c \u0f0d \u0f0e \u0f0f \u0f10 \u0f11 \u0f12 \u0f3a \u0f3b \u0f3c \u0f3d \u0f85 \u104a \u104b \u104c \u104d \u104e \u104f \u10fb \u1361 \u1362 \u1363 \u1364 \u1365 \u1366 \u1367 \u1368 \u166d \u166e \u169b \u169c \u16eb \u16ec \u16ed \u17d4 \u17d5 \u17d6 \u17d7 \u17d8 \u17d9 \u17da \u17dc \u1800 \u1801 \u1802 \u1803 \u1804 \u1805 \u1806 \u1807 \u1808 \u1809 \u180a \u2010 \u2011 \u2012 \u2013 \u2014 \u2015 \u2016 \u2017 \u2018 \u2019 \u201a \u201b \u201c \u201d \u201e \u201f \u2020 \u2021 \u2022 \u2023 \u2024 \u2025 \u2026 \u2027 \u2030 \u2031 \u2032 \u2033 \u2034 \u2035 \u2036 \u2037 \u2038 \u2039 \u203a \u203b \u203c \u203d \u203e \u2041 \u2042 \u2043 \u2045 \u2046 \u2048 \u2049 \u204a \u204b \u204c \u204d \u207d \u207e \u208d \u208e \u2329 \u232a \u3001 \u3002 \u3003 \u3008 \u3009 \u300a \u300b \u300c \u300d \u300e \u300f \u3010 \u3011 \u3014 \u3015 \u3016 \u3017 \u3018 \u3019 \u301a \u301b \u301c \u301d \u301e \u301f \u3030 \ufd3e \ufd3f \ufe30 \ufe31 \ufe32 \ufe35 \ufe36 \ufe37 \ufe38 \ufe39 \ufe3a \ufe3b \ufe3c \ufe3d \ufe3e \ufe3f \ufe40 \ufe41 \ufe42 \ufe43 \ufe44 \ufe49 \ufe4a \ufe4b \ufe4c \ufe50 \ufe51 \ufe52 \ufe54 \ufe55 \ufe56 \ufe57 \ufe58 \ufe59 \ufe5a \ufe5b \ufe5c \ufe5d \ufe5e \ufe5f \ufe60 \ufe61 \ufe63 \ufe68 \ufe6a \ufe6b \uff01 \uff02 \uff03 \uff05 \uff06 \uff07 \uff08 \uff09 \uff0a \uff0c \uff0d \uff0e \uff0f \uff1a \uff1b \uff1f \uff20 \uff3b \uff3c \uff3d \uff5b \uff5d \uff61 \uff62 \uff63 \uff64\';this.UTFWhitespacesString_=\'\t \u000b \u000c \u001f \u00a0 \u1680 \u2000 \u2001 \u2002 \u2003 \u2004 \u2005 \u2006 \u2007 \u2008 \u2009 \u200a \u200b \u2028 \u202f \u3000',
isDigit: function (c) {
var code = c.charCodeAt(0);
return (code >= 48 && code < 58);
},
isLetter: function (c) {
return !!((c + '').match(new RegExp('[A-Za-z\u00aa\u00b5\u00ba\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u021f\u0222-\u0233\u0250-\u02ad\u02b0-\u02b8\u02bb-\u02c1\u02d0\u02d1\u02e0-\u02e4\u02ee\u037a\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03ce\u03d0-\u03d7\u03da-\u03f3\u0400-\u0481\u048c-\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0-\u04f5\u04f8\u04f9\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0621-\u063a\u0640-\u064a\u0671-\u06d3\u06d5\u06e5\u06e6\u06fa-\u06fc\u0710\u0712-\u072c\u0780-\u07a5\u0905-\u0939\u093d\u0950\u0958-\u0961\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8b\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b36-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb5\u0bb7-\u0bb9\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cde\u0ce0\u0ce1\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d28\u0d2a-\u0d39\u0d60\u0d61\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc\u0edd\u0f00\u0f40-\u0f47\u0f49-\u0f6a\u0f88-\u0f8b\u1000-\u1021\u1023-\u1027\u1029\u102a\u1050-\u1055\u10a0-\u10c5\u10d0-\u10f6\u1100-\u1159\u115f-\u11a2\u11a8-\u11f9\u1200-\u1206\u1208-\u1246\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1286\u1288\u128a-\u128d\u1290-\u12ae\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12ce\u12d0-\u12d6\u12d8-\u12ee\u12f0-\u130e\u1310\u1312-\u1315\u1318-\u131e\u1320-\u1346\u1348-\u135a\u13a0-\u13f4\u1401-\u166c\u166f-\u1676\u1681-\u169a\u16a0-\u16ea\u1780-\u17b3\u1820-\u1877\u1880-\u18a8\u1e00-\u1e9b\u1ea0-\u1ef9\u1f00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u207f\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2131\u2133-\u2139\u3005\u3006\u3031-\u3035\u3041-\u3094\u309d\u309e\u30a1-\u30fa\u30fc-\u30fe\u3105-\u312c\u3131-\u318e\u31a0-\u31b7\u3400-\u4db5\u4e00-\u9fa5\ua000-\ua48c\uac00-\ud7a3\uf900-\ufa2d\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe72\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]')));
},
isLetterOrDigit: function (c) {
return this.isLetter(c) || this.isDigit(c);
},
isDoubleByteNumber: function (c) {
var code = c.charCodeAt(0);
return code >= 65296 && code < 65306;
},
isSymbol: function (c) {
var re = new RegExp('[$+<->^`|~\u00a2-\u00a9\u00ac\u00ae-\u00b1\u00b4\u00b6\u00b8\u00d7\u00f7\u02b9\u02ba\u02c2-\u02cf\u02d2-\u02df\u02e5-\u02ed\u0374\u0375\u0384\u0385\u0482\u06e9\u06fd\u06fe\u09f2\u09f3\u09fa\u0b70\u0e3f\u0f01-\u0f03\u0f13-\u0f17\u0f1a-\u0f1f\u0f34\u0f36\u0f38\u0fbe-\u0fc5\u0fc7-\u0fcc\u0fcf\u17db\u1fbd\u1fbf-\u1fc1\u1fcd-\u1fcf\u1fdd-\u1fdf\u1fed-\u1fef\u1ffd\u1ffe\u2044\u207a-\u207c\u208a-\u208c\u20a0-\u20af\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211e-\u2123\u2125\u2127\u2129\u212e\u2132\u213a\u2190-\u21f3\u2200-\u22f1\u2300-\u2328\u232b-\u237b\u237d-\u239a\u2400-\u2426\u2440-\u244a\u249c-\u24e9\u2500-\u2595\u25a0-\u25f7\u2600-\u2613\u2619-\u2671\u2701-\u2704\u2706-\u2709\u270c-\u2727\u2729-\u274b\u274d\u274f-\u2752\u2756\u2758-\u275e\u2761-\u2767\u2794\u2798-\u27af\u27b1-\u27be\u2800-\u28ff\u2e80-\u2e99\u2e9b-\u2ef3\u2f00-\u2fd5\u2ff0-\u2ffb\u3004\u3012\u3013\u3020\u3036\u3037\u303e\u303f\u309b\u309c\u3190\u3191\u3196-\u319f\u3200-\u321c\u322a-\u3243\u3260-\u327b\u327f\u328a-\u32b0\u32c0-\u32cb\u32d0-\u32fe\u3300-\u3376\u337b-\u33dd\u33e0-\u33fe\ua490-\ua4a1\ua4a4-\ua4b3\ua4b5-\ua4c0\ua4c2-\ua4c4\ua4c6\ufb29\ufe62\ufe64-\ufe66\ufe69\uff04\uff0b\uff1c-\uff1e\uff3e\uff40\uff5c\uff5e\uffe0-\uffe6\uffe8-\uffee\ufffc\ufffd]');
return re.test(c + '');
},
isPunctuation: function (c) {
return this._UTFPunctuationsString.indexOf(c) >= 0;
},
isPrintableChar: function (c) {
if((!this.isLetterOrDigit(c) && !this.isPunctuation(c)) && !this.isSymbol(c) && !this.isDoubleByteNumber(c)) {
return (c === ' ');
}
return true;
},
isAscii: function (c) {
return (c >= '!') && (c <= '~');
},
isAsciiLetter: function (c) {
return ((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z'));
},
isUpper: function (c) {
return c.toUpperCase() === c;
},
isLower: function (c) {
return c.toLowerCase() === c;
},
isAlphanumeric: function (c) {
return !this.isLetter(c) ? this.isDigit(c) : true;
},
isAciiAlphanumeric: function (c) {
if(((c < '0') || (c > '9')) && ((c < 'A') || (c > 'Z'))) {
if(c >= 'a') {
return (c <= 'z');
}
return false;
}
return true;
},
setChar: function (input, ch, pos) {
if(pos >= input.length || pos < 0) {
return input;
}
return '' || input.substr(0, pos) + ch + input.substr(pos + 1);
}
});
// add the zIndex method to util if using in mobile.
if(!$.fn.zIndex) {
$.fn.zIndex = function (zIndex) {
if(zIndex !== undefined) {
return this.css("zIndex", zIndex);
}
if(this.length) {
var elem = $(this[0]), position, value;
while(elem.length && elem[0] !== document) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css("position");
if(position === "absolute" || position === "relative" || position === "fixed") {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt(elem.css("zIndex"), 10);
if(!isNaN(value) && value !== 0) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
};
}
var c__escapeArr1 = [
'\n',
'\r',
'"',
'@',
'+',
'\'',
'<',
'>',
'%',
'{',
'}'
], c__escapeArr2 = [
"!ESC!NN!",
"!ESC!RR!",
"!ESC!01!",
"!ESC!02!",
"!ESC!03!",
"!ESC!04!",
"!ESC!05!",
"!ESC!06!",
"!ESC!07!",
"!ESC!08!",
"!ESC!09!"
], c__escapeArr3 = [
"(\n)",
"(\r)",
"(\")",
"(@)",
"(\\+)",
"(')",
"(\\<)",
"(\\>)",
"(%)",
"(\\{)",
"(\\})"
];
if(!$.wij) {
$.extend({
wij: {
charValidator: new wijCharValidator(),
encodeString: function (s) {
for(var i = 0; i < c__escapeArr1.length; i++) {
var r = /c__escapeArr3[i]/g;
s = s.replace(r, c__escapeArr2[i]);
}
return s;
},
decodeString: function (s) {
if(s === "") {
return;
}
for(var i = 0; i < c__escapeArr2.length; i++) {
var r = /c__escapeArr2[i]/g;
s = s.replace(r, c__escapeArr1[i]);
}
return s;
}
}
});
}
;
//copy from jQuery-migrate.js in case of jQuery 1.9 removing $.browser api.
if(!jQuery.uaMatch) {
jQuery.uaMatch = function (ua) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || [];
return {
browser: match[1] || "",
version: match[2] || "0"
};
};
}
// Don't clobber any existing jQuery.browser in case it's different
if(!jQuery.browser) {
var matched = jQuery.uaMatch(navigator.userAgent), browser = {
version: "0",
msie: false,
opera: false,
safari: false,
mozilla: false,
webkit: false,
chrome: false
};
if(matched.browser) {
browser[matched.browser] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if(browser.chrome) {
browser.webkit = true;
} else if(browser.webkit) {
browser.safari = true;
}
jQuery.browser = browser;
}
//Fix a known jQuery issue #8710, fix tfs issue #34746
//http://bugs.jqueryui.com/ticket/8710
if($.ui && $.ui.position && $.ui.position.flipfit) {
$.ui.position.flip.top = function (position, data) {
var within = data.within, withinOffset = within.offset.top + within.scrollTop, outerHeight = within.height, offsetTop = within.isWindow ? within.scrollTop : within.offset.top, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = collisionPosTop - offsetTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, top = data.my[1] === "top", myOffset = top ? -data.elemHeight : data.my[1] === "bottom" ? data.elemHeight : 0, atOffset = data.at[1] === "top" ? data.targetHeight : data.at[1] === "bottom" ? -data.targetHeight : 0, offset = -2 * data.offset[1], newOverTop, newOverBottom;
if(overTop < 0) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
if((position.top + myOffset + atOffset + offset) > overTop && (newOverBottom < 0 || newOverBottom < Math.abs(overTop))) {
position.top += myOffset + atOffset + offset;
}
} else if(overBottom > 0) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
if((position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - offsetTop) < overBottom && (newOverTop > 0 || Math.abs(newOverTop) < overBottom)) {
//if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
position.top += myOffset + atOffset + offset;
}
}
};
}
// for upgrade jQuery UI 1.10, it remove the offset option from option arguments.
var $position = $.fn.position;
$.fn.position = function (options) {
//$position.call(this, options);
if(options && $.isPlainObject(options) && options.offset) {
var my = (options.my || "").split(" "), rhorizontal = /left|center|right/, rvertical = /top|center|bottom/, offset = (options.offset || "").split(" ");
if(my.length === 1) {
rhorizontal.test(my[0]) ? my.concat([
"center"
]) : rvertical.test(my[0]) ? [
"center"
].concat(my) : [
"center",
"center"
];
}
if(offset.length === 1) {
offset.concat(offset[0]);
}
$.each(my, function (i, m) {
if(/\+|-/.test(offset[i])) {
my[i] = my[i] + offset[i];
} else {
my[i] = my[i] + "+" + offset[i];
}
});
options.my = my.join(" ");
}
return $position.apply(this, arguments);
};
})(wijmo || (wijmo = {}));
function __wijReadOptionEvents(eventsArr, widgetInstance) {
// handle option events
for(var k = 0; k < eventsArr.length; k++) {
if(widgetInstance.options[eventsArr[k]] !== null) {
widgetInstance.element.bind(eventsArr[k], widgetInstance.options[eventsArr[k]]);
}
}
//handle option event names separated by space, like: "afterexpand aftercollapse"
for(var k in widgetInstance.options) {
if(k.indexOf(" ") !== -1) {
// possible multiple events separated by space:
var arr = k.split(" ");
for(var j = 0; j < arr.length; j++) {
if(arr[j].length > 0) {
widgetInstance.element.bind(arr[j], widgetInstance.options[k]);
}
}
}
}
}
;
function wijmoASPNetParseOptionsReviewer(o, k) {
var a, v = o[k], d;
if(v) {
switch(typeof v) {
case "string":
a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?):(\d{3})Z$/.exec(v);
if(a) {
d = new Date(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6], +a[7]);
d.setFullYear(+a[1]);
o[k] = d;
}
break;
case "object":
if(v.needQuotes !== undefined && v.valueString !== undefined) {
if(!v.needQuotes) {
o[k] = eval(v.valueString);
} else {
o[k] = v.valueString;
}
} else {
for(k in v) {
wijmoASPNetParseOptionsReviewer(v, k);
}
}
break;
}
}
}
function wijmoASPNetParseOptions(o) {
var k;
if(!o) {
return o;
}
for(k in o) {
wijmoASPNetParseOptionsReviewer(o, k);
}
return o;
}
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
/// <reference path="../wijutil/jquery.wijmo.wijtouchutil.ts"/>
/// <reference path="../External/declarations/jquerymobile.d.ts"/>
/// <reference path="wijmo.d.ts"/>
/*
* Depends:
* jquery.ui.widget.js
*
*/
var wijmo;
(function (wijmo) {
var $ = jQuery;
var jQueryWijmo = (function () {
function jQueryWijmo() { }
jQueryWijmo.autoMobilize = true;
jQueryWijmo.wijCSS = {
widget: "ui-widget",
overlay: "ui-widget-overlay",
content: "ui-widget-content",
header: "ui-widget-header",
stateDisabled: "ui-state-disabled",
stateFocus: "ui-state-focus",
stateActive: "ui-state-active",
stateDefault: "ui-state-default",
stateHightlight: "ui-state-highlight",
stateHover: "ui-state-hover",
stateChecked: "ui-state-checked",
stateError: "ui-state-error",
getState: function (name) {
name = name.charAt(0).toUpperCase() + name.substr(1);
return $.wijmo.wijCSS["state" + name];
},
icon: "ui-icon",
iconCheck: "ui-icon-check",
iconRadioOn: "ui-icon-radio-on",
iconRadioOff: "ui-icon-radio-off",
iconClose: "ui-icon-close",
iconArrow4Diag: "ui-icon-arrow-4-diag",
iconNewWin: "ui-icon-newwin",
iconVGripSolid: "ui-icon-grip-solid-vertical",
iconHGripSolid: "ui-icon-grip-solid-horizontal",
iconPlay: "ui-icon-play",
iconPause: "ui-icon-pause",
iconStop: "ui-icon-stop",
iconArrowUp: "ui-icon-triangle-1-n",
iconArrowRight: "ui-icon-triangle-1-e",
iconArrowDown: "ui-icon-triangle-1-s",
iconArrowLeft: "ui-icon-triangle-1-w",
iconArrowRightDown: "ui-icon-triangle-1-se",
iconCaratUp: "ui-icon-carat-1-n",
iconCaratRight: "ui-icon-carat-1-e",
iconCaratDown: "ui-icon-carat-1-s",
iconCaratLeft: "ui-icon-carat-1-w",
iconSeekFirst: "ui-icon-seek-first",
iconSeekEnd: "ui-icon-seek-end",
iconSeekNext: "ui-icon-seek-next",
iconSeekPrev: "ui-icon-seek-prev",
inputSpinnerLeft: "ui-input-spinner-left",
inputSpinnerRight: "ui-input-spinner-right",
inputTriggerLeft: "ui-input-trigger-left",
inputTriggerRight: "ui-input-trigger-right",
inputSpinnerTriggerLeft: "ui-input-spinner-trigger-left",
inputSpinnerTriggerRight: "ui-input-spinner-trigger-right",
cornerAll: "ui-corner-all",
cornerLeft: "ui-corner-left",
cornerRight: "ui-corner-right",
cornerBottom: "ui-corner-bottom",
cornerBL: "ui-corner-bl",
cornerBR: "ui-corner-br",
cornerTop: "ui-corner-top",
cornerTL: "ui-corner-tl",
cornerTR: "ui-corner-tr",
helperClearFix: "ui-helper-clearfix",
helperReset: "ui-helper-reset",
helperHidden: "ui-helper-hidden",
priorityPrimary: "ui-priority-primary",
prioritySecondary: "ui-priority-secondary",
button: "ui-button",
buttonText: "ui-button-text",
buttonTextOnly: "ui-button-text-only",
tabs: "ui-tabs",
tabsTop: "ui-tabs-top",
tabsBottom: "ui-tabs-bottom",
tabsLeft: "ui-tabs-left",
tabsRight: "ui-tabs-right",
tabsLoading: "ui-tabs-loading",
tabsActive: "ui-tabs-active",
tabsPanel: "ui-tabs-panel",
tabsNav: "ui-tabs-nav",
tabsHide: "ui-tabs-hide",
tabsCollapsible: "ui-tabs-collapsible",
activeMenuitem: "ui-active-menuitem"
};
jQueryWijmo.wijMobileCSS = {
content: "ui-content",
header: "ui-header",
overlay: "ui-overlay",
stateDisabled: "ui-disabled",
stateFocus: "ui-focus",
stateActive: "ui-btn-active",
stateDefault: "ui-btn-up-a",
iconArrowUp: "ui-icon-arrow-u",
iconArrowRight: "ui-icon-arrow-r",
iconArrowDown: "ui-icon-arrow-d",
iconArrowLeft: "ui-icon-arrow-l",
iconArrowRightDown: "ui-icon-arrow-d",
iconSeekFirst: "ui-icon-arrow-l",
iconSeekEnd: "ui-icon-arrow-r",
iconSeekNext: "ui-icon-arrow-r",
iconSeekPrev: "ui-icon-arrow-l",
iconClose: "ui-icon-delete",
iconStop: "ui-icon-grid",
iconCheck: "ui-icon-checkbox-on"
};
jQueryWijmo.wijMobileThemePrefix = [
"ui-bar",
"ui-body",
"ui-overlay",
"ui-btn-up",
"ui-btn-hover",
"ui-btn-down"
];
jQueryWijmo.autoInit = // auto self-init widgets
function autoInit(widgetName, pageKeepNative) {
if($.mobile && $.mobile.page && pageKeepNative) {
//add keepNative to page to prevent default auto-initialization of form elements
var keepNative = $.mobile.page.prototype.options.keepNative;
if(keepNative && keepNative.length && keepNative.indexOf(pageKeepNative) === -1) {
keepNative = [
keepNative,
pageKeepNative
].join(", ");
} else {
keepNative = pageKeepNative;
}
$.mobile.page.prototype.options.keepNative = keepNative;
}
if($.mobile && $.wijmo[widgetName] && $.wijmo[widgetName].prototype && $.wijmo[widgetName].prototype.enhanceWithin) {
$(document).bind("pagecreate create", function (e) {
$.wijmo[widgetName].prototype.enhanceWithin(e.target);
});
}
};
jQueryWijmo.registerWidget = function registerWidget(name, baseType, def, customizeInit) {
var fullName = "wijmo." + name, init;
if(typeof def === 'function') {
init = def;
def = null;
}
if(def === null || def === undefined) {
def = $.extend(true, {
}, baseType);
baseType = $.wijmo.widget;
}
def.options = def.options || {
};
def.options.initSelector = def.options.initSelector || ":jqmData(role='" + name + "')";
if($.mobile && def.options && def.options.wijMobileCSS) {
def.options.wijCSS = def.options.wijCSS || {
};
$.extend(def.options.wijCSS, def.options.wijMobileCSS);
}
$.widget(fullName, baseType, def);
if(init) {
init.call();
} else if(this.autoInit) {
this.autoInit(name, def.options.initSelector);
}
};
jQueryWijmo.addThemeToMobileCSS = function addThemeToMobileCSS(theme, classes) {
$.each(classes, function (key, cl) {
if(typeof cl === "string") {
$.each(jQueryWijmo.wijMobileThemePrefix, function (idx, css) {
var regExp = new RegExp("\\b" + css);
if(regExp.test(cl)) {
classes[key] = cl + " " + css + "-" + theme;
}
});
} else {
jQueryWijmo.addThemeToMobileCSS(theme, cl);
}
});
};
return jQueryWijmo;
})();
$.wijmo = jQueryWijmo;
// Declarations to support TypeScript type system
var JQueryUIWidget = (function () {
function JQueryUIWidget() { }
JQueryUIWidget.prototype.destroy = /** Removes the dialog functionality completely. This will return the element back to its pre-init state. */
function () {
};
JQueryUIWidget.prototype._setOption = function (name, value) {
};
JQueryUIWidget.prototype._create = function () {
};
JQueryUIWidget.prototype._init = function () {
};
JQueryUIWidget.prototype.widget = /** Returns a jQuery object containing the original element or other relevant generated element. */
function () {
return this.element;
};
return JQueryUIWidget;
})();
wijmo.JQueryUIWidget = JQueryUIWidget;
JQueryUIWidget.prototype.options = {
wijCSS: $.wijmo.wijCSS
};
JQueryUIWidget.prototype.destroy = function () {
$.Widget.prototype.destroy.apply(this, arguments);
};
JQueryUIWidget.prototype._setOption = function (name, value) {
$.Widget.prototype._setOption.apply(this, arguments);
};
JQueryUIWidget.prototype._create = function () {
$.Widget.prototype._create.apply(this, arguments);
};
JQueryUIWidget.prototype._init = function () {
$.Widget.prototype._init.apply(this, arguments);
};
var JQueryMobileWidget = (function (_super) {
__extends(JQueryMobileWidget, _super);
function JQueryMobileWidget() {
_super.apply(this, arguments);
}
return JQueryMobileWidget;
})(JQueryUIWidget);
wijmo.JQueryMobileWidget = JQueryMobileWidget;
//Fires a wijmoinit event on the document object for users to override default settings.
//Use $(document).bind("wijmoinit", function() {//apply overrides here});
//The event handler must be binded before jquery.wijmo.widget is loaded.
$(window.document).trigger("wijmoinit");
var wijmoWidget = (function (_super) {
__extends(wijmoWidget, _super);
function wijmoWidget() {
_super.apply(this, arguments);
this._widgetCreated = false;
}
wijmoWidget.prototype._baseWidget = function () {
return this._isMobile ? $.mobile.widget : $.Widget;
};
wijmoWidget.prototype._createWidget = function (options, element) {
this._widgetCreated = true;
//Set widgetName to widgetEventPrefix for binding events like following,
//$(element).bind(widgetName + eventName, function() {});
if(this._syncEventPrefix) {
this.widgetEventPrefix = this.widgetName;
}
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
this._baseWidget().prototype._createWidget.apply(this, arguments);
};
wijmoWidget.prototype._create = function () {
this._baseWidget().prototype._create.apply(this, arguments);
};
wijmoWidget.prototype._init = function () {
this._baseWidget().prototype._init.apply(this, arguments);
};
wijmoWidget.prototype.destroy = function () {
this._baseWidget().prototype.destroy.apply(this, arguments);
};
wijmoWidget.prototype._setOption = function (name, value) {
this._baseWidget().prototype._setOption.apply(this, arguments);
//Fixed an issue for jQuery mobile. when set the disabled option, the jQuery mobile set
// 'ui-state-disabled' css on the element.
if(name === "disabled" && value && this._isMobile) {
this.element.removeClass("ui-state-disabled").addClass(this.options.wijCSS.stateDisabled);
}
};
return wijmoWidget;
})(JQueryMobileWidget);
wijmo.wijmoWidget = wijmoWidget;
wijmoWidget.prototype._syncEventPrefix = true;
wijmoWidget.prototype._isMobile = false;
//Check if jQuery Mobile is on the page and make sure autoMobilize is set to true (so that this default behavior can be turned off)
if($.mobile != null && $.wijmo.autoMobilize === true) {
//Set mobile CSS classes to work with jQuery Mobile CSS Framework
//wijmoWidget.options.wijCSS = $.wijmo.wijMobileCSS;
$.extend(true, wijmoWidget.prototype.options.wijCSS, $.wijmo.wijMobileCSS);
wijmoWidget.prototype._isMobile = true;
wijmoWidget.prototype.options = $.extend(true, {
}, wijmoWidget.prototype.options, wijmoWidget.prototype._baseWidget().prototype.options);
wijmoWidget.prototype.enhanceWithin = function (target, useKeepNative) {
if(!this._widgetCreated) {
$.mobile.widget.prototype.enhanceWithin.apply(this, arguments);
}
};
wijmoWidget.prototype._getCreateOptions = function () {
var ele = this.element, baseOptions, optionsParser = optionsParser = function (value) {
// Add quotes to key pair.
if(typeof value === 'undefined') {
return {
};
} else if(value === null) {
return {
};
}
var reg = /(?:(?:\{[\n\r\t\s]*(.+?)\s*\:[\n\r\t\s]*)|(?:,[\n\r\t\s]*(.+?)\s*\:[\n\r\t\s]*))('(.*?[^\\])')?/gi, arrReg = /\[.*?(?=[\]\[])|[\]\[].*?(?=[\]])/gi, str = value.replace(reg, function (i, str1, str2, str3) {
var result, reg1 = /[\n\r\t\s]*['"]?([^\{,\s]+?)['"]?\s*:[\n\r\t\s]*/i, reg2 = /\:[\n\r\t\s]*(?:'(.*)')?/i;
result = i.replace(reg1, "\"$1\":");
if(str3) {
return result.replace(reg2, ":\"$1\"");
}
return result;
}).replace(arrReg, function (i) {
var reg1 = /'(.*?[^\\])'/g;
return i.replace(reg1, "\"$1\"");
});
return $.parseJSON(str);
}, options = optionsParser(ele.attr("data-" + $.mobile.nsNormalize("options"))), wijCSS;
baseOptions = $.mobile.widget.prototype._getCreateOptions.apply(this, arguments);
//add theme support in mobile mode
wijCSS = $.extend(true, {
}, this.options.wijCSS);
this.theme = this.options.theme !== undefined ? this.options.theme : this.element.jqmData("theme");
if(this.theme) {
$.wijmo.addThemeToMobileCSS(this.theme, wijCSS);
}
return $.extend(baseOptions, {
wijCSS: wijCSS
}, options);
};
$.widget("wijmo.widget", $.mobile.widget, wijmoWidget.prototype);
} else {
wijmoWidget.prototype.options = $.extend(true, {
}, wijmoWidget.prototype.options, wijmoWidget.prototype._baseWidget().prototype.options);
//jQuery Mobile either does not exist or the autoMobilize flag has been turned off.
$.widget("wijmo.widget", wijmoWidget.prototype);
}
})(wijmo || (wijmo = {}));
;
/// <reference path="../External/declarations/jquery.d.ts"/>
/// <reference path="../External/declarations/jquery.ui.d.ts"/>
/*globals window*/
/*
* Wijmo Touch Utilities.
*
* Depends:
* jquery.js
*
*/
jQuery.extend(jQuery.support, {
isTouchEnabled: function () {
if(!("ontouchstart" in window) && !("ontouchend" in document) && //!window.navigator.msPointerEnabled) {
!(typeof (window.navigator.msMaxTouchPoints) !== "undefined" && window.navigator.msMaxTouchPoints > 0)) {
return false;
} else {
return true;
}
}
});
/** Deprecated!!!
* @deprecated
*/
function wijmoApplyWijTouchUtilEvents($) {
return $;
}
var wijmo;
(function (wijmo) {
(function (touch) {
"use strict";
var $ = jQuery;
var dataPropertyName = "virtualMouseBindings", touchTargetPropertyName = "virtualTouchID", virtualEventNames = "wijmouseover wijmousedown wijmousemove wijmouseup wijclick wijtap wijdoubletap wijtaphold wijmouseout wijmousecancel".split(" "), msPointerEnabled = window.navigator.msPointerEnabled, realEventNames = {
"wijmouseover": (!msPointerEnabled ? "mouseover" : "MSPointerOver"),
"wijmousedown": (!msPointerEnabled ? "mousedown" : "MSPointerDown"),
"wijmousemove": (!msPointerEnabled ? "mousemove" : "MSPointerMove"),
"wijmouseup": (!msPointerEnabled ? "mouseup" : "MSPointerUp"),
"wijmouseout": (!msPointerEnabled ? "mouseout" : "MSPointerOut"),
"wijmousecancel": (!msPointerEnabled ? "mousecancel" : "mousecancel"),
"wijclick": (!msPointerEnabled ? "click" : "MSGestureTap"),
"wijdoubletap": (!msPointerEnabled ? "dblclick" : "MSGestureDoubleTap"),
"wijtaphold": (!msPointerEnabled ? "gesturehold" : "MSGestureHold")
}, touchEventProps = "clientX clientY pageX pageY screenX screenY".split(" "), nativeEventProps = "clientX clientY pageX pageY screenX screenY".split(" "), mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [], mouseEventProps = $.event.props.concat(mouseHookProps), activeDocHandlers = {
}, resetTimerID = 0, startX = 0, startY = 0, didScroll = false, clickBlockList = [], blockMouseTriggers = false, blockTouchTriggers = false, eventCaptureSupported = "addEventListener" in document, $document = $(document), nextTouchID = 1, lastTouchID = 0, touchStartEventM = (!msPointerEnabled) ? "touchstart" : "MSPointerDown", touchEndEventM = (!msPointerEnabled) ? "touchend" : "MSPointerUp", touchMoveEventM = (!msPointerEnabled) ? "touchmove" : "MSPointerMove", touchScrollEventM = (!msPointerEnabled) ? "scroll" : "scroll";
$.wijmouse = {
moveDistanceThreshold: 10,
clickDistanceThreshold: 10,
resetTimerDuration: 1500
};
function getNativeEvent(event) {
while(event && typeof event.originalEvent !== "undefined") {
event = event.originalEvent;
}
return event;
}
function createVirtualEvent(event, eventType) {
var t = event.type, oe, props, ne, prop, ct, touch, i, j, len;
event = $.Event(event);
event.nativeType = event.type;
event.type = eventType;
oe = event.originalEvent;
props = $.event.props;
// addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280
// https://github.com/jquery/jquery-mobile/issues/3280
if(t.search(/^(mouse|click)/) > -1) {
props = mouseEventProps;
}
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if(oe) {
for(i = props.length , prop; i; ) {
prop = props[--i];
event[prop] = oe[prop];
}
}
// make sure that if the mouse and click virtual events are generated
// without a .which one is defined
if(t.search(/mouse(down|up)|click/) > -1 && !event.which) {
event.which = 1;
}
ne = getNativeEvent(oe);
// handle pageX/PageY under Metro:
for(j = 0 , len = nativeEventProps.length; j < len; j++) {
prop = nativeEventProps[j];
if(event[prop] === undefined) {
event[prop] = ne[prop];
}
}
if(t.search(/^touch/) !== -1) {
t = ne.touches;
ct = ne.changedTouches;
touch = (t && t.length) ? t[0] : ((ct && ct.length) ? ct[0] : undefined);
if(touch) {
for(j = 0 , len = touchEventProps.length; j < len; j++) {
prop = touchEventProps[j];
event[prop] = touch[prop];
}
}
}
return event;
}
function getVirtualBindingFlags(element) {
var flags = {
}, b, k;
while(element) {
b = $.data(element, dataPropertyName);
for(k in b) {
if(b[k]) {
flags[k] = flags.hasVirtualBinding = true;
}
}
element = element.parentNode;
}
return flags;
}
function getClosestElementWithVirtualBinding(element, eventType) {
var b;
while(element) {
b = $.data(element, dataPropertyName);
if(b && (!eventType || b[eventType])) {
return element;
}
element = element.parentNode;
}
return null;
}
function enableTouchBindings() {
blockTouchTriggers = false;
}
function disableTouchBindings() {
blockTouchTriggers = true;
}
function enableMouseBindings() {
lastTouchID = 0;
clickBlockList.length = 0;
blockMouseTriggers = false;
// When mouse bindings are enabled, our
// touch bindings are disabled.
disableTouchBindings();
}
function disableMouseBindings() {
// When mouse bindings are disabled, our
// touch bindings are enabled.
enableTouchBindings();
}
function startResetTimer() {
clearResetTimer();
resetTimerID = setTimeout(function () {
resetTimerID = 0;
enableMouseBindings();
}, $.wijmouse.resetTimerDuration);
}
function clearResetTimer() {
if(resetTimerID) {
clearTimeout(resetTimerID);
resetTimerID = 0;
}
}
function triggerVirtualEvent(eventType, event, flags) {
var ve;
if((flags && flags[eventType]) || (!flags && getClosestElementWithVirtualBinding(event.target, eventType))) {
ve = createVirtualEvent(event, eventType);
$(event.target).trigger(ve);
}
return ve;
}
function mouseEventCallback(event) {
var touchID = $.data(event.target, touchTargetPropertyName), vEventName, k;
if(!blockMouseTriggers && (!lastTouchID || lastTouchID !== touchID)) {
vEventName = "wij" + event.type;
for(k in realEventNames) {
if(realEventNames[k] === event.type) {
vEventName = k;
}
}
var ve = triggerVirtualEvent(vEventName, event);
if(ve) {
if(ve.isDefaultPrevented()) {
event.preventDefault();
}
if(ve.isPropagationStopped()) {
event.stopPropagation();
}
if(ve.isImmediatePropagationStopped()) {
event.stopImmediatePropagation();
}
}
}
}
function handleTouchStart(event) {
var touches = getNativeEvent(event).touches, target, flags, ne;
if(touches && touches.length === 1 || msPointerEnabled) {
target = event.target;
flags = getVirtualBindingFlags(target);
if(flags.hasVirtualBinding) {
lastTouchID = nextTouchID++;
$.data(target, touchTargetPropertyName, lastTouchID);
clearResetTimer();
disableMouseBindings();
didScroll = false;
ne = getNativeEvent(event);
var t = ne.touches ? ne.touches[0] : ne;
startX = t.pageX;
startY = t.pageY;
triggerVirtualEvent("wijmouseover", event, flags);
triggerVirtualEvent("wijmousedown", event, flags);
}
}
}
function handleScroll(event) {
if(blockTouchTriggers) {
return;
}
if(!didScroll) {
triggerVirtualEvent("wijmousecancel", event, getVirtualBindingFlags(event.target));
}
didScroll = true;
startResetTimer();
}
function handleTouchMove(event) {
if(blockTouchTriggers) {
return;
}
var ne = getNativeEvent(event), t = ne.touches ? ne.touches[0] : ne, didCancel = didScroll, moveThreshold = $.wijmouse.moveDistanceThreshold;
didScroll = didScroll || (Math.abs(t.pageX - startX) > moveThreshold || Math.abs(t.pageY - startY) > moveThreshold);
var flags = getVirtualBindingFlags(event.target);
if(didScroll && !didCancel) {
triggerVirtualEvent("wijmousecancel", event, flags);
}
triggerVirtualEvent("wijmousemove", event, flags);
startResetTimer();
}
function handleTouchEnd(event) {
if(blockTouchTriggers) {
return;
}
disableTouchBindings();
var flags = getVirtualBindingFlags(event.target), ne, t;
triggerVirtualEvent("wijmouseup", event, flags);
if(!didScroll) {
var ve = triggerVirtualEvent("wijclick", event, flags);
if(ve && ve.isDefaultPrevented()) {
// The target of the mouse events that follow the touchend
// event don't necessarily match the target used during the
// touch. This means we need to rely on coordinates for blocking
// any click that is generated.
ne = getNativeEvent(event);
t = ne.changedTouches ? ne.changedTouches[0] : ne;
clickBlockList.push({
touchID: lastTouchID,
x: t.clientX,
y: t.clientY
});
// Prevent any mouse events that follow from triggering
// virtual event notifications.
blockMouseTriggers = true;
}
}
triggerVirtualEvent("wijmouseout", event, flags);
didScroll = false;
startResetTimer();
}
function hasVirtualBindings(ele) {
var bindings = $.data(ele, dataPropertyName), k;
if(bindings) {
for(k in bindings) {
if(bindings[k]) {
return true;
}
}
}
return false;
}
function dummyMouseHandler() {
}
function getSpecialEventObject(eventType) {
//var realType = eventType.substr(2); //qq
var realType = realEventNames[eventType];
return {
setup: function (data, namespace) {
// If this is the first virtual mouse binding for this element,
// add a bindings object to its data.
if(!hasVirtualBindings(this)) {
$.data(this, dataPropertyName, {
});
}
// If setup is called, we know it is the first binding for this
// eventType, so initialize the count for the eventType to zero.
var bindings = $.data(this, dataPropertyName);
bindings[eventType] = true;
// Some browsers, like Opera Mini, won't dispatch mouse/click events
// for elements unless they actually have handlers registered on them.
// To get around this, we register dummy handlers on the elements.
$(this).bind(realType, dummyMouseHandler);
var touchStartBound = false;
// For now, if event capture is not supported, we rely on mouse handlers.
if(eventCaptureSupported) {
// If this is the first virtual mouse binding for the document,
// register our touchstart handler on the document.
activeDocHandlers[touchStartEventM] = (activeDocHandlers[touchStartEventM] || 0) + 1;
if(activeDocHandlers[touchStartEventM] === 1) {
touchStartBound = true;
$document.bind(touchStartEventM, handleTouchStart).bind(touchEndEventM, handleTouchEnd).bind(// On touch platforms, touching the screen and then dragging your finger
// causes the window content to scroll after some distance threshold is
// exceeded. On these platforms, a scroll prevents a click event from being
// dispatched, and on some platforms, even the touchend is suppressed. To
// mimic the suppression of the click event, we need to watch for a scroll
// event. Unfortunately, some platforms like iOS don't dispatch scroll
// events until *AFTER* the user lifts their finger (touchend). This means
// we need to watch both scroll and touchmove events to figure out whether
// or not a scroll happenens before the touchend event is fired.
touchMoveEventM, handleTouchMove).bind(touchScrollEventM, handleScroll);
}
}
if(!touchStartBound || touchStartEventM !== realType) {
// If this is the first virtual mouse event for this type,
// register a global handler on the document.
activeDocHandlers[eventType] = (activeDocHandlers[eventType] || 0) + 1;
if(activeDocHandlers[eventType] === 1) {
$document.bind(realType, mouseEventCallback);
}
}
},
teardown: function (data, namespace) {
// If this is the last virtual binding for this eventType,
// remove its global handler from the document.
--activeDocHandlers[eventType];
if(!activeDocHandlers[eventType]) {
$document.unbind(realType, mouseEventCallback);
}
if(eventCaptureSupported) {
// If this is the last virtual mouse binding in existence,
// remove our document touchstart listener.
--activeDocHandlers[touchStartEventM];
if(!activeDocHandlers[touchStartEventM]) {
$document.unbind(touchStartEventM, handleTouchStart).unbind(touchMoveEventM, handleTouchMove).unbind(touchEndEventM, handleTouchEnd).unbind(touchScrollEventM, handleScroll);
}
}
var $this = $(this), bindings = $.data(this, dataPropertyName);
// teardown may be called when an element was
// removed from the DOM. If this is the case,
// jQuery core may have already stripped the element
// of any data bindings so we need to check it before
// using it.
if(bindings) {
bindings[eventType] = false;
}
// Unregister the dummy event handler.
$this.unbind(realType, dummyMouseHandler);
// If this is the last virtual mouse binding on the
// element, remove the binding data from the element.
if(!hasVirtualBindings(this)) {
$this.removeData(dataPropertyName);
}
}
};
}
// Expose our custom events to the jQuery bind/unbind mechanism.
for(var i = 0; i < virtualEventNames.length; i++) {
$.event.special[virtualEventNames[i]] = getSpecialEventObject(virtualEventNames[i]);
}
// Add a capture click handler to block clicks.
// Note that we require event capture support for this so if the device
// doesn't support it, we punt for now and rely solely on mouse events.
if(eventCaptureSupported) {
document.addEventListener("click", function (e) {
var cnt = clickBlockList.length, target = e.target, x, y, ele, i, o, touchID;
if(cnt) {
x = e.clientX;
y = e.clientY;
var threshold = $.wijmouse.clickDistanceThreshold;
// The idea here is to run through the clickBlockList to see if
// the current click event is in the proximity of one of our
// wijclick events that had preventDefault() called on it. If we find
// one, then we block the click.
//
// Why do we have to rely on proximity?
//
// Because the target of the touch event that triggered the wijclick
// can be different from the target of the click event synthesized
// by the browser. The target of a mouse/click event that is syntehsized
// from a touch event seems to be implementation specific. For example,
// some browsers will fire mouse/click events for a link that is near
// a touch event, even though the target of the touchstart/touchend event
// says the user touched outside the link. Also, it seems that with most
// browsers, the target of the mouse/click event is not calculated until the
// time it is dispatched, so if you replace an element that you touched
// with another element, the target of the mouse/click will be the new
// element underneath that point.
//
// Aside from proximity, we also check to see if the target and any
// of its ancestors were the ones that blocked a click. This is necessary
// because of the strange mouse/click target calculation done in the
// Android 2.1 browser, where if you click on an element, and there is a
// mouse/click handler on one of its ancestors, the target will be the
// innermost child of the touched element, even if that child is no where
// near the point of touch.
ele = target;
while(ele) {
for(i = 0; i < cnt; i++) {
o = clickBlockList[i];
touchID = 0;
if((ele === target && Math.abs(o.x - x) < threshold && Math.abs(o.y - y) < threshold) || $.data(ele, touchTargetPropertyName) === o.touchID) {
// XXX: We may want to consider removing matches from the block list
// instead of waiting for the reset timer to fire.
e.preventDefault();
e.stopPropagation();
return;
}
}
ele = ele.parentNode;
}
}
}, true);
}
// add new event shortcuts
$.each(("touchstart touchmove touchend orientationchange throttledresize " + "wijtap wijtaphold wijswipe wijswipeleft wijswiperight wijscrollstart wijscrollstop").split(" "), function (i, name) {
$.fn[name] = function (fn) {
return fn ? this.bind(name, fn) : this.trigger(name);
};
if($.attrFn) {
$.attrFn[name] = true;
}
});
var supportTouch = ("ontouchend" in document), scrollEvent = "touchmove scroll", touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", touchMoveEvent = supportTouch ? "touchmove" : "mousemove", gesturestartEvent = supportTouch ? "gesturestart" : "gesturestart", gesturechangeEvent = supportTouch ? "gesturechange" : "gesturechange", gestureendEvent = supportTouch ? "gestureend" : "gestureend";
if(window.navigator.msPointerEnabled) {
touchStartEvent = "MSPointerDown";
touchStopEvent = "MSPointerUp";
touchMoveEvent = "MSPointerMove";
gesturestartEvent = "MSGestureStart";
gesturechangeEvent = "MSGestureChange";
gestureendEvent = "MSGestureEnd";
}
function triggerCustomEvent(obj, eventType, event) {
var originalType = event.type;
event.nativeType = event.type;
event.type = eventType;
try {
$([
obj
]).trigger(event);
}finally {
event.type = originalType;
}
}
// also handles scrollstop
$.event.special.wijscrollstart = {
enabled: true,
setup: function () {
var thisObject = this, $this = $(thisObject), scrolling, timer;
function trigger(event, state) {
scrolling = state;
triggerCustomEvent(thisObject, scrolling ? "wijscrollstart" : "wijscrollstop", event);
}
// iPhone triggers scroll after a small delay; use touchmove instead
$this.bind(scrollEvent, function (event) {
if(!$.event.special.wijscrollstart.enabled) {
return;
}
if(!scrolling) {
trigger(event, true);
}
clearTimeout(timer);
timer = setTimeout(function () {
trigger(event, false);
}, 50);
});
}
};
// also handles taphold
$.event.special.wijtap = {
setup: function () {
var thisObject = this, $this = $(thisObject);
$this.bind("wijmousedown", function (event) {
if(event.which && event.which !== 1) {
return false;
}
var origTarget = event.target, origEvent = event.originalEvent, timer;
function clearTapTimer() {
clearTimeout(timer);
}
function clearTapHandlers() {
clearTapTimer();
$this.unbind("wijclick", clickHandler).unbind("wijmouseup", clearTapTimer);
$(document).unbind("wijmousecancel", clearTapHandlers);
}
function clickHandler(event) {
clearTapHandlers();
// ONLY trigger a 'tap' event if the start target is
// the same as the stop target.
if(origTarget == event.target) {
triggerCustomEvent(thisObject, "wijtap", event);
}
}
$this.bind("wijmouseup", clearTapTimer).bind("wijclick", clickHandler);
$(document).bind("wijmousecancel", clearTapHandlers);
timer = setTimeout(function () {
triggerCustomEvent(thisObject, "wijtaphold", $.Event("wijtaphold", {
target: origTarget
}));
}, 750);
});
}
};
// also handles swipeleft, swiperight
$.event.special.wijswipe = {
scrollSupressionThreshold: 10,
durationThreshold: // More than this horizontal displacement, and we will suppress scrolling.
1000,
horizontalDistanceThreshold: // More time than this, and it isn't a swipe.
30,
verticalDistanceThreshold: // Swipe horizontal displacement must be more than this.
75,
setup: // Swipe vertical displacement must be less than this.
function () {
var thisObject = this, $this = $(thisObject);
$this.bind(touchStartEvent, function (event) {
var data = event.originalEvent.touches ? event.originalEvent.touches[0] : event, start = {
time: (new Date()).getTime(),
coords: [
data.pageX,
data.pageY
],
origin: $(event.target)
}, stop;
function moveHandler(event) {
if(!start) {
return;
}
var data = event.originalEvent.touches ? event.originalEvent.touches[0] : event;
stop = {
time: (new Date()).getTime(),
coords: [
data.pageX,
data.pageY
]
};
// prevent scrolling
if(Math.abs(start.coords[0] - stop.coords[0]) > $.event.special.wijswipe.scrollSupressionThreshold) {
event.preventDefault();
}
}
$this.bind(touchMoveEvent, moveHandler).one(touchStopEvent, function (event) {
$this.unbind(touchMoveEvent, moveHandler);
if(start && stop) {
if(stop.time - start.time < $.event.special.wijswipe.durationThreshold && Math.abs(start.coords[0] - stop.coords[0]) > $.event.special.wijswipe.horizontalDistanceThreshold && Math.abs(start.coords[1] - stop.coords[1]) < $.event.special.wijswipe.verticalDistanceThreshold) {
start.origin.trigger("wijswipe").trigger(start.coords[0] > stop.coords[0] ? "wijswipeleft" : "wijswiperight")//qq
;
}
}
start = stop = undefined;
});
});
}
};
// gesture events
var gestureEventProps = "altKey ctrlKey metaKey rotation scale shiftKey target velocityX velocityY translationX translationY".split(" ");
function preInitGestureEvent(elem, eventName) {
if(window.navigator.msPointerEnabled && !elem.__wijMSGesturePreInit) {
// listen for MS gestures
elem.__wijMSGesturePreInit = true;
var msGesture = new MSGesture();
msGesture.target = elem;
elem.addEventListener("MSPointerDown", function (e) {
msGesture.addPointer(e.pointerId);
}, false);
}
}
function triggerGestureEvent(eventType, event) {
var ve = createGestureEvent(event, eventType);
$(event.target).trigger(ve);
return ve;
}
function createGestureEvent(event, eventType) {
var t = event.type, oe, props, ne, prop, ct, touch, i, j, len;
oe = event.originalEvent;
event = $.Event(event);
event.nativeType = event.type;
event.type = eventType;
props = $.event.props;
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if(oe) {
for(i = props.length , prop; i; ) {
prop = props[--i];
event[prop] = event[prop] || oe[prop];
}
}
for(j = 0 , len = gestureEventProps.length; j < len; j++) {
prop = gestureEventProps[j];
event[prop] = event[prop] || oe[prop];
}
if(window.navigator.msPointerEnabled && event.rotation) {
// automatically convert to degrees for metro:
event.rotation = event.rotation * 360 / Math.PI;
}
return event;
}
$.event.special.wijgesturestart = {
setup: function () {
var thisObject = this, $this = $(thisObject);
preInitGestureEvent(thisObject, "wijgesturestart");
$this.bind(gesturestartEvent, function (event) {
triggerGestureEvent("wijgesturestart", event);
});
}
};
$.event.special.wijgesturechange = {
setup: function () {
var thisObject = this, $this = $(thisObject);
preInitGestureEvent(thisObject, "wijgesturechange");
$this.bind(gesturechangeEvent, function (event) {
triggerGestureEvent("wijgesturechange", event);
});
}
};
$.event.special.wijgestureend = {
setup: function () {
var thisObject = this, $this = $(thisObject);
preInitGestureEvent(thisObject, "wijgestureend");
$this.bind(gestureendEvent, function (event) {
triggerGestureEvent("wijgestureend", event);
});
}
};
//--
(function ($, window) {
// "Cowboy" Ben Alman
var win = $(window), special_event, get_orientation, last_orientation, initial_orientation_is_landscape, initial_orientation_is_default, portrait_map = {
"0": true,
"180": true
};
// It seems that some device/browser vendors use window.orientation values 0 and 180 to
// denote the "default" orientation. For iOS devices, and most other smart-phones tested,
// the default orientation is always "portrait", but in some Android and RIM based tablets,
// the default orientation is "landscape". The following code attempts to use the window
// dimensions to figure out what the current orientation is, and then makes adjustments
// to the to the portrait_map if necessary, so that we can properly decode the
// window.orientation value whenever get_orientation() is called.
//
// Note that we used to use a media query to figure out what the orientation the browser
// thinks it is in:
//
// initial_orientation_is_landscape = $.mobile.media("all and (orientation: landscape)");
//
// but there was an iPhone/iPod Touch bug beginning with iOS 4.2, up through iOS 5.1,
// where the browser *ALWAYS* applied the landscape media query. This bug does not
// happen on iPad.
if("orientation" in window && "onorientationchange" in window) {
// Check the window width and height to figure out what the current orientation
// of the device is at this moment. Note that we've initialized the portrait map
// values to 0 and 180, *AND* we purposely check for landscape so that if we guess
// wrong, , we default to the assumption that portrait is the default orientation.
// We use a threshold check below because on some platforms like iOS, the iPhone
// form-factor can report a larger width than height if the user turns on the
// developer console. The actual threshold value is somewhat arbitrary, we just
// need to make sure it is large enough to exclude the developer console case.
var ww = window.innerWidth || $(window).width(), wh = window.innerHeight || $(window).height(), landscape_threshold = 50;
initial_orientation_is_landscape = ww > wh && (ww - wh) > landscape_threshold;
// Now check to see if the current window.orientation is 0 or 180.
initial_orientation_is_default = portrait_map[window.orientation];
// If the initial orientation is landscape, but window.orientation reports 0 or 180, *OR*
// if the initial orientation is portrait, but window.orientation reports 90 or -90, we
// need to flip our portrait_map values because landscape is the default orientation for
// this device/browser.
if((initial_orientation_is_landscape && initial_orientation_is_default) || (!initial_orientation_is_landscape && !initial_orientation_is_default)) {
portrait_map = {
"-90": true,
"90": true
};
}
}
$.event.special.orientationchange = special_event = {
setup: function () {
// If the event is supported natively, return false so that jQuery
// will bind to the event using DOM methods.
if(("orientation" in window && "onorientationchange" in window) && $.mobile.orientationChangeEnabled) {
return false;
}
// Get the current orientation to avoid initial double-triggering.
last_orientation = get_orientation();
// Because the orientationchange event doesn't exist, simulate the
// event by testing window dimensions on resize.
win.bind("throttledresize", handler);
},
teardown: function () {
// If the event is not supported natively, return false so that
// jQuery will unbind the event using DOM methods.
if(("orientation" in window && "onorientationchange" in window) && $.mobile.orientationChangeEnabled) {
return false;
}
// Because the orientationchange event doesn't exist, unbind the
// resize event handler.
win.unbind("throttledresize", handler);
},
add: function (handleObj) {
// Save a reference to the bound event handler.
var old_handler = handleObj.handler;
handleObj.handler = function (event) {
// Modify event object, adding the .orientation property.
event.orientation = get_orientation();
// Call the originally-bound event handler and return its result.
return old_handler.apply(this, arguments);
};
}
};
// If the event is not supported natively, this handler will be bound to
// the window resize event to simulate the orientationchange event.
function handler() {
// Get the current orientation.
var orientation = get_orientation();
if(orientation !== last_orientation) {
// The orientation has changed, so trigger the orientationchange event.
last_orientation = orientation;
win.trigger("orientationchange");
}
}
// Get the current page orientation. This method is exposed publicly, should it
// be needed, as jQuery.event.special.orientationchange.orientation()
$.event.special.orientationchange.orientation = get_orientation = function () {
var isPortrait = true, elem = document.documentElement;
// prefer window orientation to the calculation based on screensize as
// the actual screen resize takes place before or after the orientation change event
// has been fired depending on implementation (eg android 2.3 is before, iphone after).
// More testing is required to determine if a more reliable method of determining the new screensize
// is possible when orientationchange is fired. (eg, use media queries + element + opacity)
if("orientation" in window && "onorientationchange" in window) {
// if the window orientation registers as 0 or 180 degrees report
// portrait, otherwise landscape
isPortrait = portrait_map[window.orientation];
} else {
isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1;
}
return isPortrait ? "portrait" : "landscape";
};
})(jQuery, window);
// throttled resize event
(function () {
$.event.special.throttledresize = {
setup: function () {
$(this).bind("resize", handler);
},
teardown: function () {
$(this).unbind("resize", handler);
}
};
var throttle = 250, handler = function () {
curr = (new Date()).getTime();
diff = curr - lastCall;
if(diff >= throttle) {
lastCall = curr;
$(this).trigger("throttledresize");
} else {
if(heldCall) {
clearTimeout(heldCall);
}
// Promise a held call will still execute
heldCall = setTimeout(handler, throttle - diff);
}
}, lastCall = 0, heldCall, curr, diff;
})();
$.each({
wijscrollstop: "wijscrollstart",
wijtaphold: "wijtap",
wijswipeleft: "wijswipe",
wijswiperight: "wijswipe"
}, function (event, sourceEvent) {
$.event.special[event] = {
setup: function () {
$(this).bind(sourceEvent, $.noop);
}
};
});
})(wijmo.touch || (wijmo.touch = {}));
var touch = wijmo.touch;
})(wijmo || (wijmo = {}));
;
/*globals window*/
/*
* Depends:
* jquery.effects.core.js
*
*/
$(document).ready(function () {
var userAgent = window.navigator.userAgent,
isAndroidVerBellow2_2 = userAgent.match(new RegExp("android ((1\\.)|(2\\.([^345]+)))", "i")),
areTransformsSupported = ((window.WebKitCSSMatrix) ? !isAndroidVerBellow2_2 : false),
isWebKitEnabled = !!(typeof userAgent == "string" && userAgent.match(/applewebkit/)),
isTouchDevice = "ontouchend" in document,
div = document.createElement('div'),
cssTransitionsSupported;
div.setAttribute('style', 'transition:top 1s ease;-webkit-transition:top 1s ease;-moz-transition:top 1s ease;-o-transition:top 1s ease;');
document.body.appendChild(div);
cssTransitionsSupported = !!(div.style.transition || div.style.webkitTransition || div.style.MozTransition || div.style.OTransitionDuration);
div.parentNode.removeChild(div);
div = null;
// prevent transition flickering for iTouch devices:
function with3DAcceleration(element, action, args) {
var property = "-webkit-transform",
enabler = "translate3d(0,0,0)",
origValue = element.css(property);
var isNone = !(origValue && origValue.match(/^\s*none\s*$/i));
element.css(property, isNone ? enabler : origValue + " " + enabler);
try {
return action.apply(this, args);
} finally {
element.css(property, origValue);
}
}
var $animate = jQuery.fn.animate;
jQuery.fn.animate = function (prop, speed, easing, callback) {
if (!isWebKitEnabled || !webKitTransition.apply(this, arguments)) {
return with3DAcceleration.call(this, this, function () {
return $animate.apply(this, arguments);
}, arguments);
}
};
function webKitTransition(prop, speed, easing, callback) {
var result = false, propVal, newVal,
speedOpt = $.speed(speed, easing, callback),
self = this;
if (!prop) {
return false;
}
for (var k in prop) {
propVal = prop[k];
if (k === "height") {
if (propVal === "hide") {
this.css("display", "none");
result = true;
speedOpt.complete();
//result = true;
//fadeOut(this[0], speedOpt.duration, "linear", speedOpt.complete);
} else if (propVal === "show") {
this.css("display", "");
result = true;
speedOpt.complete();
//result = true;
//fadeIn(this[0], speedOpt.duration, "linear", speedOpt.complete);
}
} else if (k === "width") {
if (propVal === "hide") {
this.css("display", "none");
result = true;
speedOpt.complete();
//result = true;
//fadeOut(this[0], speedOpt.duration, "linear", speedOpt.complete);
} else if (propVal === "show") {
this.css("display", "");
result = true;
speedOpt.complete();
//result = true;
//fadeIn(this[0], speedOpt.duration, "linear", speedOpt.complete);
}
} else if (k === "left") {
newVal = this.css("left").replace("px", "") * 1;
if (typeof propVal === "string") {
if (propVal.indexOf("-=") === 0) {
newVal = newVal -
propVal.replace("-=", "") * 1;
}
else if (propVal.indexOf("+=") === 0) {
newVal = newVal +
propVal.replace("+=", "") * 1;
}
}
result = true;
/*
var completeTranslateTransition = $.proxy(function () {
speedOpt.complete();
}, this);
*/
// prevent flickering for iTouch devices:
this.css("-webkit-perspective", 1000);
this.css("-webkit-backface-visibility", "hidden");
//
//-webkit-perspective: 1000;
//: ;
scrollToX(this[0], newVal, speedOpt.duration, "linear", speedOpt.complete);
//speedOpt.complete();
}
}
return result;
}
/// <summary>
/// Hide the element by fading it to transparent.
/// </summary>
/// <param name="element" type="Object">
/// DOM Element
/// </param>
/// <param name="duration" type="Number">
/// Transition duration in milliseconds.
/// </param>
/// <param name="timing" type="String">
/// String, easing type.
/// Available values are: ease, linear, ease-in, ease-out, ease-in-out.
/// </param>
/// <param name="endHandler" type="Function">
/// Transition end handler.
/// </param>
function fadeOut(element, duration, timing, endHandler) {
if (cssTransitionsSupported) {
if (!timing) {
timing = "ease";
}
setupTransition(element, "opacity", duration, timing);
setOpacity(element, 0);
element.addEventListener("webkitTransitionEnd", $.proxy(function () {
clearTransition(element);
element.style.display = "none";
setOpacity(element, 1);
if (endHandler) {
endHandler();
}
}, this), false);
}
else {
//jQuery(element).animate({left: + x + "px"}), duration, 'linear', endHandler);
}
}
/// <summary>
/// Display the element by fading it to opaque.
/// </summary>
/// <param name="element" type="Object">
/// DOM Element
/// </param>
/// <param name="duration" type="Number">
/// Transition duration in milliseconds.
/// </param>
/// <param name="timing" type="String">
/// String, easing type.
/// Available values are: ease, linear, ease-in, ease-out, ease-in-out.
/// </param>
/// <param name="endHandler" type="Function">
/// Transition end handler.
/// </param>
function fadeIn(element, duration, timing, endHandler) {
if (cssTransitionsSupported) {
if (!timing) {
timing = "ease";
}
setupTransition(element, "opacity", duration, timing);
setOpacity(element, 1);
element.addEventListener("webkitTransitionEnd", $.proxy(function () {
clearTransition(element);
if (element.style.display === "none") {
element.style.display = "";
}
if (endHandler) {
endHandler();
}
}, this), false);
}
else {
//jQuery(element).animate({left: + x + "px"}), duration, 'linear', endHandler);
}
}
/// <summary>
/// Scroll element horizontally using webkit transitions.
/// </summary>
/// <param name="element" type="Object">
/// DOM Element
/// </param>
/// <param name="x" type="Number">
/// The new translate value.
/// </param>
/// <param name="duration" type="Number">
/// Transition duration in milliseconds.
/// </param>
/// <param name="timing" type="String">
/// String, easing type.
/// Available values are: ease, linear, ease-in, ease-out, ease-in-out.
/// </param>
/// <param name="endHandler" type="Function">
/// Transition end handler.
/// </param>
function scrollToX(element, x, duration, timing, endHandler) {
if (cssTransitionsSupported) {
setupTransitionTransform(element, duration, timing);
setTranslateX(element, x);
element.___animationEndHandler = endHandler;
element.___internalEndHandler = $.proxy(_onScrollTransitionEnd, {});
element.addEventListener("webkitTransitionEnd", element.___internalEndHandler, false);
}
else {
//jQuery(element).animate({left: + x + "px"}), duration, 'linear', endHandler);
}
}
/// <summary>
/// Set opacity value.
/// </summary>
/// <param name="element" type="Object">
/// DOM Element or style object.
/// </param>
/// <param name="value" type="Number">
/// The new opacity value.
/// </param>
function setOpacity(element, value) {
var st;
if (cssTransitionsSupported) {
st = element.style || element;
st.opacity = value;
}
else {
}
}
/// <summary>
/// Set translate X value. This method will use left style for non-webkit browsers.
/// </summary>
/// <param name="element" type="Object">
/// DOM Element or style object.
/// </param>
/// <param name="value" type="Number">
/// The new translate value.
/// </param>
function setTranslateX(element, value) {
var st;
if (cssTransitionsSupported) {
element.___translateX = value;
st = element.style || element;
//st.webkitTransform = "translate3d(" + value + "px," + getTranslateY(element) + "px, 0)";
st.webkitTransform = "translateX(" + value + "px)";
}
else {
element.style.left = value + "px";
}
}
/// <summary>
/// Set translate Y value. This method will use top style for non-webkit browsers.
/// </summary>
/// <param name="element" type="Object">
/// DOM Element or style object.
/// </param>
/// <param name="value" type="Number">
/// The new translate value.
/// </param>
function setTranslateY(element, value) {
var st;
if (cssTransitionsSupported) {
element.___translateY = value;
st = element.style || element;
//st.webkitTransform = "translate3d(" + getTranslateX(element) + "px," + value + "px, 0)";
st.webkitTransform = "translateY(" + value + "px)";
}
else {
element.style.top = value + "px";
}
}
/// <summary>
/// Gets translate X value. This method will return left style for non-webkit browsers.
/// </summary>
function getTranslateX(element) {
var style, transform, r, match, k;
if (!element) {
return 0;
}
if (cssTransitionsSupported) {
style = element.style || element;
transform = style.webkitTransform;
if (typeof transform === "string") {
r = new RegExp("translate(3d|X|)\\(-*(\\d+)");
match = r.exec(transform);
if (match) {
k = parseFloat(match[1]);
if (isFinite(k)) {
return k;
}
}
}
}
else {
var k = parseInt($(element).css("left"));
if (isFinite(k)) {
return k;
}
}
return 0;
}
/// <summary>
/// Gets translate Y value. This method will return top style for non-webkit browsers.
/// </summary>
function getTranslateY(element) {
var style, transform, r, match, k;
if (!element) {
return 0;
}
if (cssTransitionsSupported) {
style = element.style || element;
transform = style.webkitTransform;
if (typeof transform === "string") {
r = new RegExp("translate(3d|X|)\\(.*,\\s*-*(\\d+)");
match = r.exec(transform);
if (match) {
k = parseFloat(match[1]);
if (isFinite(k)) {
return k;
}
}
}
}
else {
var k = parseInt(jQuery(element).css("top"));
if (isFinite(k)) {
return k;
}
}
return 0;
}
/// <summary>
/// Call this method in order to setup transition for transform animation.
/// </summary>
/// <param name="duration" type="Number">
/// Transition duration in milliseconds.
/// </param>
/// <param name="timing" type="String">
/// String, easing type.
/// Available values are: ease, linear, ease-in, ease-out, ease-in-out.
/// </param>
function setupTransitionTransform(element, duration, timing) {
if (!timing) {
timing = "ease";
}
setupTransition(element, "-webkit-transform", duration, timing);
}
/// <summary>
/// Setup transition animation for element given by parameter element.
/// </summary>
/// <param name="element" type="Object">
/// DOM element for transition.
/// </param>
/// <param name="properties" type="String">
/// String, specifies the name of the CSS property to which the transition is applied.
/// You can list multiple properties. Property names should be bare, unquoted names.
/// </param>
/// <param name="duration" type="Number">
/// Transition duration in milliseconds.
/// Available values are: ease, linear, ease-in, ease-out, ease-in-out.
/// </param>
/// <param name="timing" type="String">
/// String, easing type.
/// Available values are: ease, linear, ease-in, ease-out, ease-in-out.
/// </param>
function setupTransition(element, properties, duration, timing) {
if (cssTransitionsSupported) {
var style = (element).style;
style.webkitTransitionProperty = properties;
style.webkitTransitionDuration = duration + 'ms';
style.webkitTransitionTimingFunction = timing;
}
}
/// <summary>
/// Clear transition animation for element given by parameter element.
/// </summary>
function clearTransition(element) {
if (cssTransitionsSupported) {
var st = element.style;
st.webkitTransitionProperty = 'none';
var internalEndHandler = element.___internalEndHandler;
if (internalEndHandler) {
delete element.___internalEndHandler;
element.removeEventListener('webkitTransitionEnd', internalEndHandler, false);
}
}
}
function _onScrollTransitionEnd(e) {
try {
var targetElement, endHandler;
switch (e.type) {
case "webkitTransitionEnd":
targetElement = e.target;
if (targetElement) {
clearTransition(targetElement);
if (targetElement.___animationEndHandler) {
endHandler = targetElement.___animationEndHandler;
targetElement.___animationEndHandler = null;
endHandler(e);
}
}
break;
}
}
catch (ex) {
if (window.console && window.console.log) {
window.console.log("[ew219290] error: " +
(ex.message ? ex.message : ex) +
", event: " + e);
}
}
return true;
}
});
/*
prop:left=-=1224; jquery.wijmo.wijtouchtransitions.js:11
speed:queue=false;duration=250;easing=easeInQuad;complete=function (){...}
*/
/*
prop:height=hide;paddingTop=hide;paddingBottom=hide; jquery.wijmo.wijtouchtransitions.js:11
speed:step=function (now, settings) {
var val;
if (settings.prop === options.horizontal ?
"width" : "height") {
percentDone = (settings.end - settings.start === 0) ? 0 :
(settings.now - settings.start) /
(settings.end - settings.start);
}
val = (percentDone * showProps[settings.prop].value);
if (val < 0) {
//fix for 16943:
val = 0;
}
options.toShow[0].style[settings.prop] =
val + showProps[settings.prop].unit;
};
duration=300;easing=swing;complete=function () {...};
*/
/*
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
*/;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/// <reference path="../external/declarations/globalize.d.ts"/>
/*globals window document clearTimeout setTimeout jQuery */
/*
* Depends:
* jQuery.js
* jquery.ui.core.js
* jquery.ui.widget.js
* jQuery.ui.position.js
* jquery.bgiframe-2.1.3-pre.js
*/
(function (tooltip) {
"use strict";
var $ = jQuery, widgetName = "wijtooltip", defaultTooltipKey = "@wijtp@", tipCss = "wijmo-wijtooltip", calloutCssPrefix = tipCss + "-arrow-", parseF = parseFloat, win = window, doc = document, math = Math, max = math.max, oldTipPos = {
};
/** @widget*/
var wijtooltip = (function (_super) {
__extends(wijtooltip, _super);
function wijtooltip() {
_super.apply(this, arguments);
}
wijtooltip._tooltips = new Array();
wijtooltip.prototype._setOption = function (key, value) {
var self = this, funName = "_set_" + key, oldValue = self.options[key];
_super.prototype._setOption.call(this, key, value);
if($.isPlainObject(value)) {
self.options[key] = $.extend({
}, oldValue, value);
}
if(self[funName]) {
self[funName](oldValue);
}
};
wijtooltip.prototype._set_cssClass = //fix the issue 21416: cssClass does not show.
function () {
var self = this, o = self.options, tooltip = self._tooltipCache._$tooltip;
if(!tooltip) {
return;
}
if(!tooltip.hasClass(o.cssClass)) {
tooltip.addClass(o.cssClass);
}
};
wijtooltip.prototype._set_content = function (value) {
var self = this;
if(self._isAjaxCallback) {
self._callbacked = true;
self.show();
self._callbacked = false;
} else {
self._setText();
}
};
wijtooltip.prototype._create = function () {
var self = this, o = self.options, element = self.element, id = element && element.attr("id"), describedBy = "", cssClass = "", key = o.group || defaultTooltipKey, tooltip = wijtooltip._getTooltip(key);
if(tooltip) {
tooltip.count++;
} else {
tooltip = self._createTooltip();
tooltip.count = 0;
wijtooltip._tooltips[key] = tooltip;
}
//fix the issue 21416: cssClass does not show.
cssClass = o.cssClass ? o.cssClass : "";
if(!tooltip._$tooltip.hasClass(cssClass)) {
tooltip._$tooltip.addClass(cssClass);
}
o.position.of = self.element;
self._bindLiveEvents();
self._tooltipCache = tooltip;
if(id !== "") {
describedBy = tooltip._$tooltip.attr("aria-describedby");
describedBy = describedBy === undefined ? "" : describedBy + " ";
tooltip._$tooltip.attr("aria-describedby", describedBy + id);
}
};
wijtooltip.prototype.destroy = /** Removes the wijtooltip functionality completely.
* This returns the element back to its pre-init state.
*/
function () {
var self = this, element = self.element, key = self.options.group || defaultTooltipKey;
element.unbind(".tooltip");
element.attr("title", self._content);
wijtooltip._removeTooltip(key);
_super.prototype.destroy.call(this);
};
wijtooltip.prototype.widget = /** Returns the wijtooltip element. */
function () {
return this._tooltipCache._$tooltip;
};
wijtooltip.prototype.show = /** Shows the tooltip */
function () {
var self = this, tooltipCache = self._tooltipCache, _$tooltip = tooltipCache ? tooltipCache._$tooltip : null, o = self.options;
if(!tooltipCache || o.disabled) {
return;
}
if(tooltipCache._showAnimationTimer) {
clearTimeout(tooltipCache._showAnimationTimer);
tooltipCache._showAnimationTimer = null;
}
if(tooltipCache._showAtAnimationTimer) {
clearTimeout(tooltipCache._showAtAnimationTimer);
tooltipCache._showAtAnimationTimer = null;
}
if(tooltipCache._hideAnimationTimer) {
clearTimeout(tooltipCache._hideAnimationTimer);
tooltipCache._hideAnimationTimer = null;
}
_$tooltip.stop(true, true);
if(o.ajaxCallback && $.isFunction(o.ajaxCallback) && !self._callbacked) {
self._isAjaxCallback = true;
o.ajaxCallback.call(self.element);
return;
}
self._setText();
tooltipCache._showAnimationTimer = setTimeout(function () {
//self._setText();
oldTipPos = _$tooltip.offset();
if(o.mouseTrailing) {
self._setCalloutCss();
return;
}
self._setPosition();
self._showTooltip();
}, self.options.showDelay);
};
wijtooltip.prototype.showAt = /** Shows the tooltip at the specified position
* @param {object} point A point value that indicates the position that tooltip will be shown.
* @example
* //Shows the tooltip at point {x: 100, y: 120}.
* $("#tooltip").wijtooltip("showAt", {x:100, y:120});
*/
function (point) {
var self = this, tooltipCache = self._tooltipCache, _$tooltip = tooltipCache ? tooltipCache._$tooltip : null, callout = tooltipCache ? tooltipCache._callout : null, calloutPos, offsetX = 0, offsetY = 0, offset = {
}, calloutShape, border, hBorder, vBorder, width, height;
if(!tooltipCache || !callout) {
return;
}
_$tooltip.stop(true, true);
if(tooltipCache._showAtAnimationTimer) {
clearTimeout(tooltipCache._showAtAnimationTimer);
tooltipCache._showAtAnimationTimer = null;
}
if(tooltipCache._hideAnimationTimer) {
clearTimeout(tooltipCache._hideAnimationTimer);
tooltipCache._hideAnimationTimer = null;
}
tooltipCache._showAtAnimationTimer = setTimeout(function () {
var visible = _$tooltip.is(":visible");
self._setText();
oldTipPos = _$tooltip.offset();
_$tooltip.offset({
left: 0,
top: 0
}).show();
calloutPos = callout.position();
offsetX = calloutPos.left;
offsetY = calloutPos.top;
border = self._getBorder(callout);
hBorder = border.left || border.right;
vBorder = border.top || border.bottom;
width = _$tooltip.width();
height = _$tooltip.height();
calloutShape = self._getCalloutShape();
offset = {
"rt": {
left: point.x - width - hBorder,
top: point.y - offsetY
},
"rc": {
left: point.x - width - hBorder,
top: point.y - height / 2
},
"rb": {
left: point.x - width - hBorder,
top: point.y - offsetY - vBorder
},
"lt": {
left: point.x + hBorder,
top: point.y - offsetY
},
"lc": {
left: point.x + hBorder,
top: point.y - height / 2
},
"lb": {
left: point.x + hBorder,
top: point.y - offsetY - vBorder
},
"tl": {
left: point.x - offsetX,
top: point.y + vBorder
},
"tc": {
left: point.x - width / 2,
top: point.y + vBorder
},
"tr": {
left: point.x - offsetX - hBorder,
top: point.y + vBorder
},
"bl": {
left: point.x - offsetX,
top: point.y - height - vBorder
},
"bc": {
left: point.x - width / 2,
top: point.y - height - vBorder
},
"br": {
left: point.x - offsetX - hBorder,
top: point.y - height - vBorder
},
"cc": {
left: point.x - width / 2,
top: point.y - height / 2
}
}[calloutShape];
calloutShape = self._flipTooltip(offset, calloutShape, border);
self._setUnfilledCallout(calloutShape);
_$tooltip.offset(offset)//.hide();
;
if(!visible) {
_$tooltip.hide();
}
self._calloutShape = calloutShape;
self._showTooltip();
}, self.options.showDelay);
};
wijtooltip.prototype.hide = /** Hides the tooltip.*/
function () {
var self = this, tooltipCache = self._tooltipCache;
if(!tooltipCache) {
return;
}
if(tooltipCache._showAnimationTimer) {
clearTimeout(tooltipCache._showAnimationTimer);
tooltipCache._showAnimationTimer = null;
}
if(tooltipCache._showAtAnimationTimer) {
clearTimeout(tooltipCache._showAtAnimationTimer);
tooltipCache._showAtAnimationTimer = null;
}
if(tooltipCache._hideAnimationTimer) {
clearTimeout(tooltipCache._hideAnimationTimer);
tooltipCache._hideAnimationTimer = null;
}
//clearTimeout(tooltip._showAnimationTimer);
tooltipCache._hideAnimationTimer = setTimeout($.proxy(self._hideTooltip, self), self.options.hideDelay);
};
wijtooltip.prototype._createTooltip = //begin private methods
function () {
var self = this, o = self.options, tooltipCache = new TooltipCache(), _$tooltip = $("<div></div>").addClass(o.wijCSS.tooltip).addClass(o.wijCSS.widget).addClass(o.wijCSS.content).addClass(o.wijCSS.cornerAll), container = $("<div></div>").addClass(o.wijCSS.tooltipContainer), callout = $("<div></div>").addClass(o.wijCSS.content).addClass(o.wijCSS.tooltipPointer).append($("<div></div>").addClass(o.wijCSS.tooltipPointerInner)), title = $("<div></div>").addClass(o.wijCSS.tooltipTitle).addClass(o.wijCSS.header).addClass(o.wijCSS.cornerAll), closeBtn = $("<a href='#'></a>").addClass(o.wijCSS.tooltipClose).addClass(o.wijCSS.stateDefault).addClass(o.wijCSS.cornerAll);
closeBtn.append($("<span></span>").addClass(o.wijCSS.icon).addClass(o.wijCSS.iconClose)).bind("click", $.proxy(self._onClickCloseBtn, self));
if(o.closeBehavior !== "sticky") {
closeBtn.hide();
}
if(!o.showCallout) {
callout.hide();
}
_$tooltip.append(title).append(closeBtn).append(container).append(callout).css("position", "absolute").attr("role", "tooltip").appendTo("body").hide();
tooltipCache._$tooltip = _$tooltip;
tooltipCache._container = container;
tooltipCache._callout = callout;
tooltipCache._closeBtn = closeBtn;
tooltipCache._title = title;
return tooltipCache;
};
wijtooltip.prototype._bindLiveEvents = function () {
var self = this, o = self.options, element = self.element;
if(self._content === undefined) {
self._content = element.attr("title");
element.attr("title", "");
}
element.unbind('.tooltip');
if(o.mouseTrailing) {
element.bind("mousemove.tooltip", function (e) {
if(o.disabled) {
return;
}
var offset = o.position.offset || "", offsets = offset.split(" ");
if(offsets.length === 2) {
self.showAt({
x: e.pageX + parseInt(offsets[0], 10),
y: e.pageY + parseInt(offsets[1], 10)
});
} else {
self.showAt({
x: e.pageX,
y: e.pageY
});
}
});
}
switch(o.triggers) {
case "hover":
element.bind("mouseover.tooltip", $.proxy(self.show, self)).bind("mouseout.tooltip", $.proxy(self._hideIfNeeded, self));
break;
case "click":
element.bind("click.tooltip", $.proxy(self.show, self));
break;
case "focus":
element.bind("focus.tooltip", $.proxy(self.show, self)).bind("blur.tooltip", $.proxy(self._hideIfNeeded, self));
break;
case "rightClick":
element.bind("contextmenu.tooltip", function (e) {
self.show();
e.preventDefault();
});
break;
}
};
wijtooltip.prototype._hideIfNeeded = function () {
var self = this, o = self.options, closeBehavior = o.closeBehavior;
if(closeBehavior === "sticky" || o.modal || closeBehavior === "none" || o.disabled) {
return;
}
self.hide();
};
wijtooltip.prototype._flipTooltip = function (pos, calloutShape, calloutBorder) {
var self = this, tooltipCache = self._tooltipCache, _$tooltip = tooltipCache ? tooltipCache._$tooltip : null, bound = {
width: _$tooltip.width(),
height: _$tooltip.height()
}, flipCallout = self._flipCallout(pos, bound, calloutShape), flip = flipCallout && flipCallout.flip, width, height;
if(!tooltipCache || !flipCallout || (!flip.h && !flip.v)) {
return flipCallout.calloutShape;
}
width = _$tooltip.width();
height = _$tooltip.height();
if(flip.h === "l") {
pos.left -= (width + calloutBorder.right * 2) + 1;
} else if(flip.h === "r") {
pos.left += (width + calloutBorder.left * 2) + 1;
} else if(flip.v === "t") {
pos.top -= (height + calloutBorder.bottom * 2) + 1;
} else if(flip.v === "b") {
pos.top += (height + calloutBorder.top * 2) + 1;
}
return flipCallout.calloutShape;
};
wijtooltip.prototype._flipCallout = function (pos, bound, calloutShape) {
var self = this, o = self.options, tooltipCache = self._tooltipCache, _$tooltip = tooltipCache._$tooltip, flip = {
h: false,
v: false
}, jqWin = $(win), collision = (o.position.collision || "flip").split(" ");
if(collision.length === 1) {
collision[1] = collision[0];
}
if(!tooltipCache || (collision[0] !== "flip" && collision[1] !== "flip")) {
return {
flip: flip,
calloutShape: null
};
}
if(collision[0] === "flip") {
if(pos.left < 0 || pos.left + bound.width > jqWin.width() + jqWin.scrollLeft()) {
flip.h = true;
}
}
if(collision[0] === "flip") {
if(pos.top < 0 || pos.top + bound.height > jqWin.height() + jqWin.scrollTop()) {
flip.v = true;
}
}
//fix the issue 21386, calloutShape undefind
if(o.showCallout) {
if(flip.h) {
if(calloutShape.indexOf('l') > -1) {
calloutShape = calloutShape.replace(/l/, 'r');
flip.h = "l";
} else if(calloutShape.indexOf('r') > -1) {
calloutShape = calloutShape.replace(/r/, 'l');
flip.h = "r";
}
}
if(flip.v) {
if(calloutShape.indexOf('t') > -1) {
calloutShape = calloutShape.replace(/t/, 'b');
flip.v = "t";
} else if(calloutShape.indexOf('b') > -1) {
calloutShape = calloutShape.replace(/b/, 't');
flip.v = "b";
}
}
if(flip.h || flip.v) {
self._removeCalloutCss();
_$tooltip.addClass(calloutCssPrefix + calloutShape);
}
}
return {
flip: flip,
calloutShape: calloutShape
};
};
wijtooltip.prototype._set_position = //methods for options setters
function (oldValue) {
var self = this, o = self.options, val = o.position;
if(o.showCallout) {
if(oldValue.my !== val.my || oldValue.at !== val.at) {
self._setPosition();
}
self._setCalloutOffset(true);
}
//fix the issue 21467.
self._setText();
};
wijtooltip.prototype._set_showCallout = function () {
var self = this, tooltipCache = self._tooltipCache, callout = tooltipCache ? tooltipCache._callout : null;
if(!tooltipCache || !callout) {
return;
}
if(self.options.showCallout) {
self._setCalloutCss();
callout.show();
} else {
callout.hide();
}
};
wijtooltip.prototype._set_closeBehavior = function () {
var self = this, tooltipCache = self._tooltipCache, closeBtn = tooltipCache ? tooltipCache._closeBtn : null;
if(closeBtn) {
closeBtn[self.options.closeBehavior === "sticky" ? "show" : "hide"]();
}
};
wijtooltip.prototype._set_triggers = function () {
this._bindLiveEvents();
};
wijtooltip.prototype._set_mouseTrailing = function () {
this._bindLiveEvents();
};
wijtooltip.prototype._getCalloutShape = //end of methods for options setters.
function () {
var self = this, position = self.options.position, makeArr = //makeArr = function (items) {
// return $.map(items, function (item) {
// return item.substr(0, 1);
// });
//},
function (items) {
return $.makeArray($.map(items, function (item) {
return item.substr(0, 1);
}));
}, myItems = makeArr(position.my.split(" ")), atItems = makeArr(position.at.split(" ")), shape = [];
if(myItems.length === 2) {
shape = myItems;
}
if(myItems[0] === atItems[0]) {
if((myItems[1] === 't' && atItems[1] === 'b') || (myItems[1] === 'b' && atItems[1] === 't')) {
shape.reverse();
}
} else if(atItems[0] === 'c') {
shape.reverse();
}
if(shape[0] === 'c') {
shape.reverse();
}
return shape.join("");
};
wijtooltip.prototype._setCalloutCss = function () {
var self = this, o = self.options, tooltipCache = self._tooltipCache, _$tooltip = tooltipCache ? tooltipCache._$tooltip : null, cssName = "", calloutShape = "", isTouchEnabled = $.support.isTouchEnabled;
if(!o.showCallout && !isTouchEnabled) {
return;
}
self._removeCalloutCss();
calloutShape = self._getCalloutShape();
cssName = calloutCssPrefix + calloutShape;
if(_$tooltip) {
_$tooltip.addClass(cssName);
}
return calloutShape;
};
wijtooltip.prototype._removeCalloutCss = function () {
var tooltipCache = this._tooltipCache, _$tooltip;
if(tooltipCache) {
_$tooltip = tooltipCache._$tooltip;
$.each([
"tl",
"tc",
"tr",
"bl",
"bc",
"br",
"rt",
"rc",
"rb",
"lt",
"lc",
"lb",
"cc"
], function (idx, compass) {
var cssName = calloutCssPrefix + compass;
if(_$tooltip.hasClass(cssName)) {
_$tooltip.removeClass(cssName);
return false;
}
});
}
};
wijtooltip.prototype._getBorder = function (element) {
var obj = {
};
$.each([
"top",
"right",
"left",
"bottom"
], function (idx, compass) {
obj[compass] = parseF(element.css("border-" + compass + "-width"));
});
return obj;
};
wijtooltip.prototype._setPosition = function () {
var self = this, o = self.options, position = o.position, my = position.my, tooltipCache = self._tooltipCache, _$tooltip = tooltipCache ? tooltipCache._$tooltip : null, isHidden = _$tooltip.is(":hidden"), calloutShape = self._setCalloutCss(), arrCalloutShape = calloutShape ? calloutShape.split('') : null, offset = [
0,
0
], callout = //sOffset = "",
tooltipCache._callout, border, top, left, right, bottom, bound = {
width: _$tooltip.width(),
height: _$tooltip.height()
}, flipCallout, flip, isTouchEnabled = $.support.isTouchEnabled;
if(isHidden) {
_$tooltip.show();
}
_$tooltip.css({
left: 0,
top: 0
});
if(o.showCallout) {
border = self._getBorder(callout);
left = parseF(callout.css("left"));
top = parseF(callout.css("top"));
right = parseF(callout.css("right"));
bottom = parseF(callout.css("bottom"));
switch(arrCalloutShape[0]) {
case "l":
offset[0] = border.right;
break;
case "r":
offset[0] = -border.left;
break;
case "b":
offset[1] = bottom;
break;
case "t":
offset[1] = -top;
break;
}
switch(arrCalloutShape[1]) {
case "t":
offset[1] = -top;
break;
case "b":
offset[1] = bottom;
break;
case "r":
offset[0] = right;
break;
case "l":
offset[0] = -left;
break;
}
//sOffset = offset.join(" ");
}
if(isTouchEnabled && isTouchEnabled()) {
switch(arrCalloutShape[0]) {
case "l":
offset[0] = offset[0] + 30;
break;
case "r":
offset[0] = offset[0] - 30;
break;
case "b":
offset[1] = offset[1] - 30;
break;
case "t":
offset[1] = offset[1] + 30;
break;
}
switch(arrCalloutShape[1]) {
case "t":
offset[1] = offset[1] + 30;
break;
case "b":
offset[1] = offset[1] - 30;
break;
case "r":
offset[0] = offset[0] - 30;
break;
case "l":
offset[0] = offset[0] + 30;
break;
}
//sOffset = offset.join(" ");
}
//"left+10 top+-10"
if(position.my.indexOf(" ") > -1) {
my = position.my.split(" ")[0] + "+" + offset[0] + " " + position.my.split(" ")[1] + "+" + offset[1];
} else {
my = position.my + "+" + offset[0] + " " + position.my + "+" + offset[1];
}
_$tooltip.position({
my: my,
at: position.at,
of: position.of,
collision: //offset: sOffset, collision: "none none"
"none none"
});
flipCallout = self._flipCallout(_$tooltip.offset(), bound, calloutShape);
flip = flipCallout.flip;
if(flip.h || flip.v) {
_$tooltip.css({
left: 0,
top: 0
});
_$tooltip.position({
my: my,
at: position.at,
of: position.of,
collision: //offset: sOffset, collision: position.collision
position.collision
});
}
if(o.showCallout) {
self._setUnfilledCallout(calloutShape);
}
self._calloutShape = calloutShape;
if(isHidden) {
_$tooltip.hide();
}
};
wijtooltip.prototype._setCalloutOffset = function (showCalloutAnimation) {
var self = this, o = self.options, tooltipCache = self._tooltipCache, _$tooltip = tooltipCache ? tooltipCache._$tooltip : null, callout = tooltipCache && tooltipCache._callout, calloutShape = self._calloutShape, horizontal = false, offset = o.position.offset, value = "", offsetItems = [], calloutAnimation = o.calloutAnimation;
if(!callout) {
return;
}
if(!offset || offset.length === 0) {
return;
}
callout.stop(true, true);
$.each([
"tr",
"tc",
"tl",
"bl",
"bc",
"br"
], function (idx, compass) {
if(calloutShape === compass) {
horizontal = true;
return false;
}
});
if(offset) {
offsetItems = offset.split(" ");
if(offsetItems.length === 2) {
value = horizontal ? offsetItems[0] : offsetItems[1];
} else if(offsetItems.length === 1) {
value = offsetItems[0];
}
}
//when 'position.offset' is set "none none",
//the properties left and top of the 'callout' element in the tooltip
//need to be removed.
if(offsetItems && offsetItems.length === 2 && offsetItems[0] === "none" && offsetItems[1] === "none") {
callout.css("left", "").css("top", "");
} else if(value === "none") {
callout.css(horizontal ? "left" : "top", "");
} else if(value !== "") {
if(showCalloutAnimation && !showCalloutAnimation.disabled) {
if(horizontal) {
callout.animate({
left: value
}, calloutAnimation.duration, calloutAnimation.easing);
} else {
callout.animate({
top: value
}, calloutAnimation.duration, calloutAnimation.easing);
}
} else {
callout.css(horizontal ? "left" : "top", value);
}
}
};
wijtooltip.prototype._setUnfilledCallout = function (calloutShape) {
var self = this, tooltipCache = self._tooltipCache, _$tooltip = tooltipCache ? tooltipCache._$tooltip : null, callout = tooltipCache && tooltipCache._callout, innerCallout = callout && callout.children(), arrCalloutSharp = calloutShape.split(''), borderColor = _$tooltip ? _$tooltip.css("background-color") : "";
if(!innerCallout) {
return;
}
innerCallout.css({
"border-left-color": "",
"border-top-color": "",
"border-bottom-color": "",
"border-right-color": ""
});
if(!self.options.calloutFilled) {
switch(arrCalloutSharp[0]) {
case "l":
innerCallout.css("border-right-color", borderColor);
break;
case "t":
innerCallout.css("border-bottom-color", borderColor);
break;
case "r":
innerCallout.css("border-left-color", borderColor);
break;
case "b":
innerCallout.css("border-top-color", borderColor);
break;
}
}
};
wijtooltip.prototype._showTooltip = function () {
var self = this, o = self.options, tooltipCache = self._tooltipCache, _$tooltip = tooltipCache ? tooltipCache._$tooltip : null, showAnimation, animations, curPos;
if(!tooltipCache) {
return;
}
if(self._trigger("showing", null, self) === false) {
return;
}
self._showModalLayer();
_$tooltip.css("z-index", 99999);
if($.fn.wijshow) {
animations = {
show: true,
context: _$tooltip
};
showAnimation = $.extend({
}, o.animation, o.showAnimation);
if(_$tooltip.is(":visible")) {
curPos = _$tooltip.offset();
_$tooltip.offset(oldTipPos);
$.extend(animations, {
pos: curPos
});
showAnimation.animated = "tooltipSlide";
}
_$tooltip.wijshow(showAnimation, wijtooltip.animations, animations, null, function () {
self._trigger("shown");
});
} else {
_$tooltip.show();
self._trigger("shown");
}
self._setCalloutOffset(false);
};
wijtooltip.prototype._hideTooltip = function () {
var self = this, o = self.options, tooltipCache = self._tooltipCache, _$tooltip = tooltipCache ? tooltipCache._$tooltip : null, hideAnimation = $.extend({
}, o.animation, o.hideAnimation), animations;
if(!tooltipCache) {
return;
}
if(self._trigger("hiding", null, self) === false) {
return;
}
self._hideModalLayer();
if($.fn.wijhide) {
animations = {
show: false,
context: _$tooltip
};
_$tooltip.wijhide(hideAnimation, wijtooltip.animations, animations, null, function () {
self._trigger("hidden");
_$tooltip.css("z-index", "");
});
} else {
_$tooltip.hide();
self._trigger("hidden");
_$tooltip.css("z-index", "");
}
};
wijtooltip.prototype._getContent = function (content) {
var obj = {
data: ""
}, retValue;
if($.isFunction(content)) {
retValue = content.call(this.element, obj);
if(obj.data !== "") {
return obj.data;
} else {
return retValue;
}
} else if(window[content] && $.isFunction(window[content])) {
// if window[content/title] is a function, then get the
// function value.
retValue = window[content].call(this.element, obj);
if(obj.data !== "") {
return obj.data;
} else {
return retValue;
}
}
return content;
};
wijtooltip.prototype._setText = function () {
var self = this, o = self.options, tooltipCache = self._tooltipCache, content = "", title = "", jqTitle = tooltipCache ? tooltipCache._title : null;
if(!tooltipCache) {
return;
}
content = self._getContent(o.content);
content = content === "" ? self._content : content;
tooltipCache._container.html(content);
title = self._getContent(o.title);
if(title !== "") {
jqTitle.html(title).show();
} else {
jqTitle.hide();
}
};
wijtooltip.prototype._showModalLayer = function () {
var self = this, o = self.options, modalLayer = null;
if(self.options.modal) {
modalLayer = $("<div>").addClass(o.wijCSS.overlay).css("z-index", 99000).width(self._getDocSize("Width")).height(self._getDocSize("Height")).appendTo("body");
$(window).bind("resize.wijtooltip", function () {
modalLayer.width(self._getDocSize("Width")).height(self._getDocSize("Height"));
});
self._tooltipCache._modalLayer = modalLayer;
}
};
wijtooltip.prototype._hideModalLayer = function () {
var self = this, modalLayer = self._tooltipCache._modalLayer;
if(modalLayer) {
modalLayer.css("z-index", "").remove();
$(window).unbind("resize.wijtooltip");
}
};
wijtooltip.prototype._getDocSize = function (name) {
var scrollValue, offsetValue, de = "documentElement", body = "body";
// handle IE 6
if($.browser.msie && parseFloat($.browser.version) < 9) {
scrollValue = max(doc[de]["scroll" + name], doc[body]["scroll" + name]);
offsetValue = max(doc[de]["offset" + name], doc[body]["offset" + name]);
return (scrollValue < offsetValue ? ($(win)[name.toLowerCase()]() + 'px') : scrollValue + 'px');
} else {
return $(doc)[name.toLowerCase()]() + 'px';
}
};
wijtooltip.prototype._onClickCloseBtn = //begin event handler methods
function (e) {
this.hide();
e.preventDefault();
};
wijtooltip.animations = {
fade: function (options, additions) {
options = $.extend({
duration: 300,
easing: "swing"
}, options, additions);
options.context.stop(true, true).animate(options.show ? {
opacity: 'show'
} : {
opacity: 'hide'
}, options);
},
tooltipSlide: function (options, additions) {
options = $.extend({
duration: 300,
easing: "swing"
}, options, additions);
options.context.stop(true, true).animate({
left: options.pos.left,
top: options.pos.top
}, options);
}
};
wijtooltip._getTooltip = function _getTooltip(key) {
return wijtooltip._tooltips[key];
};
wijtooltip._removeTooltip = function _removeTooltip(key) {
var tooltipCache = wijtooltip._tooltips[key], _$tooltip = tooltipCache ? tooltipCache._$tooltip : null;
if(tooltipCache) {
tooltipCache.count--;
if(tooltipCache.count <= 0) {
_$tooltip.remove();
wijtooltip._tooltips[key] = null;
}
//tooltip = null;
}
};
return wijtooltip;
})(wijmo.wijmoWidget);
tooltip.wijtooltip = wijtooltip;
//#endregion
var wijtooltip_options = (function () {
function wijtooltip_options() {
/** Selector option for auto self initialization.
* This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijtooltip')";
/** tooltip css, extend from $.wijmo.wijCSS
* @ignore
*/
this.wijCSS = {
tooltip: "wijmo-wijtooltip",
tooltipContainer: "wijmo-wijtooltip-container",
tooltipPointer: "wijmo-wijtooltip-pointer",
tooltipPointerInner: "wijmo-wijtooltip-pointer-inner",
tooltipTitle: "wijmo-wijtooltip-title",
tooltipClose: "wijmo-wijtooltip-close"
};
/** @ignore */
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body-a",
stateDefault: "ui-btn-up-a",
stateHover: "ui-btn-down-a",
stateActive: "ui-btn-down-a"
};
/** Sets the tooltip's content.
* @type {string|function}
* @remarks The value can be a string, html code, or a function.
* If it is a function, then the content will be
* the function's return value.
* @example
* //Set tooltip's content to "my content".
* $(".selector").wijtooltip("option", "content", "my content").
*/
this.content = '';
/** Specifies a value that sets the tooltip's title.
* @type {string|function}
* @remarks The value can be a string, html code, or a function.
* If it is a function, then the title will be the function's return value.
* @example
* //Set tooltip's title to "my title".
* $(".selector").wijtooltip("option", "title", "my title");
*/
this.title = '';
/** Determines how to close the tooltip. Behaviors include auto or sticky.
* @remarks Options: "auto", "none" and "sticky".
*/
this.closeBehavior = 'auto';
/** If true, then the tooltip moves with the mouse. */
this.mouseTrailing = false;
/** Sets the event that will cause the tooltip to appear.
* @remarks Options: "hover", "click", "focus", "rightClick", "custom".
*/
this.triggers = 'hover';
/** Sets the tooltip's position mode in relation to the 'relativeTo',
* 'offsetX', and 'offsetY' properties.
* @remarks See jQuery ui position for more details
* http://api.jqueryui.com/position/ .
*/
this.position = {
my: 'left bottom',
at: 'right top',
offset: null
};
/** Determines whether to show the callout element. */
this.showCallout = true;
/** Sets the showAnimation and hideAnimation options if they are not specified individually.
* @remarks This should be an object value. Possible values include:
* 'animated', 'duration', and 'easing'. You can create custom easing
* animations using jQuery UI Easings.
* This property works with jQuery animation.
*/
this.animation = {
animated: 'fade',
duration: 500,
easing: null
};
/** Determines the animation effect that will be shown.
* @remarks This should be an object value. Possible values include:
* 'animated', 'duration', and 'easing'. You can create custom easing
* animations using jQuery UI Easings.
* This property works with jQuery animation.
*/
this.showAnimation = {
};
/** Determines whether the animation effect can be seen.
* @remarks This should be an object value. Possible values include:
* 'animated', 'duration', and 'easing'. You can create custom easing
* animations using jQuery UI Easings.
* This property works with jQuery animation.
*/
this.hideAnimation = {
};
/** Determines the length of the delay before the tooltip appears. */
this.showDelay = 150;
/** Determines the length of the delay before the tooltip disappears. */
this.hideDelay = 150;
/** Sets the callout's offset changing animation.
* @remarks This should be an object value. Possible values include:
* 'disabled', 'duration', and 'easing'.
*/
this.calloutAnimation = {
duration: 1000,
disabled: false,
easing: null
};
/** Determines the callout's class style.
* If true, then the callout triangle is filled.
*/
this.calloutFilled = false;
/** A value that indicates whether to show the modal tooltip. */
this.modal = false;
/** Determines which group the tooltip belongs to.
* @type {string}
*/
this.group = null;
/** A function that defines a callback when AJAX is uesd to set the
* content property.
* @type {function}
* @remarks In AJAX's complete callback method, the user set the callback
* data to the content option.
*/
this.ajaxCallback = null;
/** Trigegred before showing the tooltip. If data.cancel is
* set to true, then the tooltip is no longer shown.
* @event
* @param event jQuery.Event object
* @param ui The wijtooltip widget.
*/
this.showing = null;
/** Triggered once the tooltip has shown.
* @event
* @param event jQuery.Event object
* @param ui The wijtooltip widget.
*/
this.shown = null;
/** Triggered before hiding the tooltip.If data.cancel is
* set to true, then the tooltip is no longer hidden
* @event
* @param event jQuery.Event object
* @param ui The wijtooltip widget.
*/
this.hiding = null;
/** Triggered once the tooltip is hidden.
* @event
* @param event jQuery.Event object
* @param ui The wijtooltip widget.
*/
this.hidden = null;
/** A value that indicates whether to set user-defined class. */
this.cssClass = '';
}
return wijtooltip_options;
})();
;
//#region options
wijtooltip.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijtooltip_options());
//#endregion
$.wijmo.registerWidget(widgetName, wijtooltip.prototype);
})(wijmo.tooltip || (wijmo.tooltip = {}));
var tooltip = wijmo.tooltip;
})(wijmo || (wijmo = {}));
/** @ignore */
var TooltipCache = (function () {
function TooltipCache() { }
return TooltipCache;
})();
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/*globals window,document,jQuery*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.mouse.js
* jquery.ui.widget.js
* jquery.ui.slider.js
* jquery.ui.wijutil.js
*
*/
(function (slider) {
"use strict";
var $ = jQuery, widgetName = "wijslider";
/** @ignore */
var JQueryUISlider = (function (_super) {
__extends(JQueryUISlider, _super);
function JQueryUISlider() {
_super.apply(this, arguments);
}
JQueryUISlider.prototype._valueMin = function () {
return $.ui.slider.prototype._valueMin.apply(this, arguments);
};
JQueryUISlider.prototype._refreshValue = function () {
return $.ui.slider.prototype._refreshValue.apply(this, arguments);
};
JQueryUISlider.prototype._create = function () {
return $.ui.slider.prototype._create.apply(this, arguments);
};
JQueryUISlider.prototype.values = /** This option can be used to specify multiple handles.
* @remarks
* If the range option is set to true, the length of values should be 2.
* @param {?number} index the first value.
* @param {?number} val the second value.
*/
function (index, val) {
return $.ui.slider.prototype.values.apply(this, arguments);
};
JQueryUISlider.prototype.value = /** Determines the value of the slider, if there's only one handle.
* @remarks
* If there is more than one handle, determines the value of the first handle.
* @param {?number} val the specified value.
*/
function (val) {
return $.ui.slider.prototype.value.apply(this, arguments);
};
JQueryUISlider.prototype._slide = function (event, index, newValue) {
return $.ui.slider.prototype._slide.apply(this, arguments);
};
JQueryUISlider.prototype._change = function (event, index) {
return $.ui.slider.prototype._change.apply(this, arguments);
};
return JQueryUISlider;
})(wijmo.JQueryUIWidget);
slider.JQueryUISlider = JQueryUISlider;
/** @widget
* @extends jQuery.ui.slider
*/
var wijslider = (function (_super) {
__extends(wijslider, _super);
function wijslider() {
_super.apply(this, arguments);
}
wijslider.prototype._setOption = function (key, value) {
/// <summary>
/// Sets Slider options.
/// </summary>
var self = this;
if(key === "values") {
value = self._pre_set_values(value);
self.options[key] = value;
self._setValuesOption();
} else {
$.ui.slider.prototype._setOption.apply(self, arguments);
}
//Add for support disabled option at 2011/7/8
if(key === "range") {
self._setRangeOption(value);
}
//end for disabled option
return this;
};
wijslider.prototype._setRangeOption = function (value) {
var self = this, o = self.options, valueMin;
if(value === true) {
if(!o.values || (o.values && o.values.length === 0)) {
valueMin = self._valueMin();
o.values = [
valueMin,
valueMin
];
} else if(o.values.length && o.values.length !== 2) {
valueMin = o.values[0];
o.values = [
valueMin,
valueMin
];
}
self._refresh_handle(2);
}
self._re_createRange();
self._refreshValue();
};
wijslider.prototype._setValuesOption = function () {
var self = this, valsLength = 0, i;
self._animateOff = true;
self._refreshValue();
if($.isArray(self.options.values)) {
valsLength = self.options.values.length;
}
for(i = 0; i < valsLength; i++) {
self._change(null, i);
}
self._animateOff = false;
};
wijslider.prototype._re_createRange = function () {
var self = this, o = self.options;
if(self.range) {
self.range.remove();
//update for jquery ui 1.10 upgrade
if($(".ui-slider-range", self.element).length > 0) {
$(".ui-slider-range", self.element).remove();
}
}
if(o.range) {
self.range = $("<div></div>").appendTo(self.element).addClass("ui-slider-range ui-widget-header" + ((o.range === "min" || o.range === "max") ? " ui-slider-range-" + o.range : ""));
}
};
wijslider.prototype._pre_set_values = function (values) {
var self = this, o = self.options, newHandleLen = 1, value;
newHandleLen = values && values.length ? values.length : 1;
if(o.range === true) {
if(!values || (values && values.length === 0)) {
value = self._valueMin();
values = [
value,
value
];
} else if(values.length && values.length !== 2) {
value = values[0];
values = [
value,
value
];
}
newHandleLen = 2;
}
self._refresh_handle(newHandleLen);
self._re_createRange();
return values;
};
wijslider.prototype._refresh_handle = function (newHandleLen) {
var self = this, handleLen = self.handles.length, handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>", handles = [], i;
if(handleLen !== newHandleLen) {
if(newHandleLen > handleLen) {
for(i = handleLen; i < newHandleLen; i++) {
handles.push(handle);
}
self.element.append(handles.join(""));
} else {
self.element.find(".ui-slider-handle").eq(newHandleLen - 1).nextAll().remove();
}
self.handles = self.element.find(".ui-slider-handle");
}
};
wijslider.prototype._initState = function () {
this._dragFillTarget = false;
this._dragFillStart = 0;
this._rangeValue = 0;
this._oldValue1 = 0;
this._oldValue2 = 0;
this._oldX = 0;
this._oldY = 0;
};
wijslider.prototype._create = function () {
/// <summary>
/// Creates Slider DOM elements and binds interactive events.
/// </summary>
var self = this, element = self.element, o = self.options, jqElement, val, vals, idx, len, ctrlWidth, ctrlHeight, container, decreBtn, increBtn, thumb;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
this._initState();
self._oriStyle = element.attr("style");
if(element.is(":input")) {
if(o.orientation === "horizontal") {
jqElement = $("<div></div>").width(element.width()).appendTo(document.body);
} else {
jqElement = $("<div></div>").height(element.height()).appendTo(document.body);
}
val = element.val();
if(val !== "") {
try {
vals = val.split(";");
len = vals.length;
if(len > 0) {
for(idx = 0; idx < len; idx++) {
vals[idx] = parseInt(vals[idx], 10);
}
if(len === 1) {
o.value = vals[0];
} else {
o.values = vals;
}
}
} catch (e) {
}
}
element.data(self.widgetName, jqElement.wijslider(o)).after($(document.body).children("div:last")).hide();
//Add for support disabled option at 2011/7/8
if(o.disabledState) {
var dis = o.disabled;
self.disable();
o.disabled = dis;
}
//end for disabled option
return;
}
_super.prototype._create.call(this);
element.data("originalStyle", element.attr("style"));
element.data("originalContent", element.html());
ctrlWidth = element.width();
ctrlHeight = element.height();
container = $("<div></div>");
if(o.orientation === "horizontal") {
container.addClass("wijmo-wijslider-horizontal");
} else {
container.addClass("wijmo-wijslider-vertical");
}
container.width(ctrlWidth).height(ctrlHeight);
decreBtn = $("<a class=\"wijmo-wijslider-decbutton\"><span></span></a>");
increBtn = $("<a class=\"wijmo-wijslider-incbutton\"><span></span></a>");
element.wrap(container).before(decreBtn).after(increBtn);
self._container = element.parent();
self._attachClass();
thumb = element.find(".ui-slider-handle");
self._adjustSliderLayout(decreBtn, increBtn, thumb);
//Add for support disabled option at 2011/7/8
if(o.disabledState) {
var dis = o.disabled;
self.disable();
o.disabled = dis;
}
//end for disabled option
//update for visibility change
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
self._refreshSlider();
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
}, "wijslider");
}
self._bindEvents();
};
wijslider.prototype.values = /**
_handleDisabledOption(disabled, ele) {
var self = this;
if (disabled) {
if (!self.disabledDiv) {
self.disabledDiv = self._createDisabledDiv(ele);
}
self.disabledDiv.appendTo("body");
}
else {
if (self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
}
}
_createDisabledDiv(outerEle) {
var self = this,
//Change your outerelement here
ele = outerEle ? outerEle : self.element,
eleOffset = ele.offset(),
disabledWidth = ele.outerWidth(),
disabledHeight = ele.outerHeight();
return $("<div></div>")
.addClass("ui-disabled")
.css({
"z-index": "99999",
position: "absolute",
width: disabledWidth,
height: disabledHeight,
left: eleOffset.left,
top: eleOffset.top
});
}*/
/** This option can be used to specify multiple handles.
* @remarks
* If the range option is set to true, the length of values should be 2.
* @param {?number} index the first value.
* @param {?number} val the second value.
*/
function (index, val) {
return $.ui.slider.prototype.values.apply(this, arguments);
};
wijslider.prototype.value = /** Determines the value of the slider, if there's only one handle.
* @remarks
* If there is more than one handle, determines the value of the first handle.
* @param {?number} val the specified value.
*/
function (val) {
return $.ui.slider.prototype.value.apply(this, arguments);
};
wijslider.prototype.refresh = /** Refresh the wijslider widget. */
function () {
// note: when the original element's width is setted by percent
// it's hard to adjust the position and size, so first destroy then
// recreate
//this._refresh();
var widgetObject = this.element.data("wijslider"), wijmoWidgetObject = this.element.data("wijmoWijslider");
this.destroy();
this.element.data("wijslider", widgetObject);
this.element.data("wijmoWijslider", wijmoWidgetObject);
this._create();
};
wijslider.prototype._refreshSlider = function () {
var self = this, increBtn, decreBtn, thumb;
// self.destroy();
// self._create();
decreBtn = self._container.find(".wijmo-wijslider-decbutton");
increBtn = self._container.find(".wijmo-wijslider-incbutton");
thumb = self._container.find(".ui-slider-handle");
self._adjustSliderLayout(decreBtn, increBtn, thumb);
self._refreshValue();
};
wijslider.prototype._adjustSliderLayout = function (decreBtn, increBtn, thumb) {
var self = this, element = self.element, o = self.options, ctrlWidth, ctrlHeight, decreBtnWidth, decreBtnHeight, increBtnWidth, increBtnHeight, thumbWidth, thumbHeight, dbtop, ibtop, dbleft, ibleft;
ctrlWidth = self._container.width();
ctrlHeight = self._container.height();
decreBtnWidth = decreBtn.outerWidth();
decreBtnHeight = decreBtn.outerHeight();
increBtnWidth = increBtn.outerWidth();
increBtnHeight = increBtn.outerHeight();
thumbWidth = thumb.outerWidth();
thumbHeight = thumb.outerHeight();
if(o.orientation === "horizontal") {
dbtop = ctrlHeight / 2 - decreBtnHeight / 2;
decreBtn.css("top", dbtop).css("left", 0);
ibtop = ctrlHeight / 2 - increBtnHeight / 2;
increBtn.css("top", ibtop).css("right", 0);
element.css("left", decreBtnWidth + thumbWidth / 2 - 1).css("top", ctrlHeight / 2 - element.outerHeight() / 2).width(ctrlWidth - decreBtnWidth - increBtnWidth - thumbWidth - 2);
} else {
dbleft = ctrlWidth / 2 - decreBtnWidth / 2;
decreBtn.css("left", dbleft).css("top", 0);
ibleft = ctrlWidth / 2 - increBtnWidth / 2;
increBtn.css("left", ibleft).css("bottom", 0);
element.css("left", ctrlWidth / 2 - element.outerWidth() / 2).css("top", decreBtnHeight + thumbHeight / 2 + 1).height(ctrlHeight - decreBtnHeight - increBtnHeight - thumbHeight - 2);
}
};
wijslider.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this, decreBtn, increBtn;
decreBtn = this._getDecreBtn();
increBtn = this._getIncreBtn();
decreBtn.unbind('.' + self.widgetName);
increBtn.unbind('.' + self.widgetName);
_super.prototype.destroy.call(this);
//update for destroy by wh at 2011/11/11
//this.element.parent().removeAttr("class");
//this.element.parent().html("");
$("a", self.element.parent()).remove();
self.element.unbind('.' + self.widgetName);
self.element.unwrap();
if(self._oriStyle === undefined) {
self.element.removeAttr("style");
} else {
self.element.attr("style", self._oriStyle);
}
self.element.removeData(self.widgetName).removeData("originalStyle").removeData("originalContent");
//end
//Add for support disabled option at 2011/7/8
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
//end for disabled option
};
wijslider.prototype._slide = function (event, index, newVal) {
var self = this, o = self.options, minRange = o.minRange, newValue = newVal, values;
if(o.range === true) {
values = self.values();
if(index === 0 && values[1] - minRange < newVal) {
newValue = values[1] - minRange;
} else if(index === 1 && values[0] + minRange > newVal) {
newValue = values[0] + minRange;
}
}
_super.prototype._slide.call(this, event, index, newValue);
};
wijslider.prototype._getDecreBtn = function () {
var decreBtn = this.element.parent().find(".wijmo-wijslider-decbutton");
return decreBtn;
};
wijslider.prototype._getIncreBtn = function () {
var increBtn = this.element.parent().find(".wijmo-wijslider-incbutton");
return increBtn;
};
wijslider.prototype._attachClass = function () {
this._getDecreBtn().addClass("ui-corner-all ui-state-default").attr("role", "button");
this._getIncreBtn().addClass("ui-corner-all ui-state-default").attr("role", "button");
this.element.parent().attr("role", "slider").attr("aria-valuemin", this.options.min).attr("aria-valuenow", "0").attr("aria-valuemax", this.options.max);
if(this.options.orientation === "horizontal") {
this.element.parent().addClass("wijmo-wijslider-horizontal");
this._getDecreBtn().find("> span").addClass("ui-icon ui-icon-triangle-1-w");
this._getIncreBtn().find("> span").addClass("ui-icon ui-icon-triangle-1-e");
} else {
this.element.parent().addClass("wijmo-wijslider-vertical");
this._getDecreBtn().find("> span").addClass("ui-icon ui-icon-triangle-1-n");
this._getIncreBtn().find("> span").addClass("ui-icon ui-icon-triangle-1-s");
}
};
wijslider.prototype._bindEvents = function () {
var self = this, decreBtn, increBtn, ele;
decreBtn = this._getDecreBtn();
increBtn = this._getIncreBtn();
ele = self.element;
//
decreBtn.bind('click.' + self.widgetName, self, self._decreBtnClick);
increBtn.bind('click.' + self.widgetName, self, self._increBtnClick);
//
decreBtn.bind('mouseover.' + self.widgetName, self, self._decreBtnMouseOver);
decreBtn.bind('mouseout.' + self.widgetName, self, self._decreBtnMouseOut);
decreBtn.bind('mousedown.' + self.widgetName, self, self._decreBtnMouseDown);
decreBtn.bind('mouseup.' + self.widgetName, self, self._decreBtnMouseUp);
increBtn.bind('mouseover.' + self.widgetName, self, self._increBtnMouseOver);
increBtn.bind('mouseout.' + self.widgetName, self, self._increBtnMouseOut);
increBtn.bind('mousedown.' + self.widgetName, self, self._increBtnMouseDown);
increBtn.bind('mouseup.' + self.widgetName, self, self._increBtnMouseUp);
ele.bind('mouseup.' + self.widgetName, self, self._elementMouseupEvent);
};
wijslider.prototype._decreBtnMouseOver = function (e) {
var self = e.data, data, decreBtn;
if(self.options.disabledState || self.options.disabled) {
return;
}
data = {
buttonType: "decreButton"
};
self._trigger('buttonMouseOver', e, data);
//
decreBtn = self._getDecreBtn();
decreBtn.addClass("ui-state-hover");
};
wijslider.prototype._increBtnMouseOver = function (e) {
var self = e.data, data, increBtn;
if(self.options.disabledState || self.options.disabled) {
return;
}
data = {
buttonType: "increButton"
};
self._trigger('buttonMouseOver', e, data);
//
increBtn = self._getIncreBtn();
increBtn.addClass("ui-state-hover");
};
wijslider.prototype._decreBtnMouseOut = function (e) {
var self = e.data, data, decreBtn;
if(self.options.disabledState || self.options.disabled) {
return;
}
data = {
buttonType: "decreButton"
};
self._trigger('buttonMouseOut', e, data);
//
decreBtn = self._getDecreBtn();
decreBtn.removeClass("ui-state-hover ui-state-active");
};
wijslider.prototype._increBtnMouseOut = function (e) {
var self = e.data, data, increBtn;
if(self.options.disabledState || self.options.disabled) {
return;
}
data = {
buttonType: "increButton"
};
self._trigger('buttonMouseOut', e, data);
//
increBtn = self._getIncreBtn();
increBtn.removeClass("ui-state-hover ui-state-active");
};
wijslider.prototype._decreBtnMouseDown = function (e) {
var self = e.data, data, decreBtn;
if(self.options.disabledState || self.options.disabled) {
return;
}
data = {
buttonType: "decreButton"
};
self._trigger('buttonMouseDown', e, data);
//
decreBtn = self._getDecreBtn();
decreBtn.addClass("ui-state-active");
//if the mouse release util the mouse out, the track still take effect.
//added by wuhao 2011/7/16
$(document).bind("mouseup." + self.widgetName, {
self: self,
ele: decreBtn
}, self._documentMouseUp);
if(self._intervalID !== null) {
window.clearInterval(self._intervalID);
self._intervalID = null;
}
//end for mouse release
self._intervalID = window.setInterval(function () {
self._decreBtnHandle(self);
}, 200);
};
wijslider.prototype._documentMouseUp = function (e) {
var self = e.data.self, ele = e.data.ele;
if(self.options.disabledState || self.options.disabled) {
return;
}
ele.removeClass("ui-state-active");
if(self._intervalID !== null) {
window.clearInterval(self._intervalID);
self._intervalID = null;
}
$(document).unbind("mouseup." + self.widgetName, self._documentMouseUp);
};
wijslider.prototype._increBtnMouseDown = function (e) {
var self = e.data, data, increBtn;
if(self.options.disabledState || self.options.disabled) {
return;
}
data = {
buttonType: "increButton"
};
self._trigger('buttonMouseDown', e, data);
//
increBtn = self._getIncreBtn();
increBtn.addClass("ui-state-active");
//if the mouse release util the mouse out, the track still take effect.
//added by wuhao 2011/7/16
$(document).bind("mouseup." + self.widgetName, {
self: self,
ele: increBtn
}, self._documentMouseUp);
if(self._intervalID !== null) {
window.clearInterval(self._intervalID);
self._intervalID = null;
}
//end for mouse release
self._intervalID = window.setInterval(function () {
self._increBtnHandle(self);
}, 200);
};
wijslider.prototype._decreBtnMouseUp = function (e) {
var self = e.data, data, decreBtn;
if(self.options.disabledState || self.options.disabled) {
return;
}
data = {
buttonType: "decreButton"
};
self._trigger('buttonMouseUp', e, data);
//
decreBtn = self._getDecreBtn();
decreBtn.removeClass("ui-state-active");
window.clearInterval(self._intervalID);
};
wijslider.prototype._increBtnMouseUp = function (e) {
var self = e.data, data, increBtn;
if(self.options.disabledState || self.options.disabled) {
return;
}
data = {
buttonType: "increButton"
};
self._trigger('buttonMouseUp', e, data);
//
increBtn = self._getIncreBtn();
increBtn.removeClass("ui-state-active");
window.clearInterval(self._intervalID);
};
wijslider.prototype._decreBtnHandle = function (sender) {
if(sender.options.orientation === "horizontal") {
sender._decre();
} else {
sender._incre();
}
};
wijslider.prototype._decreBtnClick = function (e) {
var self = e.data, data;
if(self.options.disabledState || self.options.disabled) {
return;
}
//note: step1: slide the slider btn, the change event has fired;
//step2: then click the decre button, the change event don't fired.
self._mouseSliding = false;
//end
self._decreBtnHandle(self);
data = {
buttonType: "decreButton",
value: self.value()
};
self._trigger('buttonClick', e, data);
};
wijslider.prototype._increBtnHandle = function (sender) {
if(sender.options.orientation === "horizontal") {
sender._incre();
} else {
sender._decre();
}
};
wijslider.prototype._increBtnClick = function (e) {
var self = e.data, data;
if(self.options.disabledState || self.options.disabled) {
return;
}
//note: step1: slide the slider btn, the change event has fired;
//step2: then click the decre button, the change event don't fired.
self._mouseSliding = false;
//end
self._increBtnHandle(self);
data = {
buttonType: "increButton",
value: self.value()
};
self._trigger('buttonClick', e, data);
};
wijslider.prototype._decre = function () {
var self = this, curVal = self.value(), o = self.options, min = o.min, step = o.step;
//
if(o.values && o.values.length) {
curVal = self.values(0);
if(curVal <= min) {
self.values(0, min);
} else {
self.values(0, curVal - step);
}
} else {
curVal = self.value();
if(curVal <= min) {
self.value(min);
} else {
self.value(curVal - step);
}
}
//
self.element.parent().attr("aria-valuenow", self.value());
};
wijslider.prototype._incre = function () {
var self = this, curVal = self.value(), o = self.options, max = o.max, step = o.step, index;
//
if(o.values && o.values.length) {
index = o.values.length === 1 ? 0 : 1;
curVal = self.values(index);
if(curVal >= max) {
self.values(index, max);
} else {
self.values(index, curVal + step);
}
} else {
curVal = self.value();
if(curVal >= max) {
self.value(max);
} else {
self.value(curVal + step);
}
}
//
self.element.parent().attr("aria-valuenow", self.value());
};
wijslider.prototype._elementMouseupEvent = function (e) {
var self = e.data;
if(self.options.dragFill && self.options.range) {
if(self._dragFillStart > 0) {
self._dragFillStart = 0;
} else {
$.ui.slider.prototype._mouseCapture.apply(self, arguments);
}
}
};
wijslider.prototype._mouseCapture = function (event) {
this.element.parent().attr("aria-valuenow", this.value());
if(this.options.dragFill) {
if(event.target.className === "ui-slider-range ui-widget-header ui-corner-all" || //for older version of jQuery UI
event.target.className === "ui-slider-range ui-widget-header") {
this.elementSize = {
width: this.element.outerWidth(),
height: this.element.outerHeight()
};
this.elementOffset = this.element.offset();
return true;
} else {
try {
return $.ui.slider.prototype._mouseCapture.apply(this, arguments);
} catch (e) {
}
}
} else {
try {
return $.ui.slider.prototype._mouseCapture.apply(this, arguments);
} catch (e) {
}
}
};
wijslider.prototype._mouseStart = function (event) {
if(this.options.dragFill) {
if(event.target) {
if(event.target.className === "ui-slider-range ui-widget-header ui-corner-all" || //for older version of jQuery UI
event.target.className === "ui-slider-range ui-widget-header") {
this._dragFillTarget = true;
this._rangeValue = this.values(1) - this.values(0);
this._oldValue1 = this.values(0);
this._oldValue2 = this.values(1);
this._oldX = event.pageX;
this._oldY = event.pageY;
return true;
}
}
this._dragFillTarget = false;
}
return true;
};
wijslider.prototype._mouseDrag = function (event) {
var distance, eleLength, movValue, v, v0, v1;
if(this.options.dragFill) {
distance = event.pageX - this._oldX;
//var position = { x: event.pageX, y: event.pageY };
//var movValue = this._normValueFromMouse(position);
eleLength = this.element.outerWidth();
if(this.options.orientation === "vertical") {
eleLength = this.element.outerHeight();
distance = -(event.pageY - this._oldY);
}
movValue = (this.options.max - this.options.min) / eleLength * distance;
//document.title = distanceX + "|" + movValue;
if(this._dragFillTarget) {
if(this.options.orientation === "vertical") {
$(document.documentElement).css("cursor", "s-resize");
} else {
$(document.documentElement).css("cursor", "w-resize");
}
if(this._dragFillStart > 0) {
v = this._rangeValue;
/* if (normValue + v >= this.options.max) {
this.values(0, this.options.max - v);
this.values(1, this.options.max);
}
else {
}*/
this.values(0, this._oldValue1 + movValue);
this.values(1, this._oldValue1 + movValue + v);
v0 = this.values(0);
v1 = this.values(1);
if(v0 + v > this.options.max) {
this.values(0, this.options.max - v);
}
if(v1 - v < this.options.min) {
this.values(1, this.options.min + v);
}
}
this._dragFillStart++;
return false;
} else {
return $.ui.slider.prototype._mouseDrag.apply(this, arguments);
}
} else {
return $.ui.slider.prototype._mouseDrag.apply(this, arguments);
}
};
wijslider.prototype._mouseStop = function (event) {
var returnVal = $.ui.slider.prototype._mouseStop.apply(this, arguments);
if(this.options.dragFill) {
$(document.documentElement).css("cursor", "default");
window.setTimeout(function () {
this._dragFillTarget = false;
this._dragFillStart = 0;
}, 500);
}
return returnVal;
};
return wijslider;
})(JQueryUISlider);
slider.wijslider = wijslider;
wijslider.prototype.widgetEventPrefix = "wijslider";
var wijslider_options = (function () {
function wijslider_options() {
/** The buttonMouseOver event is raised when the mouse is over
* the decrement button or the increment button.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IButtonEventArgs} args The data with this event.
*/
this.buttonMouseOver = null;
/** The buttonMouseOut event is raised when the mouse leaves
* the decrement button or the increment button.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IButtonEventArgs} args The data with this event.
*/
this.buttonMouseOut = null;
/** The buttonMouseDown event is raised when the mouse is down
* on the decrement button or the increment button.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IButtonEventArgs} args The data with this event.
*/
this.buttonMouseDown = null;
/** The buttonMouseUp event is raised when the mouse is up
* on the decrement button or the increment button.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IButtonEventArgs} args The data with this event.
*/
this.buttonMouseUp = null;
/** The buttonClick event is raised when the decrement button
* or the increment button is clicked.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IButtonEventArgs} args The data with this event.
*/
this.buttonClick = null;
/** The dragFill option, when set to true, allows the user to drag
* the fill between the thumb buttons on the slider widget.
*/
this.dragFill = true;
/** The minRange option prevents the two range handles (thumb buttons)
* from being placed on top of one another.
*/
this.minRange = 0;
/** The animate option defines the sliding animation that is
* applied to the slider handle when a user clicks outside the handle on the bar.
* @remarks This option will accept a string representing one of the three predefined
* speeds or a number representing the length of time in
* milliseconds that the animation will run. The three predefined speeds are slow, normal, or fast.
*/
this.animate = false;
/** The max option defines the maximum value of the slider widget.
*/
this.max = 100;
/** The min option defines the minimum value of the slider widget.
*/
this.min = 0;
/** The orientation option determines whether the wijslider is positioned horizontally or vertically.
* @remarks If the slider is positioned horizontally, then the min value will be at the left and the max
* value will be at the right. If the slider is positioned vertically, then the min value is at the bottom and
* the max value is at the top of the widget. By default, the widget's orientation is horizontal.
*/
this.orientation = "horizontal";
/** The range option, if set to true, allows the slider to detect if you have two handles.
* @type {boolean|string}
* @remarks It will then create a stylable range element between the two handles.
* You can also create a stylable range with one handle by using the 'min' and 'max' values.
* A min range goes from the slider min value to the range handle. A max range goes from the range
* handle to the slider max value.
*/
this.range = false;
/** The step option determines the size of each interval between the slider minimum value and the slider maximum value.
* @remarks The full specified value range of the slider (from the minimum value to the maximum value)
* must be evenly divisible by the step interval.
*/
this.step = 1;
/** The value option determines the total value of the slider widget when there is only one range handle.
* @remarks If there are two range handles, then the value option determines the value of the first handle.
*/
this.value = 0;
/** The values option can be used to specify multiple handles.
* @remarks If the range option is set to true, then the 'values' option must be set in order to have two handles.
*/
this.values = null;
/** The change event is triggered when the user stops moving the range handle or
* when a value is changed programatically.
* @remarks This event takes the event and ui arguments. please refer: http://api.jqueryui.com/slider/
* Use event.originalEvent to detect if the value was changed programatically or through mouse or keyboard interaction.
* @event
*/
this.change = null;
/** Triggered on every mouse move during slide.
* @remarks please refer: http://api.jqueryui.com/slider/
* @event
*/
this.slide = null;
/** The start event is triggered when the user begins to move the slider thumb.
* @remarks please refer: http://api.jqueryui.com/slider/
* @event
*/
this.start = null;
/** The stop event is triggered when the user stops sliding the slider thumb.
* @remarks please refer: http://api.jqueryui.com/slider/
* @event
*/
this.stop = null;
}
return wijslider_options;
})();
;
if($.ui && $.ui.slider) {
wijslider.prototype.options = $.extend(true, {
}, $.ui.slider.prototype.options, new wijslider_options());
$.wijmo.registerWidget(widgetName, $.ui.slider, wijslider.prototype);
}
})(wijmo.slider || (wijmo.slider = {}));
var slider = wijmo.slider;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts"/>
/*globals window,document,jQuery*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.resizable.js
* jquery.ui.mouse.js
* jquery.wijmo.wijutil.js
*
*/
(function (splitter) {
"use strict";
var $ = jQuery, widgetName = "wijsplitter";
/** @widget */
var wijsplitter = (function (_super) {
__extends(wijsplitter, _super);
function wijsplitter() {
_super.apply(this, arguments);
}
wijsplitter.prototype._setFullSplit = function (value) {
var self = this, fields = self._fields, width = value ? "100%" : fields.width, height = value ? "100%" : fields.height;
self.element.css("width", width).css("height", height);
};
wijsplitter.prototype._setOption = function (key, value) {
var self = this, o = self.options, expander, oldValue = $.extend({
}, o[key]);
if(key === "fullSplit") {
self._setFullSplit(value);
} else if($.isPlainObject(o[key])) {
if(key === "panel1" && value.collapsed !== undefined) {
//if(value.collapsed) { o.panel2.collapsed = false; }
self._setPanel1Collapsed(value.collapsed);
} else if(key === "panel2" && value.collapsed !== undefined) {
//if(value.collapsed) { o.panel1.collapsed = false; }
self._setPanel2Collapsed(value.collapsed);
}
o[key] = $.extend(true, o[key], value);
return;
}
$.Widget.prototype._setOption.apply(self, arguments);
if(oldValue !== value) {
if(key === "orientation") {
self.refresh();
} else if(key === "collapsingPanel") {
self.refresh();
} else if(key === "fullSplit") {
self.refresh(true, false);
} else if(key === "splitterDistance") {
self.refresh(false, false);
self._trigger("sized");
} else if(key === "showExpander") {
expander = self._fields.expander;
if(expander && expander.length) {
expander.css("display", value ? "" : "none");
}
}
}
//Add for support disabled option at 2011/7/8
if(key === "disabled") {
self._handleDisabledOption(value, self.element);
}
//end for disabled option
};
wijsplitter.prototype._create = function () {
var self = this, element = self.element, o = self.options, minSize;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
if(o.splitterDistance == 100) {
minSize = this.element.width() - o.panel2.minSize;
if(o.panel1.minSize > o.splitterDistance) {
o.splitterDistance = o.panel1.minSize;
} else if(minSize < o.splitterDistance) {
o.splitterDistance = minSize;
}
}
self._fields = {
width: element.width(),
height: element.height()
};
if(o.fullSplit) {
self._setFullSplit(true);
}
self._splitterify();
self._updateElementsCss();
self._updateElements();
self._bindEvents();
self._initResizer();
//Add for support disabled option at 2011/7/8
if(o.disabled) {
self.disable();
}
//end for disabled option
//fixed bug 28059
if(self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
if(o.fullSplit) {
self.refresh();
self._updateElements();
self._initResizer();
}
}, "wijsplitter");
}
self._trigger("load", null, self);
};
wijsplitter.prototype._handleDisabledOption = function (disabled, ele) {
var self = this;
if(disabled) {
if(!self.disabledDiv) {
self.disabledDiv = self._createDisabledDiv(ele);
}
self.disabledDiv.appendTo("body");
} else {
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
}
};
wijsplitter.prototype.destroy = /**
* Removes the splitter functionality completely.This will return the element back to its pre - init state.
* @example $("selector").wijsplitter("destroy");
*/
function () {
var self = this, o = self.options, element = self.element, fields = self._fields, wrapper = fields.wrapper, expander = fields.expander, bar = fields.bar, panel1 = fields.panel1, panel2 = fields.panel2, originalStyle = fields.originalStyle, widgetName = self.widgetName, oriPnl1Content = fields.oriPnl1Content, oriPnl2Content = fields.oriPnl2Content, oriPnl1ContentStyle = fields.oriPnl1ContentStyle, oriPnl2ContentStyle = fields.oriPnl2ContentStyle, css = o.wijCSS, vSplitterCSS = css.vSplitterCss, vSplitterPre = css.vSplitterCssPrefix, hSplitterCSS = css.hSplitterCss, hSplitterPre = css.hSplitterCssPrefix, panelCss = css.panelCss;
if($.fn.resizable) {
if(panel1 && panel1.n.is(":ui-resizable")) {
panel1.n.resizable('destroy');
}
}
if(oriPnl1Content) {
oriPnl1Content.removeClass(vSplitterPre + panel1.contentCss + " " + o.wijCSS.hSplitterCssPrefix + panel1.contentCss + " " + o.wijCSS.content);
if(oriPnl1ContentStyle === undefined) {
oriPnl1Content.removeAttr("style");
} else {
oriPnl1Content.attr("style", oriPnl1ContentStyle);
}
oriPnl1Content.appendTo(element);
}
if(oriPnl2Content) {
oriPnl2Content.removeClass(vSplitterPre + panel2.contentCss + " " + o.wijCSS.hSplitterCssPrefix + panel2.contentCss + " " + o.wijCSS.content);
if(oriPnl2ContentStyle === undefined) {
oriPnl2Content.removeAttr("style");
} else {
oriPnl2Content.attr("style", oriPnl2ContentStyle);
}
oriPnl2Content.appendTo(element);
}
panel1.n.unbind('.' + widgetName);
expander.unbind('.' + widgetName);
bar.unbind('.' + widgetName);
$(window).unbind('.' + widgetName);
wrapper.remove();
element.removeClass(vSplitterCSS + " " + hSplitterCSS);
if(originalStyle === undefined) {
element.removeAttr("style");
} else {
element.attr("style", originalStyle);
}
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
self._fields = null;
};
wijsplitter.prototype.refresh = /**
* Forces the widget to recreate the splitter.
* @param {boolean} size A boolean value to indicate whether the refresh is triggered
* because the size of widget is changed.
* @param {boolean} state A boolean value to indicate whether the refresh is triggered
* because the state of expander is changed(expanded/collapsed).
*/
function (size, state) {
var self = this, fields = self._fields, panel1 = fields.panel1;
if(fields._isResizing) {
return;
}
if(state || state === undefined) {
self._updateElementsCss();
}
self._updateElements();
if(size || size === undefined) {
if(!$.fn.resizable) {
return;
}
if(panel1 && panel1.n.is(":ui-resizable")) {
panel1.n.resizable('destroy');
}
self._initResizer();
}
};
wijsplitter.prototype._createDisabledDiv = function (outerEle) {
var self = this, ele = //Change your outerelement here
outerEle ? outerEle : self.element, eleOffset = ele.offset(), disabledWidth = ele.outerWidth(), disabledHeight = ele.outerHeight(), css = {
"z-index": "99999",
position: "absolute",
width: disabledWidth,
height: disabledHeight,
left: eleOffset.left,
top: eleOffset.top
};
if($.browser.msie) {
$.extend(css, {
"background-color": "#fff",
opacity: 0.1
});
}
return $("<div></div>").addClass("ui-disabled").css(css);
};
wijsplitter.prototype._splitterify = function () {
var self = this, element = self.element, o = self.options, fields = self._fields, wrapper, bar, expander, icon, pnl1 = {
n: undefined,
content: element.find(">div:eq(0)")
}, pnl2 = {
n: undefined,
content: element.find(">div:eq(1)")
};
fields.originalStyle = element.attr("style");
//create wrapper
wrapper = $("<div></div>").appendTo(element);
//create panel1
pnl1.n = $("<div></div>").appendTo(wrapper);
//create panel1 content if needed.
if(pnl1.content.length === 0) {
pnl1.content = $("<div></div>");
} else {
fields.oriPnl1Content = pnl1.content;
fields.oriPnl1ContentStyle = pnl1.content.attr("style");
}
pnl1.content.appendTo(pnl1.n);
//create bar.
bar = $("<div></div>").appendTo(wrapper);
if(o.barZIndex !== -1) {
bar.css("z-index", o.barZIndex);
}
//create expander.
expander = $("<div></div>").appendTo(bar).attr("role", "button");
//create icon.
icon = $("<span></span>").appendTo(expander);
//create panel2
pnl2.n = $("<div></div>").appendTo(wrapper);
//create panel2 content if needed.
if(pnl2.content.length === 0) {
pnl2.content = $("<div></div>");
} else {
fields.oriPnl2Content = pnl2.content;
fields.oriPnl2ContentStyle = pnl2.content.attr("style");
}
pnl2.content.appendTo(pnl2.n);
fields.wrapper = wrapper;
fields.panel1 = pnl1;
fields.panel2 = pnl2;
fields.bar = bar;
fields.expander = expander;
fields.icon = icon;
};
wijsplitter.prototype._updateElementsCss = function () {
var self = this, element = self.element, o = self.options, isVertical = o.orientation === "vertical", fields = self._fields, wrapper = fields.wrapper, collapsingPanel = o.collapsingPanel, otherPanel = o.collapsingPanel === 'panel1' ? 'panel2' : 'panel1', bar = fields.bar, expander = fields.expander, icon = fields.icon, css = o.wijCSS, vSplitterCSS = css.vSplitterCss, vSplitterPre = css.vSplitterCssPrefix, hSplitterCSS = css.hSplitterCss, hSplitterPre = css.hSplitterCssPrefix, panelCss = css.panelCss;
//add class to the outmost markup.
//add comments by RyanWu@20110817.
//For fixing the issue#16391.
// element.removeClass(vSplitterCss + " " + hSplitterCss +
// " " + vSplitterCssPrefix + css.expandedCss +
// " " + vSplitterCssPrefix + collapsedCss +
// " " + hSplitterCssPrefix + css.expandedCss +
// " " + hSplitterCssPrefix + css.collapsedCss)
// .addClass(isVertical ? vSplitterCss : hSplitterCss);
element.removeClass(vSplitterCSS + " " + hSplitterCSS).addClass(isVertical ? vSplitterCSS : hSplitterCSS);
//end by RyanWu@20110817.
//add class to wrapper
wrapper.attr("class", css.wrapperCss);
//add class to panel1
fields[collapsingPanel].n.removeClass(vSplitterPre + panelCss[collapsingPanel].n + " " + hSplitterPre + panelCss[collapsingPanel].n).addClass((isVertical ? vSplitterPre : hSplitterPre) + panelCss[collapsingPanel].n);
//add class to panel1 content.
fields[collapsingPanel].content.removeClass(vSplitterPre + panelCss[collapsingPanel].content + " " + hSplitterPre + panelCss[collapsingPanel].content + " " + css.content).addClass((isVertical ? vSplitterPre : hSplitterPre) + panelCss[collapsingPanel].content + " " + css.content);
//add class to bar.
bar.attr("class", (isVertical ? vSplitterPre : hSplitterPre) + css.barCss + " " + css.header).css("width", "").css("height", "");
//add class to expander.
expander.attr("class", css.cornerCssPrefix + (isVertical ? "bl " + vSplitterPre : "tr " + hSplitterPre) + css.expanderCss + " " + css.stateDefault).css("left", "").css("top", "");
//add class to icon.
icon.attr("class", css.icon + " " + (isVertical ? css.iconArrowLeft : css.iconArrowUp));
//add class to panel2
fields[otherPanel].n.removeClass(vSplitterPre + panelCss[otherPanel].n + " " + hSplitterPre + panelCss[otherPanel].n).addClass((isVertical ? vSplitterPre : hSplitterPre) + panelCss[otherPanel].n);
//add class to panel2 content.
fields[otherPanel].content.removeClass(vSplitterPre + panelCss[otherPanel].content + " " + hSplitterPre + panelCss[otherPanel].content + " " + css.content).addClass((isVertical ? vSplitterPre : hSplitterPre) + panelCss[otherPanel].content + " " + css.content);
// if panel1.collapsed = true, then we need update
// the expander icon's css.
self._updateExpanderCss();
};
wijsplitter.prototype._updateExpanderCss = function () {
var self = this, o = self.options, fields = self._fields, expander = fields.expander, icon = fields.icon, css = o.wijCSS, cornerPre = css.cornerCssPrefix, isVertical = o.orientation === "vertical", panel2IsCollapsing = o.collapsingPanel !== "panel1", cssPrefix = isVertical ? css.vSplitterCssPrefix : css.hSplitterCssPrefix, ovalue = (isVertical ? 1 : 0) * 2 + (panel2IsCollapsing ? 1 : 0), collapsedExpCorner1Css = [
"bl",
"tr",
"tr",
"bl"
][ovalue], collapsedExpCorner2Css = [
"br",
"tl"
][+panel2IsCollapsing], collapsedIconCss = [
css.iconArrowDown,
css.iconArrowUp,
css.iconArrowRight,
css.iconArrowLeft
][ovalue], expandedExpCorner1Css = [
"tr",
"bl",
"bl",
"tr"
][ovalue], expandedExpCorner2Css = [
"tl",
"br"
][+panel2IsCollapsing], expandedIconCss = [
css.iconArrowUp,
css.iconArrowDown,
css.iconArrowLeft,
css.iconArrowRight
][ovalue];
expander.removeClass(cssPrefix + o.collapsingPanel + "-" + css.expandedCss + " " + cssPrefix + o.collapsingPanel + "-" + css.collapsedCss + " " + cornerPre + collapsedExpCorner1Css + " " + cornerPre + collapsedExpCorner2Css + " " + cornerPre + expandedExpCorner1Css + " " + cornerPre + expandedExpCorner2Css);
icon.removeClass(collapsedIconCss + " " + expandedIconCss);
if(o.panel1.collapsed || o.panel2.collapsed) {
//element.addClass(cssPrefix + css.collapsedCss);
expander.addClass(cornerPre + collapsedExpCorner1Css + " " + cornerPre + collapsedExpCorner2Css + " " + cssPrefix + o.collapsingPanel + "-" + css.collapsedCss);
icon.addClass(collapsedIconCss);
} else {
//element.addClass(cssPrefix + css.expandedCss);
expander.addClass(cornerPre + expandedExpCorner1Css + " " + cornerPre + expandedExpCorner2Css + " " + cssPrefix + o.collapsingPanel + "-" + css.expandedCss);
icon.addClass(expandedIconCss);
}
};
wijsplitter.prototype._AddVisiblity = function (ele) {
if(ele.wijTriggerVisibility) {
ele.wijTriggerVisibility();
}
};
wijsplitter.prototype._updateElements = function () {
var self = this, element = self.element, o = self.options, distance = o.splitterDistance, collapsingPanel = o.collapsingPanel, otherPanel = o.collapsingPanel === 'panel1' ? 'panel2' : 'panel1', fields = self._fields, wrapper = fields.wrapper, pnl1 = fields.panel1, pnl2 = fields.panel2, bar = fields.bar, expander = fields.expander, width = element.width(), height = element.height(), barW, barH;
wrapper.height(height);
self._setPanelsScrollMode();
if(o.orientation === "vertical") {
barW = bar.outerWidth(true);
if(distance > width - barW) {
distance = width - barW;
}
//fixed bug 29981
//To prevent panel2 be a new line by the css "float:left"
wrapper.width(width * 2);
if(o.panel1.collapsed) {
if(collapsingPanel === "panel1") {
expander.addClass(o.wijCSS.vSplitterCssPrefix + "panel1" + "-" + o.wijCSS.collapsedCss);
}
fields.panel1.n.css("display", "none");
fields.panel2.n.css("display", "");
this._AddVisiblity(fields.panel2.n);
distance = 0;
} else {
if(collapsingPanel === "panel1") {
expander.addClass(o.wijCSS.vSplitterCssPrefix + "panel1" + "-" + o.wijCSS.expandedCss);
}
fields.panel1.n.css("display", "");
this._AddVisiblity(fields.panel1.n);
fields.panel2.n.css("display", o.panel2.collapsed ? "none" : "");
}
if(o.panel2.collapsed) {
if(collapsingPanel === "panel2") {
expander.addClass(o.wijCSS.vSplitterCssPrefix + "panel2" + "-" + o.wijCSS.collapsedCss);
}
fields.panel2.n.css("display", "none");
distance = (collapsingPanel === "panel1") ? width - barW : width;
} else {
if(collapsingPanel === "panel2") {
expander.addClass(o.wijCSS.vSplitterCssPrefix + "panel2" + "-" + o.wijCSS.expandedCss);
}
fields.panel2.n.css("display", "");
this._AddVisiblity(fields.panel2.n);
}
if(!o.panel1.collapsed && !o.panel2.collapsed) {
expander.addClass(o.wijCSS.vSplitterCssPrefix + o.collapsingPanel + "-" + o.wijCSS.expandedCss);
}
if(collapsingPanel === "panel1") {
fields.panel1.n.height(height).width(distance);
fields.panel2.n.height(height).width(width - distance - barW);
} else {
fields.panel1.n.height(height).width(distance - barW);
fields.panel2.n.height(height).width(width - distance);
//fields.panel2.content.width(width - distance);
}
fields.panel1.content.outerHeight(height, true);
bar.outerHeight(height, true);
fields.panel2.content.outerHeight(height, true);
expander.css("cursor", "pointer").css("top", height / 2 - expander.outerHeight(true) / 2);
} else {
barH = bar.outerHeight(true);
if(distance > height - barH) {
distance = height - barH;
}
if(o.panel1.collapsed) {
if(collapsingPanel === "panel1") {
expander.addClass(o.wijCSS.hSplitterCssPrefix + "panel1" + "-" + o.wijCSS.collapsedCss);
}
fields.panel1.n.css("display", "none");
fields.panel2.n.css("display", "");
this._AddVisiblity(fields.panel2.n);
distance = 0;
} else {
if(collapsingPanel === "panel1") {
expander.addClass(o.wijCSS.hSplitterCssPrefix + "panel1" + "-" + o.wijCSS.expandedCss);
}
fields.panel1.n.css("display", "");
this._AddVisiblity(fields.panel1.n);
fields.panel2.n.css("display", o.panel2.collapsed ? "none" : "");
}
if(o.panel2.collapsed) {
if(collapsingPanel === "panel2") {
expander.addClass(o.wijCSS.hSplitterCssPrefix + "panel2" + "-" + o.wijCSS.collapsedCss);
}
fields.panel2.n.css("display", "none");
distance = (collapsingPanel === "panel1") ? height - barH : height;
} else {
if(collapsingPanel === "panel2") {
expander.addClass(o.wijCSS.hSplitterCssPrefix + "panel2" + "-" + o.wijCSS.expandedCss);
}
fields.panel2.n.css("display", "");
this._AddVisiblity(fields.panel2.n);
}
if(collapsingPanel === "panel1") {
fields.panel1.n.width(width).height(distance);
fields.panel2.n.width(width).height(height - distance - barH);
fields.panel1.content.outerHeight(distance, true);
fields.panel2.content.outerHeight(height - distance - barH, true);
} else {
fields.panel1.n.width(width).height(distance - barH);
fields.panel2.n.width(width).height(height - distance);
fields.panel1.content.outerHeight(distance - barH, true);
fields.panel2.content.outerHeight(height - distance, true);
}
expander.css("cursor", "pointer").css("left", width / 2 - expander.outerWidth(true) / 2);
}
expander.css("display", o.showExpander ? "" : "none");
};
wijsplitter.prototype._bindEvents = function () {
var self = this, o = self.options, fields = self._fields, bar = fields.bar, expander = fields.expander, widgetName = self.widgetName;
expander.bind("mouseover." + widgetName, function (e) {
if(o.disabled) {
return;
}
expander.addClass(o.wijCSS.stateHover);
}).bind("mouseout." + widgetName, function (e) {
if(o.disabled) {
return;
}
expander.removeClass(o.wijCSS.stateHover).removeClass(o.wijCSS.stateActive);
}).bind("mousedown." + widgetName, function (e) {
if(o.disabled) {
return;
}
expander.addClass(o.wijCSS.stateActive);
}).bind("mouseup." + widgetName, function (e) {
if(o.disabled) {
return;
}
expander.removeClass(o.wijCSS.stateActive);
if(o.collapsingPanel === 'panel1') {
self._setPanel1Collapsed(!o.panel1.collapsed, e);
} else {
self._setPanel2Collapsed(!o.panel2.collapsed, e);
}
});
bar.bind("mouseover." + widgetName, function (e) {
if(o.disabled) {
return;
}
bar.addClass(o.wijCSS.stateHover);
}).bind("mouseout." + widgetName, function (e) {
if(o.disabled) {
return;
}
bar.removeClass(o.wijCSS.stateHover);
});
fields.panel1.n.bind("animating." + widgetName, function (e) {
if(o.disabled) {
return;
}
self._adjustLayout(self);
self._trigger("sizing", e, null);
}).bind("animated." + widgetName, function (e) {
if(o.disabled) {
return;
}
self._adjustLayout(self);
self._trigger("sized", e, null);
});
self.element.on("mouseover." + widgetName, ".ui-resizable-handle", function (e) {
if(o.disabled) {
return;
}
bar.addClass(o.wijCSS.stateHover);
}).on("mouseout." + widgetName, ".ui-resizable-handle", function (e) {
if(o.disabled) {
return;
}
bar.removeClass(o.wijCSS.stateHover);
});
$(window).bind("resize." + widgetName, function (e) {
if(o.disabled) {
return;
}
if(o.fullSplit && self.element.is(":visible")) {
//self.refresh();
self._updateElements();
self._initResizer();
}
});
};
wijsplitter.prototype._setPanel1Collapsed = function (collapsed, e) {
var self = this, o = self.options, oldCollapsed = o.panel1.collapsed, resizableHandle = $(".ui-resizable-handle", self.element);
if(oldCollapsed === collapsed) {
return;
}
if(o.collapsingPanel === 'panel1') {
if(!self._trigger(oldCollapsed ? "expand" : "collapse", e, null)) {
return;
}
}
o.panel1.collapsed = collapsed;
if(collapsed) {
o.panel2.collapsed = false;
if(o.collapsingPanel === 'panel2') {
resizableHandle.hide();
}
} else {
resizableHandle.show();
}
self._updateElements();
self._updateExpanderCss();
if(o.collapsingPanel === 'panel1') {
self._trigger(collapsed ? "collapsed" : "expanded", e, null);
}
};
wijsplitter.prototype._setPanel2Collapsed = function (collapsed, e) {
var self = this, o = self.options, oldCollapsed = o.panel2.collapsed, resizableHandle = $(".ui-resizable-handle", self.element);
if(oldCollapsed === collapsed) {
return;
}
if(o.collapsingPanel === 'panel2') {
if(!self._trigger(oldCollapsed ? "expand" : "collapse", e, null)) {
return;
}
}
o.panel2.collapsed = collapsed;
if(collapsed) {
o.panel1.collapsed = false;
if(o.collapsingPanel === 'panel1') {
resizableHandle.hide();
}
} else {
resizableHandle.show();
}
self._updateElements();
self._updateExpanderCss();
if(o.collapsingPanel === 'panel2') {
self._trigger(collapsed ? "collapsed" : "expanded", e, null);
}
};
wijsplitter.prototype._initResizer = function () {
var self = this, element = self.element, o = self.options, fields = self._fields, bar = fields.bar, collapsingPanel = o.collapsingPanel, otherPanel = o.collapsingPanel === 'panel1' ? 'panel2' : 'panel1', resizeSettings = o.resizeSettings, animation = resizeSettings.animationOptions, duration = animation.disabled ? 0 : animation.duration, width = element.width(), height = element.height(), barW, maxW, minW, barH, maxH, minH, resizableHandle;
if(!$.fn.resizable) {
return;
}
if(o.orientation === "vertical") {
barW = bar.outerWidth(true);
maxW = width - barW - o[otherPanel].minSize;
minW = o[collapsingPanel].minSize;
if(minW < 2) {
minW = 2;
}
fields.panel1.n.resizable({
zIndex: fields.panel1.n.zIndex() + 100,
wijanimate: true,
minWidth: minW,
maxWidth: maxW,
handles: 'e',
helper: o.wijCSS.vSplitterCssPrefix + o.wijCSS.resizeHelperCss,
animateDuration: duration,
animateEasing: animation.easing,
ghost: resizeSettings.ghost,
start: function () {
fields._isResizing = true;
},
stop: function () {
fields._isResizing = false;
}
});
} else {
barH = bar.outerHeight(true);
maxH = height - barH - o[otherPanel].minSize;
minH = o[collapsingPanel].minSize;
if(minH < 2) {
minH = 2;
}
fields.panel1.n.resizable({
zIndex: fields.panel1.n.zIndex() + 100,
wijanimate: true,
minHeight: minH,
maxHeight: maxH,
handles: 's',
helper: o.wijCSS.hSplitterCssPrefix + o.wijCSS.resizeHelperCss,
animateDuration: duration,
animateEasing: animation.easing,
ghost: resizeSettings.ghost,
start: function () {
fields._isResizing = true;
},
stop: function () {
fields._isResizing = false;
}
});
}
resizableHandle = $(".ui-resizable-handle", element);
if(o[otherPanel].collapsed) {
resizableHandle.hide();
} else {
resizableHandle.show();
}
if($.browser.msie && (parseInt($.browser.version) < 7)) {
if(o.orientation === "vertical") {
resizableHandle.height(element.height());
}
}
};
wijsplitter.prototype._adjustLayout = function (self) {
var o = self.options, fields = self._fields, panel1 = fields.panel1, distance = o.orientation === "vertical" ? panel1.n.width() : panel1.n.height();
if(o.splitterDistance === distance) {
return;
}
o.splitterDistance = distance;
self._updateElements();
};
wijsplitter.prototype._setPanelsScrollMode = function () {
var self = this, fields = self._fields, o = self.options, pnlScrollBars = [
o.panel1.scrollBars,
o.panel2.scrollBars
];
$.each([
fields.panel1,
fields.panel2
], function (idx, pnl) {
if(pnlScrollBars[idx] === "auto") {
pnl.content.css("overflow", "auto");
} else if(pnlScrollBars[idx] === "both") {
pnl.content.css("overflow", "scroll");
} else if(pnlScrollBars[idx] === "none") {
pnl.content.css("overflow", "hidden");
} else if(pnlScrollBars[idx] === "horizontal") {
pnl.content.css("overflow-x", "scroll").css("overflow-y", "hidden");
} else if(pnlScrollBars[idx] === "vertical") {
pnl.content.css("overflow-x", "hidden").css("overflow-y", "scroll");
}
});
};
return wijsplitter;
})(wijmo.wijmoWidget);
splitter.wijsplitter = wijsplitter;
var wijsplitter_options = (function () {
function wijsplitter_options() {
/** @ignore
* Selector option for auto self initialization.
* This option is internal.
*/
this.initSelector = ":jqmData(role='wijsplitter')";
/** Gets or sets the javascript function name that
* would be called at the client side when a user is dragging the splitter.
* @example
* Supply a callback function to handle the sizing event:
* $("#element").wijsplitter({ sizing: function () { } });
* Bind to the event by type:
* $("#element").bind("wijsplittersizing", function () { });
* @event
*/
this.sizing = null;
/** Gets or sets the javascript function name that
* would be called at the client side when the user is done dragging the splitter.
* @example
* Supply a callback function to handle the sized event:
* $("#element").wijsplitter({ sized: function () { } });
* Bind to the event by type:
* $("#element").bind("wijsplittersized", function () { });
* @event
*/
this.sized = null;
/** Gets or sets the javascript function name to be called before panel1 is expanded.
* @example
* Supply a callback function to handle the expand event:
* $("#element").wijsplitter({ expand: function () { return false; } });
* Bind to the event by type:
* $("#element").bind("wijsplitterexpand", function () { return false; });
* @event
*/
this.expand = null;
/** Gets or sets the javascript function name to be called before panel1 is collapsed.
* @example
* Supply a callback function to handle the collapse event:
* $("#element").wijsplitter({ collapse: function () { return false; } });
* Bind to the event by type:
* $("#element").bind("wijsplittercollapse", function () { return false; });
* @event
*/
this.collapse = null;
/** Gets or sets the javascript function name to be called when panel1 is expanded by clicking the collapse/expand image.
* @example
* Supply a callback function to handle the expanded event:
* $("#element").wijsplitter({ expanded: function () { } });
* Bind to the event by type:
* $("#element").bind("wijsplitterexpanded", function () { });
* @event
*/
this.expanded = null;
/** Gets or sets the javascript function name to be called when panel1 is collapsed by clicking the collapse/expand image.
* @example
* Supply a callback function to handle the collapsed event:
* $("#element").wijsplitter({ collapsed: function () { } });
* Bind to the event by type:
* $("#element").bind("wijsplittercollapsed", function () { });
* @event
*/
this.collapsed = null;
/** A value that indicates the z-index (stack order) of the splitter bar.
* @type {number}
*/
this.barZIndex = -1;
/** A Boolean value that determines whether the expander of the wijsplitter widget is shown.
* is allowed to be shown.
* @type {boolean}
*/
this.showExpander = true;
/** Gets or sets the location of the splitter, in pixels, from the left or top edge of the SplitContainer.
* @type {number}
*/
this.splitterDistance = 100;
/** Gets or sets a value indicating the horizontal or vertical orientation of the SplitContainer panels
* of the splitter panels.
* @type {string}
*/
this.orientation = 'vertical';
/** Gets or sets a value that indicates whether the widget fills the whole page.
* @type {boolean}
*/
this.fullSplit = false;
/** Defines the animation while the bar of the splitter is being dragged.
* @type {object}
*/
this.resizeSettings = {
animationOptions: {
duration: /** Defines how long ( in milliseconds) the sliding animation will run.
* @type {number}
*/
100,
easing: /** The easing effect that is applied to the animation.
* @type {string}
*/
"swing",
disabled: /** Determines whether use the animation.
* @type {boolean}
*/
false
},
ghost: /** Gets or sets a value that determines whether an outline of a panel appears while dragging the splitter bar.
* the element is sized.
* @type {boolean}
*/
false
};
/** Defines the information for the top or left panel of the splitter.
* @type {object}
*/
this.panel1 = {
minSize: 1,
collapsed: false,
scrollBars: "auto"
};
/** Defines the information for the bottom or right panel of the splitter.
* @type {object}
*/
this.panel2 = {
minSize: 1,
collapsed: false,
scrollBars: "auto"
};
/** Specifies which panel should be collapsed after clicking the expander of the splitter. Possible values are "panel1" and "panel2".
* @example
* $('.selector' ).wijsplitter({collapsingPanel: "panel1"});
* @type {string}
*/
this.collapsingPanel = "panel1";
/** @ignore
* All CSS classes used in widgets.
*/
this.wijCSS = {
cornerCssPrefix: "ui-corner-",
arrowCssPrefix: "ui-icon-triangle-1-",
panelCss: {
panel1: {
n: "panel1",
content: "panel1-content"
},
panel2: {
n: "panel2",
content: "panel2-content"
}
},
wrapperCss: "wijmo-wijsplitter-wrapper",
hSplitterCss: "wijmo-wijsplitter-horizontal",
vSplitterCss: "wijmo-wijsplitter-vertical",
hSplitterCssPrefix: "wijmo-wijsplitter-h-",
vSplitterCssPrefix: "wijmo-wijsplitter-v-",
collapsedCss: "collapsed",
expandedCss: "expanded",
resizeHelperCss: "resize-helper",
barCss: "bar",
expanderCss: "expander"
};
/** @ignore
* wijMobileCSS.
*/
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body ui-body-c",
stateDefault: "ui-btn-up-c"
};
}
return wijsplitter_options;
})();
wijsplitter.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijsplitter_options());
$.wijmo.registerWidget("wijsplitter", wijsplitter.prototype);
if($.ui != null && $.ui.plugin != null) {
$.ui.plugin.add("resizable", "wijanimate", {
stop: function (event, ui) {
var self = $(this).data("uiResizable"), o = self.options, element = self.element, pr = self._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && $.ui.hasScroll(pr[0], 'left') ? 0 : self.sizeDiff.height, soffsetw = ista ? 0 : self.sizeDiff.width, style, left, top;
element.css("width", self.originalSize.width).css("height", self.originalSize.height);
style = {
width: (self.size.width - soffsetw),
height: (self.size.height - soffseth)
};
left = (parseInt(element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null;
top = (parseInt(element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;
element.animate($.extend(style, top && left ? {
top: top,
left: left
} : {
}), {
duration: o.animateDuration,
easing: o.animateEasing,
step: function () {
var data = {
width: parseInt(element.css('width'), 10),
height: parseInt(element.css('height'), 10),
top: parseInt(element.css('top'), 10),
left: parseInt(element.css('left'), 10)
};
if(pr && pr.length) {
$(pr[0]).css({
width: data.width,
height: data.height
});
}
// propagating resize, and updating values for each animation step
self._updateCache(data);
self._propagate("resize", event);
element.trigger("animating");
},
complete: function () {
element.trigger("animated");
}
});
}
});
}
})(wijmo.splitter || (wijmo.splitter = {}));
var splitter = wijmo.splitter;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts"/>
/*globals setTimeout jQuery*/
/*
* Wijmo ProgressBar Widget
*
* Depends:
* Jquery-1.4.2.js
* jquery.ui.core.js
* jquery.ui.widget.js
*
*Optional dependence for effect settings:
* jquery.effects.core.js
* jquery.effects.blind.js
* jquery.effects.bounce.js
* jquery.effects.clip.js
* jquery.effects.drop.js
* jquery.effects.explode.js
* jquery.effects.fold.js
* jquery.effects.hightlight.js
* jquery.effects.pulsate.js
* jquery.effects.scale.js
* jquery.effects.shake.js
* jquery.effects.slide.js
* jquery.effects.transfer.js
* HTML:
* <div id="progressbar" style="width:***;height:***"></div>
*/
(function (progressbar) {
"use strict";
var $ = jQuery;
var wijpbCss = "wijmo-wijprogressbar", pbCss = "ui-progressbar", pbLabelCss = pbCss + "-label", lblAlignPrefixCss = wijpbCss + "-lb-", cornerPrefixCss = "ui-corner-", cornerLeftCss = cornerPrefixCss + "left", cornerRightCss = cornerPrefixCss + "right", cornerTopCss = cornerPrefixCss + "top", cornerBottomCss = cornerPrefixCss + "bottom";
/** @ignore */
var JQueryUIProgress = (function (_super) {
__extends(JQueryUIProgress, _super);
function JQueryUIProgress() {
_super.apply(this, arguments);
}
JQueryUIProgress.prototype._create = function () {
return $.ui.progressbar.prototype._create.apply(this, arguments);
};
JQueryUIProgress.prototype._destroy = function () {
return $.ui.progressbar.prototype._destroy.apply(this, arguments);
};
JQueryUIProgress.prototype._setOptions = function () {
return $.ui.progressbar.prototype._setOptions.apply(this, arguments);
};
JQueryUIProgress.prototype._setOption = function (key, value) {
return $.ui.progressbar.prototype._setOption.apply(this, arguments);
};
JQueryUIProgress.prototype._constrainedValue = function (value) {
return $.ui.progressbar.prototype._constrainedValue.apply(this, arguments);
};
JQueryUIProgress.prototype.value = function (newValue) {
return $.ui.progressbar.prototype.value.apply(this, arguments);
};
JQueryUIProgress.prototype._percentage = function () {
return $.ui.progressbar.prototype._percentage.apply(this, arguments);
};
JQueryUIProgress.prototype._refreshValue = function (value) {
return $.ui.progressbar.prototype._refreshValue.apply(this, arguments);
};
return JQueryUIProgress;
})(wijmo.JQueryUIWidget);
progressbar.JQueryUIProgress = JQueryUIProgress;
var wijprogressbar_options = (function () {
function wijprogressbar_options() {
/** The label's alignment on the progress bar. The value should be "east",
* "west", "center", "north", "south" or "running".
*/
this.labelAlign = "center";
/**The value of the progress bar,the type should be numeric.
*/
this.maxValue = 100;
/**The minimum value of the progress bar,the type should be numeric.
*/
this.minValue = 0;
/**The fill direction of the progress bar.the value should be "east",
*"west", "north" or "south".
*/
this.fillDirection = "east";
/**Sets the format of the label text.
* @remarks
* The available formats are as follows:
*{0} or {ProgressValue} express the current progress Value.
*{1} or {PercentProgress} express the current percent of the progress bar.
*{2} or {RemainingProgress} express the remaining progress of the
*progress bar.
*{3} or {PercentageRemaining} express the remaining percent of
*the progress bar.
*{4} or {Min} express the min Vlaue of the progress bar.
*{5} or {Max} express the max Value of the progress bar.
*/
this.labelFormatString = "{1}%";
/**Set the format of the ToolTip of the progress bar,the expression of the
* format like the labelFormatString.
*,'{1}%').
*/
this.toolTipFormatString = "{1}%";
/**The increment of the progress bar's indicator.
*/
this.indicatorIncrement = 1;
/**The Url of the image's indicator.
*/
this.indicatorImage = "";
/**Gets or sets the delay time of the progress bar's animation in milliseconds. The default value of this option is "0".
*/
this.animationDelay = 0;
/**The options parameter of the jQuery's animation.
* @type {object}
*/
this.animationOptions = {
disabled: false,
easing: null,
duration: 500
};
/** Fire upon running the progress. The parameter is an object: {oldValue:xxx,newValue:xxx}. Returning "false" will stop the progress.
* Return false to cancel the event.
* @event
* @dataKey {number} oldValue The old value of the progressbar.
* @dataKey {number} newValue The new value of the progressbar.
*/
this.progressChanging = null;
/** Fires before running the progress. The parameters are an object: {oldValue:xxx,newValue:xxx}. Returning "false" prevents the running progress.
* @event
* @dataKey {number} oldValue The old value of the progressbar.
* @dataKey {number} newValue The new value of the progressbar.
* @return {boolean} return false to cancel the event.
*/
this.beforeProgressChanging = null;
/** Fires when the progress changes. The parameter is an object: {oldValue:xxx,newValue:xxx}.
* @event
* @dataKey {number} oldValue The old value of the progressbar.
* @dataKey {number} newValue The new value of the progressbar.
*/
this.progressChanged = null;
/** The value of the progressbar.*/
this.value = 0;
}
return wijprogressbar_options;
})();
/** @widget
* @extends jQuery.ui.progressbar
*/
var wijprogressbar = (function (_super) {
__extends(wijprogressbar, _super);
function wijprogressbar() {
_super.apply(this, arguments);
}
wijprogressbar.prototype._setOption = function (key, value) {
var self = this, o = self.options, val;
switch(key) {
case "value":
o[key] = parseInt(value, 10);
self._refreshValue();
return;
case "maxValue":
o.max = value;
case "minValue":
val = parseInt(value, 10);
o[key] = val;
self[key === "maxValue" ? "max" : "min"] = val;
self._refreshValue(true);
return;
case "labelFormatString":
case "toolTipFormatString":
o[key] = value;
self._refreshValue(true);
return;
case "fillDirection":
case "labelAlign":
case "indicatorImage":
o[key] = value;
self._updateElementsCss();
return;
default:
break;
}
$.Widget.prototype._setOption.apply(self, arguments);
//Add for support disabled option at 2011/7/8
if(key === "disabled") {
self._handleDisabledOption(value, self.element);
}
//end for disabled option
};
wijprogressbar.prototype._create = function () {
var self = this, o = self.options, element = self.element;
// enable touch support:
//if (window.wijmoApplyWijTouchUtilEvents) {
// $ = window.wijmoApplyWijTouchUtilEvents($);
//}
self.directions = {
east: "left",
west: "right",
north: "bottom",
south: "top"
};
self.min = o.minValue;
//self.max = o.maxValue;
self.max = o.max = o.maxValue//fixed bug when jui update to 1.8.18
;
element.addClass(wijpbCss);
//$.ui.progressbar.prototype._create.apply(self, arguments);
_super.prototype._create.call(this);
self.label = $("<span>").addClass(pbLabelCss).appendTo(element);
self._updateElementsCss();
self._isInit = true;
//Add for support disabled option
if(o.disabled) {
self.disable();
}
//end for disabled option
self._refreshValue();
};
wijprogressbar.prototype._handleDisabledOption = function (disabled, ele) {
var self = this;
if(disabled) {
if(!self.disabledDiv) {
self.disabledDiv = self._createDisabledDiv(ele);
}
self.disabledDiv.appendTo("body");
} else {
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
}
};
wijprogressbar.prototype._createDisabledDiv = function (outerEle) {
var self = this, ele = //Change your outerelement here
outerEle ? outerEle : self.element, eleOffset = ele.offset(), disabledWidth = ele.outerWidth(), disabledHeight = ele.outerHeight(), css = {
"z-index": "99999",
position: "absolute",
width: disabledWidth,
height: disabledHeight,
left: eleOffset.left,
top: eleOffset.top
};
if($.browser.msie) {
$.extend(css, {
"background-color": "#fff",
opacity: 0.1
});
}
return $("<div></div>").addClass("ui-disabled").css(css);
};
wijprogressbar.prototype._triggerEvent = function (eventName, oldValue, newValue, isFireEvent) {
if(!isFireEvent) {
return;
}
return this._trigger(eventName, null, {
oldValue: oldValue,
newValue: newValue
}) === false;
};
wijprogressbar.prototype._refreshValue = function (forced) {
var self = this, o = self.options, isFireEvent, animationOptions = o.animationOptions, indicatorIncrement = o.indicatorIncrement, element = self.element, value, percent, oldValue;
if(!self._isInit) {
return;
}
oldValue = element.attr("aria-valuenow");
value = self.value();
percent = (value - self.min) / (self.max - self.min) * 100;
isFireEvent = parseInt(oldValue) != value;
if(self._triggerEvent("beforeProgressChanging", oldValue, value, isFireEvent)) {
return;
}
if(!animationOptions.disabled && animationOptions.duration > 0) {
setTimeout(function () {
$.wijmo.wijprogressbar.animations.progress({
content: self.valueDiv,
complete: function () {
if(indicatorIncrement !== 1) {
self._refreshProgress(percent, value, isFireEvent);
if(o.labelAlign === "running") {
self._updateRunningLabelCss(percent);
}
}
self._triggerEvent("progressChanged", oldValue, value, isFireEvent);
self._lastStep = percent;
},
step: function (ovalue) {
self._performAnimating(ovalue, forced, isFireEvent);
},
progressValue: value * 100
}, animationOptions);
}, o.animationDelay);
} else {
self._refreshProgress(Math.round(percent));
if(o.labelAlign === "running") {
self._updateRunningLabelCss(percent);
}
self._lastStep = percent;
self._triggerEvent("progressChanged", oldValue, value, isFireEvent);
}
};
wijprogressbar.prototype._refreshProgress = function (percent, curValue, isFireEvent) {
var self = this, o = self.options, fillDirection = o.fillDirection, element = self.element;
if(curValue === undefined) {
curValue = $.wijmo.wijprogressbar.mul(percent, (self.max - self.min)) / 100 + self.min;
}
if(self._triggerEvent("progressChanging", element.attr("aria-valuenow"), curValue, isFireEvent)) {
return;
}
if(self._isHorizontal()) {
self.valueDiv.toggleClass(fillDirection === "east" ? cornerRightCss : cornerLeftCss, curValue === self.max).width(percent + "%");
} else {
self.valueDiv.toggleClass(fillDirection === "south" ? cornerBottomCss : cornerTopCss, curValue === self.max).height(percent + "%");
}
self.label.html(self._getFormatString(o.labelFormatString, percent, curValue));
element.attr("aria-valuenow", curValue).attr("title", self._getFormatString(o.toolTipFormatString, percent, curValue));
};
wijprogressbar.prototype._isHorizontal = function () {
var fillDirection = this.options.fillDirection;
return fillDirection === "west" || fillDirection === "east";
};
wijprogressbar.prototype._getRotateTextOffset = function (label) {
var width, height;
label.css("width", "auto");
width = label.outerWidth();
height = label.outerHeight();
label.css("width", "");
return Math.max(width - height - 4, 0);
};
wijprogressbar.prototype._updateElementsCss = function () {
var self = this, o = self.options, element = self.element, fillDirection = o.fillDirection;
element.removeClass(wijpbCss + "-west " + wijpbCss + "-east " + wijpbCss + "-north " + wijpbCss + "-south").addClass(wijpbCss + "-" + fillDirection);
//pb progress
self._updateProgressCss();
//pb label
self._updateLabelCss();
};
wijprogressbar.prototype._updateLabelCss = function () {
var self = this, o = self.options, element = self.element, labelAlign = o.labelAlign, label = self.label, lastStep = self._lastStep, height = element.height();
label.removeClass(lblAlignPrefixCss + "west " + lblAlignPrefixCss + "east " + lblAlignPrefixCss + "south " + lblAlignPrefixCss + "north " + lblAlignPrefixCss + "center " + lblAlignPrefixCss + "running").addClass(lblAlignPrefixCss + labelAlign).css({
left: "",
right: "",
top: "",
bottom: "",
width: "",
"text-align": "",
"line-height": ""
});
if(labelAlign !== "north" && labelAlign !== "south" && !(labelAlign === "running" && !self._isHorizontal())) {
label.css("line-height", height + "px");
}
if(labelAlign === "running") {
self._updateRunningLabelCss(lastStep);
} else if(!self._isHorizontal() && !$.browser.msie) {
//Add comments by RyanWu@20110325.
//Because nonIE brownser will rotate the text,
//I use a hack to set the text-align:right and
//width:100%, then rotate it to the north.
if(labelAlign === "north") {
label.css("width", "100%").css("text-align", "right");
} else if(labelAlign === "south") {
label.css("width", "100%").css("text-align", "left");
}
//end by RyanWu@20110325.
}
};
wijprogressbar.prototype._updateRunningLabelCss = function (step) {
var self = this, o = self.options, fillDirection = o.fillDirection, element = self.element, label = self.label, valueDiv = self.valueDiv, isHorizontal = self._isHorizontal(), pbLen, lblLen, pgLen, pos;
pbLen = element[isHorizontal ? "width" : "height"]();
lblLen = label[isHorizontal ? "outerWidth" : "outerHeight"]();
pgLen = valueDiv[isHorizontal ? "outerWidth" : "outerHeight"]();
//TODO:
//Because the text will be rotated, we need calculate
//the correct lengh of the rotated text.
if(!isHorizontal && !$.browser.msie) {
lblLen += self._getRotateTextOffset(label);
}
pos = pbLen === pgLen ? pbLen - lblLen : step * pbLen / 100 - lblLen + lblLen * (pbLen - pgLen) / pbLen;
label.css(self.directions[fillDirection], pos);
};
wijprogressbar.prototype._updateProgressCss = function () {
var self = this, o = self.options, fillDirection = o.fillDirection, indicatorImage = o.indicatorImage, valueDiv = self.valueDiv, lastStep = self._lastStep;
if(indicatorImage !== "") {
valueDiv.css("background", "transparent url(" + indicatorImage + ") repeat fixed");
}
valueDiv.removeClass(cornerLeftCss + " " + cornerRightCss + " " + cornerTopCss + " " + cornerBottomCss).addClass(cornerPrefixCss + self.directions[fillDirection]);
if(typeof lastStep === "number") {
if(self._isHorizontal()) {
valueDiv.css("width", lastStep + "%").css("height", "");
} else {
valueDiv.css("height", lastStep + "%").css("width", "");
}
} else {
valueDiv.css({
width: "",
height: ""
});
}
};
wijprogressbar.prototype._performAnimating = function (step, forced, isFireEvent) {
var self = this, o = self.options, indicatorIncrement = o.indicatorIncrement, curValue = step / 100, percent = $.wijmo.wijprogressbar.div((curValue - self.min), (self.max - self.min)) * 100, ln = 0, arrP, base, resultPrecision = 2;
if(indicatorIncrement) {
//arrP = percent.toString().split(".");
//if (arrP.length === 2) {
// ln = arrP[1].length;
// resultPrecision = ln;
//}
//base = Math.pow(10, ln);
if(indicatorIncrement !== 1) {
percent = Math.floor(percent / indicatorIncrement) * indicatorIncrement;
} else {
percent = Math.round(percent);
resultPrecision = 0;
}
self.pointNumber = ln;
if(self._lastStep === percent && !forced) {
return;
}
}
//self._lastStep = percent;
self._refreshProgress(Number(percent.toFixed(resultPrecision)), Number(curValue.toFixed(resultPrecision)), isFireEvent);
if(o.labelAlign === "running") {
self._updateRunningLabelCss(percent);
}
};
wijprogressbar.prototype._getFormatString = function (format, percent, value) {
var self = this, remainingProgress = self.max - value, percentageRemaining = 100 - percent, r = /\{0\}/g;
format = format.replace(r, value.toString());
r = /\{ProgressValue\}/g;
format = format.replace(r, value.toString());
r = /\{1\}/g;
format = format.replace(r, percent.toString());
r = /\{PercentProgress\}/g;
format = format.replace(r, percent.toString());
r = /\{2\}/g;
format = format.replace(r, remainingProgress.toString());
r = /\{RemainingProgress\}/g;
format = format.replace(r, remainingProgress.toString());
r = /\{3\}/g;
format = format.replace(r, percentageRemaining.toString());
r = /\{PercentageRemaining\}/g;
format = format.replace(r, percentageRemaining.toString());
r = /\{4\}/g;
format = format.replace(r, self.min);
r = /\{Min\}/g;
format = format.replace(r, self.min);
r = /\{5\}/g;
format = format.replace(r, self.max);
r = /\{Max\}/g;
format = format.replace(r, self.max);
return format;
};
wijprogressbar.prototype.value = /** Sets the current value of the progressbar.
* @param {?number} newValue The value to set.
*/
function (newValue) {
return $.ui.progressbar.prototype.value.apply(this, arguments);
};
wijprogressbar.prototype.destroy = /**
*Removes the wijprogressbar functionality completely. This returns the element to its pre-init state.
*/
function () {
var self = this, element = self.element;
element.attr("title", "").removeClass(wijpbCss + " " + wijpbCss + "-east " + wijpbCss + "-west " + wijpbCss + "-north " + wijpbCss + "-south");
if(self.label) {
self.label.remove();
}
//Add for support disabled option at 2011/7/8
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
//end for disabled option
$.ui.progressbar.prototype.destroy.apply(this, arguments);
};
return wijprogressbar;
})(JQueryUIProgress);
progressbar.wijprogressbar = wijprogressbar;
if($.ui && $.ui.progressbar) {
wijprogressbar.prototype.options = $.extend(true, {
}, $.ui.progressbar.prototype.options, new wijprogressbar_options());
$.wijmo.registerWidget("wijprogressbar", $.ui.progressbar, wijprogressbar.prototype);
$.extend($.wijmo.wijprogressbar, {
animations: {
progress: function (options, additions) {
options = $.extend({
easing: "swing",
duration: 1000
}, options, additions);
options.content.stop(true, true).animate({
pgvalue: //Because jquery's animation needs an
//attribute or css style to do the animation,
//here we use a temporary attribute to
//do the animation on the value div element.
options.progressValue
}, options);
}
},
add: function (arg1, arg2) {
var r1 = 0, r2 = 0, m;
try {
r1 = arg1.toString().split(".")[1].length;
} catch (e) {
}
try {
r2 = arg2.toString().split(".")[1].length;
} catch (e1) {
}
m = Math.pow(10, Math.max(r1, r2));
return (arg1 * m + arg2 * m) / m;
},
mul: function (arg1, arg2) {
var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
try {
m += s1.split(".")[1].length;
} catch (e) {
}
try {
m += s2.split(".")[1].length;
} catch (e1) {
}
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
},
div: function (arg1, arg2) {
var t1 = 0, t2 = 0, r1, r2;
try {
t1 = arg1.toString().split(".")[1].length;
} catch (e) {
}
try {
t2 = arg2.toString().split(".")[1].length;
} catch (e1) {
}
r1 = Number(arg1.toString().replace(".", ""));
r2 = Number(arg2.toString().replace(".", ""));
return (r1 / r2) * Math.pow(10, t2 - t1);
}
});
}
})(wijmo.progressbar || (wijmo.progressbar = {}));
var progressbar = wijmo.progressbar;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts"/>
/*globals window,document,jQuery*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.resizable.js
* jquery.ui.mouse.js
* jquery.wijmo.wijutil.js
*
*/
(function (dialog) {
"use strict";
var $ = jQuery, widgetName = "wijdialog", uiStateHover = "ui-state-hover", zonCSS = "wijmo-wijdialog-defaultdockingzone";
/** @ignore */
var JQueryUIDialog = (function (_super) {
__extends(JQueryUIDialog, _super);
function JQueryUIDialog() {
_super.apply(this, arguments);
}
JQueryUIDialog.prototype._create = function () {
return $.ui.dialog.prototype._create.apply(this, arguments);
};
JQueryUIDialog.prototype._init = function () {
return $.ui.dialog.prototype._init.apply(this, arguments);
};
JQueryUIDialog.prototype._destroy = function () {
return $.ui.dialog.prototype._destroy.apply(this, arguments);
};
JQueryUIDialog.prototype._appendTo = function () {
return $.ui.dialog.prototype._appendTo.apply(this, arguments);
};
JQueryUIDialog.prototype._setOptions = function () {
return $.ui.dialog.prototype._setOptions.apply(this, arguments);
};
JQueryUIDialog.prototype._setOption = function (key, value) {
return $.ui.dialog.prototype._setOption.apply(this, arguments);
};
JQueryUIDialog.prototype.widget = /** Returns a jQuery object containing the generated wrapper. */
function () {
return $.ui.dialog.prototype.widget.apply(this, arguments);
};
JQueryUIDialog.prototype.close = /** Closes the dialog. */
function () {
return $.ui.dialog.prototype.close.apply(this, arguments);
};
JQueryUIDialog.prototype.isOpen = /** Whether the dialog is currently open. */
function () {
return $.ui.dialog.prototype.isOpen.apply(this, arguments);
};
JQueryUIDialog.prototype.moveToTop = /** Moves the dialog to the top of the dialog stack. */
function () {
return $.ui.dialog.prototype.moveToTop.apply(this, arguments);
};
JQueryUIDialog.prototype._moveToTop = function () {
return $.ui.dialog.prototype._moveToTop.apply(this, arguments);
};
JQueryUIDialog.prototype.open = /** Opens the dialog. */
function () {
return $.ui.dialog.prototype.open.apply(this, arguments);
};
JQueryUIDialog.prototype._focusTabbable = function () {
return $.ui.dialog.prototype._focusTabbable.apply(this, arguments);
};
JQueryUIDialog.prototype._keepFocus = function () {
return $.ui.dialog.prototype._keepFocus.apply(this, arguments);
};
JQueryUIDialog.prototype._createWrapper = function () {
return $.ui.dialog.prototype._createWrapper.apply(this, arguments);
};
JQueryUIDialog.prototype._createTitlebar = function () {
return $.ui.dialog.prototype._createTitlebar.apply(this, arguments);
};
JQueryUIDialog.prototype._title = function () {
return $.ui.dialog.prototype._title.apply(this, arguments);
};
JQueryUIDialog.prototype._createButtonPane = function () {
return $.ui.dialog.prototype._createButtonPane.apply(this, arguments);
};
JQueryUIDialog.prototype._createButtons = function () {
return $.ui.dialog.prototype._createButtons.apply(this, arguments);
};
JQueryUIDialog.prototype._makeDraggable = function () {
return $.ui.dialog.prototype._makeDraggable.apply(this, arguments);
};
JQueryUIDialog.prototype._makeResizable = function () {
return $.ui.dialog.prototype._makeResizable.apply(this, arguments);
};
JQueryUIDialog.prototype._minHeight = function () {
return $.ui.dialog.prototype._minHeight.apply(this, arguments);
};
JQueryUIDialog.prototype._position = function () {
return $.ui.dialog.prototype._position.apply(this, arguments);
};
JQueryUIDialog.prototype._size = function () {
return $.ui.dialog.prototype._size.apply(this, arguments);
};
JQueryUIDialog.prototype._blockFrames = function () {
return $.ui.dialog.prototype._blockFrames.apply(this, arguments);
};
JQueryUIDialog.prototype._unblockFrames = function () {
return $.ui.dialog.prototype._unblockFrames.apply(this, arguments);
};
JQueryUIDialog.prototype._createOverlay = function () {
if(!this.options.modal) {
return;
}
var self = this;
if(!$.ui.dialog.overlayInstances) {
// Prevent use of anchors and inputs.
// We use a delay in case the overlay is created from an
// event that we're going to be cancelling. (#2804)
this._delay(function () {
// Handle .dialog().dialog("close") (#4065)
if($.ui.dialog.overlayInstances) {
this.document.bind("focusin.dialog", function (event) {
if(!$(event.target).closest(".ui-dialog").length && // TODO: Remove hack when datepicker implements
// the .ui-front logic (#8989)
!$(event.target).closest(".ui-datepicker").length) {
event.preventDefault();
if(event.relatedTarget && $(event.relatedTarget).closest(".ui-dialog").length) {
return;
}
var dialogEle = $(".ui-dialog:visible:last .ui-dialog-content"), dialogObj;
if(dialogEle.data("wijmoWijdialog")) {
dialogObj = dialogEle.data("wijmoWijdialog");
} else {
dialogObj = dialogEle.data("wijmoC1dialog");
}
if(dialogObj) {
dialogObj._focusTabbable();
}
}
});
}
});
}
this.overlay = $("<div>").addClass("ui-widget-overlay ui-front ui-dialog-overlay").appendTo(this._appendTo());
this._on(this.overlay, {
mousedown: "_keepFocus"
});
$.ui.dialog.overlayInstances++;
};
JQueryUIDialog.prototype._destroyOverlay = function () {
return $.ui.dialog.prototype._destroyOverlay.apply(this, arguments);
};
return JQueryUIDialog;
})(wijmo.JQueryUIWidget);
dialog.JQueryUIDialog = JQueryUIDialog;
var wijdialog_options = (function () {
function wijdialog_options() {
/**
* Which element the dialog (and overlay, if modal) should be appended to.
*/
this.appendTo = "body";
/**
* If set to true, the dialog will automatically open upon initialization. If false, the dialog will stay hidden until the open() method is called.
*/
this.autoOpen = true;
/**
* Specifies which buttons should be displayed on the dialog. The context of the callback is the dialog element; if you need access to the button, it is available as the target of the event object.
* @type {obejct|array}
*/
this.buttons = [];
/**
* Specifies whether the dialog should close when it has focus and the user presses the esacpe (ESC) key.
*/
this.closeOnEscape = true;
/**
* Specifies the text for the close button. Note that the close text is visibly hidden when using a standard theme.
*/
this.closeText = "close";
/**
* The specified class name(s) will be added to the dialog, for additional theming.
*/
this.dialogClass = "";
/**
* If set to true, the dialog will be draggable by the title bar. Requires the jQuery UI Draggable widget to be included.
*/
this.draggable = true;
/**
* The height of the dialog.
* @type {number|string}
*/
this.height = "auto";
/**
* If and how to animate the hiding of the dialog.
* @type {number|string|object}
* @remarks
* Multiple types supported:
* Number: The dialog will fade out while animating the height and width for the specified duration.
* tring: The dialog will be hidden using the specified jQuery UI effect. See the list of effects for possible values.
* Object: If the value is an object, then effect, delay, duration, and easing properties may be provided. The effect property must be the name of a jQuery UI effect. When using a jQuery UI effect that supports additional settings, you may include those settings in the object and they will be passed to the effect. If duration or easing is omitted, then the default values will be used. If delay is omitted, then no delay is used.
*/
this.hide = null;
/**
* The maximum height to which the dialog can be resized, in pixels.
* @type {number}
*/
this.maxHeight = null;
/**
* The maximum width to which the dialog can be resized, in pixels.
* @type {number}
*/
this.maxWidth = null;
/**
* The minimum height to which the dialog can be resized, in pixels.
*/
this.minHeight = 150;
/**
* The minimum width to which the dialog can be resized, in pixels.
*/
this.minWidth = 150;
/**
* If set to true, the dialog will have modal behavior; other items on the page will be disabled, i.e., cannot be interacted with. Modal dialogs create an overlay below the dialog but above other page elements.
*/
this.modal = false;
/**
* Specifies where the dialog should be displayed. The dialog will handle collisions such that as much of the dialog is visible as possible.
* @type {string|array|object}
* @remarks
* Multiple types supported:
* Object: Identifies the position of the dialog when opened. The of option defaults to the window, but you can specify another element to position against. You can refer to the jQuery UI Position utility for more details about the various options.
* String: A string representing the position within the viewport. Possible values: "center", "left", "right", "top", "bottom".
* Array: An array containing an x, y coordinate pair in pixel offset from the top left corner of the viewport or the name of a possible string value.
*/
this.position = {
my: "center",
at: "center",
of: window
};/**
* If set to true, the dialog will be resizable. Requires the jQuery UI Resizable widget to be included.
*/
this.resizable = true;
/**
* If and how to animate the showing of the dialog.
* @type {number|string|object}
* @remarks
* Number: The dialog will fade in while animating the height and width for the specified duration.
* String: The dialog will be shown using the specified jQuery UI effect. See the list of effects for possible values.
* Object: If the value is an object, then effect, delay, duration, and easing properties may be provided. The effect property must be the name of a jQuery UI effect. When using a jQuery UI effect that supports additional settings, you may include those settings in the object and they will be passed to the effect. If duration or easing is omitted, then the default values will be used. If delay is omitted, then no delay is used.
*/
this.show = null;
/**
* Specifies the title of the dialog. If the value is null, the title attribute on the dialog source element will be used.
* @type {string}
*/
this.title = null;
/**
* The width of the dialog, in pixels.
*/
this.width = 300;
/*
* Specifies whether the dialog will stack on top of other dialogs.
* This will cause the dialog to move to the front of other dialogs when it gains focus.
*/
this.stack = true;
/**
* Triggered when a dialog is about to close. If canceled, the dialog will not close.
* @event
* @param {jQuery.Event} e Standard jQuery event object
*/
this.beforeClose = null;
/**
* Triggered when the dialog is closed.
* @event
* @param {jQuery.Event} e Standard jQuery event object
*/
this.close = null;
/**
* Triggered when the dialog is created.
* @event
* @param {jQuery.Event} e Standard jQuery event object
*/
this.create = null;
/**
* Triggered while the dialog is being dragged.
* @event
* @param {jQuery.Event} e Standard jQuery event object
*/
this.drag = null;
/**
* Triggered when the user starts dragging the dialog.
* @event
* @param {jQuery.Event} e Standard jQuery event object
*/
this.dragStart = null;
/**
* Triggered after the dialog has been dragged.
* @event
* @param {jQuery.Event} e Standard jQuery event object
*/
this.dragStop = null;
/**
* Triggered when the dialog gains focus.
* @event
* @param {jQuery.Event} e Standard jQuery event object
*/
this.focus = null;
/**
* Triggered when the dialog is opened.
* @event
* @param {jQuery.Event} e Standard jQuery event object
*/
this.open = null;
/**
* Triggered while the dialog is being resized.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {ResizeEventArgs} ui Information about an event.
*/
this.resize = null;
/**
* Triggered when the user starts resizing the dialog.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {ResizeEventArgs} ui Information about an event.
*/
this.resizeStart = null;
/**
* Triggered after the dialog has been resized.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {ResizeEventArgs} ui Information about an event.
*/
this.resizeStop = null;
/** This option specifies the starting z-index for the dialog.
* @example
* $("selector").wijdialog({zIndex: 2000});
*/
this.zIndex = 1000;
/** Selector option for auto self initialization.
* This option is internal.
* @ignore
*/
this.initSelector = "";
/** The captionButtons option determines the caption buttons to show on the wijdialog title bar.
* @type {object}
* @remarks
* The default value for this option is:
* {
* pin: {visible: true, click: self.pin,
* iconClassOn: "ui-icon-pin-w", iconClassOff:"ui-icon-pin-s"},
* refresh: {visible: true, click: self.refresh,
* iconClassOn: "ui-icon-refresh"},
* toggle: {visible: true, click: self.toggle},
* minimize: {visible: true, click: self.minimize,
* iconClassOn: "ui-icon-minus"},
* maximize: {visible: true, click: self.maximize,
* iconClassOn: "ui-icon-extlink"},
* close: {visible: true, click: self.close,
* iconClassOn: "ui-icon-close"}
* };
* Each button is represented by an object in this object.
* property name: The name of the button.
* visible: A value specifies whether this button is visible.
* click: The event handler to handle the click event of this button.
* iconClassOn: Icon for normal state.
* iconClassOff: Icon after clicking.
* @example
* $("selector").wijdialog({captionButtons: {
* pin: { visible: false },
* refresh: { visible: false },
* toggle: { visible: false },
* minimize: { visible: false },
* maximize: { visible: false }
* }
* });
*/
this.captionButtons = {
};
/** The collapsingAnimation option determines the animation effect that is used when the wijdialog is collapsed.
* @type {object}
* @example
* $("selector").wijdialog({collapsingAnimation:
* { effect: "puff", duration: 300, easing: "easeOutExpo" }
* });
*/
this.collapsingAnimation = null;
/** The expandingAnimation option determines the animation effect that is used when the wijdialog is expanded.
* @type {object}
* @example
* $("selector").wijdialog({expandingAnimation:
* { effect: "puff", duration: 300, easing: "easeOutExpo" }
* });
*/
this.expandingAnimation = null;
/** This option specifies the URL for the iframe element inside wijdialog.
* @example
* $("selector").wijdialog({contentUrl: 'http://www.google.com'});
*/
this.contentUrl = "";
/** The minimizeZoneElementId option specifies the ID of the DOM element to dock to when wijdialog is minimized.
* @example
* $("selector").wijdialog({minimizeZoneElementId: "zoomId"});
*/
this.minimizeZoneElementId = "";
/** The buttonCreating event is called before the caption buttons are created.
* It can be used to change the array of the buttons or to change, add, or remove buttons from the title bar.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data Buttons array that will be created.
*/
this.buttonCreating = null;
/** The stateChanged event is called when the dialog state ("maximized", "minimized", "normal") is changed.
* @event
* @dataKey {string} originalState The original state of the dialog box.
* @dataKey {string} state The current state of the dialog box.
*/
this.stateChanged = null;
/** The blur event is called when the dialog widget loses focus.
* @event
* @dataKey {DOMElement} el The DOM element of this dialog.
*/
this.blur = null;
}
return wijdialog_options;
})();
/** @widget
* @extends jQuery.ui.dialog
*/
var wijdialog = (function (_super) {
__extends(wijdialog, _super);
function wijdialog() {
_super.apply(this, arguments);
}
wijdialog.prototype._create = function () {
var self = this, o = self.options;
// enable touch support:
//if (window.wijmoApplyWijTouchUtilEvents) {
// $ = window.wijmoApplyWijTouchUtilEvents($);
//}
$.ui.dialog.maxZ = $.ui.dialog.maxZ || 100;
//Add support for jUICE!
if($.isArray(o.buttons)) {
$.each(o.buttons, function (idx, value) {
var c = value.click;
if(c && (typeof c === "string") && window[c]) {
value.click = window[c];
}
});
}
//end
self.form = self.element.closest("form[id]")// for asp.net
;
$.ui.dialog.prototype._create.apply(self, arguments);
self.uiDialog.addClass("wijmo-wijdialog");
self._initWijWindow();
self._bindWindowResize();
self._attachDraggableResizableEvent();
self._originalPosition = o.position;
self.uiDialog.css({
zIndex: o.zIndex
});
self.isPin = false;
if(self.options.appendTo === "body") {
if(self.form.length) {
self.uiDialog.appendTo(self.form);
}
}
};
wijdialog.prototype._makeDraggable = function () {
$.ui.dialog.prototype._makeDraggable.apply(this, arguments);
this.uiDialog.draggable("option", "cancel", ".wijmo-wijdialog-captionbutton");
};
wijdialog.prototype._handleDisabledOption = function (disabled, ele) {
var self = this;
this.uiDialog.removeClass(this.options.wijCSS.stateDisabled);
if(disabled) {
if(!self.disabledDiv) {
self.disabledDiv = self._createDisabledDiv();
}
self.disabledDiv.appendTo(self.options.appendTo);
if($.browser.msie && self.uiDialog.data("ui-draggable")) {
self.uiDialog.draggable("disable");
}
this.uiDialog.addClass(this.options.wijCSS.stateDisabled);
} else if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
if($.browser.msie && self.uiDialog.data("ui-draggable")) {
self.uiDialog.draggable("enable");
}
}
};
wijdialog.prototype._createDisabledDiv = function () {
var self = this, div, ele = //Change your outerelement here
self.uiDialog, eleOffset = ele.offset(), disabledWidth = ele.outerWidth(), disabledHeight = ele.outerHeight();
div = $("<div></div>").addClass("ui-disabled").css({
"z-index": "99999",
position: "absolute",
width: disabledWidth,
height: disabledHeight,
left: eleOffset.left,
top: eleOffset.top
});
if($.browser.msie) {
div.css("background-color", "white");
if($.browser.version === "9.0") {
div.css("opacity", "0.1");
}
}
return div;
};
wijdialog.prototype.destroy = /**
* Removes the wijdialog functionality completely. This returns the element to its pre-init state.
*/
function () {
var self = this;
//Add for support disabled option at 2011/7/8
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
//end for disabled option
$.ui.dialog.prototype._destroy.apply(self, arguments);
self.element.unbind(".wijdialog").removeData('wijdialog');
};
wijdialog.prototype._attachDraggableResizableEvent = function () {
var self = this, uiDialog = self.uiDialog, o = self.options;
if(o.draggable && uiDialog.draggable) {
uiDialog.bind("dragstop", function (event, ui) {
self._saveNormalState();
self._destoryIframeMask();
}).bind("dragstart", function (event, ui) {
self._createIframeMask();
});
}
if(o.resizable && uiDialog.resizable) {
uiDialog.bind("resizestop", function (event, ui) {
self._saveNormalState();
self._destoryIframeMask();
}).bind("resizestart", function (event, ui) {
self._createIframeMask();
});
}
};
wijdialog.prototype._createIframeMask = //fixed iframe bug.
function () {
var self = this;
if(self.innerFrame) {
self.mask = $("<div style='width:100%;height:100%;position:absolute;" + "top:0px;left:0px;z-index:" + ($.ui.dialog.maxZ + 1) + "'></div>").appendTo(self.uiDialog);
}
};
wijdialog.prototype._destoryIframeMask = function () {
var self = this;
if(self.innerFrame && self.mask) {
self.mask.remove();
self.mask = undefined;
}
};
wijdialog.prototype._initWijWindow = function () {
var self = this, isIn = true;
self._createCaptionButtons();
self._checkUrl();
//self.uiDialogButtonPane = $(".ui-dialog-buttonpane", self.uiDialog);
self.uiDialog.bind("mousedown", function (event) {
var el = event.target;
if(!$.contains(self.element[0], el)) {
self.uiDialog.focus();
}
}).bind("mouseenter", function (event) {
isIn = true;
}).bind("mouseleave", function (event) {
isIn = false;
}).bind("focusout", function (event) {
if(!isIn) {
self._trigger("blur", event, {
el: self.element
});
}
});
};
wijdialog.prototype._moveToTop = function (event, force) {
var self = this, options = self.options, saveScroll;
if((options.modal && !force) || (!options.stack && !options.modal)) {
self._trigger('focus', event);
//Fixed an issue that in latest jQuery UI dialog, this method will return bool value.
// if the dialog has changed in DOM tree, this method will return true.
// and when mouse down inside of the dialog, it will according the return value to auto focus
// the first focusable element in dialog. If I click a dropdown(the dropdown element is not
// the first focusable element in dialog), it will set the first focusable element to focus.
// In this case, I can't select the dropdown value.
return false;
}
if(options.zIndex > $.ui.dialog.maxZ) {
$.ui.dialog.maxZ = options.zIndex;
}
if(self.overlay) {
$.ui.dialog.maxZ += 1;
self.overlay.css('z-index', $.ui.dialog.maxZ);
}
//Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed.
// http://ui.jquery.com/bugs/ticket/3193
saveScroll = {
scrollTop: self.element.scrollTop(),
scrollLeft: self.element.scrollLeft()
};
$.ui.dialog.maxZ += 1;
self.uiDialog.css('z-index', $.ui.dialog.maxZ);
self.element.attr(saveScroll);
self._trigger('focus', event);
//Fixed an issue that in latest jQuery UI dialog, this method will return bool value.
// if the dialog has changed in DOM tree, this method will return true.
// and when mouse down inside of the dialog, it will according the return value to auto focus
// the first focusable element in dialog. If I click a dropdown(the dropdown element is not
// the first focusable element in dialog), it will set the first focusable element to focus.
// In this case, I can't select the dropdown value.
return false;
};
wijdialog.prototype._checkUrl = function () {
var self = this, o = self.options, url = o.contentUrl, innerFrame = $('<iframe style="width:100%;height:99%;" frameborder="0"></iframe>');
if(typeof url === "string" && url.length > 0) {
self.element.addClass("wijmo-wijdialog-hasframe");
//innerFrame.attr("src", url);
self.element.append(innerFrame);
self.innerFrame = innerFrame;
}
self.contentWrapper = self.element;
};
wijdialog.prototype._setOption = function (key, value) {
var self = this;
$.ui.dialog.prototype._setOption.apply(self, arguments);
// if (key === "captionButtons") {
// // self._createCaptionButtons();
// // todo: reset captionButtons
// }
// //Add for support disabled option at 2011/7/8
// else
if(key === "disabled") {
self._handleDisabledOption(value, self.element);
} else //end for disabled option
if(key === "contentUrl") {
if(self.innerFrame) {
self.innerFrame.attr("src", value);
} else {
self._checkUrl();
}
} else if(key = "captionButtons") {
self._createCaptionButtons();
}
};
wijdialog.prototype._createCaptionButtons = function () {
var captionButtons = [], self = this, o = self.options, i, buttons = {
pin: {
visible: true,
click: self.pin,
iconClassOn: "ui-icon-pin-w",
iconClassOff: "ui-icon-pin-s"
},
refresh: {
visible: true,
click: self.refresh,
iconClassOn: "ui-icon-refresh"
},
toggle: {
visible: true,
click: self.toggle,
iconClassOn: "ui-icon-carat-1-n",
iconClassOff: "ui-icon-carat-1-s"
},
minimize: {
visible: true,
click: self.minimize,
iconClassOn: "ui-icon-minus"
},
maximize: {
visible: true,
click: self.maximize,
iconClassOn: "ui-icon-extlink"
},
close: {
visible: true,
text: o.closeText,
click: self.close,
iconClassOn: "ui-icon-close"
}
}, oCaptionButtons = o.captionButtons, uiDialogTitlebar = self.uiDialogTitlebar;
uiDialogTitlebar.children(".ui-dialog-titlebar-close, .wijmo-wijdialog-captionbutton").remove();
$.each(buttons, function (name, value) {
if(oCaptionButtons && oCaptionButtons[name]) {
$.extend(value, oCaptionButtons[name]);
}
captionButtons.push({
button: name,
info: value
});
});
self._trigger("buttonCreating", null, captionButtons);
for(i = 0; i < captionButtons.length; i++) {
self._createCaptionButton(captionButtons[i], uiDialogTitlebar);
}
};
wijdialog.prototype._createCaptionButton = function (buttonHash, uiDialogTitlebar, notAppendToHeader) {
var self = this, buttonObject, buttonCSS = "wijmo-wijdialog-titlebar-" + buttonHash.button, button = uiDialogTitlebar.children("." + buttonCSS), info = buttonHash.info, buttonIcon = $("<span></span>");
if(info.visible) {
if(button.size() === 0) {
buttonIcon.addClass("ui-icon " + info.iconClassOn).text(info.text || buttonHash.button);
buttonObject = $('<a href="#"></a>').append(buttonIcon).addClass(buttonCSS + " ui-corner-all wijmo-wijdialog-captionbutton").attr("role", "button").hover(function () {
buttonObject.addClass(uiStateHover);
}, function () {
buttonObject.removeClass(uiStateHover);
}).click(function (event) {
if(buttonIcon.hasClass(info.iconClassOff)) {
buttonIcon.removeClass(info.iconClassOff);
} else {
buttonIcon.addClass(info.iconClassOff);
}
if($.isFunction(info.click)) {
info.click.apply(self, arguments);
}
return false;
});
if(notAppendToHeader) {
return buttonObject;
} else {
buttonObject.appendTo(uiDialogTitlebar);
}
}
self[buttonHash.button + "Button"] = buttonObject;
} else {
button.remove();
}
};
wijdialog.prototype.pin = /**
* The pin method prevents the wijdialog from being moved.
*/
function () {
var drag = this.isPin, buttonIcon = this.pinButton.children("span");
if(!drag) {
if(buttonIcon.length) {
if(!buttonIcon.hasClass("ui-icon-pin-s")) {
buttonIcon.addClass("ui-icon-pin-s");
}
}
} else {
buttonIcon.removeClass("ui-icon-pin-s");
}
this._enableDisableDragger(!drag);
this.isPin = !drag;
};
wijdialog.prototype.refresh = /**
* The refresh method refreshes the iframe content within the wijdialog.
*/
function () {
var fr = this.innerFrame;
if(fr !== undefined) {
fr.attr("src", fr.attr("src"));
}
};
wijdialog.prototype.toggle = /**
* The toggle method expands or collapses the content of the wijdialog.
*/
function () {
var self = this, buttonIcon = self.toggleButton.children("span");
// TODO : toggle animation and event invoking.
if(!self.minimized) {
if(self.collapsed === undefined || !self.collapsed) {
self.collapsed = true;
if(!buttonIcon.hasClass("ui-icon-carat-1-s")) {
buttonIcon.addClass("ui-icon-carat-1-s");
}
self._collapseDialogContent(true);
} else {
self.collapsed = false;
if(buttonIcon.hasClass("ui-icon-carat-1-s")) {
buttonIcon.removeClass("ui-icon-carat-1-s");
}
self._expandDialogContent(true);
}
}
};
wijdialog.prototype._expandDialogContent = function (fireEvent) {
var self = this, o = self.options, animationSetting = o.expandingAnimation;
self.uiDialog.height("auto");
if(fireEvent && animationSetting !== null) {
self.contentWrapper.show(animationSetting.animated, animationSetting.options, animationSetting.duration, function (e) {
self.uiDialog.css("height", self._toggleHeight);
if($.isFunction(animationSetting.callback)) {
animationSetting.callback(e);
}
if(o.resizable) {
self._enableDisableResizer(false);
}
});
} else {
self.contentWrapper.show();
if(o.resizable) {
self._enableDisableResizer(false);
}
self.uiDialog.css("height", self.toggleHeight);
}
};
wijdialog.prototype._collapseDialogContent = function (fireEvent) {
var self = this, o = self.options, animationSetting = o.collapsingAnimation;
if(o.resizable) {
self._enableDisableResizer(true);
}
self._toggleHeight = self.uiDialog[0].style.height;
self.uiDialog.height("auto");
if(fireEvent && animationSetting !== null) {
self.contentWrapper.hide(animationSetting.animated, animationSetting.options, animationSetting.duration);
} else {
self.contentWrapper.hide();
}
self._enableDisableDragger(self.isPin);
};
wijdialog.prototype._enableDisableResizer = function (disabled) {
var dlg = this.uiDialog;
if(!this.options.resizable) {
return;
}
dlg.resizable({
disabled: disabled
});
if(disabled) {
dlg.removeClass("ui-state-disabled");
}
};
wijdialog.prototype._enableDisableDragger = function (disabled) {
var dlg = this.uiDialog;
if(!this.options.draggable) {
return;
}
dlg.draggable({
disabled: disabled
});
if(disabled) {
dlg.removeClass("ui-state-disabled");
}
};
wijdialog.prototype.minimize = /**
* The minimize method minimizes the wijdialog.
*/
function () {
var self = this, dlg = self.uiDialog, o = self.options, miniZone = null, $from = $("<div></div>"), $to = $("<div></div>"), defaultZone, scrollTop, top, originalPosition, originalSize = {
width: undefined,
height: undefined
}, position, size = {
width: undefined,
height: undefined
}, content = "uiDialog", originalState;
//content has 2 value 'uiDialog' for normal content,'copy' for iframe
//to resolve the issue that iframe reload when minimize.
//Only minimize from normal,maximized state
if(!self.minimized) {
originalPosition = self.uiDialog.position();
originalSize.width = self.uiDialog.width();
originalSize.height = self.uiDialog.height();
originalState = self.getState();
if(self.maximized) {
self.maximized = false;
self.restoreButton.remove();
//fixed bug can't minimize window when it's maximized
$(window).unbind(".onWinResize");
} else {
// minimize from normal state
if(self.collapsed) {
self._expandDialogContent(false);
}
self._saveNormalState();
}
// disable resizer
self._enableDisableResizer(true);
//hide content
if(self.collapsed) {
self._collapseDialogContent(false);
}
$from.appendTo(self.options.appendTo).css({
top: self.uiDialog.offset().top,
left: self.uiDialog.offset().left,
height: self.uiDialog.innerHeight(),
width: self.uiDialog.innerWidth(),
position: "absolute"
});
self.contentWrapper.hide();
if(self.uiDialogButtonPane.length) {
self.uiDialogButtonPane.hide();
}
// remove size restriction
dlg.height("auto");
dlg.width("auto");
self._doButtonAction(self.minimizeButton, "hide");
self._restoreButton(true, self.minimizeButton, "After");
self._doButtonAction(self.pinButton, "hide");
self._doButtonAction(self.refreshButton, "hide");
self._doButtonAction(self.toggleButton, "hide");
self._doButtonAction(self.maximizeButton, "show");
if($.browser.webkit) {
$(".wijmo-wijdialog-captionbutton", self.uiDialog).css("float", "left");
}
if(self.innerFrame) {
content = "copy";
self[content] = self.uiDialog.clone();
self[content].empty();
self.uiDialogTitlebar.appendTo(self[content]);
}
if(o.minimizeZoneElementId.length > 0) {
miniZone = $("#" + o.minimizeZoneElementId);
}
if(miniZone !== null && miniZone.size() > 0) {
miniZone.append(self[content]);
} else {
defaultZone = $("." + zonCSS);
if(defaultZone.size() === 0) {
defaultZone = $('<div class="' + zonCSS + '"></div>');
$(document.body).append(defaultZone);
}
defaultZone.append(self[content]).css("z-index", dlg.css("z-index"));
}
self[content].css("position", "static");
self[content].css("float", "left");
if($.browser.msie && $.browser.version === '6.0') {
scrollTop = $(document).scrollTop();
top = document.documentElement.clientHeight - defaultZone.height() + scrollTop;
defaultZone.css({
position: 'absolute',
left: "0px",
top: top
});
}
$to.appendTo("body").css({
top: self[content].offset().top,
left: self[content].offset().left,
height: self[content].innerHeight(),
width: self[content].innerWidth(),
position: "absolute"
});
self.uiDialog.hide();
if(self.innerFrame) {
self[content].hide();
}
$from.effect("transfer", {
to: $to,
className: "ui-widget-content"
}, 100, function () {
$from.remove();
$to.remove();
self[content].show();
self.minimized = true;
position = self.uiDialog.position();
size.width = self.uiDialog.width();
size.height = self.uiDialog.height();
self._enableDisableDragger(true);
self._trigger('resize', null, {
originalPosition: originalPosition,
originalSize: originalSize,
position: position,
size: size
});
self._trigger("stateChanged", null, {
originalState: originalState,
state: "minimized"
});
});
}
};
wijdialog.prototype._doButtonAction = function (button, action) {
if(button !== undefined) {
button.removeClass(uiStateHover);
button[action]();
}
};
wijdialog.prototype.maximize = /**
* The maximize method maximizes the wijdialog.
*/
function () {
var self = this, w = $(window), originalPosition, originalSize = {
width: undefined,
height: undefined
}, position, size = {
width: undefined,
height: undefined
}, state;
if(!self.maximized) {
self._enableDisableDragger(false);
originalPosition = self.uiDialog.position();
originalSize.width = self.uiDialog.width();
originalSize.height = self.uiDialog.height();
// maximized from minimized state
if(self.minimized) {
self.restore()//bug in IE when minimize -> maximize -> restore
;
} else {
if(self.collapsed) {
self._expandDialogContent(false);
}
self._saveNormalState();
state = "normal";
}
self.maximized = true;
if(self.maximizeButton !== undefined) {
self.maximizeButton.hide();
self._restoreButton(true, self.maximizeButton, "Before");
}
if($.browser.webkit) {
$(".wijmo-wijdialog-captionbutton").css("float", "");
}
self._onWinResize(self, w);
if(self.collapsed) {
self._collapseDialogContent(false);
}
/// TODO : bind resize event.
if(!self.collapsed) {
self._enableDisableDragger(true);
}
self._enableDisableResizer(true);
position = self.uiDialog.position();
size.width = self.uiDialog.width();
size.height = self.uiDialog.height();
self._trigger('resize', null, {
originalPosition: originalPosition,
originalSize: originalSize,
position: position,
size: size
});
if(state === "normal") {
self._trigger("stateChanged", null, {
originalState: "normal",
state: "maximized"
});
}
}
};
wijdialog.prototype._bindWindowResize = function () {
var self = this, w = $(window), top, scrollTop, defaultZone;
w.resize(function () {
if(self.maximized) {
self._onWinResize(self, w);
}
});
//fixed ie 6 position:fixed
if($.browser.msie && $.browser.version === '6.0') {
w.bind("scroll.wijdialog resize.wijdialog", function () {
if(self.minimized) {
scrollTop = $(document).scrollTop();
defaultZone = self.uiDialog.parent();
top = document.documentElement.clientHeight - defaultZone.height() + scrollTop;
defaultZone.css({
top: top
});
}
});
}
};
wijdialog.prototype._saveNormalState = function () {
var self = this, dialog = self.uiDialog, ele = self.element;
if(!self.maximized) {
self.normalWidth = dialog.css("width");
self.normalLeft = dialog.css("left");
self.normalTop = dialog.css("top");
self.normalHeight = dialog.css("height");
self.normalInnerHeight = ele.css("height");
self.normalInnerWidth = ele.css("width");
self.normalInnerMinWidth = ele.css("min-width");
self.normalInnerMinHeight = ele.css("min-height");
}
};
wijdialog.prototype._onWinResize = function (self, w) {
self.uiDialog.css("top", w.scrollTop());
self.uiDialog.css("left", w.scrollLeft());
self.uiDialog.setOutWidth(w.width());
self.uiDialog.setOutHeight(w.height());
self.options.width = self.uiDialog.width();
self.options.height = self.uiDialog.height();
self._size();
if(self.collapsed) {
//fixed bug when resize on maxmize and collapse state.
self.uiDialog.height("auto");
self.contentWrapper.hide();
}
};
wijdialog.prototype._restoreButton = function (show, button, position) {
var self = this, buttonHash = {
button: "restore",
info: {
visible: show,
click: self.restore,
iconClassOn: "ui-icon-newwin"
}
}, restore = self._createCaptionButton(buttonHash, self.uiDialogTitlebar, true);
if(show) {
restore["insert" + position](button);
self.restoreButton = restore;
}
};
wijdialog.prototype._appendToBody = function (dlg) {
if(!this.innerFrame) {
dlg.appendTo(this.options.appendTo);
} else {
this.uiDialogTitlebar.prependTo(dlg);
dlg.show();
}
};
wijdialog.prototype.restore = /**
* The restore method restores the wijdialog to its normal size from either the minimized or the maximized state.
*/
function () {
var self = this, dlg = self.uiDialog, originalPosition, originalSize = {
width: undefined,
height: undefined
}, position, size = {
width: undefined,
height: undefined
}, $from = $("<div></div>"), $to = $("<div></div>"), content = "uiDialog", state;
//content has 2 value 'uiDialog' for normal content,'copy' for iframe
//to resolve the issue that iframe reload when minimize on ff & webkit.
// restore form minimized state.
if(self.minimized) {
self.minimized = false;
//self._enableDisableDragger(false);
if(self.innerFrame) {
content = "copy";
if(!self[content]) {
content = "uiDialog";
}
}
originalPosition = self[content].position();
originalSize.width = self[content].width();
originalSize.height = self[content].height();
$from.appendTo(self.options.appendTo).css({
top: self[content].offset().top,
left: self[content].offset().left,
height: self[content].innerHeight(),
width: self[content].innerWidth(),
position: "absolute"
});
dlg.css("position", "absolute");
dlg.css("float", "");
self._appendToBody(dlg);
self._enableDisableResizer(false);
if(!self.isPin) {
self._enableDisableDragger(false);
}
self._restoreToNormal();
self.contentWrapper.show();
if(self.uiDialogButtonPane.length) {
self.uiDialogButtonPane.show();
}
$to.appendTo(self.options.appendTo).css({
top: self.uiDialog.offset().top,
left: self.uiDialog.offset().left,
height: self.uiDialog.innerHeight(),
width: self.uiDialog.innerWidth(),
position: "absolute"
});
self.uiDialog.hide();
$from.effect("transfer", {
to: $to,
className: "ui-widget-content"
}, 150, function () {
self.uiDialog.show();
position = self.uiDialog.position();
size.width = self.uiDialog.width();
size.height = self.uiDialog.height();
$from.remove();
$to.remove();
if(self.copy) {
self.copy.remove();
}
self._trigger('resize', null, {
originalPosition: originalPosition,
originalSize: originalSize,
position: position,
size: size
});
state = self.getState();
self._trigger("stateChanged", null, {
originalState: "minimized",
state: state
});
});
if(self.collapsed) {
self._collapseDialogContent();
}
self._doButtonAction(self.minimizeButton, "show");
self._doButtonAction(self.restoreButton, "remove");
self._doButtonAction(self.pinButton, "show");
self._doButtonAction(self.refreshButton, "show");
self._doButtonAction(self.toggleButton, "show");
if($.browser.webkit) {
$(".wijmo-wijdialog-captionbutton").css("float", "");
}
} else if(self.maximized) {
self.maximized = false;
originalPosition = self.uiDialog.position();
originalSize.width = self.uiDialog.width();
originalSize.height = self.uiDialog.height();
$(window).unbind(".onWinResize");
if(self.collapsed) {
self._expandDialogContent();
}
self._enableDisableResizer(false);
if(!self.isPin) {
self._enableDisableDragger(false);
}
self._restoreToNormal();
self.contentWrapper.show();
if(self.collapsed) {
self._collapseDialogContent();
}
if(self.maximizeButton !== undefined) {
self.maximizeButton.show();
self._restoreButton(false, self.maximizeButton, "before");
}
position = self.uiDialog.position();
size.width = self.uiDialog.width();
size.height = self.uiDialog.height();
self._trigger('resize', null, {
originalPosition: originalPosition,
originalSize: originalSize,
position: position,
size: size
});
state = self.getState();
self._trigger("stateChanged", null, {
originalState: "maximized",
state: state
});
}
};
wijdialog.prototype.getState = /**
* The getState method gets the state of the dialog widget.
* @returns {string} Possible values are: minimized, maximized, and normal.
*/
function () {
var self = this;
return self.minimized ? "minimized" : (self.maximized ? "maximized" : "normal");
};
wijdialog.prototype.reset = /**
* The reset method resets dialog properties such as width and height to their default values.
*/
function () {
var self = this;
self.normalWidth = self.normalLeft = self.normalTop = self.normalHeight = self.normalInnerHeight = self.normalInnerWidth = self.normalInnerMinWidth = self.normalInnerMinHeight = undefined;
self._setOption("position", self._originalPosition);
};
wijdialog.prototype.open = /**
* The open method opens an instance of the wijdialog.
*/
function () {
var self = this, o = self.options;
if((o.hide === "drop" || o.hide === "bounce") && $.browser.msie) {
//fixed bug when effect "drop" on IE
self.uiDialog.css("filter", "auto");
}
if(!self.innerFrame) {
if(!self.minimized) {
$.ui.dialog.prototype.open.apply(self, arguments);
// if (!self.maximized) {
// self._restoreToNormal();
// }
} else {
self.uiDialog.show();
self._isOpen = true;
}
self.uiDialog.wijTriggerVisibility();
} else {
// for 38166 issue:
// http://stackoverflow.com/questions/14965912/jquery-dialog-iframe-gives-this-error-in-ie9-script5009-array-is-undefined
if($.browser.msie && $.browser.version === "9.0") {
window.setTimeout(function () {
self.innerFrame.attr("src", o.contentUrl);
}, 200);
} else {
self.innerFrame.attr("src", o.contentUrl);
}
if(!self.minimized) {
$.ui.dialog.prototype.open.apply(self, arguments);
} else {
self.uiDialogTitlebar.show();
self._isOpen = true;
}
}
if(self.collapsed) {
self._collapseDialogContent();
}
if(o.disabled) {
if(self.disabledDiv) {
self.disabledDiv.show();
} else {
self.disable();
}
}
};
wijdialog.prototype.close = /**
* The close method closes the dialog widget.
*/
function () {
var self = this, o = self.options;
if($.ui.dialog.prototype.close.apply(self, arguments)) {
if(self.innerFrame) {
self.innerFrame.attr("src", "");
if(self.minimized) {
self.uiDialogTitlebar.hide();
}
}
if(self.disabledDiv && o.disabled) {
self.disabledDiv.hide();
}
}
};
wijdialog.prototype._restoreToNormal = function () {
var self = this, dialog = self.uiDialog, ele = self.element;
dialog.css("width", self.normalWidth);
dialog.css("left", self.normalLeft);
dialog.css("top", self.normalTop);
dialog.css("height", self.normalHeight);
ele.css("height", self.normalInnerHeight);
ele.css("width", self.normalInnerWidth);
ele.css("min-width", self.normalInnerMinWidth);
ele.css("min-height", self.normalInnerMinHeight);
self.options.width = self.uiDialog.width();
self.options.height = self.uiDialog.height();
};
return wijdialog;
})(JQueryUIDialog);
dialog.wijdialog = wijdialog;
if($.ui && $.ui.dialog) {
$.extend($.ui.dialog.overlay, {
create: function (dialog) {
if(this.instances.length === 0) {
// prevent use of anchors and inputs
// we use a setTimeout in case the overlay is created from an
// event that we're going to be cancelling (see #2804)
setTimeout(function () {
// handle $(el).dialog().dialog('close') (see #4065)
if($.ui.dialog.overlay.instances.length) {
$(document).bind($.ui.dialog.overlay.events, function (event) {
// stop events if the z-index of the target is < the z-index of the overlay
// we cannot return true when we don't want to cancel the event (#3523)
if($(event.target).zIndex() < $.ui.dialog.overlay.maxZ && !$.contains(dialog.element[0], event.target)) {
return false;
}
});
}
}, 1);
// allow closing by pressing the escape key
$(document).bind('keydown.dialog-overlay', function (event) {
if(dialog.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE) {
dialog.close(event);
event.preventDefault();
}
});
// handle window resize
$(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
}
var $el = (this.oldInstances.pop() || $('<div></div>').addClass('ui-widget-overlay')).appendTo(document.body).css({
width: this.width(),
height: this.height()
});
if($.fn.bgiframe) {
$el.bgiframe();
}
this.instances.push($el);
return $el;
},
height: function () {
var scrollHeight, offsetHeight;
// handle IE 6
if($.browser.msie) {
scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
offsetHeight = Math.max(document.documentElement.offsetHeight, document.body.offsetHeight);
if(scrollHeight < offsetHeight) {
return $(window).height() + 'px';
} else {
return scrollHeight + 'px';
}
// handle "good" browsers
} else {
return $(document).height() + 'px';
}
},
width: function () {
var scrollWidth, offsetWidth;
// handle IE 6
if($.browser.msie) {
scrollWidth = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth);
offsetWidth = Math.max(document.documentElement.offsetWidth, document.body.offsetWidth);
if(scrollWidth < offsetWidth) {
return $(window).width() + 'px';
} else {
return scrollWidth + 'px';
}
// handle "good" browsers
} else {
return $(document).width() + 'px';
}
}
});
wijdialog.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, $.ui.dialog.prototype.options, new wijdialog_options());
// for some reason, the jQuery UI dialog override these two methods to $.noonp, I orderride it as base widget.
wijdialog.prototype.disable = function () {
return this._setOption("disabled", true);
};
wijdialog.prototype.enable = function () {
return this._setOption("disabled", false);
};
$.wijmo.registerWidget(widgetName, $.ui.dialog, wijdialog.prototype);
}
})(wijmo.dialog || (wijmo.dialog = {}));
var dialog = wijmo.dialog;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/*globals jQuery,$,window,alert,document,confirm,location,setTimeout, Globalize,
amplify*/
/*jslint white: false */
/*jslint nomen: false*/
/*jslint browser: true*/
/*jslint continue: true*/
/*jslint devel: true*/
/*jslint forin: true*/
/*jslint maxlen: 110*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.wijmo.wijutil.js
* jquery.wijmo.wijaccordion.js
*
*/
(function (accordion) {
"use strict";
var $ = jQuery, widgetName = "wijaccordion";
/** @widget */
var wijaccordion = (function (_super) {
__extends(wijaccordion, _super);
function wijaccordion() {
_super.apply(this, arguments);
this.widgetEventPrefix = "wijaccordion";
}
wijaccordion.prototype._setOption = function (key, value) {
var o = this.options;
if(o[key] !== value) {
switch(key) {
case "selectedIndex":
this.activate(value);
break;
case "disabled":
if(value) {
this.element.addClass(o.wijCSS.stateDisabled);
} else {
this.element.removeClass(o.wijCSS.stateDisabled);
}
break;
case "event":
this._unbindLiveEvents();
this.options.event = value;
this._bindLiveEvents();
break;
case "header":
this._handleHeaderChange(value, o.header);
break;
case "animated":
break;
case "expandDirection":
this._onDirectionChange(value, true, o.expandDirection);
break;
default:
break;
}
}
$.wijmo.widget.prototype._setOption.apply(this, arguments);
};
wijaccordion.prototype._handleHeaderChange = function (newHeaderSelector, prevHeaderSelector) {
var prevHeaders = this.element.find(prevHeaderSelector);
prevHeaders.removeClass("wijmo-wijaccordion-header " + this.options.wijCSS.stateActive + " " + this._triangleIconOpened).siblings(".wijmo-wijaccordion-content").removeClass("wijmo-wijaccordion-content " + this.options.wijCSS.content + " wijmo-wijaccordion-content-active");
this._initHeaders(newHeaderSelector);
};
wijaccordion.prototype._initHeaders = function (selector) {
if (typeof selector === "undefined") { selector = null; }
var o = this.options, selector = selector ? selector : o.header, headers = this.element.find(selector);
headers.each(jQuery.proxy(this._initHeader, this));
};
wijaccordion.prototype._initHeader = function (index, elem) {
var o = this.options, rightToLeft = this.element.data("rightToLeft"), header = $(elem), content = $(header.next()[0]);
if(rightToLeft) {
header.remove();
header.insertAfter(content);
}
header.addClass("wijmo-wijaccordion-header").attr("role", "tab");
content.attr("role", "tabpanel");
if(header.find("> a").length === 0) {
header.wrapInner('<a href="#"></a>');
}
if(header.find("> .ui-icon").length === 0) {
$('<span class="ui-icon"></span>').insertBefore($("> a", header)[0]);
}
if(index === o.selectedIndex) {
header.addClass(this.options.wijCSS.stateActive).addClass(this._headerCornerOpened).attr({
"aria-expanded": "true",
tabIndex: 0
}).find("> .ui-icon").addClass(this._triangleIconOpened);
content.addClass("wijmo-wijaccordion-content-active").addClass(this._contentCornerOpened).wijTriggerVisibility();
} else {
header.addClass(o.wijCSS.stateDefault + " ui-corner-all").attr({
"aria-expanded": "false",
tabIndex: -1
}).find("> .ui-icon").addClass(this._triangleIconClosed);
content.hide();
}
content.addClass("wijmo-wijaccordion-content " + this.options.wijCSS.content);
//if use the header option and the header's parent wrapped an div element, when the
// accordion's expandDirection is left/top, the layout is wrong.
while(true) {
if(header.parent().hasClass("wijmo-wijaccordion")) {
break;
}
header.unwrap();
}
};
wijaccordion.prototype._create = function () {
var o = this.options, self = this;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
this.element.addClass("wijmo-wijaccordion " + o.wijCSS.widget + " wijmo-wijaccordion-icons " + "ui-helper-clearfix");
if(o.disabled) {
this.element.addClass(o.wijCSS.stateDisabled);
}
this._onDirectionChange(o.expandDirection, false);
this._initHeaders();
this.element.attr("role", "tablist");
//super._create(this, arguments);
$(window).on("resize.wijaccordion", function (e) {
self._adjustAccordion();
});
if(o.expandDirection === 'left' || o.expandDirection === 'right') {
self._adjustAccordion();
}
$.wijmo.widget.prototype._create.apply(this, arguments);
};
wijaccordion.prototype._init = function () {
this._bindLiveEvents();
};
wijaccordion.prototype._adjustAccordion = function () {
if(this.options.expandDirection === 'top' || this.options.expandDirection === 'bottom') {
return;
}
var headers = this._getHeaders(), contentEle = $('.wijmo-wijaccordion-content', this.element), fWidth = contentEle.parent().width(), paddingAndBorderWidth = parseInt(contentEle.css("paddingLeft"), 10) + parseInt(contentEle.css("paddingRight"), 10) + parseInt(contentEle.css("borderRightWidth"), 10) + parseInt(contentEle.css("borderLeftWidth"), 10), headerWidth = $('.wijmo-wijaccordion-header', this.element).outerWidth(true), adjustContentWidth = fWidth - headers.length * (headerWidth + 4) - paddingAndBorderWidth, adjustContentWidth = // default width is 36em: 576px == 36em
adjustContentWidth < 576 ? adjustContentWidth : 576;
contentEle.width(adjustContentWidth);
};
wijaccordion.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var o = this.options;
this._unbindLiveEvents();
this.element.removeClass("wijmo-wijaccordion " + o.wijCSS.widget + " wijmo-wijaccordion-icons").removeAttr("role");
$(window).off("resize.wijaccordion");
$.wijmo.widget.prototype.destroy.apply(this, arguments);
};
wijaccordion.prototype._getHeaders = function () {
var o = this.options, rightToLeft = this.element.data("rightToLeft"), headersArr = [], i, hdr;
var headers = this.element.find(o.header);
if(headers.length > 0 && !$(headers[0]).hasClass("wijmo-wijaccordion-header") && $(headers[0]).hasClass("wijmo-wijaccordion-content")) {
for(i = 0; i < headers.length; i += 1) {
// fix for 29695:
hdr = rightToLeft ? $(headers[i]).next(".wijmo-wijaccordion-header") : $(headers[i]).prev(".wijmo-wijaccordion-header");
if(hdr.length > 0) {
headersArr.push(hdr[0]);
}
}
} else {
return headers;
}
return $(headersArr);
};
wijaccordion.prototype.activate = /**
* Activates the accordion content pane at the specified index.
* @remarks
* You can use code like in the example below inside your document ready function
* to activate the specified pane using the click event of a button.
* @param {number} index The zero-based index of the accordion pane to activate.
*/
function (index) {
var nextHeader, o = this.options, headers = this._getHeaders(), prevHeader, adjustWidth, rightToLeft = this.element.data("rightToLeft"), newIndex, prevIndex, nextContent, prevContent, animOptions, proxied, proxiedDuration, animations, duration, easing;
prevHeader = $(jQuery.grep(headers, function (a) {
return $(a).hasClass(o.wijCSS.stateActive);
}));
if(typeof index === "number") {
nextHeader = $(headers[index]);
} else if(typeof index === "string") {
index = parseInt(index, 0);
nextHeader = $(headers[index]);
} else {
nextHeader = $(index);
index = headers.index(index);
}
if(nextHeader.hasClass(o.wijCSS.stateDisabled)) {
return false;
}
if(nextHeader.hasClass(o.wijCSS.stateActive)) {
if(o.requireOpenedPane) {
// fix for
// [17869] Unable to select the desire panel
// after all the panels are open in certain scenarios
if(prevHeader.length === nextHeader.length && prevHeader.index() === nextHeader.index()) {
return false;
}
} else {
prevHeader = nextHeader;
nextHeader = $(null);
}
} else if(!o.requireOpenedPane) {
prevHeader = $(null);
}
// 29193 (fix for nested accordions):
newIndex = headers.index(nextHeader);
prevIndex = headers.index(prevHeader);
nextContent = rightToLeft ? nextHeader.prev(".wijmo-wijaccordion-content") : nextHeader.next(".wijmo-wijaccordion-content");
prevContent = rightToLeft ? prevHeader.prev(".wijmo-wijaccordion-content") : prevHeader.next(".wijmo-wijaccordion-content");
if(prevHeader.length === 0 && nextHeader.length === 0) {
return false;
}
adjustWidth = nextContent.css("width");
if(!this._trigger("beforeSelectedIndexChanged", null, {
newIndex: newIndex,
prevIndex: prevIndex
})) {
return false;
}
prevHeader.removeClass(o.wijCSS.stateActive).removeClass(this._headerCornerOpened).addClass(o.wijCSS.stateDefault + " ui-corner-all").attr({
"aria-expanded": "false",
tabIndex: -1
}).find("> .ui-icon").removeClass(this._triangleIconOpened).addClass(this._triangleIconClosed);
nextHeader.removeClass(o.wijCSS.stateDefault + " ui-corner-all").addClass(o.wijCSS.stateActive).addClass(this._headerCornerOpened).attr({
"aria-expanded": "true",
tabIndex: 0
}).find("> .ui-icon").removeClass(this._triangleIconClosed).addClass(this._triangleIconOpened);
if(o.animated) {
animOptions = {
toShow: nextContent,
toHide: prevContent,
complete: jQuery.proxy(function () {
prevContent.removeClass("wijmo-wijaccordion-content-active");
nextContent.addClass("wijmo-wijaccordion-content-active").wijTriggerVisibility();
prevContent.css('display', '');
nextContent.css('display', '');
if($.fn.wijlinechart) {
prevContent.find(".wijmo-wijlinechart").wijlinechart("redraw")//?
;
nextContent.find(".wijmo-wijlinechart").wijlinechart("redraw")//?
;
}
//prevContent.wijTriggerVisibility();
//nextContent.wijTriggerVisibility();
if(adjustWidth !== null && adjustWidth !== undefined && (o.expandDirection === 'left' || o.expandDirection === 'right')) {
nextContent.width(adjustWidth);
}
this._trigger("selectedIndexChanged", null, {
newIndex: newIndex,
prevIndex: prevIndex
});
}, this),
horizontal: this.element.hasClass("ui-helper-horizontal"),
rightToLeft: this.element.data("rightToLeft"),
down: (newIndex > prevIndex),
autoHeight: o.autoHeight || o.fillSpace
};
proxied = o.animated;
proxiedDuration = o.duration;
if($.isFunction(proxied)) {
o.animated = proxied(animOptions);
}
if($.isFunction(proxiedDuration)) {
o.duration = proxiedDuration(animOptions);
}
animations = $.wijmo.wijaccordion.animations;
duration = o.duration;
easing = o.animated;
if(easing && !animations[easing] && !$.easing[easing]) {
easing = 'slide';
}
if(!animations[easing]) {
animations[easing] = function (options) {
this.slide(options, {
easing: easing,
duration: duration || 700
});
};
}
animations[easing](animOptions);
} else {
if(prevHeader.length > 0) {
prevContent.hide().removeClass("wijmo-wijaccordion-content-active");
}
if(nextHeader.length > 0) {
nextContent.show().addClass("wijmo-wijaccordion-content-active").addClass(this._contentCornerOpened).wijTriggerVisibility();
}
if($.fn.wijlinechart) {
prevContent.find(".wijmo-wijlinechart").wijlinechart("redraw")//?
;
nextContent.find(".wijmo-wijlinechart").wijlinechart("redraw")//?
;
}
//prevContent.wijTriggerVisibility();
//nextContent.wijTriggerVisibility();
if(adjustWidth !== null && adjustWidth !== undefined && (o.expandDirection === 'left' || o.expandDirection === 'right')) {
nextContent.width(adjustWidth);
}
this._trigger("selectedIndexChanged", null, {
newIndex: newIndex,
prevIndex: prevIndex
});
}
this.options.selectedIndex = newIndex;
};
wijaccordion.prototype._bindLiveEvents = /** Private methods */
function () {
var self = this;
this.element.on(this.options.event + ".wijaccordion", ".wijmo-wijaccordion-header", jQuery.proxy(this._onHeaderClick, this)).on("keydown.wijaccordion", ".wijmo-wijaccordion-header", jQuery.proxy(this._onHeaderKeyDown, this)).on("mouseenter.wijaccordion", ".wijmo-wijaccordion-header", function () {
$(this).addClass('ui-state-hover');
}).on("mouseleave.wijaccordion", ".wijmo-wijaccordion-header", function () {
$(this).removeClass('ui-state-hover');
}).on("focus.wijaccordion", ".wijmo-wijaccordion-header", function () {
$(this).addClass(self.options.wijCSS.stateFocus);
}).on("blur.wijaccordion", ".wijmo-wijaccordion-header", function () {
$(this).removeClass(self.options.wijCSS.stateFocus);
});
};
wijaccordion.prototype._unbindLiveEvents = function () {
this.element.off(".wijaccordion", ".wijmo-wijaccordion-header");
};
wijaccordion.prototype._onHeaderClick = function (e) {
if(!this.options.disabled) {
this.activate(e.currentTarget);
}
return false;
};
wijaccordion.prototype._onHeaderKeyDown = function (e) {
if(this.options.disabled || e.altKey || e.ctrlKey) {
return;
}
if(!$.ui) {
return;
}
var keyCode = $.ui.keyCode, focusedHeader = this.element.find(".wijmo-wijaccordion-header." + this.options.wijCSS.stateFocus), focusedInd, headers = this._getHeaders();
if(focusedHeader.length > 0) {
focusedInd = $(".wijmo-wijaccordion-header", this.element).index(focusedHeader);
switch(e.keyCode) {
case keyCode.RIGHT:
case keyCode.DOWN:
if(headers[focusedInd + 1]) {
headers[focusedInd + 1].focus();
return false;
}
break;
case keyCode.LEFT:
case keyCode.UP:
if(headers[focusedInd - 1]) {
headers[focusedInd - 1].focus();
return false;
}
break;
case keyCode.SPACE:
case keyCode.ENTER:
this.activate(e.currentTarget);
e.preventDefault();
break;
}
}
return true;
};
wijaccordion.prototype._onDirectionChange = function (newDirection, allowDOMChange, prevDirection) {
if (typeof prevDirection === "undefined") { prevDirection = null; }
var rightToLeft, openedHeaders, openedContents, openedTriangles, closedTriangles, prevIsRightToLeft;
var o = this.options;
if(allowDOMChange) {
openedHeaders = this.element.find(".wijmo-wijaccordion-header." + this._headerCornerOpened);
openedHeaders.removeClass(this._headerCornerOpened);
openedContents = this.element.find(".wijmo-wijaccordion-content." + this._contentCornerOpened);
openedContents.removeClass(this._contentCornerOpened);
openedTriangles = this.element.find("." + this._triangleIconOpened);
closedTriangles = this.element.find("." + this._triangleIconClosed);
openedTriangles.removeClass(this._triangleIconOpened);
closedTriangles.removeClass(this._triangleIconClosed);
}
if(prevDirection !== null) {
this.element.removeClass("wijmo-wijaccordion-" + prevDirection);
}
switch(newDirection) {
case "top":
this._headerCornerOpened = "ui-corner-bottom";
this._contentCornerOpened = "ui-corner-top";
this._triangleIconOpened = o.wijCSS.iconArrowUp;
this._triangleIconClosed = o.wijCSS.iconArrowRight;
rightToLeft = true;
this.element.removeClass("ui-helper-horizontal");
this.element.addClass("wijmo-wijaccordion-top");
break;
case "right":
this._headerCornerOpened = "ui-corner-left";
this._contentCornerOpened = "ui-corner-right";
this._triangleIconOpened = o.wijCSS.iconArrowRight;
this._triangleIconClosed = o.wijCSS.iconArrowDown;
rightToLeft = false;
this.element.addClass("ui-helper-horizontal");
this.element.addClass("wijmo-wijaccordion-right");
break;
case "left":
this._headerCornerOpened = "ui-corner-right";
this._contentCornerOpened = "ui-corner-left";
this._triangleIconOpened = o.wijCSS.iconArrowLeft;
this._triangleIconClosed = o.wijCSS.iconArrowDown;
rightToLeft = true;
this.element.addClass("ui-helper-horizontal");
this.element.addClass("wijmo-wijaccordion-left");
break;
default:
//bottom
this._headerCornerOpened = "ui-corner-top";
this._contentCornerOpened = "ui-corner-bottom";
this._triangleIconOpened = o.wijCSS.iconArrowDown;
this._triangleIconClosed = o.wijCSS.iconArrowRight;
rightToLeft = false;
this.element.removeClass("ui-helper-horizontal");
this.element.addClass("wijmo-wijaccordion-bottom");
break;
}
prevIsRightToLeft = this.element.data("rightToLeft");
this.element.data("rightToLeft", rightToLeft);
if(allowDOMChange) {
openedTriangles.addClass(this._triangleIconOpened);
closedTriangles.addClass(this._triangleIconClosed);
openedHeaders.addClass(this._headerCornerOpened);
openedContents.addClass(this._contentCornerOpened);
}
if(allowDOMChange && rightToLeft !== prevIsRightToLeft) {
this.element.children(".wijmo-wijaccordion-header").each(function (index, elem) {
var header = $(this), content;
if(rightToLeft) {
content = header.next(".wijmo-wijaccordion-content");
header.remove();
header.insertAfter(content);
} else {
content = header.prev(".wijmo-wijaccordion-content");
header.remove();
header.insertBefore(content);
}
});
}
};
return wijaccordion;
})(wijmo.wijmoWidget);
accordion.wijaccordion = wijaccordion;
;
var wijaccordion_options = (function () {
function wijaccordion_options() {
/**
* All CSS classes used in widgets that use Mobile theme framework
* @ignore
*/
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body ui-body-c"
};
/**
* Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijaccordion')";
/**
* Sets the animation easing effect that users experience when they switch
* between panes.
* @remarks
* Set this option to false in order to disable easing. This results in a plain, abrupt shift
* from one pane to the next. You can also create custom easing animations using jQuery UI Easings
* Options available for the animation function include:
* down - If true, indicates that the index of the pane should be expanded higher than the index
* of the pane that must be collapsed.
* horizontal - If true, indicates that the accordion have a horizontal
* orientation (when the expandDirection is left or right).
* rightToLeft - If true, indicates that the content element is located
* before the header element (top and left expand direction).
* toShow - jQuery object that contains the content element(s) should be shown.
* toHide - jQuery object that contains the content element(s) should be hidden.
* @example
* //Create your own animation:
* jQuery.wijmo.wijaccordion.animations.custom1 = function (options) {
* this.slide(options, {
* easing: options.down ? "easeOutBounce" : "swing",
* duration: options.down ? 1000 : 200
* });
* }
* $("#accordion3").wijaccordion({
* expandDirection: "right",
* animated: "custom1"
* });
*/
this.animated = 'slide';
/**
* The animation duration in milliseconds.
* @remarks
* @type {number}
* By default, the animation duration value depends on an animation effect specified
* by the animation option.
*/
this.duration = null;
/**
* Determines the event that triggers the accordion to change panes.
* @remarks
* To select multiple events, separate them by a space. Supported events include:
* focus -- The pane opens when you click its header.
* click (default) -- The pane opens when you click its header.
* dblclick -- The pane opens when you double-click its header.
* mousedown -- The pane opens when you press the mouse button over its header.
* mouseup -- The pane opens when you release the mouse button over its header.
* mousemove -- The pane opens when you move the mouse pointer into its header.
* mouseover -- The pane opens when you hover the mouse pointer over its header.
* mouseout -- The pane opens when the mouse pointer leaves its header.
* mouseenter -- The pane opens when the mouse pointer enters its header.
* mouseleave -- The pane opens when the mouse pointer leaves its header.
* select -- The pane opens when you select its header by clicking and then pressing Enter
* submit -- The pane opens when you select its header by clicking and then pressing Enter.
* keydown -- The pane opens when you select its header by clicking and then pressing any key.
* keypress -- The pane opens when you select its header by clicking and then pressing any key.
* keyup -- The pane opens when you select its header by clicking and then pressing and releasing any key.
*/
this.event = "click";
/**
* Determines whether the widget behavior is disabled. If set to true, the
* control appears dimmed and does not respond when clicked.
*/
this.disabled = false;
/**
* Determines the direction in which the content area of the control expands.
* @remarks
* Available values include: top, right, bottom, and left.
*/
this.expandDirection = "bottom";
/**
* Determines the selector for the header element.
* @remarks
* Set this option to put header and content elements inside the HTML tags of your choice.
* By default, the header is the first child after an <LI> element, and the content is
* the second child html markup.
*/
this.header = "> li > :first-child,> :not(li):even";
/**
* Determines whether clicking a header closes the current pane before opening the new one.
* @remarks
* Setting this value to false causes the headers to act as toggles for opening and
* closing the panes, leaving all previously clicked panes open until you click them again.
*/
this.requireOpenedPane = true;
/**
* Gets or sets the zero-based index of the accordion pane to show expanded initially.
* @remarks
* By default, the first pane is expanded. A setting of -1 specifies that no pane
* is expanded initially, if you also set the requireOpenedPane option to false.
*/
this.selectedIndex = 0;
}
return wijaccordion_options;
})();
wijaccordion.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijaccordion_options());
$.wijmo.registerWidget(widgetName, wijaccordion.prototype);
$.extend($.wijmo.wijaccordion, {
animations: {
slide: function (options, additions) {
options = $.extend({
easing: "swing",
duration: 300
}, options, additions);
var simpleShowOpts, simpleHideOpts;
if(options.horizontal) {
simpleShowOpts = {
width: "show"
};
simpleHideOpts = {
width: "hide"
};
} else {
simpleShowOpts = {
height: "show"
};
simpleHideOpts = {
height: "hide"
};
}
if(!options.toHide.size()) {
options.toShow.stop(true, true).animate(simpleShowOpts, options);
return;
}
if(!options.toShow.size()) {
options.toHide.stop(true, true).animate(simpleHideOpts, options);
return;
}
var overflow = options.toShow.css('overflow'), percentDone = 0, showProps = {
}, hideProps = {
}, toShowCssProps, fxAttrs = options.horizontal ? [
"width",
"paddingLeft",
"paddingRight"
] : [
"height",
"paddingTop",
"paddingBottom"
], originalWidth, s = options.toShow;
// fix width/height before calculating height/width of hidden element
if(options.horizontal) {
originalWidth = s[0].style.height;
s.height(parseInt(s.parent().height(), 10) - parseInt(s.css("paddingTop"), 10) - parseInt(s.css("paddingBottom"), 10) - (parseInt(s.css("borderTopWidth"), 10) || 0) - (parseInt(s.css("borderBottomWidth"), 10) || 0));
} else {
originalWidth = s[0].style.width;
s.width(parseInt(s.parent().width(), 10) - parseInt(s.css("paddingLeft"), 10) - parseInt(s.css("paddingRight"), 10) - (parseInt(s.css("borderLeftWidth"), 10) || 0) - (parseInt(s.css("borderRightWidth"), 10) || 0));
}
$.each(fxAttrs, function (i, prop) {
hideProps[prop] = "hide";
var parts = ('' + $.css(options.toShow[0], prop)).match(/^([\d+-.]+)(.*)$/);
showProps[prop] = {
value: parts ? parts[1] : "0",
unit: parts ? (parts[2] || "px") : "px"
};
});
if(options.horizontal) {
toShowCssProps = {
width: 0,
overflow: "hidden"
};
} else {
toShowCssProps = {
height: 0,
overflow: "hidden"
};
}
options.toShow.css(toShowCssProps).stop(true, true).show();
options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").stop(true, true).animate(hideProps, {
step: function (now, settings) {
var val;
if(settings.prop === options.horizontal ? "width" : "height") {
percentDone = (settings.end - settings.start === 0) ? 0 : (settings.now - settings.start) / (settings.end - settings.start);
}
val = (percentDone * showProps[settings.prop].value);
if(val < 0) {
//fix for 16943:
val = 0;
}
options.toShow[0].style[settings.prop] = val + showProps[settings.prop].unit;
},
duration: options.duration,
easing: options.easing,
complete: function () {
if(!options.autoHeight) {
options.toShow.css(options.horizontal ? "width" : "height", "");
}
options.toShow.css(options.horizontal ? "height" : "width", originalWidth);
options.toShow.css({
overflow: overflow
});
options.complete();
}
});
},
bounceslide: function (options) {
this.slide(options, {
easing: options.down ? "easeOutBounce" : "swing",
duration: options.down ? 1000 : 200
});
}
}
});
})(wijmo.accordion || (wijmo.accordion = {}));
var accordion = wijmo.accordion;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
/// <reference path="../wijutil/jquery.wijmo.wijutil.ts"/>
/// <reference path="../Base/jquery.wijmo.widget.ts"/>
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.position.js
*
*/
$.fn.extend({
getBounds: function () {
return $.extend({
}, $(this).offset(), {
width: $(this).outerWidth(true),
height: $(this).outerHeight(true)
});
},
setBounds: function (bounds) {
$(this).css({
'left': bounds.left,
'top': bounds.top
}).width(bounds.width).height(bounds.height);
return this;
},
getMaxZIndex: function () {
var max = (($(this).css('z-index') == 'auto') ? 0 : $(this).css('z-index')) * 1;
$(this).siblings().each(function (i, e) {
max = Math.max(max, (($(e).css('z-index') == 'auto') ? 0 : $(e).css('z-index')) * 1);
});
return Math.max(max, $(this).zIndex());
}
});
var wijmo;
(function (wijmo) {
(function (popup) {
/** @widget */
var wijpopup = (function (_super) {
__extends(wijpopup, _super);
function wijpopup() {
_super.apply(this, arguments);
}
wijpopup.prototype._init = function () {
this.elementZIndex = this.element.zIndex();
if(!!this.options.ensureOutermost) {
var root = $('form');
if(root.length === 0) {
root = $(document.body);
}
this.element.appendTo(root);
}
this.element.data('visible.wijpopup', false);
this.element.css('position', "absolute");
this.element.position({
of: $(document.body)
});
this.element.hide();
};
wijpopup.prototype._setOption = function (key, value) {
_super.prototype._setOption.call(this, key, value);
if(key === 'autoHide') {
var visible = this.isVisible();
this.hide();
if(visible) {
this.show();
}
}
};
wijpopup.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
_super.prototype.destroy.call(this);
if(this.isVisible()) {
this.hide();
}
if($.browser.msie && (parseInt($.browser.version) < 7)) {
var jFrame = this.element.data('backframe.wijpopup');
if(!jFrame) {
jFrame.remove();
}
}
var self = this;
this.element.unbind('.wijpopup');
$.each([
"visible",
"backframe",
"animating",
"width"
], function (i, prefix) {
self.element.removeData(prefix + ".wijpopup");
});
};
wijpopup.prototype.isVisible = /** Determines whether the element is visible. */
function () {
return (!!this.element.data('visible.wijpopup') && this.element.is(':visible'));
};
wijpopup.prototype.isAnimating = /** @ignore */
function () {
return !!this.element.data("animating.wijpopup");
};
wijpopup.prototype.show = /** Popups the element.
* Position is an optional argument, it is the options object used in jquery.ui.position.
* @param {?object} position An optional argument, it is the options object used in jquery.ui.position.
*/
function (position) {
var self = this;
this._setPosition(position);
if(this.isVisible()) {
return;
}
if(this._trigger('showing') === false) {
return;
}
if(this.options.autoHide) {
window.setTimeout(function () {
$(document).bind('mouseup.wijpopup', $.proxy(self._onDocMouseUp, self));
}, 0);
}
var effect = this.options.showEffect || "show";
var duration = this.options.showDuration || 300;
var ops = this.options.showOptions || {
};
this.element.data("animating.wijpopup", true);
if($.effects && $.effects.effect[effect]) {
this.element.show(effect, ops, duration, $.proxy(this._showCompleted, this));
} else {
this.element[effect]((effect === 'show' ? null : duration), $.proxy(this._showCompleted, this));
}
if(!effect || !duration || effect === 'show' || duration <= 0) {
this._showCompleted();
}
};
wijpopup.prototype._showCompleted = function () {
this.element.removeData("animating.wijpopup");
this.element.data('visible.wijpopup', true);
this._trigger('shown');
};
wijpopup.prototype.showAt = /** Popups the element at specified absolute position related to document.
* @param {number} x The x coordinate at which to show the popup.
* @param {number} y The y coordinate at which to show the popup.
* @example
* // set the popup position is "100, 100" that related to document.
* $(".selector").wijpopup('showAt', 100, 100);
*/
function (x, y) {
this.show({
my: //jquery 1.10: offset has removed
//my: 'left top',
'left+' + x + ' top+' + y,
at: 'left top',
of: document.body
});
//,
//jquery 1.10: offset has removed
//offset: '' + x + ' ' + y
};
wijpopup.prototype.hide = /** Hides the element. */
function () {
if(!this.isVisible()) {
return;
}
if(this._trigger('hiding') === false) {
return;
}
$(document).unbind('mouseup.wijpopup');
var effect = this.options.hideEffect || "hide";
var duration = this.options.hideDuration || 300;
var ops = this.options.hideOptions || {
};
this.element.data("animating.wijpopup", true);
if($.effects && $.effects.effect[effect]) {
this.element.hide(effect, ops, duration, $.proxy(this._hideCompleted, this));
} else {
this.element[effect]((effect === 'hide' ? null : duration), $.proxy(this._hideCompleted, this));
}
if(!effect || !duration || effect === 'hide' || duration <= 0) {
this._hideCompleted();
}
};
wijpopup.prototype._hideCompleted = function () {
if(this.element.data('width.wijpopup') !== undefined) {
this.element.width(this.element.data('width.wijpopup'));
this.element.removeData('width.wijpopup');
}
this.element.unbind('move.wijpopup');
this.element.removeData("animating.wijpopup");
if($.browser.msie && (parseInt($.browser.version) < 7)) {
var jFrame = this.element.data('backframe.wijpopup');
if(jFrame) {
jFrame.hide();
}
}
this._trigger('hidden');
};
wijpopup.prototype._onDocMouseUp = function (e) {
var srcElement = e.target ? e.target : e.srcElement;
if(this.isVisible() && !!this.options.autoHide) {
if(srcElement != this.element.get(0) && $(srcElement).parents().index(this.element) < 0) {
this.hide();
}
}
};
wijpopup.prototype._onMove = function (e) {
var jFrame = this.element.data('backframe.wijpopup');
if(jFrame) {
this.element.before(jFrame);
jFrame.css({
'top': this.element.css('top'),
'left': this.element.css('left')
});
}
};
wijpopup.prototype._addBackgroundIFrame = function () {
if($.browser.msie && (parseInt($.browser.version) < 7)) {
var jFrame = this.element.data('backframe.wijpopup');
if(!jFrame) {
jFrame = jQuery('<iframe/>').css({
'position': 'absolute',
'display': 'none',
'filter': 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'
}).attr({
'src': 'javascript:\'<html></html>\';',
'scrolling': 'no',
'frameborder': '0',
'tabIndex ': -1
});
this.element.before(jFrame);
this.element.data('backframe.wijpopup', jFrame);
this.element.bind('move.wijpopup', $.proxy(this._onMove, this));
}
jFrame.setBounds(this.element.getBounds());
jFrame.css({
'display': 'block',
'left': this.element.css('left'),
'top': this.element.css('top'),
'z-index': this.element.css('z-index') - 1
});
}
};
wijpopup.prototype._setZIndex = function (index) {
this.element.css('z-index', index);
var jFrame = this.element.data('backframe.wijpopup');
if(jFrame) {
jFrame.css('z-index', (this.element.css('z-index')) - 1);
}
};
wijpopup.prototype._setPosition = function (position) {
var visible = this.element.is(':visible'), of;
this.element.show();
this.element.position($.extend({
}, this.options.position, position ? position : {
}));
if(!visible) {
this.element.hide();
}
if(position) {
of = position.of;
}
if(!of) {
of = this.options.position.of;
}
this._addBackgroundIFrame();
var zIndex = Math.max(1000, this.elementZIndex);
if(of) {
zIndex = Math.max(zIndex, $(of).getMaxZIndex());
}
this._setZIndex(zIndex + 10);
this._trigger('posChanged');
};
return wijpopup;
})(wijmo.JQueryUIWidget);
popup.wijpopup = wijpopup;
var wijpopup_options = (function () {
function wijpopup_options() {
/** Determines if the element's parent element is the outermost element.
* @remarks
* If true, the element's parent element will be changed to
* the body or outermost form element.
*/
this.ensureOutermost = false;
/** Specifies the effect to be used when the popup is shown.
* @remarks
* This allows you to use a different effect when you show the popup
* than when you hide the popup.(See also hideEffect.) Possible values
* include 'blind', 'clip', 'drop', 'fade', 'fold', 'slide', and 'pulsate'.
* See the jQuery UI / Effects page for more information.
*/
this.showEffect = 'show';
/** Specifies the object/hash including specific options for the show effect.
* @type {object}
* @remarks
* See the option parameters used by the jQuery UI show effect for more information.
* @example
* // set the show effect's direction.
* $(".selector").wijpopup({ showOptions: {direction: 'up' });
*/
this.showOptions = {
};
/** A value that indicates the number of milliseconds it takes for the
* indicated animation effect to completely show the popup.
* @remarks
* This allows you to use a different number of milliseconds when you
* show the popup than when you hide the popup.(See also hideDuration.)
*/
this.showDuration = 300;
/** Specifies the effect to be used when the popup is hidden.
* @remarks
* This allows you to use a different effect when you show the popup than
* when you hide the popup.(See also showEffect.)
* Possible values include 'blind', 'clip', 'drop', 'fade', 'fold', 'slide',
* and 'pulsate'.See the jQuery UI / Effects page for more information.
*/
this.hideEffect = 'hide';
/** Specifies the object/hash including specific options for the hide effect.
* @remarks
* See the option parameters used by the jQuery UI hide effect for more information.
* @example
* // set the hide effect's direction.
* $(".selector").wijpopup({ hideOptions: {direction: 'up' });
*/
this.hideOptions = {
};
/** A value that indicates the number of milliseconds it takes for the
* indicated animation effect to completely hide the popup.
* @remarks
* This allows you to use a different number of milliseconds when
* you show the popup than when you hide the popup.(See also showDuration.)
*/
this.hideDuration = 100;
/** Determines whether to automatically hide the popup when clicking outside the element.
* @remarks
* If true, the popup will be automatically hidden when another element is selected.
* If false (default), the popup will remain visible until hidden with the hide method.
*/
this.autoHide = false;
/** Options for positioning the element, please see jquery.ui.position for possible options.
* @type {object}
* @example
* // positioning the element, located on "#TextBox1" and up offset is 4
* $(".selector").wijpopup({ position:{ of: $('#TextBox1'), offset: '0 4' }});
*/
this.position = {
at: 'left bottom',
my: 'left top'
};
/** The showing event handler.
* A function called before the element is shown. Cancellable.
* @remarks
* This is a cancelable event.You can set data.cancel = true to cancel the element to be shown.
* @event
*/
this.showing = null;
/** The shown event handler. A function called after the element is shown.
* @event
*/
this.shown = null;
/** The hiding event handler.
* A function called before the element is hidden. Cancellable.
* @remarks
* This is a cancelable event. You can set data.cancel = true to cancel the element to be hidden.
* @event
* @dataKey {boolean} cancel Cancel the element to be hidden if true.
*/
this.hiding = null;
/** The hidden event handler. A function called after the element is hidden.
* @event
*/
this.hidden = null;
/** The posChanged event handler.
* A function called when the position of the element is changed.
* @event
*/
this.posChanged = null;
}
return wijpopup_options;
})();
;
wijpopup.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijpopup_options());
$.wijmo.registerWidget("wijpopup", wijpopup.prototype);
})(wijmo.popup || (wijmo.popup = {}));
var popup = wijmo.popup;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts"/>
/*globals window,document,jQuery*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.resizable.js
* jquery.ui.mouse.js
* jquery.wijmo.wijutil.js
*
*/
(function (superpanel) {
"use strict";
var $ = jQuery;
var wijsuperpanel_options = (function () {
function wijsuperpanel_options() {
/**
* wijMobileCSS.
* @ignore
*/
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body-c",
stateDefault: "ui-btn-up-c",
stateHover: "ui-btn-down-c",
stateActive: "ui-btn-down-c"
};
/**
* Selector option for auto self initialization.
* This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijsuperpanel')";
/** The value determines whether the wijsuperpanel can be resized.
*/
this.allowResize = false;
/** This value determines whether wijsuperpanel is automatically refreshed when the content size or wijsuperpanel size are changed.
* Set this value to true if you load images in the wijsuperpanel without specifying their sizes.
*/
this.autoRefresh = false;
/** The animationOptions function determines whether or not the animation is shown. If true, it defines the animation effect and controls other aspects of the widget's animation, such as duration, queue, and easing.
* @example
* $('#superPanel').wijsuperpanel({
* animationOptions: {
* disabled: false,
* duration: 1000,
* easing: easeInQuad
* }
* });
* @remarks
* Set this options to null to disable animation.
*/
this.animationOptions = {
queue: /**
* This value determines whether to queue animation operations.
* @type {boolean}
*/
false,
disabled: /** This value determines whether to disable animation operations.
* @type {boolean}
*/
false,
duration: /** This value sets the animation duration of the scrolling animation.
* @type {number}
*/
250,
easing: /** Sets the type of animation easing effect that users experience as the panel is scrolled. You can create custom easing animations using jQuery UI Easings.
* @type {string}
*/
undefined
};
/** The hScrollerActivating event handler.
* A function called when horizontal scrollbar is activating.
* @event
* @dataKey {string} direction The direction of the scrolling action.
* Possible values: "v"(vertical) and "h"(horizontal).
* @dataKey {object} targetBarLen The width of the horizontal scrollbar.
* @dataKey {object} contentLength The width of the content.
*/
this.hScrollerActivating = null;
/**
*This option contains horizontal scroller settings.
*/
this.hScroller = {
scrollBarPosition: /*
* This value determines the position of the horizontal scroll bar.
* @type {string}
* @remarks
* Possible options are "bottom" and "top".
* "bottom" - The horizontal scroll bar is placed at the bottom of
* the content area.
* "top" - The horizontal scroll bar is placed at the top of the
*content area.
*/
"bottom",
scrollBarVisibility: /** This value determines the visibility of the horizontal scroll bar.
* @type {string}
* @remarks
* Possible options are "auto", "visible" and "hidden".
* "auto" - Shows the scroll when needed.
* "visible" - The Scroll bar is always visible. It is disabled
* when not needed.
* "hidden" - The Scroll bar is hidden.
*/
"auto",
scrollMode: /** This value determines the scroll mode of horizontal scrolling.
* @type {string}
* @remarks
* Possible options are "scrollBar", "buttons", "buttonsHover"
* and "edge".
* "scrollBar" - Scroll bars are used for scrolling.
* "buttons" - Scroll buttons are used for scrolling.
* Scrolling occurs only when scroll buttons are clicked.
* "buttonsHover" - Scroll buttons are used for scrolling.
* Scrolling occurs only when scroll buttons are hovered.
* "edge" - Scrolling occurs when the mouse is moving to the edge
* of the content area.
* Scroll modes can be combined with each other.
* For example, scrollMode: "scrollbar,scrollbuttons" will enable
* both a scrollbar and scroll buttons.
*/
"scrollBar",
scrollValue: /** This value determines the horizontal scrolling position of
* wijsuperpanel.
* @type {number}
*/
null,
scrollMax: /** This value sets the maximum value of the horizontal scroller.
* @type {number}
*/
100,
scrollMin: /** This value sets the minimum value of the horizontal scroller.
* @type {number}
*/
0,
scrollLargeChange: /** This value sets the large change value of the horizontal scroller.
* @type {number}
* @remarks
* Wijsuperpanel will scroll a large change when a user clicks on the
* tracks of scroll bars or presses left or right arrow keys on the
* keyboard with the shift key down.
* When scrollLargeChange is null, wijsuperpanel will scroll
* the width of content.
*/
null,
scrollSmallChange: /** This value sets the small change value of the horizontal scroller.
* @type {number}
* @remarks
* Wijsuperpanel will scroll a small change when a user clicks on
* the arrows of scroll bars, clicks or hovers scroll buttons,
* presses left or right arrow keys on keyboard,
* and hovers on the edge of wijsuperpanel.
* When scrollSmallChange is null, wijsuperpanel will scroll half of
* the width of content.
*/
null,
scrollMinDragLength: /** This value sets the minimum length, in pixel, of the horizontal
* scroll bar thumb button.
* @type {number}
*/
6,
increaseButtonPosition: /** This is an object that determines the increase button position.
* @type {object}
*/
/* @remarks
* Please look at the options for jquery.ui.position.js for more info.
*/
null,
decreaseButtonPosition: /** This is an object that determines the decrease button position.
* @type {object}
*/
null,
hoverEdgeSpan: /** This value sets the width, in pixels, of the horizontal hovering edge which will trigger the horizontal scrolling.
* @type {number}
*/
20,
firstStepChangeFix: /** This number specifies the value to add to smallchange or largechange when scrolling the first step (scrolling from scrollMin).
* @type {number}
*/
0
};
/** This value determines whether wijsuperpanel provides keyboard scrolling support.
*/
this.keyboardSupport = false;
/** This value determines the time interval to call the scrolling function when doing continuous scrolling.
*/
this.keyDownInterval = 100;
/** This value determines whether wijsuperpanel has mouse wheel support.
* @remarks
* Mouse wheel plugin is needed to support this feature.
*/
this.mouseWheelSupport = true;
/** This value determines whether to fire the mouse wheel event when wijsuperpanel is scrolled to the end.
*/
this.bubbleScrollingEvent = true;
/** This option determines the behavior of the resizable widget. See the JQuery UI resizable options document for more information.
* @type {object}
*/
this.resizableOptions = {
handles: "all",
helper: "ui-widget-content wijmo-wijsuperpanel-helper"
};
/** Resized event handler. This function gets called when the resized event is fired.
* @event
*/
this.resized = null;
/** This function gets called when the user stops dragging the thumb buttons of the scrollbars.
* @event
* @dataKey {string} dir The direction of the scrolling action.
* Possible values: "v"(vertical) and "h"(horizontal).
*/
this.dragStop = null;
/** This function gets called after panel is painted.
* @event
*/
this.painted = null;
/** Scrolling event handler. A function called before scrolling occurs.
* @event
* @dataKey {string} dir The direction of the scrolling action.
* Possible values: "v"(vertical) and "h"(horizontal).
* @dataKey {number} oldValue The scrollValue before scrolling occurs.
* @dataKey {number} newValue The scrollValue after scrolling occurs.
* @dataKey {object} beforePosition The position of content before scrolling occurs.
*/
this.scrolling = null;
/** Scroll event handler. This function is called before scrolling occurs.
* @event
* @dataKey {string} dir The direction of the scrolling action.
* Possible values: "v"(vertical) and "h"(horizontal).
* @dataKey {object} animationOptions TThe options of the animation which scrolling uses.
* @dataKey {object} position The position of content after scrolling occurs.
*/
this.scroll = null;
/** Scrolled event handler. This function gets called after scrolling occurs.
* @event
* @dataKey {string} dir The direction of the scrolling action.
* Possible values: "v"(vertical) and "h"(horizontal).
* @dataKey {object} beforePosition The position of content before scrolling occurs.
* @dataKey {object} afterPosition The position of content after scrolling occurs.
*/
this.scrolled = null;
/** This value determines whether to show the rounded corner of wijsuperpanel.
* @type {boolean}
*/
this.showRounder = true;
/** A function called when the vertical scrollbar is activating.
* @event
* @dataKey {string} direction The direction of the scrolling action.
* Possible values: "v"(vertical) and "h"(horizontal).
* @dataKey {object} targetBarLen The width of the vertical scrollbar.
* @dataKey {object} contentLength The width of the content.
*/
this.vScrollerActivating = null;
/** This option contains vertical scroller settings.
*/
this.vScroller = {
scrollBarPosition: /**
* This value determines the position of the vertical scroll bar.
* @type {String}
* @remarks
* Possible options are: "left", "right".
* "left" - The vertical scroll bar is placed at the
* left side of the content area.
* "right" - The vertical scroll bar is placed at the
* right side of the content area.
*/
"right",
scrollBarVisibility: /** This value determines the visibility of the vertical scroll bar.
* Default.: "auto".
* @type {string}
* @remarks
* Possible options are "auto", "visible" and "hidden".
* "auto" - Shows the scroll bar when needed.
* "visible" - Scroll bar will always be visible.
* It"s disabled when not needed.
* "hidden" - Scroll bar will be shown.
*/
"auto",
scrollMode: /** This value determines the scroll mode of vertical scrolling.
* @type {string}
* @remarks
* Possible options are: "scrollBar", "buttons",
* "buttonsHover" and "edge".
* "scrollBar" - Scroll bars are used for scrolling.
* "buttons" - Scroll buttons are used for scrolling.
* Scrolling occurs only when scroll buttons are clicked.
* "buttonsHover" - Scroll buttons are used for scrolling.
* Scrolling occurs only when scroll buttons are hovered.
* "edge" - Scrolling occurs when the mouse is moving to
* the edge of the content area.
* Scroll modes can be combined with each other.
* For example, vScrollMode: "scrollbar,scrollbuttons" will enable
* both a scrollbar and scroll buttons.
*/
"scrollBar",
scrollValue: /** This number determines the vertical scrolling position of
* wijsuperpanel.
* @type {number}
*/
null,
scrollMax: /** This number sets the maximum value of the vertical scroller.
* @type {number}
*/
100,
scrollMin: /** This number sets the minimum value of the vertical scroller.
* @type {number}
*/
0,
scrollLargeChange: /** This value sets the large change value of the vertical scroller.
* @type {number}
* @remarks
* wijsuperpanel will scroll a large change when a user clicks
* on the tracks of scroll bars or presses left or right arrow keys
* on the keyboard with the shift key down.
* When scrollLargeChange is null, wijsuperpanel
* will scroll the height of content.
*/
null,
scrollSmallChange: /** This value sets the small change value of the vertical scroller.
* @type {number}
* @remarks
* wijsuperpanel will scroll a small change when a user clicks on the
* arrows of scroll bars, clicks or hovers scroll buttons, presses left
* or right arrow keys on keyboard, and hovers on the edge of
* wijsuperpanel.
* When scrollSmallChange is null, wijsuperpanel will scroll half of
* the height of content.
*/
null,
scrollMinDragLength: /** This value sets the minimum length, in pixel, of the vertical
* scroll bar thumb button.
* @type {number}
*/
6,
increaseButtonPosition: /** This object determines the increase button position.
* @type {object}
* @remarks
* Please look at the options for jquery.ui.position.js for more info.
*/
null,
decreaseButtonPosition: /** This object determines the decrease button position.
* @type {object}
* @remarks
* Please look at the options for jquery.ui.position.js for more info.
*/
null,
hoverEdgeSpan: /** This value sets the width of the horizontal hovering edge which will trigger the vertical scrolling.
* @type {number}
*/
20,
firstStepChangeFix: /** This number specifies the value to add to smallchange or largechange when scrolling the first step (scrolling from scrollMin).
* @type {number}
*/
0
};
/** Determines if use custom scrolling.
*/
this.customScrolling = false;
/** Determines if the native scroll events should be listened.
*/
this.listenContentScroll = false;
}
return wijsuperpanel_options;
})();
/** @widget */
var wijsuperpanel = (function (_super) {
__extends(wijsuperpanel, _super);
function wijsuperpanel() {
_super.apply(this, arguments);
}
wijsuperpanel.prototype.destroy = /**
* Destroys wijsuperpanel widget and reset the DOM element.
*/
function () {
};
wijsuperpanel.prototype.needToScroll = /**
* Determine whether scoll the child DOM element to view
* need to scroll the scroll bar
* @param {DOMElement} child The child to scroll to.
*/
function (child1) {
};
wijsuperpanel.prototype.scrollChildIntoView = /**
* Scroll children DOM element to view.
* @param {DOMElement} child The child to scroll to.
*/
function (child1) {
};
wijsuperpanel.prototype.hScrollTo = /**
* Scroll to horizontal position.
* @param {number} x The position to scroll to.
*/
function (x) {
};
wijsuperpanel.prototype.vScrollTo = /**
* Scroll to vertical position.
* @param {number} y The position to scroll to.
*/
function (y) {
};
wijsuperpanel.prototype.scrollPxToValue = /**
* Convert pixel to scroll value.
* For example, wijsuperpanel scrolled 50px
* which is value 1 after conversion.
* @param {number} px Length of scrolling.
* @param {string} dir Scrolling direction. Options are: "h" and "v".
*/
function (px, dir) {
};
wijsuperpanel.prototype.scrollTo = /**
* Scroll to the specified position.
* which is value 1 after conversion.
* @param {number} x Horizontal position to scroll to.
* @param {number} y Vertical position to scroll to.
*/
function (x, y) {
};
wijsuperpanel.prototype.refresh = /**
* Refreshes wijsuperpanel.
* Needs to be called after content being changed.
* @returns {boolean} Returns true if it is successful, else returns false.
*/
function () {
};
wijsuperpanel.prototype.paintPanel = /**
* Refreshes wijsuperpanel.
* Needs to be called after content being changed.
* @returns {boolean} Returns true if it is successful, else returns false.
*/
function (unfocus) {
};
wijsuperpanel.prototype.getContentElement = /**
* Gets the content element of wijsuperpanel.
* @example $("selector").wijsuperpanel("getContentElement");
* @returns {jQuery}
*/
function () {
};
return wijsuperpanel;
})(wijmo.wijmoWidget);
superpanel.wijsuperpanel = wijsuperpanel;
var superpanel_widget;
if(!$.support.isTouchEnabled || !$.support.isTouchEnabled()) {
var scrollerHandle = "wijmo-wijsuperpanel-handle", hbarContainerCSS = "wijmo-wijsuperpanel-hbarcontainer", vbarContainerCSS = "wijmo-wijsuperpanel-vbarcontainer", activeCss = "", innerElementHtml = "<div class='wijmo-wijsuperpanel-statecontainer'>" + "<div class='wijmo-wijsuperpanel-contentwrapper'>" + "<div class='wijmo-wijsuperpanel-templateouterwrapper'></div>" + "</div>" + "</div>", hbarHtml = "<div class='wijmo-wijsuperpanel-hbarcontainer {header}'>" + "<div class='wijmo-wijsuperpanel-handle {stateDefault} {cornerAll}'>" + "<span class='{icon} {iconVGripSolid}'></span></div>" + "<div class='wijmo-wijsuperpanel-hbar-buttonleft {stateDefault} {cornerBL}'>" + "<span class='{icon} {iconArrowLeft}'></span></div>" + "<div class='wijmo-wijsuperpanel-hbar-buttonright {stateDefault} {cornerBR}'>" + "<span class='{icon} {iconArrowRight}'></span></div>" + "</div>", vbarHtml = "<div class='wijmo-wijsuperpanel-vbarcontainer {header}'>" + "<div class='wijmo-wijsuperpanel-handle {stateDefault} {cornerAll}'>" + "<span class='{icon} {iconHGripSolid}'></span></div>" + "<div class='wijmo-wijsuperpanel-vbar-buttontop {stateDefault} {cornerTR}'>" + "<span class='{icon} {iconArrowUp}'></span></div>" + "<div class='wijmo-wijsuperpanel-vbar-buttonbottom {stateDefault} {cornerBR}'>" + "<span class='{icon} {iconArrowDown}'></span></div>" + "</div>", hButtons = "<div class='{stateDefault} wijmo-wijsuperpanel-button " + "wijmo-wijsuperpanel-buttonleft'><span class='{icon} {iconCaratLeft}'>" + "</span></div><div class='{stateDefault}" + " wijmo-wijsuperpanel-button wijmo-wijsuperpanel-buttonright'>" + "<span class='{icon} {iconCaratRight}'></span></div>", vButtons = "<div class='{stateDefault} wijmo-wijsuperpanel-button" + " wijmo-wijsuperpanel-buttontop'><span class='{icon} {iconCaratUp}'>" + "</span></div><div class='{stateDefault} wijmo-wijsuperpanel-button" + " wijmo-wijsuperpanel-buttonbottom'><span class='{icon} {iconCaratDown}'>" + " </span></div>";
wijsuperpanel.prototype = $.extend(true, {
}, $.Widget.prototype, {
widgetEventPrefix: "wijsuperpanel",
_setOption: function (key, value) {
var self = this, o = self.options, f = self._fields(), hd = f.hbarDrag, vd = f.vbarDrag, r = f.resizer;
// override existing
if(key === "animationOptions") {
value = $.extend(o.animationOptions, value);
} else if(key === "hScroller") {
if(value.scrollLargeChange !== undefined && value.scrollLargeChange !== null) {
self._autoHLarge = false;
}
value = $.extend(o.hScroller, value);
self.refresh();
} else if(key === "vScroller") {
if(value.scrollLargeChange !== undefined && value.scrollLargeChange !== null) {
self._autoVLarge = false;
}
value = $.extend(o.vScroller, value);
self.refresh();
} else if(key === "resizableOptions") {
value = $.extend(self.resizableOptions, value);
}
$.Widget.prototype._setOption.apply(self, arguments);
if($.isPlainObject(value)) {
self.options[key] = value;
}
switch(key) {
case "allowResize":
self._initResizer();
break;
case "disabled":
if(value) {
if(hd !== undefined) {
hd.draggable("disable");
}
if(vd !== undefined) {
vd.draggable("disable");
}
if(r !== undefined) {
r.resizable("disable");
}
} else {
if(hd !== undefined) {
hd.draggable("enable");
}
if(vd !== undefined) {
vd.draggable("enable");
}
if(r !== undefined) {
r.resizable("enable");
}
}
break;
case "mouseWheelSupport":
case "keyboardSupport":
self._bindElementEvents(self, f, self.element, o);
break;
}
return self;
},
_create: function () {
var self = this, o = self.options;
o.vScroller.dir = "v";
o.hScroller.dir = "h";
self._initMarkup();
//Add support for touch
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
self.paintPanel();
self._initResizer();
if(self.options.disabled) {
self.disable();
}
self._detectAutoRefresh();
if(o.listenContentScroll) {
self._listenContentScroll();
}
//update for visibility change
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
self.refresh();
}, "wijsuperpanel");
}
},
_initMarkup: function () {
var css = this.options.wijCSS, reg = /\{(\w+?)\}/ig, callback = function (i, g1) {
return css[g1];
};
activeCss = css.stateActive;
hbarHtml = hbarHtml.replace(reg, callback);
vbarHtml = vbarHtml.replace(reg, callback);
hButtons = hButtons.replace(reg, callback);
vButtons = vButtons.replace(reg, callback);
},
_detectAutoRefresh: function () {
// register with auto fresh.
var self = this, panels = $.wijmo.wijsuperpanel.panels;
if(panels === undefined) {
panels = [];
$.wijmo.wijsuperpanel.panels = panels;
}
panels.push(self);
// start timer to monitor content.
if(self.options.autoRefresh) {
if(!$.wijmo.wijsuperpanel.setAutoRefreshInterval) {
$.wijmo.wijsuperpanel.setAutoRefreshInterval = self._setAutoRefreshInterval;
$.wijmo.wijsuperpanel.setAutoRefreshInterval();
}
}
},
_setAutoRefreshInterval: function () {
var interval = $.wijmo.wijsuperpanel.autoRereshInterval, panels = $.wijmo.wijsuperpanel.panels, intervalID = window.setInterval(function () {
window.clearInterval(intervalID);
var count = panels.length, toContinue = false, i, panel, mainElement, autoRefresh, ele, mark;
for(i = 0; i < count; i++) {
panel = panels[i];
mainElement = panel.element[0];
autoRefresh = panel.options.autoRefresh;
if(autoRefresh) {
toContinue = true;
}
ele = panel.getContentElement();
mark = panel._paintedMark;
if(panel.options.autoRefresh && ele.is(":visible") && (mark === undefined || mark.width !== ele[0].offsetWidth || mark.height !== ele[0].offsetHeight || mark.mainWidth !== mainElement.offsetWidth || mark.mainHeight !== mainElement.offsetHeight)) {
panel.paintPanel();
}
}
if(toContinue) {
window.setTimeout($.wijmo.wijsuperpanel.setAutoRefreshInterval, 0);
}
}, interval === undefined ? 500 : interval);
},
destroy: /**
* Destroys wijsuperpanel widget and reset the DOM element.
*/
function () {
var self = this, f = self._fields(), ele = self.element, buttons, templateWrapper, wijCSS = self.options.wijCSS;
// remove this widget from panels array.
$.wijmo.wijsuperpanel.panels = $.grep($.wijmo.wijsuperpanel.panels, function (value) {
return value !== self;
}, false);
if(!f.initialized) {
return;
}
if(self._radiusKey) {
self.element.css(self._radiusKey, "");
}
if(f.intervalID !== undefined) {
window.clearInterval(f.intervalID);
f.intervalID = undefined;
}
// destory widgets
if(f.resizer !== undefined) {
f.resizer.resizable("destroy");
}
if(f.hbarContainer !== undefined) {
f.hbarDrag.remove();
f.hbarContainer.unbind("." + self.widgetName);
}
if(f.vbarContainer !== undefined) {
f.vbarDrag.remove();
f.vbarContainer.unbind("." + self.widgetName);
}
ele.unbind("." + self.widgetName);
f.contentWrapper.unbind("." + self.widgetName);
buttons = f.stateContainer.find(">.wijmo-wijsuperpanel-button");
buttons.unbind("." + self.widgetName);
templateWrapper = f.templateWrapper;
templateWrapper.contents().each(function (index, e) {
ele.append(e);
});
f.stateContainer.remove();
if(f.tabindex) {
ele.removeAttr("tabindex");
}
ele.removeClass([
"wijmo-wijsuperpanel",
wijCSS.widget,
wijCSS.content,
wijCSS.cornerAll
].join(' '));
$.Widget.prototype.destroy.apply(self, arguments);
},
_fields: function () {
var self = this, ele = self.element, key = self.widgetName + "-fields", d = self._fieldsStore;
if(d === undefined) {
d = {
};
ele.data(key, d);
self._fieldsStore = d;
}
return d;
},
_hasMode: function (scroller, mode) {
var modes = scroller.scrollMode.split(",");
modes = $.map(modes, function (n) {
return $.trim(n).toLowerCase();
});
return $.inArray(mode.toLowerCase(), modes) > -1;
},
_bindElementEvents: function (self, f, ele, o) {
// mouse move only edge mode is used.
var hEdge = self._hasMode(o.hScroller, "edge"), vEdge = self._hasMode(o.vScroller, "edge"), wn = self.widgetName;
if(hEdge || vEdge) {
if(self._mousemoveBind === undefined) {
self._mousemoveBind = true;
ele.bind("mousemove." + wn, self, self._contentMouseMove);
ele.bind("mouseleave." + wn, null, function () {
self._clearInterval();
});
}
} else {
ele.unbind("mousemove", self._contentMouseMove);
self._mousemoveBind = undefined;
}
if(o.mouseWheelSupport) {
if(self._mouseWheelBind === undefined) {
self._mouseWheelBind = true;
ele.bind("mousewheel." + wn, self, self._panelMouseWheel);
}
} else {
self.element.unbind("mousewheel", self._panelMouseWheel);
self._mouseWheelBind = undefined;
}
if(o.keyboardSupport) {
if(self._keyboardBind === undefined) {
self._keyboardBind = true;
ele.bind("keydown." + wn, self, self._panelKeyDown);
}
} else {
ele.unbind("keydown", self._panelKeyDown);
self._keyboardBind = undefined;
}
},
_dragStop: function (e, self, dir) {
// Handles mouse drag stop event of thumb button.
var data = {
dragHandle: dir
};
self._trigger("dragStop", e, data);
},
_contentMouseMove: function (e) {
// Handles mouse move event of content area.
// Edge hover scrolling is handled in this method.
var self = e.data, o = self.options, hScroller, vScroller, contentWrapper, f, hMode, vMode, mousePagePosition, off, left, top, hEdge, vEdge, innerHeight, innerWidth, dir;
if(o.disabled) {
return;
}
hScroller = o.hScroller;
vScroller = o.vScroller;
contentWrapper = $(e.currentTarget);
f = self._fields();
hMode = self._hasMode(hScroller, "edge");
vMode = self._hasMode(vScroller, "edge");
self._clearInterval();
mousePagePosition = {
X: e.pageX,
Y: e.pageY
};
off = contentWrapper.offset();
left = off.left;
top = off.top;
left = mousePagePosition.X - left;
top = mousePagePosition.Y - top;
hEdge = hScroller.hoverEdgeSpan;
vEdge = vScroller.hoverEdgeSpan;
innerHeight = contentWrapper.innerHeight();
innerWidth = contentWrapper.innerWidth();
dir = "";
if(hMode) {
if(left < hEdge) {
dir = "left";
}
if(left > (innerWidth - hEdge)) {
dir = "right";
}
}
if(vMode) {
if(top < vEdge) {
dir = "top";
}
if(top > (innerHeight - vEdge)) {
dir = "bottom";
}
}
self._setScrollingInterval(f, dir, self, false);
},
_setScrollingInterval: function (f, dir, self, large) {
var o = self.options;
if(dir.length > 0) {
f.internalFuncID = window.setInterval(function () {
self._doScrolling(dir, self, large);
}, o.keyDownInterval);
}
},
_scrollButtonMouseOver: function (e) {
// Scroll buttons mouse over event handler.
var self = e.data, o = self.options, button;
if(o.disabled) {
return;
}
button = $(e.currentTarget);
if(!button.hasClass(o.wijCSS.stateDisabled)) {
button.bind("mouseout." + self.widgetName, self, self._buttonMouseOut).bind("mousedown." + self.widgetName, self, self._buttonMouseDown).bind("mouseup." + self.widgetName, self, self._buttonMouseUp).addClass(o.wijCSS.stateHover);
self._buttonScroll(button, self, "buttonshover");
}
},
_buttonScroll: function (button, self, mode) {
// Do button scroll.
var dir = "", o = self.options, f = self._fields(), hMode = self._hasMode(o.hScroller, mode), vMode = self._hasMode(o.vScroller, mode);
if(button.hasClass("wijmo-wijsuperpanel-buttonleft") && hMode) {
dir = "left";
} else if(button.hasClass("wijmo-wijsuperpanel-buttonright") && hMode) {
dir = "right";
} else if(button.hasClass("wijmo-wijsuperpanel-buttontop") && vMode) {
dir = "top";
} else if(button.hasClass("wijmo-wijsuperpanel-buttonbottom") && vMode) {
dir = "bottom";
}
if(dir.length > 0) {
self._clearInterval();
self._doScrolling(dir, self, true);
self._setScrollingInterval(f, dir, self, true);
}
},
_listenContentScroll: function () {
var self = this, o = self.options, f = self._fields(), hbarContainer = f.hbarContainer, hbarDrag = f.hbarDrag, vbarContainer = f.vbarContainer, vbarDrag = f.vbarDrag, templateWrapper = f.templateWrapper, contentWrapper = f.contentWrapper, w = contentWrapper.width(), h = contentWrapper.height(), offset = templateWrapper && templateWrapper.offset(), ox = offset && offset.left, oy = offset && offset.top, contentWidth = f.contentWidth, contentHeight = f.contentHeight;
contentWrapper.bind("scroll", function (event) {
var pos = templateWrapper.position(), x = pos.left, y = pos.top;
contentWrapper.scrollTop(0).scrollLeft(0);
templateWrapper.css({
left: x,
top: y
});
if(x <= 0 && x > w - contentWidth) {
o.hScroller.scrollValue = self.scrollPxToValue(-x, "h");
self._scrollDrag("h", hbarContainer, hbarDrag, true);
}
if(y <= 0 && y > h - contentHeight) {
o.vScroller.scrollValue = self.scrollPxToValue(-y, "v");
self._scrollDrag("v", vbarContainer, vbarDrag, true);
}
});
},
_buttonMouseDown: function (e) {
var self = e.data, button, wijCSS = self.options.wijCSS;
if(self.options.disabled) {
return;
}
button = $(e.currentTarget);
if(!button.hasClass(wijCSS.stateDisabled)) {
button.addClass(wijCSS.stateActive);
self._buttonScroll(button, self, "buttons");
}
},
_buttonMouseUp: function (e) {
var self = e.data, button = $(e.currentTarget);
button.removeClass(self.options.wijCSS.stateActive);
self._clearInterval();
},
_buttonMouseOut: function (e) {
var self = e.data, wijCSS = self.options.wijCSS, button = $(e.currentTarget);
button.unbind("mouseout", self._buttonMouseOut).unbind("mousedown", self._buttonMouseDown).unbind("mouseup", self._buttonMouseUp).removeClass(wijCSS.stateHover).removeClass(wijCSS.stateActive);
self._clearInterval();
},
getKeyCodeEnum: /** @ignore */
function () {
if($.ui && $.ui.keyCode) {
return $.ui.keyCode;
}
if($.mobile && $.mobile.keyCode) {
return $.mobile.keyCode;
}
throw "keyCode object is not found";
},
_panelKeyDown: function (e) {
// Key down handler.
var self = e.data, o = self.options, shift, keycode, kCode = self.getKeyCodeEnum();
if(!o.keyboardSupport || o.disabled) {
return;
}
shift = e.shiftKey;
keycode = e.keyCode;
if(keycode === kCode.LEFT) {
self._doScrolling("left", self, shift);
} else if(keycode === kCode.RIGHT) {
self._doScrolling("right", self, shift);
} else if(keycode === kCode.UP) {
self._doScrolling("top", self, shift);
} else if(keycode === kCode.DOWN) {
self._doScrolling("bottom", self, shift);
}
e.stopPropagation();
e.preventDefault();
},
_draggingInternal: function (data, self, scroller, originalElement) {
var dir = scroller.dir, h = dir === "h", key = h ? "left" : "top", left = //the parameter from draggable widget is supposed to
//be used instead of the style property of html element
//left = parseFloat(originalElement[0].style[key].replace("px", "")) -
data.position[key] - self._getScrollContainerPadding(key), track = self._getTrackLen(dir) - //originalElement[h ? "outerWidth" : "outerHeight"](),
originalElement[h ? "outerWidth" : "outerHeight"](true), proportion = left / track, topValue = (scroller.scrollMax - scroller.scrollLargeChange + 1), v = proportion * topValue, arg, scrollValue, val;
if(v < scroller.scrollMin) {
v = scroller.scrollMin;
}
if(v > topValue) {
v = topValue;
}
arg = {
oldValue: scroller.scrollValue,
newValue: v,
dir: dir
};
if(!self._scrolling(true, self, arg)) {
// event is canceled in scrolling.
return;
}
if(self.customScroll) {
val = Math.abs(self.customScroll);
scrollValue = self.scrollPxToValue(val, scroller.dir);
}
scroller.scrollValue = scrollValue || v;
self.customScroll = undefined;
self._setDragAndContentPosition(true, false, dir, "dragging");
},
_dragging: function (e, data, self) {
var o = self.options, originalElement = $(e.target), p = originalElement.parent();
if(p.hasClass(hbarContainerCSS)) {
self._draggingInternal(data, self, o.hScroller, originalElement);
} else {
self._draggingInternal(data, self, o.vScroller, originalElement);
}
},
_panelMouseWheel: function (e, delta) {
var self = e.data, o = self.options, originalElement, dir, onHbar, hScroller, vScroller, scrollEnd;
if(!o.mouseWheelSupport || o.disabled) {
return;
}
//var f = self._fields();
//var scrollerWrapper = f.stateContainer;
//var hbarContainer = f.hbarContainer;
originalElement = $(e.srcElement || e.originalEvent.target);
dir = "";
onHbar = originalElement.closest("." + hbarContainerCSS, self.element).size() > 0;
hScroller = o.hScroller;
vScroller = o.vScroller;
if(delta > 0) {
dir = onHbar ? "left" : "top";
} else {
dir = onHbar ? "right" : "bottom";
}
if(dir.length > 0) {
self._doScrolling(dir, self);
}
scrollEnd = false;
if(dir === "left") {
scrollEnd = !self.hNeedScrollBar || Math.abs(hScroller.scrollValue - hScroller.scrollMin) < 0.001;
}
if(dir === "right") {
scrollEnd = !self.hNeedScrollBar || Math.abs(hScroller.scrollValue - (hScroller.scrollMax - self._getHScrollBarLargeChange() + 1)) < 0.001;
}
if(dir === "top") {
scrollEnd = !self.vNeedScrollBar || Math.abs(vScroller.scrollValue - vScroller.scrollMin) < 0.001;
}
if(dir === "bottom") {
scrollEnd = !self.vNeedScrollBar || Math.abs(vScroller.scrollValue - (vScroller.scrollMax - self._getVScrollBarLargeChange() + 1)) < 0.001;
}
if(!scrollEnd || !o.bubbleScrollingEvent || dir === "left" || dir === "right") {
e.stopPropagation();
e.preventDefault();
}
},
_documentMouseUp: function (e) {
var self = e.data.self, o = self.options, ele = e.data.ele;
ele.removeClass(o.wijCSS.stateActive);
self._clearInterval();
$(document).unbind("mouseup", self._documentMouseUp);
},
_scrollerMouseOver: function (e) {
var self = e.data, o = self.options, originalElement, ele, addhover;
if(o.disabled) {
return;
}
//Fixed an issue in IE8, In IE8, the originalElement can't get by e.originalEvent.target
originalElement = $(e.srcElement || e.originalEvent.target || e.originalEvent.srcElement);
ele = null;
addhover = false;
if(originalElement.hasClass(o.wijCSS.stateDefault)) {
ele = originalElement;
addhover = true;
} else if(originalElement.parent().hasClass(o.wijCSS.stateDefault)) {
ele = originalElement.parent();
addhover = true;
} else if(originalElement.hasClass(vbarContainerCSS) || originalElement.hasClass(hbarContainerCSS)) {
ele = originalElement;
}
if(ele) {
if(addhover) {
ele.addClass(o.wijCSS.stateHover);
}
ele.bind("mouseout." + self.widgetName, self, self._elementMouseOut);
ele.bind("mousedown." + self.widgetName, self, self._elementMouseDown);
ele.bind("mouseup." + self.widgetName, self, self._elementMouseUp);
}
},
_elementMouseUp: function (e) {
var ele = $(e.currentTarget);
//var self = e.data;
ele.removeClass(activeCss);
},
_elementMouseDown: function (e) {
var ele = $(e.currentTarget), self = e.data, scrollDirection, large, active, hbarDrag, pos, vbarDrag, pos2, f;
if(self.options.disabled || e.which !== 1) {
return;
}
scrollDirection = "";
large = false;
active = false;
if(ele.hasClass("wijmo-wijsuperpanel-vbar-buttontop")) {
scrollDirection = "top";
active = true;
} else if(ele.hasClass("wijmo-wijsuperpanel-vbar-buttonbottom")) {
scrollDirection = "bottom";
active = true;
} else if(ele.hasClass("wijmo-wijsuperpanel-hbar-buttonleft")) {
scrollDirection = "left";
active = true;
} else if(ele.hasClass("wijmo-wijsuperpanel-hbar-buttonright")) {
scrollDirection = "right";
active = true;
} else if(ele.hasClass(scrollerHandle)) {
ele.addClass(activeCss);
return;
} else if(ele.hasClass(hbarContainerCSS)) {
hbarDrag = ele.find("." + scrollerHandle);
pos = hbarDrag.offset();
if(e.pageX < pos.left) {
scrollDirection = "left";
} else {
scrollDirection = "right";
}
large = true;
} else if(ele.hasClass(vbarContainerCSS)) {
vbarDrag = ele.find("." + scrollerHandle);
pos2 = vbarDrag.offset();
if(e.pageY < pos2.top) {
scrollDirection = "top";
} else {
scrollDirection = "bottom";
}
large = true;
}
self._clearInterval();
self._doScrolling(scrollDirection, self, large);
f = self._fields();
self._setScrollingInterval(f, scrollDirection, self, large);
if(active) {
ele.addClass(activeCss);
}
$(document).bind("mouseup." + self.widgetName, {
self: self,
ele: ele
}, self._documentMouseUp);
},
doScrolling: /**
* Do scrolling.
* @param {string} dir Scrolling direction. Options are: "left", "right", "top" and "bottom".
* @param {boolean} large Whether to scroll a large change.
*/
function (dir, large) {
this._doScrolling(dir, this, large);
},
_setScrollerValue: function (dir, scroller, smallChange, largeChange, isAdd, isLarge, self) {
//var o = self.options;
var vMin = scroller.scrollMin, change = isLarge ? largeChange : smallChange, value = scroller.scrollValue, t, vTopValue, firstStepChangeFix, data, scrollValue, val;
if(!value) {
value = vMin;
}
t = 0;
if(isAdd) {
vTopValue = scroller.scrollMax - largeChange + 1;
if(Math.abs(value - vTopValue) < 0.001) {
self._clearInterval();
return false;
}
firstStepChangeFix = scroller.firstStepChangeFix;
t = value + change;
if(!isLarge && Math.abs(value - vMin) < 0.0001 && !isNaN(firstStepChangeFix)) {
t += firstStepChangeFix;
}
if(t > vTopValue) {
t = vTopValue;
}
} else {
if(Math.abs(value - vMin) < 0.001) {
self._clearInterval();
return false;
}
t = value - change;
if(t < 0) {
t = vMin;
}
}
data = {
oldValue: scroller.scrollValue,
newValue: t,
direction: dir,
dir: scroller.dir
};
if(!self._scrolling(true, self, data)) {
return false;
}
if(self.customScroll) {
val = Math.abs(self.customScroll);
scrollValue = self.scrollPxToValue(val, scroller.dir);
}
scroller.scrollValue = scrollValue || t;
self.customScroll = undefined;
return true;
},
_doScrolling: function (dir, self, large) {
// Does wijsuperpanel scrolling.
// <param name="dir" type="String">
// Scroll direction.
// Options are: "left", "right", "top" and "bottom".
// </param>
// <param name="self" type="jQuery">
// Pointer to the wijsuperpanel widget instance.
// </param>
// <param name="large" type="Boolean">
// Whether to scroll a large change.
// </param>
var o = self.options, vScroller = o.vScroller, hScroller = o.hScroller, vSmall = self._getVScrollBarSmallChange(), vLarge = self._getVScrollBarLargeChange(), hLarge = self._getHScrollBarLargeChange(), hSmall = self._getHScrollBarSmallChange();
if(dir === "top" || dir === "bottom") {
if(!self._setScrollerValue(dir, vScroller, vSmall, vLarge, dir === "bottom", large, self)) {
return;
}
dir = "v";
} else if(dir === "left" || dir === "right") {
if(!self._setScrollerValue(dir, hScroller, hSmall, hLarge, dir === "right", large, self)) {
return;
}
dir = "h";
}
self._setDragAndContentPosition(true, true, dir);
},
_disableButtonIfNeeded: function (self) {
// Disables scrolling buttons.
var f = self._fields(), o, buttonLeft, buttonRight, buttonTop, buttonBottom, hLargeChange, hMax, hValue, hScrollMin, vLargeChange, vMax, vValue, vScrollMin;
if(f.intervalID > 0) {
window.clearInterval(f.intervalID);
}
o = self.options;
buttonLeft = f.buttonLeft;
buttonRight = f.buttonRight;
buttonTop = f.buttonTop;
buttonBottom = f.buttonBottom;
if(buttonLeft !== undefined) {
hLargeChange = self._getHScrollBarLargeChange();
hMax = o.hScroller.scrollMax - hLargeChange + 1;
hValue = o.hScroller.scrollValue;
hScrollMin = o.hScroller.scrollMin;
if(hValue === undefined) {
hValue = hScrollMin;
}
if(Math.abs(hValue - hScrollMin) < 0.001 || !f.hScrolling) {
buttonLeft.addClass(o.wijCSS.stateDisabled);
} else {
buttonLeft.removeClass(o.wijCSS.stateDisabled);
}
if(Math.abs(hValue - hMax) < 0.001 || !f.hScrolling) {
buttonRight.addClass(o.wijCSS.stateDisabled);
} else {
buttonRight.removeClass(o.wijCSS.stateDisabled);
}
}
if(buttonTop !== undefined) {
vLargeChange = self._getVScrollBarLargeChange();
vMax = o.vScroller.scrollMax - vLargeChange + 1;
vValue = o.vScroller.scrollValue;
vScrollMin = o.vScroller.scrollMin;
if(vValue === undefined) {
vValue = vScrollMin;
}
if(Math.abs(vValue - vScrollMin) < 0.001 || !f.vScrolling) {
buttonTop.addClass(o.wijCSS.stateDisabled);
} else {
buttonTop.removeClass(o.wijCSS.stateDisabled);
}
if(Math.abs(vValue - vMax) < 0.001 || !f.vScrolling) {
buttonBottom.addClass(o.wijCSS.stateDisabled);
} else {
buttonBottom.removeClass(o.wijCSS.stateDisabled);
}
}
},
_clearInterval: function () {
var f = this._fields(), intervalID = f.internalFuncID;
if(intervalID > 0) {
window.clearInterval(intervalID);
f.internalFuncID = -1;
}
},
_elementMouseOut: function (event) {
var ele = $(event.currentTarget), self = event.data;
ele.unbind("mouseout", self._elementMouseOut);
ele.unbind("mousedown", self._elementMouseDown);
ele.unbind("mouseup", self._elementMouseUp);
ele.removeClass(self.options.wijCSS.stateHover);
},
_getScrollOffset: function (child1) {
var child = $(child1), f, cWrapper, tempWrapper, childOffset, templateOffset, cWrapperOffset, tDistance, bDistance, lDistance, rDistance, result = // left, top,
{
left: null,
top: null
};
if(child.length === 0) {
return result;
}
f = this._fields();
cWrapper = f.contentWrapper;
tempWrapper = f.templateWrapper;
childOffset = child.offset();
templateOffset = tempWrapper.offset();
childOffset.leftWidth = childOffset.left + child.outerWidth();
childOffset.topHeight = childOffset.top + child.outerHeight();
cWrapperOffset = cWrapper.offset();
cWrapperOffset.leftWidth = cWrapperOffset.left + cWrapper.outerWidth();
cWrapperOffset.topHeight = cWrapperOffset.top + cWrapper.outerHeight();
lDistance = childOffset.left - templateOffset.left;
if(childOffset.left < cWrapperOffset.left) {
result.left = lDistance;
} else if(childOffset.leftWidth > cWrapperOffset.leftWidth) {
rDistance = childOffset.leftWidth - templateOffset.left - cWrapper.innerWidth();
if(lDistance < rDistance) {
result.left = lDistance;
} else {
result.left = rDistance;
}
}
tDistance = childOffset.top - templateOffset.top;
if(childOffset.top < cWrapperOffset.top) {
result.top = tDistance;
} else if(childOffset.topHeight > cWrapperOffset.topHeight) {
bDistance = childOffset.topHeight - templateOffset.top - cWrapper.innerHeight();
if(tDistance < bDistance) {
result.top = tDistance;
} else {
result.top = bDistance;
}
}
return result;
},
_scrollDrag: function (dir, hbarContainer, hbarDrag, fireScrollEvent) {
var self = this, o = self.options, v = dir === "v", scroller = v ? o.vScroller : o.hScroller, hMin = scroller.scrollMin, hMax = scroller.scrollMax, hValue = scroller.scrollValue === undefined ? hMin : (scroller.scrollValue - hMin), hLargeChange = self._getLargeChange(dir), max = hMax - hMin - hLargeChange + 1, dragleft = -1, track, drag, padding;
if(hValue > max) {
hValue = max;
}
if(hbarContainer !== undefined) {
track = self._getTrackLen(dir);
drag = hbarDrag[v ? "outerHeight" : "outerWidth"]();
padding = self._getScrollContainerPadding(v ? "top" : "left");
dragleft = (hValue / max) * (track - drag) + padding;
}
if(dragleft >= 0) {
hbarDrag.css(v ? "top" : "left", dragleft + "px");
}
self._scrollEnd(fireScrollEvent, self, dir);
},
needToScroll: /**
* Determine whether scoll the child DOM element to view
* need to scroll the scroll bar
* @param {DOMElement} child The child to scroll to.
*/
function (child1) {
var offset = this._getScrollOffset(child1);
return offset.top !== null || offset.left !== null;
},
scrollChildIntoView: /**
* Scroll children DOM element to view.
* @param {DOMElement} child The child to scroll to.
*/
function (child1) {
var offset = this._getScrollOffset(child1), left = offset.left, top = offset.top;
if(left !== null) {
this.hScrollTo(left);
}
if(top !== null) {
this.vScrollTo(top);
}
},
hScrollTo: /**
* Scroll to horizontal position.
* @param {number} x The position to scroll to.
*/
function (x) {
var o = this.options;
//var f = this._fields();
o.hScroller.scrollValue = this.scrollPxToValue(x, "h");
//this._setDragAndContentPosition(false, true, "h", "nonestop");
this._setDragAndContentPosition(true, true, "h", "nonestop");
},
vScrollTo: /**
* Scroll to vertical position.
* @param {number} y The position to scroll to.
*/
function (y) {
var o = this.options;
o.vScroller.scrollValue = this.scrollPxToValue(y, "v");
//this._setDragAndContentPosition(false, true, "v", "nonestop");
this._setDragAndContentPosition(true, true, "v", "nonestop");
},
scrollPxToValue: /**
* Convert pixel to scroll value.
* For example, wijsuperpanel scrolled 50px
* which is value 1 after conversion.
* @param {number} px Length of scrolling.
* @param {string} dir Scrolling direction. Options are: "h" and "v".
*/
function (px, dir) {
var o = this.options, m = (dir === "h" ? "outerWidth" : "outerHeight"), m1 = (dir === "h" ? "contentWidth" : "contentHeight"), scroller = (dir === "h" ? "hScroller" : "vScroller"), f = this._fields(), cWrapper = f.contentWrapper, size = //var tempWrapper = f.templateWrapper;
f[m1], contentHeight = cWrapper[m](), vMin = o[scroller].scrollMin, vMax = o[scroller].scrollMax, vRange = vMax - vMin, vLargeChange = (dir === "h" ? this._getHScrollBarLargeChange() : this._getVScrollBarLargeChange()), maxv = vRange - vLargeChange + 1, ret = maxv * (px / (size - contentHeight));
if(ret < vMin) {
ret = vMin;
}
if(ret > maxv) {
ret = maxv;
}
return ret;
},
scrollTo: /**
* Scroll to the specified position.
* which is value 1 after conversion.
* @param {number} x Horizontal position to scroll to.
* @param {number} y Vertical position to scroll to.
*/
function (x, y) {
this.hScrollTo(x);
this.vScrollTo(y);
},
refresh: /**
* Refreshes wijsuperpanel.
* Needs to be called after content being changed.
* @returns {boolean} Returns true if it is successful, else returns false.
*/
function () {
this.paintPanel();
},
paintPanel: /** @ignore
* Refreshes wijsuperpanel.
* Needs to be called after content being changed.
* @returns {boolean} Returns true if it is successful, else returns false.
*/
function (unfocus) {
var self = this, ele = self.element, focused, o, f, templateWrapper;
if(ele.is(":visible")) {
focused = typeof document.activeElement != 'unknown' ? document.activeElement : undefined;
o = self.options;
f = self._fields();
if(!f.initialized) {
self._initialize(f, ele, self);
}
self._resetLargeChange(self, f, o);
self._bindElementEvents(self, f, ele, o);
templateWrapper = f.templateWrapper;
templateWrapper.css({
"float": "left",
left: "0px",
top: "0px",
width: "auto",
height: "auto"
});
// hide and show wrapper div to force the width to change
// for some browser.
templateWrapper.hide();
templateWrapper.show();
f.contentWidth = templateWrapper.width();
f.contentHeight = templateWrapper.height();
templateWrapper.css("float", "");
self._setRounder(self, ele);
self._setInnerElementsSize(f, ele);
if(self._testScroll(self, f, o) === false) {
return false;
}
self._initScrollBars(self, f, o);
self._initScrollButtons(self, f, o);
self._trigger("painted");
self._paintedMark = {
date: new Date(),
mainWidth: ele[0].offsetWidth,
mainHeight: ele[0].offsetHeight,
width: f.contentWidth,
height: f.contentWidth
};
if(focused !== undefined && !unfocus) {
$(focused).focus();
}
return true;
}
return false;
},
_resetLargeChange: function (self, f, o) {
var handle;
if(self._autoVLarge) {
o.vScroller.scrollLargeChange = null;
}
if(self._autoHLarge) {
o.hScroller.scrollLargeChange = null;
}
f.vTrackLen = undefined;
f.hTrackLen = undefined;
if(f.vbarContainer) {
// fixed bug when the original draggable element removed when it's being dragged.
// use detach to keep the events to be fired(IE).
handle = f.vbarContainer.children("." + scrollerHandle + ":eq(0)");
handle.detach();
f.vbarContainer.remove();
f.vbarContainer = undefined;
}
if(f.hbarContainer) {
handle = f.hbarContainer.children("." + scrollerHandle + ":eq(0)");
handle.detach();
f.hbarContainer.remove();
f.hbarContainer = undefined;
}
},
_initialize: function (f, ele, self) {
var wijCSS = self.options.wijCSS;
f.initialized = true;
// ensure width and height
ele.addClass([
"wijmo-wijsuperpanel",
wijCSS.widget,
wijCSS.content
].join(' '));
f.oldHeight = ele.css("height");
var old = ele.css("overflow");
ele.css("overflow", "");
// set height to element
ele.height(ele.height());
ele.css("overflow", old);
self._createAdditionalDom(self, f, ele);
},
getContentElement: /**
* Gets the content element of wijsuperpanel.
* @example $("selector").wijsuperpanel("getContentElement");
* @returns {jQuery}
*/
function () {
return this._fields().templateWrapper;
},
_setButtonPosition: function (self, o, scroller, dir, target, f, state) {
var h = dir === "h", mouseoverkey = "mouseover." + self.widgetName, decKey = h ? "buttonLeft" : "buttonTop", incKey = h ? "buttonRight" : "buttonBottom", decButton = f[decKey], incButton = f[incKey], html, buttons, defaultPosition;
if(self._hasMode(scroller, "buttons") || self._hasMode(scroller, "buttonshover")) {
html = h ? hButtons : vButtons;
if(decButton === undefined) {
buttons = $(html).appendTo(state);
buttons.bind(mouseoverkey, self, self._scrollButtonMouseOver);
f[decKey] = decButton = state.children(h ? ".wijmo-wijsuperpanel-buttonleft" : ".wijmo-wijsuperpanel-buttontop");
f[incKey] = incButton = state.children(h ? ".wijmo-wijsuperpanel-buttonright" : ".wijmo-wijsuperpanel-buttonbottom");
}
defaultPosition = {
my: h ? "left" : "top",
of: target,
at: h ? "left" : "top",
collision: "none"
};
$.extend(defaultPosition, scroller.decreaseButtonPosition);
decButton.position(defaultPosition);
defaultPosition = {
my: h ? "right" : "bottom",
of: target,
at: h ? "right" : "bottom",
collision: "none"
};
$.extend(defaultPosition, scroller.increaseButtonPosition);
incButton.position(defaultPosition);
} else if(decButton !== undefined) {
decButton.remove();
incButton.remove();
f[decKey] = f[incKey] = undefined;
}
},
_initScrollButtons: function (self, f, o) {
var a = f.contentWrapper, state = f.stateContainer;
self._setButtonPosition(self, o, o.hScroller, "h", a, f, state);
self._setButtonPosition(self, o, o.vScroller, "v", a, f, state);
},
_getVScrollBarSmallChange: function () {
var o = this.options, va;
if(!o.vScroller.scrollSmallChange) {
va = this._getVScrollBarLargeChange();
o.vScroller.scrollSmallChange = va / 2;
}
return o.vScroller.scrollSmallChange;
},
_getVScrollBarLargeChange: function () {
return this._getLargeChange("v");
},
_getLargeChange: function (dir) {
var self = this, o = self.options, f = self._fields(), v = dir === "v", scroller = v ? o.vScroller : o.hScroller, clientKey = //clientKey = v ? "clientHeight" : "clientWidth",
v ? "innerHeight" : "innerWidth", offsetKey = v ? "contentHeight" : "contentWidth", autoKey = v ? "_autoVLarge" : "_autoHLarge", hMax, hMin, hRange, content, contentWidth, wrapperWidth, percent, large;
if(scroller.scrollLargeChange) {
return scroller.scrollLargeChange;
}
// calculate large change if empty
hMax = scroller.scrollMax;
hMin = scroller.scrollMin;
hRange = hMax - hMin;
content = f.contentWrapper;
//contentWidth = content[0][clientKey];
contentWidth = content[clientKey]();
wrapperWidth = f[offsetKey];
percent = contentWidth / (wrapperWidth - contentWidth);
large = ((hRange + 1) * percent) / (1 + percent);
if(isNaN(large)) {
large = 0;
}
scroller.scrollLargeChange = large;
self[autoKey] = true;
return scroller.scrollLargeChange;
},
_getHScrollBarSmallChange: function () {
var o = this.options, va;
if(!o.hScroller.scrollSmallChange) {
va = this._getHScrollBarLargeChange();
o.hScroller.scrollSmallChange = va / 2;
}
return o.hScroller.scrollSmallChange;
},
_getHScrollBarLargeChange: function () {
return this._getLargeChange("h");
},
_initScrollBars: function (self, f, o) {
// Set scroll bar initial position.
var hScroller = o.hScroller, hMax = hScroller.scrollMax, hMin = hScroller.scrollMin, hRange = hMax - hMin, vScroller = o.vScroller, vMax = vScroller.scrollMax, vMin = vScroller.scrollMin, vRange = vMax - vMin, hbarDrag = f.hbarDrag, vbarDrag = f.vbarDrag, hLargeChange, track, dragLen, difference, icon, vLargeChange, track1, dragLen1, difference1, icon1;
if(self.hNeedScrollBar && hbarDrag.is(":visible")) {
hLargeChange = self._getHScrollBarLargeChange();
track = self._getTrackLen("h");
dragLen = self._getDragLength(hRange, hLargeChange, track, o.hScroller.scrollMinDragLength);
hbarDrag.width(dragLen);
//difference = hbarDrag.outerWidth() - hbarDrag.width();
difference = hbarDrag.outerWidth(true) - hbarDrag.width();
hbarDrag.width(dragLen - difference);
icon = hbarDrag.children("span");
icon.css("margin-left", (hbarDrag.width() - icon[0].offsetWidth) / 2);
//if (track <= hbarDrag.outerWidth()) {
if(track <= hbarDrag.outerWidth(true)) {
hbarDrag.hide();
} else {
hbarDrag.show();
}
//fixed bug the dragger will be reset after refresh
if(self._isDragging == true) {
$(document).trigger("mouseup");
self._isDragging = false;
}
}
if(self.vNeedScrollBar && vbarDrag.is(":visible")) {
vLargeChange = self._getVScrollBarLargeChange();
track1 = self._getTrackLen("v");
dragLen1 = self._getDragLength(vRange, vLargeChange, track1, o.vScroller.scrollMinDragLength);
vbarDrag.height(dragLen1);
//difference1 = vbarDrag.outerHeight() - vbarDrag.height();
difference1 = vbarDrag.outerHeight(true) - vbarDrag.height();
vbarDrag.height(dragLen1 - difference1);
icon1 = vbarDrag.children("span");
icon1.css("margin-top", (vbarDrag.height() - icon1[0].offsetHeight) / 2);
//if (track1 <= vbarDrag.outerHeight()) {
if(track1 <= vbarDrag.outerHeight(true)) {
vbarDrag.hide();
} else {
vbarDrag.show();
}
//fixed bug the dragger will be reset after refresh
if(self._isDragging == true) {
$(document).trigger("mouseup");
self._isDragging = false;
}
}
self._setDragAndContentPosition(false, false, "both");
},
_getTrackLen: function (dir) {
// Get the length of the track.
// <param name="dir" type="String">
// Options are: "v" and "h".
// "v" - Vertical scroll track.
// "h" - Horizontal scroll track.
// </param>
var self = this, f = self._fields(), key = //var o = self.options;
dir + "TrackLen", hbarContainer, vbarContainer, track, padding;
if(f[key] !== undefined) {
return f[key];
}
hbarContainer = f.hbarContainer;
vbarContainer = f.vbarContainer;
track = 0;
padding = 0;
if(dir === "h") {
padding = self._getScrollContainerPadding("h");
track = hbarContainer.innerWidth();
}
if(dir === "v") {
padding = self._getScrollContainerPadding("v");
track = vbarContainer.innerHeight();
}
f[key] = (track - padding);
return f[key];
},
_getScrollContainerPadding: function (paddingType) {
// Get the padding of the scroll bar container.
var self = this, f = self._fields(), padding = 0, container, key;
if(paddingType === "h") {
padding = self._getScrollContainerPadding("left") + self._getScrollContainerPadding("right");
} else if(paddingType === "v") {
padding = self._getScrollContainerPadding("top") + self._getScrollContainerPadding("bottom");
} else {
if(paddingType === "left" || paddingType === "right") {
container = f.hbarContainer;
} else {
container = f.vbarContainer;
}
key = paddingType + "Padding";
if(f[key] !== undefined) {
padding = f[key];
return padding;
}
//padding = parseFloat(container.css("padding-" +
//paddingType).replace("px", ""));
if(container && container.css) {
padding = parseFloat(container.css("padding-" + paddingType));
}
f[key] = padding;
}
return padding;
},
_triggerScroll: function (contentLeft, dir, contentAnimationOptions) {
var data = {
position: contentLeft,
dir: dir,
animationOptions: contentAnimationOptions
};
this._trigger("scroll", null, data);
},
_contentDragAnimate: function (dir, animated, hbarContainer, hbarDrag, stop, fireScrollEvent, dragging) {
var self = this, o = self.options, v = dir === "v", scroller = v ? o.vScroller : o.hScroller, tempKey = v ? "outerHeight" : "outerWidth", wrapKey = v ? "innerHeight" : "innerWidth", contentKey = v ? "contentHeight" : "contentWidth", paddingKey = v ? "top" : "left", hMin = scroller.scrollMin, hMax = scroller.scrollMax, hRange = hMax - hMin, hValue = scroller.scrollValue === undefined ? hMin : (scroller.scrollValue - hMin), hLargeChange = self._getLargeChange(dir), max = hRange - hLargeChange + 1, f = self._fields(), cWrapper = f.contentWrapper, tempWrapper = f.templateWrapper, contentLeft, dragleft, track, drag, r, padding, dragAnimationOptions, properties, contentAnimationOptions, userComplete, properties1, key;
if(hValue > max) {
hValue = max;
}
contentLeft = (f[contentKey] - cWrapper[wrapKey]()) * (hValue / max);
if(Math.abs(contentLeft) < 0.001) {
contentLeft = 0;
}
contentLeft = Math.round(contentLeft);
dragleft = -1;
if(hbarContainer !== undefined) {
if(animated && hbarDrag.is(":animated") && stop !== "nonestop") {
hbarDrag.stop(true, false);
}
track = self._getTrackLen(dir);
//drag = hbarDrag[tempKey]();
drag = hbarDrag[tempKey](true);
r = track - drag;
padding = self._getScrollContainerPadding(paddingKey);
dragleft = (hValue / max) * r + padding;
}
if(animated && o.animationOptions && !o.animationOptions.disabled) {
if(dragleft >= 0 && dragging !== "dragging") {
dragAnimationOptions = $.extend({
}, o.animationOptions);
// not trigger scrolled when stop
dragAnimationOptions.complete = undefined;
if(v) {
properties = {
top: dragleft
};
} else {
properties = {
left: dragleft
};
}
hbarDrag.animate(properties, dragAnimationOptions);
}
contentAnimationOptions = $.extend({
}, o.animationOptions);
userComplete = o.animationOptions.complete;
contentAnimationOptions.complete = function () {
self._scrollEnd(fireScrollEvent, self, dir);
if($.isFunction(userComplete)) {
userComplete(arguments);
}
};
if(animated && tempWrapper.is(":animated") && stop !== "nonestop") {
tempWrapper.stop(true, false);
}
if(v) {
properties1 = {
top: -contentLeft
};
} else {
properties1 = {
left: -contentLeft
};
}
//console.log("content move1");
if(!o.customScrolling) {
tempWrapper.animate(properties1, contentAnimationOptions);
} else {
self._scrollEnd(fireScrollEvent, self, dir, hValue);
}
self._triggerScroll(contentLeft, dir, contentAnimationOptions);
} else if(scroller.scrollBarVisibility !== "hidden") {
key = v ? "top" : "left";
if(dragleft >= 0 && dragging !== "dragging") {
hbarDrag[0].style[key] = dragleft + "px";
}
//console.log("content move2");
if(!o.customScrolling) {
tempWrapper[0].style[key] = -contentLeft + "px";
}
self._triggerScroll(contentLeft, dir);
self._scrollEnd(fireScrollEvent, self, dir, hValue);
}
},
_setDragAndContentPosition: function (fireScrollEvent, animated, dir, stop, dragging) {
var self = this, f = self._fields(), hbarContainer = f.hbarContainer, hbarDrag = f.hbarDrag, vbarContainer = f.vbarContainer, vbarDrag = f.vbarDrag;
if((dir === "both" || dir === "h") && f.hScrolling) {
self._contentDragAnimate("h", animated, hbarContainer, hbarDrag, stop, fireScrollEvent, dragging);
}
if((dir === "both" || dir === "v") && f.vScrolling) {
self._contentDragAnimate("v", animated, vbarContainer, vbarDrag, stop, fireScrollEvent, dragging);
}
if(f.intervalID > 0) {
window.clearInterval(f.intervalID);
}
f.intervalID = window.setInterval(function () {
self._disableButtonIfNeeded(self);
}, 500);
},
_scrolling: function (fireEvent, self, d) {
var r = true;
if(fireEvent) {
d.beforePosition = self.getContentElement().position();
self._beforePosition = d.beforePosition;
//console.log("scrolling:" + JSON.stringify(d));
r = self._trigger("scrolling", null, d);
self.customScroll = d.customScroll;
}
return r;
},
_scrollEnd: function (fireEvent, self, dir, newValue) {
if(fireEvent) {
// use settimeout to return to caller immediately.
window.setTimeout(function () {
var content = self.getContentElement(), after, d;
if(!content.is(":visible")) {
return;
}
after = self.getContentElement().position();
d = {
dir: dir,
beforePosition: self._beforePosition,
afterPosition: after
};
if(!isNaN(newValue)) {
d.newValue = newValue;
}
//console.log("scrolled:" + JSON.stringify(d));
self._trigger("scrolled", null, d);
}, 0);
}
},
_getDragLength: function (range, largeChange, track, min) {
var divide = range / largeChange, dragLength = track / divide, minidrag = min;
if(dragLength < minidrag) {
dragLength = minidrag;
} else if((dragLength + 1) >= track) {
dragLength = track - 1;
}
return Math.round(dragLength);
},
_needScrollbar: function (scroller, needscroll) {
var scrollbarMode = this._hasMode(scroller, "scrollbar"), barVisibility = scroller.scrollBarVisibility, needScrollBar = scrollbarMode && (barVisibility === "visible" || (barVisibility === "auto" && needscroll));
return needScrollBar;
},
_bindBarEvent: function (barContainer, barDrag, dir) {
var self = this;
barContainer.bind("mouseover." + self.widgetName, self, self._scrollerMouseOver);
if(!$.fn.draggable) {
return;
}
barDrag.draggable({
axis: dir === "h" ? "x" : "y",
start: function (e, data) {
self._isDragging = true;
},
drag: function (e, data) {
self._dragging(e, data, self);
},
containment: "parent",
stop: function (e) {
self._dragStop(e, self, dir);
$(e.target).removeClass(activeCss);
self._isDragging = false;
}
});
},
_createBarIfNeeded: function (hNeedScrollBar, scrollerWrapper, dir, html, content) {
if(hNeedScrollBar) {
var self = this, data, f = self._fields(), strBarContainer = dir + "barContainer", strBarDrag = dir + "barDrag", hbar = dir === "h", contentLength = //contentLength = content[0][hbar ? "clientHeight" : "clientWidth"],
content[hbar ? "innerHeight" : "innerWidth"](), c = f[strBarContainer] = $(html), targetBarLen, d;
scrollerWrapper.append(c);
targetBarLen = c[0][hbar ? "offsetHeight" : "offsetWidth"];
contentLength = contentLength - targetBarLen;
data = {
direction: hbar ? "horizontal" : "vertical",
targetBarLen: targetBarLen,
contentLength: contentLength
};
if(self._trigger(hbar ? "hScrollerActivating" : "vScrollerActivating", null, data) === false) {
return false;
}
d = f[strBarDrag] = c.find("." + scrollerHandle);
self._bindBarEvent(c, d, dir);
content[hbar ? "height" : "width"](contentLength);
// fixed bug on forum when set contentlength ,the width or height is changed.
// f[hbar ? "contentWidth" : "contentHeight"] =
// f.templateWrapper[hbar ? "width" : "height"]();
}
},
_setScrollbarPosition: function (wrapper, self, content, targetBarContainer, referBarContainer, targetNeedScrollBar, referNeedScrollBar, targetScrollBarPosition, referScrollBarPosition, dir, scrollingNeed) {
var hbar = dir === "h", targetBarLen, targetPadding, targetBarPosition, barPosition1, contentPosition1, barPosition2, contentPosition2, contentLength2, referBarWidth, css = self.options.wijCSS;
if(targetNeedScrollBar) {
targetBarLen = targetBarContainer[0][hbar ? "offsetHeight" : "offsetWidth"];
targetPadding = self._getScrollContainerPadding(dir);
targetBarPosition = hbar ? "top" : "left";
barPosition1 = hbar ? {
top: "0px",
bottom: "auto",
left: "auto",
right: "auto"
} : {
left: "0px",
right: "auto",
top: "auto",
bottom: "auto"
};
contentPosition1 = hbar ? {
top: targetBarLen + "px",
left: null
} : {
left: targetBarLen + "px"
};
barPosition2 = hbar ? {
top: "auto",
right: "auto",
left: "auto",
bottom: "0px"
} : {
left: "auto",
right: "0px",
top: "auto",
bottom: "auto"
};
contentPosition2 = hbar ? {
top: "",
left: null
} : {
left: ""
};
//var contentLength = content[0][hbar? "clientHeight":"clientWidth"];
//contentLength2 = content[0][hbar? "clientWidth":"clientHeight"];
contentLength2 = content[hbar ? "innerWidth" : "innerHeight"]();
if(targetScrollBarPosition === targetBarPosition) {
targetBarContainer.css(barPosition1);
content.css(contentPosition1);
if(hbar) {
targetBarContainer.children(".wijmo-wijsuperpanel-hbar-buttonleft").removeClass(css.cornerBL).addClass(css.cornerTL);
targetBarContainer.children(".wijmo-wijsuperpanel-hbar-buttonright").removeClass(css.cornerBR).addClass(css.cornerTR);
targetBarContainer.removeClass(css.cornerBottom).addClass(css.cornerTop);
} else {
targetBarContainer.children(".wijmo-wijsuperpanel-vbar-buttontop").removeClass(css.cornerTR).addClass(css.cornerTL);
targetBarContainer.children(".wijmo-wijsuperpanel-vbar-buttonbottom").removeClass(css.cornerBR).addClass(css.cornerBL);
targetBarContainer.removeClass(css.cornerRight).addClass(css.cornerLeft);
}
} else {
targetBarContainer.css(barPosition2);
content.css(contentPosition2);
if(hbar) {
targetBarContainer.children(".wijmo-wijsuperpanel-hbar-buttonleft").removeClass(css.cornerTL).addClass(css.cornerBL);
targetBarContainer.children(".wijmo-wijsuperpanel-hbar-buttonright").removeClass(css.cornerBL).addClass(css.cornerBR);
targetBarContainer.removeClass(css.cornerTop).addClass(css.cornerBottom);
} else {
targetBarContainer.children(".wijmo-wijsuperpanel-vbar-buttontop").removeClass(css.cornerTL).addClass(css.cornerTR);
targetBarContainer.children(".wijmo-wijsuperpanel-vbar-buttonbottom").removeClass(css.cornerBL).addClass(css.cornerBR);
targetBarContainer.removeClass(css.cornerLeft).addClass(css.cornerRight);
}
}
//content[hbar?"height":"width"](contentLength - targetBarLen);
referBarWidth = 0;
if(referNeedScrollBar) {
referBarWidth = referBarContainer[0][hbar ? "offsetWidth" : "offsetHeight"];
if(referScrollBarPosition === "left") {
targetBarContainer.css("right", "0px");
} else if(referScrollBarPosition === "right") {
targetBarContainer.css("left", "0px");
} else if(referScrollBarPosition === "top") {
targetBarContainer.css("bottom", "0px");
} else if(referScrollBarPosition === "bottom") {
targetBarContainer.css("top", "0px");
}
}
if(!hbar/*vbar*/ && referNeedScrollBar) {
referBarWidth = 0;
}
targetBarContainer[hbar ? "width" : "height"](contentLength2 - targetPadding);
self._enableDisableScrollBar(dir, targetBarContainer, !scrollingNeed);
} else {
wrapper.css(hbar ? "left" : "top", "");
}
},
_testScroll: function (self, f, o) {
var wrapper = f.templateWrapper, content = f.contentWrapper, scrollerWrapper = f.stateContainer, contentWidth = content.innerWidth(), contentHeight = content.innerHeight(), wrapperWidth = f.contentWidth, wrapperHeight = f.contentHeight, hNeedScrollBar, vNeedScrollBar, hbarContainer, vbarContainer, hbarPosition, vbarPosition;
f.hScrolling = wrapperWidth > contentWidth;
f.vScrolling = wrapperHeight > contentHeight;
hNeedScrollBar = self.hNeedScrollBar = self._needScrollbar(o.hScroller, f.hScrolling);
if(self._createBarIfNeeded(hNeedScrollBar, scrollerWrapper, "h", hbarHtml, content) === false) {
return false;
}
// having h scroll bar, but no vscroll bar, we need to test vscrolling again.
if(hNeedScrollBar && !f.vScrolling) {
wrapper.css("float", "left");
f.contentHeight = wrapper.height();
f.vScrolling = f.contentHeight > (contentHeight - f.hbarContainer[0].offsetHeight);
wrapper.css("float", "");
}
vNeedScrollBar = self.vNeedScrollBar = self._needScrollbar(o.vScroller, f.vScrolling);
if(self._createBarIfNeeded(vNeedScrollBar, scrollerWrapper, "v", vbarHtml, content) === false) {
return false;
}
if(vNeedScrollBar && !f.hScrolling) {
wrapper.css("float", "left");
f.contentWidth = wrapper.width();
//contentWidth =
f.hScrolling = f.contentWidth > (contentWidth - f.vbarContainer[0].offsetWidth);
wrapper.css("float", "");
if(f.hScrolling && !hNeedScrollBar) {
hNeedScrollBar = self.hNeedScrollBar = self._needScrollbar(o.hScroller, f.hScrolling);
if(self._createBarIfNeeded(hNeedScrollBar, scrollerWrapper, "h", hbarHtml, content) === false) {
return false;
}
}
}
hbarContainer = f.hbarContainer;
vbarContainer = f.vbarContainer;
hbarPosition = o.hScroller.scrollBarPosition;
vbarPosition = o.vScroller.scrollBarPosition;
self._setScrollbarPosition(wrapper, self, content, hbarContainer, vbarContainer, hNeedScrollBar, vNeedScrollBar, hbarPosition, vbarPosition, "h", f.hScrolling);
self._setScrollbarPosition(wrapper, self, content, vbarContainer, hbarContainer, vNeedScrollBar, hNeedScrollBar, vbarPosition, hbarPosition, "v", f.vScrolling);
},
_enableDisableScrollBar: function (bar, barContainer, disable) {
// Disables scroll bar.
// <param name="bar" type="String">
// Scrollbar to disable.
// Options are: "h" and "v"
// </param>
// <param name="barContainer" type="jQuery">
// The scroll bar container jQuery object.
// </param>
// <param name="disable" type="Boolean">
// Whether to disable scroll bar.
// </param>
var o = this.options;
if(bar === "v") {
barContainer[disable ? "addClass" : "removeClass"]("wijmo-wijsuperpanel-vbarcontainer-disabled");
barContainer.find("." + o.wijCSS.stateDefault)[disable ? "addClass" : "removeClass"](o.wijCSS.stateDisabled);
} else if(bar === "h") {
barContainer[disable ? "addClass" : "removeClass"]("wijmo-wijsuperpanel-hbarcontainer-disabled");
barContainer.find("." + o.wijCSS.stateDefault)[disable ? "addClass" : "removeClass"](o.wijCSS.stateDisabled);
}
barContainer.children("." + scrollerHandle)[disable ? "hide" : "show"]();
},
_initResizer: function () {
// Initialize reseizer of wijsuperpanel.
var self = this, o = self.options, f = self._fields(), resizer = f.resizer, resizableOptions, oldstop;
if(!$.fn.resizable) {
return;
}
if(!resizer && o.allowResize) {
resizableOptions = o.resizableOptions;
oldstop = resizableOptions.stop;
resizableOptions.stop = function (e) {
self._resizeStop(e, self);
if($.isFunction(oldstop)) {
oldstop(e);
}
};
f.resizer = resizer = self.element.resizable(resizableOptions);
}
if(!o.allowResize && f.resizer) {
resizer.resizable("destroy");
f.resizer = null;
}
},
_resizeStop: function (e, self) {
// give the chance to autoRefresh polling to repaint.
if(!this.options.autoRefresh) {
self.paintPanel(true);
}
self._trigger("resized");
},
_createAdditionalDom: function (self, f, ele) {
// make sure the key pressing event work in FireFox.
if(!ele.attr("tabindex")) {
ele.attr("tabindex", "-1");
f.tabindex = true;
}
var stateContainer = f.stateContainer = $(innerElementHtml), templateW;
// move child element to content wrapper div of wijsuperpanel.
f.contentWrapper = stateContainer.children();
templateW = f.templateWrapper = f.contentWrapper.children();
ele.contents().each(function (index, el) {
var jel = $(el);
if(jel.hasClass("wijmo-wijsuperpanel-header")) {
f.header = jel;
return;
}
if(jel.hasClass("wijmo-wijsuperpanel-footer")) {
f.footer = jel;
return;
}
templateW[0].appendChild(el);
});
// apeend header to first element.
if(f.header !== undefined) {
ele.prepend(f.header);
}
ele[0].appendChild(stateContainer[0]);
// apeend footer to first element.
if(f.footer !== undefined) {
f.footer.insertAfter(stateContainer);
}
},
_setRounder: function (self, ele) {
if(this.options.showRounder) {
ele.addClass(this.options.wijCSS.cornerAll);
if(self._rounderAdded) {
return;
}
if($.browser.msie) {
return;
}
var key1, key, value, border;
key1 = key = "";
if($.browser.webkit) {
key = "WebkitBorderTopLeftRadius";
key1 = "WebkitBorderRadius";
} else if($.browser.mozilla) {
key = "MozBorderRadiusBottomleft";
key1 = "MozBorderRadius";
} else {
key = "border-top-left-radius";
key1 = "border-radius";
}
value = ele.css(key);
border = parseInt(value, 10);
// adding 1 extra to out-most radius.
ele.css(key1, border + 1);
self._rounderAdded = true;
self._radiusKey = key1;
} else {
ele.removeClass(this.options.wijCSS.cornerAll);
}
},
_setInnerElementsSize: function (f, ele) {
var state = f.stateContainer, content = f.contentWrapper, height = 0, style, clientHeight, clientWidth, style2;
if(f.header !== undefined) {
height += f.header.outerHeight();
}
if(f.footer !== undefined) {
height += f.footer.outerHeight();
}
style = state[0].style;
//clientHeight = ele[0].clientHeight - height;
//clientWidth = ele[0].clientWidth;
clientHeight = ele.innerHeight() - height;
clientWidth = ele.innerWidth();
// hide element before setting width and height to improve
//javascript performance in FF3.
style.display = "none";
style.height = clientHeight + "px";
style.width = clientWidth + "px";
style2 = content[0].style;
style2.height = clientHeight + "px";
style2.width = clientWidth + "px";
style.display = "";
}
});
wijsuperpanel.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijsuperpanel_options());
$.wijmo.registerWidget("wijsuperpanel", wijsuperpanel.prototype);
} else {
//use native scrollbar
var scrollerHandle = "wijmo-wijsuperpanel-handle", innerElementHtml = "<div class='wijmo-wijsuperpanel-statecontainer'>" + "<div class='wijmo-wijsuperpanel-contentwrapper-touch'>" + "</div></div>";
wijsuperpanel.prototype = $.extend(true, {
}, $.Widget.prototype, {
widgetEventPrefix: "wijsuperpanel",
_setOption: function (key, value) {
var self = this, o = self.options, f = self._fields();
if(key === "animationOptions" || key === "resizableOptions") {
value = $.extend(o[key], value);
} else if(key === "hScroller" || key === "vScroller") {
value = $.extend(o[key], value);
self.refresh();
}
$.Widget.prototype._setOption.apply(self, arguments);
switch(key) {
case "allowResize":
self._initResizer();
break;
case "disabled":
self._handleDisabledOption(value, self.element);
break;
case "mouseWheelSupport":
case "keyboardSupport":
self._bindElementEvents(self, f, self.element, o);
break;
}
},
_create: function () {
var self = this, o = self.options;
o.vScroller.dir = "v";
o.hScroller.dir = "h";
self._createDom();
if(self.options.disabled) {
self.disable();
}
//update for visibility change
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
self.refresh();
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
}, "wijsuperpanel");
}
},
_handleDisabledOption: function (disabled, ele) {
var self = this;
if(disabled) {
if(!self.disabledDiv) {
self.disabledDiv = self._createDisabledDiv(ele);
}
self.disabledDiv.appendTo("body");
} else {
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
}
},
_createDisabledDiv: function (outerEle) {
var self = this, ele = outerEle ? outerEle : self.element, eleOffset = ele.offset(), disabledWidth = ele.outerWidth(), disabledHeight = ele.outerHeight();
return $("<div></div>").addClass("ui-disabled").css({
"z-index": "99999",
position: "absolute",
width: disabledWidth,
height: disabledHeight,
left: eleOffset.left,
top: eleOffset.top
});
},
_createDom: function () {
var self = this, el = self.element;
self.paintPanel();
self._initResizer();
self._bindElementEvents();
},
_applyOverflow: function (stateContainer) {
var css = {
}, o = this.options, hs = o.hScroller.scrollBarVisibility, vs = o.vScroller.scrollBarVisibility;
css["overflow-x"] = hs;
css["overflow-y"] = vs;
// for 38140: ie10 don't support that setting overflow-x and
// overflow-y to "visible" at same time.
if($.support.isTouchEnabled && $.support.isTouchEnabled()) {
if(hs === "visible" && vs === "visible") {
css["overflow-x"] = "auto";
css["overflow-y"] = "auto";
}
}
stateContainer.css(css);
},
_createAdditionalDom: function (self, f, ele) {
if(!ele.attr("tabindex")) {
ele.attr("tabindex", "-1");
f.tabindex = true;
}
var stateContainer = f.stateContainer = $(innerElementHtml), templateW;
self._applyOverflow(f.stateContainer);
// move child element to content wrapper div of wijsuperpanel.
f.contentWrapper = stateContainer.children();
ele.contents().each(function (index, el) {
var jel = $(el);
if(jel.hasClass("wijmo-wijsuperpanel-header")) {
f.header = jel;
return;
}
if(jel.hasClass("wijmo-wijsuperpanel-footer")) {
f.footer = jel;
return;
}
f.contentWrapper[0].appendChild(el);
});
// append header to first element.
if(f.header !== undefined) {
ele.prepend(f.header);
}
ele[0].appendChild(stateContainer[0]);
// append footer to first element.
if(f.footer !== undefined) {
f.footer.insertAfter(stateContainer);
}
self._resetDom();
f.contentWrapper.css("float", "left");
f.contentWidth = f.contentWrapper.width();
f.contentHeight = f.contentWrapper.height();
f.contentWrapper.css("float", "");
},
_bindElementEvents: function () {
var self = this, ele = self.element, o = self.options, wn = self.widgetName, scrollEle = ele.find(".wijmo-wijsuperpanel-statecontainer"), scrollTop = scrollEle.scrollTop();
scrollEle.bind("scroll", function (event, data) {
var curScrollTop = $(this).scrollTop();
if(curScrollTop === scrollTop) {
//scroll horizontal
self._triggerScroll($(this).scrollLeft(), "h");
self._updateScrollValue($(this).scrollLeft(), "h");
} else {
//scroll vertical
self._triggerScroll(curScrollTop, "v");
self._updateScrollValue(curScrollTop, "v");
scrollTop = curScrollTop;
}
//self._triggerScroll();
});
if(o.keyboardSupport) {
if(self._keyboardBind === undefined) {
self._keyboardBind = true;
ele.bind("keydown." + wn, self, self._panelKeyDown);
}
} else {
ele.unbind("keydown." + wn, self._panelKeyDown);
self._keyboardBind = undefined;
}
if(!o.mouseWheelSupport) {
ele.bind("mousewheel", function (event) {
event.stopPropagation();
return false;
});
}
},
_setScrollingInterval: function (f, dir, self, large) {
var o = self.options;
if(dir.length > 0) {
f.internalFuncID = window.setInterval(function () {
self._doScrolling(dir, self, large);
}, o.keyDownInterval);
}
},
_triggerScroll: function (contentLeft, dir) {
var data = {
position: contentLeft,
dir: dir
};
this._trigger("scroll", null, data);
//this._trigger("scrolling", null, data);
//this._trigger("scrolled", null, data);
},
getKeyCodeEnum: /** @ignore */
function () {
if($.ui && $.ui.keyCode) {
return $.ui.keyCode;
}
if($.mobile && $.mobile.keyCode) {
return $.mobile.keyCode;
}
throw "keyCode object is not found";
},
_panelKeyDown: function (e) {
// Key down handler.
var self = e.data, o = self.options, shift, keycode, kCode = self.getKeyCodeEnum();
if(!o.keyboardSupport || o.disabled) {
return;
}
shift = e.shiftKey;
keycode = e.keyCode;
if(keycode === kCode.LEFT) {
self._doScrolling("left", self, shift);
} else if(keycode === kCode.RIGHT) {
self._doScrolling("right", self, shift);
} else if(keycode === kCode.UP) {
self._doScrolling("top", self, shift);
} else if(keycode === kCode.DOWN) {
self._doScrolling("bottom", self, shift);
}
e.stopPropagation();
e.preventDefault();
},
_doScrolling: function (dir, self, large) {
var value, orient, func, f = self._fields(), ele = f.stateContainer[0], animateOpt = {
}, scrollVal;
if(dir === "top" || dir === "bottom") {
orient = "v";
func = "scrollTop";
} else if(dir === "left" || dir === "right") {
orient = "h";
func = "scrollLeft";
}
if(large) {
value = self._getLargeChange(orient);
} else {
value = self._getSmallChange(orient);
}
scrollVal = ele[func];
if(dir === "top" || dir === "left") {
animateOpt[func] = scrollVal - value;
} else {
animateOpt[func] = scrollVal + value;
}
self._animateTo(animateOpt);
},
_getLargeChange: function (div) {
var self = this, f = self._fields(), largeChange, length = div == "h" ? f.clientWidth : f.clientHeight;
if(length) {
largeChange = length;
} else {
largeChange = f.stateContainer[div == "h" ? "width" : "height"]();
}
return largeChange;
},
_getSmallChange: function () {
return this._getLargeChange() / 2;
},
_setRounder: function (self, ele) {
var cornerCSS = this.options.wijCSS.cornerAll;
if(this.options.showRounder) {
ele.addClass(cornerCSS);
if(self._rounderAdded) {
return;
}
if($.browser.msie) {
return;
}
var key1, key, value, border;
key1 = key = "";
if($.browser.webkit) {
key = "WebkitBorderTopLeftRadius";
key1 = "WebkitBorderRadius";
} else if($.browser.mozilla) {
key = "MozBorderRadiusBottomleft";
key1 = "MozBorderRadius";
} else {
key = "border-top-left-radius";
key1 = "border-radius";
}
value = ele.css(key);
border = parseInt(value, 10);
ele.css(key1, border + 1);
self._rounderAdded = true;
self._radiusKey = key1;
} else {
ele.removeClass(cornerCSS);
}
},
_initResizer: function () {
// Initialize reseizer of wijsuperpanel.
var self = this, o = self.options, f = self._fields(), resizer = f.resizer, resizableOptions, oldstop;
if(!$.fn.resizable) {
return;
}
if(!resizer && o.allowResize) {
resizableOptions = o.resizableOptions;
oldstop = resizableOptions.stop;
resizableOptions.stop = function (e) {
self._resetDom();
self._trigger("resized");
if($.isFunction(oldstop)) {
oldstop(e);
}
};
f.resizer = resizer = self.element.resizable(resizableOptions);
}
if(!o.allowResize && f.resizer) {
resizer.resizable("destroy");
f.resizer = null;
}
},
_resetDom: function () {
var self = this, o = self.options, ele = self.element, f = self._fields(), width = ele.width(), height = ele.height();
//minus header and footer's height if they exist.
//fix #37099
if(f.header !== undefined) {
height -= f.header.outerHeight();
}
if(f.footer !== undefined) {
height -= f.footer.outerHeight();
}
if(f.stateContainer.length) {
f.stateContainer.css({
width: width,
height: height
});
f.clientWidth = f.stateContainer[0].clientWidth;
f.clientHeight = f.stateContainer[0].clientHeight;
}
},
_fields: function () {
var self = this, ele = self.element, key = self.widgetName + "-fields", d = self._fieldsStore;
if(d === undefined) {
d = {
};
ele.data(key, d);
self._fieldsStore = d;
}
return d;
},
_getScrollOffset: function (child1) {
var child = $(child1), f, cWrapper, childOffset, templateOffset, cWrapperOffset, tDistance, bDistance, lDistance, rDistance, result = {
left: null,
top: null
};
if(child.length === 0) {
return result;
}
f = this._fields();
cWrapper = f.contentWrapper;
//cWrapper = f.stateContainer;
childOffset = child.offset();
childOffset.leftWidth = childOffset.left + child.outerWidth();
childOffset.topHeight = childOffset.top + child.outerHeight();
cWrapperOffset = cWrapper.offset();
cWrapperOffset.leftWidth = cWrapperOffset.left + f.clientWidth;
cWrapperOffset.topHeight = cWrapperOffset.top + f.clientHeight;
lDistance = childOffset.left - cWrapperOffset.left;
if(childOffset.left < cWrapperOffset.left) {
result.left = lDistance;
} else if(childOffset.leftWidth > cWrapperOffset.leftWidth) {
rDistance = childOffset.leftWidth - cWrapperOffset.left - f.clientWidth;
if(lDistance < rDistance) {
result.left = lDistance;
} else {
result.left = rDistance;
}
}
tDistance = childOffset.top - cWrapperOffset.top;
if(childOffset.top < cWrapperOffset.top) {
result.top = tDistance;
} else if(childOffset.topHeight > cWrapperOffset.topHeight) {
bDistance = childOffset.topHeight - cWrapperOffset.top - f.clientHeight;
if(tDistance < bDistance) {
result.top = tDistance;
} else {
result.top = bDistance;
}
}
return result;
},
_initialize: function (f, ele, self) {
var wijCSS = self.options.wijCSS;
f.initialized = true;
ele.addClass([
"wijmo-wijsuperpanel",
wijCSS.widget,
wijCSS.content
].join(' '));
self._setRounder(self, ele);
self._createAdditionalDom(self, f, ele);
self._trigger("painted");
self._initScrollPosition();
},
_initScrollPosition: function () {
var o = this.options, hScroller = o.hScroller, vScroller = o.vScroller, hScrollValue = hScroller.scrollValue, vSCrollValue = vScroller.scrollValue, f = this._fields(), hScrollPx = hScrollValue ? this._scrollValueToPx(hScrollValue, "h") : 0, vScrollPx = vSCrollValue ? this._scrollValueToPx(vSCrollValue, "v") : 0;
if(hScrollValue) {
f.stateContainer.prop("scrollLeft", hScrollPx);
}
if(vSCrollValue) {
f.stateContainer.prop("scrollTop", vScrollPx);
}
},
_updateScrollValue: function (px, dir) {
var value = this.scrollPxToValue(px, dir), o = this.options, scroller = (dir === "h" ? "hScroller" : "vScroller");
o[scroller].scrollValue = value;
},
scrollPxToValue: /**
* Convert pixel to scroll value.
* For example, wijsuperpanel scrolled 50px
* which is value 1 after conversion.
* @param {number} px Length of scrolling.
* @param {string} dir Scrolling direction. Options are: "h" and "v".
*/
function (px, dir) {
var o = this.options, m = (dir === "h" ? "width" : "height"), m1 = (dir === "h" ? "contentWidth" : "contentHeight"), scroller = (dir === "h" ? "hScroller" : "vScroller"), f = this._fields(), cWrapper = f.stateContainer, size = //var tempWrapper = f.templateWrapper;
f[m1], contentHeight = cWrapper[m](), vMin = o[scroller].scrollMin, vMax = o[scroller].scrollMax, vRange = vMax - vMin, ret = vRange * px / (size - contentHeight) + vMin;
return ret;
},
_scrollValueToPx: function (value, dir) {
var o = this.options, m = (dir === "h" ? "width" : "height"), m1 = (dir === "h" ? "contentWidth" : "contentHeight"), scroller = (dir === "h" ? "hScroller" : "vScroller"), f = this._fields(), cWrapper = f.stateContainer, size = //var tempWrapper = f.templateWrapper;
f[m1], contentHeight = cWrapper[m](), vMin = o[scroller].scrollMin, vMax = o[scroller].scrollMax, vRange = vMax - vMin, ret = (value - vMin) * (size - contentHeight) / vRange;
return ret;
},
_animateTo: function (to) {
var self = this, ele = self.element, o = self.options, ao = o.animationOptions, f = self._fields();
f.stateContainer.animate(to, ao);
},
destroy: function () {
var self = this, ele = self.element, o = self.options, f = self._fields(), cWrapper, wijCSS = o.wijCSS;
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
if(f.resizer !== undefined) {
f.resizer.resizable("destroy");
}
ele.unbind("." + self.widgetName);
ele.removeClass([
"wijmo-wijsuperpanel",
wijCSS.widget,
wijCSS.content,
wijCSS.cornerAll
].join(' '));
cWrapper = f.contentWrapper;
cWrapper.contents().each(function (index, e) {
ele.append(e);
});
f.stateContainer.remove();
$.Widget.prototype.destroy.apply(self, arguments);
},
doScrolling: function (dir, large) {
/// <summary>
/// Do scrolling.
/// </summary>
/// <param name="dir" type="string">
/// Scrolling direction. Options are: "left", "right", "top" and "bottom".
/// </param>
/// <param name="large" type="Boolean">
/// Whether to scroll a large change.
/// </param>
this._doScrolling(dir, this, large);
},
paintPanel: function (unfocus) {
var self = this, ele = self.element, f = self._fields();
if(!f.initialized) {
this._initialize(f, ele, self);
}
},
needToScroll: function (child1) {
/// <summary>
/// Determine whether scoll the child DOM element to view
/// need to scroll the scroll bar
/// </summary>
/// <param name="child" type="DOMElement/JQueryObj">
/// The child to scroll to.
/// </param>
var offset = this._getScrollOffset(child1);
return offset.top !== null || offset.left !== null;
},
scrollChildIntoView: function (child1) {
/// <summary>
/// Scroll child DOM element into view.
/// Code Example:
/// $("selector").wijsuperpanel("scrollChildIntoView", $("li#reditem"));
/// </summary>
/// <param name="child" type="DOMElement/JQueryObj">
/// The child to scroll to.
/// </param>
var offset = this._getScrollOffset(child1), left = offset.left, top = offset.top;
this.scrollTo(left, top);
},
getContentElement: function () {
/// <summary>
/// Gets the content element of wijsuperpanel.
/// Code Example:
/// $("selector").wijsuperpanel("getContentElement");
/// </summary>
/// <returns type="JQueryObj" />
return this._fields().contentWrapper;
},
hScrollTo: function (x) {
/// <summary>
/// Scrolls to the indicated horizontal position.
/// Code Example:
/// $("selector").wijsuperpanel("hScrollTo", 100);
/// </summary>
/// <param name="x" type="Number">
/// The position to scroll to.
/// </param>
this._animateTo({
"scrollLeft": x
});
},
vScrollTo: function (y) {
/// <summary>
/// Scrolls to the indicated vertical position.
/// Code Example:
/// $("selector").wijsuperpanel("vScrollTo", 100);
/// </summary>
/// <param name="y" type="Number">
/// The position to scroll to.
/// </param>
this._animateTo({
"scrollTop": y
});
},
refresh: function () {
/// <summary>
/// Refreshes the wijsuperpanel.
/// Needs to be called after content being changed.
/// Code Example:
/// $("selector").wijsuperpanel("refresh");
/// </summary>
/// <returns type="Boolean">
/// Returns true if it is successful, else returns false.
/// </returns>
var self = this, f = self._fields();
self._applyOverflow(f.stateContainer);
self._resetDom();
},
scrollTo: function (x, y) {
/// <summary>
/// Scroll to specified position.
/// Code Example:
/// $("selector").wijsuperpanel("scrollTo", 100, 100);
/// </summary>
/// <param name="x" type="Number">
/// Horizontal position to scroll to.
/// </param>
/// <param name="y" type="Number">
/// Vertical position to scroll to.
/// </param>
this._animateTo({
"scrollTop": y,
"scrollLeft": x
});
}
});
//,
//scrollPxToValue: function (px, dir) {
// /// <summary>
// /// Convert pixel to scroll value.
// /// For example, wijsuperpanel scrolled 50px
// ///which is value 1 after conversion.
// /// </summary>
// /// <param name="px" type="Number">
// /// Length of scrolling.
// /// </param>
// /// <param name="dir" type="String">
// /// Scrolling direction. Options are: "h" and "v".
// /// </param>
// return px;
//}
wijsuperpanel.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, {
wijMobileCSS: {
header: "ui-header ui-bar-a",
content: "ui-body-c",
stateDefault: "ui-btn-up-c",
stateHover: "ui-btn-down-c",
stateActive: "ui-btn-down-c"
},
initSelector: /// <summary>
/// Selector option for auto self initialization.
/// This option is internal.
/// </summary>
":jqmData(role='wijsuperpanel')",
allowResize: false,
animationOptions: {
queue: false,
disabled: false,
duration: 250,
easing: undefined
},
hScroller: {
scrollBarVisibility: "auto",
scrollValue: null,
scrollMax: 100,
firstStepChangeFix: 0,
scrollMin: 0,
hoverEdgeSpan: 20
},
keyboardSupport: false,
keyDownInterval: 100,
mouseWheelSupport: true,
resizableOptions: {
handles: "all",
helper: "ui-widget-content wijmo-wijsuperpanel-helper"
},
resized: null,
painted: null,
scroll: null,
showRounder: true,
vScroller: {
scrollBarVisibility: "auto",
scrollValue: null,
scrollMax: 100,
scrollMin: 0,
firstStepChangeFix: 0,
hoverEdgeSpan: 20
}
});
$.wijmo.registerWidget("wijsuperpanel", wijsuperpanel.prototype);
}
})(wijmo.superpanel || (wijmo.superpanel = {}));
var superpanel = wijmo.superpanel;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/*globals jQuery */
/*
* Depends:
* jquery-1.4.2.js
* jquery.ui.core.js
* jquery.ui.widget.js
*
*/
(function (textbox) {
"use strict";
var $ = jQuery, widgetName = "wijtextbox";
/** @widget */
var wijtextbox = (function (_super) {
__extends(wijtextbox, _super);
function wijtextbox() {
_super.apply(this, arguments);
}
wijtextbox.prototype._create = function () {
var self = this, e = self.element, wijCSS = self.options.wijCSS, allowedNodes = {
'input': true,
'textarea': true
}, allowedInputTypes = {
'text': true,
'password': true,
'email': true,
'url': true
}, nodeName = e.get(0).nodeName.toLowerCase();
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
if(!allowedNodes.hasOwnProperty(nodeName)) {
return;
}
if((nodeName === 'input') && self.element.attr("type") && !allowedInputTypes.hasOwnProperty(self.element.attr("type").toLowerCase())) {
return;
}
e.addClass(wijCSS.wijtextbox).addClass(wijCSS.widget).addClass(wijCSS.stateDefault).addClass(wijCSS.cornerAll);
self.element.bind("mouseover." + self.widgetName, function () {
e.addClass(wijCSS.stateHover);
}).bind("mouseout." + self.widgetName, function () {
e.removeClass(wijCSS.stateHover);
}).bind("mousedown." + self.widgetName, function () {
e.addClass(wijCSS.stateActive);
}).bind("mouseup." + self.widgetName, function () {
e.removeClass(wijCSS.stateActive);
}).bind("focus." + self.widgetName, function () {
e.addClass(wijCSS.stateFocus);
}).bind("blur." + self.widgetName, function () {
e.removeClass(wijCSS.stateFocus);
});
//for case 20899
if(e.is(":disabled")) {
self._setOption("disabled", true);
e.addClass(wijCSS.stateDisabled);
} else {
self._setOption("disabled", false);
e.removeClass(wijCSS.stateDisabled);
}
};
wijtextbox.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this, wijCSS = self.options.wijCSS;
self.element.removeClass(wijCSS.widget).removeClass(wijCSS.stateDefault).removeClass(wijCSS.cornerAll).removeClass(wijCSS.stateHover).removeClass(wijCSS.stateActive).removeClass(wijCSS.wijtextbox).unbind("." + self.widgetName);
_super.prototype.destroy.call(this);
};
return wijtextbox;
})(wijmo.wijmoWidget);
textbox.wijtextbox = wijtextbox;
var wijtextbox_options = (function () {
function wijtextbox_options() {
/** Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijtextbox')";
/** wijtextbox css, extend from $.wijmo.wijCSS
* @ignore
*/
this.wijCSS = {
wijtextbox: "wijmo-wijtextbox"
};
}
return wijtextbox_options;
})();
;
wijtextbox.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijtextbox_options());
$.wijmo.registerWidget(widgetName, wijtextbox.prototype);
})(wijmo.textbox || (wijmo.textbox = {}));
var textbox = wijmo.textbox;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/// <reference path="../wijsuperpanel/jquery.wijmo.wijsuperpanel.ts" />
/*globals jQuery,document,window*/
/*
* Depends:
* jquery.js
* jquery.ui.js
* jquery.mousewheel.js
* jquery.bgiframe.js
* jquery.wijmo.wijsuperpanel.js
*
*/
(function (dropdown) {
"use strict";
var $ = jQuery, widgetName = "wijdropdown";
/** @widget */
var wijdropdown = (function (_super) {
__extends(wijdropdown, _super);
function wijdropdown() {
_super.apply(this, arguments);
}
wijdropdown.prototype._setOption = function (key, value) {
var self = this, wijCSS = self.options.wijCSS;
_super.prototype._setOption.call(this, key, value);
if(key === "disabled") {
self._labelWrap.toggleClass(wijCSS.stateDisabled, value);
self._label.toggleClass(wijCSS.stateDisabled, value);
self.element.attr("disabled", value ? "disabled" : "");
}
};
wijdropdown.prototype._create = function () {
var self = this, ele = self.element;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
if(ele.get(0).tagName.toLowerCase() !== "select") {
return;
}
if(ele.is(":visible")) {
self._activeItem = null;
self._createSelect();
self._bindEvents();
self.needInit = false;
} else {
self.needInit = true;
}
//update for visibility change
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
self.refresh();
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
}, "wijdropdown");
}
};
wijdropdown.prototype._createSelect = function () {
this.cssWidth = this.element.get(0).style.width;
var self = this, o = self.options, wijCSS = self.options.wijCSS, ele = self.element, width = ele.width(), eleWidth = width, selectWrap = //height = ele.height(),
ele.wrap("<div></div>").parent().addClass(wijCSS.helperHidden), container = selectWrap.wrap("<div></div>").parent().attr("role", "select").addClass(wijCSS.wijdropdown).addClass(wijCSS.widget).addClass(//ui-widwijmo-wijdropdownt-content
wijCSS.stateDefault).addClass(wijCSS.cornerAll).addClass(wijCSS.helperClearFix), label = $("<label></label>").addClass(wijCSS.wijdropdownLabel).addClass(wijCSS.cornerAll).attr("id", ele.get(0).id + "_select").attr("name", ele.attr("name") || ""), rightTrigger = $("<div></div>").addClass(wijCSS.wijdropdownTrigger).addClass(wijCSS.stateDefault).addClass(wijCSS.cornerRight), labelWrap = $("<a href=\"#\"></a>"), listContainer = $("<div>").addClass(wijCSS.wijmodropdown), list = $("<ul></ul>").addClass(wijCSS.wijdropdownList).addClass(wijCSS.content).addClass(wijCSS.widget).addClass(wijCSS.cornerAll).addClass(wijCSS.helperReset).appendTo(listContainer);
$("<span></span>").addClass(wijCSS.icon).addClass(wijCSS.iconArrowDown).appendTo(rightTrigger);
if(ele.get(0).tabIndex !== "") {
labelWrap.attr("tabindex", ele.attr("tabindex"));
}
if(ele.get(0).disabled !== false) {
self.options.disabled = true;
}
if(self.options.disabled) {
labelWrap.addClass(wijCSS.stateDisabled);
label.addClass(wijCSS.stateDisabled);
}
labelWrap.append(label);
container.append(selectWrap).append(labelWrap).append(rightTrigger);
if(o.ensureDropDownOnBody) {
listContainer.wrap($("<div></div>").addClass(wijCSS.wijdropdown)).parent().appendTo("body").css("position", "absolute");
} else {
container.append(listContainer);
}
//return;
//eleWidth = Math.max(width, container.width());
eleWidth += parseInt(label.css("padding-left").replace(/px/, ""), 10);
eleWidth += parseInt(label.css("padding-right").replace(/px/, ""), 10);
eleWidth -= 16;
container.width(eleWidth);
self._container = container;
self._buildList(list, listContainer, eleWidth);
self._rightTrigger = rightTrigger;
self._label = label;
self._listContainer = listContainer;
self._list = list;
self._value = ele.val();
//self._selectedIndex = ele.find("option:selected").index();
self._selectedIndex = $('option', ele).index(ele.find("option:selected"));
self._selectWrap = selectWrap;
self._labelWrap = labelWrap;
//update for fixed tooltip can't take effect
container.attr("title", ele.attr("title"));
ele.removeAttr("title");
};
wijdropdown.prototype._buildList = function (list, listContainer, eleWidth) {
var self = this, wijCSS = self.options.wijCSS, ele = self.element, height;
listContainer.show();
ele.children().each(function (i, n) {
var item = $(n), group, groupText, goupItems;
if(item.is("option")) {
list.append(self._buildItem(item));
} else {
group = $("<li></li>").addClass(wijCSS.wijdropdownOptgroup);
groupText = $("<span>" + item.attr("label") + "</span>").addClass(wijCSS.wijdropdownOptgroupHeader).addClass(wijCSS.priorityPrimary);
goupItems = $("<ul></ul>").addClass(wijCSS.helperReset).addClass(wijCSS.wijdropdownItems);
item.children("option").each(function () {
goupItems.append(self._buildItem($(this)));
return this;
});
group.append(groupText).append(goupItems);
list.append(group);
}
return this;
});
//update for fixing height setting is incorrect when
//execute refresh at 2011/11/30
listContainer.height("");
//end for height setting
height = listContainer.height();
height = list.outerHeight() < height ? list.outerHeight() : height;
//fixed the issue that when the select width is not set, the dropdown's width is too small,
// and the dropdown's label and items will wrap line.
if(this.cssWidth === "" || this.cssWidth === "auto") {
if(list.outerWidth() > eleWidth - 19) {
eleWidth = list.outerWidth() + 10;
this._container.width(eleWidth);
}
}
listContainer.css({
height: height,
width: eleWidth
});
//update for fixing can't show all dropdown items by wuhao at 2012/2/24
//fixed the bug 30486
//list.setOutWidth(list.parent().parent().innerWidth() - 18);
if($.browser.msie && /^[8]\.[0-9]+/.test($.browser.version)) {
//list.setOutWidth(list.parent().parent().innerWidth() - 19);
list.setOutWidth(eleWidth - 19);
} else {
//list.setOutWidth(list.parent().parent().innerWidth() - 18);
list.setOutWidth(eleWidth - 18);
}
//end for issue
if(listContainer.data("wijmoWijsuperpanel")) {
listContainer.wijsuperpanel("paintPanel");
self.superpanel = listContainer.data("wijmoWijsuperpanel");
} else {
self.superpanel = listContainer.wijsuperpanel().data("wijmoWijsuperpanel");
}
if($.fn.bgiframe) {
self.superpanel.element.bgiframe();
}
//update for fixing can't show all dropdown items by wuhao at 2012/2/24
//list.setOutWidth(list.parent().parent().innerWidth());
if(!self.superpanel.vNeedScrollBar) {
//fixed the bug 30486
if($.browser.msie && /^[8]\.[0-9]+/.test($.browser.version)) {
//list.setOutWidth(list.parent().parent().innerWidth() - 1);
list.setOutWidth(eleWidth - 1);
} else {
//list.setOutWidth(list.parent().parent().innerWidth());
list.setOutWidth(eleWidth);
}
self.superpanel.refresh();
}
//end for issue
listContainer.hide();
};
wijdropdown.prototype._handelEvents = function (ele) {
var self = this, wijCSS = self.options.wijCSS, namespace = "." + self.widgetName, element = self.element;
ele.bind("click" + namespace, function (e) {
if(self.options.disabled) {
return;
}
if(self._listContainer.is(":hidden")) {
self._show();
} else {
self._hide();
}
element.click();
if(ele.get(0) === self._label.get(0)) {
e.preventDefault();
} else {
self._labelWrap.focus();
}
}).bind("mouseover" + namespace, function () {
if(self.options.disabled) {
return;
}
self._label.addClass(wijCSS.stateHover);
self._rightTrigger.addClass(wijCSS.stateHover);
element.trigger('mouseover');
}).bind("mouseout" + namespace, function () {
if(self.options.disabled) {
return;
}
self._label.removeClass(wijCSS.stateHover);
self._rightTrigger.removeClass(wijCSS.stateHover);
element.trigger('mouseout');
}).bind("mousedown" + namespace, function () {
if(self.options.disabled) {
return;
}
self._label.addClass(wijCSS.stateActive);
self._rightTrigger.addClass(wijCSS.stateActive);
element.trigger('mousedown');
}).bind("mouseup" + namespace, function () {
if(self.options.disabled) {
return;
}
self._label.removeClass(wijCSS.stateActive);
self._rightTrigger.removeClass(wijCSS.stateActive);
element.trigger('mouseup');
});
};
wijdropdown.prototype._bindEvents = function () {
var self = this, wijCSS = self.options.wijCSS, namespace = "." + self.widgetName, label = self._label, rightTrigger = self._rightTrigger, labelWrap = self._labelWrap, listContainer = self._listContainer, ele = self.element, ischrome = false, offset;
self._handelEvents(self._label);
self._handelEvents(self._rightTrigger);
$(window).bind("resize", function (e) {
self._setListContainerPosition();
}) , $(document).bind("mouseup" + namespace, function (e) {
if(listContainer.is(":hidden")) {
label.removeClass(wijCSS.stateFocus);
rightTrigger.removeClass(wijCSS.stateFocus);
return;
}
offset = listContainer.offset();
if(e.target === label.get(0) || e.target === rightTrigger.get(0) || e.target === rightTrigger.children().get(0)) {
return;
}
//if click listContainer, list will hide itself in its click event.
if($(e.target).closest(listContainer).length > 0) {
return;
}
if(e.pageX < offset.left || e.pageX > offset.left + listContainer.width() || e.pageY < offset.top || e.pageY > offset.top + listContainer.height()) {
label.removeClass(wijCSS.stateFocus);
rightTrigger.removeClass(wijCSS.stateFocus);
self._hide();
}
});
listContainer.bind("click" + namespace, function (e) {
var target = $(e.target);
if(target.closest("li." + wijCSS.wijdropdownItem, $(this).get(0)).length > 0) {
self._setValue();
listContainer.css("z-index", "");
if($.browser.msie && /^[6,7].[0-9]+/.test($.browser.version)) {
listContainer.parent().css("z-index", "");
}
listContainer.hide();
self._setValueToEle();
//self.oldVal = ele.val();
//ele.val(self._value);
//if (self.oldVal !== self._value) {
// ele.trigger("change");
//}
}
ele.click();
});
labelWrap.bind("keydown" + namespace, function (e) {
if(self.options.disabled) {
return;
}
var keyCode = $.ui.keyCode;
switch(e.which) {
case keyCode.UP:
case keyCode.LEFT:
self._previous();
self._setValue();
//update for issue that can't get value with keydown
//by wh at 2012/1/19
self._setValueToEle();
//end for issue about keydown
break;
case keyCode.DOWN:
case keyCode.RIGHT:
self._next();
self._setValue();
//update for issue that can't get value with keydown
//by wh at 2012/1/19
self._setValueToEle();
//end for issue about keydown
break;
case keyCode.PAGE_DOWN:
self._nextPage();
self._setValue();
//update for issue that can't get value with keydown
//by wh at 2012/1/19
self._setValueToEle();
//end for issue about keydown
break;
case keyCode.PAGE_UP:
self._previousPage();
self._setValue();
//update for issue that can't get value with keydown
//by wh at 2012/1/19
self._setValueToEle();
//end for issue about keydown
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
self._setValue();
self._listContainer.hide();
//update for issue that can't get value with keydown
//by wh at 2012/1/19
self._setValueToEle();
//end for issue about keydown
break;
}
if(e.which !== keyCode.TAB) {
e.preventDefault();
}
ele.trigger('keydown');
}).bind("focus" + namespace, function () {
if(self.options.disabled) {
return;
}
label.addClass(wijCSS.stateFocus);
rightTrigger.addClass(wijCSS.stateFocus);
ele.focus();
}).bind("blur" + namespace, function () {
if(self.options.disabled) {
return;
}
label.removeClass(wijCSS.stateFocus);
rightTrigger.removeClass(wijCSS.stateFocus);
ele.trigger('blur');
}).bind("keypress" + namespace, function () {
if(self.options.disabled) {
return;
}
ele.trigger('keypress');
}).bind("keyup" + namespace, function () {
if(self.options.disabled) {
return;
}
ele.trigger('keyup');
});
ischrome = /chrome/.test(navigator.userAgent.toLowerCase());
if(ischrome || $.browser.safari) {
labelWrap.bind("click" + namespace, function () {
labelWrap.focus();
});
rightTrigger.bind("mouseout" + namespace, function () {
if(self.options.disabled) {
return;
}
label.removeClass(wijCSS.stateFocus);
rightTrigger.removeClass(wijCSS.stateFocus);
});
}
};
wijdropdown.prototype._setListContainerPosition = function () {
var self = this, o = self.options, _offset;
if(!o.ensureDropDownOnBody) {
return;
}
_offset = self._container.offset();
self._listContainer.parent().offset({
left: _offset.left,
top: _offset.top + self._container.outerHeight()
});
};
wijdropdown.prototype._init = function () {
var self = this;
self._initActiveItem();
if(self._activeItem) {
self._label.text(self._activeItem.text());
}
};
wijdropdown.prototype._buildItem = function ($item) {
var val = $item.val(), text = $item.text(), self = this, wijCSS = self.options.wijCSS, $li;
if(text === "") {
text = " ";
}
$li = $("<li></li>").addClass(wijCSS.wijdropdownItem).addClass(wijCSS.cornerAll).append($("<span>" + text + "</span>")).mousemove(function (event) {
var current = $(event.target).closest("." + wijCSS.wijdropdownItem);
if(current !== this.last) {
self._activate($(this));
}
this.last = $(event.target).closest("." + wijCSS.wijdropdownItem);
}).attr("role", "option");
$li.data("value", val);
return $li;
};
wijdropdown.prototype._show = function () {
var self = this, listContainer = self._listContainer, showingAnimation = self.options.showingAnimation;
self._setListContainerPosition();
listContainer.css("z-index", "100000");
if($.browser.msie && /^[6,7]\.[0-9]+/.test($.browser.version)) {
listContainer.parent().css("z-index", "99999");
}
if(showingAnimation) {
//update for fixing 20652 issue by wh at 2012/3/19
//listContainer.stop().show(
listContainer.show(//end for fixing issue 20652
showingAnimation.effect, showingAnimation.options, showingAnimation.speed, function () {
self._initActiveItem();
});
} else {
listContainer.show();
}
};
wijdropdown.prototype._hide = function () {
var self = this, listContainer = self._listContainer, hidingAnimation = self.options.hidingAnimation;
if(listContainer.is(":hidden")) {
return;
}
if(hidingAnimation) {
//update for fixing 20652 issue by wh at 2012/3/19
//listContainer.stop(false, true).hide(
listContainer.hide(//end for fixing issue 20652
hidingAnimation.effect, hidingAnimation.options, hidingAnimation.speed, function () {
if($.isFunction(hidingAnimation.callback)) {
hidingAnimation.callback.apply(self, arguments);
}
if($.browser.msie && /^[6,7]\.[0-9]+/.test($.browser.version)) {
listContainer.parent().css("z-index", "");
}
listContainer.css("z-index", "");
});
} else {
if($.browser.msie && $.browser.version === "6.0") {
listContainer.parent().css("z-index", "");
}
listContainer.css("z-index", "");
listContainer.hide();
}
};
wijdropdown.prototype._setValue = function () {
var self = this, wijCSS = self.options.wijCSS, listContainer = self._listContainer, top, height;
if(self._activeItem) {
self._label.text(self._activeItem.text());
self._value = self._activeItem.data("value");
//self._selectedIndex = self._activeItem.index();
self._selectedIndex = $('li.' + wijCSS.wijdropdownItem, listContainer).index(self._activeItem);
if(self.superpanel.vNeedScrollBar) {
top = self._activeItem.offset().top;
height = self._activeItem.outerHeight();
if(listContainer.offset().top > top) {
listContainer.wijsuperpanel("scrollTo", 0, top - self._list.offset().top);
} else if(listContainer.offset().top < top + height - listContainer.innerHeight()) {
listContainer.wijsuperpanel("scrollTo", 0, top + height - listContainer.height() - self._list.offset().top);
}
}
}
};
wijdropdown.prototype._setValueToEle = function () {
var self = this, ele = self.element, oldSelectedItem = ele.find(":selected"), oldSelectedIndex = //oldSelectedIndex = oldSelectedItem.index(),
$('option', ele).index(oldSelectedItem), selectedIndex = self._selectedIndex;
//self.oldVal = ele.val();
//ele.val(self._value);
if(oldSelectedIndex !== selectedIndex) {
if($.browser.mozilla) {
ele.val(self._value);
}
oldSelectedItem.removeAttr('selected');
ele.find("option:eq(" + selectedIndex + ")").prop("selected", true);
ele.trigger("change");
}
//if (self.oldVal !== self._value) {
// ele.trigger("change");
//}
};
wijdropdown.prototype._initActiveItem = function () {
var self = this, wijCSS = self.options.wijCSS;
if(self._value !== undefined) {
if(self._selectedIndex === -1) {
self._activate(self._list.find("li." + wijCSS.wijdropdownItem).eq(0));
return;
}
self._list.find("li." + wijCSS.wijdropdownItem).each(function (idx) {
if(idx === self._selectedIndex) {
self._activate($(this));
return false;
}
//if ($(this).data("value") === self._value) {
// self._activate($(this));
//}
});
}
};
wijdropdown.prototype._activate = function (item) {
var self = this, wijCSS = self.options.wijCSS;
self._deactivate();
self._activeItem = item;
self._activeItem.addClass(wijCSS.stateHover).attr("aria-selected", true);
};
wijdropdown.prototype._deactivate = function () {
var self = this, wijCSS = self.options.wijCSS;
if(self._activeItem) {
self._activeItem.removeClass(wijCSS.stateHover).attr("aria-selected", false);
}
};
wijdropdown.prototype._next = function () {
this._move("next", "first");
};
wijdropdown.prototype._previous = function () {
this._move("prev", "last");
};
wijdropdown.prototype._nextPage = function () {
this._movePage("first");
};
wijdropdown.prototype._previousPage = function () {
this._movePage("last");
};
wijdropdown.prototype.refresh = /** Use the refresh method to set the drop-down element's style. */
function () {
var self = this, wijCSS = self.options.wijCSS, ele = self.element, containerWidth;
if(self.needInit) {
if(self.element.is(":visible")) {
self._activeItem = null;
self._createSelect();
self._bindEvents();
self._init();
self.needInit = false;
}
} else {
if(!self._list) {
return;
}
self._listContainer.show();
//update for fixing width settings is wrong when
//execute refresh method at 2011/11/30
//containerWidth = self._listContainer.width();
//self._selectWrap.removeClass(wijCSS.helperHidden);
//containerWidth = self.element.width();
//containerWidth += parseInt(self._label.css("padding-left")
// .replace(/px/, ""), 10);
//containerWidth += parseInt(self._label.css("padding-right")
// .replace(/px/, ""), 10);
//containerWidth -= 16;
//self._container.width(containerWidth);
//self._selectWrap.addClass(wijCSS.helperHidden);
//end for fixing width settings at 2011/11/30
self._list.empty();
self._buildList(self._list, self._listContainer, containerWidth);
self._value = self.element.val();
//self._selectedIndex = ele.find("option :selected").index();
self._selectedIndex = $('option', ele).index(ele.find("option:selected"));
self._initActiveItem();
if(self._activeItem) {
self._label.text(self._activeItem.text());
}
}
};
wijdropdown.prototype._move = function (direction, edge) {
var self = this, wijCSS = self.options.wijCSS, $nextLi, next;
if(!self._activeItem) {
self._activate(self._list.find("." + wijCSS.wijdropdownItem + ":" + edge));
return;
}
$nextLi = self._activeItem[direction]().eq(0);
if($nextLi.length) {
next = self._getNextItem($nextLi, direction, edge);
} else if(self._activeItem.closest("." + wijCSS.wijdropdownOptgroup).length) {
next = self._getNextItem(self._activeItem.closest("." + wijCSS.wijdropdownOptgroup)[direction](), direction, edge);
}
if(next && next.length) {
self._activate(next);
} else {
self._activate(self._list.find("." + wijCSS.wijdropdownItem + ":" + edge));
}
};
wijdropdown.prototype._movePage = function (direction) {
//argu: "first","last"
var self = this, wijCSS = self.options.wijCSS, base, height, result, antiDirection = direction === "first" ? "last" : "first";
if(self.superpanel.vNeedScrollBar) {
base = self._activeItem.offset().top;
height = self.options.height;
result = self._list.find("." + wijCSS.wijdropdownItem).filter(function () {
var close = $(this).offset().top - base + (direction === "first" ? -height : height) + $(this).height(), lineheight = $(this).height();
return close < lineheight && close > -lineheight;
});
if(!result.length) {
result = self._list.find("." + wijCSS.wijdropdownItem + ":" + antiDirection);
}
self._activate(result);
} else {
self._activate(self._list.find("." + wijCSS.wijdropdownItem + ":" + (!self._activeItem ? direction : antiDirection)));
}
};
wijdropdown.prototype._getNextItem = function (next, direction, edge) {
var wijCSS = this.options.wijCSS;
if(next.length) {
if(next.is("." + wijCSS.wijdropdownOptgroup)) {
if(!!next.find(">ul>li." + wijCSS.wijdropdownItem).length) {
return next.find(">ul>li." + wijCSS.wijdropdownItem + ":" + edge).eq(0);
} else {
this._getNextItem(next[direction]().eq(0));
}
} else {
return next;
}
}
};
wijdropdown.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this, wijCSS = self.options.wijCSS;
//update for fixed tooltip can't take effect
this.element.attr("title", this._container.attr("title"));
/// Remove the functionality completely.
/// This will return the element back to its pre-init state.
this.element.closest("." + wijCSS.wijdropdown).find(">div." + wijCSS.wijdropdownTrigger + ",>div." + wijCSS.wijmodropdown + ",>a").remove();
this._listContainer.remove();
this.element.unwrap().unwrap().removeData("maxZIndex");
_super.prototype.destroy.call(this);
};
return wijdropdown;
})(wijmo.wijmoWidget);
dropdown.wijdropdown = wijdropdown;
;
var wijdropdown_options = (function () {
function wijdropdown_options() {
/** Selector option for auto self initialization.
* @ignore
*/
this.initSelector = ":jqmData(role='wijdropdown')";
/** wijdropdown css, extend from $.wijmo.wijCSS.
* @ignore
*/
this.wijCSS = {
wijmodropdown: "wijmo-dropdown",
wijdropdown: "wijmo-wijdropdown",
wijdropdownLabel: "wijmo-dropdown-label",
wijdropdownTrigger: "wijmo-dropdown-trigger",
wijdropdownList: "wijmo-dropdown-list",
wijdropdownOptgroup: "wijmo-dropdown-optgroup",
wijdropdownOptgroupHeader: "wijmo-optgroup-header",
wijdropdownItems: "wijmo-dropdown-items",
wijdropdownItem: "wijmo-dropdown-item"
};
/** A value indicates the z-index of wijdropdown. */
this.zIndex = 1000;
/** A value that specifies the animation options for a drop-down list
* when it is visible.
* @type {object}
* @example
* var animationOptions = {
* animated: "Drop", duration: 1000 };
* $("#tags").wijdropdown("option", "showingAnimation", animationOptions)
*/
this.showingAnimation = {
effect: "blind"
};
/** A value that specifies the animation options such as the animation effect and
* duration for the drop-down list when it is hidden.
* @type {object}
* @example
* var animationOptions = {
* animated: "Drop", duration: 1000 };
* $("#tags").wijdropdown("option", "hidingAnimation", animationOptions)
*/
this.hidingAnimation = {
effect: "blind"
};
/** A value indicating the dropdown element will be append to the body or dropdown container.
* @remarks
* If the value is true, the dropdown list will be appended to body element.
* else it will append to the dropdown container.
*/
this.ensureDropDownOnBody = false;
}
return wijdropdown_options;
})();
;
wijdropdown.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijdropdown_options());
$.wijmo.registerWidget(widgetName, wijdropdown.prototype);
})(wijmo.dropdown || (wijmo.dropdown = {}));
var dropdown = wijmo.dropdown;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/*globals jQuery*/
/*
* Depends:
* jquery-1.4.2.js
* jquery.ui.core.js
* jquery.ui.widget.js
*
*
*/
(function (checkbox) {
"use strict";
var $ = jQuery, widgetName = "wijcheckbox", _csspre = "wijcheckbox", checkboxId = 0;
/** @widget */
var wijcheckbox = (function (_super) {
__extends(wijcheckbox, _super);
function wijcheckbox() {
_super.apply(this, arguments);
}
wijcheckbox.prototype._init = function () {
var self = this, ele = self.element, o = self.options, checkboxElement, label, targetLabel, boxElement, iconElement;
if(ele.is(":checkbox")) {
if(!ele.attr("id")) {
ele.attr("id", _csspre + checkboxId);
checkboxId += 1;
}
if(ele.parent().is("label")) {
checkboxElement = ele.parent().wrap($("<div></div>").addClass(o.wijCSS.wijcheckboxInputwrapper)).parent().wrap("<div></div>").parent().addClass(o.wijCSS.wijcheckbox).addClass(o.wijCSS.widget);
label = ele.parent();
label.attr("for", ele.attr("id"));
checkboxElement.find("." + o.wijCSS.wijcheckboxInputwrapper).append(ele);
checkboxElement.append(label);
} else {
checkboxElement = ele.wrap($("<div></div>").addClass(o.wijCSS.wijcheckboxInputwrapper)).parent().wrap("<div></div>").parent().addClass(o.wijCSS.wijcheckbox).addClass(o.wijCSS.widget);
}
targetLabel = $("label[for='" + ele.attr("id") + "']");
if(targetLabel.length > 0) {
checkboxElement.append(targetLabel);
targetLabel.attr("labelsign", "C1");
}
if(ele.is(":disabled")) {
self._setOption("disabled", true);
}
boxElement = $("<div></div>").addClass(o.wijCSS.wijcheckboxBox).addClass(o.wijCSS.widget).addClass(o.disabled ? o.wijCSS.stateDisabled : o.wijCSS.stateDefault).addClass(o.wijCSS.cornerAll).append($("<span></span>").addClass(o.wijCSS.wijcheckboxIcon));
iconElement = boxElement.children("." + o.wijCSS.wijcheckboxIcon);
checkboxElement.append(boxElement);
ele.data("iconElement", iconElement);
ele.data("boxElement", boxElement);
ele.data("checkboxElement", checkboxElement);
boxElement.removeClass(o.wijCSS.wijcheckboxRelative).attr("role", "checkbox").bind("mouseover", function () {
ele.mouseover(null);
}).bind("mouseout", function () {
ele.mouseout(null);
});
if(targetLabel.length === 0 || targetLabel.html() === "") {
boxElement.addClass(o.wijCSS.wijcheckboxRelative);
}
ele.bind("click.checkbox", function (e) {
if(o.disabled) {
return;
}
self.refresh(e);
self._trigger("changed", null, {
checked: self.options.checked
});
}).bind("focus.checkbox", function () {
if(o.disabled) {
return;
}
boxElement.removeClass(o.wijCSS.stateDefault).addClass(o.wijCSS.stateFocus);
}).bind("blur.checkbox", function () {
if(o.disabled) {
return;
}
boxElement.removeClass(o.wijCSS.stateFocus).not("." + o.wijCSS.stateHover).addClass(o.wijCSS.stateDefault);
}).bind("keydown.checkbox", function (e) {
if(e.keyCode === 32) {
if(o.disabled) {
return;
}
self.refresh(null);
}
});
boxElement.bind("click.checkbox", function (e) {
if(o.disabled) {
return;
}
ele.get(0).checked = !ele.get(0).checked;
ele.change();
ele.focus();
self.refresh(e);
self._trigger("changed", null, {
checked: self.options.checked
});
});
self._initCheckState();
self.refresh(null);
checkboxElement.bind("mouseover.checkbox", function (e) {
if(o.disabled) {
return;
}
boxElement.removeClass(o.wijCSS.stateDefault).addClass(o.wijCSS.stateHover);
}).bind("mouseout.checkbox", function (e) {
if(o.disabled) {
return;
}
boxElement.removeClass(o.wijCSS.stateHover).not("." + o.wijCSS.stateFocus).addClass(o.wijCSS.stateDefault);
});
//update for fixed tooltip can't take effect
checkboxElement.attr("title", ele.attr("title"));
}
};
wijcheckbox.prototype._create = function () {
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
};
wijcheckbox.prototype._setOption = function (key, value) {
var self = this, originalCheckedState = self.options.checked;
_super.prototype._setOption.call(this, key, value);
if(key === 'checked') {
self.element.get(0).checked = value;
self.refresh(null);
if(originalCheckedState !== value) {
self._trigger("changed", null, {
checked: value
});
}
}
};
wijcheckbox.prototype._initCheckState = function () {
var self = this, o = self.options;
if(o.checked !== undefined && o.checked !== null) {
self.element.get(0).checked = o.checked;
}
};
wijcheckbox.prototype.refresh = /** Use the refresh method to set the checkbox element's style.
* @param {object} e The event that fires the refresh the checkbox.
*/
function (e) {
var self = this, o = self.options;
o.checked = self.element.get(0).checked;
self.element.data("iconElement").toggleClass(o.wijCSS.icon + " " + o.wijCSS.iconCheck, self.element.get(0).checked);
self.element.data("boxElement").toggleClass(o.wijCSS.stateActive, self.element.get(0).checked).attr("aria-checked", self.element.get(0).checked);
self.element.data("checkboxElement").toggleClass(o.wijCSS.stateChecked, self.element.get(0).checked);
if(e) {
e.stopPropagation();
}
};
wijcheckbox.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this, boxelement = self.element.parent().parent();
boxelement.children("div." + self.options.wijCSS.wijcheckboxBox).remove();
self.element.unwrap();
self.element.unwrap();
_super.prototype.destroy.call(this);
};
return wijcheckbox;
})(wijmo.wijmoWidget);
checkbox.wijcheckbox = wijcheckbox;
var wijcheckbox_options = (function () {
function wijcheckbox_options() {
/** Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijcheckbox')";
/** wijcheckbox css, extend from $.wijmo.wijCSS
* @ignore
*/
this.wijCSS = {
wijcheckbox: "wijmo-checkbox",
wijcheckboxBox: "wijmo-checkbox-box",
wijcheckboxIcon: "wijmo-checkbox-icon",
wijcheckboxInputwrapper: "wijmo-checkbox-inputwrapper",
wijcheckboxRelative: "wijmo-checkbox-relative"
};
/** wijcheckbox css, extend from $.wijmo.wijCSS
* @ignore
*/
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body-c",
stateDefault: "ui-btn-up-c",
stateHover: "ui-btn-down-c",
stateActive: "ui-btn-down-b"
};
/** Causes the checkbox to appear with a checkmark.
* @type {boolean}
*/
this.checked = null;
/** A function that is called when the checked state changes.
* @event
* @dataKey {boolean} checked the state of checkbox.
*/
this.changed = null;
}
return wijcheckbox_options;
})();
;
wijcheckbox.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijcheckbox_options());
$.wijmo.registerWidget(widgetName, wijcheckbox.prototype);
})(wijmo.checkbox || (wijmo.checkbox = {}));
var checkbox = wijmo.checkbox;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/*globals jQuery*/
/*
* Depends:
* jquery-1.4.2.js
* jquery.ui.core.js
* jquery.ui.widget.js
*
*/
(function (radio) {
"use strict";
var $ = jQuery, widgetName = "wijradio", _radiobuttonPre = "wijmo-wijradio", radiobuttonId = 0;
/** @widget */
var wijradio = (function (_super) {
__extends(wijradio, _super);
function wijradio() {
_super.apply(this, arguments);
}
wijradio.prototype._create = function () {
var self = this, ele = self.element, wijCSS = self.options.wijCSS, eleChkState, radiobuttonElement, label, targetLabel, boxElement, iconElement;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
if(ele.is(":radio")) {
if(!ele.attr("id")) {
ele.attr("id", _radiobuttonPre + radiobuttonId);
radiobuttonId += 1;
}
if(ele.parent().is("label")) {
radiobuttonElement = ele.parent().wrap($("<div></div>").addClass(wijCSS.wijradioInputwrapper)).parent().wrap("<div></div>").parent().addClass(wijCSS.wijradio).addClass(wijCSS.widget);
label = ele.parent();
label.attr("for", ele.attr("id"));
radiobuttonElement.find("." + wijCSS.wijradioInputwrapper).append(ele);
radiobuttonElement.append(label);
} else {
radiobuttonElement = ele.wrap($("<div></div>").addClass(wijCSS.wijradioInputwrapper)).parent().wrap("<div></div>").parent().addClass(wijCSS.wijradio).addClass(wijCSS.widget);
}
targetLabel = $("label[for='" + ele.attr("id") + "']");
if(targetLabel.length > 0) {
radiobuttonElement.append(targetLabel);
targetLabel.attr("labelsign", "wij");
//targetLabel.attr("tabindex", 0);
}
if(ele.is(":disabled")) {
self._setOption("disabled", true);
}
boxElement = $("<div></div>").addClass(wijCSS.wijradioBox).addClass(wijCSS.widget).addClass(self.options.disabled ? wijCSS.stateDisabled : wijCSS.stateDefault).addClass(wijCSS.cornerAll).append($("<span></span>").addClass(wijCSS.wijradioIcon));
iconElement = boxElement.children("." + wijCSS.wijradioIcon);
radiobuttonElement.append(boxElement);
iconElement.addClass(wijCSS.icon).addClass(wijCSS.iconRadioOn);
ele.data("iconElement", iconElement);
ele.data("boxElement", boxElement);
ele.data("radiobuttonElement", radiobuttonElement);
boxElement.removeClass(wijCSS.wijradioRelative).attr("role", "radio").bind("mouseover", function () {
ele.mouseover(null);
}).bind("mouseout", function () {
ele.mouseout(null);
});
if(targetLabel.length === 0 || targetLabel.html() === "") {
boxElement.addClass(wijCSS.wijradioRelative);
}
self._setDefaul();
// boxElement.css("margin-top","9px");
ele.bind("click.radio", function () {
//fixed bug:
//the "focus()" event fires twice when the radio is clicked
//ele.focus();
if(self.options.disabled) {
return;
}
eleChkState = self.options.checked;
self._refresh();
if(eleChkState !== self.element.is(":checked")) {
self._trigger("changed", null, {
checked: self.options.checked
});
}
}).bind("focus.radio", function () {
if(self.options.disabled) {
return;
}
boxElement.removeClass(wijCSS.stateDefault).addClass(wijCSS.stateFocus);
}).bind("blur.radio", function () {
if(self.options.disabled) {
return;
}
boxElement.removeClass(wijCSS.stateFocus).not("." + wijCSS.stateHover).addClass(wijCSS.stateDefault);
});
radiobuttonElement.click(function () {
if(self.options.disabled) {
return;
}
if(targetLabel.length === 0 || targetLabel.html() === "") {
//fixed bug:
//the "focus()" event fires twice when the radio is clicked
eleChkState = self.options.checked;
ele.attr("checked", true);
//ele.attr("checked", true).focus();
self._refresh();
ele.change();
if(eleChkState !== self.element.is(":checked")) {
self._trigger("changed", null, {
checked: self.options.checked
});
}
}
});
radiobuttonElement.bind("mouseover.radio", function () {
if(self.options.disabled) {
return;
}
boxElement.removeClass(wijCSS.stateDefault).addClass(wijCSS.stateHover);
}).bind("mouseout.radio", function () {
if(self.options.disabled) {
return;
}
boxElement.removeClass(wijCSS.stateHover).not("." + wijCSS.stateFocus).addClass(wijCSS.stateDefault);
});
//update for fixed tooltip can't take effect
radiobuttonElement.attr("title", ele.attr("title"));
}
};
wijradio.prototype._setOption = function (key, value) {
var self = this, originalCheckedState = self.options.checked;
_super.prototype._setOption.call(this, key, value);
if(key === 'checked') {
self.element.attr("checked", value);
self._refresh();
if(originalCheckedState !== value) {
self._trigger("changed", null, {
checked: value
});
}
}
};
wijradio.prototype._setDefaul = function () {
var self = this, o = self.options;
if(o.checked !== undefined && o.checked !== null) {
this.element.attr("checked", o.checked);
}
if(this.element.attr("checked")) {
this.element.parents("." + o.wijCSS.wijradio).find("." + o.wijCSS.wijradioBox).children().removeClass(o.wijCSS.iconRadioOn).addClass(o.wijCSS.iconRadioOff);
this.element.data("boxElement").removeClass(o.wijCSS.stateDefault).addClass(o.wijCSS.stateActive).attr("aria-checked", true);
this.element.data("radiobuttonElement").addClass(o.wijCSS.stateChecked);
}
};
wijradio.prototype._refresh = function () {
var name = this.element.attr("name") || "", self = this, wijCSS = self.options.wijCSS, radioEle;
if(name === "") {
return;
}
$("[name='" + name + "']").each(function (i, n) {
$(n).parents("." + wijCSS.wijradio).find("." + wijCSS.wijradioBox).children().removeClass(wijCSS.iconRadioOff).addClass(wijCSS.iconRadioOn);
$(n).parents("." + wijCSS.wijradio).find("." + wijCSS.wijradioBox).removeClass(wijCSS.stateActive).addClass(wijCSS.stateDefault).attr("aria-checked", false);
$(n).parents("." + wijCSS.wijradio).removeClass(wijCSS.stateChecked);
radioEle = $(n).parents("." + wijCSS.wijradio).find(":radio");
if(radioEle.wijradio("option", "checked") && radioEle[0] !== self.element[0]) {
radioEle.wijradio("setCheckedOption", false);
}
return this;
});
if(self.element.is(":checked")) {
self.element.data("iconElement").removeClass(wijCSS.iconRadioOn).addClass(wijCSS.iconRadioOff);
self.element.data("boxElement").removeClass(wijCSS.stateDefault).addClass(wijCSS.stateActive).attr("aria-checked", true);
self.element.data("radiobuttonElement").addClass(wijCSS.stateChecked);
}
self.options.checked = self.element.is(":checked");
};
wijradio.prototype.setCheckedOption = /** @ignore */
function (value) {
var self = this, o = self.options;
if(o.checked !== null && o.checked !== value) {
o.checked = value;
self._trigger("changed", null, {
checked: value
});
}
};
wijradio.prototype.refresh = /** Use the refresh method to set the radio button's style.
*/
function () {
this._refresh();
};
wijradio.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this, boxelement = self.element.parent().parent();
boxelement.children("div." + self.options.wijCSS.wijradioBox).remove();
self.element.unwrap();
self.element.unwrap();
_super.prototype.destroy.call(this);
};
return wijradio;
})(wijmo.wijmoWidget);
radio.wijradio = wijradio;
var wijradio_options = (function () {
function wijradio_options() {
/** Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijradio')";
/** wijradio css, extend from $.wijmo.wijCSS
* @ignore
*/
this.wijCSS = {
wijradio: "wijmo-wijradio",
wijradioBox: "wijmo-wijradio-box",
wijradioIcon: "wijmo-wijradio-icon",
wijradioInputwrapper: "wijmo-wijradio-inputwrapper",
wijradioRelative: "wijmo-wijradio-relative"
};
/** Causes the radio button to appear in the selected state.*/
this.checked = null;
/** A function called when checked state is changed.
* @event
* @dataKey {boolean} checked The state of the radio button.
*/
this.changed = null;
}
return wijradio_options;
})();
;
wijradio.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijradio_options());
$.wijmo.registerWidget(widgetName, wijradio.prototype);
})(wijmo.radio || (wijmo.radio = {}));
var radio = wijmo.radio;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../external/declarations/globalize.d.ts"/>
/// <reference path="../wijutil/jquery.wijmo.wijutil.ts"/>
/// <reference path="../Base/jquery.wijmo.widget.ts"/>
/// <reference path="../wijsuperpanel/jquery.wijmo.wijsuperpanel.ts"/>
/*globals jQuery,window,document*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.wijmo.wijtooltip.js
*/
(function (list) {
"use strict";
var $ = jQuery, widgetName = "wijlist";
//listCSS = "ui-widget ui-widget-content ui-corner-all wijmo-wijlist",
var listItemCSS = "wijmo-wijlist-item", //listCSS = "ui-widget ui-widget-content ui-corner-all wijmo-wijlist",
listItemCSSAlternate = listItemCSS + "-alternate", //listCSS = "ui-widget ui-widget-content ui-corner-all wijmo-wijlist",
listItemCSSSelected = listItemCSS + "-selected", //listCSS = "ui-widget ui-widget-content ui-corner-all wijmo-wijlist",
listItemCSSFirst = listItemCSS + "-first", //listCSS = "ui-widget ui-widget-content ui-corner-all wijmo-wijlist",
listItemCSSLast = listItemCSS + "-last", //listCSS = "ui-widget ui-widget-content ui-corner-all wijmo-wijlist",
activeItem = //stateHover = "ui-state-hover",
//uiStateActive = "ui-state-active",
"wijmo-wijlistitem-active", //listCSS = "ui-widget ui-widget-content ui-corner-all wijmo-wijlist",
itemKey = //selectedActive = listItemCSSSelected + " " + uiStateActive,
"item.wijlist";
/** @widget */
var wijlist = (function (_super) {
__extends(wijlist, _super);
function wijlist() {
_super.apply(this, arguments);
}
wijlist.prototype.removeAll = /** The removeAll method removes all items from the wijlist.*/
function () {
var self = this;
self.items = [];
self._refresh();
};
wijlist.prototype.addItem = /** The addItem method adds the specified item to the list by index.
* @remarks
* If the index is undefined, then the item becomes the last list item.
* @param {object} item Indicates the listItem to add.
* @param {number} index Index of the added item.
*/
function (item, index) {
var self = this;
self._checkData();
if(index === null || index === undefined) {
self.items.push(item);
} else {
if(self.items) {
self.items.splice(index, 0, item);
}
}
self._refresh();
};
wijlist.prototype.removeItem = /** The removeItem method removes the specified item from the wijlist.
* @param {object} item Indicates the item to be removed.
*/
function (item) {
var self = this, index;
self._checkData();
index = self.indexOf(item);
if(index >= 0) {
self.removeItemAt(index);
}
};
wijlist.prototype.indexOf = /** The indexOf method returns the index of the specified list item.
* @param {object} item Indicates the specified item.
* @returns {number} the index of first matched specified item.
*/
function (item) {
var self = this, index = -1, i = 0, oItem;
self._checkData();
for(i = 0; i < self.items.length; i++) {
oItem = self.items[i];
if(oItem.label === item.label && oItem.value === item.value) {
index = i;
break;
}
}
return index;
};
wijlist.prototype.findIndexByLabel = /** Allows the user to find the index of first matched list item by item's label.
* @param {string} label Indicates the specified item's label that used to search.
* @returns {number} the index of first matched list item.
* @remarks
* If there is no matched list item, it will return -1.
*/
function (label) {
var self = this, index = -1, i = 0, oItem;
if(label === null || label === undefined) {
return index;
}
self._checkData();
for(i = 0; i < self.items.length; i++) {
oItem = self.items[i];
if(oItem.label === label) {
index = i;
break;
}
}
return index;
};
wijlist.prototype.removeItemAt = /** The removeItemAt method removes the specified list item by index from the wijlist widget.
* @param {number} index The zero-based index of the list item to remove.
*/
function (index) {
var self = this;
self._checkData();
self.items.splice(index, 1);
self._refresh();
};
wijlist.prototype._checkData = function () {
var self = this;
if(!self.items) {
self.items = [];
}
};
wijlist.prototype._refresh = function () {
var self = this;
self.renderList();
self.refreshSuperPanel();
};
wijlist.prototype._setOption = function (key, value) {
var self = this, selectedItem, selectedActive = listItemCSSSelected + " " + self.options.wijCSS.stateActive, ulOuterHeight, isBind, renderItems;
//$.wijmo.widget.prototype._setOption.apply(self, arguments);
_super.prototype._setOption.call(this, key, value);
if(key === "disabled") {
self._handleDisabledOption(value, self.element);
} else if(key === "selectionMode") {
selectedItem = self.selectedItem;
if(selectedItem) {
selectedItem.selected = false;
if(selectedItem.element) {
selectedItem.element.removeClass(selectedActive);
}
self.selectedItem = undefined;
}
if(self.selectedItems) {
$.each(self.selectedItems, function (index, i) {
i.selected = false;
i.element.removeClass(selectedActive);
});
}
self.selectedItem = [];
} else if(key === "listItems") {
isBind = self._isBind();
if(isBind) {
renderItems = self._getRenderItems();
self.setItems(renderItems);
} else {
self.setItems(value);
}
self.renderList();
self.refreshSuperPanel();
} else if(key === "dataSource") {
isBind = self._isBind();
if(isBind) {
renderItems = self._getRenderItems();
self.setItems(renderItems);
self.renderList();
self.refreshSuperPanel();
}
} else if(key === "autoSize" || key === "maxItemsCount") {
if(!self.options.autoSize && self.element.is(":visible")) {
if(self._oriHeight !== 0) {
self.element.height(self._oriHeight);
} else {
ulOuterHeight = self.ul.outerHeight();
self.element.height(ulOuterHeight);
$(".wijmo-wijsuperpanel-statecontainer", self.element).height(ulOuterHeight);
$(".wijmo-wijsuperpanel-contentwrapper", self.element).height(ulOuterHeight);
}
}
self.refreshSuperPanel();
}
};
wijlist.prototype._create = function () {
var self = this, ele = this.element, o = this.options, wijCSS = o.wijCSS, listCSS = wijCSS.widget + " " + wijCSS.content + " " + wijCSS.cornerAll + " wijmo-wijlist", renderItems;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
self._oriHeight = parseInt(ele.css("height"), 10);
ele.addClass(listCSS).attr({
role: "listbox",
"aria-activedescendant": activeItem,
"aria-multiselectable": o.selectionMode === "multiple"
}).bind("click." + self.widgetName, self, self._onListClick);
if(ele.is("div") && ele.children().is("ul")) {
self._isInnerData = true;
self._templates = [];
$.each($("ul > li", ele), function (idx, liNode) {
self._templates.push({
templateHtml: liNode.innerHTML
});
});
self._oriChildren = ele.children().hide();
}
self.ul = $("<ul class='wijmo-wijlist-ul'></ul>").appendTo(ele);
if(o.listItems !== null) {
renderItems = self._getRenderItems();
if(renderItems) {
self.setItems(renderItems);
self.renderList();
self.refreshSuperPanel();
}
}
//update for visibility change
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
self.refreshSuperPanel();
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
}, "wijlist");
}
if(o.disabled) {
self.disable();
self._handleDisabledOption(true, self.element);
}
};
wijlist.prototype._isBind = function () {
var o = this.options, listItems = o.listItems;
if(listItems !== null && listItems.label && listItems.label.bind) {
return true;
}
return false;
};
wijlist.prototype._getRenderItems = function () {
var o = this.options, listItems = o.listItems;
if(listItems !== null) {
if($.isArray(listItems) && listItems.length > 0 && typeof (listItems[0].label) === "string") {
return listItems;
} else if(listItems.label && listItems.label.bind) {
return this._getMappingItems();
} else {
return null;
}
}
return null;
};
wijlist.prototype._getMappingItems = function () {
var o = this.options, dataSource = o.dataSource, listItems = o.listItems, mappingItems, labelKey, valueKey;
if(!dataSource || !listItems) {
return null;
}
if(!listItems.label || !listItems.label.bind || !listItems.value || !listItems.value.bind) {
return null;
}
labelKey = listItems.label.bind;
valueKey = listItems.value.bind;
//1.Array
if(dataSource && dataSource.length !== 0) {
mappingItems = [];
$.each(dataSource, function (i, item) {
mappingItems.push({
label: item[labelKey],
value: item[valueKey]
});
});
return mappingItems;
}
return null;
};
wijlist.prototype._handleDisabledOption = function (disabled, ele) {
var self = this;
if(disabled) {
if(!self.disabledDiv) {
self.disabledDiv = self._createDisabledDiv(ele);
}
self.disabledDiv.appendTo("body");
} else {
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
}
};
wijlist.prototype._createDisabledDiv = function (outerEle) {
var self = this, ele = outerEle || self.element, eleOffset = ele.offset(), disabledWidth = ele.outerWidth(), disabledHeight = ele.outerHeight();
return $("<div></div>").addClass("ui-disabled").css({
"z-index": "99999",
position: "absolute",
width: disabledWidth,
height: disabledHeight,
left: eleOffset.left,
top: eleOffset.top,
"pointer-events": "auto"
});
};
wijlist.prototype.setTemplateItems = /** @ignore */
function (data) {
this._setItemsByExtend(data, true);
};
wijlist.prototype.setItems = /** The method sets the items for the wijlist to render.
* @param {array} items Items to be rendered by the wijlist.
*/
function (items) {
this._setItemsByExtend(items, false);
};
wijlist.prototype._setItemsByExtend = function (items, isExtend) {
/// <summary>
/// Sets Items to be rendered by the wijlist.
/// </summary>
/// <param name="items" type="Array">
/// Items array to be rendered. The array contains object like
///{label: "label", value: "value"}.
/// </param>
var self = this, selectedItems;
// fixed the issue 39687, because the item is referenced with the data option,
// when use the same data to init more than one list, when set the item's sub field and store to jQuery data,
// it will also change the previous stored jQuery data.
$.each(items, function (i, item) {
items[i] = $.extend({
}, item);
});
if(isExtend) {
//update for 24130 issue at 2012/7/20
//first load the items by keydown, the
//items.length will not be equal self._templates.length
if(self._templates && items && items.length !== self._templates.length) {
return;
}
self.items = items;
//end
if(!self.items) {
self.items = [];
}
$.each(self._templates, function (idx) {
if(self.items[idx]) {
self.items[idx].templateHtml = self._templates[idx].templateHtml;
} else {
self.items.push({
templateHtml: self._templates[idx].templateHtml,
label: items[idx].label,
value: items[idx].value
});
}
});
} else {
self.items = items;
}
if(!items) {
return null;
}
selectedItems = $.grep(items, function (a) {
return a.selected;
}, undefined);
if(self.options.selectionMode === "single") {
self.selectedItems = [];
self.selectedItem = selectedItems.length > 0 ? selectedItems[0] : undefined;
} else {
self.selectedItems = selectedItems;
}
};
wijlist.prototype.filterItems = /** @ignore */
function (searchTerm, autoFilter, needHighlightMatching, hightWord) {
var self = this, term1 = self._escapeRegex(searchTerm), matcher, selectedActive = listItemCSSSelected + " " + self.options.wijCSS.stateActive, priorityPrimary = self.options.wijCSS.priorityPrimary, label, liText = '', itemsChanged = false, topHit = null;
/// TODO : start with or contains and case sensitive.
if(!this.items) {
return null;
}
if($("li[wijhidden].wijmo-wijlist-item", self.element) && $("li[wijhidden].wijmo-wijlist-item", self.element).length > 0) {
itemsChanged = true;
}
if($("span." + priorityPrimary, self.element) && $("span." + priorityPrimary, self.element).length > 0) {
itemsChanged = true;
}
if(!itemsChanged && (!searchTerm || searchTerm.length === 0)) {
$.each(this.items, function (index, item) {
if(item.selected) {
self.activate(null, item, false);
if(item.element) {
item.element.addClass(selectedActive);
}
self.selectedItem = item;
} else {
if(item.element && item.element.hasClass(selectedActive)) {
item.element.removeClass(selectedActive);
}
}
});
return;
}
matcher = new RegExp(term1, "i");
$.each(this.items, function (index, item) {
label = item.label;
// if text is set, text will override label value.
if(item.templateHtml) {
label = item.templateHtml;
} else if(item.text !== undefined) {
label = item.text;
}
/* remove the code the close the dropdown list
* when close the dropdown list, all items need to
* restore original style, see resetItemsStyle*/
if($("span." + priorityPrimary, item.element).length > 0) {
item.element.empty().append(label);
}
//filter still use the item.label;
var matchResult = matcher.exec(item.label);
if(matchResult === null && autoFilter) {
if(item.element) {
item.element.hide();
item.element.attr("wijhidden", "wijhidden");
}
} else {
// update for: when using the key to active the item
// the active item is incorrect at 2012/8/13
if(item.selected) {
self.activate(null, item, false);
if(item.element) {
item.element.addClass(selectedActive);
}
self.selectedItem = item;
} else {
if(item.element && item.element.hasClass(selectedActive)) {
item.element.removeClass(selectedActive);
}
}
if(needHighlightMatching) {
liText = label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term1 + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<span class='" + priorityPrimary + "'>$1</span>");
if(item.element) {
item.element.html(liText);
}
}
if(item.element && !item.element.is(":visible")) {
item.element.show();
item.element.removeAttr("wijhidden");
}
//update for 25224 issue at 2012/8/13
if(term1 !== undefined && term1.length !== 0 && topHit === null && matchResult && matchResult.index === 0) {
//self.activate(null, item, true);
topHit = item;
}
}
});
return topHit;
};
wijlist.prototype.popItem = /** The popItem method removes the last item from the wijlist widget.*/
function () {
var self = this;
self._checkData();
self.items.pop();
self._refresh();
};
wijlist.prototype.getList = /** The method gets the jQuery object reference of the <ul> element of the wijlist widget.
* @returns {object} the ul JQuery reference.
*/
function () {
return this.ul;
};
wijlist.prototype._onListClick = function (e) {
var self = e.data;
if(self.options.disabled) {
return;
}
if(!$(e.target).closest(".wijmo-wijlist-item").length) {
return;
}
self.select(e);
};
wijlist.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this, ele = this.element, o = this.options, wijCSS = o.wijCSS, listCSS = wijCSS.widget + " " + wijCSS.content + " " + wijCSS.cornerAll + " wijmo-wijlist";
if(self.superPanel !== undefined) {
self.superPanel.destroy();
}
ele.removeClass("wijmo-wijobserver-visibility").removeClass(listCSS).removeAttr("role").removeAttr("aria-activedescendant").unbind("." + self.widgetName);
self.ul.remove();
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
if(self._isInnerData) {
self._oriChildren.show();
}
// $.wijmo.widget.prototype.destroy.apply(self, arguments);
_super.prototype.destroy.call(this);
};
wijlist.prototype.activate = /** The activate method activates an item in the wijlist and allows the list to scroll to the item.
* @param {object} event The event object that activates the item.
* @param {object} item The listItem to activate.
* @param {boolean} scrollTo Indicates whether to scroll the activated item into view.
*/
function (event, item, scrollTo) {
var self = this, active, activeElement;
self.deactivate();
if(item === null || item === undefined) {
return;
}
if(self._trigger("focusing", event, item) === false) {
return;
}
active = self.active = item;
activeElement = item.element;
if(activeElement) {
if(self.options.addHoverItemClass) {
activeElement.addClass(self.options.wijCSS.stateHover);
}
activeElement.attr("id", activeItem);
}
if(scrollTo && self.superPanel !== undefined) {
self.superPanel.scrollChildIntoView(activeElement);
}
if(self.element.is(":visible")) {
self._trigger("focus", event, item);
}
};
wijlist.prototype.deactivate = /** The deactivate method deactivates the activated item in the wijlist widget.*/
function () {
var self = this, a = self.active, ele;
if(!a) {
return;
}
ele = a.element;
self._trigger("blur", null, a);
if(ele) {
ele.removeClass(self.options.wijCSS.stateHover).removeAttr("id");
}
self.active = undefined;
};
wijlist.prototype.next = /** The next method moves focus to the next list item.
* @param {object} event Event will raise activation.
*/
function (event) {
this.move("next", "." + listItemCSS + ":first", event);
};
wijlist.prototype.nextPage = /** The nextPage method turns to the next page of the list.*/
function () {
this.superPanel.doScrolling("bottom", true);
};
wijlist.prototype.previous = /** The previous method moves focus to the previous list item.
* @param {object} event Event will raise activation.
*/
function (event) {
this.move("prev", "." + listItemCSS + ":last", event);
};
wijlist.prototype.previousPage = /** The previous method moves focus to the previous list item.
*/
function () {
this.superPanel.doScrolling("top", true);
};
wijlist.prototype.first = /** The first method tests whether the focus is at the first list item.*/
function () {
return this.active && !this.active.element.prev().length;
};
wijlist.prototype.last = /** The last method tests whether the last list item has focus.*/
function () {
return this.active && !this.active.element.next().length;
};
wijlist.prototype.move = /** @ignore */
function (direction, edge, event) {
/// <summary>
/// Move focus between items.
/// </summary>
var self = this, item, next;
if(!self.active) {
item = self.ul.children(":visible" + edge).data(itemKey);
self.activate(event, item, true);
return;
}
next = self.active.element[direction + "All"](":visible." + listItemCSS).eq(0);
/*
if (!self._templates) {
next = self.active.element[direction + "All"]("." + listItemCSS).eq(0);
} else {
//add for only visible item will be moved
next = self.active.element[direction + "All"](":visible." + listItemCSS).eq(0);
}*/
if(next.length) {
self.activate(event, next.data(itemKey), true);
} else {
self.activate(event, self.element.children(edge).data(itemKey), true);
}
};
wijlist.prototype.select = /** @ignore */
function (event, data) {
/// <summary>
/// Selects active list item.
/// </summary>
///
var self = this, ele, selectedIndex, selectedActive = listItemCSSSelected + " " + self.options.wijCSS.stateActive, item, singleMode, previous;
if(self.active === undefined) {
self.active = $($(event.target).closest(".wijmo-wijlist-item")).data(itemKey);
if(self.active === undefined) {
return;
}
}
ele = self.active.element;
if(ele === undefined || ele.attr("wijhidden")) {
return;
}
item = ele.data(itemKey);
if(!item) {
return;
}
//end
singleMode = self.options.selectionMode === "single";
if(singleMode) {
previous = self.selectedItem;
ele.addClass(selectedActive).attr("aria-selected", "true");
item.selected = true;
if(previous !== undefined && item !== previous) {
previous.selected = false;
if(previous.element) {
previous.element.removeClass(selectedActive).removeAttr("aria-selected");
}
}
self.selectedItem = item;
selectedIndex = $.inArray(item, self.items);
self._trigger("selected", event, {
item: item,
previousItem: previous,
selectedIndex: selectedIndex,
data: data
});
} else {
item.selected = !item.selected;
if(item.selected) {
ele.addClass(selectedActive).attr("aria-selected", "true");
} else {
ele.removeClass(selectedActive).removeClass("wijmo-wijcombobox-selecteditem").removeAttr("aria-selected", "true");
}
selectedIndex = [];
self.selectedItems = $.grep(self.items, function (a, index) {
if(a.selected) {
selectedIndex.push(index);
}
return a.selected;
}, undefined);
self._trigger("selected", event, {
selectedIndex: selectedIndex,
item: item,
selectedItems: self.selectedItems
});
}
};
wijlist.prototype._findItemsByValues = function (values) {
var itemFound, found = [];
found = $.grep(this.items, function (itm, i) {
itemFound = false;
for(var j = 0; j < values.length; j++) {
if(itm.value === values[j]) {
itemFound = true;
}
}
return itemFound;
}, undefined);
return found;
};
wijlist.prototype._findItemsByIndices = function (indices) {
var self = this, len = this.items.length, found = [];
$.each(indices, function (index, value) {
if(value >= 0 && value < len) {
found.push(self.items[value]);
}
});
return found;
};
wijlist.prototype.getItems = /** The getItems method allows the user to find list items by index or by value.
* @param {array|number|string} indices the indices of the items.
* @param {boolean} byIndex Indicates the indices parameter is indices or values of items.
* If true, it's used as the index/indices of the item(s) to get.
* If false, it's used as the value/values of the item(s) to get.
* @returns {object} the item at the specified index or with the specified value.
*/
function (indices, byIndex) {
var self = this, isNumber, byArray, searchTerms, foundItems;
byArray = $.isArray(indices);
isNumber = (!byArray) && typeof (indices) === "number" || (byArray && typeof (indices[0]) === "number");
searchTerms = byArray ? indices : [
indices
];
if(!byIndex) {
foundItems = self._findItemsByValues(searchTerms);
} else {
if(!isNumber) {
return null;
}
foundItems = self._findItemsByIndices(searchTerms);
}
return foundItems;
};
wijlist.prototype.selectItems = /** Selects item(s) in the list by item index/indices or value(s).
* @param {array|number|string} indices the indices of the items.
* @param {boolean} triggerSelected Whether to trigger selected event of list.
* @param {boolean} byIndex Indicates the indices parameter is indices or values of items.
* If true, it's used as the index/indices of the item(s) to get.
* If false, it's used as the value/values of the item(s) to get.
*/
function (indices, triggerSelected, byIndex) {
var self = this, singleMode = this.options.selectionMode === "single", selectedActive = listItemCSSSelected + " " + self.options.wijCSS.stateActive, item, previous, foundItems;
foundItems = self.getItems(indices, byIndex);
if(singleMode) {
if(foundItems.length > 0) {
item = foundItems[0];
item.selected = true;
item.element.addClass(selectedActive);
}
previous = self.selectedItem;
if(previous) {
previous.selected = false;
previous.element.removeClass(selectedActive);
}
self.selectedItem = item;
if(triggerSelected) {
self._trigger("selected", null, {
item: item,
previousItem: previous
});
}
} else {
$.each(foundItems, function (index, itm) {
itm.selected = true;
itm.element.addClass(selectedActive);
});
self.selectedItems = $.grep(self.items, function (a) {
return a.selected;
}, undefined);
if(triggerSelected) {
self._trigger("selected", null, {
selectedItems: self.selectedItems
});
}
}
};
wijlist.prototype.unselectItems = /** The unselectItems method clears selections from the indicated list items.
* @param {array} indices The zero-based index numbers of items to clear.
*/
function (indices) {
var self = this, mode = this.options.selectionMode, selectedActive = listItemCSSSelected + " " + self.options.wijCSS.stateActive, selectedItem, foundItems;
if(mode === "single") {
selectedItem = self.selectedItem;
if(selectedItem) {
selectedItem.selected = false;
selectedItem.element.removeClass(selectedActive);
self.selectedItem = undefined;
}
} else {
foundItems = self.getItems(indices, true);
if(!foundItems || foundItems.length === 0) {
return;
}
$.each(foundItems, function (index, i) {
i.selected = false;
i.element.removeClass(selectedActive);
});
self.selectedItems = $.grep(self.items, function (a) {
return a.selected;
}, undefined);
}
};
wijlist.prototype.renderList = /** The renderList method renders the wijlist widget on the client browser when list items change. */
function () {
var self = this, ul = this.ul, o = this.options, items, count, singleMode, i, item;
//licollection;
ul.empty();
// returns if no items to render.
items = self.items;
if(items === undefined || items === null) {
return;
}
count = items.length;
if(count === 0) {
return;
}
singleMode = o.selectionMode === "single";
//for performance change
//licollection = [];
for(i = 0; i < count; i++) {
item = items[i];
//for jquery 1.9 change
self._renderItem(ul, item, i, singleMode);
//licollection.push(self._renderItem(ul, item, i, singleMode));
}
//for jquery 1.9 change
//for performance change
//$(licollection).appendTo(ul);
if(count > 0) {
if(items[0].element) {
items[0].element.addClass(listItemCSSFirst);
}
if(items[count - 1].element) {
items[count - 1].element.addClass(listItemCSSLast);
}
}
self._trigger("listRendered", null, self);
};
wijlist.prototype._renderItem = function (ul, item, index, singleMode) {
var self = this, li = $("<li role='option' class='wijmo-wijlist-item " + self.options.wijCSS.cornerAll + "'></li>"), selectedActive = listItemCSSSelected + " " + self.options.wijCSS.stateActive, label, url;
item.element = li;
item.list = self;
if(self._trigger("itemRendering", null, item) === false) {
return;
}
label = item.label;
if(item.title) {
li.attr("title", item.title);
}
// if text is set, text will override label value.
if(item.templateHtml) {
label = item.templateHtml;
} else if(item.text !== undefined) {
label = item.text;
}
// binds list item event
li.bind("mouseover", function (event) {
if(self.options.disabled) {
return;
}
self.activate(event, item, false);
}).bind("mouseout", function () {
if(self.options.disabled) {
return;
}
if(!self.options.keepHightlightOnMouseLeave) {
self.deactivate();
}
}).data(itemKey, item).append(label).appendTo(ul)//for jquery 1.9
;
// render image
if(!self._isInnerData) {
// render image
url = item.imageUrl;
if(url !== undefined && url.length > 0) {
li.prepend("<img src='" + item.imageUrl + "'>");
}
}
// add selected items
if(item.selected) {
self.activate(null, item, false);
li.addClass(selectedActive);
}
if(index % 2 === 1) {
li.addClass(listItemCSSAlternate);
}
self._trigger("itemRendered", null, item);
return li;
};
wijlist.prototype._escapeRegex = function (value) {
if(value === undefined) {
return value;
}
return value.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1");
};
wijlist.prototype.adjustOptions = //update for juice
function () {
var o = this.options, i;
if(o.data !== null) {
for(i = 0; i < o.listItems.length; i++) {
delete o.listItems[i].element;
delete o.listItems[i].list;
}
}
return o;
};
wijlist.prototype.refreshSuperPanel = /** The refreshSuperPanel method refreshes the SuperPanel around
* the wijlist to reflect a change in the wijlist content.
*/
function () {
var self = this, ele = this.element, o = this.options, ul = this.ul, singleItem = ul.children(".wijmo-wijlist-item:first"), headerHeight, ulOuterHeight, eleInnerWidth, spHeader = ele.find(".wijmo-wijsuperpanel-header"), spFooter = ele.find(".wijmo-wijsuperpanel-footer"), adjustHeight = null, h, percent, small, vScroller, large, spOptions, pt;
if(!ele.is(":visible")) {
return false;
}
ulOuterHeight = ul.outerHeight();
eleInnerWidth = ele.innerWidth();
if(o.autoSize) {
adjustHeight = singleItem.outerHeight(true) * o.maxItemsCount;
}
if(adjustHeight !== null) {
ele.height(Math.min(adjustHeight, ulOuterHeight));
}
h = ele.innerHeight();
//fix #37228, minus header and footer's height.
if(spHeader.length) {
h -= spHeader.height();
}
if(spFooter.length) {
h -= spFooter.height();
}
//end comments
percent = h / (ulOuterHeight - h);
large = (101 * percent) / (1 + percent);
small = (singleItem.outerHeight() / (ulOuterHeight - h)) * (101 - large);
if(self.superPanel === undefined) {
spOptions = {
allowResize: false,
keyboardSupport: false,
bubbleScrollingEvent: true,
hScroller: {
scrollBarVisibility: "hidden"
},
vScroller: {
scrollSmallChange: small,
scrollLargeChange: large
}
};
$.extend(spOptions, o.superPanelOptions);
self.superPanel = ele.wijsuperpanel(spOptions).data("wijmoWijsuperpanel");
//update for fixing can't show all dropdown items by wuhao
if(self.superPanel && self.superPanel.vNeedScrollBar) {
ul.setOutWidth(eleInnerWidth - 18);
self.superPanel.refresh();
}
//end for issue
} else {
vScroller = self.superPanel.options.vScroller;
vScroller.scrollLargeChange = large;
vScroller.scrollSmallChange = small;
//update for fixing can't show all dropdown items by wuhao
self.superPanel.paintPanel();
if(self.superPanel.vNeedScrollBar || ($.support.isTouchEnabled && $.support.isTouchEnabled())) {
ul.setOutWidth(eleInnerWidth - 18);
self.superPanel.refresh();
} else {
ul.setOutWidth(ele.outerWidth());
headerHeight = ele.children(".wijmo-wijsuperpanel-header").outerHeight();
//update for case 24248 at 2012/7/27
//Note: not good method for doing this
if(headerHeight !== null && headerHeight !== undefined) {
ele.height(ulOuterHeight + headerHeight);
}
//end
self.superPanel.refresh();
}
//end for issue
}
pt = ul.css("padding-top");
if(pt.length > 0) {
vScroller = self.superPanel.options.vScroller;
vScroller.firstStepChangeFix = self.superPanel.scrollPxToValue(parseFloat(pt), "v");
} else {
vScroller.firstStepChangeFix = 0;
}
ul.setOutWidth(ul.parent().parent().innerWidth());
//if list is disabled, adjust disabledDiv's width/height
if(o.disabled && self.disabledDiv) {
self.disabledDiv.css("left", ele.offset().left).css("top", ele.offset().top).css("width", ele.outerWidth()).css("height", ele.outerHeight());
}
};
return wijlist;
})(wijmo.wijmoWidget);
list.wijlist = wijlist;
var wijlist_options = (function () {
function wijlist_options() {
/** @ignore */
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body-c",
stateDefault: "ui-btn-up-c",
stateHover: "ui-btn-up-b",
stateActive: "ui-btn-down-b"
};
/** Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijlist')";
/** This option is the wijdataview to which the wijlist is bound.
* @type {wijdataview}
* @remarks
* This option is used if this wijlist is bound to a wijdataview.
* In that case, you can also specify a mapping option to
* select the properties to bind to,
* and the listItems option returns an array of objects containing
* value and label property values determined by that mapping.
*/
this.dataSource = null;
/** An array that specifies the listItem collections of wijlist.*/
this.listItems = [];
/** Select event handler of wijlist.
* A function will be called when any item in the list is selected.
* @event
* @dataKey {objcect} item By data.item to obtain the selected item.
*/
this.selected = null;
/** A value indicates the list items can be single-selected or multi-selected
* @remarks
* Options are "single" and "multiple". This option should not be set
* again after initialization.
*/
this.selectionMode = "single";
/** The autoSize determines whether or not the wijlist will be automatically sized.*/
this.autoSize = false;
/** A value specifies the maximum number of items that will be displayed
* if the autoSize option is also set to true.
*/
this.maxItemsCount = 5;
/** The addHoverItemClass option determines whether the "ui-state-hover" class
* is applied to a list item on mouse over.
*/
this.addHoverItemClass = true;
/** The superPanelOptions option indicates the customized options of wijsuperpanel
* when the wijsuperpanel is created.
* @remarks
* superpanel is the list container.For detailed options please refer to the Superpanel widget
*/
this.superPanelOptions = null;
/** A value indicates whether wijlist is disabled.*/
this.disabled = false;
/** The focusing event is fired when the mouse enters the list item and
* before the hover event logic is processed.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IItemEventArgs} args The data with this event.
* @returns {boolean} false to cancel item focusing.
*/
this.focusing = null;
/** The focus event is fired when the mouse enters the list item and
* after the hover event logic is processed.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IItemEventArgs} args The data with this event.
*/
this.focus = null;
/** The blur event is fired when the mouse leaves the item.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IItemEventArgs} args The data with this event.
*/
this.blur = null;
/** The itemRendering event is fired before a list item is rendered.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IItemEventArgs} args The data with this event.
*/
this.itemRendering = null;
/** The itemRendered event is fired after a list item is rendered.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IItemEventArgs} args The data with this event.
*/
this.itemRendered = null;
/** The listRendered event is fired after the list is rendered.
* @event
* @dataKey {object} list The list to be rendered.
*/
this.listRendered = null;
/** A value determines the highlight state when the mouse leaves an item. */
this.keepHightlightOnMouseLeave = false;
}
return wijlist_options;
})();
;
wijlist.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijlist_options());
$.wijmo.registerWidget("wijlist", wijlist.prototype);
})(wijmo.list || (wijmo.list = {}));
var list = wijmo.list;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../wijutil/jquery.wijmo.wijutil.ts"/>
/// <reference path="../Base/jquery.wijmo.widget.ts"/>
/// <reference path="../wijpopup/jquery.wijmo.wijpopup.ts"/>
/// <reference path="../external/declarations/globalize.d.ts"/>
/*globals jQuery,window,document*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.wijmo.wijtooltip.js
*/
(function (calendar) {
"use strict";
var $ = jQuery, widgetName = "wijcalendar";
var wijDayType = {
general: /** A general day cell, denotes nothing.*/
0,
weekEnd: /** A weekend day cell.*/
1,
otherMonth: /** A day cell with a date blongs to other month.*/
2,
outOfRange: /** A day cell with a date out of the minDate/maxDate range.*/
4,
today: /** A day cell represents today.*/
8,
custom: /** A custom day cell, which has CSS class 'wijmo-wijcalendar-customday' associated.*/
16,
disabled: /** A day cell in disabled state.*/
32,
selected: /** A day cell in selected state.*/
64,
gap: /** A blank day cell.*/
128
};
/** @widget */
var wijcalendar = (function (_super) {
__extends(wijcalendar, _super);
function wijcalendar() {
_super.apply(this, arguments);
}
wijcalendar.prototype._create = function () {
var self = this, wijCSS = self.options.wijCSS;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
// Add for parse date options for jUICE. D.H
if($.isFunction(window["wijmoASPNetParseOptions"])) {
wijmoASPNetParseOptions(this.options);
}
this.element.addClass("wijmo-wijcalendar " + wijCSS.datepickerInline + " " + wijCSS.datepicker + " " + wijCSS.widget + " " + wijCSS.content + " " + wijCSS.helperClearFix + " " + wijCSS.cornerAll).attr('role', 'grid');
this._previewWrapper(this.options.allowPreview);
this.element.data('preview.wijcalendar', false);
//update for visibility change
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
self.refresh();
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
}, "wijcalendar");
}
};
wijcalendar.prototype._init = function () {
if(this.options.popupMode) {
var po = {
autoHide: !!this.options.autoHide,
showing: undefined,
shown: undefined,
hiding: undefined,
hidden: undefined
}, self = this;
if(this.options.beforePopup) {
po.showing = this.options.beforePopup;
}
if(this.options.afterPopup) {
po.shown = this.options.afterPopup;
}
if(this.options.beforeClose) {
po.hiding = this.options.beforeClose;
}
po.hidden = function (data) {
self.element.removeData("lastdate.wijcalendar");
if(self.options.afterClose) {
self.options.afterClose.call(data);
}
};
this.element.wijpopup(po);
}
this._getSelectedDates();
this._getDisabledDates();
this._resetWidth();
this.refresh();
//this.element.width(this.element.width() + 2);
};
wijcalendar.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var wijCSS = this.options.wijCSS;
//$.wijmo.widget.prototype.destroy.apply(this, arguments);
_super.prototype.destroy.call(this);
this.close();
this.element.html("");
this.element.removeClass("wijmo-wijcalendar " + wijCSS.datepickerInline + " " + wijCSS.datepicker + " " + wijCSS.widget + " " + wijCSS.content + " " + wijCSS.helperClearFix + " " + wijCSS.cornerAll + " " + wijCSS.datepickerMulti).removeAttr('role');
var self = this;
$.each([
"preview",
"disableddates",
"selecteddates",
"dragging",
"lastdate",
"animating"
], function (i, prefix) {
self.element.removeData(prefix + ".wijcalendar");
});
this._previewWrapper(false);
};
wijcalendar.prototype._setOption = function (key, value) {
//$.wijmo.widget.prototype._setOption.apply(this, arguments);
_super.prototype._setOption.call(this, key, value);
switch(key) {
case "showWeekDays":
case "showWeekNumbers":
case "showTitle":
case "showOtherMonthDays":
case "selectionMode":
this.unSelectAll();
this._resetWidth();
this.refresh();
break;
case "culture":
this.refresh();
break;
case "allowPreview":
this._previewWrapper(value);
this.refresh();
break;
case "monthCols":
if(this._myGrid) {
this._myGrid = undefined;
}
this._resetWidth();
this.refresh();
break;
case "monthRows":
if(this._myGrid) {
this._myGrid = undefined;
}
break;
case "autoHide":
this.element.wijpopup({
autoHide: this.options.autoHide
});
break;
case "selectedDates":
this._getSelectedDates().setDates(value);
this.refresh();
break;
case "disabledDates":
this._getDisabledDates().setDates(value);
this.refresh();
break;
case "displayDate":
this.refresh();
break;
}
};
wijcalendar.prototype._previewWrapper = function (add) {
if(add) {
if(!this.element.parent().hasClass('wijmo-wijcalendar-preview-wrapper')) {
this.element.wrap("<div class='wijmo-wijcalendar-preview-wrapper" + " " + this.options.wijCSS.helperClearFix + "'></div>");
}
} else {
if(this.element.parent().hasClass('wijmo-wijcalendar-preview-wrapper')) {
this.element.unwrap();
}
}
};
wijcalendar.prototype._isRTL = function () {
return !!this._getCulture(null).isRTL;
};
wijcalendar.prototype.refresh = /** Refreshes the calendar.*/
function () {
this.element.empty().append(this._createCalendar());
this.element[(this._isRTL() ? 'add' : 'remove') + 'Class'](this.options.wijCSS.datepickerRtl);
if(!this.options.showTitle) {
this.element.addClass("wijmo-wijcalendar-notitle");
} else {
this.element.removeClass("wijmo-wijcalendar-notitle");
}
this._bindEvents();
};
wijcalendar.prototype.refreshDate = /** Refereshes a single date on the calendar.
* @param {Date} date The date to be refreshed.
*/
function (date) {
if(!this._monthViews) {
return;
}
if(date < this._groupStartDate || date > this._groupEndDate) {
return;
}
$.each(this._monthViews, function () {
this._refreshDate(date);
});
};
wijcalendar.prototype.getDisplayDate = /** Gets the valid display date.*/
function () {
var d = this.options.displayDate ? this.options.displayDate : new Date();
if(wijDateOps.isSameDate(d, new Date(1900, 0, 1))) {
d = new Date();
}
return d;
};
wijcalendar.prototype.getSelectedDate = /** Gets the currently selected date.*/
function () {
var dates = this.options.selectedDates;
return (!dates || dates.length === 0) ? null : dates[0];
};
wijcalendar.prototype.selectDate = /** Selects the specified date.
* @param {Date} date The date to be selected.
*/
function (date) {
date = new Date(date);
if(this._getDisabledDates().contains(date)) {
return false;
}
if(date < this.options.minDate || date > this.options.maxDate) {
return false;
}
this._getSelectedDates().add(date);
this.refreshDate(date);
return true;
};
wijcalendar.prototype.unSelectDate = /** Clears any selection from the specified date.
* @param {Date} date The date to be removed from the selectedDates collection.
*/
function (date) {
date = new Date(date);
if(this._getDisabledDates().contains(date)) {
return false;
}
if(date < this.options.minDate || date > this.options.maxDate) {
return false;
}
this._getSelectedDates().remove(date);
this.refreshDate(date);
return true;
};
wijcalendar.prototype.unSelectAll = /** Clears any selections from dates on the calendar, removing them from the selectedDates collection.*/
function () {
var dates = this.options.selectedDates, i;
if(dates && dates.length > 0) {
this._getSelectedDates().clear();
for(i = 0; i < dates.length; i++) {
this.refreshDate(dates[i]);
}
}
};
wijcalendar.prototype._slideToDate = function (date) {
if(wijDateOps.isSameMonth(this.getDisplayDate(), date)) {
return;
}
var visible = this.element.is(":visible");
if(!visible) {
this.options.displayDate = date;
} else {
if(this._trigger('beforeSlide') === false) {
return;
}
if(this._isSingleMonth()) {
this._playSlideAnimation(date);
} else {
this._playMmSlideAnimation(date);
}
}
};
wijcalendar.prototype.isPopupShowing = /** Determines whether the calendar is in the pop-up state.*/
function () {
return !!this.options.popupMode ? this.element.wijpopup('isVisible') : false;
};
wijcalendar.prototype.popup = /** Pops up the calendar at specifies position.
* @param {Object} position A jQuery Position plugin that indicates the position in which to pop up the calendar.
* Please see "http://jqueryui.com/demos/position/" for details of the parameter.
*/
function (position) {
this._myGrid = undefined;
this.refresh();
this.element.data('dragging.wijcalendar', false);
if(this.element.data("wijmoWijpopup")) {
this.element.wijpopup('show', position);
}
};
wijcalendar.prototype.popupAt = /** Pops up the calendar at the specified X and Y coordinates in the document.
* @param {number} x X offset.
* @param {number} y Y offset.
*/
function (x, y) {
this._myGrid = undefined;
this.refresh();
this.element.data('dragging.wijcalendar', false);
if(this.element.data("wijmoWijpopup")) {
this.element.wijpopup('showAt', x, y);
}
};
wijcalendar.prototype.close = /** Closes the calendar if it is in the pop-up state.*/
function () {
if(this.isPopupShowing()) {
this.element.wijpopup('hide');
}
};
wijcalendar.prototype._getCulture = function (name) {
return Globalize.findClosestCulture(name || this.options.culture);
};
wijcalendar.prototype._getDates = function (token) {
var name = token.toLowerCase() + ".wijcalendar", dates = this.element.data(name);
if(dates === undefined) {
dates = new wijDateCollection(this, token);
this.element.data(name, dates);
}
return dates;
};
wijcalendar.prototype._getDisabledDates = function () {
return this._getDates('disabledDates');
};
wijcalendar.prototype._getSelectedDates = function () {
return this._getDates('selectedDates');
};
wijcalendar.prototype._onDayDragStart = function (e) {
e.preventDefault();
e.stopPropagation();
return false;
};
wijcalendar.prototype._onDayMouseDown = function (e) {
e.preventDefault();
e.stopPropagation();
var o = this.options, self = this, date, args, selected = false, selDates = o.selectedDates, exist = false, dates = [];
if(e.which !== 1) {
return false;
}
date = this._getCellDate(e.currentTarget);
if(date === undefined) {
return false;
}
if(!o.selectionMode.day) {
return false;
}
args = {
date: date
};
if(this._trigger("beforeSelect", null, args) === false) {
return false;
}
if(!o.selectionMode.days || (!e.metaKey && !e.shiftKey && !e.ctrlKey)) {
this.unSelectAll();
}
if(!!o.selectionMode.days) {
if(e.shiftKey && this.element.data("lastdate.wijcalendar")) {
this._selectRange(this.element.data("lastdate.wijcalendar"), date, null);
selected = true;
} else {
if(e.ctrlKey) {
this.element.data("lastdate.wijcalendar", date);
$.each(selDates, function (i, d) {
if(date.getFullYear() === d.getFullYear() && date.getMonth() === d.getMonth() && date.getDate() === d.getDate()) {
exist = true;
return false;
}
});
if(exist) {
this.unSelectDate(date);
} else {
this.selectDate(date);
}
selDates = o.selectedDates;
$.each(selDates, function (i, d) {
dates.push(new Date(d));
});
this._trigger('selectedDatesChanged', null, {
dates: dates
});
selected = true;
}
}
}
if(!selected) {
this.element.data("lastdate.wijcalendar", date);
selected = this.selectDate(date);
this._trigger('selectedDatesChanged', null, {
dates: [
date
]
});
}
if(selected) {
this._trigger('afterSelect', null, args);
if(!!o.selectionMode.days) {
this.element.data('dragging.wijcalendar', true);
$(document.body).bind("mouseup." + this.widgetName, function () {
$(document.body).unbind("mouseup." + self.widgetName);
self.element.data('dragging.wijcalendar', false);
});
}
}
return false;
};
wijcalendar.prototype._onMouseUp = function (e) {
e.preventDefault();
e.stopPropagation();
//var self = this;
this.element.data('dragging.wijcalendar', false);
return false;
};
wijcalendar.prototype._onDayClicked = function (e) {
var date = this._getCellDate(e.currentTarget);
if(date === undefined) {
return false;
}
if(!this.options.selectionMode.day) {
return false;
}
if(this.isPopupShowing()) {
this.close();
} else {
if($(e.currentTarget).hasClass(this.options.wijCSS.datepickerOtherMonth)) {
this._slideToDate(date);
}
}
return false;
};
wijcalendar.prototype._onDayMouseEnter = function (e) {
$(e.currentTarget).attr('state', 'hover');
this._refreshDayCell(e.currentTarget);
if(!!this.element.data('dragging.wijcalendar')) {
var date = this._getCellDate(e.currentTarget);
if(date === undefined) {
return;
}
this.unSelectAll();
this._selectRange(this.element.data("lastdate.wijcalendar"), date, true);
}
};
wijcalendar.prototype._onDayMouseLeave = function (e) {
$(e.currentTarget).attr('state', 'normal');
this._refreshDayCell(e.currentTarget);
};
wijcalendar.prototype._selectRange = function (start, end, bymouse) {
if(start !== undefined && start !== new Date(1900, 1, 1)) {
var minDate = start, maxDate = end, selDates = [];
if(start > end) {
maxDate = start;
minDate = end;
}
while(true) {
if(minDate > maxDate) {
break;
}
this.selectDate(minDate);
selDates[selDates.length] = minDate;
minDate = wijDateOps.addDays(minDate, 1);
}
if(!bymouse) {
this.element.removeData("lastdate.wijcalendar");
}
this._trigger('selectedDatesChanged', null, {
dates: selDates
});
} else {
this.selectDate(start);
this._trigger('selectedDatesChanged', null, {
dates: [
start
]
});
}
return true;
};
wijcalendar.prototype._getCellDate = function (c) {
var d = $(c).attr('date');
return (d === undefined) ? d : new Date(d);
};
wijcalendar.prototype._getParentTable = function (c) {
var parents = $(c).parents('table');
return (parents.length === 0) ? undefined : parents.get(0);
};
wijcalendar.prototype._initMonthSelector = function (ms) {
if($(ms).data('cells') !== undefined) {
return;
}
var tokens = ms.id.split('_'), monthID, monthTable, cells = [], i, j, td, dt, row;
if(tokens[tokens.length - 1] !== 'ms') {
throw Error["create"]('not a monthview');
}
monthID = (tokens.slice(0, tokens.length - 1)).join('_');
monthTable = this._getParentTable(ms);
if(monthTable) {
if(monthTable.id !== monthID) {
throw Error["create"]('not a monthview');
}
for(i = 0; i < monthTable.rows.length; i++) {
row = monthTable.rows[i];
for(j = 0; j < row.cells.length; j++) {
td = row.cells[j];
if(td) {
dt = $(td).attr('daytype');
if(dt !== undefined) {
if($(td).find('a').hasClass(this.options.wijCSS.prioritySecondary) === false) {
if(this._isSelectable(parseInt(dt, 10))) {
cells[cells.length] = td;
}
}
}
}
}
}
}
$(ms).data('cells', cells);
};
wijcalendar.prototype._onMonthSelectorClicked = function (e) {
this._initMonthSelector(e.currentTarget);
var cells = $(e.currentTarget).data('cells'), selDates = [], i, c, d, date;
this.element.removeData("lastdate.wijcalendar");
this.unSelectAll();
for(i = 0; i < cells.length; i++) {
c = cells[i];
d = $(c).attr('date');
if(d !== undefined) {
date = new Date(d);
this.selectDate(date);
selDates[selDates.length] = date;
}
}
this._trigger('selectedDatesChanged', null, {
dates: selDates
});
if(this.isPopupShowing()) {
this.close();
}
return false;
};
wijcalendar.prototype._onMonthSelectorMouseEnter = function (e) {
this._initMonthSelector(e.currentTarget);
var cells = $(e.currentTarget).data('cells'), i;
for(i = 0; i < cells.length; i++) {
e.currentTarget = cells[i];
this._onDayMouseEnter(e);
}
};
wijcalendar.prototype._onMonthSelectorMouseLeave = function (e) {
this._initMonthSelector(e.currentTarget);
var cells = $(e.currentTarget).data('cells'), i;
for(i = 0; i < cells.length; i++) {
e.currentTarget = cells[i];
this._onDayMouseLeave(e);
}
};
wijcalendar.prototype._initWeekDaySelector = function (wd) {
if($(wd).data('cells') !== undefined) {
return;
}
var tokens = wd.id.split('_'), colIndex, monthID, monthTable, cells = [], i = 0, tr, td, dt;
if(tokens[tokens.length - 2] !== 'cs') {
throw Error["create"]('not a column');
}
colIndex = parseInt(tokens[tokens.length - 1], 10);
monthID = (tokens.slice(0, tokens.length - 2)).join('_');
monthTable = this._getParentTable(wd);
if(monthTable) {
if(monthTable.id !== monthID) {
throw Error["create"]('not a column');
}
/** update for issue 29995
if (!this._isSingleMonth()) {
i++;
}*/
if(this.options.showWeekDays) {
i++;
}
for(; i < monthTable.rows.length; i++) {
tr = monthTable.rows[i];
if(colIndex < tr.cells.length) {
td = tr.cells[colIndex];
if(td) {
dt = $(td).attr('daytype');
if(dt !== undefined) {
if($(td).find('a').hasClass(this.options.wijCSS.prioritySecondary) === false) {
if(this._isSelectable(parseInt(dt, 10))) {
cells[cells.length] = td;
}
}
}
}
}
}
}
$(wd).data('cells', cells);
};
wijcalendar.prototype._onWeekDayClicked = function (e) {
this._initWeekDaySelector(e.currentTarget);
var cells = $(e.currentTarget).data('cells'), selDates = [], i, c, d, date;
this.unSelectAll();
for(i = 0; i < cells.length; i++) {
c = $(cells[i]);
d = c.attr('date');
if(d !== undefined) {
date = new Date(d);
this.selectDate(date);
selDates[selDates.length] = date;
}
}
this._trigger('selectedDatesChanged', null, {
dates: selDates
});
if(this.isPopupShowing()) {
this.close();
}
return false;
};
wijcalendar.prototype._onWeekDayMouseEnter = function (e) {
this._initWeekDaySelector(e.currentTarget);
var cells = $(e.currentTarget).data('cells'), i;
for(i = 0; i < cells.length; i++) {
e.currentTarget = cells[i];
this._onDayMouseEnter(e);
}
};
wijcalendar.prototype._onWeekDayMouseLeave = function (e) {
this._initWeekDaySelector(e.currentTarget);
var cells = $(e.currentTarget).data('cells'), i;
for(i = 0; i < cells.length; i++) {
e.currentTarget = cells[i];
this._onDayMouseLeave(e);
}
};
wijcalendar.prototype._initWeekNumberSelector = function (wn) {
if($(wn).data('cells') !== undefined) {
return;
}
var tokens = wn.id.split('_'), rowIndex, monthID, monthTable, cells = [], tr, i, td, dt;
if(tokens[tokens.length - 2] !== 'rs') {
throw Error["create"]('not a row');
}
rowIndex = parseInt(tokens[tokens.length - 1], 10);
monthID = (tokens.slice(0, tokens.length - 2)).join('_');
monthTable = this._getParentTable(wn);
if(monthTable) {
if(monthTable.id !== monthID) {
throw Error["create"]('not a row');
}
tr = monthTable.rows[rowIndex];
if(tr) {
i = 0;
if(this.options.showWeekNumbers) {
i++;
}
for(; i < tr.cells.length; i++) {
td = tr.cells[i];
if(td) {
dt = $(td).attr('daytype');
if(dt !== undefined) {
if($(td).find('a').hasClass(this.options.wijCSS.prioritySecondary) === false) {
if(this._isSelectable(parseInt(dt, 10))) {
cells[cells.length] = td;
}
}
}
}
}
}
}
$(wn).data('cells', cells);
};
wijcalendar.prototype._onWeekNumberClicked = function (e) {
this._initWeekNumberSelector(e.currentTarget);
var cells = $(e.currentTarget).data('cells'), selDates = [], i, c, d, date;
this.unSelectAll();
for(i = 0; i < cells.length; i++) {
c = $(cells[i]);
d = c.attr('date');
if(d !== undefined) {
date = new Date(d);
this.selectDate(date);
selDates[selDates.length] = date;
}
}
this._trigger('selectedDatesChanged', null, {
dates: selDates
});
if(this.isPopupShowing()) {
this.close();
}
return false;
};
wijcalendar.prototype._onWeekNumberMouseEnter = function (e) {
this._initWeekNumberSelector(e.currentTarget);
var cells = $(e.currentTarget).data('cells'), i;
for(i = 0; i < cells.length; i++) {
e.currentTarget = cells[i];
this._onDayMouseEnter(e);
}
};
wijcalendar.prototype._onWeekNumberMouseLeave = function (e) {
this._initWeekNumberSelector(e.currentTarget);
var cells = $(e.currentTarget).data('cells'), i;
for(i = 0; i < cells.length; i++) {
e.currentTarget = cells[i];
this._onDayMouseLeave(e);
}
};
wijcalendar.prototype._isAnimating = function () {
return !!this.element.data('animating.wijcalendar');
};
wijcalendar.prototype._onPreviewMouseEnter = function (e) {
if(!!this.element.data('previewContainer')) {
return;
}
if(this._isAnimating()) {
return;
}
var btn = $(e.currentTarget), btnId = btn.attr('id'), mainDate = this.getDisplayDate(), wijCSS = this.options.wijCSS, months = this.options.monthCols * this.options.monthRows, previewContainer = $('<div/>');
if(btnId === undefined) {
return;
}
if(btnId === "prevPreview") {
months = -months;
}
this.options.displayDate = wijDateOps.addMonths(mainDate, months);
this.element.data('preview.wijcalendar', true);
previewContainer.appendTo(document.body);
previewContainer.hide();
previewContainer.addClass('wijmo-wijcalendar ' + wijCSS.datepickerInline + " " + wijCSS.datepicker + " " + wijCSS.widget + " " + wijCSS.content + " " + wijCSS.helperClearFix + " " + wijCSS.cornerAll);
previewContainer.append(this._createCalendar());
this.options.displayDate = mainDate;
this.element.data('preview.wijcalendar', false);
this._createMonthViews();
previewContainer.wijpopup({
showEffect: 'slide',
showOptions: {
direction: (btnId === 'prevPreview' ? 'right' : 'left')
},
hideEffect: 'slide',
hideOptions: {
direction: (btnId === 'prevPreview' ? 'right' : 'left')
}
});
previewContainer.wijpopup('show', {
my: (btnId === 'prevPreview' ? 'right top' : 'left top'),
at: (btnId === 'prevPreview' ? 'left top' : 'right top'),
of: btn
});
this.element.data('previewContainer', previewContainer);
};
wijcalendar.prototype._onPreviewMouseLeave = function (e) {
var btn = $(e.currentTarget), btnId = btn.attr('id'), previewContainer = this.element.data('previewContainer'), self = this;
if(btnId === undefined) {
return;
}
if(previewContainer) {
if(previewContainer.wijpopup('isAnimating')) {
window.setTimeout(function () {
self._onPreviewMouseLeave(e);
}, 200);
} else {
previewContainer.wijpopup('hide');
this.element.removeData('previewContainer');
}
}
};
wijcalendar.prototype._resetWidth = function () {
if(!this._myGrid) {
this.element.css('height', '');
if(this.options.monthCols > 1) {
this.element.css('width', 17 * this.options.monthCols + 'em');
this.element.addClass(this.options.wijCSS.datepickerMulti);
} else {
this.element.css('width', '');
this.element.removeClass(this.options.wijCSS.datepickerMulti);
}
}
};
wijcalendar.prototype._playMmSlideAnimation = function (toDate) {
var w = this.element.width(), h = this.element.height(), date = this.getDisplayDate(), curContent, newContent, goNext, direction = this.options.direction || 'horizontal', calendar = this, curContentAniOpts, newContentAniOpts;
this.element.height(h);
this.element.wrapInner("<div class='wijmo-wijcalendar-multi-aniwrapper'></div>");
curContent = this.element.find('>:first-child').width(w).height(h);
newContent = curContent.clone(false);
newContent.hide();
this.options.displayDate = toDate;
this._createMonthViews();
newContent.empty().append(this._createMonthGroup());
newContent.appendTo(this.element);
goNext = toDate > date;
this.element.data('animating.wijcalendar', true);
if($.effects) {
curContent.effect('slide', {
mode: 'hide',
direction: direction === 'horizontal' ? (goNext ? 'left' : 'right') : (goNext ? 'up' : 'down'),
easing: this.options.easing || 'easeOutBack',
duration: this.options.duration
}, function () {
curContent.remove();
});
newContent.effect('slide', {
direction: direction === 'horizontal' ? (goNext ? 'right' : 'left') : (goNext ? 'down' : 'up'),
easing: this.options.easing || 'easeOutBack',
duration: this.options.duration
}, function () {
while(newContent.parent().is('.wijmo-wijcalendar-multi-aniwrapper')) {
newContent.parent().replaceWith(newContent);
}
newContent.replaceWith(newContent.contents());
calendar.element.height('');
calendar._bindEvents();
calendar.element.data('animating.wijcalendar', false);
calendar._trigger('afterSlide');
});
} else {
if(direction === 'horizontal') {
curContentAniOpts = {
width: 0
};
newContentAniOpts = {
width: '100%'
};
} else {
curContentAniOpts = {
height: 0
};
newContentAniOpts = {
height: '100%'
};
}
curContent.animate(curContentAniOpts, this.options.duration, //this.options.easing || 'easeOutBack',
null, function () {
curContent.remove();
});
newContent.animate(newContentAniOpts, this.options.duration, null, //this.options.easing || 'easeOutBack',
function () {
while(newContent.parent().is('.wijmo-wijcalendar-multi-aniwrapper')) {
newContent.parent().replaceWith(newContent);
}
newContent.replaceWith(newContent.contents());
calendar.element.height('');
calendar._bindEvents();
calendar.element.data('animating.wijcalendar', false);
calendar._trigger('afterSlide');
});
}
};
wijcalendar.prototype._playSlideAnimation = function (toDate) {
if(!this._isSingleMonth()) {
return;
}
var self = this, date = this.getDisplayDate(), wijCSS = self.options.wijCSS, curTable = this.element.find('.' + wijCSS.datepickerCalendar), wrapper, slideContainer, yearStep = 1, direction = this.options.direction || 'horizontal', goNext = toDate > date, months = [], w, h, wrapperAniOpts;
if(curTable.parent().is('.wijmo-wijcalendar-aniwrapper')) {
wrapper = curTable.parent();
} else {
//wrapper = $.effects.createWrapper(curTable).css({ overflow: 'hidden' });
wrapper = $.createWrapper(curTable).css({
overflow: 'hidden'
});
wrapper.removeClass(wijCSS.effectsWrapper);
wrapper.addClass('wijmo-wijcalendar-aniwrapper');
}
if(wrapper.parent().is('.wijmo-wijcalendar-aniwrapper')) {
slideContainer = wrapper.parent();
} else {
//slideContainer = $.effects.createWrapper(wrapper)
// .css({ overflow: 'hidden' });
slideContainer = $.createWrapper(wrapper).css({
overflow: 'hidden'
});
slideContainer.removeClass(wijCSS.effectsWrapper);
slideContainer.addClass('wijmo-wijcalendar-aniwrapper');
}
if(this._myGrid) {
switch(this._myGrid.gridType) {
case "month":
yearStep = 1;
break;
case "year":
yearStep = 10;
break;
case "decade":
yearStep = 100;
break;
}
}
months[months.length] = toDate;
w = curTable.outerWidth();
h = curTable.outerHeight();
if(direction === 'horizontal') {
curTable.width(w).css('float', goNext ? 'left' : 'right');
wrapper.width((months.length + 1) * w);
wrapper.css('left', goNext ? 0 : -months.length * w).css('position', 'absolute');
} else {
wrapper.width(w);
wrapper.css('top', goNext ? 0 : -months.length * h).css('position', 'absolute');
wrapper.height((months.length + 1) * h);
}
$.each(months, function (index, date) {
if(self._myGrid === undefined) {
var mv = new wijMonthView(self, date), $view = self._customize(mv.getHtml(true));
if(direction === 'horizontal') {
$view.width(w).css('float', goNext ? 'left' : 'right').appendTo(wrapper);
} else {
$view.appendTo(wrapper);
}
} else {
if(direction === 'horizontal') {
$(self._myGrid.getHtml(date, true)).width(w).height(h).css('float', goNext ? 'left' : 'right').appendTo(wrapper);
} else {
$(self._myGrid.getHtml(date, true)).height(h).appendTo(wrapper);
}
}
});
this.options.displayDate = toDate;
if(this._myGrid === undefined) {
this._createMonthViews();
}
this._refreshTitle();
this.element.data('animating.wijcalendar', true);
if($.effects) {
wrapper.effect('slide', {
mode: 'hide',
direction: direction === 'horizontal' ? (goNext ? 'left' : 'right') : (goNext ? 'up' : 'down'),
easing: this.options.easing || 'easeOutBack',
distance: (direction === 'horizontal' ? w : h) * months.length,
duration: this.options.duration
}, function () {
curTable = wrapper.children(':last');
while(curTable.parent().is('.wijmo-wijcalendar-aniwrapper')) {
curTable.parent().replaceWith(curTable);
}
curTable.css({
'float': '',
'width': ''
});
self._bindEvents();
self.element.data('animating.wijcalendar', false);
self._trigger('afterSlide');
});
} else {
if(direction === 'horizontal') {
wrapperAniOpts = {
width: 0
};
} else {
wrapperAniOpts = {
height: 0
};
}
wrapper.animate(wrapperAniOpts, this.options.duration, null, //this.options.easing || 'easeOutBack',
function () {
curTable = wrapper.children(':last');
while(curTable.parent().is('.wijmo-wijcalendar-aniwrapper')) {
curTable.parent().replaceWith(curTable);
}
curTable.css({
'float': '',
'width': ''
});
self._bindEvents();
self.element.data('animating.wijcalendar', false);
self._trigger('afterSlide');
});
}
};
wijcalendar.prototype._onTitleClicked = function () {
if(!this.options.allowQuickPick || !this._isSingleMonth()) {
return;
}
if(this._isAnimating()) {
return;
}
if(this._myGrid === undefined) {
this._myGrid = new wijMyGrid(this);
} else {
switch(this._myGrid.gridType) {
case "month":
this._myGrid.gridType = "year";
break;
case "year":
this._myGrid.gridType = "decade";
break;
case "decade":
return;
}
}
this._refreshTitle();
this.element.width(this.element.width()).height(this.element.height());
var wijCSS = this.options.wijCSS, curTable = this.element.find('.' + wijCSS.datepickerCalendar), wrapper, container, nextTable, w = curTable.outerWidth(), h = curTable.outerHeight(), selIndex, row, col, toWidth, toHeight, toBounds, calendar = this;
if(curTable.parent().is('.wijmo-wijcalendar-aniwrapper')) {
wrapper = curTable.parent();
} else {
//wrapper = $.effects.createWrapper(curTable).css({ overflow: 'hidden' })
wrapper = $.createWrapper(curTable).css({
overflow: 'hidden'
}).removeClass(wijCSS.effectsWrapper).addClass('wijmo-wijcalendar-aniwrapper');
}
if(wrapper.parent().is('.wijmo-wijcalendar-aniwrapper')) {
container = wrapper.parent();
} else {
//container = $.effects.createWrapper(wrapper).css({ overflow: 'hidden' })
container = $.createWrapper(wrapper).css({
overflow: 'hidden'
}).removeClass(wijCSS.effectsWrapper).addClass('wijmo-wijcalendar-aniwrapper').width(w).height(h);
}
nextTable = $(this._myGrid.getHtml(true)).css({
position: 'absolute',
top: 0,
left: 0,
opacity: 0
}).appendTo(container).height(h);
selIndex = this._myGrid.getSelectedIndex();
row = Math.floor(selIndex / 4);
col = selIndex - (row * 4);
toWidth = w / 4;
toHeight = h / 3;
toBounds = {
left: toWidth * col,
top: toHeight * row,
width: toWidth,
height: toHeight
};
curTable.width("100%").height("100%");
wrapper.css({
border: 'solid 1px #cccccc'
});
this.element.data('animating.wijcalendar', true);
if($.effects) {
wrapper.effect('size', {
to: toBounds,
duration: this.options.duration || 500
}, function () {
wrapper.remove();
});
} else {
wrapper.animate(toBounds, this.options.duration || 500, null, function () {
wrapper.remove();
});
}
nextTable.animate({
opacity: 1
}, this.options.duration || 500, null, function () {
nextTable.css({
position: '',
top: '',
left: '',
filter: ''
});
while(nextTable.parent().is('.wijmo-wijcalendar-aniwrapper')) {
nextTable.parent().replaceWith(nextTable);
}
calendar._bindEvents();
calendar.element.data('animating.wijcalendar', false);
});
};
wijcalendar.prototype._onMyGridClicked = function (e) {
if(this._myGrid === undefined) {
return false;
}
if(this._isAnimating()) {
return false;
}
var cell = $(e.currentTarget), index = parseInt(cell.attr('index'), 10), value = parseInt(cell.attr('value'), 10), wijCSS = this.options.wijCSS, curTable = this.element.find('.' + wijCSS.datepickerCalendar), wrapper, container, w, h, bounds, $content, date, mv, nextTable, calendar = this;
if(this._myGrid.gridType !== "month") {
if(!index || index === 11) {
return false;
}
}
if(!cell.hasClass(wijCSS.stateActive)) {
this._myGrid.select(index, value);
}
if(this._myGrid.gridType === "decade") {
this._myGrid.gridType = "year";
} else {
if(this._myGrid.gridType === "year") {
this._myGrid.gridType = "month";
} else {
this._myGrid = undefined;
}
}
this._refreshTitle();
w = curTable.outerWidth();
h = curTable.outerHeight();
if(curTable.parent().is('.wijmo-wijcalendar-aniwrapper')) {
container = curTable.parent();
} else {
//container = $.effects.createWrapper(curTable).css({ overflow: 'hidden' })
container = $.createWrapper(curTable).css({
overflow: 'hidden'
}).removeClass(wijCSS.effectsWrapper).addClass('wijmo-wijcalendar-aniwrapper').width(w).height(h);
}
bounds = $.extend({
}, cell.position(), {
width: cell.width(),
height: cell.height()
});
if(this._myGrid === undefined) {
this._createMonthViews();
date = this.getDisplayDate();
mv = this._getMonthView(date);
$content = this._customize(mv.getHtml(true));
} else {
$content = $(this._myGrid.getHtml(true));
}
nextTable = $content.height(h).appendTo(container);
//wrapper = $.effects.createWrapper(nextTable).css({ overflow: 'hidden' })
wrapper = $.createWrapper(nextTable).css({
overflow: 'hidden'
}).removeClass(wijCSS.effectsWrapper).addClass('wijmo-wijcalendar-aniwrapper').css($.extend(bounds, {
border: 'solid 1px #cccccc',
position: 'absolute'
}));
this.element.data('animating.wijcalendar', true);
wrapper.animate({
left: 0,
top: 0,
width: w,
height: h
}, this.options.duration || 500, null, function () {
nextTable.css("width", "");
});
curTable.animate({
opacity: 0
}, this.options.duration || 500, null, function () {
curTable.remove();
while(nextTable.parent().is('.wijmo-wijcalendar-aniwrapper')) {
nextTable.parent().replaceWith(nextTable);
}
if(calendar._myGrid === undefined) {
calendar.element.width('').height('');
}
calendar._bindEvents();
calendar.element.data('animating.wijcalendar', false);
});
return false;
};
wijcalendar.prototype._onMyGridMouseEnter = function (e) {
if(this._myGrid === undefined) {
return;
}
var cell = $(e.currentTarget), index = parseInt(cell.attr('index'), 10);
if(this._myGrid.gridType !== "month" && (index < 0 || index > 11)) {
return;
}
cell.addClass(this.options.wijCSS.stateHover);
};
wijcalendar.prototype._onMyGridMouseLeave = function (e) {
if(this._myGrid === undefined) {
return;
}
var cell = $(e.currentTarget), index = parseInt(cell.attr('index'), 10);
if(this._myGrid.gridType !== "month" && (index < 0 || index > 11)) {
return;
}
cell.removeClass(this.options.wijCSS.stateHover);
};
wijcalendar.prototype._bindEvents = function () {
var wijCSS = this.options.wijCSS;
if(!this.element.data('preview.wijcalendar') && !this.options.disabledState && !this.options.disabled) {
this.element.find('div .wijmo-wijcalendar-navbutton').unbind().bind('mouseout.wijcalendar', function () {
var el = $(this);
el.removeClass(wijCSS.stateHover);
if(el.hasClass(wijCSS.datepickerNextHover)) {
el.removeClass(wijCSS.datepickerNextHover);
} else if(el.hasClass(wijCSS.datepickerPrevHover)) {
el.removeClass(wijCSS.datepickerPrevHover);
}
}).bind('mouseover.wijcalendar', function () {
var el = $(this);
el.addClass(wijCSS.stateHover);
if(el.hasClass(wijCSS.datepickerNext)) {
el.addClass(wijCSS.datepickerNextHover);
} else if(el.hasClass(wijCSS.datepickerPrev)) {
el.addClass(wijCSS.datepickerPrevHover);
}
}).bind('click.wijcalendar', $.proxy(this._onNavButtonClicked, this));
this.element.unbind(".wijcalendar").bind({
"mouseup.wijcalendar": $.proxy(this._onMouseUp, this)
});
this.element.find("." + wijCSS.datepickerTitle).unbind().bind('mouseout.wijcalendar', function () {
$(this).removeClass(wijCSS.stateHover);
}).bind('mouseover.wijcalendar', function () {
$(this).addClass(wijCSS.stateHover);
}).bind('click.wijcalendar', $.proxy(this._onTitleClicked, this));
this.element.find(".wijmo-wijcalendar-prevpreview-button, " + ".wijmo-wijcalendar-nextpreview-button").unbind('mouseenter.wijcalendar').unbind('mouseleave.wijcalendar').bind({
"mouseenter.wijcalendar": $.proxy(this._onPreviewMouseEnter, this),
"mouseleave.wijcalendar": $.proxy(this._onPreviewMouseLeave, this)
});
if(this._myGrid === undefined) {
this.element.find(".wijmo-wijcalendar-day-selectable").unbind().bind({
"click.wijcalendar": $.proxy(this._onDayClicked, this),
"mouseenter.wijcalendar": $.proxy(this._onDayMouseEnter, this),
"mouseleave.wijcalendar": $.proxy(this._onDayMouseLeave, this),
"mousedown.wijcalendar": $.proxy(this._onDayMouseDown, this),
"dragstart.wijcalendar": $.proxy(this._onDayDragStart, this)
});
if(!!this.options.selectionMode.month) {
this.element.find(".wijmo-wijcalendar-monthselector").unbind().bind({
"click.wijcalendar": $.proxy(this._onMonthSelectorClicked, this),
"mouseenter.wijcalendar": $.proxy(this._onMonthSelectorMouseEnter, this),
"mouseleave.wijcalendar": $.proxy(this._onMonthSelectorMouseLeave, this)
});
}
if(!!this.options.selectionMode.weekDay) {
this.element.find("." + wijCSS.datepickerWeekDay).unbind().bind({
"click.wijcalendar": $.proxy(this._onWeekDayClicked, this),
"mouseenter.wijcalendar": $.proxy(this._onWeekDayMouseEnter, this),
"mouseleave.wijcalendar": $.proxy(this._onWeekDayMouseLeave, this)
});
}
if(!!this.options.selectionMode.weekNumber) {
this.element.find(".wijmo-wijcalendar-week-num").unbind().bind({
"click.wijcalendar": $.proxy(this._onWeekNumberClicked, this),
"mouseenter.wijcalendar": $.proxy(this._onWeekNumberMouseEnter, this),
"mouseleave.wijcalendar": $.proxy(this._onWeekNumberMouseLeave, this)
});
}
} else {
this.element.find(".wijmo-wijcalendar-day-selectable").unbind().bind({
"click.wijcalendar": $.proxy(this._onMyGridClicked, this),
"mouseenter.wijcalendar": $.proxy(this._onMyGridMouseEnter, this),
"mouseleave.wijcalendar": $.proxy(this._onMyGridMouseLeave, this)
});
}
}
};
wijcalendar.prototype._isSelectable = function (dayType) {
var o = this.options;
return (o.showOtherMonthDays && (dayType & wijDayType.otherMonth)) || !(dayType & (wijDayType.outOfRange | wijDayType.disabled | wijDayType.otherMonth));
};
wijcalendar.prototype._getCellClassName = function (dayType, date, previewMode) {
var o = this.options, cssCell = '', cssText = o.wijCSS.stateDefault, allowSelDay = (!!o.selectionMode.day || !!o.selectionMode.days);
previewMode = previewMode || false;
if(!previewMode && !o.disabledState && !o.disabled && allowSelDay && this._isSelectable(dayType)) {
cssCell += " wijmo-wijcalendar-day-selectable";
}
if((dayType & wijDayType.weekEnd)) {
cssCell += ' ' + o.wijCSS.datepickerWeekEnd;
}
if((dayType & wijDayType.otherMonth)) {
cssCell += ' ' + o.wijCSS.datepickerOtherMonth;
cssText += ' ' + o.wijCSS.prioritySecondary;
}
if((dayType & wijDayType.outOfRange)) {
cssCell += ' wijmo-wijcalendar-outofrangeday';
cssText += ' ' + o.wijCSS.prioritySecondary;
}
if((dayType & wijDayType.gap)) {
cssCell += ' wijmo-wijcalendar-gap';
} else {
if((dayType & wijDayType.disabled)) {
cssCell += ' ' + o.wijCSS.datepickerUnselectable;
cssText += ' ' + o.wijCSS.stateDisabled;
}
if((dayType & wijDayType.today)) {
cssCell += ' ' + o.wijCSS.datepickerDaysCellOver + ' ' + o.wijCSS.datepickerToday;
cssText += ' ' + o.wijCSS.stateHighlight;
}
if((dayType & wijDayType.selected) && ((dayType & (wijDayType.outOfRange | wijDayType.disabled)) === 0)) {
cssCell += ' ' + o.wijCSS.datepickerCurrentDay;
cssText += ' ' + o.wijCSS.stateActive;
}
if((dayType & wijDayType.gap)) {
cssCell += ' wijmo-wijcalendar-gap';
}
if((dayType & wijDayType.custom)) {
cssCell += ' wijmo-wijcalendar-customday';
}
}
return {
cssCell: cssCell,
cssText: cssText
};
};
wijcalendar.prototype._onNavButtonClicked = function (e) {
if(this._isAnimating()) {
return false;
}
var step = 1, btnId = $(e.currentTarget).attr('id'), date = this.getDisplayDate(), nextDate = date;
if(this._myGrid === undefined) {
step = btnId.indexOf('quick') >= 0 ? this.options.quickNavStep : 1;
step = btnId.indexOf('next') >= 0 ? step : -step;
step = step * this.options.monthRows * this.options.monthCols;
nextDate = wijDateOps.addMonths(date, step);
} else {
step = btnId.indexOf('next') >= 0 ? 1 : -1;
switch(this._myGrid.gridType) {
case "month":
nextDate = wijDateOps.addYears(date, step);
break;
case "year":
nextDate = wijDateOps.addYears(date, step * 10);
break;
case "decade":
nextDate = wijDateOps.addYears(date, step * 100);
break;
}
}
this._slideToDate(nextDate);
return false;
};
wijcalendar.prototype._getMonthGroupHtml = function () {
var date = this.getDisplayDate(), mv, width, hw, wijCSS = this.options.wijCSS, r, c;
if(this._isSingleMonth()) {
mv = this._getMonthView(date);
mv.showPreview = this.options.allowPreview && !this.element.data('preview.wijcalendar');
return mv.getHtml();
}
width = 100 / this.options.monthCols + '%';
hw = new htmlTextWriter();
for(r = 0; r < this.options.monthRows; r++) {
for(c = 0; c < this.options.monthCols; c++) {
hw.writeBeginTag('div');
hw.writeAttribute('class', wijCSS.datepickerGroup + (c === 0 ? ' ' + wijCSS.datepickerGroupFirst : '') + (c === this.options.monthCols - 1 ? ' ' + wijCSS.datepickerGroupLast : ''));
hw.writeAttribute('style', 'width:' + width);
hw.writeTagRightChar();
mv = this._getMonthView(date);
mv.showPreview = false;
hw.write(mv.getHtml());
hw.writeEndTag('div');
date = wijDateOps.addMonths(date, 1);
}
hw.writeBeginTag('div');
hw.writeAttribute('class', wijCSS.datepickerRowBreak);
hw.writeTagRightChar();
hw.writeEndTag('div');
}
return hw.toString();
};
wijcalendar.prototype._getCalendarHtml = function () {
this._createMonthViews();
var hw = new htmlTextWriter();
hw.write(this._getMonthGroupHtml());
return hw.toString();
};
wijcalendar.prototype._customizeDayCell = function ($dayCell) {
if($dayCell.attr("state") === undefined) {
$dayCell.attr("state", 'normal');
}
if($dayCell.attr("daytype") === undefined) {
return;
}
if($dayCell.attr("date") === undefined) {
return;
}
var dayType = parseInt($dayCell.attr("daytype"), 10), date = new Date($dayCell.attr("date")), hover = $dayCell.attr("state") === 'hover';
this.options.customizeDate($dayCell, date, dayType, hover);
};
wijcalendar.prototype._customize = function (html) {
var o = this.options, self = this, $h = $(html);
if(!$.isFunction(o.customizeDate)) {
return $h;
}
$.each($h.find('.wijmo-wijcalendar-day-selectable'), function (index, dayCell) {
self._customizeDayCell($(dayCell));
});
return $h;
};
wijcalendar.prototype._createCalendar = function () {
//for jquery change to 1.9 $.parseHTML
return this._customize($($.parseHTML(this._getCalendarHtml())));
};
wijcalendar.prototype._createMonthGroup = function () {
return this._customize($(this._getMonthGroupHtml()));
};
wijcalendar.prototype._getMonthID = function (date) {
return date.getFullYear() + '_' + (date.getMonth() + 1);
};
wijcalendar.prototype._createMonthViews = function () {
this._monthViews = {
};
var monthID = '', date = this.getDisplayDate(), row, col, mv, count;
for(row = 0; row < this.options.monthRows; row++) {
for(col = 0; col < this.options.monthCols; col++) {
monthID = this._getMonthID(date);
this._monthViews[monthID] = new wijMonthView(this, date);
if(row === 0) {
if(col === 0) {
this._monthViews[monthID].isFirst = true;
}
if(col === this.options.monthCols - 1) {
this._monthViews[monthID].isLast = true;
}
}
date = wijDateOps.addMonths(date, 1);
}
}
date = this.getDisplayDate();
monthID = this._getMonthID(date);
mv = this._monthViews[monthID];
if(mv) {
this._groupStartDate = mv.getStartDate();
}
count = this.options.monthRows * this.options.monthCols;
if(count > 1) {
date = wijDateOps.addMonths(date, count - 1);
monthID = this._getMonthID(date);
mv = this._monthViews[monthID];
}
if(mv) {
this._groupEndDate = mv.getEndDate();
}
};
wijcalendar.prototype._getMonthView = function (date) {
var monthID = this._getMonthID(date);
return this._monthViews[monthID];
};
wijcalendar.prototype._getId = function () {
return this.element.attr("id");
};
wijcalendar.prototype._getChildElement = function (id) {
var child = this.element.find('[id*=\'' + id + '\']');
return child.length === 0 ? undefined : child;
};
wijcalendar.prototype._refreshDayCell = function (dayCell) {
var $dc = $(dayCell), o = this.options, dayType, date, hover, txt;
if($dc.attr("state") === undefined) {
$dc.attr("state", 'normal');
}
if($dc.attr("daytype") === undefined) {
return;
}
if($dc.attr("date") === undefined) {
return;
}
dayType = parseInt($dc.attr("daytype"), 10);
date = new Date($dc.attr("date"));
hover = $dc.attr("state") === 'hover';
$dc.attr('class', this._getCellClassName(dayType, date, undefined).cssCell);
$dc.removeAttr('aria-selected');
if(dayType & wijDayType.selected) {
$dc.attr('aria-selected', true);
}
if($.isFunction(o.customizeDate)) {
if(this._customizeDayCell($dc)) {
return;
}
}
txt = $dc.find('a');
if(txt.length > 0) {
txt.toggleClass(this.options.wijCSS.stateHover, hover);
txt.toggleClass(this.options.wijCSS.stateActive, ((dayType & wijDayType.selected) !== 0));
}
};
wijcalendar.prototype._isSingleMonth = function () {
return this.options.monthCols * this.options.monthRows === 1;
};
wijcalendar.prototype._splitString = function (s, sep, count) {
if(count === undefined) {
return s.split(sep);
}
var ret = [], arr = s.split(sep), i;
for(i = 0; i < arr.length; i++) {
if(i >= count) {
ret[count - 1] = ret[count - 1] + sep + arr[i];
} else {
ret.push(arr[i]);
}
}
return ret;
};
wijcalendar.prototype._getNavButtonHtml = function (id, cls, imgClass, tooltip) {
var hw = new htmlTextWriter();
hw.writeBeginTag('a');
hw.writeAttribute('id', id);
hw.writeAttribute('class', cls);
hw.writeAttribute('role', 'button');
hw.writeAttribute('href', '#');
if(tooltip) {
hw.writeAttribute('title', tooltip);
hw.writeAttribute('aria-label', tooltip);
}
hw.writeTagRightChar();
hw.writeBeginTag('span');
hw.writeAttribute('class', imgClass);
hw.writeTagRightChar();
if(tooltip) {
hw.write(tooltip);
}
hw.writeEndTag('span');
hw.writeEndTag('a');
return hw.toString();
};
wijcalendar.prototype._getTitleText = // 2013-1-6
function (monthDate) {
if(this._myGrid !== undefined) {
return this._myGrid.getTitle();
} else {
var d = monthDate || this.getDisplayDate(), f = this.options.titleFormat || 'MMMM yyyy';
if($.isFunction(this.options.title)) {
return this.options.title(d, f) || this._formatDate(f, d);
}
return this._formatDate(f, d);
}
};
wijcalendar.prototype._refreshTitle = function () {
this.element.find('.' + this.options.wijCSS.datepickerTitle).html(this._getTitleText(undefined));
};
wijcalendar.prototype._fillTitle = function (hw, date) {
var wijCSS = this.options.wijCSS;
hw.writeBeginTag('div');
hw.writeAttribute('class', wijCSS.datepickerTitle + ' wijmo-wijcalendar-title' + ' ' + wijCSS.stateDefault + ' ' + wijCSS.cornerAll);
hw.writeTagRightChar();
hw.write(this._getTitleText(date));
hw.writeEndTag('div');
};
wijcalendar.prototype._getHeaderHtml = function (monthDate, prevButtons, nextButtons) {
var previewMode = !!this.element.data('preview.wijcalendar'), wijCSS = this.options.wijCSS, buttons = previewMode ? 'none' : (this._isSingleMonth() ? this.options.navButtons : 'default'), isRTL = this.element.is('.' + wijCSS.datepickerRtl), hw = new htmlTextWriter();
if(buttons === 'quick') {
hw.writeBeginTag('div');
hw.writeAttribute('class', wijCSS.header + ' wijmo-wijcalendar-header ' + wijCSS.helperClearFix + ' ' + wijCSS.cornerAll);
hw.writeAttribute('role', 'heading');
hw.writeTagRightChar();
if(!!prevButtons) {
hw.write(this._getNavButtonHtml('quickprev', 'wijmo-wijcalendar-navbutton ' + wijCSS.datepickerPrev + ' ' + wijCSS.cornerAll, wijCSS.icon + ' ui-icon-seek-' + (isRTL ? 'next' : 'prev') + ' ' + (isRTL ? this.options.wijCSS.iconArrowRight : this.options.wijCSS.iconArrowLeft), this.options.quickPrevTooltip.replace('#', this.options.quickNavStep)));
}
hw.writeBeginTag('div');
hw.writeAttribute('class', wijCSS.datepickerHeader + ' wijmo-wijcalendar-header-inner');
hw.writeTagRightChar();
if(!!prevButtons) {
hw.write(this._getNavButtonHtml('prev', 'wijmo-wijcalendar-navbutton ' + wijCSS.datepickerPrev + ' ' + wijCSS.cornerAll, wijCSS.icon + ' ui-icon-circle-triangle-' + (isRTL ? 'e' : 'w') + " " + (isRTL ? this.options.wijCSS.iconArrowRight : this.options.wijCSS.iconArrowLeft), this.options.prevTooltip));
}
this._fillTitle(hw, monthDate);
if(!!nextButtons) {
hw.write(this._getNavButtonHtml('next', 'wijmo-wijcalendar-navbutton ' + wijCSS.datepickerNext + ' ' + wijCSS.cornerAll, wijCSS.icon + ' ui-icon-circle-triangle-' + (isRTL ? 'w' : 'e') + " " + (isRTL ? this.options.wijCSS.iconArrowLeft : this.options.wijCSS.iconArrowRight), this.options.nextTooltip));
}
hw.writeEndTag('div');
if(!!nextButtons) {
hw.write(this._getNavButtonHtml('quicknext', 'wijmo-wijcalendar-navbutton ' + wijCSS.datepickerNext + ' ' + wijCSS.cornerAll, wijCSS.icon + ' ui-icon-seek-' + (isRTL ? 'prev' : 'next') + " " + (isRTL ? this.options.wijCSS.iconArrowLeft : this.options.wijCSS.iconArrowRight), this.options.quickNextTooltip.replace('#', this.options.quickNavStep)));
}
hw.writeEndTag('div');
} else {
hw.writeBeginTag('div');
hw.writeAttribute('class', wijCSS.datepickerHeader + ' ' + wijCSS.header + ' ' + wijCSS.datepickerHeader + ' ' + wijCSS.helperClearFix + ' ' + wijCSS.cornerAll);
hw.writeAttribute('role', 'heading');
hw.writeTagRightChar();
if(buttons !== 'none' && !!prevButtons) {
hw.write(this._getNavButtonHtml('prev', 'wijmo-wijcalendar-navbutton ' + wijCSS.datepickerPrev + ' ' + wijCSS.cornerAll, wijCSS.icon + ' ui-icon-circle-triangle-' + (isRTL ? 'e' : 'w') + ' ' + (isRTL ? this.options.wijCSS.iconArrowRight : this.options.wijCSS.iconArrowLeft), this.options.prevTooltip));
}
this._fillTitle(hw, monthDate);
if(buttons !== 'none' && !!nextButtons) {
hw.write(this._getNavButtonHtml('next', 'wijmo-wijcalendar-navbutton ' + wijCSS.datepickerNext + ' ' + wijCSS.cornerAll, wijCSS.icon + ' ui-icon-circle-triangle-' + (isRTL ? 'w' : 'e') + ' ' + (isRTL ? this.options.wijCSS.iconArrowLeft : this.options.wijCSS.iconArrowRight), this.options.nextTooltip));
}
hw.writeEndTag('div');
}
return hw.toString();
};
wijcalendar.prototype._formatDate = function (format, date) {
if(!wijDateOps.getTicks(date)) {
return ' ';
}
return Globalize.format(date, format, this._getCulture(null));
};
return wijcalendar;
})(wijmo.wijmoWidget);
calendar.wijcalendar = wijcalendar;
var wijcalendar_options = (function () {
function wijcalendar_options() {
/** Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijcalendar')";
//All CSS classes used in widgets that use jQuery UI CSS Framework
/** @ignore*/
this.wijCSS = {
datepickerInline: "ui-datepicker-inline",
datepicker: "ui-datepicker",
datepickerCalendar: "ui-datepicker-calendar",
datepickerMulti: "ui-datepicker-multi",
datepickerRtl: "datepicker-rtl",
datepickerOtherMonth: "ui-datepicker-other-month",
prioritySecondary: "ui-priority-secondary",
effectsWrapper: "ui-effects-wrapper",
datepickerNextHover: "ui-datepicker-next-hover",
datepickerPrevHover: "ui-datepicker-prev-hover",
datepickerNext: "ui-datepicker-next",
datepickerPrev: "ui-datepicker-prev",
datepickerTitle: "ui-datepicker-title",
datepickerWeekDay: "ui-datepicker-week-day",
datepickerWeekEnd: "ui-datepicker-week-end",
datepickerUnselectable: "ui-datepicker-unselectable",
datepickerDaysCellOver: "ui-datepicker-days-cell-over",
datepickerToday: "ui-datepicker-today",
stateHighlight: "ui-state-highlight",
datepickerCurrentDay: "ui-datepicker-current-day",
datepickerGroup: "ui-datepicker-group",
datepickerGroupFirst: "ui-datepicker-group-first",
datepickerGroupLast: "ui-datepicker-group-last",
datepickerRowBreak: "ui-datepicker-row-break",
datepickerHeader: "ui-datepicker-header",
uiIconGripDottedVertical: "ui-icon-grip-dotted-vertical",
uiDatepickerWeekCol: "ui-datepicker-week-col"
};
/** @ignore*/
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body ui-body-c",
stateDefault: "ui-btn-up-c",
stateHighlight: "ui-btn-down-e"
};
/** Assigns the string value of the culture ID that appears on the calendar
* for the weekday and title names.
*/
this.culture = '';
/** Gets or sets the number of calendar months in horizontal direction.
* @remarks
* By setting the monthCols property, calendar months will be added horizontally to the widget.
* The default value of this option is "1", which displays one calendar month at a time.
*/
this.monthCols = 1;
/** Gets or sets the number of calendar months in vertical direction.
* @remarks
* By setting the monthRows property, calendar months will be added vertically to the widget.
* The default value of this option is "1", which displays one calendar month at a time.
*/
this.monthRows = 1;
/** Gets or sets the format for the title text.*/
this.titleFormat = "MMMM yyyy";
/** A Boolean property that determines whether to display the calendar's title.*/
this.showTitle = true;
/** Gets or sets the display date for the first month view.
* You can specify the date via a Date object.
* @type {Date}
*/
this.displayDate = undefined;
/** Gets or sets the number of day rows that appear in the calendar.
* This is useful if you want to view more or less calendar days on the calendar month.
*/
this.dayRows = 6;
/** Gets or sets the number of day columns that appear in the calendar.
* This is useful if you want to view more or less calendar days on the calendar month.
*/
this.dayCols = 7;
/** Gets or sets the format for the week day.
* @remarks
* Possible values are: "short", "full", "firstLetter" or "abbreviated".
*/
this.weekDayFormat = "short";
/** A Boolean property that determines whether to display week days.*/
this.showWeekDays = true;
/** Determines whether to display week numbers.
* @remarks
* When enabled, the week numbers appear vertically on the left side of the calendar.
* The week numbers represent a week number for each week in the calendar month.
* In the calendar year there are a total of 52 weeks so the weeknumbers will range from 1 to 52.
*/
this.showWeekNumbers = false;
/** Defines different rules for determining the first week of the year.
* @example
* $("#calendar1").wijcalendar(
* { calendarWeekRule: 'firstFourDayWeek'}
* );
* @remarks
* Possible values are: "firstDay", "firstFullWeek" or "firstFourDayWeek"
*/
this.calendarWeekRule = "firstDay";
/** Determines the minimum date to display. You can specify the minDate via a Date object.
* @type {Date}
* @remarks The default value is new Date(1900, 0, 1).
*/
this.minDate = new Date(1900, 0, 1);
/** Determines the maximum date to display. You can specify the maxDate via a Date object.
* @type {Date}
* @remarks The default value is new Date(1900, 0, 1).
*/
this.maxDate = new Date(2099, 11, 31);
/** Determines whether to display the days of the next and/or previous month.
*/
this.showOtherMonthDays = true;
/** Determines whether to add zeroes to days with only one digit
* @remarks
* for example, "1" would become "01" if this property were set to "true"
*/
this.showDayPadding = false;
/** Gets or sets the date selection mode on the calendar control that
* specifies whether the user can select a single day, a week, or an entire month.
* @remarks
* Possible fields in hash are: day, days, weekDay, weekNumber, month.
* @example
* $("#calendar1").wijcalendar(
* { selectionMode: {day:true, weekDay:true}}
* );
*/
this.selectionMode = {
day: true,
days: true
};
/** Allows users to preview the next and previous months by
* hovering over the previousPreview and nextPreview buttons.
*/
this.allowPreview = false;
/** Determines whether users can change the view to month/year/decade
* while clicking on the calendar title.
*/
this.allowQuickPick = true;
/** Gets or sets the format for the ToolTip. */
this.toolTipFormat = "dddd, MMMM dd, yyyy";
/** Gets or sets the text for the 'previous' button's ToolTip. */
this.prevTooltip = "Previous";
/** Gets or sets the text for the 'next' button's ToolTip. */
this.nextTooltip = "Next";
/** Gets or sets the "quick previous" button's ToolTip.*/
this.quickPrevTooltip = "Quick Previous";
/** Gets or sets the "quick next" button's ToolTip.*/
this.quickNextTooltip = "Quick Next";
/** Gets or sets the "previous preview" button's ToolTip.*/
this.prevPreviewTooltip = "";
/** Gets or sets the "next preview" button's ToolTip. */
this.nextPreviewTooltip = "";
/** Determines the display type of navigation buttons.
* @remarks
* Possible values are: "default", "quick" or "none"
*/
this.navButtons = 'default';
/** Determines the increase/decrease steps when clicking the quick navigation button. */
this.quickNavStep = 12;
/** Determines the month slide direction.
* @remarks
* Possible values are: horizontal or vertical
*/
this.direction = 'horizontal';
/** Gets or sets the animation duration in milliseconds. */
this.duration = 250;
/** Sets the type of animation easing effect that users experience
* when they click the previous or next buttons on the wijcalendar.
* @remarks
* For example, if the easing is set to "easeInBounce" the calendar
* bounces back and forth several times and then slides to the previous
* or next calendar month.
* You can create custom easing animations using jQuery UI Easings.
*/
this.easing = 'easeInQuad';
/** A Boolean property that determines whether the wijcalendar widget
* is a pop-up calendar.
* @remarks
* this is useful, for example,
* if you're integrating the calendar with an input control to create a date picker.
*/
this.popupMode = false;
/** A Boolean property that determines whether to autohide
* the calendar in pop-up mode when clicking outside of the calendar.
*/
this.autoHide = true;
/** Function used for customizing the content, style and attributes of a day cell.
* @type {function}
* @remarks the function include following parameter:
* $daycell:jQuery jQuery object that represents table cell of the date to be customized.
* date: Date Date of the cell.
* hover: boolean Whether mouse is over the day cell.
* preview: object Whether rendering in preview container.
* returns true if day cell content has been changed
* and default cell content will not be applied.
*/
this.customizeDate = null;
/** A callback function used to customizing the title text on month view.
* @type {function}
* @remarks the function include following parameter:
* date: Date The display date of the month.
* format: string The title format. Determined by the options.titleFormat.
*/
this.title = null;
/** The beforeSlide event handler.
* A function called before the calendar view slides to another month.
* Cancellable.
* @event
*/
this.beforeSlide = null;
/** The afterSlide event handler.
* A function called after the calendar view slided to another month.
* Cancellable.
* @event
*/
this.afterSlide = null;
/** The beforeSelect event handler.
* A function called before user selects a day by mouse. Cancellable.
* @event
* @param {Object} e The jQuery.Event object.
* @param {ISelectedDate} args The data with this event.
* @example
* $("#calendar1").wijcalendar({
* beforeSelect: function (e, data)
* {
* var selDates = $("#calendar1").wijcalendar('option', 'selectedDates'),
* selected = false,
* list;
* $.each(selDates, function (i, d)
* {
* if (data.date.getFullYear() === d.getFullYear() &&
* data.date.getMonth() === d.getMonth() && data.date.getDate() === d.getDate())
* {
* selected = true;
* return false;
* }
* );
*
* if (selected)
* {
* $("#calendar1").wijcalendar('unSelectDate', data.date);
* } else
* {
* $("#calendar1").wijcalendar('selectDate', data.date);
* }
*
* list = $("#msg").empty();
* selDates = $("#calendar1").wijcalendar('option', 'selectedDates');
* $.each(selDates, function (i, d)
* {
* var li = $("<li/>");
* li.text(d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate());
* list.append(li);
* });
*
* return false;
* }
* });
*/
this.beforeSelect = null;
/** The afterSelect event handler.
* A function called after user selects a day by mouse.
* @event
* @param {Object} e The jQuery.Event object.
* @param {ISelectedDate} args The data with this event.
*/
this.afterSelect = null;
/** The selectedDatesChanged event handler.
* A function called after the selectedDates collection changed.
* @event
* @dataKey {Date} dates The array with all selected date object.
* @example
* $("#calendar").wijcalendar(
* {
* popupMode: true,
* selectedDatesChanged: function () {
* var selDate = $(this).wijcalendar("getSelectedDate");
* var selectDate = new Date(selDate);
* if (!!selDate) $("#popdate").val(selectDate.getMonth() + 1 + "/" + selectDate.getDate() + "/" + selectDate.getFullYear());
* }
*/
this.selectedDatesChanged = null;
}
return wijcalendar_options;
})();
;
wijcalendar.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijcalendar_options());
$.wijmo.registerWidget("wijcalendar", wijcalendar.prototype);
/** @ignore */
var htmlTextWriter = (function () {
function htmlTextWriter() {
this._html = [];
}
htmlTextWriter.prototype.writeTagLeftChar = function () {
this._html[this._html.length] = '<';
};
htmlTextWriter.prototype.writeTagRightChar = function () {
this._html[this._html.length] = '>';
};
htmlTextWriter.prototype.write = function (text) {
this._html[this._html.length] = ' ' + text + ' ';
};
htmlTextWriter.prototype.writeBeginTag = function (tagName) {
this._html[this._html.length] = '<' + tagName;
};
htmlTextWriter.prototype.writeEndTag = function (tagName) {
this._html[this._html.length] = '</' + tagName + '>';
};
htmlTextWriter.prototype.writeFullBeginTag = function (tagName) {
this._html[this._html.length] = '<' + tagName + '>';
};
htmlTextWriter.prototype.writeSelfClosingTagEnd = function () {
this._html[this._html.length] = '/>';
};
htmlTextWriter.prototype.writeAttribute = function (name, value) {
if(value === undefined || value === null) {
return;
}
this._html[this._html.length] = ' ' + name + '=\"';
this._html[this._html.length] = value;
this._html[this._html.length] = '\"';
};
htmlTextWriter.prototype.clean = function () {
this._html = [];
};
htmlTextWriter.prototype.toString = function () {
return this._html.join('');
};
return htmlTextWriter;
})();
calendar.htmlTextWriter = htmlTextWriter;
var wijDateOps = {
addDays: function (date, days) {
var dt = new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);
if(days) {
if(dt.getDate() === date.getDate()) {
dt = new Date(date.getFullYear(), date.getMonth(), date.getDate());
dt.setTime(dt.getTime() + (days * 24 * 3600 * 1000));
}
}
return dt;
},
addMonths: function (date, months) {
return new Date(date.getFullYear(), date.getMonth() + months, 1);
},
addYears: function (date, years) {
return this.addMonths(date, years * 12);
},
getDate: function (date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
},
getTicks: function (date) {
return date.valueOf();
},
isSameDate: function (date1, date2) {
return date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate();
},
isSameMonth: function (date1, date2) {
return date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth();
},
getDaysInMonth: function (date) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
},
getWeekStartDate: function (date, firstDayOfWeek) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() - ((date.getDay() - firstDayOfWeek + 7) % 7));
},
getDayOfYear: function (date) {
var start = new Date(date.getFullYear(), 0, 1), distance = this.getTicks(date) - this.getTicks(start), days = distance / (24 * 60 * 60 * 1000);
return Math.floor(days) + 1;
},
getFirstDayWeekOfYear: function (date, firstDayOfWeek) {
var days = this.getDayOfYear(date) - 1, offset = date.getDay() - (days % 7), weeks;
offset = ((offset - firstDayOfWeek) + 14) % 7;
weeks = ((days + offset) / 7);
return Math.floor(weeks) + 1;
},
getDayOfWeek: function (date, firstDayOfWeek) {
return ((date.getDay() - firstDayOfWeek + 7) % 7);
},
getWeekOfYearFullDays: function (time, rule, firstDayOfWeek, fullDays) {
var days = this.getDayOfYear(time) - 1, offset = (this.getDayOfWeek(time, firstDayOfWeek)) - (days % 7);
offset = ((firstDayOfWeek - offset) + 14) % 7;
if((offset) && (offset >= fullDays)) {
offset -= 7;
}
offset = days - offset;
if(offset >= 0) {
return (Math.floor(offset / 7) + 1);
}
return this.getWeekOfYearFullDays(this.addDays(time, -(days + 1)), rule, firstDayOfWeek, fullDays);
},
getWeekOfYear: function (date, rule, firstDayOfWeek) {
switch(rule) {
case "firstDay":
return this.getFirstDayWeekOfYear(date, firstDayOfWeek);
case "firstFullWeek":
return this.getWeekOfYearFullDays(date, rule, firstDayOfWeek, 7);
case "firstFourDayWeek":
return this.getWeekOfYearFullDays(date, rule, firstDayOfWeek, 4);
}
return this.getFirstDayWeekOfYear(date, firstDayOfWeek);
},
getDateToken: function (date) {
return date.getFullYear() + '_' + date.getMonth() + '_' + date.getDate();
}
};
/** @ignore */
var wijMonthView = (function () {
function wijMonthView(calendar, displayDate) {
this.calendar = calendar;
if(displayDate === undefined || wijDateOps.isSameDate(displayDate, new Date(1900, 0, 1))) {
displayDate = new Date();
}
this.displayDate = displayDate;
this.id = this.calendar._getId() + '_' + this.calendar._getMonthID(displayDate);
this.isFirst = false;
this.isLast = false;
this.showPreview = false;
this.culture = this.calendar._getCulture();
this._calcDates(this.displayDate);
}
wijMonthView.prototype._calcDates = function (date) {
var daysInMonth = wijDateOps.getDaysInMonth(date);
this._startDateInMonth = new Date(date.getFullYear(), date.getMonth(), 1);
this._endDateInMonth = wijDateOps.addDays(this._startDateInMonth, daysInMonth - 1);
this._startDate = wijDateOps.getWeekStartDate(this._startDateInMonth, this.culture.calendar.firstDay);
this._endDate = wijDateOps.addDays(this._startDate, this.calendar.options.dayRows * this.calendar.options.dayCols - 1);
};
wijMonthView.prototype._isFirstMonth = function () {
var date = this.calendar.getDisplayDate();
return wijDateOps.isSameMonth(this._startDateInMonth, date);
};
wijMonthView.prototype._isLastMonth = function () {
var date = this.calendar.getDisplayDate();
date = new Date(date.getFullYear(), date.getMonth(), 1);
date = wijDateOps.addMonths(date, this.calendar.options.monthCols * this.calendar.options.monthRows - 1);
return wijDateOps.isSameMonth(this._startDateInMonth, date);
};
wijMonthView.prototype.getStartDate = function () {
return this._startDate;
};
wijMonthView.prototype.getEndDate = function () {
return this._endDate;
};
wijMonthView.prototype._getMonthDate = function () {
if(this._startDateInMonth === undefined) {
//this._calcDates(this.getDisplayDate());
}
return this._startDateInMonth;
};
wijMonthView.prototype._setMonthDate = function (date) {
this._calcDates(date);
};
wijMonthView.prototype._getWeekDayText = function (day, format) {
format = format || "short";
var days = this.culture.calendar.days, text = '';
switch(format) {
case "full":
text = days.names[day];
break;
case "firstLetter":
text = days.names[day].substring(0, 1);
break;
case "abbreviated":
text = days.namesAbbr[day];
break;
default:
text = days.namesShort[day];
break;
}
return text;
};
wijMonthView.prototype._getRowCount = function () {
var o = this.calendar.options;
return o.showWeekDays ? o.dayRows + 1 : o.dayRows;
};
wijMonthView.prototype._getColCount = function () {
var o = this.calendar.options;
return o.showWeekNumbers ? o.dayCols + 1 : o.dayCols;
};
wijMonthView.prototype._getDayType = function (date) {
var o = this.calendar.options, dayType = wijDayType.general, dow = date.getDay(), weekEnd = dow === 6 || dow === 0, outOfRange = // Saturday or Sunday
date < o.minDate || date > o.maxDate, otherMonth = date < this._startDateInMonth || date > this._endDateInMonth, isDisabled = outOfRange || this.calendar._getDisabledDates().contains(date), isSelected = this.calendar._getSelectedDates().contains(date), today = new Date(), isToday = wijDateOps.isSameDate(date, today), isCustom = false;
if(weekEnd) {
dayType |= wijDayType.weekEnd;
}
if(isToday) {
dayType |= wijDayType.today;
}
if(isDisabled) {
dayType |= wijDayType.disabled;
}
if(otherMonth) {
dayType |= wijDayType.otherMonth;
}
if(outOfRange) {
dayType |= wijDayType.outOfRange;
}
if(isSelected) {
dayType |= wijDayType.selected;
}
if(isCustom) {
dayType |= wijDayType.custom;
}
if(otherMonth && !o.showOtherMonthDays) {
dayType |= wijDayType.gap;
}
return dayType;
};
wijMonthView.prototype._refreshDate = function (date) {
if(date < this._startDate || date > this._endDate) {
return;
}
var o = this.calendar.options, dUTC = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()), startUTC = Date.UTC(this._startDate.getFullYear(), this._startDate.getMonth(), this._startDate.getDate()), offset = (Math.floor(Math.abs(dUTC - startUTC) / (24 * 60 * 60 * 1000))), row = Math.floor(offset / this.calendar.options.dayCols), col = Math.floor(offset % this.calendar.options.dayCols), tbl, r, dayCell, dayType;
if(o.showWeekNumbers) {
col++;
}
if(o.showWeekDays) {
row++;
}
tbl = $("#" + this.id, this.calendar.element).get(0);
if(tbl) {
if(row < tbl.rows.length) {
r = tbl.rows[row];
if(col < r.cells.length) {
dayCell = r.cells[col];
dayType = this._getDayType(date);
$(dayCell).attr('daytype', dayType.toString());
this.calendar._refreshDayCell(dayCell);
}
}
}
};
wijMonthView.prototype._fillDayCell = function (hw, date, previewMode) {
var o = this.calendar.options, custom = null, text = date.getDate().toString(), tooltip = this.calendar._formatDate(o.toolTipFormat || "dddd, MMMM dd, yyyy", date), dayType = this._getDayType(date), selectable = this.calendar._isSelectable(dayType), css = this.calendar._getCellClassName(dayType, date, previewMode);
text = (o.showDayPadding && text.length === 1) ? '0' + text : text;
hw.writeBeginTag('td');
hw.writeAttribute('daytype', (dayType).toString());
if(selectable) {
hw.writeAttribute('title', tooltip);
hw.writeAttribute('aria-label', tooltip);
}
hw.writeAttribute('date', date.toDateString());
hw.writeAttribute('class', css.cssCell);
hw.writeAttribute('role', 'gridcell');
if(!selectable) {
hw.writeAttribute('aria-disabled', 'true');
}
hw.writeTagRightChar();
if((dayType & wijDayType.gap)) {
hw.write(' ');
} else {
if(custom && custom.content) {
hw.write(custom.content);
} else {
hw.writeBeginTag('a');
hw.writeAttribute('class', css.cssText);
hw.writeAttribute('href', '#');
hw.writeAttribute('onclick', 'return false;');
hw.writeTagRightChar();
hw.write(text);
hw.writeEndTag('a');
}
}
hw.writeEndTag('td');
};
wijMonthView.prototype.getHtml = function (tableOnly) {
tableOnly = !!tableOnly;
var o = this.calendar.options, wijCSS = o.wijCSS, previewMode = !!this.calendar.element.data('preview.wijcalendar'), hw = new htmlTextWriter(), i, j, dayOfWeek, weekStartDate, weekEnd, colIndex, txt, fullTxt, date, wnDate, rowIndex, weekNumber;
if(!tableOnly && o.showTitle) {
hw.write(this.calendar._getHeaderHtml(this._startDateInMonth, this.isFirst, this.isLast));
}
if(!tableOnly && !previewMode && this.showPreview) {
hw.writeBeginTag('div');
hw.writeAttribute('class', 'wijmo-wijcalendar-prevpreview-button');
hw.writeAttribute('role', 'button');
hw.writeAttribute('aria-haspopup', 'true');
hw.writeAttribute('id', 'prevPreview');
hw.writeTagRightChar();
hw.writeBeginTag('a');
hw.writeAttribute('class', wijCSS.icon + ' ' + wijCSS.uiIconGripDottedVertical);
hw.writeAttribute('href', '#');
hw.writeAttribute('title', o.prevPreviewTooltip);
hw.writeAttribute('aria-label', o.prevPreviewTooltip);
hw.writeAttribute('onclick', 'return false;');
hw.writeTagRightChar();
hw.write(' ');
hw.writeEndTag('a');
hw.writeEndTag('div');
}
hw.writeBeginTag('table');
hw.writeAttribute('id', this.id);
hw.writeAttribute('class', wijCSS.datepickerCalendar + ' wijmo-wijcalendar-table');
hw.writeAttribute('role', 'grid');
hw.writeAttribute('summary', this.calendar._getTitleText(this._startDateInMonth));
hw.writeAttribute('onselectstart', 'return false;');
hw.writeTagRightChar();
if(o.showWeekDays) {
hw.writeFullBeginTag('thead');
hw.writeBeginTag('tr');
hw.writeTagRightChar();
if(o.showWeekNumbers) {
hw.writeBeginTag('th');
hw.writeAttribute('id', this.id + '_ms');
hw.writeAttribute('class', wijCSS.uiDatepickerWeekCol + ' wijmo-wijcalendar-monthselector' + (!!o.selectionMode.month ? ' wijmo-wijcalendar-selectable' : ''));
hw.writeAttribute('role', 'columnheader');
hw.writeTagRightChar();
if(!!o.selectionMode.month && !previewMode) {
// && !o.disabledState && !o.disabled) { for 30863 issue
hw.writeBeginTag('a');
hw.writeAttribute('class', wijCSS.icon + ' ' + wijCSS.iconArrowRightDown);
hw.writeAttribute('style', 'display: block;');
hw.writeSelfClosingTagEnd();
} else {
hw.write(o.weekString ? o.weekString : "Wk");
}
hw.writeEndTag('th');
}
dayOfWeek = this._startDate.getDay();
weekStartDate = this._startDate;
for(i = 0; i < o.dayCols; i++) {
weekEnd = dayOfWeek === 6 || dayOfWeek === 0;
colIndex = i + ((o.showWeekNumbers) ? 1 : 0);
txt = this._getWeekDayText(dayOfWeek, o.weekDayFormat);
fullTxt = this._getWeekDayText(dayOfWeek, "full");
hw.writeBeginTag('th');
hw.writeAttribute('id', this.id + '_cs_' + colIndex);
hw.writeAttribute('class', wijCSS.datepickerWeekDay + (weekEnd ? ' ' + wijCSS.datepickerWeekEnd : '') + (!!o.selectionMode.weekDay ? ' wijmo-wijcalendar-selectable' : ''));
hw.writeAttribute('role', 'columnheader');
hw.writeTagRightChar();
hw.writeBeginTag('span');
hw.writeAttribute('title', fullTxt);
hw.writeAttribute('aria-label', fullTxt);
hw.writeTagRightChar();
hw.write(txt);
hw.writeEndTag('span');
hw.writeEndTag('th');
dayOfWeek = ((dayOfWeek + 1) % 7);
weekStartDate = wijDateOps.addDays(weekStartDate, 1);
}
hw.writeEndTag('tr');
hw.writeEndTag('thead');
}
hw.writeFullBeginTag('tbody');
date = this._startDate;
wnDate = this._startDateInMonth;
for(i = 0; i < o.dayRows; i++) {
hw.writeBeginTag('tr');
hw.writeTagRightChar();
if(o.showWeekNumbers) {
rowIndex = i + ((o.showWeekDays) ? 1 : 0);
hw.writeBeginTag('td');
hw.writeAttribute('id', this.id + '_rs_' + rowIndex);
hw.writeAttribute('class', wijCSS.uiDatepickerWeekCol + ' wijmo-wijcalendar-week-num' + (!!o.selectionMode.weekNumber ? ' wijmo-wijcalendar-selectable' : ''));
hw.writeAttribute('role', 'rowheader');
hw.writeTagRightChar();
weekNumber = wijDateOps.getWeekOfYear(wnDate, o.calendarWeekRule, this.culture.calendar.firstDay);
hw.write(weekNumber);
hw.writeEndTag('td');
wnDate = wijDateOps.addDays(wnDate, o.dayCols);
}
for(j = 0; j < o.dayCols; j++) {
this._fillDayCell(hw, date, previewMode);
date = wijDateOps.addDays(date, 1);
}
hw.writeEndTag('tr');
}
hw.writeEndTag('tbody');
hw.writeEndTag('table');
if(!tableOnly && !previewMode && this.showPreview) {
hw.writeBeginTag('div');
hw.writeAttribute('class', 'wijmo-wijcalendar-nextpreview-button');
hw.writeAttribute('role', 'button');
hw.writeAttribute('aria-haspopup', 'true');
hw.writeAttribute('id', 'nextPreview');
hw.writeTagRightChar();
hw.writeBeginTag('a');
hw.writeAttribute('class', wijCSS.icon + ' ' + wijCSS.uiIconGripDottedVertical);
hw.writeAttribute('href', '#');
hw.writeAttribute('title', o.nextPreviewTooltip);
hw.writeAttribute('aria-label', o.nextPreviewTooltip);
hw.writeAttribute('onclick', 'return false;');
hw.writeTagRightChar();
hw.write(' ');
hw.writeEndTag('a');
hw.writeEndTag('div');
}
return hw.toString();
};
return wijMonthView;
})();
calendar.wijMonthView = wijMonthView;
/** @ignore */
var wijDateCollection = (function () {
function wijDateCollection(calendar, optionName) {
this._calendar = calendar;
this._optionName = optionName ? optionName : 'selectedDates';
this._normalize();
}
wijDateCollection.prototype.getDates = function () {
if(this._calendar.options[this._optionName] === undefined) {
this._calendar.options[this._optionName] = [];
}
return this._calendar.options[this._optionName];
};
wijDateCollection.prototype.setDates = function (dates) {
this._calendar.options[this._optionName] = dates;
this._normalize();
};
wijDateCollection.prototype.getCount = function () {
return this.getDates().length;
};
wijDateCollection.prototype.clear = function () {
this.setDates([]);
};
wijDateCollection.prototype.add = function (date) {
this.addRange(date, date);
};
wijDateCollection.prototype.remove = function (date) {
this.removeRange(date, date);
};
wijDateCollection.prototype.indexOf = function (date) {
if(!this.getCount()) {
return -1;
}
return this._findRangeBound(date, true, false);
};
wijDateCollection.prototype.contains = function (date) {
return this.indexOf(date) !== -1;
};
wijDateCollection.prototype.removeRange = function (start, end) {
if(!this.getCount()) {
return;
}
var startIndex = this._findRangeBound(start, false, true), endIndex = this._findRangeBound(end, false, false), dates, startSlice, endSlice;
if(startIndex < 0 || endIndex < 0) {
return;
}
if(startIndex > endIndex) {
return;
}
dates = this.getDates();
if(dates[endIndex] > end) {
return;
}
startSlice = (!startIndex) ? [] : dates.slice(0, startIndex);
endSlice = endIndex >= (dates.length - 1) ? [] : dates.slice(endIndex + 1);
this.setDates(startSlice.concat(endSlice));
};
wijDateCollection.prototype.addRange = function (start, end) {
this.removeRange(start, end);
var dates = this.getDates(), insertIndex = this._findRangeBound(start, false, true), startSlice = (!insertIndex) ? [] : dates.slice(0, insertIndex), endSlice = dates.slice(insertIndex), midSlice = [], curDate;
start = wijDateOps.getDate(start);
end = wijDateOps.getDate(end);
for(curDate = start; curDate <= end; curDate = wijDateOps.addDays(curDate, 1)) {
midSlice[midSlice.length] = curDate;
}
this.setDates(startSlice.concat(midSlice.concat(endSlice)));
};
wijDateCollection.prototype._findRangeBound = function (date, exact, isStart) {
var dates = this.getDates(), low = 0, hi = dates.length, index;
while(low < hi) {
index = (low + hi) >> 1;
if(wijDateOps.isSameDate(date, dates[index])) {
return index;
}
if(date < dates[index]) {
hi = index;
} else {
low = index + 1;
}
}
if(exact) {
return -1;
}
return (isStart) ? low : hi;
};
wijDateCollection.prototype._parseDate = function (date) {
var strDate;
if(!date) {
date = new Date();
} else {
if(typeof date === 'string') {
strDate = date;
}
}
if(strDate) {
strDate = strDate.replace(/-/g, '/');
try {
date = new Date(strDate);
if(isNaN(date)) {
date = new Date();
}
} catch (e) {
date = new Date();
}
}
return date;
};
wijDateCollection.prototype._normalize = function () {
//Normalize the array
var dates = this._calendar.options[this._optionName], self = this, newDates;
if($.isArray(dates)) {
newDates = $.map(dates, function (d, i) {
return self._parseDate(d);
});
this._calendar.options[this._optionName] = newDates.sort(function (a, b) {
return a.getTime() - b.getTime();
});
}
};
return wijDateCollection;
})();
calendar.wijDateCollection = wijDateCollection;
/** @ignore */
var wijMyGrid = (function () {
function wijMyGrid(calendar) {
this.gridType = "month";
this.calendar = calendar;
if(calendar) {
this.culture = calendar._getCulture();
}
}
wijMyGrid.prototype.select = function (index, value) {
var date = this.calendar.getDisplayDate();
switch(this.gridType) {
case "month":
date.setMonth(value);
break;
case "year":
date.setFullYear(value);
break;
case "decade":
date.setFullYear(value);
break;
}
this.calendar.options.displayDate = date;
};
wijMyGrid.prototype.getSelectedIndex = function () {
var date = this.calendar.getDisplayDate(), year = date.getFullYear(), startYear = Math.floor(year / 10) * 10 - 1, startDecade = Math.floor(year / 100) * 100 - 10;
switch(this.gridType) {
case "month":
return date.getMonth();
case "year":
return year - startYear;
case "decade":
return Math.floor((year - startDecade) / 10);
}
return 0;
};
wijMyGrid.prototype.getTitle = function () {
var date = this.calendar.getDisplayDate(), year = date.getFullYear(), startYear = Math.floor(year / 10) * 10 - 1, startDecade = Math.floor(year / 100) * 100 - 10;
switch(this.gridType) {
case "month":
return year.toString();
case "year":
return (startYear + 1) + " - " + (startYear + 10);
case "decade":
return (startDecade + 10) + " - " + (startDecade + 109);
}
return '';
};
wijMyGrid.prototype.getHtml = function (date, tableOnly) {
if(date === undefined) {
date = this.calendar.getDisplayDate();
} else {
if(typeof (date) === 'boolean') {
tableOnly = date;
date = this.calendar.getDisplayDate();
}
}
tableOnly = !!tableOnly;
var o = this.calendar.options, rows = 3, cols = 4, hw = new htmlTextWriter(), wijCSS = o.wijCSS, height, year, startMonth, startYear, startDecade, ms, i, j, index, selected, outofRange, cellText, v, cls;
if(o.showTitle && !tableOnly) {
hw.write(this.calendar._getHeaderHtml(null, true, true));
}
height = 100 / rows + '%';
height = '30%';
hw.writeBeginTag('table');
hw.writeAttribute('class', wijCSS.datepickerCalendar + ' wijmo-wijcalendar-mygrid');
hw.writeAttribute('role', 'grid');
hw.writeAttribute('onselectstart', 'return false;');
hw.writeTagRightChar();
year = date.getFullYear();
startMonth = date.getFullYear() * 12;
startYear = Math.floor(year / 10) * 10 - 1;
startDecade = Math.floor(year / 100) * 100 - 10;
ms = this.culture.calendar.months;
for(i = 0; i < rows; i++) {
hw.writeBeginTag('tr');
hw.writeAttribute('height', height);
hw.writeTagRightChar();
for(j = 0; j < cols; j++) {
index = i * 4 + j;
selected = false;
outofRange = false;
cellText = '';
v = null;
switch(this.gridType) {
case "month":
if(date.getMonth() === index) {
selected = true;
}
v = index;
cellText = ms.namesAbbr[index];
outofRange = ((startMonth + index) < (o.minDate.getFullYear() * 12 + o.minDate.getMonth())) || ((startMonth + index) > (o.maxDate.getFullYear() * 12 + o.maxDate.getMonth()));
break;
case "year":
if(index === 0 || index === 11) {
outofRange = true;
}
v = startYear + index;
if(v < o.minDate.getFullYear() || v > o.maxDate.getFullYear()) {
outofRange = true;
} else {
selected = (year === v);
}
cellText = v.toString();
break;
case "decade":
if(index === 0 || index === 11) {
outofRange = true;
}
v = startDecade + index * 10;
if(v + 10 < o.minDate.getFullYear() || v > o.maxDate.getFullYear()) {
outofRange = true;
} else {
selected = (year >= v && year < (v + 10));
}
cellText = v.toString() + '-<br/>' + (v + 9).toString();
break;
}
cls = wijCSS.datepickerWeekDay;
if(outofRange) {
cls = cls + ' ' + wijCSS.datepickerOtherMonth + ' ' + wijCSS.prioritySecondary + ' ' + wijCSS.datepickerUnselectable;
} else {
if(!o.disabledState && !o.disabled) {
cls += " wijmo-wijcalendar-day-selectable";
}
}
cls += " " + wijCSS.stateDefault + (outofRange ? ' ' + wijCSS.stateDisabled : '') + (selected ? ' ' + wijCSS.stateActive + ' ' + wijCSS.stateHighlight : '');
hw.writeBeginTag('td');
hw.writeAttribute('class', cls);
hw.writeAttribute('role', 'gridcell');
//hw.writeAttribute('width', width);
hw.writeAttribute('index', index.toString());
hw.writeAttribute('value', v.toString());
hw.writeAttribute('other', outofRange.toString());
hw.writeTagRightChar();
hw.writeBeginTag('a');
hw.writeAttribute('href', '#');
hw.writeTagRightChar();
hw.write(cellText);
hw.writeEndTag('a');
hw.writeEndTag('td');
}
hw.writeEndTag('tr');
}
hw.writeEndTag('table');
return hw.toString();
};
return wijMyGrid;
})();
calendar.wijMyGrid = wijMyGrid;
})(wijmo.calendar || (wijmo.calendar = {}));
var calendar = wijmo.calendar;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/*globals jQuery,$*/
/*jslint white: false */
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.wijmo.wijutil.js
* jquery.wijmo.wijexpander.js
* Non-default animations requires UI Effects Core
*
*/
(function (expander) {
"use strict";
var $ = jQuery, widgetName = "wijexpander";
/** @widget */
var wijexpander = (function (_super) {
__extends(wijexpander, _super);
function wijexpander() {
_super.apply(this, arguments);
}
wijexpander.prototype._setOption = // handle option changes:
function (key, value) {
switch(key) {
case "contentUrl":
if(value) {
this.element.find("> ." + this.options.wijCSS.content).wijContent(value);
} else {
this.element.find("> ." + this.options.wijCSS.content).html("");
}
break;
case "disabled":
if(value) {
this.element.addClass(this.options.wijCSS.stateDisabled).find("> .ui-expander-header").addClass(this.options.wijCSS.stateDisabled);
this.element.find("> ." + this.options.wijCSS.content).addClass(this.options.wijCSS.stateDisabled);
} else {
this.element.removeClass(this.options.wijCSS.stateDisabled).find("> .ui-expander-header").removeClass(this.options.wijCSS.stateDisabled);
this.element.find("> ." + this.options.wijCSS.content).removeClass(this.options.wijCSS.stateDisabled);
}
break;
case "expandDirection":
this._onDirectionChange(value, true, this.options.expandDirection);
break;
case "expanded":
if(value) {
this.expand();
} else {
this.collapse();
}
// option value already stored inside expand/collapse method
// if action is not cancelled, so we need return here.
return;
default:
break;
}
$.wijmo.widget.prototype._setOption.apply(this, arguments);
};
wijexpander.prototype._create = function () {
var o = this.options, elems = this.element.children(), header, content;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
// do not call base c1headercontentcontrol _create method here since we don't
// want to place c1headercontentcontrol classes on the widget element
this.element.addClass("wijmo-wijexpander ui-expander " + o.wijCSS.widget + " ui-expander-icons");
header = $(elems[0]);
content = $(elems[1]);
if(o.expandDirection === "left" || o.expandDirection === "top") {
header.remove();
header.insertAfter(content);
}
header.addClass("ui-expander-header");
// ARIA
header.attr("role", "tab");
content.attr("role", "tabpanel");
if(header.find("> a").length === 0) {
// fix for 32089:
header.wrapInner('<a href="javascript:void(null)"></a>');
//header.wrapInner('<a href="#"></a>');
}
if(header.find("> .ui-icon").length === 0) {
$('<span class="ui-icon"></span>').insertBefore($("> a", header)[0]);
}
content.addClass("ui-expander-content " + o.wijCSS.content);
};
wijexpander.prototype._init = // widget initialization:
function () {
var o = this.options;
this._onDirectionChange(o.expandDirection, false);
if(o.contentUrl) {
$("." + o.wijCSS.content, this.element).wijContent(this.options.contentUrl);
}
if(!o.expanded) {
this.element.find("> .ui-expander-content").hide();
this.element.find("> .ui-expander-header").addClass(o.wijCSS.stateDefault + " " + o.wijCSS.cornerAll).attr({
"aria-expanded": "false",
tabIndex: -1
}).find("> .ui-icon").addClass(this._triangleIconClosed);
} else {
this.element.find("> .ui-expander-header").addClass(o.wijCSS.stateActive).attr({
"aria-expanded": "true",
tabIndex: 0
}).addClass(this._headerCornerOpened).find("> .ui-icon").addClass(this._triangleIconOpened);
this.element.find("> .ui-expander-content").addClass("ui-expander-content-active").addClass(this._contentCornerOpened).wijTriggerVisibility();
}
if(o.disabled) {
this.element.addClass(o.wijCSS.stateDisabled).find("> .ui-expander-header").addClass(o.wijCSS.stateDisabled);
this.element.find("> .ui-expander-content").addClass(o.wijCSS.stateDisabled);
}
this._bindLiveEvents();
};
wijexpander.prototype.destroy = /**
* Removes the wijexpander functionality completely. This returns the element to its pre-init state.
*/
function () {
var o = this.options;
this._unbindLiveEvents();
this.element.removeClass("wijmo-wijexpander ui-expander " + o.wijCSS.widget + " ui-helper-reset ui-expander-icons");
//.removeData('wijexpander');
$.wijmo.widget.prototype.destroy.apply(this, arguments);
};
wijexpander.prototype._bindLiveEvents = function () {
var o = this.options;
//"on" was introduced to JQuery in v1.7, Nov 2011. It is not yet in JQuery Mobile!.
this.element.on("click.wijexpander", ">.ui-expander-header", jQuery.proxy(this._onHeaderClick, this));
this.element.on("mouseenter.wijexpander", ".ui-expander-header", function () {
$(this).addClass(o.wijCSS.stateHover);
});
this.element.on("mouseleave.wijexpander", ".ui-expander-header", function () {
$(this).removeClass(o.wijCSS.stateHover);
});
this.element.on("focus.wijexpander", ".ui-expander-header", function () {
$(this).addClass(o.wijCSS.stateFocus);
});
this.element.on("blur.wijexpander", ".ui-expander-header", function () {
$(this).removeClass(o.wijCSS.stateFocus);
});
};
wijexpander.prototype._unbindLiveEvents = function () {
this.element.off(".wijexpander", ".ui-expander-header");
};
wijexpander.prototype._onDirectionChange = function (newDirection, allowDOMChange, prevDirection) {
if (typeof prevDirection === "undefined") { prevDirection = null; }
var rightToLeft, openedHeaders, openedContents, openedTriangles, closedTriangles, prevIsRightToLeft, content, header;
var o = this.options;
if(prevDirection && prevDirection !== newDirection) {
this.element.removeClass("ui-expander-" + prevDirection);
}
if(allowDOMChange) {
openedHeaders = this.element.find(".ui-expander-header." + this._headerCornerOpened);
openedHeaders.removeClass(this._headerCornerOpened);
openedContents = this.element.find(".ui-expander-content" + "." + this._contentCornerOpened);
openedContents.removeClass(this._contentCornerOpened);
openedTriangles = this.element.find("." + this._triangleIconOpened);
closedTriangles = this.element.find("." + this._triangleIconClosed);
openedTriangles.removeClass(this._triangleIconOpened);
closedTriangles.removeClass(this._triangleIconClosed);
}
switch(newDirection) {
case "top":
this._headerCornerOpened = "ui-corner-bottom";
this._contentCornerOpened = "ui-corner-top";
this._triangleIconOpened = o.wijCSS.iconArrowUp;
this._triangleIconClosed = o.wijCSS.iconArrowRight;
rightToLeft = true;
this.element.removeClass("ui-helper-horizontal");
this.element.addClass("ui-expander-top");
break;
case "right":
this._headerCornerOpened = "ui-corner-left";
this._contentCornerOpened = "ui-corner-right";
this._triangleIconOpened = o.wijCSS.iconArrowRight;
this._triangleIconClosed = o.wijCSS.iconArrowDown;
rightToLeft = false;
this.element.addClass("ui-helper-horizontal");
this.element.addClass("ui-expander-right");
break;
case "left":
this._headerCornerOpened = "ui-corner-right";
this._contentCornerOpened = "ui-corner-left";
this._triangleIconOpened = o.wijCSS.iconArrowLeft;
this._triangleIconClosed = o.wijCSS.iconArrowDown;
rightToLeft = true;
this.element.addClass("ui-helper-horizontal");
this.element.addClass("ui-expander-left");
break;
default:
//case "bottom":
this._headerCornerOpened = "ui-corner-top";
this._contentCornerOpened = "ui-corner-bottom";
this._triangleIconOpened = o.wijCSS.iconArrowDown;
this._triangleIconClosed = o.wijCSS.iconArrowRight;
rightToLeft = false;
this.element.removeClass("ui-helper-horizontal");
this.element.addClass("ui-expander-bottom");
break;
}
prevIsRightToLeft = this.element.data("rightToLeft");
this.element.data("rightToLeft", rightToLeft);
if(allowDOMChange) {
openedTriangles.addClass(this._triangleIconOpened);
closedTriangles.addClass(this._triangleIconClosed);
openedHeaders.addClass(this._headerCornerOpened);
openedContents.addClass(this._contentCornerOpened);
}
if(allowDOMChange && rightToLeft !== prevIsRightToLeft) {
this.element.children(".ui-expander-header").each(function (index, element) {
header = $(this);
if(rightToLeft) {
content = header.next(".ui-expander-content");
header.remove();
header.insertAfter(content);
} else {
content = header.prev(".ui-expander-content");
header.remove();
header.insertBefore(content);
}
});
}
};
wijexpander.prototype.collapse = // public methods
/**
* Collapses the content panel.
*/
function () {
var o = this.options, animOptions, animations, duration, easing;
if(!o.allowExpand) {
return;
}
if(this.element.hasClass(o.wijCSS.stateDisabled)) {
return false;
}
if(!this._trigger("beforeCollapse")) {
return false;
}
/*
newEv = jQuery.Event("beforecollapse");
this.element.trigger(newEv);
if (newEv.isDefaultPrevented()) {
return false;
}*/
if(o.animated) {
animOptions = {
expand: false,
content: this.element.find("> .ui-expander-content"),
complete: jQuery.proxy(function () {
this.element.find("> .ui-expander-content").removeClass("ui-expander-content-active");
this._trigger("afterCollapse");
this.element.find("> .ui-expander-content").css('display', '');
}, this),
horizontal: this.element.hasClass("ui-helper-horizontal")
};
animations = $.wijmo.wijexpander.animations;
duration = o.duration;
easing = o.animated;
if(easing && !animations[easing] && !$.easing[easing]) {
easing = 'slide';
}
if(!animations[easing]) {
animations[easing] = function (options) {
this.slide(options, {
easing: easing,
duration: duration || 700
});
};
}
animations[easing](animOptions);
} else {
this.element.find("> .ui-expander-content").hide();
this._trigger("afterCollapse");
}
this.element.find("> .ui-expander-header").removeClass(o.wijCSS.stateActive).removeClass(this._headerCornerOpened).attr({
"aria-expanded": "false",
tabIndex: -1
}).addClass(o.wijCSS.stateDefault + " " + o.wijCSS.cornerAll).find("> .ui-icon").removeClass(this._triangleIconOpened).addClass(this._triangleIconClosed);
this.options.expanded = false;
return true;
};
wijexpander.prototype.expand = /**
* Expands the content panel.
*/
function () {
var o = this.options, animOptions, animations, duration, easing;
if(!o.allowExpand) {
return;
}
if(this.element.hasClass(o.wijCSS.stateDisabled)) {
return false;
}
if(!this._trigger("beforeExpand")) {
return false;
}
//this.element.addClass("ui-state-expanded");
if(o.animated) {
//console.log("$.easing=" + $.easing + "," + $.effects[easing] + ",easing=" + easing);
animOptions = {
expand: true,
content: this.element.find("> .ui-expander-content"),
complete: jQuery.proxy(function () {
this.element.find("> .ui-expander-content").addClass("ui-expander-content-active").addClass(this._contentCornerOpened).wijTriggerVisibility();
this._trigger("afterExpand");
this.element.find("> .ui-expander-content").css('display', '');
}, this),
horizontal: this.element.hasClass("ui-helper-horizontal")
};
animations = $.wijmo.wijexpander.animations;
duration = o.duration;
easing = o.animated;
if(easing && !animations[easing] && !$.easing[easing]) {
easing = 'slide';
}
if(!animations[easing]) {
animations[easing] = function (options) {
this.slide(options, {
easing: easing,
duration: duration || 700
});
};
}
animations[easing](animOptions);
} else {
this.element.find("> .ui-expander-content").show();
this._trigger("afterExpand");
}
this.element.find("> .ui-expander-header").removeClass(o.wijCSS.stateDefault + " " + o.wijCSS.cornerAll).addClass(o.wijCSS.stateActive).addClass(this._headerCornerOpened).attr({
"aria-expanded": "true",
tabIndex: 0
}).find("> .ui-icon").removeClass(this._triangleIconClosed).addClass(this._triangleIconOpened);
this.options.expanded = true;
return true;
};
wijexpander.prototype._onHeaderClick = /** Private methods */
function (e) {
this.option("expanded", !this.options.expanded);
// commented in order to fix issue 32089:
//return false; // fix for 32089
};
return wijexpander;
})(wijmo.wijmoWidget);
expander.wijexpander = wijexpander;
var wijexpander_options = (function () {
function wijexpander_options() {
/** wijMobileCSS.
* @ignore
*/
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-content ui-body ui-body-c"
};
/** Selector option for auto self initialization.
* This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijexpander')";
/** Determines if the widget can be collapsed or expanded through user interaction.Set this option to false to disable collapsing and expanding in the widget.
* @example $("#element").wijexpander({ allowExpand: false });
*/
this.allowExpand = true;
/** Determines the animation easing effect; set this option to false in order to disable animation.
* Note that custom easing effects require the UI Effects Core. Additional options
* that are available for the animation function include:
* expand - value of true indicates that content element must be expanded.
* horizontal - value of true indicates that expander is horizontally
* orientated (when expandDirection is left or right).
* content - jQuery object that contains content element to be expanded or
* collapsed.
* @example
* $("#expander2").wijexpander({
* animated: "custom1"
* });
* jQuery.wijmo.wijexpander.animations.custom1 = function (options) {
* this.slide(options, {
* easing: "easeInBounce",
* duration: 900
* });
* }
*/
this.animated = 'slide';
/** Determines the URL to the external content. For example,
* http://componentone.com/ for the ComponentOne Web site.
* @example
* $("#element").wijexpander({ contentUrl: "http://componentone.com/" });
*/
this.contentUrl = "";
/** Determines the visibility state of the content panel. If true, the
* content element is visible.
* @example $("#element").wijexpander({ expanded: false });
*/
this.expanded = true;
/** Determines the content expand direction. Available values are top, right, bottom, and left.
* @example $("#element").wijexpander({ expandDirection: "right" });
*/
this.expandDirection = "bottom";
/** Occurs before the content area collapses.
* Return false or call event.preventDefault() in order to cancel event and
* prevent the content area from collapsing.
* @event
*/
this.beforeCollapse = null;
/** Occurs before the content area expands.
* Return false or call event.preventDefault() in order to cancel event and
* prevent the content area from expanding.
* @event
*/
this.beforeExpand = null;
/** Occurs after the content area collapses.
* @event
*/
this.afterCollapse = null;
/** Occurs after the content area expands.
* @event
*/
this.afterExpand = null;
}
return wijexpander_options;
})();
wijexpander.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijexpander_options());
$.wijmo.registerWidget(widgetName, wijexpander.prototype);
$.extend($.wijmo.wijexpander, {
animations: {
slide: function (options, additions) {
var animOpts;
options = $.extend({
easing: "swing",
duration: 300
}, options, additions);
if(options.expand) {
if(options.horizontal) {
animOpts = {
width: 'show',
opacity: 'show'
};
} else {
animOpts = {
height: 'show',
opacity: 'show'
};
}
options.content.stop(true, true).animate(animOpts, options);
} else {
if(options.horizontal) {
animOpts = {
width: 'hide',
opacity: 'hide'
};
} else {
animOpts = {
height: 'hide',
opacity: 'hide'
};
}
options.content.stop(true, true).animate(animOpts, options);
}
}
}
});
})(wijmo.expander || (wijmo.expander = {}));
var expander = wijmo.expander;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../external/declarations/globalize.d.ts"/>
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/// <reference path="../wijsuperpanel/jquery.wijmo.wijsuperpanel.ts" />
/*globals window,document,jQuery,clearTimeout,setTimeout*/
/*
* Depends:
* jquery.js
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.wijmo.wijutil.js
* jquery.ui.position.js
* jquery.ui.effects.core.js
* jquery.mousewheel.js
* jquery.bgiframe.js
* jquery.wijmo.wijsuperpanel.js
*
*/
(function (menu) {
"use strict";
var $ = jQuery, widgetName = "wijmenu";
/** @widget*/
var wijmenu = (function (_super) {
__extends(wijmenu, _super);
function wijmenu() {
_super.apply(this, arguments);
}
wijmenu._itemWidgetName = "wijmenuitem";
wijmenu.prototype._preventEvent = function (event) {
event.preventDefault();
event.stopImmediatePropagation();
};
wijmenu.prototype._initState = function () {
var self = this;
if(!self.options.items) {
self.options.items = [];
}
};
wijmenu.prototype._create = function () {
// Before crete menu items,hide the menu. To avoid show wild uls
// in the page before init the menu.
var self = this, o = self.options, direction = o.direction, mode = o.mode, parentWidget, ele = self.element, sublist, keycode, disabled = o.disabled;
if($.mobile != null) {
keycode = $.mobile.keyCode;
} else {
keycode = $.ui.keyCode;
}
self._initState();
if(ele.is(":hidden") && ele.wijAddVisibilityObserver) {
ele.wijAddVisibilityObserver(function () {
self.refresh();
if(ele.wijRemoveVisibilityObserver) {
ele.wijRemoveVisibilityObserver();
}
}, "wijmenu");
}
//Fix for jQuery UI 1.10
ele.data("wijmomenu", $.camelCase(self.widgetFullName));
//ele.data("wijmomenu", self.widgetName);
//fix for issus 20651 by Chandler.Zheng on 2012/03/19
self.clickNameSpace = "click.wijmenudoc" + self._newId();
//end comment
ele.hide();
self.cssPre = "wijmo-wijmenu";
self.nowIndex = 9999;
self.activeItem = null;
self.refresh();
ele.attr("tabIndex", 0);
//Add for support disabled option at 2011/7/8
if(self._getDisabled()) {
self.disable();
if(o.disabledState === true) {
o.disabled = disabled;
}
}
//end for disabled option
ele.bind("keydown.wijmenuEvent", function (event) {
if(self._getDisabled()) {
return;
}
if(mode === "sliding") {
self._getSublist().stop(true, true);
}
var activeItem = self.activeItem, isRoot, link, orientation = o.orientation;
if(activeItem) {
isRoot = activeItem._isRoot();
sublist = activeItem._getSublist();
} else {
isRoot = true;
}
switch(event.keyCode) {
case keycode.PAGE_UP:
self.previousPage(event);
self._preventEvent(event);
break;
case keycode.PAGE_DOWN:
self.nextPage(event);
self._preventEvent(event);
break;
case keycode.UP:
if(orientation === "vertical" || mode === "sliding" || !isRoot) {
self.previous(event);
self._preventEvent(event);
}
break;
case keycode.DOWN:
if(orientation === "vertical" || mode === "sliding" || !isRoot) {
self.next(event);
self._preventEvent(event);
} else {
if(activeItem) {
if(mode === "flyout" && wijmenu._hasVisibleSubMenus(activeItem)) {
if(sublist.is(":hidden")) {
activeItem._showFlyoutSubmenu(event, function () {
self.activate(event, activeItem._getFirstSelectableSubItem());
});
}
}
}
}
break;
case keycode.RIGHT:
if(orientation === "horizontal" && isRoot && mode === "flyout") {
if(direction === "rtl") {
self.previous(event);
} else {
self.next(event);
}
self._preventEvent(event);
} else {
if(activeItem) {
parentWidget = activeItem.getParent();
if(direction === "rtl") {
self._keyDownToCloseSubmenu(mode, event, parentWidget);
} else {
self._keyDownToOpenSubmenu(activeItem, mode, event, sublist);
}
}
}
break;
case keycode.LEFT:
if(orientation === "horizontal" && isRoot && mode === "flyout") {
if(direction === "rtl") {
self.next(event);
} else {
self.previous(event);
}
self._preventEvent(event);
} else {
if(activeItem) {
parentWidget = activeItem.getParent();
}
if(direction === "rtl") {
self._keyDownToOpenSubmenu(activeItem, mode, event, sublist);
} else {
self._keyDownToCloseSubmenu(mode, event, parentWidget);
}
}
break;
case keycode.ENTER:
if(!activeItem) {
return;
}
link = activeItem._getLink();
if(mode === "flyout") {
break;
} else {
self.select();
if(link.is("a") && link.attr("href") === "#") {
self._preventEvent(event);
}
}
break;
case keycode.TAB:
self.next(event);
self._preventEvent(event);
break;
}
});
};
wijmenu.prototype._keyDownToOpenSubmenu = function (activeItem, mode, event, sublist) {
var self = this;
if(mode === "flyout" && wijmenu._hasVisibleSubMenus(activeItem)) {
if(sublist.is(":hidden")) {
activeItem._showFlyoutSubmenu(event, function () {
self.activate(event, activeItem._getFirstSelectableSubItem());
});
}
} else if(mode === "sliding") {
if(sublist.length > 0) {
activeItem._getLink().trigger("click", activeItem._getFirstSelectableSubItem());
}
}
};
wijmenu.prototype._keyDownToCloseSubmenu = function (mode, event, parentWidget) {
var self = this, o = self.options, breadcrumb;
if(mode === "flyout") {
if(parentWidget) {
parentWidget._hideCurrentSubmenu(event);
self.activate(event, parentWidget);
}
} else {
if(o.backLink && self._backLink && self._backLink.is(":visible")) {
self._backLink.trigger("click", function () {
if(parentWidget) {
self.activate(event, parentWidget);
}
});
}
breadcrumb = $("." + o.wijCSS.wijmenuBreadcrumb, self.domObject.menucontainer).find("li a");
if(breadcrumb.length > 0) {
breadcrumb.eq(breadcrumb.length - 2).trigger("click", function () {
if(parentWidget) {
self.activate(event, parentWidget);
}
});
}
}
};
wijmenu.prototype._createMenuItems = function () {
var self = this, items = [], o = self.options, optionItemsLength = self.options.items.length, childMenuCount = self._getSublist().children('li').length, i, w, itemContainer;
for(i = 0; i < optionItemsLength - childMenuCount; i++) {
self._getSublist().append('<li>');
}
if(o.ensureSubmenuOnBody && o.mode === "flyout") {
self._submenuContainer = $("<div>").addClass(o.wijCSS.helperReset).addClass(o.wijCSS.widget).addClass(o.wijCSS.header).addClass(o.wijCSS.wijmenu).addClass(o.wijCSS.wijmenuSubmenuContainer);
if(o.orientation === "horizontal" && o.mode === "flyout") {
self._submenuContainer.addClass(o.wijCSS.wijmenuHorizontal);
}
itemContainer = $("<ul>").addClass(o.wijCSS.wijmenuList).addClass(o.wijCSS.helperReset).data($.camelCase(self.widgetFullName), self).data("wijmomenu", $.camelCase(self.widgetFullName));
}
$(">li", self._getSublist()).each(function (i, n) {
var $li = $(this), options = wijmenu._getMenuItemOptions(self.options, i), sublistWrapper, sublist;
w = self._createItemWidget($li, options);
items.push(w);
self.options.items[i] = w.options;
if(o.ensureSubmenuOnBody && o.mode === "flyout") {
sublist = w._getSublist();
self._bindMousehoverEvent(sublist);
if(sublist.children().length > 0) {
sublistWrapper = $("<li>").addClass(o.wijCSS.widget).addClass(o.wijCSS.wijmenuItem).addClass(o.wijCSS.stateDefault).addClass(o.wijCSS.cornerAll).addClass(o.wijCSS.wijmenuParent).addClass(o.wijCSS.header).append(sublist);
$(sublistWrapper).appendTo(itemContainer);
}
}
if(o.ensureSubmenuOnBody && o.mode === "flyout") {
$(self._submenuContainer).append(itemContainer).appendTo("body");
}
return this;
});
return items;
};
wijmenu.prototype._createItemWidget = function ($li, options) {
//var itemWidgetName = $.wijmo.wijmenu._itemWidgetName;
var itemWidgetName = wijmenu._itemWidgetName;
if($.fn[itemWidgetName]) {
$li[itemWidgetName](options);
}
return wijmenu._getItemWidget($li);
};
wijmenu.prototype._handleDisabledOption = function (disabled, ele) {
var self = this;
if(disabled) {
if(!self.disabledDiv) {
self.disabledDiv = self._createDisabledDiv(ele);
}
//fix for tfs issue 21458
//self.disabledDiv.appendTo("body");
self.disabledDiv.appendTo(self.domObject.menucontainer);
} else {
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
}
};
wijmenu.prototype._getDisabled = function () {
var self = this, o = self.options;
return o.disabledState === true || o.disabled === true;
};
wijmenu.prototype._createDisabledDiv = function (outerEle) {
return $("<div></div>").css({
"z-index": "99999",
position: "absolute",
width: "100%",
height: "100%",
left: 0,
top: 0
});
};
wijmenu.prototype._innerDestroy = function () {
var self = this, o = self.options;
self.destroying = true;
self[o.mode === "flyout" ? "_killFlyout" : "_killDrilldown"]();
self._killMenuItems();
self._killtrigger();
self._killElement();
if(o.ensureSubmenuOnBody && o.mode === "flyout" && self._submenuContainer) {
self._submenuContainer.remove();
}
self.destroying = false;
};
wijmenu.prototype.destroy = /** The destroy method removes the wijmenu functionality completely
* and returns the element to its pre-init state.
*/
function () {
var self = this;
this._innerDestroy();
//Add for support disabled option at 2011/7/8
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
//end for disabled option
_super.prototype.destroy.call(this);
};
wijmenu.prototype.activate = /** This method activates a menu item by deactivating the current item,
* scrolling the new item into view, and, if necessary,making it the active item,
* and triggering a focus event.
* @param {event} event The javascript event.
* @param item A menu item to activate.
* @example
* //Actives a menu item with "sub-item" class.
* $(".selector").wijmenu("activate", null, $(".sub-item"));
*/
function (event, item) {
if(!item) {
return;
}
var self = this, o = self.options, scrollContainer = self.domObject.scrollcontainer, active, link, needToScroll = false, isInCurrentSublist = true;
active = (item.jquery ? item : item.element).eq(0);
if(self.activeItem && self.activeItem.element.get(0) === active.get(0)) {
return;
}
self.deactivate(event);
self.activeItem = wijmenu._getItemWidget(active);
link = active.children(":first");
self._trigger("focus", event, {
item: self.activeItem
});
if(self.options.mode === "sliding") {
isInCurrentSublist = active.parent().is('.' + o.wijCSS.wijmenuCurrent);
needToScroll = isInCurrentSublist && self._hasScroll() && scrollContainer.wijsuperpanel('needToScroll', active);
if(needToScroll) {
self._linkContainer.link = link;
self._linkContainer.needToFocus = true;
scrollContainer.wijsuperpanel("scrollChildIntoView", active);
}
}
link.addClass(o.wijCSS.stateFocus).end();
self.element.removeAttr("aria-activedescendant");
self.element.attr("aria-activedescendant", active.attr("id"));
//fix for issue 20547
if(isInCurrentSublist && !needToScroll && link.is('a')) {
link.focus();
}
};
wijmenu.prototype.deactivate = /** The deactivate method clears the current selection.
* This method is useful when reopening a menu which previously had an item selected.
* @param {event} event The javascript event.
*/
function (event) {
var self = this, o = self.options, active = self.activeItem;
if(!active) {
return;
}
//Fix an issue that the class can't be removed sometimes when
//playing animation in FF/Webkit.
setTimeout(function () {
active._getLink().removeClass(o.wijCSS.stateFocus).removeAttr("id");
self._trigger("blur");
}, 0);
self.activeItem = null;
};
wijmenu.prototype.next = /** The next method gets the next selectable item.
* The first item is selected if none is active or the last one is active.
* It returns null if none is selectable in next.
* @param {event} event The javascript event.
*/
function (event) {
this._move("next", function (widget) {
return widget._getFirstSelectableSubItem();
}, event);
};
wijmenu.prototype.previous = /** Get the previous selectable item.
* It selects the last item if none is active or the first one is active.
* It returns null if no previous item is selectable.
* @param {event} event The javascript event.
*/
function (event) {
this._move("previous", function (widget) {
return widget._getLastSelectableSubItem();
}, event);
};
wijmenu.prototype.first = /** The first method defines the first menu item as the active item. */
function () {
var self = this, active, parent, firstItem;
if(!self.activeItem) {
return false;
}
active = self._getActiveItemElement();
parent = self.activeItem._getParentOrMenu();
firstItem = parent._getFirstSelectableSubItem();
return firstItem && active[0] === firstItem.element[0];
};
wijmenu.prototype.last = /** The last method defines the last menu item as the active item. */
function () {
var self = this, active, parent, lastItem;
if(!self.activeItem) {
return false;
}
active = self._getActiveItemElement();
parent = self.activeItem._getParentOrMenu();
lastItem = parent._getLastSelectableSubItem();
return lastItem && active[0] === lastItem.element[0];
};
wijmenu.prototype.nextPage = /** This method is similar to the "next" method,
* but it jumps a whole page to the next page instead of to the next selectable item.
* @param {event} event The javascript event.
*/
function (event) {
var self = this, activeItem = self._getActiveItemElement(), base, height, result, widget, itemToActivate;
if(activeItem) {
widget = self.activeItem._getParentOrMenu();
} else {
widget = self;
activeItem = self._getFirstSelectableSubItem();
}
if(self.options.mode === "sliding" && self._hasScroll()) {
if(!activeItem || self.last()) {
self.activate(event, widget._getFirstSelectableSubItem());
return;
}
base = activeItem.offset().top;
height = self.options.maxHeight;
result = wijmenu._getSelectableSubItems(widget, function (n) {
var node = $(n.element), close = height - (node.offset().top - base + node.height()), lineheight = node.height();
return close < lineheight && close > -lineheight;
});
if(!result.length) {
result = widget._getLastSelectableSubItem();
} else {
//get the last of the result;
result = result[result.length - 1];
}
self.activate(event, result);
} else {
if(!activeItem || self.last()) {
itemToActivate = widget._getFirstSelectableSubItem();
} else {
itemToActivate = widget._getLastSelectableSubItem();
}
self.activate(event, itemToActivate);
}
};
wijmenu.prototype.previousPage = /** This method is similar to the "previous" method,
* but it jumps a whole page to the previous page.
* @param {event} event The javascript event.
*/
function (event) {
var self = this, activeItem = self._getActiveItemElement(), base, height, result, widget, itemToActivate;
if(activeItem) {
widget = self.activeItem._getParentOrMenu();
} else {
widget = self;
activeItem = self._getFirstSelectableSubItem();
}
if(self.options.mode === "sliding" && self._hasScroll()) {
if(!activeItem || self.first()) {
self.activate(event, widget._getLastSelectableSubItem());
return;
}
base = activeItem.offset().top;
height = self.options.maxHeight;
result = wijmenu._getSelectableSubItems(widget, function (n) {
var node = $(n.element), close = node.offset().top - base + height - node.height(), lineheight = node.height();
return close < lineheight && close > -lineheight;
});
if(!result.length) {
result = widget._getFirstSelectableSubItem();
} else {
//get the first of the result;
result = result[0];
}
self.activate(event, result);
} else {
if(!activeItem || self.first()) {
itemToActivate = widget._getLastSelectableSubItem();
} else {
itemToActivate = widget._getFirstSelectableSubItem();
}
self.activate(event, itemToActivate);
}
};
wijmenu.prototype.select = /** Selects the active item,triggering the selected event for that
* item. This event is useful for custom keyboard handling.
* @param {event} event The javascript event.
*/
function (event) {
var self = this, activeItem = self.activeItem, selected;
self._trigger("select", event, {
item: activeItem
});
//if the checkable is true, toggle the selected value of menuitem
if(self.options.checkable) {
selected = !activeItem.options.selected;
activeItem._setOption("selected", selected);
}
};
wijmenu.prototype._getActiveItemElement = function () {
return this.activeItem ? this.activeItem.element : null;
};
wijmenu.prototype.setItemDisabled = /** The setItemDisabled method allows the user to disable a specific menu item.
* @param selector jQuery selector, indicates the item to be disabled.
* @param {boolean} disabled If the value is true, the item is disabled; Otherwise, the item is enabled.
* @example
* //Disables a menuitem with "sub-item" class.
* $(".selector").wijmenu("setItemDisabled", $(".sub-item"), true);
*/
function (selector, disabled) {
var items = $(selector, this.element), o = this.options;
items.find("." + o.wijCSS.wijmenuItem + ">a").attr("disabled", disabled);
items.find(">a").toggleClass(o.wijCSS.stateDisabled, disabled);
};
wijmenu.prototype._setOption = ///set options
function (key, value) {
var self = this;
if(self.destroying) {
return;
}
if(self["_set_" + key]) {
self["_set_" + key](value);
}
self.options[key] = value;
//Add for support disabled option at 2011/7/8
if(key === "disabled") {
self._handleDisabledOption(value, self.domObject.menucontainer);
}
//end for disabled option
};
wijmenu.prototype._set_items = function (value) {
var self = this;
//when set items by options, clear the old items at first
self._getSublist().children().remove();
self.options.items = value;
self.refresh();
};
wijmenu.prototype._set_mode = function (value) {
var self = this;
self._innerDestroy();
self.options.mode = value;
self.refresh();
};
wijmenu.prototype._set_backLink = function (value) {
var self = this, o = self.options, breadcrumb;
this.options.backLink = value;
if(self.options.mode === 'sliding') {
self._killDrilldown();
self._drilldown();
breadcrumb = $("." + o.wijCSS.wijmenuBreadcrumb, self.domObject.menucontainer);
self._resetDrilldownMenu(breadcrumb);
}
};
wijmenu.prototype._set_direction = function (value) {
var self = this;
self._innerDestroy();
self.refresh();
};
wijmenu.prototype._set_orientation = function (value) {
var self = this, menuContainer = self.domObject.menucontainer, direction = self.options.direction, cssPre = "ui-icon-triangle-1-", directionClass = direction === "rtl" ? "w" : "e", oldCss = value === "horizontal" ? directionClass : "s", newCss = value === "horizontal" ? "s" : directionClass;
menuContainer.removeClass(self.cssPre + "-vertical " + self.cssPre + "-horizontal");
if(self.options.mode === "flyout") {
menuContainer.addClass(self.cssPre + "-" + value);
$.each(self.getItems(), function (i, n) {
if(n.getItems().length === 0) {
return;
}
n._getLink().find("." + cssPre + oldCss).removeClass(cssPre + oldCss + " " + cssPre + newCss).addClass(cssPre + newCss);
});
} else {
menuContainer.addClass(self.cssPre + "-vertical");
}
};
wijmenu.prototype._getTriggerEle = function () {
return wijmenu._getOuterElement(this.options.trigger, "." + this.options.wijCSS.wijmenu);
};
wijmenu.prototype._set_triggerEvent = function (value) {
var self = this, o = self.options, triggerEle = self._getTriggerEle();
self._killtrigger();
o.triggerEvent = value;
if(triggerEle.length > 0) {
self._initTrigger(triggerEle);
}
if(o.mode === "flyout") {
self._killFlyout();
self._flyout();
}
};
wijmenu.prototype._set_trigger = function (value) {
var self = this, o = self.options, triggerEle;
self._killtrigger();
o.trigger = value;
triggerEle = self._getTriggerEle();
if(triggerEle.length > 0) {
self._initTrigger(triggerEle);
}
if(o.mode === "flyout") {
self._killFlyout();
self._flyout();
}
};
wijmenu.prototype._initTrigger = function (triggerEle) {
var o = this.options, event = o.triggerEvent, self = this, menuContainer = self.domObject.menucontainer, namespace = ".wijmenuEvent";
if(triggerEle.is("iframe")) {
triggerEle = $(triggerEle.get(0).contentWindow.document);
}
switch(event) {
case "click":
triggerEle.bind(event + namespace, function (e) {
if(o.mode !== "popup") {
self._displayMenu(e);
}
e.stopPropagation();
});
break;
case "mouseenter":
triggerEle.bind(event + namespace, function (e) {
self._displayMenu(e);
e.stopPropagation();
});
break;
case "dblclick":
triggerEle.bind(event + namespace, function (e) {
self._displayMenu(e);
e.stopPropagation();
});
break;
case "rtclick":
triggerEle.bind("contextmenu" + namespace, function (e) {
menuContainer.hide();
self._displayMenu(e);
e.preventDefault();
e.stopPropagation();
});
break;
}
};
wijmenu.prototype._killtrigger = function () {
var o = this.options, triggerEle;
if(o.trigger !== "") {
triggerEle = $(o.trigger);
if(triggerEle.is("iframe")) {
triggerEle = $(triggerEle.get(0).contentWindow.document);
}
if(triggerEle && triggerEle.length > 0) {
triggerEle.unbind(".wijmenuEvent").unbind("wijmenuEvent");
}
}
};
wijmenu.prototype._move = function (driection, fnDefault, event) {
var self = this, active = self._getActiveItemElement(), next, parent, widget;
if(!active || !active.length) {
self.activate(event, fnDefault(self));
return;
}
widget = wijmenu._getItemWidget(active);
next = widget[driection]()//next/previuos
;
parent = widget._getParentOrMenu();
if(next) {
self.activate(event, next);
} else {
self.activate(event, fnDefault(parent));
}
};
wijmenu.prototype._bindMousehoverEvent = function (element) {
var self = this;
var o = self.options;
element.delegate("li>." + o.wijCSS.wijmenuLink, "mouseenter.wijmenuEvent", function () {
var itemDisabled = $(this).hasClass(o.wijCSS.stateDisabled);
if(self._getDisabled() || itemDisabled) {
return;
}
$(this).addClass(o.wijCSS.stateHover);
}).delegate("li>." + o.wijCSS.wijmenuLink, "mouseleave.wijmenuEvent", function () {
var itemDisabled = $(this).hasClass(o.wijCSS.stateDisabled);
if(self._getDisabled() || itemDisabled) {
return;
}
$(this).removeClass(o.wijCSS.stateHover);
if($(this).data("subMenuOpened")) {
$(this).addClass(o.wijCSS.stateActive);
}
});
};
wijmenu.prototype.refresh = /** The method is used to refresh the menu whenDOM operations add or replace a menu item,
* @example
* //Adds a new item and refresh menu.
* menu.append("<li><a href='#'>new item</a></li>").wijmenu("refresh");
*/
function () {
var self = this, ele = self.element, o = self.options, direction = o.direction, scrollcontainer, menucontainer, domObject, triggerEle, breadcrumb;
if(self.domObject) {
self._innerDestroy();
}
if(ele.is("ul")) {
self._rootMenu = ele;
scrollcontainer = ele.wrap("<div></div>").parent();
menucontainer = scrollcontainer.wrap("<div></div>").parent();
} else if(ele.is("div")) {
self._rootMenu = $("ul:first", ele);
scrollcontainer = ele;
menucontainer = ele.wrap("<div></div>").parent();
} else {
return;
}
if(direction === "rtl") {
self._rootMenu.addClass(o.wijCSS.wijmenuRtl);
}
scrollcontainer.addClass("scrollcontainer checkablesupport");
menucontainer.addClass(o.wijCSS.widget).addClass(o.wijCSS.header).addClass(o.wijCSS.wijmenu).addClass(o.wijCSS.cornerAll).addClass(o.wijCSS.helperClearFix).attr("aria-activedescendant", o.wijCSS.activeMenuitem);
if(o.orientation === "horizontal" && o.mode === "flyout") {
menucontainer.addClass(o.wijCSS.wijmenuHorizontal);
}
domObject = {
scrollcontainer: scrollcontainer,
menucontainer: menucontainer
};
self.domObject = domObject;
self._getSublist().data("topmenu", true);
if(!self._getSublist().hasClass(o.wijCSS.wijmenuList)) {
self._getSublist().addClass(o.wijCSS.wijmenuList).addClass(o.wijCSS.helperReset);
}
self._items = self._createMenuItems();
ele.show();
self._bindMousehoverEvent(ele);
this[o.mode === "flyout" ? "_flyout" : "_drilldown"]();
if(o.trigger !== "") {
triggerEle = self._getTriggerEle();
if(triggerEle.length > 0) {
menucontainer.hide();
self._initTrigger(triggerEle);
}
}
$(document).bind(self.clickNameSpace, function (e) {
///fixed when click the breadcrumb choose item link to show
/// the root menu in sliding menu.
var t = o.trigger;
if($(e.target).parent().is("." + o.wijCSS.wijmenuAllLists)) {
return;
}
// fix tfs issue 20650 by Chandler.Zheng on 2012-03-19
if($(e.target).closest(o.trigger).is(o.trigger)) {
return;
}
//end comments
var obj = $(e.target).closest("." + o.wijCSS.wijmenu);
if(obj.length === 0) {
if(o.mode === "sliding") {
breadcrumb = $("." + o.wijCSS.wijmenuBreadcrumb, menucontainer);
// fixed a bug, when the trigger is not seted.
// when click the document, trigger this method!
if(o.trigger === "") {
return;
}
self._resetDrilldownMenu(breadcrumb);
} else if(o.mode === "flyout" && o.triggerEvent !== "mouseenter") {
self._hideAllMenus(e);
return;
}
if(triggerEle && triggerEle.length > 0) {
self._hideMenu(e);
}
}
});
};
wijmenu.prototype._flyout = function () {
var container = this.domObject.menucontainer, o = this.options, items = this.getItems();
container.attr("role", "menu");
if(o.orientation === "horizontal") {
container.attr("role", "menubar");
}
$.each(items, function (index, item) {
item._flyout();
});
};
wijmenu.prototype._hideAllMenus = function (e) {
var self = this, container, outerTrigger, fnHideSubmenu = function (menuitem) {
if(menuitem.getItems().length > 0) {
$.each(menuitem.getItems(), function (i, n) {
fnHideSubmenu(n);
});
menuitem._hideSubmenu(false, e);
}
};
$.each(self._items, function (i, n) {
fnHideSubmenu(n);
});
if(self.options.trigger !== "") {
container = self.domObject.menucontainer;
if(container.data("isAnimated")) {
return;
}
/*if (container.is(":animated")) {
return;
}*/
// if the trigger is outer of the menu,
//when hide all menus hide the root menu.
outerTrigger = self._getTriggerEle();
if(outerTrigger.length === 0) {
return;
}
self._hideMenu(e);
}
};
wijmenu.prototype.hideAllMenus = /** The hideAllMenus method hides all menu items currently showing.*/
function (e) {
this._hideAllMenus(e);
};
wijmenu.prototype._killFlyout = function () {
$.each(this.getItems(), function () {
this._killFlyout();
});
};
wijmenu.prototype._killElement = function () {
var self = this, o = self.options, ele = self._getSublist();
ele.removeClass(o.wijCSS.wijmenuList).removeClass(o.wijCSS.helperReset).removeClass(o.wijCSS.wijmenuContent).removeClass(o.wijCSS.helperClearFix);
//self.domObject.menucontainer.removeClass("");
$(document).unbind(self.clickNameSpace);
//remove warping
if(self.element.is("ul")) {
self.element.unwrap().unwrap();
} else {
self.element.unwrap();
}
//For fix the tfs issue id 24830. js error: object is null or undefined
self.domObject = null;
self.element.removeData("topmenu").removeData("firstLeftValue").removeData("domObject");
//self.element.removeData("domObject").removeData("topmenu")
//.removeData("firstLeftValue");
ele.undelegate(".wijmenuEvent");
};
wijmenu.prototype._killMenuItems = function () {
var self = this, items = self.getItems(), i;
//$.each(self.getItems(), function (i, n) {
// n.destroy(true);
//});
for(i = items.length - 1; i >= 0; i--) {
items[i].destroy(true);
}
self._items.length = 0;
};
wijmenu.prototype._sroll = function () {
var scroll = this.domObject.scrollcontainer, options = $.extend({
hScroller: {
scrollBarVisibility: "hidden"
}
}, this.options.superPanelOptions);
scroll.height(this.options.maxHeight);
scroll.wijsuperpanel(options);
};
wijmenu.prototype._initScrollCallback = function () {
var self = this, scrollContainer = self.domObject.scrollcontainer;
self._linkContainer = {
link: null,
needToFocus: false
};
scrollContainer.wijsuperpanel({
scrolled: function () {
var link = self._linkContainer.link;
if(self._linkContainer.needToFocus && link && link.is('a')) {
link.focus();
self._linkContainer.needToFocus = false;
}
}
});
};
wijmenu.prototype._resetScroll = function (widget) {
var self = this, mycontainer = self._rootMenu.parent(), fixPadding = 5, scrollcontainer = self.domObject.scrollcontainer, sublist = widget._getSublist();
mycontainer.height(sublist.height());
scrollcontainer.wijsuperpanel("option", "hScroller", {
scrollValue: 0
});
scrollcontainer.wijsuperpanel("option", "vScroller", {
scrollValue: 0
});
scrollcontainer.wijsuperpanel("paintPanel");
if(self._hasScroll()) {
if(sublist.prev().length > 0) {
fixPadding = sublist.prev().css("padding-left").replace(/px/g, "");
}
sublist.width(scrollcontainer.find(".wijmo-wijsuperpanel-contentwrapper" + ":first").width() - fixPadding);
//because the scroll bar has 16px width, there has a possible
//that the height of ul will modified after appending scrollbar
//so there should get the height of container again, and repaint panel
mycontainer.height(sublist.height());
scrollcontainer.wijsuperpanel("paintPanel");
}
};
wijmenu.prototype._hasScroll = function () {
var scroll = this.domObject.scrollcontainer;
//Fix for jQuery UI 1.10
return scroll.data("wijmoWijsuperpanel").vNeedScrollBar;
//return scroll.data("wijsuperpanel").vNeedScrollBar;
};
wijmenu.prototype._resetDrillChildMenu = function (el) {
var o = this.options;
el.removeClass(o.wijCSS.wijmenuScroll).removeClass(o.wijCSS.wijmenuCurrent).height("auto");
};
wijmenu.prototype._resetDrilldownMenu = function (breadcrumb, callback) {
var self = this, o = self.options, ele = self._getSublist(), container = self.domObject.menucontainer, crumbDefaultHeader = $('<li>' + o.crumbDefaultText + '</li>').addClass(o.wijCSS.wijmenuBreadcrumbText), fnResetSublists = function (items) {
$.each(items, function (i, n) {
var ul = n._getSublist(), childItems = n.getItems();
ul.hide();
self._resetDrillChildMenu(ul);
if(childItems.length > 0) {
fnResetSublists(childItems);
}
});
};
$('.' + o.wijCSS.wijmenuCurrent, container).removeClass(o.wijCSS.wijmenuCurrent);
ele.animate({
left: 0
}, o.showDuration, null, function () {
fnResetSublists(self.getItems());
ele.addClass(o.wijCSS.wijmenuCurrent);
if(callback) {
callback();
}
});
$('.' + o.wijCSS.wijmenuAllLists, container).find('span').remove();
breadcrumb.empty().append(crumbDefaultHeader);
$('.' + o.wijCSS.wijmenuFooter, container).empty().hide();
self._resetScroll(self);
};
wijmenu.prototype._drilldown = function () {
var self = this, ele = self._getSublist(), container = self.domObject.menucontainer.attr("role", "menu"), containerWidth, o = self.options, direction = //fixPadding,
o.direction, breadcrumb = $('<ul></ul>').addClass(o.wijCSS.wijmenuBreadcrumb).addClass(o.wijCSS.stateDefault).addClass(o.wijCSS.cornerAll).addClass(o.wijCSS.helperClearFix), crumbDefaultHeader = $('<li>' + o.crumbDefaultText + '</li>').addClass(o.wijCSS.wijmenuBreadcrumbText), firstCrumb = $('<li><a href="#">' + o.topLinkText + '</a></li>').addClass(o.wijCSS.wijmenuAllLists);
//wraping mycontainer
ele.wrap("<div>").parent().css("position", "relative");
container.addClass(o.wijCSS.wijmenuIpod).addClass(o.wijCSS.wijmenuContainer);
if(o.backLink) {
breadcrumb.addClass(o.wijCSS.wijmenuFooter).appendTo(container).hide();
} else {
breadcrumb.addClass(o.wijCSS.wijmenuHeader).prependTo(container);
}
if(!o.backLink) {
breadcrumb.append(crumbDefaultHeader);
}
containerWidth = container.width();
ele.addClass(o.wijCSS.wijmenuContent).addClass(o.wijCSS.wijmenuCurrent).addClass(o.wijCSS.content).addClass(o.wijCSS.helperClearFix).css({
width: containerWidth
});
$.each(self.getItems(), function (i, n) {
n._setDrilldownUlStyle();
});
self._sroll();
self._initScrollCallback();
self._resetScroll(self);
self.element.data("firstLeftValue", parseFloat(ele.css('left')));
ele.delegate("li>." + o.wijCSS.wijmenuLink, "click", function (e, itemWidgetToActive) {
var li = $(this).parent(), itemDisabled = li.attr("disabled"), nextList, parentUl, parentLeft, crumbText, newCrumb, nextLeftVal, footer, setPrevMenu, hasVisibleSubMenu, itemWidget = wijmenu._getItemWidget(li), backlinkIcon, backlinkText;
if(self._getDisabled() || itemDisabled) {
return;
}
if(self._isSliding) {
return;
}
ele.stop(true, true);
hasVisibleSubMenu = wijmenu._hasVisibleSubMenus(itemWidget);
if(!hasVisibleSubMenu) {
self._leafNodeClick(e, itemWidget, breadcrumb);
return;
}
nextList = itemWidget._getSublist();
//prevent dblclick.
if(nextList.hasClass(o.wijCSS.wijmenuCurrent)) {
return;
}
//end comments.
if(!self._trigger("showing", e, itemWidget)) {
return;
}
self._isSliding = true;
parentUl = itemWidget._getParentOrMenu()._getSublist();
parentLeft = (parentUl.data("topmenu")) ? 0 : parseFloat(ele.css('left'));
if(direction === "rtl") {
nextLeftVal = Math.round(parentLeft + parseFloat(container.width().toString()));
} else {
nextLeftVal = Math.round(parentLeft - parseFloat(container.width().toString()));
}
footer = $('.' + o.wijCSS.wijmenuFooter, container);
setPrevMenu = function (backlink, current) {
var b = backlink, c = $('.' + o.wijCSS.wijmenuCurrent, container), prevList, widget;
if(c.get(0) === self._getSublist().get(0)) {
return;
}
if(current) {
prevList = current._getSublist();
widget = current;
} else {
prevList = c.parents('ul:eq(0)');
widget = wijmenu._getItemWidget(c.parent())._getParentOrMenu();
}
c.hide().attr('aria-expanded', 'false');
self._resetDrillChildMenu(c);
self._resetScroll(widget);
prevList.addClass(o.wijCSS.wijmenuCurrent).attr('aria-expanded', 'true');
if(prevList.hasClass(o.wijCSS.wijmenuContent)) {
b.remove();
footer.hide();
}
};
// show next menu
self._resetDrillChildMenu(parentUl);
self._resetScroll(itemWidget);
self._slidingAnimation(ele, nextLeftVal, function () {
self._trigger("shown", e, itemWidget);
self.activate(e, itemWidgetToActive || itemWidget);
//add comments for tfs issue 18483
self.select(e);
//end comments.
self._isSliding = false;
});
nextList.show().addClass(o.wijCSS.wijmenuCurrent).attr('aria-expanded', 'true');
// initialize "back" link
if(o.backLink) {
if(footer.find('a').size() === 0) {
footer.show();
backlinkIcon = $("<span></span>").addClass(o.wijCSS.icon).addClass(o.wijCSS.iconArrowLeft);
backlinkText = $('<span></span>').addClass(o.wijCSS.wijmenuBacklinktext);
self._backLink = $('<a href="#"></a>').append(backlinkIcon).append(backlinkText).appendTo(footer).click(function (e, callback) {
// ----- show the previous menu
if(self._getDisabled()) {
return;
}
var currentItemWidget = self._getCurrentItemInSliding(), b = $(this), prevLeftVal;
if(!self._trigger("hidding", e, currentItemWidget)) {
return;
}
ele.stop(true, true);
if(direction === "rtl") {
prevLeftVal = Math.round(ele.css('left').replace("px", "")) - Math.round(container.width());
} else {
prevLeftVal = Math.round(ele.css('left').replace("px", "")) + Math.round(container.width());
///to fix click the back button too quickly.
///The menu display wrong.
if(prevLeftVal > parentLeft) {
return;
}
}
self._slidingAnimation(ele, prevLeftVal, function () {
self._trigger("hidden", e, currentItemWidget);
setPrevMenu(b);
if(callback) {
callback();
}
});
e.preventDefault();
});
backlinkText.width(footer.width() - backlinkIcon.width());
backlinkText.text(o.backLinkText);
}
} else// or initialize top breadcrumb
{
if(breadcrumb.find('li').size() === 1) {
breadcrumb.empty().append(firstCrumb);
firstCrumb.find('a').click(function (e, callback) {
var targetCrumb = $(this).parent(), currentItemWidget = self._getCurrentItemInSliding();
self._slidingMenu(e, targetCrumb, currentItemWidget, null, function (item) {
if(!item) {
self._resetDrilldownMenu(breadcrumb, callback);
} else {
setPrevMenu(null, item);
if(callback) {
callback();
}
}
});
e.preventDefault();
});
}
$('.' + o.wijCSS.wijmenuCurrentCrumb, container).removeClass(o.wijCSS.wijmenuCurrentCrumb);
crumbText = itemWidget._getLink().text();
newCrumb = $("<li></li>").addClass(o.wijCSS.wijmenuCurrentCrumb).append($('<a href="#">' + crumbText + '</a>').addClass(o.wijCSS.wijmenuCrumb));
newCrumb.appendTo(breadcrumb).find('a').click(function (e, callback) {
if(self._getDisabled()) {
return;
}
var targetCrumb = $(this).parent(), currentItemWidget;
if(!targetCrumb.is('.' + o.wijCSS.wijmenuCurrentCrumb)) {
currentItemWidget = self._getCurrentItemInSliding();
self._slidingMenu(e, targetCrumb, currentItemWidget, itemWidget, function (item) {
setPrevMenu(null, item);
if(callback) {
callback();
}
});
}
e.preventDefault();
});
newCrumb.prev().append($('<span></span>').addClass(o.wijCSS.icon).addClass(o.wijCSS.iconCaratRight));
}
if($(this).attr("href") === "#") {
e.preventDefault();
}
});
};
wijmenu.prototype._slidingMenu = function (e, targetCrumb, currentItem, targetItem, animationCallback) {
var self = this, ele = self._getSublist(), direction = self.options.direction, container = self.domObject.menucontainer, containerWidth = container.width(), level = targetCrumb.parent().children().length - 1, newLeftVal, _targetItem, crumb, hiddenCallback, fnSlidingAnimation = function (targetItem, level, callback) {
newLeftVal = (direction === "rtl" ? 1 : -1) * level * containerWidth;
self._slidingAnimation(ele, newLeftVal, function () {
if(callback) {
callback(targetItem);
}
});
}, fnGetTargetItem = function (currentItem, targetItem) {
var hidding;
if(currentItem !== targetItem) {
hidding = self._trigger("hidding", e, currentItem);
if(hidding) {
level--;
if(hiddenCallback) {
hiddenCallback();
}
hiddenCallback = function () {
self._trigger("hidden", e, currentItem);
};
return fnGetTargetItem(currentItem.getParent(), targetItem);
}
}
return currentItem;
};
_targetItem = fnGetTargetItem(currentItem, targetItem);
if(_targetItem !== currentItem) {
fnSlidingAnimation(_targetItem, level, function () {
if(hiddenCallback) {
hiddenCallback();
}
if(animationCallback) {
animationCallback(_targetItem);
}
});
crumb = targetCrumb.parent().children().eq(level);
crumb.addClass('wijmo-wijmenu-current-crumb').find('span').remove();
crumb.nextAll().remove();
}
};
wijmenu.prototype._getCurrentItemInSliding = function () {
var self = this, container = self.domObject.menucontainer, c = $('.wijmo-wijmenu-current', container), currentItemWidget = wijmenu._getItemWidget(c.parent());
return currentItemWidget;
};
wijmenu.prototype._leafNodeClick = function (e, itemWidget, breadcrumb) {
var self = this, o = self.options, triggers;
self.activate(e, itemWidget);
self.select(e);
if(o.trigger) {
triggers = self._getTriggerEle();
if(triggers.length) {
self._hideMenu(e);
self._resetDrilldownMenu(breadcrumb);
}
}
if(itemWidget._getLink().attr("href") === "#") {
e.preventDefault();
}
};
wijmenu.prototype._slidingAnimation = function (ele, left, callback) {
var o = this.options.slidingAnimation;
if(o && !o.disabled) {
ele.stop(true, true).animate({
left: left
}, o.duration, o.easing, callback);
} else {
ele.css("left", left);
callback.call(this);
}
};
wijmenu.prototype._killDrilldown = function () {
var ele = this._getSublist(), o = this.options, domObject = this.domObject, style = {
width: "",
height: ""
};
ele.css(style).removeClass(o.wijCSS.content);
//fix bug that set mode as 'sliding' at setOptions stage
// will remove the self.element from the page
if(domObject.scrollcontainer && domObject.scrollcontainer.parent().length > 0) {
domObject.scrollcontainer.css(style);
domObject.scrollcontainer.wijsuperpanel("destroy");
domObject.scrollcontainer.removeClass("wijmo-wijsuperpanel").append(ele);
}
ele.prevAll().remove();
domObject.menucontainer.removeClass(o.wijCSS.wijmenuIpod).removeClass(o.wijCSS.wijmenuContainer);
$('.' + o.wijCSS.wijmenuCurrent, domObject.menucontainer).removeClass(o.wijCSS.wijmenuCurrent);
$("." + o.wijCSS.wijmenuBreadcrumb, domObject.menucontainer).remove();
ele.undelegate("li>." + o.wijCSS.wijmenuLink, "click");
$("ul", ele).css({
left: "",
width: ""
});
ele.css("left", "");
domObject.scrollcontainer = domObject.menucontainer.children(":first");
};
wijmenu.prototype._displayMenu = function (e) {
var self = this, o = self.options, animationOptions, direction, showAnimation, menucontainer = self.domObject.menucontainer, triggerEle = $(e.target), haveNoVisibleChild = !wijmenu._hasVisibleSubMenus(self);
if(menucontainer.is(":visible") || haveNoVisibleChild) {
return;
}
if(!self._trigger("showing", e, self)) {
return;
}
//self._trigger("showing", e, self);
menucontainer.show();
self._setPosition(triggerEle);
self.nowIndex++;
self._setZindex(menucontainer, self.nowIndex);
menucontainer.hide();
animationOptions = {
context: menucontainer,
show: true
};
direction = o.direction === "rtl" ? "right" : "left";
showAnimation = $.extend({
}, {
option: {
direction: direction
}
}, o.animation, o.showAnimation);
wijmenu._animateFlyoutMenu(showAnimation, animationOptions, function () {
//add the event shown
self._trigger("shown", e, self);
});
//$.wijmo.wijmenu._animateFlyoutMenu(showAnimation, animationOptions);
self._isClickToOpen = o.triggerEvent === "click";
this.element.data("shown", true);
};
wijmenu.prototype._hideMenu = function (e) {
var self = this, o = self.options, sublist = this.domObject.menucontainer, animations = wijmenu.animations, animationOptions, hideAnimation;
if(!this.element.data("shown")) {
return;
}
//add event hidding
if(!self._trigger("hidding", e, self)) {
return;
}
this.element.data("shown", false);
if($.fn.wijhide) {
animationOptions = {
context: sublist,
show: false
};
hideAnimation = $.extend({
}, o.animation, o.hideAnimation);
sublist.wijhide(hideAnimation, animations, animationOptions, null, function () {
self._setZindex(sublist, null);
sublist.attr("aria-hidden", true);
self._trigger("hidden", e, self);
});
} else {
sublist.hide().attr("aria-hidden", true);
self._setZindex(sublist, null);
self._trigger("hidden", e, self);
}
};
wijmenu.prototype._setZindex = function (ele, value) {
var domObject = this.domObject, menucontainer;
if(!domObject) {
return;
}
menucontainer = domObject.menucontainer;
//fixed a bug which menu cannot shows up above other elements
//when set an outer triggerEle
if(ele.get(0) === menucontainer.get(0)) {
if(value) {
menucontainer.css("z-index", value);
} else {
menucontainer.css("z-index", "");
}
return;
}
if(value) {
ele.parent().css("z-index", 999);
ele.css("z-index", value);
if($.browser.msie && parseInt($.browser.version) < 8 && menucontainer.css("z-index") === 0) {
menucontainer.css("z-index", 9950);
}
} else {
ele.css("z-index", "");
ele.parent().css("z-index", "");
if($.browser.msie && parseInt($.browser.version) < 8 && $("ul:visible", this._getSublist()).length === 0 && menucontainer.css("z-index") === 9950) {
menucontainer.css("z-index", "");
}
}
};
wijmenu.prototype._setPosition = function (triggerEle) {
var pOption = this._getPosition(), obj = {
of: triggerEle
}, menuContainer = this.domObject.menucontainer;
menuContainer.css({
left: '0',
top: '0',
position: 'absolute'
});
//now do not support the equal-height menu.
/*
if (tag) {
var parentUl = item.parent().parent();
if (!parentUl.is(".wijmo-wijmenu-child")) {
parentUl = this.element.data("domObject").menucontainer;
}
obj = { of: parentUl };
}
*/
menuContainer.position($.extend(obj, pOption));
};
wijmenu.prototype._getPosition = function () {
var o = this.options, direction = o.direction, pOption = direction === "rtl" ? {
my: 'right top',
at: 'right bottom'
} : {
my: 'left top',
at: 'left bottom'
};
pOption = $.extend(pOption, o.position);
return pOption;
};
wijmenu.prototype._getFirstSelectableSubItem = function () {
return wijmenu._getFirstSelectableSubItem(this);
};
wijmenu.prototype._getLastSelectableSubItem = function () {
return wijmenu._getLastSelectableSubItem(this);
};
wijmenu.prototype.add = /** Adds a child menuItem to the menuItem.
* @param menuitem The menuItem to be added
* 1.markup html.such as "<a>menuItem</a>" as a menuItem.
* 2.object options according to the options of wijmenuItem.
* @param {number} position the position to insert at
*/
function (menuItem, position) {
wijmenu._add(this, menuItem, position);
};
wijmenu.prototype._getSublist = function () {
return this._rootMenu;
};
wijmenu.prototype.getItems = /**
* Gets the collection of child items.
* @returns {array} the menu items.
*/
function () {
return this._items;
};
wijmenu.prototype.remove = /** Remove an item from the menu.
* @param {Number} index The index of menuitem to be removed
* @example
* //Removes the second menuitem.
* $("#menu").wijmenu("remove", 1);
*/
function (index) {
wijmenu._remove(this, index);
};
wijmenu.prototype._newId = function () {
var charArray = [
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z'
], id = "", i;
for(i = 0; i < 16; i++) {
id += charArray[Math.round(Math.random() * 25)];
}
return id;
};
wijmenu.animations = {
slide: function (options, addtions) {
options = $.extend({
duration: 400,
easing: "swing"
}, options, addtions);
if(options.show) {
options.context.stop(true, true).animate({
height: 'show'
}, options, function () {
options.context.attr("aria-hidden", false);
});
} else {
options.context.stop(true, true).animate({
height: 'hide'
}, options, function () {
options.context.attr("aria-hidden", true);
});
}
}
};
wijmenu._animateFlyoutMenu = function _animateFlyoutMenu(showAnimation, animationOptions, callback) {
var sublist = animationOptions.context;
if($.fn.wijshow) {
sublist.data("isAnimated", true);
sublist.wijshow(showAnimation, wijmenu.animations, animationOptions, null, function () {
sublist.data("isAnimated", false);
var browser = $.browser;
if(browser.msie && browser.version === "9.0") {
sublist.wrap("<div></div>");
sublist.unwrap();
} else if(browser.msie && browser.version === "6.0") {
sublist.css("overflow", "");
}
sublist.attr("aria-hidden", false);
if(callback) {
callback();
}
});
} else {
sublist.show().attr("aria-hidden", false);
}
};
wijmenu._getMenuItemOptions = function _getMenuItemOptions(options, index) {
if(!options) {
return {
};
}
if(!options.items || !$.isArray(options.items)) {
return {
};
}
if(index >= options.items.length) {
return {
};
}
return options.items[index];
};
wijmenu._getOuterElement = function _getOuterElement(selector, isInnerSelector) {
return $(selector).filter(function () {
return $(this).closest(isInnerSelector).length === 0;
});
};
wijmenu._hasVisibleSubMenus = function _hasVisibleSubMenus(widgetElement) {
var widget, items, i;
if(widgetElement.jquery) {
if(widgetElement.data("wijmomenu")) {
widget = widgetElement.data(widgetElement.data("wijmomenu"));
} else if(widgetElement.data("wijmomenuitem")) {
widget = widgetElement.data(widgetElement.data("wijmomenuitem"));
}
} else {
widget = widgetElement;
}
if(!widget) {
throw "the arugment 'menuItem' must be an wijmenu or wijmenuitem";
}
items = widget.getItems();
if(!items.length) {
return false;
}
for(i = 0; i < items.length; i++) {
//if any of item was set displayVisible as true, just return true;
if(items[i].options.displayVisible) {
return true;
}
}
return false;
};
wijmenu._getFirstSelectableSubItem = function _getFirstSelectableSubItem(widget) {
var i, items = widget.getItems(), o;
for(i = 0; i < items.length; i++) {
o = items[i].options;
if(o.displayVisible !== false && !o.header && !o.separator) {
return items[i];
}
}
return null;
};
wijmenu._getLastSelectableSubItem = function _getLastSelectableSubItem(widget) {
var i, items = widget.getItems(), o;
for(i = items.length - 1; i >= 0; i--) {
o = items[i].options;
if(o.displayVisible !== false && !o.header && !o.separator) {
return items[i];
}
}
return null;
};
wijmenu._getSelectableSubItems = function _getSelectableSubItems(widget, filter) {
return $.grep(widget.getItems(), function (n, i) {
var o = n.options;
if(o.header || o.separator || o.displayVisible === false) {
return false;
}
return filter(n, i);
}, false);
};
wijmenu._add = /** Adds a child menuItem to the menuItem. */
function _add(self, menuItem, position) {
var menuItemWidget = null, $menuItem = $("<li></li>"), $ul = self._getSublist(), items = self.getItems(), elementToInserBefore, o, hasCreatedUl = false;
if(typeof menuItem === "string") {
//if is h1-h5 or an link
if(/<(h[1-5]|a)[\s\S]*>[\s\S]*<\/\1>/.test(menuItem)) {
$menuItem.append(menuItem);
}
} else if($.isPlainObject(menuItem)) {
o = jQuery.extend(true, {
}, menuItem);
}
//if the li has no children before, add an new ul
if(!$ul || $ul.length <= 0) {
$ul = $("<ul></ul>");
self.element.append($ul);
hasCreatedUl = true;
}
//if position is 0, '', undefined, null
//OR not an number,
//OR was specifed an out of range value
if(!position || isNaN(position) || position > items.length) {
if(position !== 0) {
position = items.length;
}
}
//if the posiotn has been specified, insert it to the appropriate position
if(items.length > 0 && items.length !== position) {
elementToInserBefore = items[position].element;
$menuItem.insertBefore(elementToInserBefore);
} else {
$ul.append($menuItem);
}
menuItemWidget = self._createItemWidget($menuItem, o);
if(menuItemWidget === null || menuItemWidget === undefined) {
return;
}
wijmenu._changeCollection(position, self.getItems(), self.options.items, menuItemWidget);
if(self._bindModeEvents) {
self._bindModeEvents(menuItemWidget, hasCreatedUl);
} else {
menuItemWidget._bindModeEvents(menuItemWidget, hasCreatedUl);
}
if(hasCreatedUl) {
self._initUlCssClass();
}
};
wijmenu._changeCollection = function _changeCollection(idx, menuItems, items, menuItemWidget) {
//var indexOfItem;
if(!menuItemWidget) {
menuItems.splice(idx, 1);
items.splice(idx, 1);
return;
}
//if the menuItemWidget has been in the array, remove it at first
// indexOfItem = $.inArray(menuItemWidget, menuItems);
// if (indexOfItem !== -1) {
// menuItems.splice(indexOfItem, 1);
// }
menuItems.splice(idx, 0, menuItemWidget);
items.splice(idx, 0, menuItemWidget.options);
};
wijmenu._remove = function _remove(self, index) {
var menuItem = self.getItems()[index];
if(menuItem && menuItem.element) {
menuItem.element.remove();
}
};
wijmenu._getItemWidget = function _getItemWidget(li) {
//return li.data($.wijmo.wijmenu._itemWidgetName);
return li.data(li.data("wijmomenuitem"));
};
return wijmenu;
})(wijmo.wijmoWidget);
menu.wijmenu = wijmenu;
var wijmenu_options = (function () {
function wijmenu_options() {
/** Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijmenu')";
/** wijmenu css, extend from $.wijmo.wijCSS
* @ignore
*/
this.wijCSS = {
wijmenu: "wijmo-wijmenu",
wijmenuHorizontal: "wijmo-wijmenu-horizontal",
wijmenuCurrent: "wijmo-wijmenu-current",
wijmenuCurrentCrumb: "wijmo-wijmenu-current-crumb",
wijmenuBreadcrumb: "wijmo-wijmenu-breadcrumb",
wijmenuBreadcrumbText: "wijmo-wijmenu-breadcrumb-text",
wijmenuItem: "wijmo-wijmenu-item",
wijmenuLink: "wijmo-wijmenu-link",
wijmenuList: "wijmo-wijmenu-list",
wijmenuScroll: "wijmo-wijmenu-scroll",
wijmenuContent: "wijmo-wijmenu-content",
wijmenuFooter: "wijmo-wijmenu-footer",
wijmenuHeader: "wijmo-wijmenu-header",
wijmenuContainer: "wijmo-wijmenu-container",
wijmenuIpod: "wijmo-wijmenu-ipod",
wijmenuCrumb: "wijmo-wijmenu-crumb",
wijmenuAllLists: "wijmo-wijmenu-all-lists",
wijmenuPrevList: "wijmo-wijmenu-prev-list",
wijmenuRtl: "wijmo-wijmenu-rtl",
wijmenuBacklinktext: "wijmo-wijmenu-backlinktext",
wijmenuSubmenuContainer: "wijmo-wijmenu-submenu-container",
wijmenuParent: "wijmo-wijmenu-parent"
};
/** @ignore*/
this.wijMobileCSS = {
header: "ui-header ui-bar-c",
content: "ui-body ui-body-c",
stateDefault: "ui-btn-up-c",
stateHover: "ui-btn-down-c",
stateActive: "ui-btn-down-c"
};
/** A jQuery selector which handles the open event for the menu or submenu.
* @remarks If the trigger is set to a menu item(the <li> element),
* then the submenu appears when the item is clicked if the triggerEvent
* is set to click. If the trigger is set to an element outside of the menu,
* then the menu opens when the element is clicked if the triggerEvent is
* set to click as a contextmenu.
* @example
* //Set trigger to make menu as input's contextmenu.
* $(".selector").wijmenu("option", "trigger", "input")
*/
this.trigger = '';
/** The triggerEvent option specifies the mouse event used to show the menu or submenu.
* @remarks The value can be seted to 'click', 'mouseenter', 'dbclick', 'rtclick'
*/
this.triggerEvent = 'click';
/** Specifies the location and Orientation of the menu relative to the button
* or link used to open it.
* @remarks Configuration for the Position Utility,Of option
* is excluded, it is always configured by the widget.
* Collision also controls collision detection automatically too.
* It uses jQuery position plugin, see the following link for more details,
* http://api.jqueryui.com/position/
*/
this.position = {
};
/** The animation option sets the menu animation if the showAnimation
* and hideAnimation properties are not individually specified.
* @remarks This option uses the standard animation setting syntax
* from jQuery.UI.
*/
this.animation = {
animated: "slide",
duration: 400,
easing: null
};
/** Determines the animation used to show submenus.
* @remarks This option uses the standard animation setting syntax
* from jQuery.UI.
*/
this.showAnimation = {
};
/** Determines the animation used to hide submenus.
* @remarks This option uses the standard animation setting syntax
* from jQuery.UI.
*/
this.hideAnimation = {
animated: "fade",
duration: 400,
easing: null
};
/** This option determines how many milliseconds to delay
* before showing the submenu in a fly-out menu.
*/
this.showDelay = 400;
/** This option determines how many milliseconds to delay
* before hiding the submenu in a fly-out menu.
*/
this.hideDelay = 400;
/** This option defines the animation used to slide a submenu when in sliding mode.*/
this.slidingAnimation = {
duration: 400,
easing: null
};
/** The mode option defines the behavior of the menu,
* whether it is a pop-up menu or an iPod style navigation list.
* @remarks The possible values are "flyout" or "sliding".
* If your submenu is shown in the same container be sliding animation, use the "sliding" mode.
*/
this.mode = 'flyout';
/** This option specifies a hash value that sets to superpanel options
* when a superpanel is created. It is used to set appearances and behaviors
* when a scrollbar is shown in sliding mode.
* @remarks It uses wijsuperpanel, see the following link for more details,
* http://wijmo.com/wiki/index.php/Superpanel .
*/
this.superPanelOptions = null;
/** A value that defines whether the item can be checked.*/
this.checkable = false;
/** This option controls the root menu's orientation. All submenus are vertical
* regardless of the orientation of the root menu.
* @remarks The value should be "horizontal" or "vertical".
*/
this.orientation = 'horizontal';
/** A value that indicates menu's direction.
* @remarks The value should be "ltr" or "rtl".
*/
this.direction = 'ltr';
/** This option determines the iPod-style menu's maximum height.
* @remarks This option can only be used in an iPod style menu.
* When the menu's heiget is largger than this value,
* the menu shows a scroll bar.
*/
this.maxHeight = 200;
/** This option determines whether the iPod menu shows a back link or a breadcrumb header
* in the menu.
*/
this.backLink = true;
/** This option sets the text of the back link.*/
this.backLinkText = 'Back';
/** A value that sets the text of the top link. */
this.topLinkText = 'All';
/** A value that sets the top breadcrumb's default text.*/
this.crumbDefaultText = 'Choose an option';
/** The select event is triggered when a menu item is selected.
* @event
* @dataKey item item.item is the active item of the menu.
*/
this.select = null;
/** The focus event is triggered either on mouse hover or
* when the keyboard cursor keys are used for navigation.
* @event
* @dataKey item item.item is the item which is focused.
*/
this.focus = null;
/** Triggered when a menu item loses focus.
* @event
* @dataKey item item.item is the item which is blured.
*/
this.blur = null;
/** The showing event is triggered before the submenu is shown.
* This event can be cancelled with "return false";
* @event
* @param event This is the jQuery.Event object.
* @param item This is the event object that relates to the submenu's parent item.
*/
this.showing = null;
/** The shown event is triggered after the menu or submenu is shown.
* @event
* @param event This is the jQuery.Event object.
* @param item The wijmenu widget object when the menu has been displayed,
* or the wijmenuitem widget when the submenu has been displayed.
*/
this.shown = null;
/** The hidding event is triggered before hidding the menu or submenu.
* This event can be cancelled with "return false";
* @event
* @param event This is the jQuery.Event object.
* @param item This is the wijmenu widget object when hiding the menu
* or a wijmenuitem when hiding the submenu.
*/
this.hidding = null;
/** The hidden event is triggered after the menu or submenu is hidden.
* @event
* @param event This is the jQuery.Event object.
* @param item The wijmenu widget object when a menu is hidden
* or a wijmenuitem object when the submenu is hidden.
*/
this.hidden = null;
/** The options of child items
* @type {array}
*/
this.items = null;
/** A value indicating the submenu element will be append to the body or menu container.
* @remarks
* If the value is true, the submenu will be appended to body element.
* else it will append to the menu container.
*/
this.ensureSubmenuOnBody = false;
}
return wijmenu_options;
})();
;
//#region menu options
wijmenu.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijmenu_options());
;
;
/** @ignore*/
(function (MarkupType) {
MarkupType._map = [];
MarkupType.link = 0;
MarkupType.separator = 1;
MarkupType.header = 2;
MarkupType.other = 3;
})(menu.MarkupType || (menu.MarkupType = {}));
var MarkupType = menu.MarkupType;
/** @ignore*/
var wijmenuitem = (function (_super) {
__extends(wijmenuitem, _super);
function wijmenuitem() {
_super.apply(this, arguments);
}
wijmenuitem.prototype._initState = function () {
this._items = [];
this._resetMarkupValue();
if(!this.options.items) {
this.options.items = [];
}
};
wijmenuitem.prototype._create = function () {
var self = this;
if(self._isMobile) {
$.extend(true, self.options.wijCSS, self.options.wijMobileCSS);
}
//update for jQuery UI 1.10
self.element.data("wijmomenuitem", $.camelCase(self.widgetFullName));
//self.element.data("wijmomenuitem", self.widgetName);
self._initState();
self._getOrSetOptionsValues();
self._createChildMenuItems();
self._initCssClass();
//invoke base create.
_super.prototype._create.call(this);
};
wijmenuitem.prototype._refresh = function () {
var self = this, o = self.options;
self._set_navigateUrl(o.navigateUrl);
self._set_target(o.target);
self._set_displayVisible(o.displayVisible);
self._createChildMenuItems();
self._initCssClass();
//self._bindEvents();
};
wijmenuitem.prototype._setOption = function (key, value) {
var self = this, o = self.options, parent;
if(key === "items") {
_super.prototype._setOption.call(this, key, value);
self._set_items(value);
return;
}
if(value === o[key]) {
return;
}
_super.prototype._setOption.call(this, key, value);
if(!$.isFunction(self["_set_" + key])) {
return;
}
self["_set_" + key](value, true);
switch(key) {
case "header":
case "separator":
self._refresh();
break;
case "displayVisible":
parent = self.getParent();
if(parent) {
parent._setSubmenuIcon();
}
break;
default:
break;
}
};
wijmenuitem.prototype.index = function () {
/// <summary>
/// return index of the item.
/// </summary>
return this.element.index();
};
wijmenuitem.prototype._set_selected = function (value) {
var self = this, o = self.options, itemType = self._getMenuItemType();
if(itemType === MarkupType.link) {
self._getLink().toggleClass(o.wijCSS.stateActive, value);
} else {
//if not an link item set selected as false;
self.options.selected = false;
}
};
wijmenuitem.prototype._set_items = function (value) {
var self = this;
self._getSublist().remove();
self._items = [];
if(value.length > 0) {
self._createChildMenuItems();
self._initUlCssClass();
//self._initCssClass();
}
self._setSubmenuIcon(value.length > 0);
self._bindModeEvents(self, true);
self._resetMarkupValue();
};
wijmenuitem.prototype._bindModeEvents = function (widget, createdUl) {
var self = this, menu = widget._getMenu(), o = menu.options;
if(createdUl) {
self._initUlCssClass();
self._setSubmenuIcon();
self._resetMarkupValue();
}
if(o.mode === "flyout") {
//if created an ul means the event of the li
//has been modified from an leaf to an node
//so there must be kill flyout at first
if(createdUl) {
self._killFlyout();
self._flyout();
} else {
widget._flyout();
}
} else {
self._setDrilldownUlStyle();
//reset scroll only if is add to an visible ul
if(widget.element.parent().is(':visible')) {
menu._resetScroll(widget._getParentOrMenu());
}
}
};
wijmenuitem.prototype._set_value = function (value, writeOnly) {
this.options.value = value;
};
wijmenuitem.prototype._set_text = function (value, writeOnly) {
var self = this, o = self.options;
if(value || writeOnly) {
self._setText(value);
} else {
o.text = self._getText();
}
};
wijmenuitem.prototype._set_navigateUrl = function (value, writeOnly) {
var self = this, o = self.options, link = self._getLink();
if(link.is('a')) {
if(value || writeOnly) {
link.attr('href', value);
} else {
o.navigateUrl = link.attr('href');
}
}
};
wijmenuitem.prototype._set_target = function (value, writeOnly) {
var self = this, o = self.options, link = self._getLink();
if(link.is('a')) {
if(o.target || writeOnly) {
link.attr('target', value);
} else {
o.target = link.attr('target') || '';
}
}
};
wijmenuitem.prototype._set_iconClass = function (value, writeOnly) {
var self = this, o = self.options, link, iconSpan, textSpan, text;
//is header or separator, do nothing
if(o.header === true || o.separator === true) {
return;
}
link = self._getLink();
iconSpan = link.find('span.' + o.wijCSS.wijmenuitemIcon);
if(value) {
//does not have the span, create it
if(iconSpan.length === 0) {
iconSpan = $("<span>");
textSpan = link.children("." + o.wijCSS.wijmenuText).wrap("<span>").parent();
textSpan.addClass(o.wijCSS.wijmenuText);
textSpan.prepend(iconSpan);
}
//have specified value, set cssClass as user specified value
iconSpan.addClass(value).addClass(o.wijCSS.wijmenuIconLeft).addClass(o.wijCSS.wijmenuitemIcon);
if(writeOnly) {
self._set_imagePosition(o.imagePosition);
}
} else {
//else value is not specified
if(iconSpan.length !== 0) {
iconSpan.remove();
textSpan = link.children("." + o.wijCSS.wijmenuText);
text = textSpan.text();
textSpan.html('');
textSpan.text(text);
}
}
//add class to link to fix tfs issue 24238
if(self._getMenuItemType() === MarkupType.other) {
//if (link && link.is("div")) {
link.addClass(o.wijCSS.wijmenuLink).addClass(o.wijCSS.cornerAll);
}
};
wijmenuitem.prototype._set_imagePosition = function (value, writeOnly) {
var self = this, o = self.options, link = self._getLink(), iconSpan = link.find('>span>span.' + o.wijCSS.wijmenuitemIcon), positionCss = value === 'right' ? o.wijCSS.wijmenuIconRight : o.wijCSS.wijmenuIconLeft;
if(iconSpan.length === 0) {
return;
}
iconSpan.removeClass(o.wijCSS.wijmenuIconRight).removeClass(o.wijCSS.wijmenuIconLeft).addClass(positionCss);
};
wijmenuitem.prototype._set_separator = function (value, writeOnly) {
var self = this, ele = self.element, o = self.options, link = self._getLink();
if(writeOnly && value === false) {
ele.html("").removeClass(o.wijCSS.wijmenuSeparator).removeClass(o.wijCSS.widget).removeClass(o.wijCSS.wijmenuItem).removeClass(o.wijCSS.stateDefault).removeClass(o.wijCSS.cornerAll);
self._createMenuItemMarkup(MarkupType.link).appendTo(ele);
} else if(value === true || link.length === 0) {
o.separator = true;
o.header = false;
//if is separator, modify html markup
self._createMenuItemMarkup(MarkupType.separator);
} else {
o.separator = false;
}
self._resetMarkupValue();
};
wijmenuitem.prototype._set_header = function (value, writeOnly) {
var self = this, ele = self.element, o = self.options, link = self._getLink();
if(writeOnly && value === false) {
o.header = false;
ele.html("").removeClass(o.wijCSS.header).removeClass(o.wijCSS.cornerAll).removeClass(o.wijCSS.widget).removeClass(o.wijCSS.wijmenuItem).removeClass(o.wijCSS.stateDefault);
self._createMenuItemMarkup(MarkupType.link).appendTo(ele);
} else if(value === true || link.is("h1,h2,h3,h4,h5")) {
o.header = true;
o.separator = false;
//if is header, modify the html markup
if(!link.is("h1,h2,h3,h4,h5")) {
//clear html element and add an h3 as header
link.remove();
link = self._createMenuItemMarkup(MarkupType.header);
ele.append(link);
}
} else {
o.header = false;
}
self._resetMarkupValue();
};
wijmenuitem.prototype._set_displayVisible = function (value) {
var self = this, ele = self.element;
if(value) {
ele.show();
} else {
ele.hide();
}
};
wijmenuitem.prototype._createMenuItemMarkup = function (markupType) {
var self = this, o = self.options, ele = self.element, result;
if(markupType === MarkupType.separator) {
//just clear html markup
//ele.html('');
ele.html('<span class="' + o.wijCSS.wijmenuSeparatorContent + '"> </span>');
return null;
} else if(markupType === MarkupType.header) {
result = $("<h3></h3>").text(o.text);
} else {
result = $('<a>').text(o.text);
}
return result;
};
wijmenuitem.prototype._getMenuItemType = function (newOptions) {
var self = this, o = self.options, link = self._getLink();
if(newOptions) {
o = $.extend({
}, o, newOptions);
}
if(o.separator === true) {
return MarkupType.separator;
}
if(o.header === true) {
return MarkupType.header;
}
//when neither specified options.separator nor options.header as true
//if markup is <li></li>
if(link.length === 0) {
if(o.text) {
//if text have specified
return MarkupType.link;
}
//else is separator
return MarkupType.separator;
}
if(link.is('a')) {
return MarkupType.link;
}
if(link.is('h1,h2,h3,h4,h5')) {
return MarkupType.header;
}
return MarkupType.other;
};
wijmenuitem.prototype._getOrSetOptionsValues = function () {
var self = this, ele = self.element, o = self.options, link = self._getLink(), type = self._getMenuItemType();
if(type === MarkupType.header) {
self._set_header(o.header);
self._set_text(o.text);
} else if(type === MarkupType.separator) {
self._set_separator(o.separator);
} else {
//if the markup is just an <li></li> create markup at first
if(link.length === 0) {
link = self._createMenuItemMarkup(type);
ele.append(link);
} else {
self._set_text(o.text);
}
self._resetMarkupValue();
self._set_navigateUrl(o.navigateUrl);
self._set_target(o.target);
}
self._set_displayVisible(o.displayVisible);
self._set_selected(o.selected);
};
wijmenuitem.prototype._getText = function () {
//get the text of the item
return this._getLink().text();
};
wijmenuitem.prototype._setText = function (text) {
var ele = this.element, o = this.options, link;
//have 4 kind of situations
//1 first time li created as widget, the markup like <li><a>text</a></li>
//2 the li has been created as widget, html markup like
// <li role="menuitem" class="ui-widget wijmo-wijmenu-item">
// <a class="wijmo-wijmenu-link ui-corner-all" aria-haspopup="">
// <span class="wijmo-wijmenu-text">menu item2</span></a></li>
//3 is an header mark up like <li><h3>text</h3></li>
//4 is an separator this situation don't need to set text
//find first-child a to fix tfs issue 24238
link = ele.find(":not(ul)a ." + o.wijCSS.wijmenuText + ":first");
//link = ele.find(".wijmo-wijmenu-text");
//end comments.
if(link.length !== 0) {
link.text(text);
return;
}
link = ele.children('h1,h2,h3,h4,h5').filter(':first');
if(link.length !== 0) {
link.text(text);
return;
}
link = ele.children('a:first');
if(link.length !== 0) {
link.text(text);
return;
}
};
wijmenuitem.prototype._createChildMenuItems = function () {
var self = this, ele = self.element, items = self._items, o = self.options, optionItemsLength, ul, childMenuCount, i, w, frame;
if(o.header === true || o.separator === true) {
return;
}
optionItemsLength = o.items.length;
ul = self._getSublist();
childMenuCount = ul.children('li').length;
// add iframe for preventing the submenu display behind the OCX control
frame = self.element.children('iframe.bgiframe');
if(frame.length === 0) {
frame = $('<iframe class="bgiframe" frameborder="0" tabindex="-1" src="javascript: false;" style="display:none;position:absolute;z-index:-1;top:0px;left:0px;opacity:0;" />');
self.element.append(frame);
}
// if the count of items more than li contained in html markup
if(optionItemsLength > childMenuCount) {
if(ul.length === 0) {
ul = $('<ul>').appendTo(ele);
self._resetMarkupValue();
}
for(i = 0; i < optionItemsLength - childMenuCount; i++) {
ul.append('<li>');
}
}
$.each(self._getChildren(), function (idx, child) {
var $li = $(child), options;
options = wijmenu._getMenuItemOptions(self.options, idx);
w = self._createItemWidget($li, options);
items.push(w);
self.options.items[idx] = w.options;
});
};
wijmenuitem.prototype._createItemWidget = function ($li, options) {
var self = this, itemWidgetName = self.widgetName;
//itemWidgetName = $.wijmo.wijmenu._itemWidgetName;
$li[itemWidgetName](options);
//Fix for jQuery UI 1.10
return $li.data($.camelCase(self.widgetFullName));
//return $li.data(self.widgetName);
};
wijmenuitem.prototype._initCssClass = function () {
var self = this, li = this.element, o = self.options, link = self._getLink(), type = self._getMenuItemType();
if(type !== MarkupType.separator) {
li.attr("role", "menuitem");
}
if(type === MarkupType.separator) {
li.addClass(o.wijCSS.wijmenuSeparator).addClass(o.wijCSS.stateDefault).addClass(o.wijCSS.cornerAll);
} else if(type === MarkupType.header) {
li.addClass(o.wijCSS.header).addClass(o.wijCSS.cornerAll);
} else {
if(type === MarkupType.link) {
if(!li.hasClass(o.wijCSS.wijmenuItem)) {
li.addClass(o.wijCSS.widget).addClass(o.wijCSS.wijmenuItem).addClass(o.wijCSS.stateDefault).addClass(o.wijCSS.cornerAll);
link.addClass(o.wijCSS.wijmenuLink).addClass(o.wijCSS.cornerAll);
link.wrapInner("<span>").children("span").addClass(o.wijCSS.wijmenuText);
}
} else {
li.addClass(o.wijCSS.widget).addClass(o.wijCSS.wijmenuItem).addClass(o.wijCSS.stateDefault).addClass(o.wijCSS.cornerAll);
}
self._setSubmenuIcon();
}
self._set_iconClass(o.iconClass);
self._set_imagePosition(o.imagePosition);
self._initUlCssClass();
};
wijmenuitem.prototype._initUlCssClass = function () {
var o = this.options;
this._getSublist().addClass(o.wijCSS.wijmenuList).addClass(o.wijCSS.content).addClass(o.wijCSS.cornerAll).addClass(o.wijCSS.helperClearFix).addClass(o.wijCSS.wijmenuChild).addClass(o.wijCSS.helperReset).hide();
};
wijmenuitem.prototype._setSubmenuIcon = function (hasSubmenu) {
var self = this, o = this.options, link = self._getLink(), menu = self._getMenu(), direction = menu.options.direction, submenuIcon = direction === "rtl" ? link.children("span." + o.wijCSS.icon + ":first") : link.children("span." + o.wijCSS.icon + ":last");
//if the arugment 'hasSubmenu' was not specified
if(hasSubmenu === undefined) {
hasSubmenu = wijmenu._hasVisibleSubMenus(self);
}
if(hasSubmenu && !link.is(":input")) {
if(submenuIcon.length === 0) {
if(direction === "rtl") {
submenuIcon = $("<span>").prependTo(link);
} else {
submenuIcon = $("<span>").appendTo(link);
}
}
if(self._isRoot() && menu.options.orientation === "horizontal" && menu.options.mode === 'flyout') {
submenuIcon.addClass(o.wijCSS.icon).addClass(o.wijCSS.iconArrowDown);
} else {
if(direction === "rtl") {
submenuIcon.addClass(o.wijCSS.icon).addClass(o.wijCSS.iconArrowLeft);
} else {
submenuIcon.addClass(o.wijCSS.icon).addClass(o.wijCSS.iconArrowRight);
}
}
} else {
submenuIcon.remove();
}
};
wijmenuitem.prototype._killFlyout = function () {
var ele = this.element.attr("role", ""), o = this.options;
ele.removeClass(o.wijCSS.wijmenuParent).unbind(".wijmenuEvent").unbind(".wijmenuitem").children(":first").unbind(".wijmenuEvent").unbind(".wijmenuitem").attr("aria-haspopup", "");
//add by chandler for unbinding ul mouseleave event
this._getSublist().unbind(".wijmenuEvent").unbind(".wijmenuitem");
$.each(this.getItems(), function () {
this._killFlyout();
});
};
wijmenuitem.prototype._getItemTriggerEvent = function () {
var self = this, ele = self.element, menu = self._getMenu(), o = menu.options, triggerEvent = "default";
if(o.trigger !== "") {
if(ele.is(o.trigger) || menu.element.is(o.trigger)) {
triggerEvent = o.triggerEvent;
} else {
ele.parents("." + o.wijCSS.wijmenuParent).each(function (i, n) {
if($(n).is(o.trigger)) {
triggerEvent = o.triggerEvent;
return false;
}
});
if(triggerEvent === "default" && self._isOuterTirggerEle()) {
triggerEvent = o.triggerEvent;
}
}
}
ele.data("triggerEvent", triggerEvent);
return triggerEvent;
};
wijmenuitem.prototype._isOuterTirggerEle = function () {
var menu = this._getMenu();
return wijmenu._getOuterElement(menu.options.trigger, "." + menu.options.wijCSS.wijmenu).length > 0;
};
wijmenuitem.prototype._flyout = function () {
var self = this, menu = self._getMenu(), o = menu.options, nameSpace = ".wijmenuitem", li = $(self.element).attr("aria-haspopup", true), showTimer, hideTimer, triggerEvent = self._getItemTriggerEvent(), link = li.children('a.' + o.wijCSS.wijmenuLink), subList = self._getSublist(), itemDisabled;
if(self.getItems().length > 0) {
subList.bind("mouseleave" + nameSpace, function (e) {
if(o.disabled) {
return;
}
hideTimer = setTimeout(function () {
self._hideCurrentSubmenu(e);
}, o.hideDelay);
});
li.addClass(self.options.wijCSS.wijmenuParent);
if(triggerEvent !== "default" && o.triggerEvent !== "mouseenter") {
switch(o.triggerEvent) {
case "click":
link.bind("click" + nameSpace, function (e) {
if(o.disabled || $(this).hasClass(o.wijCSS.stateDisabled)) {
return;
}
self._showFlyoutSubmenu(e);
});
break;
case "dblclick":
link.bind("dblclick" + nameSpace, function (e) {
if(o.disabled || $(this).hasClass(o.wijCSS.stateDisabled)) {
return;
}
self._showFlyoutSubmenu(e);
});
break;
case "rtclick":
link.bind("contextmenu" + nameSpace, function (e) {
if(o.disabled || $(this).hasClass(o.wijCSS.stateDisabled)) {
return;
}
self._showFlyoutSubmenu(e);
e.preventDefault();
});
break;
}
subList.data("notClose", true);
} else {
link.bind("mouseenter.wijmenuEvent", function (e) {
if(o.disabled || $(this).hasClass(o.wijCSS.stateDisabled)) {
return;
}
clearTimeout(hideTimer);
showTimer = setTimeout(function () {
self._displaySubmenu(e, null);
}, o.showDelay);
}).bind("mouseleave" + nameSpace, function (e) {
if(o.disabled || $(this).hasClass(o.wijCSS.stateDisabled)) {
return;
}
clearTimeout(showTimer);
if(!subList.is("ul")) {
subList = subList.children("ul:first");
}
hideTimer = setTimeout(function () {
self._hideSubmenu(false, e);
}, o.hideDelay);
});
if(self.getItems().length > 0) {
self._getSublist().bind("mouseenter" + nameSpace, function (e) {
if(o.disabled) {
return;
}
clearTimeout(hideTimer);
});
}
}
}
///when click the menu item hide the submenus.
link.bind("click.wijmenuEvent", function (e) {
itemDisabled = link.hasClass(o.wijCSS.stateDisabled);
if(o.disabled || itemDisabled) {
return;
}
if(link.is("a")) {
if(self._getSublist().length === 0) {
menu._hideAllMenus(e);
} else if(!(o.trigger !== "" && li.data("triggerEvent") !== "default" && o.triggerEvent !== "mouseenter")) {
menu._hideAllMenus(e);
} else {
var curList = menu._currentMenuList, item, j;
if(curList !== undefined) {
item = li;
if(self._getSublist().length === 0) {
for(j = curList.length; j > 0; j--) {
if(curList[j - 1] === self) {
break;
} else {
curList[j - 1]._hideSubmenu(false, e);
}
}
}
}
}
menu.activate(e, self);
}
menu.select(e);
if(link.attr("href") === "#") {
e.preventDefault();
}
}).bind("focusin.wijmenuEvent", function (e) {
itemDisabled = link.hasClass(o.wijCSS.stateDisabled);
if(o.disabled || itemDisabled) {
return;
}
if(link.is("a")) {
menu.activate(e, self);
}
});
$.each(self.getItems(), function () {
this._flyout();
});
};
wijmenuitem.prototype._hideSubmenu = function (hideImmediately, e) {
var self = this, menu = self._getMenu(), o = menu.options, animations = wijmenu.animations, animationOptions, hideAnimation, list, sublist = self._getSublist(), link = self._getLink(), frame = self.element.children("iframe.bgiframe"), frameAnimationOptions;
if(!link.data("subMenuOpened")) {
return;
}
if(!menu._trigger("hidding", e, self)) {
return;
}
if(link.is("." + o.wijCSS.wijmenuLink)) {
link.data("subMenuOpened", false);
link.removeClass(o.wijCSS.stateActive);
}
if($.fn.wijhide && hideImmediately !== true) {
animationOptions = {
context: sublist,
show: false
};
frameAnimationOptions = {
context: frame,
show: false
};
hideAnimation = $.extend({
}, o.animation, o.hideAnimation);
sublist.wijhide(hideAnimation, animations, animationOptions, null, function () {
menu._setZindex(sublist, null);
sublist.attr("aria-hidden", true);
menu._trigger("hidden", e, self);
});
frame.wijhide(hideAnimation, animations, frameAnimationOptions, null, null);
} else {
sublist.hide().attr("aria-hidden", true);
menu._setZindex(sublist, null);
menu._trigger("hidden", e, self);
frame.hide();
}
//menu.element.data("shown", false);
list = menu._currentMenuList;
if(list) {
list = $.makeArray($.map(list, function (n) {
return n && (n === self) ? null : n;
}));
menu._currentMenuList = $.makeArray(list);
}
};
wijmenuitem.prototype._displaySubmenu = function (e, callback) {
var self = this, menu = self._getMenu(), o = menu.options, animationOptions, direction, showAnimation, animations = wijmenu.animations, haveNoVisibleChild, link = self._getLink(), sublist = self._getSublist(), frame, frameAnimationOptions;
//modified for supporting displayVisible in li
haveNoVisibleChild = !wijmenu._hasVisibleSubMenus(self);
if(sublist.is(":visible") || haveNoVisibleChild) {
return;
}
if(!menu._trigger("showing", e, self)) {
return;
}
//menu._trigger("showing", e, self);
if(link.is("a." + o.wijCSS.wijmenuLink)) {
link.data("subMenuOpened", true);
}
sublist.show();
frame = self.element.children('iframe.bgiframe');
self._setMenuItemPosition();
self._setIframeBounds(sublist, frame);
menu.nowIndex++;
menu._setZindex(sublist, menu.nowIndex);
sublist.hide();
animationOptions = {
context: sublist,
show: true
};
frameAnimationOptions = {
context: frame,
show: true
};
direction = o.direction === "rtl" ? "right" : "left";
if(o.orientation === "horizontal") {
if(self._isRoot()) {
direction = "up";
}
}
showAnimation = $.extend({
}, {
option: {
direction: direction
}
}, o.animation, o.showAnimation);
wijmenu._animateFlyoutMenu(showAnimation, animationOptions, function () {
//fix for tfs issue 20975
if(sublist.is(":hidden")) {
self._hideSubmenu(true, e);
}
//add the event 'shown'
menu._trigger("shown", e, self);
if(callback) {
callback();
}
});
frame.wijshow(showAnimation, animations, frameAnimationOptions, null, null);
menu._isClickToOpen = o.triggerEvent === "click";
if(menu._currentMenuList === undefined) {
menu._currentMenuList = [];
}
menu._currentMenuList.push(self);
};
wijmenuitem.prototype._setMenuItemPosition = function () {
var self = this, sublist = self._getSublist(), pOption = self._getMenuItemPosition(), obj = {
of: this._getLink()
};
sublist.css({
left: '0',
top: '0',
position: 'absolute'
});
sublist.position($.extend(obj, pOption));
};
wijmenuitem.prototype._getMenuItemPosition = function () {
var self = this, menu = this._getMenu(), o = menu.options, direction = o.direction, pOption = direction === "rtl" ? {
my: 'right top',
at: 'left top'
} : {
my: 'left top',
at: 'right top'
};
//If the menu's orientation is horizontal,
//set the first level submenu's position to horizontal.
if(o.orientation === "horizontal") {
if(self._isRoot()) {
pOption = direction === "rtl" ? {
my: 'right top',
at: 'right bottom'
} : {
my: 'left top',
at: 'left bottom'
};
}
}
pOption = $.extend(pOption, o.position);
return pOption;
};
wijmenuitem.prototype._getChildren = function () {
return this._getSublist().children('li');//.filter('li');
};
wijmenuitem.prototype._setDrilldownUlStyle = function () {
var self = this, o = self.options, sublist = self._getSublist(), menu = self._getMenu(), width = menu.domObject.menucontainer.width();
if(menu.options.direction === "rtl") {
sublist.css({
width: width,
left: -width
});
} else {
sublist.css({
width: width,
left: width
});
}
sublist.addClass(o.wijCSS.content);
$.each(self.getItems(), function (i, n) {
if(n.getItems().length) {
this._setDrilldownUlStyle();
}
});
};
wijmenuitem.prototype._getMenu = function () {
var self = this, result = self._menu, parent, tmp;
//if result is empty, get menu object from parent until body
if(!result) {
parent = self.element.parent();
while(!parent.is('body') && parent.length > 0) {
//tmp = parent.data($.wijmo.wijmenu._menuWidgetName);
tmp = parent.data("wijmomenu");
if(tmp) {
//result = tmp;
result = parent.data(tmp);
self._menu = result;
return result;
}
parent = parent.parent();
}
//if cannot find menu, throw an exception
throw 'An menuitem must be a child of menu';
}
return result;
};
wijmenuitem.prototype.getParent = function () {
/// <summary>
/// Gets the parent of the current item,
/// the method will return null when current item is a top item
/// </summary>
var self = this, ele = self.element, menu, result, parent;
result = self._parent;
if(result !== undefined) {
return result;
}
//find an parent li which contains cache 'wijmenuitem'
parent = ele.parents('li:first');
if(parent.length > 0) {
result = wijmenu._getItemWidget(parent);
if(result !== undefined) {
self._parent = result;
return result;
}
}
menu = self._getMenu();
//the element at the top level
if(menu._getSublist().get(0) === ele.parent().get(0)) {
self._parent = null;
return null;
}
throw 'An menuitem must be a child of menu or another menuitem';
};
wijmenuitem.prototype._getParentOrMenu = function () {
return this.getParent() || this._getMenu();
};
wijmenuitem.prototype._getField = function (key) {
return this.element.data(key);
};
wijmenuitem.prototype._setField = function (key, value) {
return this.element.data(key, value);
};
wijmenuitem.prototype._innerDestroy = function (invokedByParent) {
var self = this, o = self.options, item = self.element, link, items = self.getItems(), i = items.length - 1;
//remove all classses of li
item.removeClass(o.wijCSS.widget).removeClass(o.wijCSS.wijmenuItem).removeClass(o.wijCSS.stateDefault).removeClass(o.wijCSS.cornerAll).removeClass(o.wijCSS.wijmenuParent).removeClass(o.wijCSS.header).removeClass(o.wijCSS.wijmenuSeparator);
link = item.children("." + o.wijCSS.wijmenuLink);
link.removeClass(o.wijCSS.wijmenuLink).removeClass(o.wijCSS.cornerAll).removeClass(o.wijCSS.stateFocus).removeClass(o.wijCSS.stateHover).removeClass(o.wijCSS.stateActive).html(link.children("." + o.wijCSS.wijmenuText).html()).unbind(".wijmenuitem").unbind(".wijmenuEvent");
item.children("ul").removeClass(o.wijCSS.wijmenuList).removeClass(o.wijCSS.content).removeClass(o.wijCSS.cornerAll).removeClass(o.wijCSS.helperClearFix).removeClass(o.wijCSS.wijmenuChild).removeClass(o.wijCSS.helperReset).attr("role", "").attr("aria-activedescendant", "").show().css({
left: "",
top: "",
position: ""
}).attr("hidden", "");
//add by chandler
item.removeAttr("role");
link.removeAttr("aria-haspopup");
//if is not invoked recursively from parent,
//which means there must remove self from parent._items
if(!invokedByParent) {
self._removeFromParentCollection();
}
item.removeData('menu').removeData('parent');
if(item.children('iframe.bgiframe').length !== 0) {
item.children('iframe.bgiframe').remove();
}
//destroy child menus recursively
//$.each(self.getItems() || [], function (i, n) {
// n.destroy(true);
//});
for(; i >= 0; i--) {
items[i].destroy(true);
}
self._items.length = 0;
self._resetMarkupValue();
};
wijmenuitem.prototype.destroy = function (invokedByParent) {
/// <summary>
/// The destroy() method removes the wijmenu functionality completely
/// and returns the element back to its pre-init state.
/// </summary>
var self = this;
self._innerDestroy(invokedByParent);
//end for disabled option
_super.prototype.destroy.call(this);
};
wijmenuitem.prototype._getFirstSelectableSubItem = function () {
return wijmenu._getFirstSelectableSubItem(this);
};
wijmenuitem.prototype._getLastSelectableSubItem = function () {
return wijmenu._getLastSelectableSubItem(this);
};
wijmenuitem.prototype.next = function () {
///<summary>
/// Gets the next selectable item. The first item will be selected
/// if none is active or the last one is active.
/// return null if none is selectable in next.
///</summary>
var self = this, items = self._getParentOrMenu().getItems(), i, o, indexOfItem = $.inArray(self, items);
if(indexOfItem === -1) {
throw 'cannot find item from the parent collection';
}
for(i = indexOfItem + 1; i < items.length; i++) {
o = items[i].options;
if(o.displayVisible !== false && !o.header && !o.separator) {
return items[i].element;
}
}
return null;
};
wijmenuitem.prototype.previous = function () {
///<summary>
/// Get the previous selectable item.
/// It selects the last item if none is active or the first one is active.
/// It returns null if no previous item is selectable.
///</summary>
/// Code Example:
/// $(".selector").wijmenu("previous");
var self = this, items = self._getParentOrMenu().getItems(), i, o, indexOfItem = $.inArray(self, items);
if(indexOfItem === -1) {
throw 'cannot find item from the parent collection';
}
for(i = indexOfItem - 1; i >= 0; i--) {
o = items[i].options;
if(o.displayVisible !== false && !o.header && !o.separator) {
return items[i].element;
}
}
return null;
};
wijmenuitem.prototype._removeFromParentCollection = function () {
var self = this, parent, deleteFromMenu = false, indexOfSelf;
parent = self.getParent();
if(parent === null) {
parent = self._getMenu();
deleteFromMenu = true;
}
indexOfSelf = $.inArray(self, parent.getItems());
if(indexOfSelf === -1) {
return;
}
//remove self from parent.getItems()
wijmenu._changeCollection(indexOfSelf, parent.getItems(), parent.options.items, null);
if(parent.getItems().length === 0) {
if(!deleteFromMenu) {
parent._setSubmenuIcon(false);
parent._resetMarkupValue();
}
parent.element.children('ul').remove();
}
};
wijmenuitem.prototype._resetMarkupValue = function () {
this._sublist = null;
this._link = null;
};
wijmenuitem.prototype._hideCurrentSubmenu = function (e) {
var self = this, subList = self._getSublist();
if(subList.length === 0) {
return;
}
if(!subList.data("notClose")) {
self._hideSubmenu(false, e);
}
$.each(self.getItems(), function () {
this._hideCurrentSubmenu(e);
});
};
wijmenuitem.prototype._showFlyoutSubmenu = function (e, callback) {
var self = this, menu = this._getMenu(), curList = menu._currentMenuList, i;
if(curList !== undefined) {
for(i = curList.length; i > 0; i--) {
if(curList[i - 1] === self.getParent()) {
break;
} else {
curList[i - 1]._hideSubmenu(false, e);
}
}
}
self._displaySubmenu(e, callback);
};
wijmenuitem.prototype.getItems = function () {
///<summary>
/// Gets the collection of child items.
///</summary>
return this._items;
};
wijmenuitem.prototype._getSublist = function () {
var self = this;
if(!self._sublist) {
self._sublist = this.element.children('ul:first');
}
return self._sublist;
};
wijmenuitem.prototype._getLink = function () {
var self = this;
if(!self._link) {
self._link = this.element.children(':first');
}
return self._link;
};
wijmenuitem.prototype._isRoot = function () {
return this.getParent() === null;
};
wijmenuitem.prototype.add = /** Adds a child menuItem to the menuItem.*/
function (menuItem, position) {
wijmenu._add(this, menuItem, position);
};
wijmenuitem.prototype.remove = /** Remove an item from the menu.*/
function (index) {
wijmenu._remove(this, index);
};
wijmenuitem.prototype._setIframeBounds = /** set the bounds for the frame by the bounds and box-shadow setting of the sub menu */
function (sublist, frame) {
var self = this, sublistShadowBox, leftOffset = 0, rightOffset = 0, topOffset = 0, bottomeOffset = 0, shadowRadius, shadowBlurRadius, yOffset, xOffSet, arrayLength, browser = $.browser;
if(!(browser.msie && parseFloat($.browser.version) < 9)) {
sublistShadowBox = sublist.css("box-shadow").split(' ');
arrayLength = sublistShadowBox.length;
if(arrayLength > 1) {
if(browser.msie && arrayLength < 4) {
shadowRadius = 0;
} else {
shadowRadius = self._parsePxToNumber(browser.msie ? sublistShadowBox[3] : sublistShadowBox[arrayLength - 1]);
}
if(browser.msie && arrayLength < 3) {
shadowBlurRadius = 0;
} else {
shadowBlurRadius = 0.3 * self._parsePxToNumber(browser.msie ? sublistShadowBox[2] : sublistShadowBox[arrayLength - 2]);
}
yOffset = self._parsePxToNumber(browser.msie ? sublistShadowBox[1] : sublistShadowBox[arrayLength - 3]);
xOffSet = self._parsePxToNumber(browser.msie ? sublistShadowBox[0] : sublistShadowBox[arrayLength - 4]);
leftOffset = shadowBlurRadius + shadowRadius - xOffSet;
leftOffset = leftOffset >= 0 ? leftOffset : 0;
rightOffset = shadowBlurRadius + shadowRadius + xOffSet;
rightOffset = rightOffset >= 0 ? rightOffset : 0;
topOffset = shadowBlurRadius + shadowRadius - yOffset;
topOffset = topOffset >= 0 ? topOffset : 0;
bottomeOffset = shadowBlurRadius + shadowRadius + yOffset;
bottomeOffset = bottomeOffset >= 0 ? bottomeOffset : 0;
}
}
frame.css({
'width': sublist.outerWidth(true) + leftOffset + rightOffset + 'px',
'height': sublist.outerHeight(true) + topOffset + bottomeOffset + 'px',
'left': self._parsePxToNumber(sublist.css("left")) - leftOffset + 'px',
'top': self._parsePxToNumber(sublist.css("top")) - topOffset + 'px'
});
};
wijmenuitem.prototype._parsePxToNumber = /** Parse string setting to number */
function (px) {
var pxIndex = px.indexOf("px");
if(!pxIndex || pxIndex === -1) {
return 0;
} else {
return parseFloat(px.substr(0, pxIndex));
}
};
return wijmenuitem;
})(wijmo.wijmoWidget);
menu.wijmenuitem = wijmenuitem;
//#region menuitem options
wijmenuitem.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, {
initSelector: /** Selector option for auto self initialization.*/
":jqmData(role='wijmenuitem')",
wijCSS: /** wijmenu css, extend from $.wijmo.wijCSS.*/
{
wijmenuitemIcon: "wijmenuitem-icon",
wijmenuParent: "wijmo-wijmenu-parent",
wijmenuLink: "wijmo-wijmenu-link",
wijmenuText: "wijmo-wijmenu-text",
wijmenuList: "wijmo-wijmenu-list",
wijmenuItem: "wijmo-wijmenu-item",
wijmenuSeparator: "wijmo-wijmenu-separator",
wijmenuIconLeft: "wijmo-wijmenu-icon-left",
wijmenuIconRight: "wijmo-wijmenu-icon-right",
wijmenuChild: "wijmo-wijmenu-child",
wijmenuSeparatorContent: "wijmo-wijmenu-separator-content"
},
wijMobileCSS: {
header: "ui-header ui-bar-c",
content: "ui-body ui-body-c",
stateDefault: "ui-btn-up-c",
stateHover: "ui-btn-down-c",
stateActive: "ui-btn-down-c"
},
header: /** A value that determines whether the menu item is a header item.*/
false,
separator: /** A value that determines whether the item is a separator.*/
false,
value: /** Sets the menuItem's value.*/
'',
text: /** Sets the node's text.*/
"",
navigateUrl: /** The menuItem's navigate url.*/
'',
target: /** Gets or sets the target of the link item.*/
'',
iconClass: /** Gets or sets the icon css class to the menuitem.*/
'',
imagePosition: /** Gets or sets which side, left or right, the image will
* be rendered from the menu item.
*/
'',
displayVisible: /** A value that indicates whether to show the menu.*/
true,
selected: /** A value that determines whether the item has beend selected.*/
false,
items: /** The options of child items.*/
null
});
//#endregion
$.wijmo.registerWidget(widgetName, wijmenu.prototype);
$.widget("wijmo.wijmenuitem", $.wijmo.widget, wijmenuitem.prototype);
})(wijmo.menu || (wijmo.menu = {}));
var menu = wijmo.menu;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts"/>
/// <reference path="../wijsuperpanel/jquery.wijmo.wijsuperpanel.ts"/>
/*globals $, jQuery, document, window, location, wijmoASPNetParseOptions*/
/*
* Depends:
* jquery-1.4.2.js
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.position.js
* jquery.effects.core.js
* jquery.cookie.js
* jquery.wijmo.wijsuperpanel.js
* jquery.wijmo.wijutil.js
*/
(function (tabs) {
"use strict";
var $ = jQuery;
var tabId = 0, listId = 0, effects = $.effects ? $.effects : $, effectsSave = effects.save, effectsRestore = effects.restore, effectsCreateWrapper = effects.createWrapper, effectsRemoveWrapper = effects.removeWrapper, getNextTabId = function () {
return ++tabId;
}, getNextListId = function () {
return ++listId;
};
/** @widget*/
var wijtabs = (function (_super) {
__extends(wijtabs, _super);
function wijtabs() {
_super.apply(this, arguments);
}
wijtabs.prototype._setOption = function (key, value) {
_super.prototype._setOption.call(this, key, value);
switch(key) {
case 'selected':
if(this.options.collapsible && value === this.options.selected) {
return;
}
this.select(value);
break;
case 'alignment':
this._innerDestroy(true);
this._tabify(true);
break;
default:
this._tabify(false);
break;
}
};
wijtabs.prototype._create = function () {
var _this = this;
var o = this.options;
if(this.element.is(":hidden") && this.element.wijAddVisibilityObserver) {
this.element.wijAddVisibilityObserver(function () {
if(_this.element.wijRemoveVisibilityObserver) {
_this.element.wijRemoveVisibilityObserver();
}
var dataObj = _this.element.data("wijtabs"), wijmoDataObj = _this.element.data("wijmoWijtabs");
_this._innerDestroy(true);
_this.element.data("wijtabs", dataObj);
_this.element.data("wijmoWijtabs", wijmoDataObj);
_this._tabify(true);
}, "wijtabs");
}
this._tabify(true);
if(o.disabledstate || o.disabled) {
this.disable();
}
_super.prototype._create.call(this);
};
wijtabs.prototype.destroy = /** The destroy() method will remove the wijtabs functionality completely
* and will return the element to its pre-init state.
*/
function () {
this._innerDestroy();
_super.prototype.destroy.call(this);
};
wijtabs.prototype._tabify = function (init) {
this.list = this.element.children('ol,ul').eq(0);
this.lis = $('li:has(a)', this.list);
this.anchors = this.lis.map(function () {
return $('a', this)[0];
});
this.panels = $([]);
var self = this, o = self.options, fragmentId = /^#.+/, tabsAlign, panelCorner, content, i, li, addState, removeState, showTab, hideTab;
// Safari 2 reports '#' for an empty hash
$.each(self.anchors, function (i, a) {
var href = $(a).attr('href') || "", hrefBase = // For dynamically created HTML that contains a hash as href IE < 8
// expands such href to the full page url with hash and then
// misinterprets tab as ajax.
// Same consideration applies for an added tab with a fragment identifier
// since a[href=#fragment-identifier] does unexpectedly not match.
// Thus normalize href attribute...
href.split('#')[0], baseEl, id, $panel;
//if (hrefBase && (hrefBase === location.toString().split('#')[0] ||
if(hrefBase && (hrefBase === location.toString().split('#')[0] || (baseEl = $('base')[0]) && hrefBase === baseEl.href)) {
href = a.hash;
a.href = href;
}
// inline tab
if(fragmentId.test(href)) {
self.panels = self.panels.add(self._sanitizeSelector(href), self.element);
} else // remote tab
// prevent loading the page itself if href is just "#"
if(href !== '#') {
$.data(a, 'href.tabs', href)// required for restore on destroy
;
$.data(a, 'load.tabs', href.replace(/#.*$/, ''))// mutable data
;
id = self._tabId(a);
a.href = '#' + id;
$panel = $('#' + id);
if(!$panel.length) {
$panel = $(o.panelTemplate || self._defaults.panelTemplate).attr('id', id).addClass(o.wijCSS.tabsPanel).addClass(o.wijCSS.content).addClass(o.wijCSS.cornerBottom).insertAfter(self.panels[i - 1] || self.list);
$panel.data('destroy.tabs', true);
}
self.panels = self.panels.add($panel);
} else// invalid tab href
{
o.disabledIndexes.push(i);
}
});
tabsAlign = this._getAlignment(true);
panelCorner = this._getAlignment(false);
// initialization from scratch
if(init) {
// ARIA
this.list.attr("role", "tablist");
this.lis.attr("role", "tab");
this.panels.attr("role", "tabpanel");
this.element.addClass(o.wijCSS.tabs).addClass(o.wijCSS.wijtabs).addClass(o.wijCSS.widget).addClass(o.wijCSS.content).addClass(o.wijCSS.cornerAll).addClass(o.wijCSS.helperClearFix).addClass(o.wijCSS.tabsPanel).addClass(o.wijCSS.tabsPanel).addClass(o.wijCSS["tabs" + tabsAlign]);
this.list.addClass(o.wijCSS.tabsNav).addClass(o.wijCSS.helperReset).addClass(o.wijCSS.helperClearFix).addClass(o.wijCSS.header).addClass(o.wijCSS.cornerAll);
this.lis.addClass(o.wijCSS.stateDefault).addClass(o.wijCSS["corner" + tabsAlign]);
this.panels.addClass(o.wijCSS.tabsPanel).addClass(o.wijCSS.content).addClass(o.wijCSS["corner" + panelCorner]);
// attach necessary classes for styling
switch(tabsAlign) {
case 'Bottom':
this.list.appendTo(this.element);
break;
case 'Left':
content = $('<div/>').addClass(o.wijCSS.wijtabsContent).appendTo(this.element);
this.panels.appendTo(content);
break;
case 'Right':
content = $('<div/>').addClass(o.wijCSS.wijtabsContent).insertBefore(this.list);
this.panels.appendTo(content);
break;
case 'Top':
this.list.prependTo(this.element);
break;
}
if(o.sortable && this.list.sortable) {
this.list.sortable({
axis: (tabsAlign === 'Top' || tabsAlign === 'Bottom') ? "x" : "y"
});
}
// Selected tab
// use "selected" option or try to retrieve:
// 1. from fragment identifier in url
// 2. from cookie
// 3. from selected class attribute on <li>
if(o.selected === undefined) {
if(location.hash) {
$.each(this.anchors, function (i, a) {
if(a.hash === location.hash) {
o.selected = i;
return false;// break
}
});
}
if(typeof o.selected !== 'number' && o.cookie) {
o.selected = parseInt(self._cookie(undefined, undefined), 10);
}
if(typeof o.selected !== 'number' && this.lis.filter('.' + o.wijCSS.tabsActive).length) {
o.selected = this.lis.index(this.lis.filter('.' + o.wijCSS.tabsActive));
}
o.selected = o.selected || (this.lis.length ? 0 : -1);
} else if(o.selected === null) {
// usage of null is deprecated, TODO remove in next release
o.selected = -1;
}
// sanity check - default to first tab...
o.selected = ((o.selected >= 0 && this.anchors[o.selected]) || o.selected < 0) ? o.selected : 0;
// Take disabling tabs via class attribute from HTML
// into account and update option properly.
// A selected tab cannot become disabled.
o.disabledIndexes = $.unique(o.disabledIndexes.concat($.map(this.lis.filter('.' + o.wijCSS.stateDisabled), function (n, i) {
return self.lis.index(n);
}))).sort();
if($.inArray(o.selected, o.disabledIndexes) !== -1) {
o.disabledIndexes.splice($.inArray(o.selected, o.disabledIndexes), 1);
}
// highlight selected tab
this.panels.addClass(o.wijCSS.wijtabsHide).attr('aria-hidden', true);
this.lis.removeClass(o.wijCSS.tabsActive).removeClass(o.wijCSS.stateActive).attr('aria-selected', false);
// check for length avoids error when initializing empty list
if(o.selected >= 0 && this.anchors.length) {
this.panels.eq(o.selected).removeClass(o.wijCSS.wijtabsHide).attr('aria-hidden', false);
this.lis.eq(o.selected).addClass(o.wijCSS.tabsActive).addClass(o.wijCSS.stateActive).attr('aria-selected', true);
// seems to be expected behavior that the show callback is fired
self.element.queue("tabs", function () {
if(self.element.wijTriggerVisibility) {
$(self.panels[o.selected]).wijTriggerVisibility();
}
self._trigger('show', null, self._ui(self.anchors[o.selected], self.panels[o.selected]));
});
this.load(o.selected);
}
// clean up to avoid memory leaks in certain versions of IE 6
$(window).bind('unload', function () {
if(self.lis) {
self.lis.add(self.anchors).unbind('.tabs');
}
self.lis = self.anchors = self.panels = null;
});
} else {
// update selected after add/remove
o.selected = this.lis.index(this.lis.filter('.' + o.wijCSS.tabsActive));
}
// update collapsible
this.element[o.collapsible ? 'addClass' : 'removeClass'](o.wijCSS.tabsCollapsible);
// set or update cookie after init and add/remove respectively
if(o.cookie) {
this._cookie(o.selected, o.cookie);
}
// disable tabs
//for (i = 0; (li = this.lis[i]); i++) {
for(i = 0; i < this.lis.length; i++) {
li = this.lis[i];
$(li)[$.inArray(i, o.disabledIndexes) !== -1 && !$(li).hasClass(o.wijCSS.tabsActive) ? 'addClass' : 'removeClass'](o.wijCSS.stateDisabled);
if($(li).hasClass(o.wijCSS.stateDisabled)) {
$(li).attr('aria-disabled', true);
}
}
// reset cache if switching from cached to not cached
if(o.cache === false) {
this.anchors.removeData('cache.tabs');
}
// remove all handlers before, tabify may run on existing tabs
// after add or option change
this.lis.add(this.anchors).unbind('.tabs');
if(!o.disabledState && !o.disabled && o.event !== 'mouseover') {
addState = function (state, el) {
if(el.is(':not(.' + o.wijCSS.stateDisabled + ')')) {
el.addClass(state);
}
};
removeState = function (state, el) {
el.removeClass(state);
};
this.lis.bind('mouseover.tabs', function () {
addState(o.wijCSS.stateHover, $(this));
});
this.lis.bind('mouseout.tabs', function () {
removeState(o.wijCSS.stateHover, $(this));
});
this.anchors.bind('focus.tabs', function () {
self.lis.filter("." + o.wijCSS.stateFocus).removeClass(o.wijCSS.stateFocus);
addState(o.wijCSS.stateFocus, $(this).closest('li'));
});
this.anchors.bind('blur.tabs', function () {
removeState(o.wijCSS.stateFocus, $(this).closest('li'));
});
}
if(o.showOption === undefined || o.showOption === null) {
o.showOption = {
};
}
this._normalizeBlindOption(o.showOption);
if(o.hideOption === undefined || o.hideOption === null) {
o.hideOption = {
};
}
this._normalizeBlindOption(o.hideOption);
// Show a tab...
showTab = ((o.showOption.blind || o.showOption.fade) && o.showOption.duration > 0) ? function (clicked, $show) {
$(clicked).closest('li').addClass(o.wijCSS.tabsActive).addClass(o.wijCSS.stateActive).attr('aria-selected', true);
self._showContent();
$show.removeClass(o.wijCSS.wijtabsHide).attr('aria-hidden', false);
if(tabsAlign === 'Top' || tabsAlign === 'Bottom') {
var props = {
duration: o.showOption.duration,
height: 'toggle',
opacity: 'toggle'
};
if(!o.showOption.blind) {
delete props.height;
}
if(!o.showOption.fade) {
delete props.opacity;
}
// avoid flicker that way
$show.hide().removeClass(o.wijCSS.wijtabsHide).attr('aria-hidden', false).animate(props, o.showOption.duration || 'normal', function () {
self._resetStyle($show);
if($show.wijTriggerVisibility) {
$show.wijTriggerVisibility();
}
self._trigger('show', null, self._ui(clicked, $show[0]));
});
} else {
self._showContent();
self._blindPanel($show, 'show');
}
} : function (clicked, $show) {
$(clicked).closest('li').addClass(o.wijCSS.tabsActive).addClass(o.wijCSS.stateActive).attr('aria-selected', true);
self._showContent();
$show.removeClass(o.wijCSS.wijtabsHide).attr('aria-hidden', false);
if($show.wijTriggerVisibility) {
$show.wijTriggerVisibility();
}
self._trigger('show', null, self._ui(clicked, $show[0]));
};
// Hide a tab, $show is optional...
hideTab = ((o.hideOption.blind || o.hideOption.fade) && o.hideOption.duration > 0) ? function (clicked, $hide) {
if(tabsAlign === 'Top' || tabsAlign === 'Bottom') {
var props = {
duration: o.hideOption.duration,
height: 'toggle',
opacity: 'toggle'
};
if(!o.hideOption.blind) {
delete props.height;
}
if(!o.hideOption.fade) {
delete props.opacity;
}
$hide.animate(props, o.hideOption.duration || 'normal', function () {
self.lis.removeClass(o.wijCSS.tabsActive).removeClass(o.wijCSS.stateActive).attr('aria-selected', false);
$hide.addClass(o.wijCSS.wijtabsHide).attr('aria-hidden', true);
self._resetStyle($hide);
self.element.dequeue("tabs");
});
} else {
self._saveLayout();
self._blindPanel($hide, 'hide');
}
} : function (clicked, $hide, $show) {
self.lis.removeClass(o.wijCSS.tabsActive).removeClass(o.wijCSS.stateActive).attr('aria-selected', false);
self._hideContent();
$hide.addClass(o.wijCSS.wijtabsHide).attr('aria-hidden', true);
self.element.dequeue("tabs");
};
// attach tab event handler, unbind to avoid duplicates from former tabifying
if(!o.disabledState && !o.disabled) {
this.anchors.bind(o.event + '.tabs', function () {
var el = this, $li = $(this).closest('li'), $hide = self.panels.filter(':not(.' + o.wijCSS.wijtabsHide + ')'), $show = $(self._sanitizeSelector(this.hash), self.element);
// If tab is already selected and not collapsible or tab disabled or
// or is already loading or click callback returns false stop here.
// Check if click handler returns false last so that it is not
// executed for a disabled or loading tab!
if(($li.hasClass(o.wijCSS.tabsActive) && !o.collapsible) || $li.hasClass(o.wijCSS.stateDisabled) || $li.hasClass(o.wijCSS.tabsLoading) || self._trigger('select', null, self._ui(this, $show[0])) === false) {
this.blur();
return false;
}
o.selected = self.anchors.index(this);
self.abort();
// if tab may be closed
if(o.collapsible) {
if($li.hasClass(o.wijCSS.tabsActive)) {
o.selected = -1;
if(o.cookie) {
self._cookie(o.selected, o.cookie);
}
self.element.queue("tabs", function () {
hideTab(el, $hide);
}).dequeue("tabs");
this.blur();
return false;
} else if(!$hide.length) {
if(o.cookie) {
self._cookie(o.selected, o.cookie);
}
self.element.queue("tabs", function () {
showTab(el, $show);
});
// TODO make passing in node possible,
// see also http://dev.jqueryui.com/ticket/3171
self.load(self.anchors.index(this));
this.blur();
return false;
}
}
if(o.cookie) {
self._cookie(o.selected, o.cookie);
}
// show new tab
if($show.length) {
if($hide.length) {
self.element.queue("tabs", function () {
hideTab(el, $hide);
});
}
self.element.queue("tabs", function () {
showTab(el, $show);
});
self.load(self.anchors.index(this));
} else {
throw 'jQuery UI Tabs: Mismatching fragment identifier.';
}
// Prevent IE from keeping other link focussed when using
// the back button and remove dotted border from clicked link.
// This is controlled via CSS in modern browsers;
// blur() removes focus from address bar in Firefox which can
// become a usability and annoying problem with tabs('rotate').
if($.browser.msie) {
this.blur();
}
});
}
this._initScroller();
// disable click in any case
this.anchors.bind('click.tabs', function () {
return false;
});
};
wijtabs.prototype._blindPanel = function (panel, mode) {
var self = this, o = self.options, content = panel.parent('.' + o.wijCSS.wijtabsContent), props = [
'position',
'top',
'left',
'width'
], blindOption = mode === 'show' ? o.showOption : o.hideOption, wrapper, a, listWidth;
if(!content.length) {
return;
}
self.list.width(self.list.width());
//$.effects.save(panel, props);
if(effectsSave) {
effectsSave(panel, props);
}
panel.show()// Save & Show
;
if(mode === 'show') {
// Show
panel.removeClass(o.wijCSS.wijtabsHide).attr('aria-hidden', false);
panel.width(self.element.data('panel.width'));
} else {
panel.width(panel.width());
}
// Create Wrapper
//wrapper = $.effects.createWrapper(panel).css({ overflow: 'hidden' });
if(effectsCreateWrapper) {
wrapper = effectsCreateWrapper(panel).css({
overflow: 'hidden'
});
} else {
wrapper = $('<div></div>');
}
if(mode === 'show') {
// Shift
wrapper.css($.extend({
width: 0
}, blindOption.fade ? {
opacity: 0
} : {
}));
}
// Animation
a = $.extend({
width: mode === 'show' ? self.element.data('panel.outerWidth') : 0
}, blindOption.fade ? {
opacity: mode === 'show' ? 1 : 0
} : {
});
listWidth = self.list.outerWidth(true);
// Animate
wrapper.animate(a, {
duration: blindOption.duration,
step: function () {
var ww = wrapper.outerWidth(true);
self.element.width(listWidth + ww);
content.width(Math.max(0, self.element.innerWidth() - listWidth - 6));
},
complete: function () {
if(mode === 'hide') {
self.lis.removeClass(o.wijCSS.tabsActive).removeClass(o.wijCSS.stateActive).attr('aria-selected', false);
// Hide
panel.addClass(o.wijCSS.wijtabsHide).attr('aria-hidden', true);
} else {
panel.css('width', '');
}
////$.effects.restore(panel, props);
//$.effects.removeWrapper(panel); // Restore
if(effectsRemoveWrapper) {
effectsRemoveWrapper(panel);
}
if(mode === 'show') {
self._restoreLayout();
}
self._resetStyle(panel);
panel.dequeue();
self.element.dequeue("tabs");
}
});
};
wijtabs.prototype._hideContent = function () {
var wijCSS = this.options.wijCSS, content = this.element.find('.' + wijCSS.wijtabsContent);
if(content.length) {
this._saveLayout();
content.addClass(wijCSS.wijtabsHide).attr('aria-hidden', true);
this.element.width(this.list.outerWidth(true));
}
};
wijtabs.prototype._showContent = function () {
var wijCSS = this.options.wijCSS, content = this.element.find('.' + wijCSS.wijtabsContent);
if(content.length) {
this._restoreLayout();
content.removeClass(wijCSS.wijtabsHide).attr('aria-hidden', false);
}
};
wijtabs.prototype._saveLayout = function () {
var wijCSS = this.options.wijCSS, props = [
'width',
'height',
'overflow'
], $hide = this.panels.filter(':not(.' + wijCSS.wijtabsHide + ')');
//$.effects.save(self.element, props);
//$.effects.save(self.list, props);
//$.effects.save(self.element.find('.' + wijCSS.wijtabsContent), props);
if(effectsSave) {
effectsSave(this.element, props);
effectsSave(this.list, props);
effectsSave(this.element.find('.' + wijCSS.wijtabsContent), props);
}
this.list.width(this.list.width());
this.element.data('panel.width', $hide.width());
this.element.data('panel.outerWidth', $hide.outerWidth(true));
};
wijtabs.prototype._restoreLayout = function () {
var wijCSS = this.options.wijCSS, props = [
'width',
'height',
'overflow'
];
//$.effects.restore(self.element, props);
//$.effects.restore(self.list, props);
//$.effects.restore(self.element.find('.' + wijCSS.wijtabsContent), props);
if(effectsRestore) {
effectsRestore(this.element, props);
effectsRestore(this.list, props);
effectsRestore(this.element.find('.' + wijCSS.wijtabsContent), props);
}
};
wijtabs.prototype._resetStyle = // Reset certain styles left over from animation
// and prevent IE's ClearType bug...
function ($el) {
$el.css({
display: ''
});
if(!$.support.opacity) {
$el[0].style.removeAttribute('filter');
}
};
wijtabs.prototype._normalizeBlindOption = function (o) {
if(o.blind === undefined) {
o.blind = false;
}
if(o.fade === undefined) {
o.fade = false;
}
if(o.duration === undefined) {
o.duration = 200;
}
if(typeof o.duration === 'string') {
try {
o.duration = parseInt(o.duration, 10);
} catch (e) {
o.duration = 200;
}
}
};
wijtabs.prototype._initScroller = function () {
var horz = $.inArray(this._getAlignment(true), [
'Top',
'Bottom'
]) !== -1, width = 0;
if(!horz) {
return;
}
$.each(this.lis, function () {
// In IE, the render width has decimals. but the jQuery get's width doesn't contains decimals.
if($.browser.msie) {
$(this).width($(this).width());
}
width += $(this).outerWidth(true);
});
if(!!this.options.scrollable && this.element.innerWidth() < width) {
if(this.scrollWrap === undefined) {
this.list.wrap("<div class='scrollWrap'></div>");
this.scrollWrap = this.list.parent();
//$.effects.save(this.list, ['width', 'height', 'overflow']);
if(effectsSave) {
effectsSave(this.list, [
'width',
'height',
'overflow'
]);
}
}
this.list.width(width + 2);
this.scrollWrap.height(this.list.outerHeight(true));
this.scrollWrap.wijsuperpanel({
allowResize: false,
hScroller: {
scrollMode: 'edge'
},
vScroller: {
scrollBarVisibility: 'hidden'
}
});
} else {
this._removeScroller();
}
};
wijtabs.prototype._ui = function (tab, panel) {
return {
tab: tab,
panel: panel,
index: this.anchors.index(tab)
};
};
wijtabs.prototype._tabId = function (a) {
var $a = $(a), tabId, hrefParams;
if($a.data && $a.data("tabid")) {
return $a.data("tabid");
}
if(a.href && a.href.length) {
hrefParams = this._getURLParameters(a.href);
if(hrefParams.tabId) {
tabId = hrefParams.tabId;
$a.data("tabid", tabId);
return tabId;
}
}
tabId = a.title && a.title.replace(/\s/g, '_').replace(/[^A-Za-z0-9\-_:\.]/g, '') || this.options.idPrefix + getNextTabId();
$a.data("tabid", tabId);
return tabId;
};
wijtabs.prototype._getURLParameters = function (url) {
var params = {
}, parametersString, parameters;
if(url.indexOf('?') > -1) {
parametersString = url.split('?')[1];
parameters = parametersString.split('&');
$.each(parameters, function (i, param) {
var p = param.split('=');
if(p.length > 1) {
params[p[0]] = p[1];
}
});
}
return params;
};
wijtabs.prototype._getAlignment = function (tabs) {
var align = this.options.alignment || 'top';
if(tabs) {
return align.charAt(0).toUpperCase() + align.substr(1);
}
switch(align) {
case 'top':
align = 'Bottom';
break;
case 'bottom':
align = 'Top';
break;
case 'left':
align = 'Right';
break;
case 'right':
align = 'Left';
break;
}
return align;
};
wijtabs.prototype._sanitizeSelector = function (hash) {
// we need this because an id may contain a ":"
return hash.replace(/:/g, '\\:');
};
wijtabs.prototype._innerDestroy = function (keepAddedItems) {
var o = this.options, content = $('.' + o.wijCSS.wijtabsContent);
this.abort();
this._removeScroller();
this.element.unbind('.tabs').removeClass(o.wijCSS.wijtabs).removeClass(o.wijCSS.tabsTop).removeClass(o.wijCSS.tabsBottom).removeClass(o.wijCSS.tabsLeft).removeClass(o.wijCSS.tabsRight).removeClass(o.wijCSS.tabs).removeClass(o.wijCSS.widget).removeClass(o.wijCSS.content).removeClass(o.wijCSS.cornerAll).removeClass(o.wijCSS.tabsCollapsible).removeClass(o.wijCSS.helperClearFix).removeData('tabs').removeAttr('role');
this.list.removeClass(o.wijCSS.tabsNav).removeClass(o.wijCSS.helperReset).removeClass(o.wijCSS.helperClearFix).removeClass(o.wijCSS.header).removeClass(o.wijCSS.cornerAll).removeAttr('role');
$.each(this.anchors, function (idx, a) {
var $a = $(a), href = $a.data('href.tabs');
if(href) {
a.href = href;
}
$a.unbind('.tabs');
$.each([
'href',
'load',
'cache'
], function (i, prefix) {
$a.removeData(prefix + '.tabs');
});
});
this.lis.unbind('.tabs').add(this.panels).each(function (idx, li) {
var $li = $(li);
if($li.data('destroy.tabs') && !keepAddedItems) {
$li.remove();
} else {
$li.removeClass(o.wijCSS.stateDefault).removeClass(o.wijCSS.cornerTop).removeClass(o.wijCSS.cornerBottom).removeClass(o.wijCSS.cornerLeft).removeClass(o.wijCSS.cornerRight).removeClass(o.wijCSS.tabsActive).removeClass(o.wijCSS.stateActive).removeClass(o.wijCSS.stateHover).removeClass(o.wijCSS.stateFocus).removeClass(o.wijCSS.stateDisabled).removeClass(o.wijCSS.tabsPanel).removeClass(o.wijCSS.content).removeClass(o.wijCSS.wijtabsHide).css({
position: '',
left: '',
top: ''
}).removeAttr('role').removeAttr('aria-hidden').removeAttr('aria-selected').removeAttr('aria-disabled');
}
});
if(content.length) {
content.replaceWith(content.contents());
}
if(o.cookie) {
this._cookie(null, o.cookie);
}
return this;
};
wijtabs.prototype._cleanup = function () {
// restore all former loading tabs labels
var wijCSS = this.options.wijCSS;
this.lis.filter('.' + wijCSS.tabsLoading).removeClass(wijCSS.tabsLoading).find('span:data(label.tabs)').each(function () {
var el = $(this);
el.html(el.data('label.tabs')).removeData('label.tabs');
});
};
wijtabs.prototype._removeScroller = function () {
if(!this.scrollWrap) {
return;
}
this.scrollWrap.wijsuperpanel('destroy').replaceWith(this.scrollWrap.contents());
this.scrollWrap = undefined;
if(effectsRestore) {
effectsRestore(this.list, [
'width',
'height',
'overflow'
]);
}
};
wijtabs.prototype._cookie = function (index, cookie) {
var c = this.cookie || (this.cookie = this.options.cookie.name || 'ui-tabs-' + getNextListId());
return $.cookie.apply(null, [
c
].concat($.makeArray(arguments)));
};
wijtabs.prototype.abort = /** Terminate all running tab ajax requests and animations.*/
function () {
this.element.queue([]);
this.panels.stop(false, true);
// "tabs" queue must not contain more than two elements,
// which are the callbacks for the latest clicked tab...
this.element.queue("tabs", this.element.queue("tabs").splice(-2, 2));
// terminate pending requests from other tabs
if(this.xhr) {
this.xhr.abort();
delete this.xhr;
}
// take care of tab labels
this._cleanup();
return this;
};
wijtabs.prototype.select = /** Selects a tab; for example, a clicked tab.
* @param {number|string} index The zero-based index of the tab to be selected or
* the id selector of the panel the tab is associated with.
* @example
* //Select the second tab.
* $("#element").wijtabs('select', 1);
*/
function (index) {
if(typeof index === 'string') {
index = this.anchors.index(this.anchors.filter('[href$=' + index + ']'));
} else if(index === null) {
// usage of null is deprecated, TODO remove in next release
index = -1;
}
if(index === -1 && this.options.collapsible) {
index = this.options.selected;
}
this.anchors.eq(index).trigger(this.options.event + '.tabs');
return this;
};
wijtabs.prototype.load = /** Reload the content of an Ajax tab programmatically.
* This method always loads the tab content from the remote location,
* even if cache is set to true.
* @param {number} index The zero-based index of the tab to be reloaded.
* @example
* //Reload the second tab.
* $("#element").wijtabs('load', 1);
*/
function (index) {
var self = this, o = self.options, a = self.anchors.eq(index)[0], url = $.data(a, 'load.tabs'), span = $('span', a);
self.abort();
if(false === self._trigger('beforeShow', null, self._ui(self.anchors[index], self.panels[index]))) {
self.element.dequeue("tabs");
return;
}
// not remote or from cache
if(!url || self.element.queue("tabs").length !== 0 && $.data(a, 'cache.tabs')) {
self.element.dequeue("tabs");
return;
}
// load remote from here on
self.lis.eq(index).addClass(o.wijCSS.tabsLoading);
if(o.spinner || self._defaults.spinner) {
span.data('label.tabs', span.html()).html(o.spinner || self._defaults.spinner);
}
self.xhr = $.ajax($.extend({
}, o.ajaxOptions, {
url: url,
success: function (r, s) {
$(self._sanitizeSelector(a.hash), self.element).html(r);
// take care of tab labels
self._cleanup();
if(o.cache) {
// if loaded once do not load them again
$.data(a, 'cache.tabs', true);
}
// callbacks
self._trigger('load', null, self._ui(self.anchors[index], self.panels[index]));
try {
o.ajaxOptions.success(r, s);
} catch (e1) {
}
},
error: function (xhr, s, e) {
// take care of tab labels
self._cleanup();
// callbacks
self._trigger('load', null, self._ui(self.anchors[index], self.panels[index]));
try {
// Passing index avoid a race condition when this method is
// called after the user has selected another tab.
// Pass the anchor that initiated this request allows
// loadError to manipulate the tab content panel via $(a.hash)
o.ajaxOptions.error(xhr, s, index, a);
} catch (e2) {
}
}
}));
// last, so that load event is fired before show...
self.element.dequeue("tabs");
return self;
};
wijtabs.prototype.add = /** Add a new tab.
* @param {string} url A URL consisting of a fragment identifier
* only to create an in-page tab or a full url
* (relative or absolute, no cross-domain support) to
* turn the new tab into an Ajax (remote) tab.
* @param {string} label The tab label.
* @param {number} index Zero-based position where to insert the new tab.
* @example
* //Add a new tab to be a second tab.
* $("#element").wijtabs('add', "http://wijmo.com/newTab", "NewTab", 1);
*/
function (url, label, index) {
if(index === undefined) {
index = this.anchors.length// append by default
;
}
var self = this, o = self.options, $li = $((o.tabTemplate || self._defaults.tabTemplate).replace(/#\{href\}/g, url).replace(/#\{label\}/g, label)), id = !url.indexOf('#') ? url.replace('#', '') : self._tabId($('a', $li)[0]), tabsAlign = self._getAlignment(true), panelCorner = self._getAlignment(false), $panel = $('#' + id), $content;
$li.addClass(o.wijCSS.stateDefault).addClass(o.wijCSS["corner" + tabsAlign]).data('destroy.tabs', true).attr('role', 'tab').attr('aria-selected', false);
// try to find an existing element before creating a new one
if(!$panel.length) {
$panel = $(o.panelTemplate || self._defaults.panelTemplate).attr('id', id).data('destroy.tabs', true).attr('role', 'tabpanel');
}
$panel.addClass(o.wijCSS.tabsPanel).addClass(o.wijCSS.content).addClass(o.wijCSS["corner" + panelCorner] + ' ' + o.wijCSS.wijtabsHide).attr('aria-hidden', true);
if(index >= self.lis.length) {
$li.appendTo(self.list);
if(self.panels.length > 0) {
$panel.insertAfter(self.panels[self.panels.length - 1]);
} else {
$content = self.element.find('.' + o.wijCSS.wijtabsContent);
if($content.length === 0) {
$content = self.element;
}
$panel.appendTo($content);
}
} else {
$li.insertBefore(self.lis[index]);
$panel.insertBefore(self.panels[index]);
}
o.disabledIndexes = $.map(o.disabledIndexes, function (n, i) {
return n >= index ? ++n : n;
});
self._removeScroller();
self._tabify(false);
if(self.anchors.length === 1) {
// after tabify
o.selected = 0;
$li.addClass(o.wijCSS.tabsActive).addClass(o.wijCSS.stateActive).attr('aria-selected', true);
$panel.removeClass(o.wijCSS.wijtabsHide).attr('aria-hidden', false);
self.element.queue("tabs", function () {
if(self.element.wijTriggerVisibility) {
$(self.panels[0]).wijTriggerVisibility();
}
self._trigger('show', null, self._ui(self.anchors[0], self.panels[0]));
});
self.load(0);
}
// callback
self._trigger('add', null, self._ui(self.anchors[index], self.panels[index]));
return self;
};
wijtabs.prototype.remove = /** Removes a tab.
* @param {number} index The zero-based index of the tab to be removed.
* @example
* //Removes the second tab
* $("#element").wijtabs('remove', 1);
*/
function (index) {
var o = this.options, $li = this.lis.eq(index).remove(), $panel = this.panels.eq(index).remove();
// If selected tab was removed focus tab to the right or
// in case the last tab was removed the tab to the left.
if($li.hasClass(o.wijCSS.tabsActive) && this.anchors.length > 1) {
this.select(index + (index + 1 < this.anchors.length ? 1 : -1));
}
o.disabledIndexes = $.map($.grep(o.disabledIndexes, function (n, i) {
return n !== index;
}, false), function (n, i) {
return n >= index ? --n : n;
});
this._removeScroller();
this._tabify(false);
// callback
this._trigger('remove', null, this._ui($li.find('a')[0], $panel[0]));
return this;
};
wijtabs.prototype.enableTab = /** Enable a disabled tab.
* @param {number} index The zero-based index of the tab to be enabled.
* @example
* //Enables the second tab
* $("#element").wijtabs('enableTab', 1);
*/
function (index) {
var o = this.options;
if($.inArray(index, o.disabledIndexes) === -1) {
return;
}
this.lis.eq(index).removeClass(o.wijCSS.stateDisabled).removeAttr('aria-disabled');
o.disabledIndexes = $.grep(o.disabledIndexes, function (n, i) {
return n !== index;
}, false);
// callback
this._trigger('enable', null, this._ui(this.anchors[index], this.panels[index]));
return this;
};
wijtabs.prototype.disableTab = /** Disabled a tab.
* @param {number} index The zero-based index of the tab to be disabled.
* @example
* //Disables the second tab
* $("#element").wijtabs('disableTab', 1);
*/
function (index) {
var o = this.options;
if(index !== o.selected) {
// cannot disable already selected tab
this.lis.eq(index).addClass(o.wijCSS.stateDisabled).attr('aria-disabled', true);
o.disabledIndexes.push(index);
o.disabledIndexes.sort();
// callback
this._trigger('disable', null, this._ui(this.anchors[index], this.panels[index]));
}
return this;
};
wijtabs.prototype.url = /** Changes the url from which an Ajax (remote) tab will be loaded.
* @param {number} index The zero-based index of the tab of which its URL is to be updated.
* @param {string} url A URL the content of the tab is loaded from.
* @remarks The specified URL will be used for subsequent loads.
* Note that you can not only change the URL for an existing remote tab
* with this method, but you can also turn an in-page tab into a remote tab.
* @example
* //Changes the second tab to a new tab url.
* $("#element").wijtabs('url', 1, "http://wijmo.com/newTabUrl")
*/
function (index, url) {
this.anchors.eq(index).removeData('cache.tabs').data('load.tabs', url);
return this;
};
wijtabs.prototype.length = /** Retrieve the number of tabs of the first matched tab pane.*/
function () {
return this.anchors.length;
};
return wijtabs;
})(wijmo.wijmoWidget);
tabs.wijtabs = wijtabs;
wijtabs.prototype._defaults = {
panelTemplate: '<div></div>',
spinner: '<em>Loading…</em>',
tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a></li>'
};
var wijtabs_options = (function () {
function wijtabs_options() {
/** All CSS classes used in widgets.
* @ignore
*/
this.wijCSS = {
wijtabs: "wijmo-wijtabs",
wijtabsContent: "wijmo-wijtabs-content",
wijtabsHide: "wijmo-wijtabs-hide"
};
/** @ignore */
this.wijMobileCSS = {
header: "ui-header ui-bar-c",
content: "ui-content ui-body ui-body-c",
stateDefault: "ui-btn-up-a",
stateActive: "ui-btn-down-b"
};
/** Determines the tabs' alignment in respect to the content.
* @remarks Possible values are: 'top', 'bottom', 'left' and 'right'.
*/
this.alignment = 'top';
/** Determines whether the tab can be dragged to a new position.
* @remarks This option only works when jQuery.ui.sortable is available
* which means that it doesn't work in mobile mode.
*/
this.sortable = false;
/** Determines whether to wrap to the next line or enable scrolling
* when the number of tabs exceeds the specified width.
*/
this.scrollable = false;
/** Additional Ajax options to consider when loading tab content (see $.ajax).
* @type {object}
* @remarks Please see following link for more details,
* http://api.jquery.com/jQuery.ajax/ .
*/
this.ajaxOptions = null;
/** Determines whether or not to cache the remote tabs content,
* for example, to load content only once or with every click.
* @remarks Note that to prevent the actual Ajax requests from being cached
* by the browser, you need to provide an extra cache:
* false flag to ajaxOptions.
*/
this.cache = false;
/** Stores the latest selected tab in a cookie.
* The cookie is then used to determine the initially selected tab
* if the selected option is not defined.
* This option requires a cookie plugin. The object needs to have key/value pairs
* of the form the cookie plugin expects as options.
* @example
* //Set cookie to wijtabs.
* $('.selector').wijtabs({cookie: {
* expires: 7, path: '/', domain: 'jquery.com', secure: true }});
*/
this.cookie = null;
/** Determines whether a tab can be collapsed by a user.
* When this is set to true, an already selected tab
* will be collapsed upon reselection.
*/
this.collapsible = false;
/** This is an animation option for hiding the tab's panel content.
* @type {object}
* @example
* //Set hide animation to blind/fade and duration to 200.
* $('.selector').wijtabs({
* hideOption: { blind: true, fade: true, duration: 200}});
*/
this.hideOption = null;
/** This is an animation option for showing the tab's panel content.
* @type {object}
* @example
* //Set show animation to blind/fade and duration to 200.
* $('.selector').wijtabs({
* showOption: { blind: true, fade: true, duration: 200}});
*/
this.showOption = null;
/** An array containing the position of the tabs (zero-based index)
* that should be disabled upon initialization.
*/
this.disabledIndexes = [];
/** The type of event to be used for selecting a tab. */
this.event = 'click';
/** If the remote tab, its anchor element that is, has no title attribute
* to generate an id from,
* an id/fragment identifier is created from this prefix and a unique id
* returned by $.data(el), for example "ui-tabs-54".
*/
this.idPrefix = 'ui-tabs-';
/** This is the HTML template from which a new tab panel is created in case
* a tab is added via the add method or
* if a panel for a remote tab is created on the fly.
*/
this.panelTemplate = '';
/** The HTML content of this string is shown in a tab title
* while remote content is loading.
* Pass in an empty string to deactivate that behavior.
* A span element must be present in the A tag of the title
* for the spinner content to be visible.
*/
this.spinner = '';
/** HTML template from which a new tab is created and added.
* The placeholders #{href} and #{label} are replaced with the url
* and tab label that are passed as arguments to the add method.
*/
this.tabTemplate = '';
/** The add event handler. A function called when a tab is added.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijTabsEventArgs} args The data with this event.
*/
this.add = null;
/** The remove event handler. A function called when a tab is removed.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijTabsEventArgs} args The data with this event.
*/
this.remove = null;
/** The select event handler. A function called when clicking a tab.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijTabsEventArgs} args The data with this event.
*/
this.select = null;
/** The beforeShow event handler. A function called before a tab is shown.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijTabsEventArgs} args The data with this event.
*/
this.beforeShow = null;
/** The show event handler. A function called when a tab is shown.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijTabsEventArgs} args The data with this event.
*/
this.show = null;
/** The load event handler.
* A function called after the content of a remote tab has been loaded.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijTabsEventArgs} args The data with this event.
*/
this.load = null;
/** The disable event handler. A function called when a tab is disabled.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijTabsEventArgs} args The data with this event.
*/
this.disable = null;
/** The enable event handler. A function called when a tab is enabled.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijTabsEventArgs} args The data with this event.
*/
this.enable = null;
}
return wijtabs_options;
})();
;
wijtabs.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijtabs_options());
$.wijmo.registerWidget("wijtabs", wijtabs.prototype);
;
})(wijmo.tabs || (wijmo.tabs = {}));
var tabs = wijmo.tabs;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
(function (video) {
"use strict";
var $ = jQuery, widgetName = "wijvideo";
/** @widget */
var wijvideo = (function (_super) {
__extends(wijvideo, _super);
function wijvideo() {
_super.apply(this, arguments);
}
wijvideo.prototype._create = function () {
var self = this, pos, $playbtn, videoIsSupport, wijCSS = self.options.wijCSS, o = self.options, interval;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
if($(this.element).is("video")) {
this.$video = $(this.element);
} else {
this.$video = $(this.element).find("video");
}
//update for fixing bug 18129 by wh at 2011/11/2
if(!this.$video || this.$video.length === 0 || ($.browser.msie && parseInt($.browser.version, 10) < 9)) {
return;
}
//end for fixing
//Add for fixing bug 18204 by wh at 2011/11/7
videoIsSupport = this.$video[0].canPlayType;
if(!videoIsSupport) {
return;
}
//end for fixing bug 18204
this.$video.wrap('<div class="wijmo-wijvideo ' + wijCSS.content + ' ' + wijCSS.widget + '" />').after('<div class="wijmo-wijvideo-wrapper">' + '<ul class="wijmo-wijvideo-controls ' + wijCSS.header + ' ' + wijCSS.helperClearFix + ' ' + wijCSS.helperReset + '">' + '<li class="wijmo-wijvideo-play ' + wijCSS.stateDefault + ' ' + wijCSS.cornerAll + '">' + '<span class="' + wijCSS.icon + " " + wijCSS.iconPlay + '"></span>' + '</li>' + '<li class="wijmo-wijvideo-index"><div class="wijmo-wijvideo-index-slider"></div></li>' + '<li class="wijmo-wijvideo-timer">00:00</li>' + '<li class="wijmo-wijvideo-volume ' + wijCSS.stateDefault + ' ' + wijCSS.cornerAll + '">' + '<div class="wijmo-wijvideo-volume-container">' + '<div class="wijmo-wijvideo-volumeslider ' + wijCSS.stateDefault + ' ' + wijCSS.cornerTop + '"></div>' + '</div>' + '<span class="' + wijCSS.icon + " " + wijCSS.iconVolumeOn + '"></span>' + '</li>' + '<li class="wijmo-wijvideo-fullscreen ' + wijCSS.stateDefault + " " + wijCSS.cornerAll + '">' + '<span class="' + wijCSS.icon + " " + wijCSS.iconArrow4Diag + '"></span>' + '</li>' + '</ul>' + '</div>');
this.$vidParent = this.$video.parent('.wijmo-wijvideo');
// size the div wrapper to the height and width of the controls
this.$vidParent.width(this.$video.outerWidth()).height(this.$video.outerHeight());
this.$seekSlider = this.$vidParent.find('.wijmo-wijvideo-index-slider');
//Volumn
self._volumnOn = true;
self.$volumeBtn = this.$vidParent.find('.wijmo-wijvideo-volume');
// create the video this.seek slider
interval = window.setInterval(function () {
//replace the attr to prop
//if (this.$video.attr('readyState')) {
if(self._getVideoAttribute("readyState")) {
window.clearInterval(interval);
//note: we need to adjust the size of the video in
//this time
self.$vidParent.width(self.$video.outerWidth()).height(self.$video.outerHeight());
//note: if the controls is invisible, it will not
//get the position
self.$video.parent().find('.wijmo-wijvideo-controls').show();
//this.$seekSlider = this.$vidParent.find('.wijmo-wijvideo-index-slider');
pos = self.$vidParent.find('.wijmo-wijvideo-timer').position().left;
self.$seekSlider.width(pos - self.$seekSlider.position().left - 15);
self.$seekSlider.slider({
value: 0,
step: 0.01,
max: self._getVideoAttribute("duration"),
range: 'min',
stop: function (e, ui) {
self.seek = false;
self._setVideoAttribute("currentTime", ui.value);
},
slide: function () {
self.seek = true;
}
});
self._updateTime();
// wire up the volume
self.$volumeSlider = self.$vidParent.find('.wijmo-wijvideo-volumeslider');
self.$volumeSlider.slider({
min: 0,
max: 1,
value: self._getVideoAttribute("volume"),
step: 0.1,
orientation: 'vertical',
range: 'min',
slide: function (e, ui) {
self._setVideoAttribute("volume", ui.value);
if(ui.value === 0) {
self._volumnOn = false;
self.$volumeBtn.find("span").removeClass(wijCSS.iconVolumeOn).addClass(wijCSS.iconVolumeOff);
} else {
self._volumnOn = true;
self.$volumeBtn.find("span").removeClass(wijCSS.iconVolumeOff).addClass(wijCSS.iconVolumeOn);
}
}
});
self.$video.parent().find('.wijmo-wijvideo-controls').css('display', 'none');
self._initialToolTip();
if(!o.showControlsOnHover) {
$('.wijmo-wijvideo-controls').show();
self.$vidParent.height(self.$video.outerHeight() + $('.wijmo-wijvideo-controls').height());
}
}
}, 200);
this.$video.bind("click." + self.widgetName, function () {
self._togglePlay();
});
// display the bar on hover
if(o.showControlsOnHover) {
$('.wijmo-wijvideo').hover(function () {
$('.wijmo-wijvideo-controls').stop(true, true).fadeIn();
}, function () {
$('.wijmo-wijvideo-controls').delay(300).fadeOut();
});
}
$playbtn = this.$vidParent.find('.wijmo-wijvideo-play > span');
$playbtn.click(function () {
self._togglePlay();
}).parent().hover(function () {
$(this).addClass(wijCSS.stateHover);
}, function () {
$(this).removeClass(wijCSS.stateHover);
});
this.$vidParent.find('.wijmo-wijvideo-volume').hover(function () {
$('.wijmo-wijvideo-volume-container').stop(true, true).slideToggle();
});
this.$fullScreenBtn = this.$vidParent.find('.wijmo-wijvideo-fullscreen > span');
this.$fullScreenBtn.click(function () {
self._toggleFullScreen();
}).parent().hover(function () {
$(this).addClass(wijCSS.stateHover);
}, function () {
$(this).removeClass(wijCSS.stateHover);
});
if(!self.options.fullScreenButtonVisible) {
this.$vidParent.find('.wijmo-wijvideo-fullscreen').hide();
}
this.$volumeBtn.hover(function () {
$(this).addClass(wijCSS.stateHover);
}, function () {
$(this).removeClass(wijCSS.stateHover);
}).click(function () {
if(self._getVideoAttribute("readyState")) {
self._volumnOn = !self._volumnOn;
if(!self._volumnOn) {
self.currentVolumn = self.$volumeSlider.slider('value');
self.$volumeSlider.slider('value', 0);
self._setVideoAttribute('volume', 0);
self.$volumeBtn.find("span").removeClass(wijCSS.iconVolumeOn).addClass(wijCSS.iconVolumeOff);
} else {
//self.currentVolumn = self.currentVolumn === 0 ? 100 : self.currentVolumn;
self.$volumeSlider.slider('value', self.currentVolumn ? self.currentVolumn : 1);
self._setVideoAttribute('volume', self.currentVolumn ? self.currentVolumn : 1);
self.$volumeBtn.find("span").removeClass(wijCSS.iconVolumeOff).addClass(wijCSS.iconVolumeOn);
}
}
});
//move the init tooltip to interval, when the video's state
//is ready, then init the tooltip
//self._initialToolTip();
this.$video.bind('play.' + self.widgetName, function () {
$playbtn.removeClass(wijCSS.icon + " " + wijCSS.iconPlay).addClass(wijCSS.icon + " " + wijCSS.iconPause);
});
this.$video.bind('pause.' + self.widgetName, function () {
$playbtn.removeClass(wijCSS.icon + " " + wijCSS.iconPause).addClass(wijCSS.icon + " " + wijCSS.iconPlay);
});
this.$video.bind('ended.' + self.widgetName, function () {
self.pause();
});
this.$video.bind('timeupdate.' + self.widgetName, function () {
self._updateTime();
});
self._videoIsControls = false;
if(self._getVideoAttribute("controls")) {
self._videoIsControls = true;
}
this.$video.removeAttr('controls');
//update for visibility change
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
self._refresh();
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
}, "wijvideo");
}
//update for juice 22288
if(self.options.disabled) {
self._handleDisabledOption(true, self.element);
}
};
wijvideo.prototype._setOption = function (key, value) {
var self = this, o = self.options;
//$.wijmo.widget.prototype._setOption.apply(self, arguments);
_super.prototype._setOption.call(this, key, value);
if(key === "fullScreenButtonVisible") {
o.fullScreenButtonVisible = value;
if(value) {
this.$vidParent.find('.wijmo-wijvideo-fullscreen').show();
} else {
this.$vidParent.find('.wijmo-wijvideo-fullscreen').hide();
}
} else if(key === "disabled") {
self._handleDisabledOption(value, self.element);
} else if(key === "showControlsOnHover") {
if(!value) {
$('.wijmo-wijvideo').unbind('mouseenter mouseleave');
window.setTimeout(function () {
$('.wijmo-wijvideo-controls').show();
self.$vidParent.height(self.$video.outerHeight() + $('.wijmo-wijvideo-controls').height());
}, 200);
} else {
this.$vidParent.height(this.$video.outerHeight());
$('.wijmo-wijvideo-controls').hide();
$('.wijmo-wijvideo').hover(function () {
$('.wijmo-wijvideo-controls').stop(true, true).fadeIn();
}, function () {
$('.wijmo-wijvideo-controls').delay(300).fadeOut();
});
}
}
//end for disabled option
};
wijvideo.prototype._handleDisabledOption = function (disabled, ele) {
var self = this;
if(disabled) {
if(!self.disabledDiv) {
self.disabledDiv = self._createDisabledDiv(ele);
}
self.disabledDiv.appendTo("body");
if($.browser.msie) {
$('.wijmo-wijvideo').unbind('mouseenter mouseleave');
this.$video.unbind("click." + self.widgetName);
}
} else {
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
if($.browser.msie) {
$('.wijmo-wijvideo').hover(function () {
$('.wijmo-wijvideo-controls').stop(true, true).fadeIn();
}, function () {
$('.wijmo-wijvideo-controls').delay(300).fadeOut();
});
this.$video.bind("click." + self.widgetName, function () {
self._togglePlay();
});
}
}
}
};
wijvideo.prototype._createDisabledDiv = function (outerEle) {
var ele = this.$vidParent, eleOffset = ele.offset(), disabledWidth = ele.outerWidth(), disabledHeight = ele.outerHeight();
return $("<div></div>").addClass("ui-disabled").css({
"z-index": "99999",
position: "absolute",
width: disabledWidth,
height: disabledHeight,
left: eleOffset.left,
top: eleOffset.top
});
};
wijvideo.prototype._getVideoAttribute = function (name) {
if(name === "") {
return;
}
return this.$video.prop(name);
};
wijvideo.prototype._setVideoAttribute = function (name, value) {
if(name === "") {
return;
}
return this.$video.prop(name, value);
};
wijvideo.prototype._initialToolTip = function () {
var self = this;
//ToolTip-slider
this.$seekSlider.wijtooltip({
mouseTrailing: true,
showCallout: false,
position: {
offset: '-60 -60'
}
});
this.$seekSlider.bind("mousemove", function (e, ui) {
self._changeToolTipContent(e);
});
//ToolTip-button
this.$volumeBtn.wijtooltip({
content: self._localizeString("volumeToolTip", "Volume"),
showCallout: false
});
this.$fullScreenBtn.wijtooltip({
content: self._localizeString("fullScreenToolTip", "Full Screen"),
showCallout: false
});
//add class to prevent from overriding the origin css of tooltip.
this.$seekSlider.wijtooltip("widget").addClass("wijmo-wijvideo");
this.$volumeBtn.wijtooltip("widget").addClass("wijmo-wijvideo");
this.$volumeBtn.wijtooltip("widget").addClass("wijmo-wijvideo");
};
wijvideo.prototype._updateTime = function () {
var self = this, dur = self._getVideoAttribute("duration"), cur = self._getVideoAttribute("currentTime"), mm, ss, mfmt = '', sfmt = '';
mm = this._truncate((dur - cur) / 60);
ss = this._truncate((dur - cur) - (mm * 60));
if(mm < 10) {
mfmt = '0';
}
if(ss < 10) {
sfmt = '0';
}
this.$vidParent.find('.wijmo-wijvideo-timer').html(mfmt + mm + ':' + sfmt + ss);
if(!this.seek) {
this.$seekSlider.slider('value', cur);
}
};
wijvideo.prototype._truncate = function (n) {
return Math[n > 0 ? "floor" : "ceil"](n);
};
wijvideo.prototype._togglePlay = function () {
var self = this;
if(!self._getVideoAttribute("readyState")) {
return;
}
if(self._getVideoAttribute("paused")) {
this.play();
} else {
this.pause();
}
};
wijvideo.prototype._toggleFullScreen = function () {
var self = this, isPaused = self._getVideoAttribute("paused"), offsetWidth = 0, fWidth = $(window).width(), fHeight = $(window).height();
this.fullScreen = !this.fullScreen;
if(this.fullScreen) {
self._oriVidParentStyle = this.$vidParent.attr("style");
self._oriWidth = this.$video.outerWidth();
self._oriHeight = this.$video.outerHeight();
self._oriDocOverFlow = $(document.documentElement).css("overflow");
$(document.documentElement).css({
overflow: "hidden"
});
if(!self._replacedDiv) {
self._replacedDiv = $("<div />");
}
this.$vidParent.after(self._replacedDiv);
this.$vidParent.addClass("wijmo-wijvideo-container-fullscreen").css({
width: fWidth,
height: fHeight
}).appendTo($("body"));
this.$video.attr("width", fWidth).attr("height", fHeight);
$(window).bind("resize.wijvideo", function () {
self._fullscreenOnWindowResize();
});
//for reposition the video control
offsetWidth = fWidth - self._oriWidth;
} else {
$(document.documentElement).css({
overflow: self._oriDocOverFlow
});
//for reposition the video control
offsetWidth = self._oriWidth - this.$video.width();
self._replacedDiv.after(this.$vidParent).remove();
this.$vidParent.removeClass("wijmo-wijvideo-container-fullscreen").attr("style", "").attr("style", self._oriVidParentStyle);
this.$video.attr("width", self._oriWidth).attr("height", self._oriHeight);
$(window).unbind("resize.wijvideo");
}
self._positionControls(offsetWidth);
self._hideToolTips();
if(!isPaused) {
self.play();
} else {
self.pause();
}
};
wijvideo.prototype._fullscreenOnWindowResize = function () {
var self = this, fWidth = $(window).width(), fHeight = $(window).height(), offsetWidth = fWidth - this.$vidParent.width();
this.$vidParent.css({
width: fWidth,
height: fHeight
});
this.$video.attr("width", fWidth).attr("height", fHeight);
self._positionControls(offsetWidth);
};
wijvideo.prototype._positionControls = function (offsetWidth) {
var seekSlider = this.$vidParent.find('.wijmo-wijvideo-index-slider');
seekSlider.width(seekSlider.width() + offsetWidth);
};
wijvideo.prototype._showToolTip = function (e) {
var self = this, mousePositionX = e.pageX, mousePositionY = e.pageY, sliderOffset = this.$seekSlider.offset().left, sliderWidth = this.$seekSlider.width(), curWidth = mousePositionX - sliderOffset, dur = self._getVideoAttribute("duration"), currentTime;
currentTime = dur * (curWidth / sliderWidth);
this.$seekSlider.wijtooltip("option", "content", self._getToolTipContent(currentTime));
this.$seekSlider.wijtooltip("showAt", {
x: mousePositionX,
y: mousePositionY - 10
});
};
wijvideo.prototype._changeToolTipContent = function (e) {
var self = this, mousePositionX = e.pageX, sliderOffset = this.$seekSlider.offset().left, sliderWidth = this.$seekSlider.width(), curWidth = mousePositionX - sliderOffset, dur = self._getVideoAttribute("duration"), currentTime;
currentTime = dur * (curWidth / sliderWidth);
this.$seekSlider.wijtooltip("option", "content", self._getToolTipContent(currentTime));
};
wijvideo.prototype._hideToolTips = function () {
if(this.$seekSlider.data("wijmoWijtooltip")) {
this.$seekSlider.wijtooltip("hide");
}
if(this.$volumeBtn.data("wijmoWijtooltip")) {
this.$volumeBtn.wijtooltip("hide");
}
if(this.$fullScreenBtn.data("wijmoWijtooltip")) {
this.$fullScreenBtn.wijtooltip("hide");
}
};
wijvideo.prototype._localizeString = function (key, defaultValue) {
var o = this.options;
if(o.localization && o.localization[key]) {
return o.localization[key];
}
return defaultValue;
};
wijvideo.prototype._getToolTipContent = function (currentTime) {
var mm, ss, mfmt = '', sfmt = '';
mm = parseInt((currentTime / 60).toString(), 10);
ss = parseInt((currentTime - (mm * 60)).toString(), 10);
if(mm < 10) {
mfmt = '0';
}
if(ss < 10) {
sfmt = '0';
}
return mfmt + mm + ':' + sfmt + ss;
};
wijvideo.prototype._refresh = function () {
var pos;
this.$video.parent().find('.wijmo-wijvideo-controls').show();
pos = this.$vidParent.find('.wijmo-wijvideo-timer').position().left;
this.$seekSlider.width(pos - this.$seekSlider.position().left - 15);
this.$video.parent().find('.wijmo-wijvideo-controls').css('display', 'none');
if(!this.options.showControlsOnHover) {
$('.wijmo-wijvideo-controls', this.$vidParent).show();
this.$vidParent.height(this.$video.outerHeight() + $('.wijmo-wijvideo-controls').height());
}
};
wijvideo.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this;
//$.wijmo.widget.prototype.destroy.apply(this, arguments);
_super.prototype.destroy.call(this);
//remove the controls
this.$vidParent.after(this.$video).remove();
this.$video.unbind('.' + self.widgetName);
if(self._videoIsControls) {
self._setVideoAttribute("controls", true);
}
};
wijvideo.prototype.play = /** Play the video.
*/
function () {
this.$video[0].play();
};
wijvideo.prototype.pause = /** Pause the video.
*/
function () {
this.$video[0].pause();
};
wijvideo.prototype.getWidth = /** Gets the video width in pixel.
*/
function () {
return this.$video.outerWidth();
};
wijvideo.prototype.setWidth = /** Sets the video width in pixel.
* @param {number} width Width value in pixel.
* @example
* // Sets the video width to 600 pixel.
* $("#element").wijvideo("setWidth", 600);
*/
function (width) {
width = width || 600;
var origWidth = this.getWidth();
this.$video.attr('width', width);
this.$vidParent.width(this.$video.outerWidth());
this._positionControls(this.getWidth() - origWidth);
};
wijvideo.prototype.getHeight = /** Gets the video height in pixel.
*/
function () {
return this.$video.outerHeight();
};
wijvideo.prototype.setHeight = /** Sets the video height in pixel.
* @param {number} height Height value in pixel.
* @example
* // Sets the video height to 400 pixel.
* $("#element").wijvideo("setHeight", 400);
*/
function (height) {
height = height || 400;
this.$video.attr('height', height);
if(this.options.showControlsOnHover) {
this.$vidParent.height(this.$video.outerHeight());
} else {
this.$vidParent.height(this.$video.outerHeight() + $('.wijmo-wijvideo-controls').height());
}
};
return wijvideo;
})(wijmo.wijmoWidget);
video.wijvideo = wijvideo;
var wijvideo_options = (function () {
function wijvideo_options() {
/** Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijvideo')";
/** All CSS classes used in widgets that use jQuery UI CSS Framework.
* @ignore
*/
this.wijCSS = {
iconVolumeOn: "ui-icon-volume-on",
iconVolumeOff: "ui-icon-volume-off"
};
/** A value that indicates whether to show the full screen button. */
this.fullScreenButtonVisible = true;
/** Determines whether to display the controls only when hovering the mouse to the video. */
this.showControlsOnHover = true;
/** Use the localization option in order to localize text which not depends on culture.
* @remarks
* The default localization: {
* volumeToolTip: "Volume",
* fullScreenToolTip: "Full Screen"
* }
* @example
* $("#video").wijvideo(
* {
* localization: {
* volumeToolTip: "newVolume",
* fullScreenToolTip: "newFullScreen"
* }
* });
*/
this.localization = null;
}
return wijvideo_options;
})();
wijvideo.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijvideo_options());
$.wijmo.registerWidget("wijvideo", wijvideo.prototype);
})(wijmo.video || (wijmo.video = {}));
var video = wijmo.video;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/*globals jQuery*/
/*
* Depends:
* jquery.mobile.js
*
*/
(function (listview) {
"use strict";
var $ = jQuery, widgetName = "wijlistview";
var wijlistview = (function (_super) {
__extends(wijlistview, _super);
function wijlistview() {
_super.apply(this, arguments);
}
wijlistview.prototype._baseWidget = function () {
return $.mobile.listview;
};
return wijlistview;
})(wijmo.wijmoWidget);
listview.wijlistview = wijlistview;
// empty so far
if($.mobile) {
wijlistview.prototype.options = $.extend({
}, $.mobile.listview.prototype.options, wijmo.wijmoWidget.prototype.options, {
initSelector: ":jqmData(role='wijlistview')"
});
$.wijmo.registerWidget(widgetName, $.mobile.listview, wijlistview.prototype);
}
/** jQuery-mobile 1.3.1 */
if($.mobile && $.mobile.document) {
wijlistview.prototype.options.filter = false;
wijlistview.prototype.options.filterPlaceholder = "Filter items...";
wijlistview.prototype.options.filterTheme = "c";
wijlistview.prototype.options.filterReveal = false;
// TODO rename callback/deprecate and default to the item itself as the first argument
var defaultFilterCallback = function (text, searchValue, item) {
return text.toString().toLowerCase().indexOf(searchValue) === -1;
};
wijlistview.prototype.options.filterCallback = defaultFilterCallback;
$.mobile.document.delegate("ul, ol", "wijlistviewcreate", function () {
var list = $(this), listview = list.data("wijmoWijlistview");
if(!listview || !listview.options.filter) {
return;
}
if(listview.options.filterReveal) {
list.children().addClass("ui-screen-hidden");
}
var wrapper = $("<form>", {
"class": "ui-listview-filter ui-bar-" + listview.options.filterTheme,
"role": "search"
}).submit(function (e) {
e.preventDefault();
search.blur();
}), onKeyUp = function (e) {
var $this = $(this), val = this.value.toLowerCase(), listItems = null, li = list.children(), lastval = $this.jqmData("lastval") + "", childItems = false, itemtext = "", item, isCustomFilterCallback = // Check if a custom filter callback applies
listview.options.filterCallback !== defaultFilterCallback;
if(lastval && lastval === val) {
// Execute the handler only once per value change
return;
}
listview._trigger("beforefilter", "beforefilter", {
input: this
});
// Change val as lastval for next execution
$this.jqmData("lastval", val);
if(isCustomFilterCallback || val.length < lastval.length || val.indexOf(lastval) !== 0) {
// Custom filter callback applies or removed chars or pasted something totally different, check all items
listItems = list.children();
} else {
// Only chars added, not removed, only use visible subset
listItems = list.children(":not(.ui-screen-hidden)");
if(!listItems.length && listview.options.filterReveal) {
listItems = list.children(".ui-screen-hidden");
}
}
if(val) {
// This handles hiding regular rows without the text we search for
// and any list dividers without regular rows shown under it
for(var i = listItems.length - 1; i >= 0; i--) {
item = $(listItems[i]);
itemtext = item.jqmData("filtertext") || item.text();
if(item.is("li:jqmData(role=list-divider)")) {
item.toggleClass("ui-filter-hidequeue", !childItems);
// New bucket!
childItems = false;
} else if(listview.options.filterCallback(itemtext, val, item)) {
//mark to be hidden
item.toggleClass("ui-filter-hidequeue", true);
} else {
// There's a shown item in the bucket
childItems = true;
}
}
// Show items, not marked to be hidden
listItems.filter(":not(.ui-filter-hidequeue)").toggleClass("ui-screen-hidden", false);
// Hide items, marked to be hidden
listItems.filter(".ui-filter-hidequeue").toggleClass("ui-screen-hidden", true).toggleClass("ui-filter-hidequeue", false);
} else {
//filtervalue is empty => show all
listItems.toggleClass("ui-screen-hidden", !!listview.options.filterReveal);
}
listview._addFirstLastClasses(li, listview._getVisibles(li, false), false);
}, search = $("<input>", {
placeholder: listview.options.filterPlaceholder
}).attr("data-" + $.mobile.ns + "type", "search").jqmData("lastval", "").bind("keyup change input", onKeyUp).appendTo(wrapper).textinput();
if(listview.options.inset) {
wrapper.addClass("ui-listview-filter-inset");
}
wrapper.bind("submit", function () {
return false;
}).insertBefore(list);
});
wijlistview.prototype.options.autodividers = false;
wijlistview.prototype.options.autodividersSelector = function (elt) {
// look for the text in the given element
var text = $.trim(elt.text()) || null;
if(!text) {
return null;
}
// create the text for the divider (first uppercased letter)
text = text.slice(0, 1).toUpperCase();
return text;
};
$.mobile.document.delegate("ul,ol", "wijlistviewcreate", function () {
var list = $(this), listview = list.data("wijmoWijlistview");
if(!listview || !listview.options.autodividers) {
return;
}
var replaceDividers = function () {
list.find("li:jqmData(role='list-divider')").remove();
var lis = list.find('li'), lastDividerText = null, li, dividerText;
for(var i = 0; i < lis.length; i++) {
li = lis[i];
dividerText = listview.options.autodividersSelector($(li));
if(dividerText && lastDividerText !== dividerText) {
var divider = document.createElement('li');
divider.appendChild(document.createTextNode(dividerText));
divider.setAttribute('data-' + $.mobile.ns + 'role', 'list-divider');
li.parentNode.insertBefore(divider, li);
}
lastDividerText = dividerText;
}
};
var afterListviewRefresh = function () {
list.unbind('listviewafterrefresh', afterListviewRefresh);
replaceDividers();
listview.refresh();
list.bind('listviewafterrefresh', afterListviewRefresh);
};
afterListviewRefresh();
});
}
})(wijmo.listview || (wijmo.listview = {}));
var listview = wijmo.listview;
})(wijmo || (wijmo = {}));
/*
*
* Wijmo Library 3.20132.8
* http://wijmo.com/
*
* Copyright(c) GrapeCity, Inc. All rights reserved.
*
* Licensed under the Wijmo Commercial License. Also available under the GNU GPL Version 3 license.
* licensing@wijmo.com
* http://wijmo.com/widgets/license/
*
*
*/
/// <reference path="../../External/declarations/jquery.d.ts"/>
var wijmo;
(function (wijmo) {
wijmo.expando = ".wijmo";
/** @ignore */
var WijmoError = (function () {
function WijmoError(message) {
this.message = message;
this.stack = "Wijmo" + (new Error()).stack;
this.name = "WijmoError";
}
return WijmoError;
})();
wijmo.WijmoError = WijmoError;
var wijerr = WijmoError;
wijerr.prototype = new Error();
wijerr.prototype["constructor"] = wijerr;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
(function (data) {
/** @ignore */
var Expando = (function () {
function Expando(object) {
this.object = object;
}
Expando.getFrom = function getFrom(obj, create) {
if (typeof create === "undefined") { create = true; }
var propertyName = wijmo.expando, ext;
if(Object(obj) !== obj) {
return null;
}
ext = obj[propertyName];
if(ext && ext.object !== obj) {
ext = null;
}
if(create && !(ext instanceof Expando && Object.prototype.hasOwnProperty.call(obj, propertyName))) {
ext = new Expando(obj);
try {
Object.defineProperty(obj, propertyName, {
value: ext,
configurable: false,
enumerable: false,
writable: false
});
} catch (e) {
obj[propertyName] = ext;
}
}
return ext;
};
return Expando;
})();
data.Expando = Expando;
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
(function (data) {
/** @ignore */
(function (util) {
function funcClass(ctor) {
return function () {
var result = function () {
return ctor.prototype._call.apply(result, arguments);
};
$.extend(result, ctor.prototype);
ctor.apply(result, arguments);
return result;
};
}
util.funcClass = funcClass;
})(data.util || (data.util = {}));
var util = data.util;
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="./core.ts"/>
/// <reference path="./util.ts"/>
(function (data) {
var $ = jQuery;
/** @ignore */
var SubscriberEntry = (function () {
function SubscriberEntry(handler, context) {
this.handler = handler;
this.context = context;
}
SubscriberEntry.prototype.trigger = function (args) {
return this.handler.apply(this.context, args);
};
return SubscriberEntry;
})();
data.SubscriberEntry = SubscriberEntry;
/** @ignore */
var Subscribable = (function () {
function Subscribable(defaultContext) {
this.defaultContext = defaultContext;
this._entries = [];
}
Subscribable.prototype.subscribe = function (handler, context) {
if (typeof context === "undefined") { context = this.defaultContext; }
var _this = this;
var entry = new SubscriberEntry(handler, context);
this._entries.push(entry);
return {
dispose: function () {
return data.util.remove(_this._entries, entry);
}
};
};
Subscribable.prototype.trigger = function () {
var args = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
args[_i] = arguments[_i + 0];
}
data.util.each(this._entries, function (_, e) {
return e.trigger(args);
});
};
Subscribable.makeSubscribable = function makeSubscribable(obj) {
var subscribable = new Subscribable(obj);
obj.subscribe = $.proxy(subscribable.subscribe, subscribable);
return subscribable;
};
return Subscribable;
})();
data.Subscribable = Subscribable;
function isSubscriptable(subscribable) {
return $.isFunction(subscribable.subscribe);
}
data.isSubscriptable = isSubscriptable;
/** @ignore */
var BaseObservable = (function () {
function BaseObservable() { }
BaseObservable.prototype.subscribe = function (handler, context) {
this._subscribable = this._subscribable || new Subscribable(this);
return this._subscribable.subscribe(handler, context);
};
BaseObservable.prototype._trigger = function () {
var args = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
args[_i] = arguments[_i + 0];
}
if(this._subscribable) {
this._subscribable.trigger.apply(this._subscribable, arguments);
}
};
return BaseObservable;
})();
data.BaseObservable = BaseObservable;
/** @ignore */
var _ReadOnlyObservable = (function (_super) {
__extends(_ReadOnlyObservable, _super);
function _ReadOnlyObservable(mutable) {
_super.call(this);
this.mutable = mutable;
}
_ReadOnlyObservable.prototype._call = function () {
return this.mutable.value;
};
return _ReadOnlyObservable;
})(BaseObservable);
data._ReadOnlyObservable = _ReadOnlyObservable;
var ReadOnlyObservable = data.util.funcClass(_ReadOnlyObservable);
/** @ignore */
var _MutableObservable = (function (_super) {
__extends(_MutableObservable, _super);
function _MutableObservable(value, checkNewValue) {
if (typeof checkNewValue === "undefined") { checkNewValue = false; }
_super.call(this);
this.value = value;
this.checkNewValue = checkNewValue;
}
_MutableObservable.prototype._call = function (newValue) {
if(arguments.length > 0 && (!this.checkNewValue || newValue !== this.value)) {
this.value = newValue;
this._trigger(newValue);
if(this._readOnly) {
this._readOnly._trigger(newValue);
}
}
return this.value;
};
_MutableObservable.prototype.read = function () {
this._readOnly = this._readOnly || new ReadOnlyObservable(this);
return this._readOnly;
};
return _MutableObservable;
})(BaseObservable);
data._MutableObservable = _MutableObservable;
var MutableObservable = data.util.funcClass(_MutableObservable);
function observable(value) {
if (typeof value === "undefined") { value = null; }
return new MutableObservable(value);
}
data.observable = observable;
/** @ignore */
function observableWithNewValueCheck(value) {
if (typeof value === "undefined") { value = null; }
return new MutableObservable(value, true);
}
data.observableWithNewValueCheck = observableWithNewValueCheck;
function isObservable(observable) {
return $.isFunction(observable) && isSubscriptable(observable);
}
data.isObservable = isObservable;
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
(function (data) {
/// <reference path="./core.ts"/>
/// <reference path="./observable.ts"/>
/** @ignore */
(function (util) {
var $ = jQuery;
function clone(obj, deep) {
if (typeof deep === "undefined") { deep = false; }
if($.isArray(obj)) {
obj = obj.slice(0);
} else if($.isPlainObject(obj)) {
obj = $.extend(!!deep, {
}, obj);
}
return obj;
}
util.clone = clone;
function isString(str) {
return typeof str === "string" || str instanceof String;
}
util.isString = isString;
function isNumeric(value) {
return typeof value === "number";
}
util.isNumeric = isNumeric;
function isInternalProperty(p) {
return p === wijmo.expando || p === $.expando;
}
util.isInternalProperty = isInternalProperty;
function each(obj, fn) {
var _this = this;
$.each(obj, function (key, value) {
if(!isInternalProperty(key)) {
return fn.call(_this, key, value);
}
});
}
util.each = each;
function map(obj, fn) {
var result = $.map(obj, fn);
delete result[wijmo.expando];
return result;
}
util.map = map;
function toStr(obj) {
var text;
if(obj && $.isFunction(obj.toString) && obj.toString !== Object.prototype.toString) {
text = obj.toString();
} else {
text = JSON.stringify(obj);
}
if(text != null && text.length > 2 && text[0] === '"' && text[text.length - 1] === '"') {
text = text.substr(1, text.length - 2);
}
return text;
}
util.toStr = toStr;
function format(format) {
var args = [];
for (var _i = 0; _i < (arguments.length - 1); _i++) {
args[_i] = arguments[_i + 1];
}
return format.replace(/{(\d+)}/g, function (m, index) {
return toStr(args[parseInt(index, 10)]);
});
}
util.format = format;
function every(obj, predicate) {
var res = true;
each(obj, function (key, value) {
res = value;
if(predicate) {
res = predicate.call(res, res, key);
}
if(!res) {
return false;
}
});
return res;
}
util.every = every;
function some(obj, predicate) {
var res = false;
each(obj, function (key, value) {
res = value;
if(predicate) {
res = predicate.call(res, res, key);
}
if(res) {
return false;
}
});
return res;
}
util.some = some;
function compare(a, b) {
var i, len, cmp;
if(a == null) {
return b == null ? 0 : -1;
} else if(b == null) {
return 1;
}
if($.isArray(a) && $.isArray(b)) {
len = Math.min(a.length, b.length);
for(i = 0; i < len; i++) {
cmp = compare(a[i], b[i]);
if(cmp !== 0) {
return cmp;
}
}
return a.length - b.length;
} else if(isString(a) && isString(b)) {
a = a.toLowerCase();
b = b.toLowerCase();
return a < b ? -1 : a > b ? 1 : 0;
}
cmp = a - b;
return isNaN(cmp) ? 0 : cmp;
}
util.compare = compare;
function contains(array, elem) {
return $.inArray(elem, array) >= 0;
}
util.contains = contains;
function remove(array, elem) {
var removed = 0, i;
for(i = 0; i < array.length; ) {
if(array[i] !== elem) {
i++;
} else {
array.splice(i, 1);
removed++;
}
}
return removed;
}
util.remove = remove;
function pageCount(totalCount, pageSize) {
if(totalCount == -1) {
return -1;
} else if(totalCount == 0) {
return 0;
} else if(!pageSize) {
return 1;
} else {
return Math.ceil(totalCount / pageSize);
}
}
util.pageCount = pageCount;
;
function executeDelayed(fn, context) {
var args = [];
for (var _i = 0; _i < (arguments.length - 2); _i++) {
args[_i] = arguments[_i + 2];
}
function callback() {
return fn.apply(context, args);
}
if(typeof setTimeout === typeof undefined) {
return callback();
} else {
setTimeout(callback, 10);
}
}
util.executeDelayed = executeDelayed;
function logError(message) {
if(!console) {
return;
}
if(console.error) {
console.error(message);
} else if(console.log) {
console.log(message);
}
}
util.logError = logError;
function getProperty(obj, property) {
var start = 0, value = obj, key;
while(true) {
var point = property.indexOf('.', start);
if(point >= 0) {
key = property.substring(start, point);
start = point + 1;
} else if(start > 0) {
key = property.substring(start);
} else {
key = property;
}
value = value[key];
if(data.isObservable(value)) {
value = value();
}
if(point < 0) {
break;
}
}
return value;
}
util.getProperty = getProperty;
function setProperty(obj, property, newValue) {
var start = 0, key;
while(true) {
var point = property.indexOf('.', start);
if(point >= 0) {
key = property.substring(start, point);
start = point + 1;
} else if(start > 0) {
key = property.substring(start);
} else {
key = property;
}
var value = obj[key];
if(point >= 0) {
if(data.isObservable(value)) {
value = value();
}
obj = value;
} else {
if(data.isObservable(value)) {
value(newValue);
} else {
obj[key] = newValue;
}
break;
}
}
}
util.setProperty = setProperty;
function isClassInstance(instance) {
return typeof instance === "object" && !$.isArray(instance) && !$.isPlainObject(instance) && instance.constructor !== (Object.prototype).constructor;
}
util.isClassInstance = isClassInstance;
function convertDateProperties(entities) {
data.util.each(entities, function (_, entity) {
if(!entity || typeof entity !== "object") {
return;
}
data.util.each(entity, function (key, value) {
var match;
if(!data.util.isString(value)) {
return;
}
match = /\/Date\((-?\d+)\)\//.exec(value);
if(!match) {
return;
}
entity[key] = new Date(parseInt(match[1], 10));
});
});
}
util.convertDateProperties = convertDateProperties;
})(data.util || (data.util = {}));
var util = data.util;
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="./util.ts"/>
/** @ignore */
(function (data) {
data.errors = {
};
data.errors._register = function (messages) {
data.util.each(messages, function (name, msg) {
function create() {
var fmtArgs = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
fmtArgs[_i] = arguments[_i + 0];
}
var lastChar;
if($.isFunction(msg)) {
msg = msg.apply(this, arguments);
} else if(arguments.length > 0) {
fmtArgs.unshift(msg);
msg = data.util.format.apply(this, fmtArgs);
}
msg = $.trim(msg);
lastChar = msg[msg.length - 1];
if(lastChar !== '.' && lastChar !== '!' && lastChar !== '?') {
msg += '.';
}
return new wijmo.WijmoError(msg);
}
data.errors[name] = function () {
throw create.apply(this, arguments);
};
data.errors[name].create = create;
});
};
data.errors._register({
indexOutOfBounds: "Index is outside the bounds of the array.",
notImplemented: "The operation is not implemented",
unsupportedOperation: "Unsupported operation",
unsupportedFilterOperator: "Unsupported filter operator: {0}",
unsupportedDataSource: "Unsupported data source",
argument: function (paramName) {
var message = "Unexpected argument value.";
if(paramName) {
message += "\nParameter name: " + paramName;
}
return message;
},
argumentNull: "Argument '{0}' is null/undefined",
noParser: "There is no parser for type '{0}'",
noUrl: "Url is not specified",
cantConvert: "Value can't be converted to type '{0}': '{1}'",
noGlobalize: "Globalize is not defined. Make sure you include globalize.js",
itemNotInView: "Item {0} is not in the data view",
unsupportedFilterFormat: "The filter format is not supported",
multiPropertyKeysNotSupported: "Entities with multiple properties in the primary key are not supported. Entity type: {0}",
keyPropertyNotFound: "Key property not found in {0} entity type"
});
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
(function (data) {
/// <reference path="dataView.ts"/>
/** @ignore */
(function (filtering) {
var $ = jQuery;
filtering.opMap = {
"==": "equals",
doesnotcontain: "notcontain",
"!=": "notequal",
">": "greater",
"<": "less",
">=": "greaterorequal",
"<=": "lessorequal",
isnotempty: "notisempty",
isnotnull: "notisnull"
};
function findOperator(name, throwIfNotFound) {
if (typeof throwIfNotFound === "undefined") { throwIfNotFound = false; }
name = name.toLowerCase();
var op = filtering.ops[name];
if(!op) {
var mappedName = filtering.opMap[name];
if(mappedName) {
op = filtering.ops[mappedName];
}
}
if(!op && throwIfNotFound) {
data.errors.unsupportedFilterOperator(name);
}
return op;
}
function normalizeCondition(cond) {
var filter;
if(!$.isPlainObject(cond)) {
return {
operator: "==",
op: filtering.ops.equals,
value: cond
};
}
var op = cond.operator || filtering.ops.equals;
if(data.util.isString(cond.operator)) {
if(cond.operator.toLowerCase() === "nofilter") {
return null;
}
op = findOperator(cond.operator, true);
} else if(!$.isFunction(op.apply)) {
data.errors.unsupportedFilterOperator(op);
}
return {
operator: cond.operator,
op: op,
value: cond.value
};
}
filtering.normalizeCondition = normalizeCondition;
function compile(filter) {
var result = {
original: filter,
func: null,
normalized: null
};
if($.isFunction(filter)) {
result.func = filter;
} else if($.isArray(filter)) {
data.errors.unsupportedFilterFormat(filter);
} else if(filter) {
result.normalized = {
};
var hasConditions = false;
data.util.each(filter, function (prop, cond) {
if($.isArray(cond)) {
data.errors.unsupportedFilterFormat();
}
cond = normalizeCondition(cond);
if(cond) {
result.normalized[prop] = cond;
hasConditions = true;
}
});
if(!hasConditions) {
result.normalized = null;
} else {
result.func = function (x) {
return data.util.every(result.normalized, function (cond, prop) {
var propValue = data.util.getProperty(x, prop);
return cond.op.apply(propValue, cond.value);
});
};
}
}
if(!result.normalized && !result.func) {
result.func = function (x) {
return true;
};
}
return result;
}
filtering.compile = compile;
//#region operators
filtering.ops = (function () {
var ops = {
}, types = {
str: [
"string"
],
prim: [
"string",
"number",
"datetime",
"currency",
"boolean"
]
};
function op(name, displayName, arity, types, apply) {
return ops[name.toLowerCase()] = {
name: name,
displayName: displayName,
arity: arity,
applicableTo: types,
apply: apply
};
}
function preprocessOperand(value) {
if(value instanceof Date) {
value = value.getTime();
}
if(data.util.isString(value)) {
value = value.toLowerCase();
}
return value;
}
function bin(name, displayName, types, apply) {
op(name, displayName, 2, types, function (left, right) {
return apply(preprocessOperand(left), preprocessOperand(right));
});
}
function unary(name, displayName, types, apply) {
op(name, displayName, 1, types, apply);
}
function binprim(name, displayName, apply) {
bin(name, displayName, types.prim, apply);
}
function binstr(name, displayName, apply) {
bin(name, displayName, types.str, apply);
}
// Primitive binary operators
binprim("Equals", "Equals", function (l, r) {
return l == r;
});
binprim("NotEqual", "Not equal", function (l, r) {
return l != r;
});
binprim("Greater", "Greater than", function (l, r) {
return l > r;
});
binprim("Less", "Less than", function (l, r) {
return l < r;
});
binprim("GreaterOrEqual", "Greater or equal", function (l, r) {
return l >= r;
});
binprim("LessOrEqual", "Less or equal", function (l, r) {
return l <= r;
});
// String operators
binstr("Contains", "Contains", function (left, right) {
return left == right || left && left.indexOf && left.indexOf(right) >= 0;
});
binstr("NotContain", "Does not contain", function (left, right) {
return left != right && (!left || !left.indexOf || left.indexOf(right) < 0);
});
binstr("BeginsWith", "Begins with", function (left, right) {
return left == right || left && left.indexOf && left.indexOf(right) == 0;
});
binstr("EndsWith", "Ends with", function (left, right) {
var idx;
if(!data.util.isString(left) || !data.util.isString(right)) {
return false;
}
idx = left.lastIndexOf(right);
return idx >= 0 && left.length - idx === right.length;
});
// Unary operators
unary("IsEmpty", "Is empty", types.str, function (x) {
return !x && x !== 0 && x !== false;
})// null, undefined, or empty string
;
unary("NotIsEmpty", "Is not empty", types.str, function (x) {
return !!x || x === 0 || x === false;
});
unary("IsNull", "Is null", types.prim, function (x) {
return x == null;
});
unary("NotIsNull", "Is not null", types.prim, function (x) {
return x != null;
});
return ops;
})();
//#endregion operators
})(data.filtering || (data.filtering = {}));
var filtering = data.filtering;
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
(function (data) {
/// <reference path="dataView.ts"/>
/** @ignore */
(function (sorting) {
function normalize(sort) {
var result = [];
sort = data.util.isString(sort) ? sort.split(/,\s*/) : !$.isArray(sort) ? [
sort
] : sort.slice(0);
sort = $.isArray(sort) ? sort.slice(0) : [
sort
];
data.util.each(sort, function (_, prop) {
var asc = true, i;
if(prop == null) {
return;
}
if(!data.util.isString(prop)) {
if(prop.property != null) {
result.push(prop);
}
return;
}
if(prop[0] === "-") {
asc = false;
prop = prop.substr(1);
} else {
var match = /\s(asc|desc)\s*$/.exec(prop);
if(match) {
prop = prop.substr(0, match.index);
asc = !(match[1] === "desc");
}
}
result.push({
property: prop,
asc: asc
});
});
return result;
}
function compile(sort, compareTo) {
if (typeof compareTo === "undefined") { compareTo = data.util.compare; }
var normalized = normalize(sort);
var result = {
original: sort,
propertyCompareTo: compareTo,
compare: null,
normalized: normalized
};
if(normalized != null) {
result.compare = function (a, b) {
var i = 0, cmp, descr;
for(i = 0; i < normalized.length; i++) {
descr = normalized[i];
cmp = compareTo(data.util.getProperty(a, descr.property), data.util.getProperty(b, descr.property));
if(cmp !== 0) {
if(!descr.asc) {
cmp = -cmp;
}
return cmp;
}
}
return 0;
};
}
return result;
}
sorting.compile = compile;
})(data.sorting || (data.sorting = {}));
var sorting = data.sorting;
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="./core.ts"/>
/// <reference path="./filtering.ts"/>
/// <reference path="./sorting.ts"/>
/// <reference path="./arrayDataView.ts"/>
(function (data) {
var $ = jQuery;
var dataViewFactories = [];
/** Registers a new IDataView provider.
* @param {IDataViewFactory} factory A function that creates a IDataView for a data source if possible. Otherwise returns null.
* @returns An IDisposable that can be used to remove the registration.
* @remarks
* Use this method to provide your own IDataView implementation for a specific data source. See wijmo.data.breeze.ts for an example.
*/
function registerDataViewFactory(factory) {
if(!$.isFunction(factory)) {
data.errors.argument("factory");
}
dataViewFactories.push(factory);
return {
dispose: function () {
data.util.remove(dataViewFactories, factory);
}
};
}
data.registerDataViewFactory = registerDataViewFactory;
registerDataViewFactory(function (view) {
return isDataView(view) && view;
});
registerDataViewFactory(function (array) {
return $.isArray(array) && new data.ArrayDataView(array);
});
//#endregion Data view factories
/** Creates an IDataView for a data source.
* @param src A data source, can be anything that is supported by the registered IDataView providers
* @returns An IDataView instance for the data source.
*/
function asDataView(src) {
if(isDataView(src)) {
return src;
}
var view = data.util.some(dataViewFactories, function (p) {
return p(src);
});
return view || data.errors.unsupportedDataSource();
}
data.asDataView = asDataView;
/** Returns true if the view parameter is a IDataView */
function isDataView(view) {
return view && $.isFunction(view.count) && $.isFunction(view.item) && $.isFunction(view.getProperty);
}
data.isDataView = isDataView;
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="./core.ts"/>
/// <reference path="./arrayDataView.ts"/>
/** @ignore */
(function (data) {
var $ = jQuery;
var CurrencyManager = (function () {
function CurrencyManager(array) {
this.array = array;
this.currentItem = data.observableWithNewValueCheck(null);
this.currentPosition = data.observableWithNewValueCheck(-1);
var syncing = false;
function synced(fn) {
return function () {
if(syncing) {
return;
}
syncing = true;
try {
fn.apply(this, arguments);
}finally {
syncing = false;
}
};
}
this.currentItem.subscribe(synced(function (value) {
this.currentPosition(value == null ? -1 : $.inArray(value, this.array));
}), this);
this.currentPosition.subscribe(synced(function (value) {
if(!data.util.isNumeric(value)) {
data.errors.argument("value");
}
if(value < -1 || value >= this.array.length) {
data.errors.indexOutOfBounds();
}
this.currentItem(value < 0 ? null : this.array[value]);
}), this);
}
CurrencyManager.prototype.update = function () {
var item = this.currentItem(), pos = this.currentPosition(), newIndex = $.inArray(item, this.array);
if(newIndex < 0 && item == null && this._recentlyRemovedItem != null) {
newIndex = $.inArray(this._recentlyRemovedItem, this.array);
}
if(newIndex >= 0) {
if(item) {
this._recentlyRemovedItem = item;
}
this.currentPosition(newIndex);
} else if(pos >= 0 && pos < this.array.length) {
this.currentItem(this.array[pos]);
} else if(pos == this.array.length && this.array.length > 0) {
pos = this.array.length - 1;
this.currentPosition(pos);
this.currentItem(this.array[pos]);
} else {
this.currentPosition(-1);
this.currentItem(null);
}
};
CurrencyManager.prototype.updateDelayed = function () {
data.util.executeDelayed(this.update, this);
};
return CurrencyManager;
})();
data.CurrencyManager = CurrencyManager;
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
(function (data) {
var $ = jQuery;
/** @ignore */
var Shape = (function () {
function Shape(onChanged) {
this.onChanged = onChanged;
this.filter = data.observable();
this.sort = data.observable();
this.pageIndex = data.observable(0);
this.pageSize = data.observable(0);
this._skip = 0;
this._take = -1;
this.filter.subscribe(function (newValue) {
this.onFilterChanged(newValue);
onChanged();
}, this);
this.sort.subscribe(function () {
this._compiledSort = data.sorting.compile(this.sort());
onChanged();
}, this);
function updatePaging() {
if(this.pageSize() > 0 && this.pageIndex() >= 0) {
this._skip = this.pageSize() * this.pageIndex();
this._take = this.pageSize();
} else {
this._skip = 0;
this._take = -1;
}
onChanged(true);
}
this.pageIndex.subscribe(updatePaging, this);
this.pageSize.subscribe(updatePaging, this);
}
Shape.prototype.onFilterChanged = function (newValue) {
this._compiledFilter = data.filtering.compile(newValue);
};
Shape.prototype.setFilter = function (filter) {
this.filter(filter);
};
Shape.prototype.update = function (shape) {
if("filter" in shape) {
this.setFilter(shape.filter);
}
if("sort" in shape) {
this.sort(shape.sort);
}
if("pageSize" in shape) {
this.pageSize(shape.pageSize);
}
if("pageIndex" in shape) {
this.pageIndex(shape.pageIndex);
}
};
Shape.prototype.apply = function (array, applyPaging) {
if (typeof applyPaging === "undefined") { applyPaging = true; }
var _this = this;
var result = [];
// filter
data.util.each(array, function (i, item) {
if(_this._compiledFilter && !_this._compiledFilter.func(item)) {
return;
}
result.push(item);
});
// sort
if(this._compiledSort) {
result.sort(this._compiledSort.compare);
}
// page
var totalCount = result.length;
if(applyPaging && this._take > 0) {
if(this._skip > 0) {
result.splice(0, Math.min(this._skip, result.length));
}
if(this._take < result.length) {
result.length = this._take;
}
}
return {
results: result,
totalCount: totalCount
};
};
Shape.prototype.toObj = function () {
return {
filter: this._compiledFilter && this._compiledFilter.normalized,
sort: this._compiledSort && this._compiledSort.normalized,
pageSize: this.pageSize(),
pageIndex: this.pageIndex()
};
};
return Shape;
})();
data.Shape = Shape;
var ArrayDataViewBase = (function () {
function ArrayDataViewBase(shape) {
this.isRemote = false;
this.localPaging = true;
//#region items
this.local = [];
this._updatingShape = false;
this._pageCount = data.observable(1);
this._totalItemCount = data.observable(0);
//#endregion shape
//#region loading
this._isLoaded = data.observable(false);
this._isLoading = data.observable(false);
//#endregionn
//#region editing
this._currentEditItem = data.observable();
this._isCurrentEditItemNew = false;
this._currentEditItemSnapshot = null;
this.isLoading = this._isLoading.read();
this.isLoaded = this._isLoaded.read();
this._changed = new data.Subscribable(this);
this.currentEditItem = this._currentEditItem.read();
this._initCurrency();
this._initShape(shape);
}
ArrayDataViewBase.prototype.dispose = function () {
};
ArrayDataViewBase.prototype.count = function () {
return this.local.length;
};
ArrayDataViewBase.prototype.item = function (index) {
if(index < 0 || index >= this.local.length) {
data.errors.indexOutOfBounds();
}
return this.local[index];
};
ArrayDataViewBase.prototype.indexOf = function (item) {
return $.inArray(item, this.local);
};
ArrayDataViewBase.prototype.getSource = function () {
return this.sourceArray;
};
ArrayDataViewBase.prototype.toObservableArray = function () {
if(!this._koArray) {
this._koArray = ko.observableArray(this.local);
}
return this._koArray;
};
ArrayDataViewBase._getProps = //#endregion items
//#region properties
function _getProps(item) {
var cols = [];
data.util.each(item, function (key, value) {
key = String(key);
if(key.match(/^_/)) {
return;
}
if($.isFunction(value) && !value.subscribe) {
return;
}
cols.push({
name: key
});
});
return cols;
};
ArrayDataViewBase.prototype.getProperties = function () {
return this.count() ? ArrayDataViewBase._getProps(this.item(0)) : [];
};
ArrayDataViewBase.prototype._readProperty = function (item, property) {
return data.util.getProperty(item, property);
};
ArrayDataViewBase.prototype.getProperty = function (itemOrIndex, property) {
var entry = this._resolve(itemOrIndex, true);
return this._readProperty(entry.item, property);
};
ArrayDataViewBase.prototype._writeProperty = function (item, property, newValue) {
data.util.setProperty(item, property, newValue);
};
ArrayDataViewBase.prototype.setProperty = function (itemOrIndex, property, newValue) {
var entry = this._resolve(itemOrIndex, true);
if(entry.item === this.currentEditItem() && this._currentEditItemSnapshot && !(property in this._currentEditItemSnapshot)) {
this._currentEditItemSnapshot[property] = this.getProperty(itemOrIndex, property);
}
this._writeProperty(entry.item, property, newValue);
return this;
};
ArrayDataViewBase.prototype.subscribe = function (handler, context) {
return this._changed.subscribe(handler, context);
};
ArrayDataViewBase.prototype.trigger = function () {
this._currencyManager.update();
this._changed.trigger(this.local);
if(this._koArray) {
this._koArray.notifySubscribers(this.local);
}
};
ArrayDataViewBase.prototype.canFilter = function () {
return true;
};
ArrayDataViewBase.prototype.canSort = function () {
return true;
};
ArrayDataViewBase.prototype._updateShape = function (shape) {
this._updatingShape = true;
try {
this._shape.update(shape);
}finally {
this._updatingShape = false;
}
};
ArrayDataViewBase.prototype.prevPage = function () {
if(this.pageIndex() < 1) {
return false;
}
this.pageIndex(this.pageIndex() - 1);
return true;
};
ArrayDataViewBase.prototype.nextPage = function () {
if(this.pageCount() > 0 && this.pageIndex() + 1 >= this.pageCount()) {
return false;
}
this.pageIndex(this.pageIndex() + 1);
return true;
};
ArrayDataViewBase.prototype._createShape = function (onChanged) {
return new Shape(onChanged);
};
ArrayDataViewBase.prototype._initShape = function (shape) {
var _this = this;
var onChanged = function (onlyPaging) {
if (typeof onlyPaging === "undefined") { onlyPaging = false; }
if(!_this._updatingShape) {
_this.refresh(null, onlyPaging && _this.localPaging);
}
};
this._shape = this._createShape(onChanged);
if(shape) {
this._updateShape(shape);
}
this.filter = this._shape.filter;
this.sort = this._shape.sort;
this.pageIndex = this._shape.pageIndex;
this.pageSize = this._shape.pageSize;
this.pageCount = this._pageCount.read();
this.totalItemCount = this._totalItemCount.read();
};
ArrayDataViewBase.prototype._localRefresh = function (doPaging) {
if (typeof doPaging === "undefined") { doPaging = this.localPaging; }
var _this = this;
var result = this._shape.apply(this.sourceArray, doPaging);
this.local.length = 0;
$.each(result.results, function (_, x) {
return _this.local.push(x);
});
if(doPaging) {
this._totalItemCount(result.totalCount);
}
this._pageCount(data.util.pageCount(this.totalItemCount(), this.pageSize()));
// notify
this.trigger();
return $.Deferred().resolve().promise();
};
ArrayDataViewBase.prototype._remoteRefresh = function () {
return this._localRefresh();
};
ArrayDataViewBase.prototype.refresh = function (shape, local) {
if (typeof local === "undefined") { local = false; }
var _this = this;
this.cancelRefresh();
if(shape) {
this._updateShape(shape);
}
this._isLoading(true);
var promise = local ? this._localRefresh() : this._remoteRefresh();
return promise.then(function () {
_this._isLoaded(true);
_this._isLoading(false);
});
};
ArrayDataViewBase.prototype.cancelRefresh = function () {
};
ArrayDataViewBase.prototype._initCurrency = function () {
this._currencyManager = new data.CurrencyManager(this.local);
this.currentItem = this._currencyManager.currentItem;
this.currentPosition = this._currencyManager.currentPosition;
};
ArrayDataViewBase.prototype.isCurrentEditItemNew = function () {
return this._isCurrentEditItemNew;
};
ArrayDataViewBase.prototype._beginEdit = function (item, isNew) {
this.commitEdit();
this._currentEditItemSnapshot = {
};
this._isCurrentEditItemNew = isNew;
this._currentEditItem(item);
};
ArrayDataViewBase.prototype.canAdd = function () {
return true;
};
ArrayDataViewBase.prototype.add = function (item) {
if(!item) {
data.errors.argument("item");
}
this.commitEdit();
this.local.push(item);
this._beginEdit(item, true);
this.trigger();
};
ArrayDataViewBase.prototype.canAddNew = function () {
return false;
};
ArrayDataViewBase.prototype.addNew = function () {
return data.errors.unsupportedOperation();
};
ArrayDataViewBase.prototype.editItem = function (item) {
if (typeof item === "undefined") { item = this.currentItem(); }
this.commitEdit();
var entry = this._resolve(item);
if(entry) {
this._beginEdit(entry.item, false);
}
};
ArrayDataViewBase.prototype.canRemove = function () {
return true;
};
ArrayDataViewBase.prototype._remove = function (entry) {
this.local.splice(entry.index, 1);
data.util.remove(this.sourceArray, entry.item);
this.trigger();
};
ArrayDataViewBase.prototype.remove = function (item) {
if (typeof item === "undefined") { item = this.currentItem(); }
this.commitEdit();
var entry = this._resolve(item);
if(!entry) {
return false;
}
this._remove(entry);
return true;
};
ArrayDataViewBase.prototype.canCancelEdit = function () {
return true;
};
ArrayDataViewBase.prototype.cancelEdit = function () {
var _this = this;
var key;
if(!this.currentEditItem()) {
return;
}
var item = this.currentEditItem();
this._currentEditItem(null);
if(this._isCurrentEditItemNew) {
data.util.remove(this.local, this.item);
} else if(this._currentEditItemSnapshot) {
$.each(this._currentEditItemSnapshot, function (k, v) {
return _this._writeProperty(item, k, v);
});
}
this.trigger();
};
ArrayDataViewBase.prototype.canCommitEdit = function () {
return true;
};
ArrayDataViewBase.prototype.commitEdit = function () {
if(!this.currentEditItem()) {
return;
}
var item = this.currentEditItem;
this._currentEditItem(null);
if(this._isCurrentEditItemNew) {
this.sourceArray.push(item);
}
var filter = this._shape._compiledFilter && this._shape._compiledFilter.func;
if(filter && !filter(item)) {
data.util.remove(this.local, item);
}
this.trigger();
};
ArrayDataViewBase.prototype._resolve = //#endregion editing
function (itemOrIndex, raiseIfNotContained) {
if (typeof raiseIfNotContained === "undefined") { raiseIfNotContained = false; }
var index;
if(data.util.isNumeric(itemOrIndex)) {
return {
index: itemOrIndex,
item: this.item(itemOrIndex)
};
} else {
index = this.indexOf(itemOrIndex);
if(index < 0) {
if(raiseIfNotContained) {
data.errors.itemNotInView(itemOrIndex);
}
return null;
}
return {
index: index,
item: itemOrIndex
};
}
};
return ArrayDataViewBase;
})();
data.ArrayDataViewBase = ArrayDataViewBase;
var ArrayDataView = (function (_super) {
__extends(ArrayDataView, _super);
function ArrayDataView(source, shape) {
_super.call(this, shape);
this.sourceArray = source;
this.refresh();
}
return ArrayDataView;
})(ArrayDataViewBase);
data.ArrayDataView = ArrayDataView;
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="arrayDataView.ts"/>
(function (data) {
var $ = jQuery;
var RemoteDataView = (function (_super) {
__extends(RemoteDataView, _super);
function RemoteDataView(options) {
_super.call(this);
this.isRemote = true;
this.sourceArray = [];
if(options) {
this._construct(options);
}
}
RemoteDataView.prototype._construct = function (options) {
this.options = options = $.extend({
localPaging: false
}, options);
this.localPaging = options.localPaging;
this._updateShape(options);
};
return RemoteDataView;
})(data.ArrayDataViewBase);
data.RemoteDataView = RemoteDataView;
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/*globals jQuery, Globalize, wijmo */
/*
* Depends:
* wijmo.data.js
* globalize.js
* jquery.js
*
*/
(function (data) {
var $ = jQuery;
var wijdatasourceReader = (function () {
function wijdatasourceReader(originalReader) {
this._originalReader = originalReader;
}
wijdatasourceReader.prototype.read = function (wijDataSource) {
wijDataSource.items = null;
if(this._originalReader && $.isFunction(this._originalReader.read)) {
this._originalReader.read(wijDataSource);
}
if(!$.isArray(wijDataSource.items)) {
if($.isArray(wijDataSource.data)) {
wijDataSource.items = wijDataSource.data;
} else if(wijDataSource.data && $.isArray(wijDataSource.data.rows)) {
wijDataSource.items = wijDataSource.data.rows// remoteDynamical
;
} else {
wijDataSource.items = [];
}
}
if(wijDataSource.dynamic) {
if(!wijDataSource.data || isNaN(wijDataSource.data.totalRows)) {
throw "totalRows value is missing";
}
}
};
return wijdatasourceReader;
})();
var WijdatasourceView = (function (_super) {
__extends(WijdatasourceView, _super);
function WijdatasourceView(dataSource) {
var _this = this;
_super.call(this);
this.dataSource = dataSource;
this.isRemote = true;
this.localPaging = true;
this._origLoaded = dataSource.loaded;
this._origReader = dataSource.reader;
dataSource.loaded = function (e, data) {
_this._loaded();
if($.isFunction(_this._origLoaded)) {
_this._origLoaded.apply(_this, arguments);
}
};
dataSource.reader = new wijdatasourceReader(dataSource.reader);
var hasItems = dataSource.items && dataSource.items.length > 0;
if($.isArray(dataSource.data) && !hasItems) {
dataSource.read();
}
if(dataSource.items) {
this._loaded();
}
}
WijdatasourceView.prototype.dispose = function () {
this.dataSource.loaded = this._origLoaded;
this.dataSource.reader = this._origReader;
_super.prototype.dispose.call(this);
};
WijdatasourceView.prototype.getProperties = function () {
return this.sourceArray && this.sourceArray.length ? data.ArrayDataViewBase._getProps(this.sourceArray[0]) : [];
};
WijdatasourceView.prototype._loaded = function () {
this.sourceArray = this.dataSource.items;
if(this.dataSource.data && data.util.isNumeric(this.dataSource.data.totalRows)) {
this._totalItemCount(this.dataSource.data.totalRows);
}
var def = _super.prototype._localRefresh.call(this, !this.dataSource.dynamic);
if(this._currentDeferred) {
def.then(this._currentDeferred.resolve);
}
};
WijdatasourceView.prototype._remoteRefresh = function () {
if(this._currentDeferred && this._currentDeferred.state() === "pending") {
this._currentDeferred.fail();
}
this._currentDeferred = $.Deferred();
var userData = {
}, forceReload = false;
if(this.dataSource.dynamic) {
forceReload = true;
userData.data = this._prepareRequest();
if(this.dataSource.proxy) {
if(!this._origDataOption) {
this._origDataOption = $.extend({
}, this.dataSource.proxy.options.data);
}
this.dataSource.proxy.options.data = $.extend({
}, this._origDataOption, userData.data);
}
}
this.dataSource.load(userData, forceReload);
return this._currentDeferred;
};
WijdatasourceView.prototype._prepareRequest = function () {
return {
filtering: this._prepareFilterRequest(),
paging: this._preparePageRequest(),
sorting: this._prepareSortRequest()
};
};
WijdatasourceView.prototype._prepareFilterRequest = function () {
var result = [];
if(this._shape._compiledFilter && this._shape._compiledFilter.normalized) {
$.each(this._shape._compiledFilter.normalized, function (prop, cond) {
result.push({
dataKey: prop,
filterOperator: cond.op.Name,
filterValue: cond.value
});
});
}
return result;
};
WijdatasourceView.prototype._preparePageRequest = function () {
return {
pageIndex: this._shape.pageIndex(),
pageSize: this._shape.pageSize()
};
};
WijdatasourceView.prototype._prepareSortRequest = function () {
if(!this._shape._compiledSort || !this._shape._compiledSort.normalized || this._shape._compiledSort.normalized.length == 0) {
return [];
}
return $.map(this._shape._compiledSort.normalized, function (sd) {
return {
dataKey: sd.property,
sortDirection: sd.asc ? "ascending" : "descending"
};
});
};
return WijdatasourceView;
})(data.ArrayDataViewBase);
data.registerDataViewFactory(function (wds) {
if(typeof wijdatasource !== "function" || !(wds instanceof wijdatasource)) {
return;
}
return new WijdatasourceView(wds);
});
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts"/>
/*globals jQuery*/
/*jslint white: false */
/*
* Depends:
* jquery-1.9.1.js
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.wijmo.widget.js
*/
(function (pager) {
"use strict";
var $ = jQuery;
/** @widget */
var wijpager = (function (_super) {
__extends(wijpager, _super);
function wijpager() {
_super.apply(this, arguments);
}
wijpager.prototype._create = function () {
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
this.element.addClass(this.options.wijCSS.widget + " wijmo-wijpager " + this.options.wijCSS.helperClearFix);
if(this.options.disabled) {
this.disable();
}
this._refresh();
};
wijpager.prototype._destroy = function () {
this.element.removeClass(this.options.wijCSS.widget + " wijmo-wijpager " + this.options.wijCSS.helperClearFix);
this.$ul.remove();
};
wijpager.prototype._setOption = function (key, value) {
this._super(key, value);
this._refresh();
};
wijpager.prototype._refresh = function () {
this._validate();
if(this.$ul) {
this.$ul.remove();
}
this.element.append(this.$ul = $("<ul class=\"ui-list " + this.options.wijCSS.cornerAll + " " + this.options.wijCSS.content + " " + this.options.wijCSS.helperClearFix + "\" role=\"tablist\"></ul>"));
switch((this.options.mode || "").toLowerCase()) {
case "nextprevious":
this._createNextPrev(false);
break;
case "nextpreviousfirstlast":
this._createNextPrev(true);
break;
case "numeric":
this._createNumeric(false);
break;
case "numericfirstlast":
this._createNumeric(true);
break;
}
};
wijpager.prototype._validate = function () {
var o = this.options;
if(isNaN(o.pageCount) || o.pageCount < 1) {
o.pageCount = 1;
}
if(isNaN(o.pageIndex) || o.pageIndex < 0) {
o.pageIndex = 0;
} else {
if(o.pageIndex >= o.pageCount) {
o.pageIndex = o.pageCount - 1;
}
}
if(isNaN(o.pageButtonCount) || o.pageButtonCount < 1) {
o.pageButtonCount = 1;
}
};
wijpager.prototype._createNextPrev = function (addFirstLast) {
var o = this.options;
// first button
if(addFirstLast && o.pageIndex) {
this.$ul.append(this._createPagerItem(false, o.firstPageText, 1, o.firstPageClass));
}
// previous button
if(o.pageIndex) {
this.$ul.append(this._createPagerItem(false, o.previousPageText, o.pageIndex, o.previousPageClass));
}
// next button
if(o.pageIndex + 1 < o.pageCount) {
this.$ul.append(this._createPagerItem(false, o.nextPageText, o.pageIndex + 2, o.nextPageClass));
}
// last button
if(addFirstLast && (o.pageIndex + 1 < o.pageCount)) {
this.$ul.append(this._createPagerItem(false, o.lastPageText, o.pageCount, o.lastPageClass));
}
};
wijpager.prototype._createNumeric = function (addFirstLast) {
var o = this.options, currentPage = o.pageIndex + 1, startPageNumber = 1, endPageNumber = Math.min(o.pageCount, o.pageButtonCount), i;
if(currentPage > endPageNumber) {
startPageNumber = (Math.floor(o.pageIndex / o.pageButtonCount)) * o.pageButtonCount + 1;
endPageNumber = startPageNumber + o.pageButtonCount - 1;
endPageNumber = Math.min(endPageNumber, o.pageCount);
if(endPageNumber - startPageNumber + 1 < o.pageButtonCount) {
startPageNumber = Math.max(1, endPageNumber - o.pageButtonCount + 1);
}
}
// first + "..." buttons
if(startPageNumber !== 1) {
// first button
if(addFirstLast) {
this.$ul.append(this._createPagerItem(false, o.firstPageText, 1, o.firstPageClass));
}
// "..." button
this.$ul.append(this._createPagerItem(false, "...", startPageNumber - 1, ""));
}
// page numbers buttons
for(i = startPageNumber; i <= endPageNumber; i++) {
this.$ul.append(this._createPagerItem(i === currentPage, i.toString(), i, ""));
}
// "..." + last buttons
if(o.pageCount > endPageNumber) {
this.$ul.append(this._createPagerItem(false, "...", endPageNumber + 1, ""));
// last button
if(addFirstLast) {
this.$ul.append(this._createPagerItem(false, o.lastPageText, o.pageCount, o.lastPageClass));
}
}
};
wijpager.prototype._createPagerItem = function (active, title, pageIndex, btnClass) {
var btnContent, wijCSS = this.options.wijCSS, self = this, $li = $("<li />").addClass("wijmo-wijpager-button " + wijCSS.cornerAll).attr({
"role": "tab",
"aria-label": title,
"title": title
});
if(active) {
$li.addClass(wijCSS.stateActive).attr("aria-selected", "true");
} else {
$li.addClass(wijCSS.stateDefault).hover(function () {
if(!self.options.disabled) {
$(this).removeClass(wijCSS.stateDefault).addClass(wijCSS.stateHover);
}
}, function () {
if(!self.options.disabled) {
$(this).removeClass(wijCSS.stateHover).addClass(wijCSS.stateDefault);
}
}).bind("click." + this.widgetName, {
newPageIndex: pageIndex - 1
}, $.proxy(this._onClick, this))// pageIndex is 1-based.
;
}
if(active) {
btnContent = $("<span />");
} else {
btnContent = btnClass ? $("<span />").addClass(wijCSS.icon + " " + btnClass) : $("<a/>").attr("href", "#");
}
btnContent.text(title);
$li.append(btnContent);
return $li;
};
wijpager.prototype._onClick = function (arg) {
if(this.options.disabled) {
return false;
}
var pagingArgs = {
newPageIndex: arg.data.newPageIndex,
handled: false
};
if(this._trigger("pageIndexChanging", null, pagingArgs) !== false) {
if(this.options.pageIndex !== pagingArgs.newPageIndex) {
this.options.pageIndex = pagingArgs.newPageIndex;
if(!pagingArgs.handled) {
this._refresh();
}
var pagedArgs = {
newPageIndex: pagingArgs.newPageIndex
};
this._trigger("pageIndexChanged", null, pagedArgs);
}
}
return false;
};
return wijpager;
})(wijmo.wijmoWidget);
pager.wijpager = wijpager;
wijpager.prototype.widgetEventPrefix = "wijpager";
var wijpager_options = (function () {
function wijpager_options() {
/** @ignore */
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body-c",
stateDefault: "ui-btn-up-c",
stateHover: "ui-btn-down-b",
stateActive: "ui-btn-down-c"
};
/**
* An option that indicates the class of the first-page button. You can set this option with any of the jQuery UI CSS Framework icons.
* @default "ui-icon-seek-first"
* @example
* // Here's the general way you'll set the option:
* $("#element").wijpager({
* firstPageClass: "ui-icon-seek-first"
* });
*/
this.firstPageClass = $.wijmo.widget.prototype.options.wijCSS.iconSeekFirst;
/**
* An option that indicates the text to display for the first-page button. The text will display like a tooltip when a user hovers over the first-page button.
* @example
* // Here's the general way you'll set the option:
* $("#element").wijpager({
* firstPageText: "Go To First"
* });
*/
this.firstPageText = "First";
/**
* An option that indicates the class of the last-page button. You can set this option with any of the jQuery UI CSS Framework icons.
* @default "ui-icon-seek-end"
* @example
* // Here's the general way you'll set the option:
* $("#element").wijpager({
* lastPageClass: "ui-icon-seek-end"
* });
*/
this.lastPageClass = $.wijmo.widget.prototype.options.wijCSS.iconSeekEnd;
/**
* An option that indicates the text to display for the last-page button. The text will display like a tooltip when a user hovers over the last-page button.
* @example
* // Here's the general way you'll set the option:
* $("#element").wijpager({
* lastPageText: "Go To Last"
* });
*/
this.lastPageText = "Last";
/**
* This option determines the pager mode. The possible values for this option are: "nextPrevious", "nextPreviousFirstLast", "numeric", "numericFirstLast".
* @remarks
* Possible values are: "nextPrevious", "nextPreviousFirstLast", "numeric", "numericFirstLast".
* "nextPrevious": a set of pagination controls consisting of Previous and Next buttons.
* "nextPreviousFirstLast": a set of pagination controls consisting of Previous, Next, First, and Last buttons.
* "numeric": a set of pagination controls consisting of numbered link buttons to access pages directly.
* "numericFirstLast": a set of pagination controls consisting of numbered and First and Last link buttons.
* @example
* // Here's the general way you'll set the option:
* $("#element").wijpager({
* mode: "nextPrevious"
* });
*/
this.mode = "numeric";
/**
* An option that indicates the class of the next-page button. You can set this option with any of the jQuery UI CSS Framework Icons.
* @default "ui-icon-seek-next"
* @example
* // Here's the general way you'll set the option:
* $("#element").wijpager({
* nextPageClass: "ui-icon-seek-next"
* });
*/
this.nextPageClass = $.wijmo.widget.prototype.options.wijCSS.iconSeekNext;
/**
* An option that indicates the text to display for the next-page button. The text appears like a tooltip when a user hovers over the next-page button.
* @example
* // Here's the general way you'll set the option:
* $("#element").wijpager({
* nextPageText: "Go To Next"
* });
*/
this.nextPageText = "Next";
/**
* An option that indicates the number of page buttons to display in the pager. You can customize how many page buttons are available for your users to use to page through content.
* You can use this option in conjunction with the pageCount to customize the pager display.
* @example
* // Here's the general way you'll set the option:
* $("#element").wijpager({
* pageButtonCount: 15
* });
*/
this.pageButtonCount = 10;
/**
* An option that indicates the class of the previous-page button. You can set this option with any of the jQuery UI CSS Framework Icons.
* @type {string}
* @default "ui-icon-seek-prev"
* @example
* // Here's the general way you'll set the option:
* $("#element").wijpager({
* previousPageClass: "ui-icon-seek-prev"
* });
*/
this.previousPageClass = $.wijmo.widget.prototype.options.wijCSS.iconSeekPrev;
/**
* An option that indicates the text to display for the previous-page button. The text appears like a tooltip when a user hovers over the previous-page button.
* @example
* // Here's the general way you'll set the option:
* $("#element").wijpager({
* previousPageText: "Go To Previous"
* });
*/
this.previousPageText = "Previous";
/**
* An option that indicates the total number of pages. This option allows you to customize the total number of pages that your users will be able to page through. You can use this option in conjunction with the pageButtonCount to customize the pager display.
* @example
* // Here's the general way you'll set the option:
* $("#element").wijpager({
* pageCount: 10
* });
*/
this.pageCount = 1;
/**
* An option that indicates the zero-based index of the current page. By default, your pager will display with the first pager button highlighted since its index is 0.
* @example
* // Here's the general way you'll set the option. This will allow your pager widget to display with the 3rd page button highlighted:
* $("#element").wijpager({
* pageIndex: 2
* });
*/
this.pageIndex = 0;
/**
* The pageIndexChanging event handler is a function called when page index is changing. This item is cancellable if you return false.
* @event
* @param {object} e The jQuery.Event object.
* @param {wijmo.grid.IPageIndexChangingEventArgs} args The data associated with this event.
* @example
* // Supply a callback function to handle the event:
* $("#element").wijpager({
* pageIndexChanging: function (e, args) {
* // Handle the event here.
* }
* });
* // Bind to the event by type:
* $("#element").bind("wijpagerpageindexchanging", function (e, args) {
* // Handle the event here.
* });
*
* // You can cancel this event be returning false:
* $("#element").wijpager({
* pageIndexChanging: function(e, args) {
* return false;
* }
* });
*/
this.pageIndexChanging = null;
/**
* The pageIndexChanged event handler is a function called when the page index is changed.
* @event
* @param {object} e The jQuery.Event object.
* @param {wijmo.grid.IPageIndexChangedEventArgs} args The data associated with this event.
* @example
* // Supply a callback function to handle the event:
* $("#element").wijpager({
* pageIndexChanged: function (e, args) {
* // Handle the event here.
* }
* });
* // Bind to the event by type:
* $("#element").bind("wijpagerpageindexchanged", function (e, args) {
* // Handle the event here.
* });
*
* // You can also use this event to get the selected page by using the args.newPageIndex parameter:
* $("#element").wijpager({
* pageIndexChanged: function(e, args) {
* var selectedPageIndex = args.newPageIndex;
* }
* });
*/
this.pageIndexChanged = null;
}
return wijpager_options;
})();
;
wijpager.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijpager_options());
$.wijmo.registerWidget("wijpager", wijpager.prototype);
;
})(wijmo.pager || (wijmo.pager = {}));
var pager = wijmo.pager;
})(wijmo || (wijmo = {}));
;
(function ($) {
"use strict";
$.fn.extend({
wijtextselection: function () {
/// <summary>jQuery plugins to get/set text selection for input element</summary>
var start, end, t = this[0];
var val = this.val();
if (arguments.length === 0) {
var range, stored_range, s, e;
if ($.browser.msie && $.browser.version < 9) {
try {
var selection = document.selection;
if (t.tagName.toLowerCase() != "textarea") {
//$(this).focus();
range = selection.createRange().duplicate();
range.moveEnd("character", val.length);
s = (range.text === "" ? val.length : val.lastIndexOf(range.text));
range = selection.createRange().duplicate();
range.moveStart("character", -val.length);
e = range.text.length;
} else {
range = selection.createRange();
stored_range = range.duplicate();
stored_range.moveToElementText(t);
stored_range.setEndPoint('EndToEnd', range);
s = stored_range.text.length - range.text.length,
e = s + range.text.length
}
}
catch(e) {}//fixed bug 26153
} else {
s = t.selectionStart;
e = t.selectionEnd;
}
var te = val.substring(s, e);
return { start: s, end: e, text: te, replace: function (st) {
return val.substring(0, s) + st + val.substring(e, val.length)
}
};
} else if (arguments.length === 1) {
if (typeof arguments[0] === "object" && typeof arguments[0].start === "number" && typeof arguments[0].end === "number") {
start = arguments[0].start;
end = arguments[0].end;
} else if (typeof arguments[0] === "string") {
if ((start = val.indexOf(arguments[0])) > -1) {
end = start + arguments[0].length;
}
} else if (Object.prototype.toString.call(arguments[0]) === "[object RegExp]") {
var re = arguments[0].exec(val);
if (re != null) {
start = re.index;
end = start + re[0].length;
}
}
} else if (arguments.length === 2) {
if (typeof arguments[0] === "number" && typeof arguments[1] === "number") {
start = arguments[0];
end = arguments[1];
}
}
if (typeof start === "undefined") {
start = 0;
end = val.length;
}
if ($.browser.msie) {
var selRange = t.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end - start);
selRange.select();
} else {
t.selectionStart = start;
t.selectionEnd = end;
}
}
});
})(jQuery);
;
/*globals window jQuery */
/*
*
* Depends:
* jquery.js
* jquery.ui.js
*
*/
(function ($) {
"use strict";
/// <summary>
/// wijdatasource reads local raw data or remote raw data through proxy by using
/// a DataReader and provide tabular object data for widgets.
/// </summary>
var wijdatasource, wijarrayreader, wijhttpproxy;
wijdatasource = function (options) {
var self = this;
/// <summary>
/// The data to process using the wijdatasource class.
/// Default: {}.
/// Type: Object.
/// </summary>
self.data = {};
/// <summary>
/// The reader to use with wijdatasource. The wijdatasource class will call the
/// read method of reader to read from rawdata with an array of fields provided.
/// The field contains a name, mapping and defaultValue properties which define
/// the rule of the mapping.
/// If no reader is configured with wijdatasource it will directly return the
/// raw data.
/// Default: null.
/// Type: Object.
/// </summary>
self.reader = null;
/// <summary>
/// The proxy to use with wijdatasource. The wijdatasource class will call
/// the proxy object's request method.
/// In the proxy object, you can send a request to a remote server to
/// obtain data with the ajaxs options object provided.
/// Then you can use the wijdatasource reader to process the raw data in the call.
/// Default: null.
/// Type: Object.
/// </summary>
self.proxy = null;
/// <summary>
/// The processed items from the raw data. This can be obtained after
/// datasource is loaded.
/// Default: [].
/// Type: Array.
/// </summary>
self.items = [];
/// <summary>
/// Function called before loading process starts
/// Default: null.
/// Type: Function.
/// Code example:
/// var datasource = new wijdatasource({loading: function(e, data) { }})
/// </summary>
/// <param name="datasource" type="wijdatasource">
/// wijdatasource object that raises this event.
/// </param>
/// <param name="data" type="Object">
/// data passed in by load method.
/// </param>
self.loading = null;
/// <summary>
/// Function called after loading.
/// Default: null.
/// Type: Function.
/// Code example:
/// var datasource = new wijdatasource({loaded: function(e, data) { }})
/// </summary>
/// <param name="datasource" type="wijdatasource">
/// wijdatasource object that raises this event.
/// </param>
/// <param name="data" type="Object">
/// data passed in by load method.
/// </param>
self.loaded = null;
self._constructor(options);
};
window.wijdatasource = wijdatasource;
$.extend(wijdatasource.prototype, {
_constructor: function (options) {
$.extend(this, options);
},
load: function (data, forceLocalReload) {
/// <summary>
/// Triggers data loading process of wijdatasource.
/// </summary>
/// <param name="data" type="Object">
/// The data to pass to the loading and loaded event handler.
/// </param>
/// <param name="forceLocalReload" type="Boolean">
/// Normally local data is only load for one time,
/// if needs to reload the data, try to set forceLocalReload to true.
/// </param>
var self = this,
p = self.proxy;
//var d = self.data;
// fire loading event.
if ($.isFunction(self.loading)) {
//self.loading(self, data);
//if return false in loading event, cancel this request.
if (self.loading(self, data) === false) {
return;
}
}
// if datasource has an proxy object, it will use the request method of
// proxy to retrive the raw data.
if (p) {
// pass callback function to request method so that proxy could
// call the function when request is finished.
p.request(self, self.loaded, data);
}
else {
// local data is loaded only once, if force loading is needed
// forceLocalReload should be true.
if (self.items.length === 0 || forceLocalReload) {
// no proxy, read raw data
this.read();
}
// callback function is called
if ($.isFunction(self.loaded)) {
self.loaded(self, data);
}
}
},
read: function () {
/// <summary>
/// Triggers data reading process of wijdatasource
/// by using a DataReader if presented.
/// </summary>
var self = this,
d = self.data;
// reads using a reader object
if (d && self.reader) {
self.reader.read(self);
}
else {
// returns raw data if no reader is configured with datasource.
self.items = self.data;
//removed by Jeffrey for removing unnecessary return
//return self.data;
//end by Jeffrey
}
}
});
/// <summary>
/// wijdatasource ArrayReader reads from a array and processes items.
/// </summary>
wijarrayreader = function (fields) {
// this.fields to store the fields info
// Add for parse objectValue options for jUICE. D.H
if ($.isFunction(window["wijmoASPNetParseOptions"])) {
wijmoASPNetParseOptions(fields);
}
if ($.isArray(fields)) {
this.fields = fields;
}
};
window.wijarrayreader = wijarrayreader;
$.extend(wijarrayreader.prototype, {
read: function (datasource) {
/// <summary>
/// Starts reading data.
/// </summary>
/// <param name="datasource" type="wijdatasource">
/// The wijdatasource using this DataReader.
/// </param>
// convert the raw data of wijdatasource
if ($.isArray(datasource.data)) {
datasource.items = this._map(datasource.data);
}
else {
datasource.items = [];
}
},
_map: function (data) {
var self = this, arr = [];
if (self.fields === undefined || self.fields.length === 0) {
$.extend(true, arr, data);
return arr;
}
else {
$.each(data, function (index, value) {
var i = {};
$.each(self.fields, function (index, field) {
// mapping property is a function,
// the return value will be used as value.
//handle the juice
if (field.mapping && typeof field.mapping && window[field.mapping]) {
field.mapping = window[field.mapping];
}
if ($.isFunction(field.mapping)) {
i[field.name] = field.mapping(value);
return true;
}
// use string field mapping or number index mapping.
var mapping = field.mapping !== undefined ?
field.mapping : field.name,
v = value[mapping];
if (v === undefined) {
if (field.defaultValue !== undefined) {
v = field.defaultValue;
}
else {
v = value;
}
}
i[field.name] = v;
});
arr.push(i);
});
}
return arr;
}
});
/// <summary>
/// wijdatasource HttpProxy fetches data by using Ajax request.
/// </summary>
wijhttpproxy = function (options) {
this.options = options;
// Add for parse objectValue options for jUICE. D.H
if ($.isFunction(window["wijmoASPNetParseOptions"])) {
wijmoASPNetParseOptions(options);
}
};
window.wijhttpproxy = wijhttpproxy;
$.extend(wijhttpproxy.prototype, {
request: function (datasource, callBack, userData) {
/// <summary>
/// Starts requesting data.
/// </summary>
/// <param name="datasource" type="wijdatasource">
/// The wijdatasource using this DataReader.
/// </param>
/// <param name="callback" type="Function">
/// The function to call after requesting data successfully.
/// </param>
var self = this,
o = $.extend({}, this.options),
oldSuccess = o.success;
o.success = function (data) {
if ($.isFunction(oldSuccess)) {
oldSuccess(data);
}
self._complete(data, datasource, callBack, o, userData);
};
$.ajax(o);
},
_complete: function (data, datasource, callback, options, userData) {
// set raw data
datasource.data = options.key !== undefined ? data[options.key] : data;
// read raw data using a data reader in datasource
datasource.read();
// fire loaded callback
if ($.isFunction(callback)) {
callback(datasource, userData);
}
}
});
} (jQuery));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/// <reference path="../external/declarations/globalize.d.ts" />
/*globals jQuery,window,document*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.wijmo.wijtooltip.js
*/
(function (combobox) {
"use strict";
var $ = jQuery, widgetName = "wijcombobox";
var inputCSS = "wijmo-wijcombobox-input";
/** @widget */
var wijcombobox = (function (_super) {
__extends(wijcombobox, _super);
function wijcombobox() {
_super.apply(this, arguments);
}
wijcombobox.prototype._create = function () {
var t = this, focusElement;
// inits selected items
t.selectedItem = null;
t.selectedItems = [];
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
//When trying to access the document.activeElement object in an page
//that is loaded in an iframe in the Sys.Application.Load event
//"Unspecified error" exception will throw.
//Add code here to fix this issue.
//document.documentElement.focus();
//end comments.
try {
focusElement = document.activeElement;
} catch (e) {
}// inits wijcombobox
t._initInnerData();
t._createDOMElements();
t._bindInputEvents();
t._initDropDownList();
t.repaint();
t._checkSelectIndex();
if(t._usingRemoteData() && t.options.data) {
t.originalDataSourceLoaded = t.options.data.loaded;
}
//If combo is in an invisible iframe, exception will throw.
//add this in try block to prevent this exception.
//focusElement = document.activeElement;
if(focusElement === t._input[0] && t.options.isEditable) {
$(function () {
t._input.focus();
});
}
//update for visibility change
if(t.element.is(":hidden") && t.element.wijAddVisibilityObserver) {
t.element.wijAddVisibilityObserver(function () {
t.repaint();
if(t.element.wijRemoveVisibilityObserver) {
t.element.wijRemoveVisibilityObserver();
}
}, "wijcombobox");
}
};
wijcombobox.prototype._initInnerData = function () {
var self = this, o = self.options, isBind;
if(o.datasource !== null) {
isBind = self._isBind();
if(isBind) {
self.innerData = self._getMappingItems();
} else {
self.innerData = o.data;
}
}
self.listHasCreated = false;
};
wijcombobox.prototype._checkSelectIndex = function () {
var self = this, index, o = self.options, data = self.innerData;
if(o.selectedIndex === -1 && o.selectedValue) {
$.each(data, function (i, item) {
if(data[i].value === o.selectedValue) {
self.options.selectedIndex = i;
return false;
}
});
}
index = o.selectedIndex;
if(!self._usingRemoteData() && (index >= 0 || $.isArray(index))) {
self.search(null, "checkindex");
}
// if the selecteIndex is -1 and selectedValue is null, the text
// option will give to combobox
if(o.selectedIndex === -1 && o.text) {
if(!o.forceSelectionText || (o.forceSelectionText && self._checkTextInItems(o.text) !== -1)) {
self._input.val(o.text);
}
}
};
wijcombobox.prototype.repaint = /** Repaints wijcombobox. Returns true if it succeeds;
* otherwise, returns false.
* @returns {boolean} true if it succeeds; otherwise, returns false.
*/
function () {
var o = this.options, self = this;
if(self.element.is(":visible") || self._comboDiv || (self._select !== undefined && self._input.is(":visible"))) {
self._showTrigger();
if(o.disabledState) {
var dis = o.disabled;
self.disable();
o.disabled = dis;
}
if(o.disabled) {
self.disable();
}
return true;
}
return false;
};
wijcombobox.prototype._bindInputEvents = function () {
var self = this, wijCSS = this.options.wijCSS, input, o, code, keyCode, inputText;
input = self._input;
o = self.options;
// self.element is an html input element.
input.bind("keydown.wijcombobox", function (event) {
if(o.disabledState === true || o.disabled) {
return;
}
code = event.keyCode;
//keyCode = $.ui.keyCode;
keyCode = self._getKeyCodeEnum();
switch(code) {
case keyCode.UP:
self._move("previous", event);
// prevent moving cursor to beginning of
// text field in some browsers
event.preventDefault();
break;
case keyCode.DOWN:
self._move("next", event);
// prevent moving cursor to end of text field in some browsers
event.preventDefault();
break;
case keyCode.ENTER:
// when menu is open or has focus
if(self.menu.active) {
event.preventDefault();
//update for issue 24045
if(o.selectionMode === "multiple" && self.menu && self.menu.items && self.menu.items.length === 1) {
$.each(self.selectedItems, function (index, i) {
if(i !== self.menu.items[0]) {
i.selected = false;
}
});
}
//end
self.menu.select(event);
}
event.preventDefault()//update for issue 24134 at 2012/7/19
;
break;
//passthrough - ENTER and TAB both select the current element
case keyCode.TAB:
input.trigger("wijcomboblur");
if(!self.menu.active || (o.selectionMode === "multiple" && keyCode.TAB === code)) {
return;
}
self.menu.select(event);
// remove selection from input.
var end = input.val().length;
self._selectText(end, end, input);
break;
case keyCode.ESCAPE:
self.close(event, undefined);
break;
case keyCode.LEFT:
case keyCode.RIGHT:
case keyCode.SHIFT:
case 16:
case 17:
//ctrl for jquery 1.9
case keyCode.CONTROL:
case keyCode.HOME:
case keyCode.END:
case keyCode.DELETE:
case keyCode.PAGE_UP:
case keyCode.PAGE_DOWN:
// ignore metakeys (shift, ctrl, alt)
break;
case 18:
//alt key
input.trigger("wijcomboblur");
break;
default:
// keypress is triggered before the input value is changed
window.clearTimeout(self.searching);
if(o.isEditable === false) {
if(self._cacheKey === undefined) {
self._cacheKey = "";
}
self._cacheKey += String.fromCharCode(code);
}
self.searching = window.setTimeout(function () {
var term;
if(o.isEditable === false) {
term = self._cacheKey;
self._cacheKey = undefined;
} else {
term = input.val();
}
self.search(term, event);
}, o.delay);
break;
}
}).bind("wijcomboblur.wijcombobox", function (event) {
window.clearTimeout(self.searching);
self._addInputFocus(false, wijCSS.stateFocus);
// TODO try to implement this without a timeout,
// see clearTimeout in search()
self.closing = window.setTimeout(function () {
self.close(event, true);
}, 150);
}).bind("focus.wijcombobox", function () {
self._addInputFocus(true, wijCSS.stateFocus);
}).bind("blur.wijcombobox", function () {
if(!self.menu.element.is(":visible")) {
input.trigger("wijcomboblur");
}
inputText = input.val();
if(o.text !== inputText) {
self._trigger("textChanged", null, {
oldText: o.text,
newText: inputText
});
}
self._change();
});
};
wijcombobox.prototype._addInputFocus = function (add, css) {
var self = this, wrap, key, arrow;
wrap = self._input.parent();
key = add ? "addClass" : "removeClass";
arrow = self._triggerArrow;
wrap[key](css);
if(arrow !== undefined) {
arrow[key](css);
}
};
wijcombobox.prototype._renderColumnsHeader = function (header) {
var self = this, ul = $("<ul class='wijmo-wijcombobox-rowheader'></ul>");
$.each(this.options.columns, function (index, column) {
var li = $("<li class='wijmo-wijcombobox-cell " + self.options.wijCSS.header + "'></li>");
li.html(column.name);
if(column.width !== undefined) {
li.width(column.width);
}
li.appendTo(ul);
});
header.append(ul);
};
wijcombobox.prototype._hasSameValueText = function (item1, item2) {
return item1.label === item2.label && item1.value === item2.value;
};
wijcombobox.prototype._initDropDownList = function () {
var self = this, doc, menuElement, o, header, listOptions, wijCSS = this.options.wijCSS, zIndex = parseInt(self._input.css("zIndex"), 10), dropDownContainer;
doc = self.element[0].ownerDocument;
if(isNaN(zIndex)) {
zIndex = 0;
}
if(!self._comboDiv) {
menuElement = $("<div class='wijmo-wijcombobox-list'></div>");
} else {
menuElement = self._oriList;
}
o = self.options;
if(o.columns.length > 0) {
menuElement.addClass("wijmo-wijcombobox-multicolumn");
header = $("<div class='wijmo-wijsuperpanel-header " + wijCSS.stateDefault + "'></div>");
self._renderColumnsHeader(header);
menuElement.append(header);
}
listOptions = {
keepHightlightOnMouseLeave: true,
selectionMode: o.selectionMode,
addHoverItemClass: o.columns.length === 0,
focus: function (e, item) {
var i = item;
if(o.selectOnItemFocus) {
self.menu.select(null, {
notCloseAfterSelected: true
});
}
if(o.columns.length > 0) {
if(i.element) {
i.element.prev().addClass("wijmo-wijcombobox-active-prev");
i.element.find(".wijmo-wijcombobox-row>.wijmo-wijcombobox-cell").addClass(wijCSS.stateHover);
}
}
},
selected: function (event, ui) {
window.clearTimeout(self.closing);
var mode = o.selectionMode, item, newIndex, cancelSelect = false, oldText, oldIndex, oldItem;
item = ui.item;
if(self._trigger("select", event, item)) {
if(mode === "single") {
// single mode selection
// local data select
if(!self._usingRemoteData()) {
newIndex = $.inArray(item, self.items);
if(newIndex === undefined) {
newIndex = ui.selectedIndex;
}
if(newIndex !== o.selectedIndex) {
oldIndex = o.selectedIndex;
oldItem = self.selectedItem;
cancelSelect = self._triggerSelectedIndexChanging(oldItem, item, oldIndex, newIndex);
if(cancelSelect) {
return;
}
self._setInputText(item.label);
if(oldItem !== null) {
oldItem.selected = false;
}
self.selectedItem = item;
o.selectedIndex = newIndex;
o.selectedValue = self.selectedItem.value;
// fire select change event
if(self._select !== undefined) {
self._select[0].selectedIndex = o.selectedIndex;
self._select.trigger("change");
}
o.inputTextInDropDownList = true;
o.text = self._input.val();
if(oldItem && oldItem.element) {
oldItem.element.removeClass("wijmo-wijcombobox-selecteditem");
}
self._trigger("changed", null, {
oldItem: oldItem,
selectedItem: self.selectedItem,
newIndex: o.selectedIndex,
oldIndex: oldIndex
});
self._triggerSelectedIndexChanged(oldItem, self.selectedItem, oldIndex, o.selectedIndex);
} else {
// for fixing bug 24133 at 2012/8/6
if(self.selectedItem && self._input.val() !== self.selectedItem.label && (ui.data === undefined || !ui.data.notCloseAfterSelected)) {
self._input.val(item.label);
}
}
} else {
// If items have the same text and value,
// they are considered to be same in remote mode.
if(self.selectedItem === null || !self._hasSameValueText(item, self.selectedItem)) {
oldItem = self.selectedItem;
oldIndex = o.selectedIndex;
cancelSelect = self._triggerSelectedIndexChanging(oldItem, item, oldIndex, ui.selectedIndex);
if(cancelSelect) {
return;
}
//self._input.val(item.label);
self._setInputText(item.label);
o.text = self._input.val();
self.selectedItem = item;
//update for 29162 issue.
newIndex = $.inArray(item, self.items);
if(newIndex === undefined) {
newIndex = ui.selectedIndex;
}
if(newIndex !== o.selectedIndex) {
o.selectedIndex = newIndex;
o.selectedValue = self.selectedItem.value;
}
//end
o.inputTextInDropDownList = true;
self._trigger("changed", null, {
selectedItem: item
});
self._triggerSelectedIndexChanged(oldItem, item, oldIndex, o.selectedIndex);
}
}
} else {
// multiple selection mode
if(!self._usingRemoteData()) {
cancelSelect = self._triggerSelectedIndexChanging(null, item, oldIndex, ui.selectedIndex);
if(cancelSelect) {
return;
}
self.selectedItems = ui.selectedItems;
self._selectedItemsToInputVal(self.selectedItems);
o.inputTextInDropDownList = true;
o.selectedIndex = ui.selectedIndex;
self._trigger("changed", null, {
selectedItem: item,
selectedItems: self.selectedItems
});
self._triggerSelectedIndexChanged(null, item, null, o.selectedIndex);
///TODO: show helper list
}
}
}
if((ui.data === undefined || !ui.data.notCloseAfterSelected) && mode === "single") {
self.close(event);
self._input.focus();
}
},
blur: function (e, item) {
var d = item.element;
if(o.columns.length > 0 && d) {
d.find(".wijmo-wijcombobox-row>.wijmo-wijcombobox-cell").removeClass(wijCSS.stateHover);
d.prev().removeClass("wijmo-wijcombobox-active-prev");
}
},
itemRendering: function (event, data) {
var item = data, css;
css = "";
if(item.isSeparator) {
css += " wijmo-wijcombobox-separator";
}
if(item.selected) {
css += " wijmo-wijcombobox-selecteditem";
}
if(css.length > 0) {
item.element.addClass(css);
}
},
itemRendered: function (event, data) {
var item = data, li, u;
if(item.cells === undefined) {
return;
}
li = item.element;
li.empty();
u = $("<ul class='wijmo-wijcombobox-row'></ul>");
$.each(item.cells, function (index, cell) {
var l = $("<li class='wijmo-wijcombobox-cell " + wijCSS.stateDefault + "'></li>");
//Fix a bug that columns.width doesn't work.
if(o.columns && o.columns.length > index) {
if(typeof o.columns[index].width !== "undefined") {
l.width(o.columns[index].width);
}
}
//end comments.
l.append(cell);
l.attr("title", cell);
u.append(l);
});
li.append(u);
},
superPanelOptions: {
resized: function (e) {
var m = self.menu, ele = m.element;
o.dropdownWidth = ele.outerWidth();
o.dropdownHeight = ele.outerHeight();
self._positionList();
self.menu.refreshSuperPanel();
}
}
};
listOptions = $.extend(true, listOptions, o.listOptions);
dropDownContainer = o.ensureDropDownOnBody ? $("body") : self._comboElement;
self.menu = menuElement.appendTo(dropDownContainer, doc).wijlist(listOptions).css(//.zIndex(self._input.zIndex() + 1)
{
zIndex: zIndex + 1,
top: 0,
left: 0
}).hide().data("wijmoWijlist");
self._createDropDownList();
self._menuUL = self.menu.ul;
};
wijcombobox.prototype._setInputText = function (text, firedTextChanged) {
var self = this, oldText = self._input.val();
self._input.val(text);
if(oldText !== text) {
self._trigger("textChanged", null, {
oldText: oldText,
newText: text
});
}
};
wijcombobox.prototype._triggerSelectedIndexChanged = function (oldItem, newItem, oldIndex, newIndex) {
var o = this.options, curSelectedIdx;
if(o.selectionMode === "single") {
this._trigger("selectedIndexChanged", null, {
oldItem: oldItem,
selectedItem: newItem,
newIndex: newIndex,
oldIndex: oldIndex
});
} else {
curSelectedIdx = $.inArray(newItem, this.items);
this._trigger("selectedIndexChanged", null, {
selectedItem: newItem,
selectedIndex: curSelectedIdx,
selectedItems: this.selectedItems
});
}
};
wijcombobox.prototype._triggerSelectedIndexChanging = function (oldItem, newItem, oldIndex, newIndex) {
var o = this.options, curSelectedIdx, args, isSelect = true;
if(o.selectionMode === "single") {
args = {
oldItem: oldItem,
selectedItem: newItem,
newIndex: newIndex,
oldIndex: oldIndex
};
isSelect = this._trigger("selectedIndexChanging", null, args);
} else {
curSelectedIdx = $.inArray(newItem, this.items);
args = {
selectedItem: newItem,
selectedIndex: curSelectedIdx,
selectedItems: this.selectedItems
};
isSelect = this._trigger("selectedIndexChanging", null, args);
}
if(!isSelect) {
newItem.selected = false;
if(newItem.element) {
newItem.element.removeClass("wijmo-wijcombobox-selecteditem");
}
}
return !isSelect;
};
wijcombobox.prototype._createDropDownList = function (datasrc) {
var self = this, items, o = self.options, datasource = datasrc;
if(!datasource) {
datasource = self.innerData;
}
if(datasource === null) {
items = null;
} else {
items = $.isArray(datasource) ? datasource : datasource.items;
}
if(self._comboDiv) {
//update for case 20689 at 2012/4/11
if(!self.listHasCreated && items && items.length > 0) {
self.menu.setTemplateItems(o.data);
self.menu.renderList();
self.listHasCreated = true;
}
} else {
if(!self.listHasCreated && items && items.length > 0) {
self.menu.setItems(items);
self.menu.renderList();
self.listHasCreated = true;
}
}
};
wijcombobox.prototype._getSelectedItemsText = function (items) {
var s = "", self, sep;
self = this;
sep = self.options.multipleSelectionSeparator;
self.selectedItems = items;
$.each(items, function (index, item) {
//update for bug 24045
if(item) {
s += item.label + sep;
}
});
if(s.length > 0) {
s = s.substr(0, s.lastIndexOf(sep));
}
return s;
};
wijcombobox.prototype._selectedItemsToInputVal = function (items) {
var self = this;
//self._input.val(self._getSelectedItemsText(items));
self._setInputText(self._getSelectedItemsText(items));
self.options.text = self._input.val();
};
wijcombobox.prototype._createDOMElements = function () {
var self = this, comboElement, wijCSS = this.options.wijCSS, ele, input, wrapperElement;
wrapperElement = $("<div class='wijmo-wijcombobox-wrapper " + wijCSS.stateDefault + " " + wijCSS.cornerAll + "'>" + "</div>");
// check if element is a select element
ele = self.element;
// create from a select element
if(ele.is("select")) {
comboElement = $("<div role='combobox' class='wijmo-wijcombobox " + wijCSS.widget + " " + wijCSS.helperClearFix + "'>" + "</div>");
comboElement.append(wrapperElement);
self._comboElement = comboElement;
self._select = ele;
// add class to set font size to get the correct width of select.
ele.addClass(wijCSS.widget);
input = self._input = $("<input role='textbox' " + "aria-autocomplete='list' aria-haspopup='true' />").insertAfter(ele);
if(!self.options.data) {
self.options.data = self._convertSelectOptions();
self._initInnerData();
}
} else if(ele.is("div") && $(ele.children()[0]).is("input[type='text']") && $(ele.children()[1]).is("div")) {
//div tag
self._comboElement = self._comboDiv = comboElement = ele;
self._oriList = $(ele.children()[1]);
input = self._input = $(ele.children()[0]);
wrapperElement.prependTo(comboElement).append(input);
ele.addClass("wijmo-wijcombobox " + wijCSS.widget + " " + wijCSS.helperClearFix);
ele.attr("role", "combobox");
} else {
comboElement = $("<div role='combobox' class='wijmo-wijcombobox " + wijCSS.widget + " " + wijCSS.helperClearFix + "'>" + "</div>");
comboElement.append(wrapperElement);
self._comboElement = comboElement;
input = self._input = ele;
}
if(!self._comboDiv) {
comboElement.insertBefore(input);
//update for fixing bug 17328 at 2011/10/18 by wuhao
//add visible judge for visibility change at 2012/7/24
if(self.element.is(":visible")) {
input.width(input.width());
}
//end for fixing bug 17328
comboElement.children(".wijmo-wijcombobox-wrapper").append(input);
}
if(ele.attr("title")) {
self._comboElement.attr("title", ele.attr("title"));
}
input.attr({
autocomplete: "off",
role: "textbox",
"aria-wijcombobox": "list",
"aria-haspopup": "true"
}).addClass(inputCSS);
self._oldWidth = ele.css("width");
if(self.options.isEditable === false) {
input.attr("readonly", "readonly");
//update for add issue: when iseditable is false
//click the all the combobox, the dropdown list will open
wrapperElement.bind("click", function () {
if(self.options.disabledState === true || self.options.disabled) {
return;
}
self._triggerClick();
});
}
if(self.options.disabledState === true || self.options.disabled === true) {
input.attr("disabled", "disabled");
}
comboElement.bind("mouseenter", function () {
if(self.options.disabledState === true || self.options.disabled) {
return;
}
self._addInputFocus(true, wijCSS.stateHover);
}).bind("mouseleave", function () {
self._addInputFocus(false, wijCSS.stateHover);
});
};
wijcombobox.prototype._convertSelectOptions = function () {
var items = [], self, selectOptions;
self = this;
selectOptions = self._select.get(0).options;
$.each(selectOptions, function (idx, opt) {
items.push({
label: opt.text,
value: opt.value
});
});
//update for case 28976
if(self.options.selectedIndex === -1 && self.options.selectedValue === null && self.options.text === null) {
self.options.selectedIndex = self._select[0].selectedIndex;
}
return items;
};
wijcombobox.prototype.getComboElement = /** @ignore */
function () {
return this._comboElement;
};
wijcombobox.prototype._showTrigger = function () {
var self = this, o, input, inputWrapper, comboElement, wijCSS = this.options.wijCSS, selectClone, selectWidth = 0, trigger, label, sp, padding, labelPadding, triggerPadding, labelHTML = "<label class='wijmo-wijcombobox-label " + wijCSS.content + "'></label>", triggerHTML = "<div class='wijmo-wijcombobox-trigger " + wijCSS.stateDefault + " " + wijCSS.cornerRight + "'>" + "<span class='" + wijCSS.icon + " " + wijCSS.iconArrowDown + "'></span>" + "</div>";
o = self.options;
input = self._input;
inputWrapper = input.parent();
comboElement = self._comboElement;
trigger = self._triggerArrow;
label = self._label;
// set size
if(self._select !== undefined) {
if(!$.browser.msie) {
selectWidth = self._select.width();
} else {
selectClone = self._select.clone();
self._select.after(selectClone);
selectWidth = selectClone.width();
selectClone.remove();
}
//update for bind array
input.width(selectWidth + (self.innerData.length > 20 ? o.selectElementWidthFix : 0));
self._select.hide();
}
//update for fixing bug 15920 by wuhao
input.css("margin-left", "");
input.css("margin-right", "");
//end for bug 15920.
comboElement.width(inputWrapper[0].offsetWidth);
//comboElement.height(inputWrapper[0].offsetHeight);
// show label
if(o.labelText !== null) {
label = self._label = $(labelHTML);
inputWrapper.append(label.html(o.labelText));
} else {
if(label !== undefined) {
label.remove();
self._label = undefined;
}
}
if(o.showTrigger) {
input.removeClass(wijCSS.cornerAll);
if(trigger === undefined) {
trigger = self._triggerArrow = $(triggerHTML);
comboElement.append(trigger);
trigger.bind("mouseover.triggerevent", self, function (e) {
if(o.disabledState === true || o.disabled) {
return;
}
var ct = $(e.currentTarget);
ct.addClass(wijCSS.stateHover);
}).bind("mousedown.triggerevent", self, function (e) {
if(o.disabledState === true || o.disabled) {
return;
}
var ct = $(e.currentTarget);
ct.addClass(wijCSS.stateActive);
}).bind("mouseup.triggerevent", self, function (e) {
var ct = $(e.currentTarget);
ct.removeClass(wijCSS.stateActive);
}).bind("click.triggerevent", self, function () {
if(o.disabledState === true || o.disabled) {
return;
}
self._triggerClick();
});
}
if(o.triggerPosition === "right") {
trigger.css({
left: "",
right: "0px"
});
trigger.removeClass(wijCSS.cornerLeft);
trigger.addClass(wijCSS.cornerRight);
} else {
trigger.css({
"right": "",
"left": "0px"
});
trigger.removeClass(wijCSS.cornerRight);
trigger.addClass(wijCSS.cornerLeft);
}
trigger.setOutHeight(comboElement.innerHeight());
sp = trigger.find("span");
sp.css("margin-left", (trigger.innerWidth() - sp[0].offsetWidth) / 2);
sp.css("margin-top", (trigger.innerHeight() - sp[0].offsetHeight) / 2);
} else {
if(trigger !== undefined) {
trigger.unbind(".triggerevent");
trigger.remove();
self._triggerArrow = undefined;
}
input.removeClass(wijCSS.cornerLeft);
input.removeClass(wijCSS.cornerRight);
input.addClass(wijCSS.cornerAll);
}
// padding
padding = labelPadding = triggerPadding = 0;
if(label !== undefined) {
labelPadding += label[0].offsetWidth;
}
if(trigger !== undefined) {
triggerPadding = trigger[0].offsetWidth;
}
padding = labelPadding + triggerPadding;
input.setOutWidth(inputWrapper.innerWidth() - padding);
padding = padding === 0 ? "" : padding;
if(o.triggerPosition === "right") {
input.css("margin-left", "");
input.css("margin-right", padding);
if(label !== undefined) {
label.css("left", "");
label.css("right", triggerPadding);
}
} else {
input.css("margin-right", "");
input.css("margin-left", padding);
if(label !== undefined) {
label.css("right", "");
label.css("left", triggerPadding);
}
}
};
wijcombobox.prototype._triggerClick = function (e) {
var self = this, term = "";
window.clearTimeout(self.closing);
if(self.menu.element.is(":visible")) {
self.close();
} else {
// TODO: click open should not render again.
if(self._usingRemoteData()) {
term = self._input.val();
}
self.search(term, e);
}
};
wijcombobox.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this, wijCSS = this.options.wijCSS, ele = self.element;
if(self.options.isEditable === false) {
ele.removeAttr("readonly");
}
if(self._select !== undefined) {
self._select.removeClass(wijCSS.widget);
self._select.show();
self._input.remove();
} else if(self._comboDiv) {
self._comboDiv.removeClass("wijmo-wijcombobox " + wijCSS.widget + " " + wijCSS.helperClearFix);
self._comboDiv.removeAttr("role");
self._input.insertBefore(self._comboDiv);
self._comboDiv.children(".wijmo-wijcombobox-wrapper").remove();
} else {
ele.css("width", self._oldWidth);
ele.removeClass(inputCSS);
ele.removeAttr("autocomplete").removeAttr("role").removeAttr("aria-wijcombobox").removeAttr("aria-haspopup");
ele.insertBefore(self._comboElement);
ele.css("padding", "");
}
self._comboElement.remove();
self.menu.destroy();
self.menu.element.remove();
$.wijmo.widget.prototype.destroy.call(self);
};
wijcombobox.prototype._setOption = function (key, value) {
var self = this, ele, input, items, inputWrapper, cancelSelect, wijCSS = this.options.wijCSS, label = self._label, triggerPadding, oldSelectedIndex, newSelectedItem, oldSelectedItem = null, triggerWidth = 0, labelHTML = "<label class='wijmo-wijcombobox-label " + wijCSS.content + "'></label>", o = self.options;
ele = self._comboElement;
input = self.element;
inputWrapper = input.parent();
oldSelectedIndex = o.selectedIndex;
if(self._triggerArrow) {
triggerWidth = self._triggerArrow.outerWidth();
}
$.wijmo.widget.prototype._setOption.apply(self, arguments);
if(key === "disabled") {
if(value) {
ele.addClass("wijmo-wijcombobox-disabled " + wijCSS.stateDisabled);
//update for 27917
self._input.attr("disabled", "disabled");
if(self._comboDiv) {
self._input.addClass("wijmo-wijcombobox-disabled " + wijCSS.stateDisabled).attr("disabled", "disabled");
}
if(self._triggerArrow) {
self._triggerArrow.unbind("click.triggerevent");
}
self.close();
} else {
ele.removeClass("wijmo-wijcombobox-disabled " + wijCSS.stateDisabled);
self._input.removeAttr("disabled");
if(self._comboDiv) {
self._input.removeClass("wijmo-wijcombobox-disabled " + wijCSS.stateDisabled).removeAttr("disabled");
}
if(self._triggerArrow) {
self._triggerArrow.bind("click.triggerevent", self, function () {
if(o.disabledState === true) {
return;
}
self._triggerClick();
});
}
}
} else if(key === "labelText") {
if(o.labelText !== null) {
label = self._label = $(labelHTML);
self._input.parent().append(label.html(o.labelText));
if(self._triggerArrow !== undefined) {
triggerPadding = self._triggerArrow[0].offsetWidth;
}
if(o.triggerPosition === "right") {
if(label !== undefined) {
label.css("left", "");
label.css("right", triggerPadding);
}
} else {
if(label !== undefined) {
label.css("right", "");
label.css("left", triggerPadding);
}
}
self.repaint();
} else {
if(label !== undefined) {
label.remove();
self._label = undefined;
}
}
} else if(key === "showTrigger") {
self._showTrigger();
if(!o.showTrigger && self.element.is("select")) {
input.width(input.width() + triggerWidth);
}
} else if(key === "triggerPosition") {
input.width(input.width() + triggerWidth);
self._showTrigger();
} else if(key === "selectionMode") {
self.menu._setOption("selectionMode", value);
} else if(key === "isEditable") {
if(value) {
//update for 27917
self._input.removeAttr("readonly");
//update for add issue: when iseditable is false
//click the all the combobox, the dropdown list will open
$(".wijmo-wijcombobox-wrapper", self._comboElement[0]).bind("click", function () {
self._triggerClick();
});
} else {
//update for 27917
self._input.attr("readonly", "readonly");
$(".wijmo-wijcombobox-wrapper", self._comboElement[0]).unbind("click");
}
} else //Add comments by RyanWu@20110119.
//For fixing the issue that first open the dropdown list and choose one item,
//then set the new data to the combo and click the dropdown list,
//an exception will be thrown.
if(key === "data" || key === "dataSource") {
self._initInnerData();
self._setSelectedIndex(o.selectedIndex);
if($.isArray(self.innerData)) {
self.listHasCreated = false;
self._createDropDownList();
} else {
try {
self.innerData.loaded = function (e, data) {
if(e === null) {
self.items = null;
} else {
self.items = $.isArray(e) ? e : e.items;
}
self.listHasCreated = false;
self._createDropDownList();
};
self.innerData.load(null);
} catch (e) {
}
}
if(o.selectedIndex !== -1) {
oldSelectedItem = items ? items[oldSelectedIndex] : null;
items = self.innerData;
self._trigger("changed", null, {
oldItem: oldSelectedItem,
selectedItem: self.selectedItem,
newIndex: o.selectedIndex,
oldIndex: oldSelectedIndex
});
self._triggerSelectedIndexChanged(oldSelectedItem, self.selectedItem, oldSelectedIndex, o.selectedIndex);
}
self._keypress = false;
} else //end by RyanWu@20110119.
if(key === "selectedIndex") {
if(value === oldSelectedIndex) {
return;
}
self.selectedItem = null;
if(self.innerData === null) {
items = null;
} else {
items = $.isArray(self.innerData) ? self.innerData : self.innerData.items;
}
oldSelectedItem = items ? items[oldSelectedIndex] : null;
if(value > -1) {
if(items && items[value] !== null) {
newSelectedItem = items[value];
}
cancelSelect = self._triggerSelectedIndexChanging(oldSelectedItem, newSelectedItem, oldSelectedIndex, value);
if(cancelSelect) {
o.selectedIndex = oldSelectedIndex;
return;
}
// if the data option is reset and the self.selectedItem is underfined,
// need use oldSelectedIndex to clear selection
if(oldSelectedIndex !== null && oldSelectedIndex !== -1 && oldSelectedIndex !== undefined && oldSelectedItem) {
oldSelectedItem.selected = false;
if(oldSelectedItem.element) {
oldSelectedItem.element.removeClass("wijmo-wijcombobox-selecteditem");
}
}
if(items && items[value] !== null) {
self.selectedItem = items[value];
if(self.selectedItem) {
self.selectedItem.selected = true;
//self._input.val(self.selectedItem.label);
self._setInputText(self.selectedItem.label);
o.selectedValue = self.selectedItem.value;
o.inputTextInDropDownList = true;
o.text = self._input.val();
}
}
} else if(value <= -1 || !value) {
cancelSelect = self._triggerSelectedIndexChanging(oldSelectedItem, null, oldSelectedIndex, value);
if(cancelSelect) {
o.selectedIndex = oldSelectedIndex;
return;
}
o.inputTextInDropDownList = false;
self._clearSelection();
}
self._trigger("changed", null, {
oldItem: oldSelectedItem,
selectedItem: self.selectedItem,
newIndex: o.selectedIndex,
oldIndex: oldSelectedIndex
});
self._triggerSelectedIndexChanged(oldSelectedItem, self.selectedItem, oldSelectedIndex, o.selectedIndex);
} else if(key === "selectedValue") {
if(value) {
if(self.selectedItem && self.selectedItem.selected !== undefined) {
self.selectedItem.selected = false;
}
items = self.items;
if(!items) {
items = self.innerData;
}
if(items) {
$.each(items, function (index, item) {
if(items[index].value === value) {
self.selectedItem = items[index];
self.selectedItem.selected = true;
//self._input.val(self.selectedItem.label);
self._setInputText(self.selectedItem.label);
self.options.selectedIndex = index;
o.inputTextInDropDownList = true;
o.text = self._input.val();
return false;
}
});
}
} else {
o.inputTextInDropDownList = false;
self._clearSelection();
}
} else if(key === "text") {
if(o.forceSelectionText && self._checkTextInItems(value) === -1) {
return;
}
//self._input.val(value);
self._setInputText(value);
}
};
wijcombobox.prototype._setSelectedIndex = function (value) {
var self = this, o = self.options;
if(value === null || value === undefined) {
return;
}
if(value === -1) {
self.selectedItem = null;
o.selectedIndex = -1;
o.selectedValue = null;
if(o.text) {
self._input.val(o.text);
} else {
self._input.val("");
}
} else {
if(self.innerData && self.innerData[value] !== null && self.innerData[value] !== undefined) {
self.innerData[value].selected = true;
self._input.val(self.innerData[value].label);
self.selectedItem = self.innerData[value];
} else if(self.innerData && $.isArray(self.innerData) && value > self.innerData.length - 1) {
o.selectedIndex = -1;
self._input.val("");
}
}
o.text = self._input.val();
};
wijcombobox.prototype.search = /** Searches the wijcombobox drop-down list for the specified value.
* @param {string} value Text to search in the drop-down list.
* @param {object} eventObj The jquery event object.
*/
function (value, eventObj) {
var self = this, o, datasource, d, isBind;
o = self.options;
//datasource = o.data;
datasource = self.innerData;
window.clearTimeout(self.closing);
d = {
value: value,
e: eventObj,
self: self
};
// load data when data is not loaded yet
// or datasource is using a proxy to obtain data.
if(datasource !== null || self._comboDiv) {
//update 2012/9/14
isBind = self._isBind();
// check index will skip search event
if(eventObj !== "checkindex") {
if(self._trigger("search", eventObj, {
datasrc: datasource,
term: d
}) === false) {
return;
}
}
if($.isArray(datasource) || isBind || self._comboDiv) {
self._hideShowArrow(false);
self._onListLoaded(datasource, d);
} else if(!isBind && $.isArray(o.dataSource)) {
return;
} else {
if(self._usingRemoteData() && eventObj !== undefined && value.length < o.minLength) {
return;
}
self._hideShowArrow(false);
// update for: datasource loaded event don't fired
// in combobox
datasource.loaded = function (e, data) {
//need to re initialize the dropdown list
//datasource condition the data is get by proxy
self.listHasCreated = false;
self._createDropDownList(e);
self._onListLoaded(e, data);
if(self.originalDataSourceLoaded) {
self.originalDataSourceLoaded(e, data);
}
};
datasource.load(d);
}
}
};
wijcombobox.prototype.getSelectedItems = /** Get the select item(s) in combobox.
* @remarks
* when using multiple mode, it will return array object.
* If no item is selected, it will return null or empty array.
* @returns {array} array object or empty array.
*/
function () {
var o = this.options;
if(o.selectionMode === "single") {
return this.selectedItem;
} else {
return this.selectedItems;
}
};
wijcombobox.prototype._isBind = //for bind data
function () {
var o = this.options, data = o.data;
if(data !== null && data.label && data.label.bind) {
return true;
}
return false;
};
wijcombobox.prototype._getMappingItems = function () {
var o = this.options, dataSource = o.dataSource, data = o.data, mappingItems, labelKey, valueKey;
if(!dataSource || !data) {
return null;
}
if(!data.label || !data.label.bind || !data.value || !data.value.bind) {
return null;
}
labelKey = data.label.bind;
valueKey = data.value.bind;
//1.Array
if(dataSource && dataSource.length !== 0) {
mappingItems = [];
$.each(dataSource, function (i, item) {
mappingItems.push({
label: item[labelKey],
value: item[valueKey]
});
});
return mappingItems;
}
return null;
};
wijcombobox.prototype._clearSelection = //end for bind data
function () {
var self = this, o = self.options;
if(o.selectionMode === "single") {
if(self.selectedItem !== null) {
self.selectedItem.selected = false;
}
self.selectedItem = null;
} else {
if(self.selectedItems) {
$.each(self.selectedItems, function (index, item) {
if(item.selected) {
item.selected = false;
}
});
self.selectedItem = null;
self.selectedItems = null;
}
}
o.selectedValue = null;
//self._input.val("");
self._setInputText("");
o.text = self._input.val();
};
wijcombobox.prototype._usingRemoteData = function () {
var o = this.options.data, r = false;
if(!$.isArray(o) && o !== null && o.proxy) {
r = true;
}
return r;
};
wijcombobox.prototype._hideShowArrow = function (show) {
// hide arrow to show
var self = this, input, arrow;
input = self.element;
arrow = self._triggerArrow;
if(arrow !== undefined) {
arrow[show ? "show" : "hide"]();
}
input[show ? "removeClass" : "addClass"]("wijmo-wijcombobox-loading");
};
wijcombobox.prototype._onListLoaded = function (datasource, data) {
var self = data.self, ele, o, wijCSS = this.options.wijCSS, searchTerm, items, idx, itemsToRender;
ele = self._input;
o = self.options;
searchTerm = data.value;
if(datasource === null) {
items = null;
} else {
items = $.isArray(datasource) ? datasource : datasource.items;
}
self.items = items;
if(data.e === "checkindex") {
idx = o.selectedIndex;
if(o.selectionMode === "multiple" && $.isArray(idx)) {
$.each(idx, function (i, n) {
var itm = items[n];
itm.selected = true;
self.selectedItems.push(itm);
});
self._selectedItemsToInputVal(self.selectedItems);
} else {
items[idx].selected = true;
self.selectedItem = items[idx];
ele.val(self.selectedItem.label);
}
self._hideShowArrow(true);
return;
}
// only fileter result when using local data.
if(!self._usingRemoteData() && items) {
/*update for improving performance
self._filter(items, searchTerm);
itemsToRender = $.grep(items, function (item1) {
return !o.autoFilter || item1.match;
});*/
itemsToRender = items;
} else {
self._topHit = null;
itemsToRender = items;
}
if((itemsToRender && itemsToRender.length > 0) || self._comboDiv) {
// open dropdown list
self._openlist(itemsToRender, data, searchTerm);
// move the trigger dropdown open event to openlist.
//self._trigger("open");
self._addInputFocus(true, wijCSS.stateFocus);
} else {
self.close(null, true);
}
self._hideShowArrow(true);
};
wijcombobox.prototype.close = /** Closes drop-down list.
* @param {?EventObj} event The jquery event object.
* @param {?boolean} skipAnimation A value indicating whehter to skip animation.
*/
function (event, skipAnimation) {
var self = this, menu, wijCSS = this.options.wijCSS, hidingAnimation, hidingStyle;
menu = self.menu;
self._dropDownHeight = menu.element.outerHeight();
self._dropDownWidth = menu.element.outerWidth();
window.clearTimeout(self.closing);
// test parent element is need, hidingAnimation
// because some effect will wrap the target element.
if(menu.element.is(":visible") && !menu.element.is(":animated") && !menu.element.parent().is(":animated")) {
self._trigger("close", event);
menu.deactivate();
hidingAnimation = self.options.hidingAnimation;
//add for size animation by wuhao 2011/7/16
if(hidingAnimation && (hidingAnimation.effect === "size" || hidingAnimation.animated === "size")) {
hidingAnimation.options = $.extend({
to: {
width: 0,
height: 0
}
}, hidingAnimation.options);
}
hidingStyle = menu.element.attr("style");
//end for size animation
if(skipAnimation !== true && hidingAnimation) {
menu.element.hide(hidingAnimation.effect || hidingAnimation.animated, hidingAnimation.options, hidingAnimation.speed || hidingAnimation.duration, function () {
menu.element.removeAttr("style").attr("style", hidingStyle).hide();
if(hidingAnimation.callback) {
hidingAnimation.callback.apply(this, arguments);
}
});
} else {
menu.element.hide();
}
self._addInputFocus(false, wijCSS.stateFocus);
//$(document).unbind("click", self.closeOnClick);
$(document).unbind("mouseup", self.closeOnClick);
}
};
wijcombobox.prototype._getKeyCodeEnum = function () {
if($.ui && $.ui.keyCode) {
return $.ui.keyCode;
}
if($.mobile && $.mobile.keyCode) {
return $.mobile.keyCode;
}
throw "keyCode object is not found";
};
wijcombobox.prototype._change = function () {
// TODO: finish _change event.
var self = this, o, f, m, ele, t, itm, items, oldIndex, innerData, inputIndex = -1;
o = self.options;
f = o.forceSelectionText;
m = o.selectionMode;
ele = self._input;
t = ele.val();
itm = self.selectedItem;
items = self.selectedItems;
oldIndex = o.selectedIndex ? o.selectedIndex : -1;
innerData = self.innerData;
if(f) {
if(m === "single") {
if(itm !== null) {
if(itm.label !== t) {
ele.val(itm.label);
}
} else {
ele.val("");
}
}
} else {
//update for inputed non-listed value,
//update selected index and selected value
if(m === "single") {
if((!itm && t !== "") || (itm !== null && itm.label !== t)) {
if(self.selectedItem !== null) {
self.selectedItem.selected = false;
}
inputIndex = self._checkTextInItems(t);
if(inputIndex === -1) {
self.selectedItem = null;
o.selectedIndex = -1;
o.selectedValue = null;
o.inputTextInDropDownList = false;
} else {
if(innerData) {
self.selectedItem = innerData[inputIndex];
o.selectedIndex = inputIndex;
o.selectedValue = self.selectedItem.value;
o.inputTextInDropDownList = true;
}
}
o.text = self._input.val();
self._trigger("changed", null, {
oldItem: itm,
selectedItem: self.selectedItem,
newIndex: o.selectedIndex,
oldIndex: oldIndex
});
if(oldIndex !== inputIndex) {
self._triggerSelectedIndexChanged(itm, self.selectedItem, oldIndex, o.selectedIndex);
}
}
}
}
//Todo: when input something to combobox,
//the text will restore in multiple mode
//Maybe it need to be adjusted.
if(m === "multiple") {
//update for add issue: when iseditable is false
//click the all the combobox, the dropdown list will open
//self._selectedItemsToInputVal(self.selectedItems);
if(!self.selectedItems || self.selectedItems.length === 0) {
items = [
itm
];
}
self._selectedItemsToInputVal(items);
}
};
wijcombobox.prototype._checkTextInItems = function (text) {
var self = this, index = -1, data = self.innerData;
if(text) {
$.each(data, function (i, item) {
if(data[i] && data[i].label && data[i].label === text) {
index = i;
return false;
}
});
}
return index;
};
wijcombobox.prototype._openlist = function (items, data, searchTerm) {
var self = data.self, eventObj = data.e, keypress, textWidth, menuElement, o, oldPadding, verticalBorder = 2, headerHeight = 0, dropDownHeight, origCloseOnClick, h, showingAnimation, showingStyle, showingSize, inputValueLength = $.trim(self._input.val()).length, keyCode = self._getKeyCodeEnum(), zIndex, needHighlightMatching = false;
keypress = self._keypress = !!eventObj;
o = self.options;
menuElement = self.menu.element;
if($.ui) {
menuElement.zIndex(self.element.zIndex() + 100);
} else {
zIndex = parseInt(self.element.css("zIndex"), 10);
if(isNaN(zIndex)) {
zIndex = 0;
}
menuElement.css("zIndex", zIndex + 100);
}
//update for 32309 issue
if(!self.listHasCreated) {
self._createDropDownList();
}
/* for improving performance
if (self._comboDiv) {
//update for case 20689 at 2012/4/11
if (!self.listHasCreated) {
//update for issue 24130 at 2012/7/20
//self.menu.setTemplateItems(items);
self.menu.setTemplateItems(o.data);
self.menu.renderList();
self.listHasCreated = true;
}
} else {
if (!self.listHasCreated) {
self.menu.setItems(items);
self.menu.renderList();
self.listHasCreated = true;
}
}*/
//update for issue 24130 at 2012/7/20
if(!self._usingRemoteData() && searchTerm !== null && searchTerm !== undefined) {
needHighlightMatching = self._keypress && o.isEditable && o.columns.length === 0 && o.highlightMatching && inputValueLength > 0;
//if down key press condition for 33017 issue at 2013/1/8
if(eventObj && eventObj.keyCode === $.ui.keyCode.DOWN && searchTerm.length === 0 && inputValueLength > 0) {
self._topHit = self.menu.filterItems(self._input.val(), false, needHighlightMatching);
} else {
self._topHit = self.menu.filterItems(searchTerm, o.autoFilter, needHighlightMatching);
}
//can't find the matched items
if(self._topHit === null && self.innerData && $("li[wijhidden]", self.menu.element).length === self.innerData.length) {
self.close(null, true);
return false;
}
}
// show dropdown
self.menu.element.show();
if(o.dropdownWidth === "auto") {
textWidth = self._comboElement.outerWidth();
} else {
textWidth = o.dropdownWidth;
}
oldPadding = menuElement.css("padding");
menuElement.css("padding", "0px");
menuElement.setOutWidth(textWidth);
menuElement.css("padding", oldPadding);
dropDownHeight = o.dropdownHeight;
if(menuElement.children(".wijmo-wijsuperpanel-header")) {
headerHeight = menuElement.children(".wijmo-wijsuperpanel-header").outerHeight() || 0;
}
//end for fixing bug 15778
h = Math.min(self._menuUL.outerHeight() + verticalBorder + headerHeight, dropDownHeight);
menuElement.setOutHeight(h);
self.menu.refreshSuperPanel();
self._positionList();
if(!keypress && self.selectedItem !== undefined) {
self.menu.activate(null, self.selectedItem, true);
}
if(keypress && eventObj.keyCode !== $.ui.keyCode.BACKSPACE) {
if(o.isEditable) {
self._runAutoComplete();
} else {
self.menu.activate(null, self._topHit, true);
}
} else {
showingAnimation = self.options.showingAnimation;
if(o.showingAnimation !== null && !(eventObj !== undefined && eventObj.keyCode === $.ui.keyCode.BACKSPACE)) {
self.menu.element.hide();
showingSize = {
from: {
width: 0,
height: 0
},
to: {
width: self._dropDownWidth || menuElement.outerWidth(),
height: self._dropDownHeight || menuElement.outerHeight()
}
};
if(showingAnimation && (showingAnimation.effect === "size" || showingAnimation.animated === "size")) {
showingAnimation.options = $.extend(showingSize, showingAnimation.options);
}
showingStyle = menuElement.attr("style");
//end for size animation
menuElement.show(//update for modify animation name by wh at 2011/9/26
//showingAnimation.effect,
showingAnimation.effect || showingAnimation.animated, showingAnimation.options, showingAnimation.speed || showingAnimation.duration, function () {
//add for size animation by wuhao 2011/7/16
menuElement.removeAttr("style").attr("style", showingStyle).show();
//end for size animation
if(showingAnimation.callback) {
showingAnimation.callback.apply(this, arguments);
}
if($.browser.msie) {
menuElement.css("filter", "");
}
});
}
}
if(!self.hasOwnProperty("closeOnClick")) {
origCloseOnClick = self.closeOnClick;
self.closeOnClick = function (e) {
return origCloseOnClick(e);
};
}
self._trigger("open");
//update for issue 2012/6/14: place combobox in expander
//open the dropdown, then collapse the expander
//the dropdown is still open
//$(document).bind("click", self, self.closeOnClick);
$(document).bind("mouseup", self, self.closeOnClick);
return true;
};
wijcombobox.prototype.closeOnClick = /** @ignore */
function (e) {
var self = e.data, wijCSS = self.options.wijCSS, offset, t = e.target;
if(!$.contains(self._comboElement[0], t) && !$.contains(self.menu.element[0], t)) {
if($.support.isTouchEnabled && $.support.isTouchEnabled()) {
offset = self.menu.element.offset();
if(e.pageX < offset.left || e.pageX > offset.left + self.menu.element.width() || e.pageY < offset.top || e.pageY > offset.top + self.menu.element.height()) {
self.close();
}
} else {
self.close();
}
$(".wijmo-wijcombobox-wrapper", self._comboElement[0]).removeClass(wijCSS.stateHover).removeClass(wijCSS.stateFocus);
$(".wijmo-wijcombobox-trigger", self._comboElement[0]).removeClass(wijCSS.stateHover).removeClass(wijCSS.stateFocus);
}
};
wijcombobox.prototype._positionList = function () {
var self = this, positionOptions, defaultPosition;
positionOptions = self.options.dropDownListPosition;
defaultPosition = {
my: "left top",
at: "left bottom",
of: self._comboElement,
collision: "none"
};
defaultPosition = $.extend(defaultPosition, positionOptions);
self.menu.element.position(defaultPosition);
};
wijcombobox.prototype._runAutoComplete = function () {
var self = this, ele, topHit, oldText, fullText, start, end;
ele = self._input;
topHit = self._topHit;
if(!self.options.autoComplete || topHit === null || topHit === undefined) {
return;
}
self.menu.activate(null, topHit, true);
oldText = ele.val();
fullText = topHit.label;
ele.val(fullText);
start = oldText.length;
end = fullText.length;
self._selectText(start, end, ele);
};
wijcombobox.prototype._selectText = function (start, end, input) {
var v = input.val(), inputElement = input.get(0), range;
if(v.length > 0) {
if(inputElement.setSelectionRange !== undefined) {
inputElement.setSelectionRange(start, end);
} else if(inputElement.createTextRange !== undefined) {
range = inputElement.createTextRange();
range.moveStart("character", start);
range.moveEnd("character", end - v.length);
range.select();
}
}
};
wijcombobox.prototype._move = function (direction, event) {
if(!this.menu.element.is(":visible")) {
this.search("", event);
return;
}
if(this.menu.first() && /^previous/.test(direction) || this.menu.last() && /^next/.test(direction)) {
//update for fixing bug 15964 by wuhao
//this.menu.deactivate();
//end for bug 15964.
return;
}
this.menu[direction](event);
};
wijcombobox.prototype._escapeRegex = function (value) {
if(value === undefined) {
return value;
}
return value.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1");
};
wijcombobox.prototype._filter = function (array, searchTerm) {
var term1 = this._escapeRegex(searchTerm), matcher, topHit = null;
/// TODO : start with or contains and case sensitive.
if(!array) {
return null;
}
matcher = new RegExp(term1, "i");
$.each(array, function (index, item) {
if(term1 === undefined || term1.length === 0) {
item.match = true;
return;
}
var matchResult = matcher.exec(item.label);
if(matchResult === null) {
item.match = false;
} else {
if(topHit === null && matchResult.index === 0) {
topHit = item;
}
item.match = matchResult.index >= 0;
}
});
this._topHit = topHit;
return array;
};
return wijcombobox;
})(wijmo.wijmoWidget);
combobox.wijcombobox = wijcombobox;
var wijcombobox_options = (function () {
function wijcombobox_options() {
/** Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijcombobox')";
/** wijdataview to which this wijcombobox is bound.
* @type {wijdataview}
* @remarks
* This option is used if this wijcombobox is bound to a wijdataview.
* In that case, you can also specify a mapping option to select the properties to bind to,
* and the data option returns an array of objects containing
* value and label property values determined by that mapping.
*/
this.dataSource = null;
/** A value that specifies the underlying data source provider of wijcombobox.
* @type {wijdatasource|Array}
* @remarks
* This option could either be a wijdatasource object
* or an Object Array containing an item such as
* {label: "label text", value: "value"}.
* @example
* var testArray = [
* {label: 'c++',value: 'c++'},
* {label: 'java',value: 'java'},
* {label: 'php',value: 'php'}
* ];
* $("#tags").wijcombobox({
* data: testArray
* });
*/
this.data = null;
/** A value that specifies the text in the wijcombobox label.*/
this.labelText = null;
/** A value that determines the minimum length of text
* that can be entered in the wijcombobox text box to issue an AJAX request.
*/
this.minLength = 4;
/** A value that determines the duration (in milliseconds) of the time
* to delay before autocomplete begins after typing stops.
*/
this.delay = 300;
/** A value that specifies the animation options for a drop-down list
* when it is visible.
* @example
* var animationOptions = {
* animated: "Drop",
* duration: 1000
* };
* $("#tags").wijcombobox("option", "showingAnimation", animationOptions)
});
*/
this.showingAnimation = null;
/** A value that specifies the animation options such as the animation effect and
* duration for the drop-down list when it is hidden.
* @example
* var animationOptions = {
* animated: "Drop",
* duration: 1000
* };
* $("#tags").wijcombobox("option", "hidingAnimation", animationOptions)
*/
this.hidingAnimation = null;
/** A value that determines whether to show the trigger of wijcombobox.*/
this.showTrigger = true;
/** A value that specifies the position of the drop-down list trigger.
* @remarks
* possible value: right or left
*/
this.triggerPosition = "right";
/** A value that specifies the height of the drop-down list.
* @remarks
* If the total height of all items is less than the value of this option,
* it will use the total height of items as the height of the drop-down list.
*/
this.dropdownHeight = 300;
/** A value that specifies the width of the drop-down list.
* @type {number|string}
* @remarks
* When this option is set to "auto", the width of the drop-down
* list is equal to the width of wijcombobox.
*/
this.dropdownWidth = "auto";
/** A value that determines whether to select the item when the item gains focus or is activated. */
this.selectOnItemFocus = false;
/** A value determines whether to shorten the drop-down list items
* by matching the text in the textbox after typing.
*/
this.autoFilter = true;
/** A value that determines whether to start the auto-complete
* function after typing in the text if a match exists.
*/
this.autoComplete = true;
/** A value that determines whether to highlight the keywords in an item.
* @remarks
* If "abc" is typed in the textbox,
* all "abc" matches are highlighted in the drop-down list.
*/
this.highlightMatching = true;
/** A value that specifies the position options of the drop-down list.
* The default value of the "of" options is the input of wijcombobox.
* @example
* var positionOptions = {my:"right", at:"top"};
* //specifies the position options of the drop-down list on "right, top" of combobox.
* $("#tags").wijcombobox("option", "dropDownListPosition", positionOptions)
*/
this.dropDownListPosition = {
};
/** An array that specifies the column collections of wijcombobox.
* @example
* $("#tags").wijcombobox("option", "columns", [
* {name: 'header1', width: 150},
* {name: 'header2', width: 150},
* {name: 'header3', width: 150}
* ]);
*/
this.columns = [];
/** A value that specifies the selection mode of wijcombobox.
* @remarks
* Possible options are: "single" and "multiple".
*/
this.selectionMode = "single";
/** A value that specifies the separator for
* the multiple selected items text in the textbox.
*/
this.multipleSelectionSeparator = ",";
/** A value that determines whether to check the input text against
* the text of the selected item when the focus blurs.
* @remarks
* If the text does not match any item, input text will restore
* to text the selected item or empty if no item is selected.
*/
this.forceSelectionText = false;
/** A function called when any item in list is selected.
* @event
* @dataKey {element} element LI element with this item.
* @dataKey {object} list wijlist instance.
* @dataKey {string} label Label of item.
* @dataKey {object} value Value of item.
* @dataKey {string} text Could be set in handler to override rendered label of item.
*/
this.select = null;
/** A value that determines whether input is editable.*/
this.isEditable = true;
/** A value that specifies the index of the item to select when using single mode.
* @type {number|array}
* @remarks
* If the selectionMode is "multiple", then this option could be set
* to an array of Number which contains the indices of the items to select.
* If no item is selected, it will return -1.
* @example
* //To get the selected item using the selected index:
* var selectedIndex = $("# tags ").wijcombobox("option","selectedIndex");
* var selectedItem = $("# tags ").wijcombobox("option","data")[selectedIndex];
* // To set the selected item using the selected index:
* $("#tags").wijcombobox("option"," selectedIndex", 5);
*/
this.selectedIndex = -1;
/** A value that specifies the value of the item to select when using single mode.
* @type {number|string|object}
* @remarks
* If no item is selected, it will return null.
*/
this.selectedValue = null;
/** A value that specifies the input text of the combobox is in dropdown list or not.
* @remarks
* It's readonly option, if user typed text is not in dropdown list, it returns false;
* if user selects a item form the dropdown list or typed text in dropdown list, it returns true.
*/
this.inputTextInDropDownList = false;
/** A value that specifies the input text of the combobox.
* @type {string}
* @remarks
* When set the text by code, it will not affect the selectedIndex and selectedValue.
*/
this.text = null;
/** A value indicating the dropdown element will be append to the body or combobox container.
* @remarks
* If the value is true, the dropdown list will be appended to body element.
* else it will append to the combobox container.
*/
this.ensureDropDownOnBody = true;
/** This event is triggered when the drop-down list is opened.
* @event
*/
this.open = null;
/** This event is triggered when the drop-down list is closed.
* @event
*/
this.close = null;
/** A value added to the width of the original HTML select element to account
* for the scroll bar width of the drop-down list.
* @remarks
* Unit for this value is pixel.
* Because the width of the scroll bar may be different between browsers
* if wijcombobox is initialized with the width of the HTML select element,
* the text may be hidden by the scroll bar of wijcombobox.
*/
this.selectElementWidthFix = 6;
/** This event is triggered when a user searches an item in the drop-down list either
* by typing in the textbox or by calling the search method of wijcombobox.
* @event
* @dataKey {datasource} datasrc The datasource of wijcombobox.
* @dataKey {string} term The text to search.
*/
this.search = null;
/** The event is obsolete event.
* A function called when select item is changed.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IselectedEventArgs} data The data with this event.
*/
this.changed = null;
/** This event is triggered when the text of the combobox is changed.
* @event
* @dataKey {string} oldText The old text of combobox.
* @dataKey {string} newText The new text of combobox.
*/
this.textChanged = null;
/** This event is triggered when the selected index of the combobox is changed.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IselectedEventArgs} data The data with this event.
*/
this.selectedIndexChanged = null;
/** A function called when the selected index of the comboBox is about to change.
* Cancellable. If return false, the select operation will be canceled.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IselectedEventArgs} data The data with this event.
*/
this.selectedIndexChanging = null;
/** A value that determines the object that contains the options of wijlist.*/
this.listOptions = null;
}
return wijcombobox_options;
})();
;
wijcombobox.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijcombobox_options());
$.wijmo.registerWidget("wijcombobox", wijcombobox.prototype);
})(wijmo.combobox || (wijmo.combobox = {}));
var combobox = wijmo.combobox;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../external/declarations/globalize.d.ts"/>
/// <reference path="../Base/jquery.wijmo.widget.ts"/>
/// <reference path="../wijpopup/jquery.wijmo.wijpopup.ts"/>
/// <reference path="../wijlist/jquery.wijmo.wijlist.ts"/>
/// <reference path="../wijsuperpanel/jquery.wijmo.wijsuperpanel.ts"/>
/*globals Globalize window jQuery wijInputResult document*/
(function (input) {
"use strict";
var $ = jQuery, jqKeyCode = ($.ui || $.mobile).keyCode;
/** @widget */
var wijinputcore = (function (_super) {
__extends(wijinputcore, _super);
function wijinputcore() {
_super.apply(this, arguments);
this._boundMouseWheel = false;
this._wasPopupShowing = false;
}
wijinputcore.prototype._elemWithClasses = function (elem, classes) {
if (typeof classes === "undefined") { classes = []; }
return $(elem).addClass(classes.join(" "));
};
wijinputcore.prototype._divWithClasses = function () {
var classes = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
classes[_i] = arguments[_i + 0];
}
return this._elemWithClasses("<div/>", classes);
};
wijinputcore.prototype._spanWithClasses = function () {
var classes = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
classes[_i] = arguments[_i + 0];
}
return this._elemWithClasses("<span/>", classes);
};
wijinputcore.prototype._horizontalBorderWidth = function (elem) {
return elem.leftBorderWidth() + elem.rightBorderWidth();
};
wijinputcore.prototype._verticalBorderWidth = function (elem) {
return elem.topBorderWidth() + elem.bottomBorderWidth();
};
wijinputcore.prototype._create = function () {
var _this = this;
var focused = document.activeElement == this.element[0], hBorder = this._horizontalBorderWidth(this.element), vBorder = this._verticalBorderWidth(this.element);
if(this.element[0].tagName.toLowerCase() !== 'input') {
throw "Target element is not a INPUT";
}
this._creationDate = new Date();
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
if(this.element.is(":hidden") && this.element.wijAddVisibilityObserver) {
this.element.wijAddVisibilityObserver(function () {
_this._destroy();
_this._create();
if(_this.element.wijRemoveVisibilityObserver) {
_this.element.wijRemoveVisibilityObserver();
}
}, "wijinput");
}
this.element.data("widgetName", this.widgetName);
//$.effects.save(this.element, ['width', 'height']);
if($.effects && $.effects.save) {
$.effects.save(this.element, [
'width',
'height'
]);
} else if($.save) {
$.save(this.element, [
'width',
'height'
]);
}
var wijCSS = this.options.wijCSS;
this.element.wrap("<div><span/></div");
this.wrapper = this.element.parent();
this.outerDiv = this.wrapper.parent();
this.outerDiv.addClass([
wijCSS.wijinput,
wijCSS.widget,
wijCSS.helperClearFix,
wijCSS.stateDefault,
wijCSS.cornerAll
].join(" "));
this.wrapper.addClass(wijCSS.wijinputWrapper);
this.element.addClass(wijCSS.wijinputInput).addClass(wijCSS.cornerAll).attr('role', 'textbox');
if(!($.browser.msie && parseFloat($.browser.version) <= 7)) {
//Can't set 'aria-multiline' attribute by jQuery's attr() api in IE10 Compatibility View
try {
this.element.attr('aria-multiline', false);
} catch (e) {
this.element[0].setAttribute('aria-multiline', "false");
}//self.element.attr('aria-multiline', false);
}
var leftBtn = this.options.buttonAlign === 'left';
if(this.options.showTrigger) {
this.triggerBtn = this._divWithClasses(wijCSS.wijinputTrigger, wijCSS.stateDefault, leftBtn ? wijCSS.cornerLeft : wijCSS.cornerRight).append(this._spanWithClasses(wijCSS.icon, wijCSS.iconArrowDown)).attr('role', 'button').appendTo(this.outerDiv);
this.element.attr({
'role': 'combobox',
'aria-expanded': false
});
}
if(this.options.showSpinner) {
this.spinner = this._divWithClasses(wijCSS.wijinputSpinner, wijCSS.wijinputButton);
this.spinUp = this._divWithClasses(wijCSS.stateDefault, wijCSS.wijinputSpinUp).append(this._spanWithClasses(wijCSS.icon, wijCSS.iconArrowUp)).attr('role', 'button');
this.spinDown = this._divWithClasses(wijCSS.stateDefault, wijCSS.wijinputSpinDown).append(this._spanWithClasses(wijCSS.icon, wijCSS.iconArrowDown)).attr('role', 'button');
if(!this.options.showTrigger) {
this.spinUp.addClass(leftBtn ? wijCSS.cornerTL : wijCSS.cornerTR);
this.spinDown.addClass(leftBtn ? wijCSS.cornerBL : wijCSS.cornerBR);
}
this.spinner.append(this.spinUp).append(this.spinDown).appendTo(this.outerDiv);
this.element.attr('role', 'spinner');
}
if(this.options.showTrigger && this.options.showSpinner) {
this.outerDiv.addClass(leftBtn ? wijCSS.inputSpinnerTriggerLeft : wijCSS.inputSpinnerTriggerRight);
} else {
if(this.options.showTrigger) {
this.outerDiv.addClass(leftBtn ? wijCSS.inputTriggerLeft : wijCSS.inputTriggerRight);
}
if(this.options.showSpinner) {
this.outerDiv.addClass(leftBtn ? wijCSS.inputSpinnerLeft : wijCSS.inputSpinnerRight);
}
}
this._initialize();
if(focused) {
$(function () {
return _this.element.focus().wijtextselection(0, _this.element.val().length);
});
}
// We need to move width and height from the <input/> to the outer <div/> because the input must span the parent wrapper.
// It must be done if A dimension is set in the style attribute, hence the "if" statements
// The a dimension is in pixels, it must be adjusted according to the input's and div's border/margin/padding.
// The input's total border size must be calcualted before changing the classes, hence variables hBorder and vBorder.
var style = this.element[0].style;
if(style.width) {
if(this._isInPercents(style.width)) {
this.outerDiv.width(style.width);
} else {
this.outerDiv.width(this.element.width() + hBorder - this._horizontalBorderWidth(this.outerDiv));
}
this.element.width("");
}
if(style.height) {
if(this._isInPercents(style.height)) {
this.outerDiv.height(style.height);
} else {
this.outerDiv.height(this.element.height() + vBorder - this._verticalBorderWidth(this.outerDiv));
}
this.element.height("");
}
};
wijinputcore.prototype._isInPercents = function (size) {
return size.match(/%$/);
};
wijinputcore.prototype._createTextProvider = function () {
return undefined;
};
wijinputcore.prototype._beginUpdate = function () {
};
wijinputcore.prototype._endUpdate = function () {
var _this = this;
if(this.element.mousewheel && !this._boundMouseWheel) {
this.element.mousewheel(function (e, delta) {
if(_this.isFocused() && _this._doSpin(delta > 0, false)) {
e.preventDefault();
}
});
this._boundMouseWheel = true;
}
};
wijinputcore.prototype._isPopupShowing = function () {
return !!this._comboDiv && this._comboDiv.wijpopup("isVisible");
};
wijinputcore.prototype._onTriggerMouseUp = function () {
this._wasPopupShowing = this._isPopupShowing();
};
wijinputcore.prototype._onTriggerClicked = function () {
if(this._wasPopupShowing) {
this._hidePopup();
} else {
this._showPopup();
this._wasPopupShowing = true;
}
};
wijinputcore.prototype._showPopup = function () {
this._popupComboList();
};
wijinputcore.prototype._hidePopup = function () {
this._comboDiv.wijpopup('hide');
};
wijinputcore.prototype._initialize = function () {
var _this = this;
this.element.data('initializing', true);
this._trigger('initializing');
this.element.data('preText', this.element.val());
this.element.data('elementValue', this.element.val());
this.element.data('errorstate', false);
this.element.data('breakSpinner', true);
this.element.data('prevCursorPos', -1);
this.element.data('simulating', false);
this._createTextProvider();
this._beginUpdate();
var options = this.options, isLeftButton = function (e) {
return (!e.which ? e.button : e.which) === 1;
}, spinButtonDown = function (e) {
if(_this.options.disabled) {
return;
}
if(!isLeftButton(e)) {
return;
}
_this._trySetFocus();
_this.element.data('breakSpinner', false);
_this._addState('active', $(_this));
_this._doSpin($(e.currentTarget).hasClass(options.wijCSS.wijinputSpinUp), true);
}, spinButtonUp = function (e) {
if(_this.options.disabled) {
return;
}
if(!isLeftButton(e)) {
return;
}
_this._stopSpin();
_this._removeState('active', $(_this));
}, dis;
if(this.triggerBtn && !options.disabledState) {
this.triggerBtn.bind({
'mouseover': function () {
if(_this.options.disabled) {
return;
}
_this._addState('hover', $(_this));
},
'mouseout': function () {
if(_this.options.disabled) {
return;
}
_this._removeState('hover', $(_this));
},
'mousedown': function (e) {
if(_this.options.disabled) {
return;
}
if(!isLeftButton(e)) {
return;
}
_this._stopEvent(e);
_this._addState('active', $(_this));
_this._trigger('triggerMouseDown');
},
'mouseup': function (e) {
_this._onTriggerMouseUp();
},
'click': function (e) {
if(_this.options.disabled) {
return;
}
_this._stopEvent(e);
_this._stopSpin();
_this._removeState('active', $(_this));
_this._trigger('triggerMouseUp');
_this._onTriggerClicked();
_this._trySetFocus();
}
});
}
if(this.spinUp && !options.disabledState) {
this.spinUp.bind({
'mouseover': function () {
if(_this.options.disabled) {
return;
}
_this._addState('hover', $(_this));
},
'mouseout': function () {
if(_this.options.disabled) {
return;
}
_this._removeState('hover', $(_this));
_this._removeState('active', $(_this));
_this._stopSpin();
},
'mousedown': spinButtonDown,
'mouseup': spinButtonUp
});
}
if(this.spinDown && !options.disabledState) {
this.spinDown.bind({
'mouseover': function () {
if(_this.options.disabled) {
return;
}
_this._addState('hover', $(_this));
},
'mouseout': function () {
if(_this.options.disabled) {
return;
}
_this._removeState('hover', $(_this));
_this._removeState('active', $(_this));
_this._stopSpin();
},
'mousedown': spinButtonDown,
'mouseup': spinButtonUp
});
}
this.element.bind({
'focus.wijinput': $.proxy(this._onFocus, this),
'blur.wijinput': $.proxy(this._onBlur, this),
'mouseup.wijinput': $.proxy(this._onMouseUp, this),
'keypress.wijinput': $.proxy(this._onKeyPress, this),
'keydown.wijinput': $.proxy(this._onKeyDown, this),
'keyup.wijinput': $.proxy(this._onKeyUp, this),
'compositionstart.wijinput': $.proxy(this._onCompositionStart, this),
'compositionend.wijinput': $.proxy(this._onCompositionEnd, this),
'change.wijinput': $.proxy(this._onChange, this),
'paste.wijinput': $.proxy(this._onPaste, this),
'drop.wijinput': $.proxy(this._onDrop, this)
});
this.element.bind('propertychange.wijinput input.wijinput', $.proxy(this._onInput, this));
this.element.data('initializing', false);
this._resetData();
this._endUpdate();
this._updateText();
if(this.options.disabledState) {
dis = options.disabled;
this.disable();
options.disabled = dis;
}
if(this.options.disabled) {
this.disable();
}
this.element.data('initialized', true);
this._trigger('initialized');
};
wijinputcore.prototype._init = function () {
};
wijinputcore.prototype._setOption = function (key, value) {
this._super(key, value);
switch(key) {
case 'buttonAlign':
case 'showTrigger':
case 'showSpinner':
this._destroy();
this._create();
break;
case 'showNullText':
this._updateText();
break;
case 'disabled':
this.element.attr('disabled', value);
var addRemove = value ? 'addClass' : 'removeClass', stateDisabled = this.options.wijCSS.stateDisabled;
this.element[addRemove](stateDisabled);
if(this.triggerBtn) {
this.triggerBtn[addRemove](stateDisabled);
}
if(this.spinUp) {
this.spinUp[addRemove](stateDisabled);
}
if(this.spinDown) {
this.spinDown[addRemove](stateDisabled);
}
break;
}
};
wijinputcore.prototype.destroy = function () {
this._super();
this._destroy();
};
wijinputcore.prototype.isDestroyed = function () {
return !this.outerDiv;
};
wijinputcore.prototype._destroy = function () {
if(this.isDestroyed()) {
return;
}
this.wrapper = undefined;
this.outerDiv = undefined;
this.element.unbind('.wijinput');
this.element.removeData('errorstate').removeData('breakSpinner').removeData('prevCursorPos').removeData('simulating').removeData('isPassword').removeClass(this.options.wijCSS.wijinputInput).removeAttr('role').removeAttr('aria-valuemin').removeAttr('aria-valuemax').removeAttr('aria-valuenow').removeAttr('aria-expanded');
this.element.parent().replaceWith(this.element);
this.element.parent().replaceWith(this.element);
//$.effects.restore(this.element, ['width', 'height']);
if($.effects && $.effects.restore) {
$.effects.restore(this.element, [
'width',
'height'
]);
} else if($.restore) {
$.restore(this.element, [
'width',
'height'
]);
}
};
wijinputcore.prototype.widget = /** Gets element this widget is associated. */
function () {
return this.outerDiv || this._super();
};
wijinputcore.prototype._getCulture = function (name) {
if (typeof name === "undefined") { name = this.options.culture; }
return Globalize.findClosestCulture(name || this.options.culture);
};
wijinputcore.prototype._addState = function (state, el) {
if(el.is(':not(.ui-state-disabled)')) {
el.addClass(this.options.wijCSS.getState(state));
}
};
wijinputcore.prototype._removeState = function (state, el) {
el.removeClass(this.options.wijCSS.getState(state));
};
wijinputcore.prototype._isInitialized = function () {
return !this.element.data('initializing');
};
wijinputcore.prototype._setData = function (val) {
this.setText(val);
};
wijinputcore.prototype._resetData = function () {
};
wijinputcore.prototype._validateData = function () {
};
wijinputcore.prototype.getText = /** Gets the text displayed in the input box. */
function () {
if(!this._isInitialized()) {
return this.element.val();
}
return this._textProvider.toString(true, false, false);
};
wijinputcore.prototype.setText = /** Sets the text displayed in the input box.
* @example
* // This example sets text of a wijinputcore to "Hello"
* $(".selector").wijinputcore("setText", "Hello");
*/
function (value) {
if(!this._isInitialized()) {
this.element.val(value);
} else {
this._textProvider.set(value);
this._updateText();
}
};
wijinputcore.prototype.getPostValue = /** Gets the text value when the container
* form is posted back to server.
*/
function () {
if(!this._isInitialized()) {
return this.element.val();
}
return this._textProvider.toString(true, false, true);
};
wijinputcore.prototype.selectText = /** Selects a range of text in the widget.
* @param {Number} start Start of the range.
* @param {Number} end End of the range.
* @example
* // Select first two symbols in a wijinputcore
* $(".selector").wijinputcore("selectText", 0, 2);
*/
function (start, end) {
if (typeof start === "undefined") { start = 0; }
if (typeof end === "undefined") { end = this.getText().length; }
if(this.element.is(':disabled')) {
return;
}
this.element.wijtextselection(start, end);
};
wijinputcore.prototype.focus = /** Set the focus to the widget. */
function () {
if(this.element.is(':disabled')) {
return;
}
this.element.get(0).focus();
};
wijinputcore.prototype.isFocused = /** Determines whether the widget has the focus. */
function () {
return this.outerDiv.hasClass(this.options.wijCSS.stateFocus);
};
wijinputcore.prototype._raiseTextChanged = function () {
var txt = this.element.val(), preText = this.element.data('preText');
if(!!this.element.data('initialized') && preText !== txt) {
this._trigger('textChanged', null, {
text: txt
});
this.element.data('changed', true);
}
this.element.data('preText', txt);
};
wijinputcore.prototype._raiseDataChanged = function () {
};
wijinputcore.prototype._allowEdit = function () {
return !this.element.attr('readOnly') && !this.element.is(':disabled');
};
wijinputcore.prototype._updateText = function (keepSelection) {
if (typeof keepSelection === "undefined") { keepSelection = false; }
if(!this._isInitialized()) {
return;
}
// default is false
keepSelection = !!keepSelection;
var range = this.element.wijtextselection(), o = this.options;
if(this.isDeleteAll && o.showNullText) {
this.isDeleteAll = false;
o.date = null;
this.element.val(o.nullText);
} else {
this.element.val(this._textProvider.toString());
this.options.text = this._textProvider.toString(true, false, false);
}
if(this.element.is(':disabled')) {
return;
}
if(keepSelection) {
this.selectText(range.start, range.end);
}
this.element.data('prevCursorPos', range.start);
this._raiseTextChanged();
this._raiseDataChanged();
};
wijinputcore.prototype._trySetFocus = function () {
if(!this.isFocused()) {
try {
if(!this.options.disableUserInput) {
this.element.focus();
}
} catch (e) {
}
}
};
wijinputcore.prototype._deleteSelText = function (backSpace) {
if (typeof backSpace === "undefined") { backSpace = false; }
if(!this._allowEdit()) {
return;
}
var selRange = this.element.wijtextselection(), rh;
if(backSpace) {
if(selRange.end < 1) {
return;
}
if(selRange.end === selRange.start) {
selRange.start--;
}
}
selRange.end--;
if(selRange.end < selRange.start) {
selRange.end = selRange.start;
}
rh = new wijInputResult();
this._textProvider.removeAt(selRange.start, selRange.end, rh);
this._updateText();
this.selectText(rh.testPosition, rh.testPosition);
};
wijinputcore.prototype._fireIvalidInputEvent = function (chr) {
var _this = this;
var cls;
if($.isFunction(this.options.invalidInput) && this._trigger('invalidInput', null, {
widget: this,
char: chr
}) === true) {
return;
}
if(!this.element.data('errorstate')) {
cls = this.options.invalidClass || this.options.wijCSS.stateError;
this.element.data('errorstate', true);
window.setTimeout(function () {
if(_this.outerDiv) {
_this.outerDiv.removeClass(cls);
}
_this.element.data('errorstate', false);
}, 200);
this.outerDiv.addClass(cls);
}
};
wijinputcore.prototype._onInput = function (e) {
if(!this._isSimulating() || !this.element.data('ime') || this.element.data("isComposingIME")) {
if(this.element.data("isComposingIME")) {
this.element.data("simulationPending", true);
}
return;
}
this._simulate();
};
wijinputcore.prototype._keyDownPreview = function (e) {
return false;// true means handled.
};
wijinputcore.prototype._onDoubleByteCharacter = function () {
var prev = this.element.data("lastDbsState");
var curSel = this.element.wijtextselection();
var curText = this.element.val();
if(this.element.data("isComposingIME") && prev && prev.selection.start === curSel.start && prev.Text === curText) {
// nothing changed. The input must be accepted
this.element.removeData("lastDbsState");
this._onCompositionEnd();
} else {
this.element.data("lastDbsState", {
selection: curSel,
text: curText
});
this._onCompositionStart();
}
};
wijinputcore.prototype._onCompositionStart = function () {
if(this.element.data("isComposingIME")) {
return;
}
this.element.data("isComposingIME", true);
this._beforeSimulate(true);
};
wijinputcore.prototype._onCompositionEnd = function () {
if(!this.element.data("isComposingIME")) {
return;
}
this.element.data("isComposingIME", false);
if(this._isInitialized() && (!this._textProvider || !this._textProvider.noMask)) {
this._simulateIfPending();
}
};
wijinputcore.prototype._simulateIfPending = function () {
if(this.element.data("simulationPending") && this.element.data("lastSelection")) {
this._simulate();
}
};
wijinputcore.prototype._beforeSimulate = function (ime) {
if (typeof ime === "undefined") { ime = false; }
if(!this.element.data('lastSelection')) {
this.element.data('lastSelection', this.element.wijtextselection());
this.element.data('lastValue', this.element.val());
}
this.element.data('ime', ime);
this.element.data('simulating', true);
};
wijinputcore.prototype._isSimulating = function () {
return this.element.data('simulating');
};
wijinputcore.prototype._simulate = function (text) {
var self = this, str = null, range, start, end;
this.element.data("simulationPending", false);
if(typeof text === "string") {
str = text;
} else {
range = this.element.wijtextselection();
start = this.element.data('lastSelection').start;
end = range.end;
if(end >= start) {
str = this.element.val().substring(start, end);
}
}
if(str) {
window.setTimeout(function () {
if(!self.element.data('lastValue')) {
return;
}
self.element.val(self.element.data('lastValue'));
var lastSel = self.element.data('lastSelection'), e, i;
self.element.wijtextselection(lastSel);
self.element.data('batchKeyPress', true);
self.element.data('simulating', false);
e = jQuery.Event('keypress');
e.ctrlKey = e.altKey = false;
for(i = 0; i < str.length; i++) {
e.which = e.charCode = e.keyCode = str.charCodeAt(i);
self._onKeyPress(e);
}
self.element.data('batchKeyPress', false);
self._endSimulate();
}, 1);
}
};
wijinputcore.prototype._endSimulate = function () {
this._simulateIfPending();
this.element.removeData('ime');
this.element.removeData('lastSelection');
this.element.removeData('lastValue');
};
wijinputcore.prototype._onKeyDown = function (e) {
this.element.data('prevCursorPos', -1);
if(!this._isInitialized() || (this._textProvider && !!this._textProvider.noMask)) {
return;
}
var k = this._getKeyCode(e);
if(k === 229) {
// Double Bytes
this._onDoubleByteCharacter();
return;
}
this._onCompositionEnd();
if(this.options.disableUserInput) {
this._stopEvent(e);
return;
}
if(this._keyDownPreview(e)) {
this._stopEvent(e);
return;
}
switch(k) {
case jqKeyCode.UP:
this._doSpin(true, false);
this._stopEvent(e);
return;
case jqKeyCode.DOWN:
this._doSpin(false, false);
this._stopEvent(e);
return;
}
if(e.ctrlKey) {
switch(k) {
case jqKeyCode.INSERT:
case 67:
// 'c'
return;
default:
break;
}
}
if((e.ctrlKey || e.altKey)) {
return;
}
switch(k) {
case 112:
// F1-F6
case 113:
case 114:
case 115:
case 116:
case 117:
case jqKeyCode.TAB:
case jqKeyCode.CAPSLOCK:
case jqKeyCode.END:
case jqKeyCode.HOME:
case jqKeyCode.CTRL:
case jqKeyCode.SHIFT:
return;
case jqKeyCode.BACKSPACE:
this._deleteSelText(true);
this._stopEvent(e);
return;
case jqKeyCode.DELETE:
this._deleteSelText(false);
this._stopEvent(e);
return;
case jqKeyCode.ENTER:
this._onEnterDown(e);
break;
case jqKeyCode.ESCAPE:
this._stopEvent(e);
window.setTimeout($.proxy(this._resetData, this), 1);
return;
case jqKeyCode.PAGE_UP:
case jqKeyCode.PAGE_DOWN:
case jqKeyCode.ALT:
this._stopEvent(e);
return;
}
};
wijinputcore.prototype._onEnterDown = function (e) {
if(this.options.hideEnter) {
this._stopEvent(e);
}
};
wijinputcore.prototype._onKeyUp = function (e) {
if(this._textProvider && !!this._textProvider.noMask) {
return;
}
var key = this._getKeyCode(e);
if(this._isSimulating()) {
if(key === jqKeyCode.ENTER) {
this._onCompositionEnd();
}
return;
}
if(!this._isInitialized()) {
return;
}
if(key === jqKeyCode.ENTER || key === jqKeyCode.ESCAPE) {
return;
}
if(this.options.disableUserInput) {
this._raiseTextChanged();
this._raiseDataChanged();
return;
}
this._stopEvent(e);
};
wijinputcore.prototype._getKeyCode = function (e) {
var userAgent = window.navigator.userAgent;
if((userAgent.indexOf('iPod') !== -1 || userAgent.indexOf('iPhone') !== -1) && e.which === 127) {
return 8;
}
return e.keyCode || e.which;
};
wijinputcore.prototype._keyPressPreview = function (e) {
return false;
};
wijinputcore.prototype._onKeyPress = function (e) {
if(this._isSimulating() || (this._textProvider && !!this._textProvider.noMask)) {
return;
}
this.element.data('prevCursorPos', -1);
if(this.options.disableUserInput) {
return;
}
if(!this._allowEdit()) {
return;
}
if(e.ctrlKey && e.keyCode === 119) {
//Ctrl + F8
this._onPaste(e);
return;
}
var key = e.keyCode || e.which, rh, ch;
switch(key) {
case 0:
case jqKeyCode.TAB:
case jqKeyCode.UP:
case jqKeyCode.DOWN:
case jqKeyCode.LEFT:
case jqKeyCode.RIGHT:
return;
case jqKeyCode.BACKSPACE:
this._stopEvent(e);
return;
case jqKeyCode.ENTER:
if(this.options.hideEnter) {
this._stopEvent(e);
}
return;
}
if(e.ctrlKey || e.altKey) {
if(key !== jqKeyCode.SPACE) {
return;
}
}
if(this._keyPressPreview(e)) {
return;
}
ch = String.fromCharCode(key);
rh = this._textProvider.replaceWith(this.element.wijtextselection(), ch);
if(rh) {
this._updateText();
this.selectText(rh.testPosition + 1, rh.testPosition + 1);
} else {
this._fireIvalidInputEvent(ch);
}
if(!this.element.data('batchKeyPress')) {
this._stopEvent(e);
}
};
wijinputcore.prototype._isNullText = function (val) {
val = val || this.element.val();
return this.options.showNullText && val === this.options.nullText;
};
wijinputcore.prototype._doFocus = function () {
var selRange = this.element.wijtextselection(), sta = selRange.start, s;
this._updateText();
s = this.element.val();
if(s.length === sta) {
sta = 0;
}
if(!$.browser.safari) {
this.selectText(sta, sta);
}
};
wijinputcore.prototype._afterFocused = function () {
if(this._isNullText()) {
this._doFocus();
}
};
wijinputcore.prototype._onFocus = function (e) {
if(this.options.disableUserInput) {
return;
}
this._addState('focus', this.outerDiv);
if(!this.element.data('breakSpinner')) {
return;
}
if(!this._isInitialized()) {
return;
}
if(!this._allowEdit()) {
return;
}
if(!this.element.data('focusNotCalledFirstTime')) {
this.element.data('focusNotCalledFirstTime', new Date().getTime());
}
this._afterFocused();
};
wijinputcore.prototype._onBlur = function (e) {
var _this = this;
if(this.options.disableUserInput) {
return;
}
this._onCompositionEnd();
if(this._isComboListVisible()) {
return;
}
var focused = this.isFocused(), curPos;
this._removeState('focus', this.outerDiv);
if(!this.element.data('breakSpinner')) {
this.element.get(0).focus();
curPos = this.element.data('prevCursorPos');
if(curPos !== undefined && curPos !== -1) {
this.selectText(curPos, curPos);
}
return;
}
if(!this._isInitialized() || !focused) {
return;
}
this.element.data('value', this.element.val());
window.setTimeout(function () {
// this._onChange();
_this._updateText();
_this._validateData();
if(_this.element.data('changed')) {
_this.element.data('changed', false);
if(!_this._popupVisible()) {
_this._trigger('change');
_this.element.change();
}
}
}, 100);
};
wijinputcore.prototype._popupVisible = function () {
return this._isComboListVisible();
};
wijinputcore.prototype._onMouseUp = function (e) {
if(!this._isInitialized()) {
return;
}
if(this.element.is(':disabled')) {
return;
}
var selRange = this.element.wijtextselection(), self = this;
this.element.data('prevCursorPos', selRange.start);
// fixed an issue of IE10(browser mode IE9), when runs in this mode,
// the input element will show clear button at the right side of the input element.
// click the button, the widget's text value will not cleared.
if(this.element.val() == '') {
return;
}
// Wait for it....
setTimeout(function () {
if(self.element.val() == '') {
self.setText("");
}
}, 5);
};
wijinputcore.prototype._onChange = function () {
if(!this.element) {
return;
}
var val = this.element.val(), txt = this.getText();
if(txt !== val) {
this.setText(val);
}
};
wijinputcore.prototype._onPaste = function (e) {
if(this._textProvider && !!this._textProvider.noMask) {
return;
}
this._beforeSimulate();
var self = this;
window.setTimeout(function () {
self._simulate();
}, 1);
};
wijinputcore.prototype._onDrop = function (e) {
this._beforeSimulate();
if(e.originalEvent && e.originalEvent.dataTransfer) {
var text = e.originalEvent.dataTransfer.getData('Text');
if(text) {
this._simulate(text);
}
}
};
wijinputcore.prototype._stopEvent = function (e) {
e.stopPropagation();
e.preventDefault();
};
wijinputcore.prototype._calcSpinInterval = function () {
this._repeatingCount++;
if(this._repeatingCount > 10) {
return 50;
} else if(this._repeatingCount > 4) {
return 100;
} else if(this._repeatingCount > 2) {
return 200;
}
return 400;
};
wijinputcore.prototype._doSpin = function (up, repeating) {
return false;
};
wijinputcore.prototype._stopSpin = function () {
this.element.data('breakSpinner', true);
this._repeatingCount = 0;
};
wijinputcore.prototype._hasComboItems = function () {
return (!!this.options.comboItems && this.options.comboItems.length);
};
wijinputcore.prototype._isComboListVisible = function () {
if(!this._comboDiv) {
return false;
}
return this._comboDiv.wijpopup('isVisible');
};
wijinputcore.prototype._popupComboList = function () {
var _this = this;
if(!this._hasComboItems()) {
return;
}
if(!this._allowEdit()) {
return;
}
var content;
if(this._comboDiv === undefined) {
this._comboDiv = $("<div></div>").appendTo(document.body).css('position', 'absolute');
content = this._normalize(this.options.comboItems);
this._comboDiv.wijlist({
maxItemsCount: 5,
selected: function (event, ui) {
_this._setData(ui.item.value);
_this._comboDiv.wijpopup('hide');
_this._trySetFocus();
}
});
this._comboDiv.wijlist('setItems', content);
this._comboDiv.wijlist('renderList');
}
// dimensions
this._comboDiv.width(this.outerDiv.width());
this._comboDiv.wijlist("option", "autoSize", !this.options.comboHeight);
if(this.options.comboHeight) {
this._comboDiv.height(this.options.comboHeight);
}
this._comboDiv.wijlist("refreshSuperPanel");
this._comboDiv.wijpopup({
autoHide: true
});
this.outerDiv.attr('aria-expanded', true);
this._comboDiv.wijpopup('show', {
of: this.outerDiv,
offset: '0 4',
hidden: function () {
_this.outerDiv.attr('aria-expanded', false);
}
});
};
wijinputcore.prototype._normalize = function (items) {
// assume all items have the right format when the first item is complete
if(items.length && items[0].label && items[0].value) {
return items;
}
return $.map(items, function (item) {
if(typeof item === "string") {
return {
label: item,
value: item
};
}
return $.extend({
label: item.label || item.value,
value: item.value || item.label
}, item);
});
};
return wijinputcore;
})(wijmo.wijmoWidget);
input.wijinputcore = wijinputcore;
;
var wijinputClass = "wijmo-wijinput", classPrefix = wijinputClass + "-";
var wijinputcore_options = (function () {
function wijinputcore_options() {
this.wijCSS = {
wijinput: wijinputClass,
wijinputInput: classPrefix + "input",
wijinputWrapper: classPrefix + "wrapper",
wijinputTrigger: classPrefix + "trigger",
wijinputSpinner: classPrefix + "spinner",
wijinputButton: classPrefix + "button",
wijinputSpinUp: classPrefix + "spinup",
wijinputSpinDown: classPrefix + "spindown"
};
/** Determines the culture used to show values in the wijinputdate widget. */
this.culture = '';
/** The CSS class applied to the widget when an invalid value is entered. */
this.invalidClass = $.wijmo.wijCSS.stateError;
/** Determines the text displayed when the widget is blank and contains no initial text. */
this.nullText = '';
/** Shows the nullText value if the widget is blank and loses focus. */
this.showNullText = false;
/** If true, then the browser response is disabled
* when the ENTER key is pressed.
*/
this.hideEnter = false;
/** Determines whether a user can enter a value in the wijinputdate widget. */
this.disableUserInput = false;
/** Determines the side, left or right, where the trigger or spinner buttons appear.
* Possible values are: 'left', 'right'
*/
this.buttonAlign = 'right';
/** Determines whether trigger button is displayed. */
this.showTrigger = false;
/** Determines whether spinner button is displayed. */
this.showSpinner = false;
/** Array of data items used to populate the drop-down list. */
this.comboItems = undefined;
/** Determines the width of the drop-down list. */
this.comboWidth = undefined;
/** Determines the height of the drop-down list. */
this.comboHeight = undefined;
/** The initializing event handler.
* A function called before the widget is initialized.
* @event
*/
this.initializing = null;
/** The initialized event handler.
* A function called after the widget is initialized.
* @event
*/
this.initialized = null;
/** The triggerMouseDown event handler. A function called
* when the mouse is pressed down on the trigger button.
* @event
*/
this.triggerMouseDown = null;
/** The triggerMouseUp event handler. A function called
* when the mouse is released on the trigger button.
* @event
*/
this.triggerMouseUp = null;
/** Fired when the widget text is changed.
* @event
* @dataKey {String} text The new text.
*/
this.textChanged = null;
/** The invalidInput event handler. A function called
* when invalid charactor is typed.
* @event
* @dataKey {String} char The newly input character.
* @dataKey widget The widget object itself.
*/
this.invalidInput = null;
}
return wijinputcore_options;
})();
wijinputcore.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijinputcore_options());
var wijInputResult = (function () {
function wijInputResult() {
this.characterEscaped = 1;
this.noEffect = 2;
this.sideEffect = 3;
this.success = 4;
this.unknown = 0;
this.hint = 0;
this.alphanumericCharacterExpected = -2;
this.asciiCharacterExpected = -1;
this.digitExpected = -3;
this.invalidInput = -51;
this.letterExpected = -4;
this.nonEditPosition = -54;
this.positionOutOfRange = -55;
this.promptCharNotAllowed = -52;
this.signedDigitExpected = -5;
this.unavailableEditPosition = -53;
this.testPosition = -1;
}
wijInputResult.prototype.clone = function () {
var rh = new wijInputResult();
rh.hint = this.hint;
rh.testPosition = this.testPosition;
return rh;
};
return wijInputResult;
})();
input.wijInputResult = wijInputResult;
var wijTextProvider = (function () {
function wijTextProvider() { }
wijTextProvider.prototype.set = function (value, rh) {
};
wijTextProvider.prototype.toString = function (ignorePasswordChar, includePrompt, includeLiterals, start, length) {
return "";
};
wijTextProvider.prototype.insertAt = function (char, index, rh) {
return false;
};
wijTextProvider.prototype.removeAt = function (start, end, rh, skipCheck) {
};
wijTextProvider.prototype.replaceWith = function (range, text) {
var index = range.start, result = new wijInputResult();
if(range.start < range.end) {
this.removeAt(range.start, range.end - 1, result, true);
index = result.testPosition;
}
return this.insertAt(text, index, result) ? result : null;
};
return wijTextProvider;
})();
input.wijTextProvider = wijTextProvider;
})(wijmo.input || (wijmo.input = {}));
var input = wijmo.input;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="jquery.wijmo.wijinputcore.ts"/>
/// <reference path="../wijcalendar/jquery.wijmo.wijcalendar.ts"/>
/*globals wijDateTextProvider wijinputcore wijInputResult window document Globalize jQuery*/
/*
* Depends:
* jquery-1.4.2.js
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.position.js
* jquery.effects.core.js
* jquery.effects.blind.js
* globalize.js
* jquery.plugin.wijtextselection.js
* jquery.mousewheel.js
* jquery.wijmo.wijpopup.js
* jquery.wijmo.wijcalendar.js
* jquery.wijmo.wijinputcore.js
*
*/
(function (input) {
"use strict";
var $ = jQuery, jqKeyCode = ($.ui || $.mobile).keyCode;
// var wijdigits = {
// useDefault: -2,
// asIs: -1,
// zero: 0,
// one: 1,
// two: 2,
// three: 3,
// four: 4,
// five: 5,
// six: 6,
// seven: 7,
// eight: 8
// }
function paddingZero(val, aCount) {
if (typeof aCount === "undefined") { aCount = 2; }
var text = '' + val + '';
if(text.length > aCount) {
text = text.substr(text.length - aCount);
} else {
while(text.length < aCount) {
text = '0' + text;
}
}
return text;
}
/** @widget */ var wijinputdate = (function (_super) {
__extends(wijinputdate, _super);
function wijinputdate() {
_super.apply(this, arguments);
}
wijinputdate.prototype._createTextProvider = function () {
this._textProvider = new wijDateTextProvider(this, this.options.dateFormat);
};
wijinputdate.prototype._strToDate = function (str) {
return this._textProvider.parseDate(str);
};
wijinputdate.prototype._beginUpdate = function () {
var o = this.options, strDate, date = null;
_super.prototype._beginUpdate.call(this);
if(o.minDate) {
if(typeof o.minDate === 'string') {
o.minDate = this._strToDate(o.minDate);
}
}
if(o.maxDate) {
if(typeof o.maxDate === 'string') {
o.maxDate = this._strToDate(o.maxDate);
}
}
if(!o.date) {
if(!!this.element.data('elementValue')) {
strDate = this.element.data('elementValue');
}
} else {
if(typeof o.date === 'string') {
strDate = o.date;
} else {
date = o.date;
}
}
if(strDate) {
date = this._strToDate(strDate);
}
this._safeSetDate(date);
this.element.data({
defaultDate: date === null ? date : new Date(o.date.getTime()),
preDate: date === null ? date : new Date(o.date.getTime())
});
this._resetTimeStamp();
if(o.showTrigger && !this._hasComboItems()) {
this._initCalendar();
}
this.element.addClass(o.wijCSS.wijinputdate).attr({
'aria-valuemin': new Date(1900, 1, 1),
'aria-valuemax': new Date(2099, 1, 1),
'aria-valuenow': o.date
});
};
wijinputdate.prototype._endUpdate = function () {
var _this = this;
_super.prototype._endUpdate.call(this);
this.element.bind("click.wijinput", function () {
_this._highLightCursor();
});
};
wijinputdate.prototype._isValidDate = function (date, chkBounds) {
var o = this.options;
if(date === undefined) {
return false;
}
if(isNaN(date)) {
return false;
}
if(date.getFullYear() < 1 || date.getFullYear() > 9999) {
return false;
}
if(chkBounds) {
if(o.minDate) {
if(date < o.minDate) {
return false;
}
}
if(o.maxDate) {
if(date > o.maxDate) {
return false;
}
}
}
return true;
};
wijinputdate.prototype._checkRange = function (date) {
var o = this.options;
if(date) {
if(o.minDate && date < o.minDate) {
date = new Date(Math.max(o.minDate, date));
}
if(o.maxDate && date > o.maxDate) {
date = new Date(Math.min(o.maxDate, date));
}
}
return date;
};
wijinputdate.prototype._safeSetDate = function (date) {
var o = this.options, cache = date;
date = this._checkRange(date);
if(isNaN(date)) {
date = cache;
}
o.date = date;
return true;
};
wijinputdate.prototype._safeGetDate = function () {
var date = this.options.date || this._creationDate;
date = this._checkRange(date);
return date;
};
wijinputdate.prototype._setOption = function (key, value) {
_super.prototype._setOption.call(this, key, value);
switch(key) {
case 'date':
if(!!value) {
if(typeof value === "string") {
value = this._strToDate(value);
} else if(typeof value === "object") {
value = new Date(value.getTime());
} else {
value = new Date(value);
}
if(isNaN(value)) {
value = new Date();
}
}
this._safeSetDate(value);
this._updateText();
this._highLightField();
break;
case 'dateFormat':
case 'culture':
this._textProvider._setFormat(this.options.dateFormat);
this._updateText();
// update the calendar 's culture
var calendar = this.element.data('calendar');
if(calendar) {
calendar.wijcalendar("option", key, value);
}
break;
case 'activeField':
value = Math.min(value, this._textProvider.getFieldCount() - 1);
value = Math.max(value, 0);
this.options.activeField = value;
this._highLightField();
this._resetTimeStamp();
break;
//add for localization(calendar's tooltip)
case 'nextTooltip':
case 'prevTooltip':
case 'titleFormat':
case 'toolTipFormat':
// update the calendar 's tooltip
var calendar = this.element.data('calendar', calendar);
if(calendar) {
calendar.wijcalendar("option", key, value);
}
break;
}
};
wijinputdate.prototype._setData = function (val) {
this.option('date', val);
};
wijinputdate.prototype._resetData = function () {
var d = this.element.data('defaultDate');
if(d === undefined || d === null) {
d = this.element.data('elementValue');
if(d !== undefined && d !== null && d !== "") {
this.setText(d);
} else {
this._setData(null);
}
} else {
this._setData(d);
}
};
wijinputdate.prototype._resetTimeStamp = function () {
this.element.data('cursorPos', 0);
this.element.data('timeStamp', new Date('1900/1/1'));
};
wijinputdate.prototype.getPostValue = /** Gets the text value when the container form is posted back to server. */
function () {
if(!this._isInitialized()) {
return this.element.val();
}
if(this.options.showNullText && this.isDateNull()) {
return "";
}
var val = this._textProvider.toString();
if(val === this.options.nullText) {
return "";
}
return val;
};
wijinputdate.prototype._highLightField = function (index) {
if (typeof index === "undefined") { index = this.options.activeField; }
if(this.isFocused()) {
var range = this._textProvider.getFieldRange(index);
if(range) {
this.element.wijtextselection(range);
}
}
};
wijinputdate.prototype._highLightCursor = function (pos) {
if(this._isNullText()) {
return;
}
if(pos === undefined) {
pos = Math.max(0, this.element.wijtextselection().start);
}
var index = this._textProvider.getCursorField(pos);
if(index < 0) {
return;
}
this._setOption('activeField', index);
};
wijinputdate.prototype._toNextField = function () {
this._setOption('activeField', this.options.activeField + 1);
};
wijinputdate.prototype._toPrevField = function () {
this._setOption('activeField', this.options.activeField - 1);
};
wijinputdate.prototype._toFirstField = function () {
this._setOption('activeField', 0);
};
wijinputdate.prototype._toLastField = function () {
this._setOption('activeField', this._textProvider.getFieldCount());
};
wijinputdate.prototype._clearField = function (index) {
if (typeof index === "undefined") { index = this.options.activeField; }
var range = this._textProvider.getFieldRange(index), rh, self = this;
if(range) {
rh = new input.wijInputResult();
this._textProvider.removeAt(range.start, range.end, rh);
this._updateText();
window.setTimeout(function () {
self._highLightField();
}, 1);
}
};
wijinputdate.prototype._doSpin = function (up, repeating) {
var _this = this;
if(!this._allowEdit()) {
return false;
}
if(repeating && this.element.data('breakSpinner')) {
return false;
}
if(this._textProvider[up ? 'incEnumPart' : 'decEnumPart']()) {
this._updateText();
this._highLightField();
}
if(repeating && !this.element.data('breakSpinner')) {
window.setTimeout(function () {
return _this._doSpin(up, true);
}, this._calcSpinInterval());
}
return true;
};
wijinputdate.prototype._onChange = function () {
};
wijinputdate.prototype._afterFocused = function () {
if(this._isNullText()) {
this._doFocus();
}
//var hc = () => {
// this._highLightCursor();
// this._resetTimeStamp();
//};
// to fixed the issue 27522. remove this time out. by dail 2012-9-6
//window.setTimeout(hc, 10);
};
wijinputdate.prototype._keyDownPreview = function (e) {
var key = e.keyCode || e.which, selRange;
switch(key) {
case jqKeyCode.LEFT:
this._toPrevField();
return true;
case jqKeyCode.RIGHT:
this._toNextField();
return true;
case jqKeyCode.TAB:
//update for 37520 issue
if(e.shiftKey) {
if(this.options.activeField > 0) {
this._toPrevField();
return true;
}
} else {
selRange = this.element.wijtextselection();
if(selRange && selRange.end - selRange.start === this.element.val().length) {
break;
}
if(this.options.activeField < this._textProvider.getFieldCount() - 1) {
this._toNextField();
return true;
}
}
break;
case jqKeyCode.SPACE:
case 188:
// ,
case 190:
// .
case 110:
// . on pad
case 191:
// /
if(e.shiftKey) {
if(this.options.activeField > 0) {
this._toPrevField();
return true;
}
} else {
if(this.options.activeField < this._textProvider.getFieldCount() - 1) {
this._toNextField();
return true;
}
}
break;
case jqKeyCode.HOME:
if(e.ctrlKey) {
this._setOption('date', new Date());
} else {
this._toFirstField();
}
return true;
case jqKeyCode.END:
if(e.ctrlKey) {
this._setOption('date', new Date('1970/1/1'));
} else {
this._toLastField();
}
return true;
case jqKeyCode.DELETE:
if(this._allowEdit()) {
selRange = this.element.wijtextselection();
if(selRange.end - selRange.start === this.element.val().length) {
this.isDeleteAll = true;
this._setOption('date', new Date('1970/1/1'));
} else {
this._clearField();
}
return true;
}
break;
}
return false;
};
wijinputdate.prototype._autoMoveToNextField = function (pos, ch) {
if(!this.options.autoNextField) {
return;
}
if(this._textProvider.needToMove(this.options.activeField, pos, ch)) {
this._toNextField();
}
};
wijinputdate.prototype._keyPressPreview = function (e) {
var key = e.keyCode || e.which, range, ch, fieldSep, cursor, now, newAction, lastTime, pos, ret, input, lastInput;
if(key === jqKeyCode.ENTER) {
if(this.isDateNull()) {
this.options.date = new Date();
}
return false;
}
range = this._textProvider.getFieldRange(this.options.activeField);
if(range) {
if(key === jqKeyCode.TAB) {
return true;
}
if(key === jqKeyCode.SPACE) {
this._stopEvent(e);
return true;
}
ch = String.fromCharCode(key);
fieldSep = this._textProvider.isFieldSep(ch, this.options.activeField);
if(fieldSep) {
this._toNextField();
this._stopEvent(e);
return true;
}
cursor = this.element.data('cursorPos');
now = new Date();
lastTime = this.element.data('timeStamp');
lastInput = this.element.data('lastInput');
newAction = (now.getTime() - lastTime.getTime()) > this.options.keyDelay;
var input = ch;
if(newAction) {
cursor = 0;
} else if(lastInput) {
input = lastInput + input;
}
this.element.data({
timeStamp: now,
lastInput: input
});
pos = range.start + cursor;
this.element.data('cursorPos', ++cursor);
ret = this._textProvider.addToField(input, this.options.activeField, pos);
if(ret) {
this._updateText();
this._autoMoveToNextField(cursor, ch);
this._highLightField();
} else {
this._resetTimeStamp();
this._fireIvalidInputEvent();
}
this._stopEvent(e);
return true;
}
return false;
};
wijinputdate.prototype._raiseDataChanged = function () {
var d = this.options.date, prevDt = this.element.data('preDate');
this.element.data('preDate', !d ? null : new Date(d.getTime()));
if((!prevDt && d) || (prevDt && !d) || (prevDt && d && (prevDt.getTime() !== d.getTime()))) {
this._syncCalendar();
this.element.attr('aria-valuenow', d);
this._trigger('dateChanged', null, {
date: d
});
}
};
wijinputdate.prototype.isDateNull = /** Determines whether the date is a null value. */
function () {
return this.options.date === null || this.options.date === undefined;
};
wijinputdate.prototype._isMinDate = function (date) {
return date.getFullYear() === 1 && date.getMonth() === 0 && date.getDate() === 1;
};
wijinputdate.prototype._initCalendar = function () {
var _this = this;
var o = this.options, c = o.calendar, calendar;
if(c === undefined || c === null) {
return;
}
if(typeof (c) === 'boolean' || c === 'default') {
c = $("<div/>");
c.appendTo(document.body);
}
calendar = $(c);
if(calendar.length !== 1) {
return;
}
this.element.data('calendar', calendar);
// if the localization from the resource files.
if(o.localization) {
o.nextTooltip = o.localization.nextTooltip;
o.prevTooltip = o.localization.prevTooltip;
o.titleFormat = o.localization.titleFormat;
o.toolTipFormat = o.localization.toolTipFormat;
}
calendar.wijcalendar({
popupMode: true,
culture: o.culture,
nextTooltip: //add for localization(tooltip)
o.nextTooltip || 'Next',
prevTooltip: o.prevTooltip || 'Previous',
titleFormat: o.titleFormat || 'MMMM yyyy',
toolTipFormat: o.toolTipFormat || 'dddd, MMMM dd, yyyy',
selectedDatesChanged: function () {
var selDate = calendar.wijcalendar("getSelectedDate"), curDate = _this.option('date');
calendar.wijcalendar("close");
if(selDate) {
if(curDate) {
selDate.setHours(curDate.getHours());
selDate.setMinutes(curDate.getMinutes());
selDate.setSeconds(curDate.getSeconds());
selDate.setMilliseconds(curDate.getMilliseconds());
}
_this.option('date', selDate);
_this.selectText();
}
_this._trySetFocus();
}
});
this._syncCalendar();
// the bind event can't trigger.!!!
// calendar.bind('wijcalendarselectedDatesChanged', function () {
// var selDate = $(this).wijcalendar("getSelectedDate");
// $(this).wijcalendar("close");
// if (!!selDate) { self.option('date', selDate); }
// self._trySetFocus();
// });
};
wijinputdate.prototype._syncCalendar = function () {
var calendar = this.element.data('calendar'), o, d;
if(!calendar) {
return;
}
o = this.options;
d = this._safeGetDate();
if(this._isMinDate(d)) {
d = new Date();
}
calendar.wijcalendar('option', 'displayDate', d);
if(o.minDate) {
calendar.wijcalendar('option', 'minDate', o.minDate);
}
if(o.maxDate) {
calendar.wijcalendar('option', 'maxDate', o.maxDate);
}
calendar.wijcalendar('unSelectAll');
calendar.wijcalendar('selectDate', d);
calendar.wijcalendar('refresh');
};
wijinputdate.prototype._isPopupShowing = function () {
var calendar = this.element.data('calendar');
if(!calendar) {
return _super.prototype._isPopupShowing.call(this);
}
return calendar.wijcalendar('isPopupShowing');
};
wijinputdate.prototype._showPopup = function () {
var calendar = this.element.data('calendar');
if(!calendar) {
return _super.prototype._showPopup.call(this);
}
if(!this._allowEdit()) {
return;
}
this._syncCalendar();
calendar.wijcalendar('popup', $.extend({
}, this.options.popupPosition, {
of: this.outerDiv
}));
};
wijinputdate.prototype._hidePopup = function () {
var calendar = this.element.data('calendar');
if(!calendar) {
return _super.prototype._hidePopup.call(this);
}
calendar.wijcalendar("close");
};
wijinputdate.prototype._isCalendarVisible = function () {
if(!this._allowEdit()) {
return false;
}
var calendar = this.element.data('calendar');
if(!calendar) {
return false;
}
return calendar.wijcalendar('isPopupShowing');
};
wijinputdate.prototype._popupVisible = function () {
if(this._hasComboItems()) {
return this._isComboListVisible();
} else {
return this._isCalendarVisible();
}
return false;
};
return wijinputdate;
})(input.wijinputcore);
input.wijinputdate = wijinputdate;
var wijinputdate_options = (function () {
function wijinputdate_options() {
this.wijCSS = {
wijinputdate: input.wijinputcore.prototype.options.wijCSS.wijinput + "-date"
};
/** Determines the initial date value shown for the wijdateinput widget. */
this.date = null;
/** Determines the earliest, or minimum, date that can be entered. */
this.minDate = null;
/** Determines the latest, or maximum date, that can be entered. */
this.maxDate = null;
/** The format pattern to display the date value
*
* @remarks
* wijinputdate supports two types of formats:
* Standard Format and Custom Format.
*
* A standard date and time format string uses a single format specifier
* to define the text representation of a date and time value.
*
* Possible values for Standard Format are:
* "d": ShortDatePattern
* "D": LongDatePattern
* "f": Full date and time (long date and short time)
* "F": FullDateTimePattern
* "g": General (short date and short time)
* "G": General (short date and long time)
* "m": MonthDayPattern
* "M": monthDayPattern
* "r": RFC1123Pattern
* "R": RFC1123Pattern
* "s": SortableDateTimePattern
* "t": shortTimePattern
* "T": LongTimePattern
* "u": UniversalSortableDateTimePattern
* "U": Full date and time (long date and long time) using universal time
* "y": YearMonthPattern
* "Y": yearMonthPattern
*
* Any date and time format string that contains more than one character,
* including white space, is interpreted as a custom date and time format
* string. For example:
* "mmm-dd-yyyy", "mmmm d, yyyy", "mm/dd/yyyy", "d-mmm-yyyy",
* "ddd, mmmm dd, yyyy" etc.
*
* Below are the custom date and time format specifiers:
*
* "d": The day of the month, from 1 through 31.
* "dd": The day of the month, from 01 through 31.
* "ddd": The abbreviated name of the day of the week.
* "dddd": The full name of the day of the week.
* "m": The minute, from 0 through 59.
* "mm": The minute, from 00 through 59.
* "M": The month, from 1 through 12.
* "MM": The month, from 01 through 12.
* "MMM": The abbreviated name of the month.
* "MMMM": The full name of the month.
* "y": The year, from 0 to 99.
* "yy": The year, from 00 to 99
* "yyy": The year, with a minimum of three digits.
* "yyyy": The year as a four-digit number
* "h": The hour, using a 12-hour clock from 1 to 12.
* "hh": The hour, using a 12-hour clock from 01 to 12.
* "H": The hour, using a 24-hour clock from 0 to 23.
* "HH": The hour, using a 24-hour clock from 00 to 23.
* "s": The second, from 0 through 59.
* "ss": The second, from 00 through 59.
* "t": The first character of the AM/PM designator.
* "tt": The AM/PM designator.
*/
this.dateFormat = 'd';
/** Determines the value of the starting year to be used for the smart
* input year calculation.
*/
this.startYear = 1950;
/** Allows smart input behavior.
* @remarks
* If this option is true, if the date's year is start '00',
* user input a character, the year will auto calculate according the start year option.
*/
this.smartInputMode = true;
/** Determines the active field index. */
this.activeField = 0;
/** Determines the time span, in milliseconds,
* between two input intentions.
* @remarks
* when press a keyboard, and the widget will delay a time and then handle
* the next keyboard press. Use this option to control the speed of the key press.
*/
this.keyDelay = 800;
/** Determines whether to automatically moves to the next field.
* @remarks
* For example, if user want input the '2012-9-20' in inputdate widget,
* if this option's value is true, when user type '2012' in textbox,
* it will auto focus in next field, user can type '9' in second field,
* if this option's value is false, user want to type '9' in second field,
* they should focus the second field by manual.
*/
this.autoNextField = true;
/** This option will supply an element to init the calendar widget
* @remarks
* If the value is 'default', the widget will create a div and
* append it to body element, and using this element to init calendar.
* User can set this option value to an element,
* and the widget will init the calendar using this element.
*/
this.calendar = 'default';
/** Detemines the popup position of a calendar.
* See jQuery.ui.position for position options.
*/
this.popupPosition = {
offset: '0 4'
};
/** The dateChanged event handler.
* A function called when the date of the input is changed.
* @event
* @dataKey {Date} date The data with this event.
*/
this.dateChanged = null;
}
return wijinputdate_options;
})();
wijinputdate.prototype.options = $.extend(true, {
}, input.wijinputcore.prototype.options, new wijinputdate_options());
$.wijmo.registerWidget("wijinputdate", wijinputdate.prototype);
var wijDateTextProvider = (function (_super) {
__extends(wijDateTextProvider, _super);
function wijDateTextProvider(inputWidget, format) {
_super.call(this);
this.inputWidget = inputWidget;
this.maskPartsCount = 0;
this.pattern = 'M/d/yyyy';
this._disableSmartInputMode = false;
this.paddingZero = paddingZero;
this.descriptors = new Array(0);
this.desPostions = new Array(0);
this.fields = new Array(0);
this._setFormat(format);
}
wijDateTextProvider.prototype.initialize = function () {
};
wijDateTextProvider.prototype.getFieldCount = function () {
return this.fields.length;
};
wijDateTextProvider.prototype.getFieldRange = function (index) {
var desc = this.fields[index];
return {
start: desc.startIndex,
end: desc.startIndex + desc.getText().length
};
};
wijDateTextProvider.prototype.getCursorField = function (pos) {
pos = Math.min(pos, this.desPostions.length - 1);
pos = Math.max(pos, 0);
var desc = this.desPostions[pos].desc, i;
if(desc.type === -1) {
i = $.inArray(desc, this.descriptors);
if(i > 0 && this.descriptors[i - 1].type !== -1) {
desc = this.descriptors[i - 1];
} else {
return -1;// liternal
}
}
return $.inArray(desc, this.fields);
};
wijDateTextProvider.prototype.needToMove = function (index, pos, ch) {
if(!this.inputWidget._isValidDate(this.inputWidget._safeGetDate(), true)) {
return false;
}
var desc = this.fields[index], val = parseInt(ch, 10);
if(pos === desc.maxLen) {
return true;
}
if(isNaN(val)) {
return false;
}
switch(desc.type) {
case 20:
case 25:
case 45:
case 46:
return val > 1;
case 47:
case 48:
return val > 2;
case 30:
case 31:
return val > 3;
case 50:
case 51:
case 60:
case 61:
return val > 6;
}
return false;
};
wijDateTextProvider.prototype._getCulture = function () {
return this.inputWidget._getCulture();
};
wijDateTextProvider.prototype._isDigitString = function (s) {
s = $.trim(s);
if(s.length === 0) {
return true;
}
var c = s.charAt(0), f, t;
if(c === '+' || c === '-') {
s = s.substr(1);
s = $.trim(s);
}
if(s.length === 0) {
return true;
}
try {
f = parseFloat(s);
t = f.toString();
return t === s;
} catch (e) {
return false;
}
};
wijDateTextProvider.prototype._setFormat = function (format) {
this.descriptors = [];
var curPattern = '', prevCh = '', isBegin = false, liternalNext = false, i, ch;
this.pattern = this._parseFormatToPattern(format);
for(i = 0; i < this.pattern.length; i++) {
ch = this.pattern.charAt(i);
if(liternalNext) {
this.descriptors.push(this.createDescriptor(-1, ch));
curPattern = '';
liternalNext = false;
continue;
}
if(ch === '\\') {
liternalNext = true;
if(curPattern.length > 0) {
if(!this.handlePattern(curPattern)) {
this.descriptors.push(this.createDescriptor(-1, prevCh));
}
curPattern = '';
}
continue;
}
if(ch === '\'') {
if(isBegin) {
isBegin = false;
curPattern = '';
} else {
isBegin = true;
if(curPattern.length > 0) {
if(!this.handlePattern(curPattern)) {
this.descriptors.push(this.createDescriptor(-1, prevCh));
}
curPattern = '';
}
}
continue;
}
if(isBegin) {
this.descriptors.push(this.createDescriptor(-1, ch));
curPattern = '';
continue;
}
if(!i) {
prevCh = ch;
}
if(prevCh !== ch && curPattern.length > 0) {
if(!this.handlePattern(curPattern)) {
this.descriptors.push(this.createDescriptor(-1, prevCh));
}
curPattern = '';
}
curPattern += ch;
prevCh = ch;
}
if(curPattern.length > 0) {
if(!this.handlePattern(curPattern)) {
this.descriptors.push(this.createDescriptor(-1, prevCh));
}
}
this.fields = $.grep(this.descriptors, function (d) {
return d.type !== -1;
});
};
wijDateTextProvider.prototype._parseFormatToPattern = function (format) {
var cf = this.inputWidget._getCulture().calendars.standard, pattern = cf.patterns.d;
if(format.length <= 1) {
switch(format) {
case "":
case "d":
// ShortDatePattern
pattern = cf.patterns.d;
break;
case "D":
// LongDatePattern
pattern = cf.patterns.D;
break;
case "f":
// Full date and time (long date and short time)
pattern = cf.patterns.D + " " + cf.patterns.t;
break;
case "F":
// Full date and time (long date and long time)
pattern = cf.patterns.D + " " + cf.patterns.T;
break;
case "g":
// General (short date and short time)
pattern = cf.patterns.d + " " + cf.patterns.t;
break;
case "G":
// General (short date and long time)
pattern = cf.patterns.d + " " + cf.patterns.T;
break;
case "m":
// MonthDayPattern
pattern = cf.patterns.M;
break;
case "M":
// monthDayPattern
pattern = cf.patterns.M;
break;
case "s":
// SortableDateTimePattern
pattern = cf.patterns.S;
break;
case "t":
// shortTimePattern
pattern = cf.patterns.t;
break;
case "T":
// LongTimePattern
pattern = cf.patterns.T;
break;
case "u":
// UniversalSortableDateTimePattern
pattern = cf.patterns.S;
break;
case "U":
// Full date and time (long date and long time) using universal time
pattern = cf.patterns.D + " " + cf.patterns.T;
break;
case "y":
// YearMonthPattern
pattern = cf.patterns.Y;
break;
case "Y":
// yearMonthPattern
pattern = cf.patterns.Y;
break;
}
} else {
pattern = format;
}
return pattern;
};
wijDateTextProvider.prototype.getDate = function () {
return (!!this.inputWidget) ? new Date(this.inputWidget._safeGetDate().getTime()) : undefined;
};
wijDateTextProvider.prototype.setDate = function (value) {
if(this.inputWidget) {
this.inputWidget._setData(value);
}
};
wijDateTextProvider.prototype._internalSetDate = function (date) {
if(this.inputWidget) {
var self = this, o = this.inputWidget.options, inputElement = this.inputWidget.element, typing = !!inputElement.data('typing'), chkBounds;
if(typing) {
o.date = date;
chkBounds = function () {
var now = new Date(), lastTime = inputElement.data('timeStamp');
if((now.getTime() - lastTime.getTime()) > o.keyDelay) {
self.inputWidget._safeSetDate(o.date);
self.inputWidget._updateText();
self.inputWidget._highLightField();
} else {
window.setTimeout(chkBounds, o.keyDelay);
}
};
window.setTimeout(chkBounds, o.keyDelay);
} else {
this.inputWidget._safeSetDate(date);
}
}
};
wijDateTextProvider.prototype.daysInMonth = function (m, y) {
m = m - 1;
var d = new Date(y, ++m, 1, -1).getDate();
return d;
};
wijDateTextProvider.prototype.setYear = function (val, resultObj, chkBounds) {
try {
if(resultObj && resultObj.isfullreset) {
resultObj.offset = 1;
val = '1970';
}
if(typeof val === 'string') {
if(!this._isDigitString(val)) {
return false;
}
}
val = val * 1;
var o = this.inputWidget.options, minYear = 1, maxYear = 9999, currentDate, testDate, mmm;
if(chkBounds) {
if(o.minDate) {
minYear = Math.max(minYear, o.minDate.getFullYear());
}
if(o.maxDate) {
maxYear = Math.min(maxYear, o.maxDate.getFullYear());
}
}
if(resultObj && resultObj.isreset) {
val = minYear;
}
if(val < minYear) {
val = minYear;
}
if(val > maxYear) {
val = maxYear;
}
currentDate = this.getDate();
testDate = new Date(currentDate.getTime());
testDate.setFullYear(val);
if(this._isValidDate(testDate)) {
mmm = this.daysInMonth(this.getMonth(), this.getYear());
if(mmm === currentDate.getDate()) {
testDate = new Date(currentDate.getTime());
testDate.setDate(1);
testDate.setFullYear(val);
mmm = this.daysInMonth((testDate.getMonth() + 1), testDate.getFullYear());
testDate.setDate(mmm);
if(this._isValidDate(testDate)) {
this._internalSetDate(testDate);
return true;
} else {
return false;
}
}
currentDate.setFullYear(val);
this._internalSetDate(currentDate);
return true;
} else {
if(resultObj && resultObj.isreset) {
currentDate.setFullYear(1);
this._internalSetDate(currentDate);
return true;
}
return false;
}
} catch (e) {
return false;
}
};
wijDateTextProvider.prototype.getYear = function () {
return this.getDate().getFullYear();
};
wijDateTextProvider.prototype.setMonth = function (val, allowChangeOtherParts, resultObj) {
try {
if(resultObj && resultObj.isfullreset) {
val = '1';
}
val = val * 1;
var currentDate = this.getDate(), mmm, testDate;
if(typeof (allowChangeOtherParts) !== 'undefined' && !allowChangeOtherParts) {
if(val > 12 || val < 1) {
if(resultObj && resultObj.isreset) {
val = 1;
} else {
return false;
}
}
}
mmm = this.daysInMonth(this.getMonth(), this.getYear());
if(mmm === this.getDate().getDate()) {
testDate = new Date(currentDate.getTime());
testDate.setDate(1);
testDate.setMonth(val - 1);
mmm = this.daysInMonth((testDate.getMonth() + 1), testDate.getFullYear());
testDate.setDate(mmm);
if(this._isValidDate(testDate)) {
this._internalSetDate(testDate);
return true;
} else {
return false;
}
} else {
testDate = new Date(currentDate.getTime());
testDate.setMonth(val - 1);
if(this._isValidDate(testDate)) {
this._internalSetDate(testDate);
return true;
} else {
return false;
}
}
} catch (e) {
return false;
}
};
wijDateTextProvider.prototype.getMonth = function () {
return (this.getDate().getMonth() + 1);
};
wijDateTextProvider.prototype.setDayOfMonth = function (val, allowChangeOtherParts, resultObj) {
try {
if(resultObj && resultObj.isfullreset) {
return this.setDayOfMonth(1, allowChangeOtherParts);
}
var currentDate = this.getDate(), mmm, testDate;
val = val * 1;
if(typeof (allowChangeOtherParts) !== 'undefined' && !allowChangeOtherParts) {
mmm = this.daysInMonth(this.getMonth(), this.getYear());
if(val > mmm || val < 1) {
if(resultObj && resultObj.isreset) {
return this.setDayOfMonth(1, allowChangeOtherParts, resultObj);
}
return false;
}
}
testDate = new Date(currentDate.getTime());
testDate.setDate(val);
if(this._isValidDate(testDate)) {
this._internalSetDate(testDate);
return true;
} else {
return false;
}
} catch (e) {
return false;
}
};
wijDateTextProvider.prototype.getDayOfMonth = function () {
return this.getDate().getDate();
};
wijDateTextProvider.prototype.setHours = function (val, allowChangeOtherParts) {
try {
val = val * 1;
if(typeof (allowChangeOtherParts) !== 'undefined' && !allowChangeOtherParts) {
if(val > 24) {
return false;
}
}
var testDate = new Date(this.getDate().getTime());
testDate.setHours(val);
if(this._isValidDate(testDate)) {
this._internalSetDate(testDate);
return true;
} else {
return false;
}
} catch (e) {
return false;
}
};
wijDateTextProvider.prototype.getHours = function () {
return this.getDate().getHours();
};
wijDateTextProvider.prototype.setMinutes = function (val, allowChangeOtherParts) {
try {
val = val * 1;
if(typeof (allowChangeOtherParts) !== 'undefined' && !allowChangeOtherParts) {
if(val > 60) {
return false;
}
}
var testDate = new Date(this.getDate().getTime());
testDate.setMinutes(val);
if(this._isValidDate(testDate)) {
this._internalSetDate(testDate);
return true;
} else {
return false;
}
} catch (e) {
return false;
}
};
wijDateTextProvider.prototype.getMinutes = function () {
return this.getDate().getMinutes();
};
wijDateTextProvider.prototype.setSeconds = function (val, allowChangeOtherParts) {
try {
val = val * 1;
if(typeof (allowChangeOtherParts) !== 'undefined' && !allowChangeOtherParts) {
if(val > 60) {
return false;
}
}
var testDate = new Date(this.getDate().getTime());
testDate.setSeconds(val);
if(this._isValidDate(testDate)) {
this._internalSetDate(testDate);
return true;
} else {
return false;
}
} catch (e) {
return false;
}
};
wijDateTextProvider.prototype.getSeconds = function () {
return this.getDate().getSeconds();
};
wijDateTextProvider.prototype.setDayOfWeek = function (val) {
try {
val = val * 1;
var aDif = val - this.getDayOfWeek();
return this.setDayOfMonth(this.getDayOfMonth() + aDif, true);
} catch (e) {
return false;
}
};
wijDateTextProvider.prototype.getDayOfWeek = function () {
return (this.getDate().getDay() + 1);
};
wijDateTextProvider.prototype.handlePattern = function (p) {
var reg = new RegExp('y{3,4}'), suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(10));
return true;
}
reg = new RegExp('y{2,2}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(2));
return true;
}
reg = new RegExp('y{1,1}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(1));
return true;
}
reg = new RegExp('d{4,4}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(101));
return true;
}
reg = new RegExp('d{3,3}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(100));
return true;
}
reg = new RegExp('d{2,2}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(30));
return true;
}
reg = new RegExp('d{1,1}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(31));
return true;
}
reg = new RegExp('M{4,4}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(27));
return true;
}
reg = new RegExp('M{3,3}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(26));
return true;
}
reg = new RegExp('M{2,2}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(20));
return true;
}
reg = new RegExp('M{1,1}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(25));
return true;
}
reg = new RegExp('h{2,2}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(46));
return true;
}
reg = new RegExp('h{1,1}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(45));
return true;
}
reg = new RegExp('H{2,2}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(48));
return true;
}
reg = new RegExp('H{1,1}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(47));
return true;
}
reg = new RegExp('m{2,2}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(50));
return true;
}
reg = new RegExp('m{1,1}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(51));
return true;
}
reg = new RegExp('s{2,2}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(60));
return true;
}
reg = new RegExp('s{1,1}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(61));
return true;
}
reg = new RegExp('t{2,2}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(251));
return true;
}
reg = new RegExp('t{1,1}');
suc = reg.test(p);
if(suc) {
this.descriptors.push(this.createDescriptor(250));
return true;
}
return false;
};
wijDateTextProvider.prototype.createDescriptor = function (t, liternal) {
var desc = null, id = this.maskPartsCount++;
switch(t) {
case -1:
desc = new _dateDescriptor(this, id);
desc.liternal = liternal;
break;
case 20:
desc = new _dateDescriptor20(this, id);
break;
case 25:
desc = new _dateDescriptor25(this, id);
break;
case 26:
desc = new _dateDescriptor26(this, id);
break;
case 27:
desc = new _dateDescriptor27(this, id);
break;
case 30:
desc = new _dateDescriptor30(this, id);
break;
case 31:
desc = new _dateDescriptor31(this, id);
break;
case 100:
desc = new _dateDescriptor100(this, id);
break;
case 101:
desc = new _dateDescriptor101(this, id);
break;
case 10:
desc = new _dateDescriptor10(this, id);
break;
case 1:
desc = new _dateDescriptor1(this, id);
break;
case 2:
desc = new _dateDescriptor2(this, id);
break;
case 45:
desc = new _dateDescriptor45(this, id);
break;
case 46:
desc = new _dateDescriptor46(this, id);
break;
case 47:
desc = new _dateDescriptor47(this, id);
break;
case 48:
desc = new _dateDescriptor48(this, id);
break;
case 250:
desc = new _dateDescriptor250(this, id);
break;
case 251:
desc = new _dateDescriptor251(this, id);
break;
case 50:
desc = new _dateDescriptor50(this, id);
break;
case 51:
desc = new _dateDescriptor51(this, id);
break;
case 60:
desc = new _dateDescriptor60(this, id);
break;
case 61:
desc = new _dateDescriptor61(this, id);
break;
default:
break;
}
return desc;
};
wijDateTextProvider.prototype.toString = function () {
if(this.inputWidget.options.showNullText && !this.inputWidget.isFocused() && this.inputWidget.isDateNull()) {
return this.inputWidget.options.nullText;
}
var s = '', l = 0, i, txt, j;
this.desPostions = new Array(0);
for(i = 0; i < this.descriptors.length; i++) {
this.descriptors[i].startIndex = s.length;
txt = '' || this.descriptors[i].getText();
s += txt;
for(j = 0; j < txt.length; j++) {
this.desPostions.push({
desc: this.descriptors[i],
pos: j,
text: txt,
length: txt.length
});
l++;
if(this.desPostions.length !== l) {
throw 'Fatal Error !!!!!!!!!!!!!!!';
}
}
}
return s;
};
wijDateTextProvider.prototype.parseDate = function (str) {
var date;
if(this.pattern === 'dddd' || this.pattern === 'ddd' || typeof str === 'object') {
try {
date = new Date(str);
if(isNaN(date)) {
date = new Date();
}
} catch (e) {
date = new Date();
}
} else {
date = Globalize.parseDate(str, this.pattern, this._getCulture());
if(!date) {
date = this._tryParseDate(str, this.pattern);
}
if(!date) {
date = new Date();
}
}
return date;
};
wijDateTextProvider.prototype.set = function (input) {
this._internalSetDate(new Date(this.parseDate(input)));
return true;
};
wijDateTextProvider.prototype.haveEnumParts = function () {
return false;
};
wijDateTextProvider.prototype.removeLiterals = function (s) {
s = '' + s + '';
s = s.replace(new RegExp('[+]', 'g'), '');
s = s.replace(new RegExp('[.]', 'g'), '');
s = s.replace(new RegExp('[:]', 'g'), '');
s = s.replace(new RegExp('[-]', 'g'), '');
s = s.replace(new RegExp('[()=]', 'g'), '');
return s;
};
wijDateTextProvider.prototype.getFirstDelimiterPos = function (aText, bText) {
var i = 0, j = 0, ch1, ch2;
while(i < bText.length && j < aText.length) {
ch1 = bText.charAt(i);
ch2 = aText.charAt(j);
if(ch1 === ch2) {
j++;
} else {
return j - 1;
}
i++;
}
return aText.length - 1;
};
wijDateTextProvider.prototype.findAlikeArrayItemIndex = function (arr, txt) {
var index = -1, pos = 99999, i, k;
for(i = 0; i < arr.length; i++) {
k = arr[i].toLowerCase().indexOf(txt.toLowerCase());
if(k !== -1 && k < pos) {
pos = k;
index = i;
}
}
return index;
};
wijDateTextProvider.prototype._isValidDate = function (dt) {
return this.inputWidget._isValidDate(dt);
};
wijDateTextProvider.prototype.isFieldSep = function (input, activeField) {
var nextField = activeField++, desc;
if(nextField < this.descriptors.length) {
desc = this.descriptors[nextField];
if(desc.type !== -1) {
return false;
}
return (input === desc.text);
}
return false;
};
wijDateTextProvider.prototype.getPositionType = function (pos) {
var desPos = this.desPostions[pos];
return desPos.desc.type;
};
wijDateTextProvider.prototype.addToField = function (input, activeField, pos) {
var desc = this.fields[activeField], txt, resultObj, ret;
txt = input;
resultObj = {
val: input,
pos: 0,
offset: 0,
isreset: false
};
this.inputWidget.element.data('typing', true);
ret = desc.setText(txt, ((input.length === 1) ? false : true), resultObj);
this.inputWidget.element.data('typing', false);
return ret;
};
wijDateTextProvider.prototype.insertAt = function (strInput, position, rh) {
if (typeof rh === "undefined") { rh = new input.wijInputResult(); }
rh.testPosition = -1;
var desPos, oldTxt, pos, txt, tryToExpandAtRight, result, tryToExpandAtLeft, curInsertTxt, resultObj, prevTextLength, posAdjustValue, altInsertText, newTextLength, diff, s, delimOrEndPos, delta;
if(strInput.length === 1) {
desPos = this.desPostions[position];
if(desPos && desPos.desc.type === -1) {
if(desPos.text === strInput) {
rh.testPosition = position;
rh.hint = rh.characterEscaped;
return true;
}
}
}
oldTxt = strInput;
pos = position;
strInput = this.removeLiterals(strInput);
txt = strInput;
tryToExpandAtRight = false;
tryToExpandAtLeft = false;
if(pos > 0 && txt.length === 1) {
pos--;
position = pos;
desPos = this.desPostions[pos];
tryToExpandAtRight = true;
if(desPos && (desPos.desc.type === -1 || desPos.desc.getText().length !== 1)) {
position++;
pos++;
tryToExpandAtRight = false;
}
}
result = false;
while(txt.length > 0 && pos < this.desPostions.length) {
desPos = this.desPostions[pos];
if(desPos.desc.type === -1) {
pos = pos + desPos.length;
continue;
}
if(desPos.desc.needAdjustInsertPos()) {
curInsertTxt = txt.substr(0, (desPos.length - desPos.pos));
curInsertTxt = desPos.text.slice(0, desPos.pos) + curInsertTxt + desPos.text.slice(desPos.pos + curInsertTxt.length, desPos.length);
if(tryToExpandAtRight) {
curInsertTxt = desPos.text + curInsertTxt;
}
if(tryToExpandAtLeft) {
curInsertTxt = curInsertTxt + desPos.text;
}
prevTextLength = desPos.desc.getText().length;
altInsertText = '';
try {
if(strInput.length === 1) {
if(!desPos.pos) {
altInsertText = strInput;
} else if(desPos.pos > 0) {
altInsertText = curInsertTxt.substring(0, desPos.pos + 1);
}
}
} catch (e) {
}
if(prevTextLength === 1 && curInsertTxt.length > 1 && strInput.length === 1) {
if(desPos.desc.type === 31 || desPos.desc.type === 25) {
this._disableSmartInputMode = true;
}
}
resultObj = {
val: strInput,
pos: desPos.pos,
offset: 0,
isreset: false
};
result = desPos.desc.setText(curInsertTxt, ((strInput.length === 1) ? false : true), resultObj);
this._disableSmartInputMode = false;
if(!result && typeof (altInsertText) !== 'undefined' && altInsertText.length > 0 && (desPos.desc.type === 26 || desPos.desc.type === 27 || desPos.desc.type === 100 || desPos.desc.type === 101 || desPos.desc.type === 250 || desPos.desc.type === 251)) {
result = desPos.desc.setText(altInsertText, ((strInput.length === 1) ? false : true), resultObj);
}
if(result) {
rh.hint = rh.success;
rh.testPosition = pos + resultObj.offset;
if(strInput.length === 1) {
newTextLength = desPos.desc.getText().length;
posAdjustValue = desPos.pos;
if(desPos.pos > (newTextLength - 1)) {
posAdjustValue = newTextLength;
}
diff = newTextLength - prevTextLength;
if(diff > 0 && desPos.pos === prevTextLength - 1) {
posAdjustValue = newTextLength - 1;
}
s = this.toString();
rh.testPosition = desPos.desc.startIndex + posAdjustValue + resultObj.offset;
}
txt = txt.slice(desPos.length - desPos.pos, txt.length);
} else {
rh.hint = rh.invalidInput;
if(rh.testPosition !== -1) {
rh.testPosition = position;
}
if(desPos.desc.type !== -1 && strInput.length === 1) {
return false;
}
}
pos = pos + desPos.length;
} else {
delimOrEndPos = this.getFirstDelimiterPos(txt, oldTxt);
if(delimOrEndPos < 0) {
delimOrEndPos = 0;
}
curInsertTxt = txt.substring(0, delimOrEndPos + 1);
resultObj = {
val: strInput,
pos: desPos.pos,
offset: 0,
isreset: false
};
result = desPos.desc.setText(curInsertTxt, ((strInput.length === 1) ? false : true), resultObj);
if(result) {
rh.hint = rh.success;
rh.testPosition = pos + resultObj.offset;
txt = txt.slice(delimOrEndPos + 1, txt.length);
} else {
rh.hint = rh.invalidInput;
if(rh.testPosition !== -1) {
rh.testPosition = position;
}
}
if(delimOrEndPos < 0) {
delimOrEndPos = 0;
}
delta = delimOrEndPos + 1;
pos = pos + delta;
}
}
return result;
};
wijDateTextProvider.prototype.removeAt = function (start, end, rh) {
try {
var desPos = this.desPostions[start], curInsertTxt, pos, resultObj, result, widget = this.inputWidget, element = widget.element, dateLength = element.val().length;
if(dateLength === end + 1 && start === 0) {
widget.isDeleteAll = true;
}
if(desPos.desc.needAdjustInsertPos()) {
curInsertTxt = '0';
pos = start;
desPos.text = desPos.desc.getText();
curInsertTxt = desPos.text.slice(0, desPos.pos) + curInsertTxt + desPos.text.slice(desPos.pos + curInsertTxt.length, desPos.length);
resultObj = {
val: curInsertTxt,
pos: desPos.pos,
offset: 0,
isreset: true,
isfullreset: false
};
if((end - start + 1) >= desPos.length) {
resultObj.isfullreset = true;
start = start + desPos.length;
pos = start;
}
result = desPos.desc.setText(curInsertTxt, false, resultObj);
if(result) {
rh.hint = rh.success;
rh.testPosition = pos;
} else {
rh.hint = rh.invalidInput;
if(rh.testPosition === -1) {
rh.testPosition = start;
}
}
}
if(start < end) {
this.removeAt(start + 1, end, rh);
}
return true;
} catch (e) {
return false;
}
};
wijDateTextProvider.prototype.incEnumPart = function () {
var desc = this.fields[this.inputWidget.options.activeField];
if(desc) {
desc.inc();
}
return true;
};
wijDateTextProvider.prototype.decEnumPart = function (pos) {
var desc = this.fields[this.inputWidget.options.activeField];
if(desc) {
desc.dec();
}
return true;
};
wijDateTextProvider.prototype.setValue = function (val) {
this.setDate(new Date(val instanceof Date ? val.getTime() : val));
return true;
};
wijDateTextProvider.prototype.getValue = function () {
return this.getDate();
};
wijDateTextProvider.prototype._isSmartInputMode = function () {
if(this._disableSmartInputMode) {
return false;
}
if(this.inputWidget) {
return this.inputWidget.options.smartInputMode;
}
return true;
};
wijDateTextProvider.prototype._getInt = function (str, i, minlength, maxlength) {
var x, token;
for(x = maxlength; x >= minlength; x--) {
token = str.substring(i, i + x);
if(token.length < minlength) {
return null;
}
if($.wij.charValidator.isDigit(token)) {
return token;
}
}
return null;
};
wijDateTextProvider.prototype._tryParseDate = function (val, pattern) {
var ci = this._getCulture().calendars, pattern2, sep, patterns, d;
pattern = pattern || ci.standard.patterns.d;
if(pattern) {
if(pattern.indexOf('MMM') === -1 && pattern.indexOf('MMMM') === -1) {
pattern = pattern.replace('MM', 'M');
}
pattern = pattern.replace('dd', 'd');
pattern = pattern.replace('tt', 'a');
}
pattern2 = pattern.replace('yyyy', 'yy');
sep = ci.standard["/"];
patterns = [
pattern,
pattern2,
pattern.replace(new RegExp(sep, 'g'), '-'),
pattern2.replace(new RegExp(sep, 'g'), '-'),
pattern.replace(new RegExp(sep, 'g'), '.'),
pattern2.replace(new RegExp(sep, 'g'), '.')
];
d = Globalize.parseDate(val, patterns, this._getCulture());
if(d) {
return d;
}
// if the val is datetime string,
// parse the string to datetime. added by dail 2012-6-25
d = new Date(val);
if(d.toString() !== "Invalid Date" && val && val !== "") {
return d;
}
return 0;
};
wijDateTextProvider.prototype._formatDate = function (date, format, culture) {
var _this = this;
if(!(date.valueOf())) {
return ' ';
}
var cf = this.inputWidget._getCulture().calendars.standard, sRes = format.replace(new RegExp('yyyy|MMMM|MMM|MM|M|mm|m|dddd|ddd|dd|d|hh|h|HH|H|ss|s|tt|t|a/p', 'gi'), function (match) {
var h;
switch(match) {
case 'yyyy':
return paddingZero(date.getFullYear(), 4);
case 'MMMM':
return culture.dateTimeFormat.monthNames[date.getMonth()];
case 'MMM':
return culture.dateTimeFormat.abbreviatedMonthNames[date.getMonth()];
case 'MM':
return _this.paddingZero((date.getMonth() + 1), 2);
case 'M':
return _this.paddingZero((date.getMonth() + 1), 1);
case 'mm':
return _this.paddingZero(date.getMinutes(), 2);
case 'm':
return _this.paddingZero(date.getMinutes(), 1);
case 'dddd':
return culture.dateTimeFormat.dayNames[date.getDay()];
case 'ddd':
return culture.dateTimeFormat.abbreviatedDayNames[date.getDay()];
case 'dd':
return _this.paddingZero(date.getDate(), 2);
case 'd':
return _this.paddingZero(date.getDate(), 1);
case 'hh':
h = date.getHours() % 12;
return _this.paddingZero(((h) ? h : 12), 2);
case 'h':
h = date.getHours() % 12;
return _this.paddingZero(((h) ? h : 12), 1);
case 'HH':
return _this.paddingZero(date.getHours(), 2);
case 'H':
return _this.paddingZero(date.getHours(), 1);
case 'ss':
return _this.paddingZero(date.getSeconds(), 2);
case 's':
return _this.paddingZero(date.getSeconds(), 1);
case 'tt':
return (date.getHours() < 12) ? cf.AM[0] : cf.PM[0];
case 't':
return (date.getHours() < 12) ? ((cf.AM[0].length > 0) ? cf.AM[0].charAt(0) : '') : ((cf.PM[0].length > 0) ? cf.PM[0].charAt(0) : '');
case 'a/p':
return (date.getHours() < 12) ? 'a' : 'p';
}
return 'N';
});
return sRes;
};
return wijDateTextProvider;
})(input.wijTextProvider);
input.wijDateTextProvider = wijDateTextProvider;
;
(function (DescriptorType) {
DescriptorType._map = [];
DescriptorType.liternal = -1;
DescriptorType.OneDigitYear = 1;
DescriptorType.TwoDigitYear = 2;
DescriptorType.FourDigitYear = 10;
DescriptorType.TwoDigitMonth = 20;
DescriptorType.Month = 25;
DescriptorType.AbbreviatedMonthNames = 26;
DescriptorType.MonthNames = 27;
DescriptorType.TwoDigityDayOfMonth = 30;
DescriptorType.DayOfMonth = 31;
DescriptorType.AbbreviatedDayNames = 100;
DescriptorType.DayNames = 101;
DescriptorType.h = 45;
DescriptorType.hh = 46;
DescriptorType.H = 47;
DescriptorType.HH = 48;
DescriptorType.ShortAmPm = 250;
DescriptorType.AmPm = 251;
DescriptorType.mm = 50;
DescriptorType.m = 51;
DescriptorType.ss = 60;
DescriptorType.s = 61;
})(input.DescriptorType || (input.DescriptorType = {}));
var DescriptorType = input.DescriptorType;
////////////////////////////////////////////////////////////////////////////////
// _iDateDescriptor
var _iDateDescriptor = (function () {
function _iDateDescriptor(textProvider, id) {
this.id = id;
this.startIndex = 0;
this.name = null;
this.type = DescriptorType.liternal;
this.maxLen = 2;
this._txtProvider = textProvider;
this.startIndex = 0;
}
_iDateDescriptor.prototype.getText = function () {
return null;
};
_iDateDescriptor.prototype.setText = function (value, allowchangeotherpart, result) {
return false;
};
_iDateDescriptor.prototype.inc = function () {
};
_iDateDescriptor.prototype.dec = function () {
};
_iDateDescriptor.prototype.needAdjustInsertPos = function () {
return true;
};
_iDateDescriptor.prototype.reachMaxLen = function () {
var t = this.getText();
do {
if(t.charAt(0) === '0') {
t = t.slice(1);
} else {
break;
}
}while(t.length > 0);
return t.length >= this.maxLen;
};
return _iDateDescriptor;
})();
input._iDateDescriptor = _iDateDescriptor;
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor
var _dateDescriptor = (function (_super) {
__extends(_dateDescriptor, _super);
function _dateDescriptor(owner, id) {
_super.call(this, owner, id);
this.liternal = '';
this.maxLen = 100;
}
_dateDescriptor.prototype.getText = function () {
return this.liternal;
};
return _dateDescriptor;
})(_iDateDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor20
var MonthDateDescriptor = (function (_super) {
__extends(MonthDateDescriptor, _super);
function MonthDateDescriptor(owner, id) {
_super.call(this, owner, id);
}
MonthDateDescriptor.prototype.inc = function () {
this._txtProvider.setMonth(this._txtProvider.getMonth() + 1, true);
};
MonthDateDescriptor.prototype.dec = function () {
this._txtProvider.setMonth(this._txtProvider.getMonth() - 1, true);
};
MonthDateDescriptor.prototype.setText = function (value, allowchangeotherpart, result) {
return this._txtProvider.setMonth(value, allowchangeotherpart, result);
};
return MonthDateDescriptor;
})(_iDateDescriptor);
var _dateDescriptor20 = (function (_super) {
__extends(_dateDescriptor20, _super);
function _dateDescriptor20(owner, id) {
_super.call(this, owner, id);
this.name = 'Two-digit month';
this.type = DescriptorType.TwoDigitMonth;
}
_dateDescriptor20.prototype.getText = function () {
var m = '' + this._txtProvider.getMonth() + '';
return m.length === 1 ? ('0' + m) : m;
};
return _dateDescriptor20;
})(MonthDateDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor25
var _dateDescriptor25 = (function (_super) {
__extends(_dateDescriptor25, _super);
function _dateDescriptor25(owner, id) {
_super.call(this, owner, id);
this.name = 'month';
this.type = DescriptorType.Month;
}
_dateDescriptor25.prototype.getText = function () {
var m = '' + this._txtProvider.getMonth() + '';
return m;
};
return _dateDescriptor25;
})(MonthDateDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor26
var _dateDescriptor26 = (function (_super) {
__extends(_dateDescriptor26, _super);
function _dateDescriptor26(owner, id) {
_super.call(this, owner, id);
this.name = 'AbbreviatedMonthNames';
this.type = DescriptorType.AbbreviatedMonthNames;
this.maxLen = DescriptorType.AbbreviatedMonthNames;
}
_dateDescriptor26.prototype.getText = function () {
var m = this._txtProvider.getMonth(), culture = this._txtProvider._getCulture();
return culture.calendars.standard.months.namesAbbr[m - 1];
};
_dateDescriptor26.prototype.setText = function (value, allowchangeotherpart, result) {
var m = -1, cf = this._txtProvider.inputWidget._getCulture().calendars.standard;
m = this._txtProvider.findAlikeArrayItemIndex(cf.months.namesAbbr, value);
if(m === -1) {
return false;
}
return this._txtProvider.setMonth(m + 1, allowchangeotherpart, result);
};
return _dateDescriptor26;
})(MonthDateDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor27
var _dateDescriptor27 = (function (_super) {
__extends(_dateDescriptor27, _super);
function _dateDescriptor27(owner, id) {
_super.call(this, owner, id);
this.name = 'MonthNames';
this.type = DescriptorType.MonthNames;
this.maxLen = 100;
}
_dateDescriptor27.prototype.getText = function () {
var m = this._txtProvider.getMonth(), culture = this._txtProvider._getCulture();
return culture.calendars.standard.months.names[m - 1];
};
_dateDescriptor27.prototype.setText = function (value, allowchangeotherpart, result) {
var m = -1, culture;
if(result && result.isfullreset) {
m = 1;
} else {
culture = this._txtProvider._getCulture();
m = this._txtProvider.findAlikeArrayItemIndex(culture.calendars.standard.months.names, value);
if(m === -1) {
return false;
}
}
return this._txtProvider.setMonth(m + 1, allowchangeotherpart, result);
};
return _dateDescriptor27;
})(MonthDateDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor30
var DayOfMonthDescriptor = (function (_super) {
__extends(DayOfMonthDescriptor, _super);
function DayOfMonthDescriptor(owner, id) {
_super.call(this, owner, id);
}
DayOfMonthDescriptor.prototype.inc = function () {
this._txtProvider.setDayOfMonth(this._txtProvider.getDayOfMonth() + 1, true);
};
DayOfMonthDescriptor.prototype.dec = function () {
this._txtProvider.setDayOfMonth(this._txtProvider.getDayOfMonth() - 1, true);
};
DayOfMonthDescriptor.prototype.setText = function (value, allowchangeotherpart, result) {
return this._txtProvider.setDayOfMonth(value, allowchangeotherpart, result);
};
return DayOfMonthDescriptor;
})(_iDateDescriptor);
var _dateDescriptor30 = (function (_super) {
__extends(_dateDescriptor30, _super);
function _dateDescriptor30(owner, id) {
_super.call(this, owner, id);
this.name = 'Two-digit day of month';
this.type = DescriptorType.TwoDigityDayOfMonth;
}
_dateDescriptor30.prototype.getText = function () {
return paddingZero(this._txtProvider.getDayOfMonth());
};
return _dateDescriptor30;
})(DayOfMonthDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor31
var _dateDescriptor31 = (function (_super) {
__extends(_dateDescriptor31, _super);
function _dateDescriptor31(owner, id) {
_super.call(this, owner, id);
this.name = 'Day of month';
this.type = DescriptorType.DayOfMonth;
}
_dateDescriptor31.prototype.getText = function () {
var dom = this._txtProvider.getDayOfMonth();
return '' + dom + '';
};
return _dateDescriptor31;
})(DayOfMonthDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor100
var _dateDescriptor100 = (function (_super) {
__extends(_dateDescriptor100, _super);
function _dateDescriptor100(owner, id) {
_super.call(this, owner, id);
this.name = 'AbbreviatedDayNames';
this.type = DescriptorType.AbbreviatedDayNames;
this.maxLen = 100;
}
_dateDescriptor100.prototype.getText = function () {
var dw = this._txtProvider.getDayOfWeek(), culture = this._txtProvider._getCulture();
return culture.calendars.standard.days.namesShort[dw - 1];
};
_dateDescriptor100.prototype.setText = function (value, allowchangeotherpart, result) {
var dw = -1, culture = this._txtProvider._getCulture();
dw = this._txtProvider.findAlikeArrayItemIndex(culture.calendars.standard.days.namesShort, value);
if(dw === -1) {
return false;
}
return this._txtProvider.setDayOfWeek(dw + 1);
};
_dateDescriptor100.prototype.needAdjustInsertPos = function () {
return false;
};
return _dateDescriptor100;
})(DayOfMonthDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor101
var _dateDescriptor101 = (function (_super) {
__extends(_dateDescriptor101, _super);
function _dateDescriptor101(owner, id) {
_super.call(this, owner, id);
this.name = 'DayNames';
this.type = DescriptorType.DayNames;
this.maxLen = 100;
}
_dateDescriptor101.prototype.getText = function () {
var dw = this._txtProvider.getDayOfWeek(), culture = this._txtProvider._getCulture();
return culture.calendars.standard.days.names[dw - 1];
};
_dateDescriptor101.prototype.setText = function (value, allowchangeotherpart, result) {
var dw = -1, culture = this._txtProvider._getCulture();
dw = this._txtProvider.findAlikeArrayItemIndex(culture.calendars.standard.days.names, value);
if(dw === -1) {
return false;
}
return this._txtProvider.setDayOfWeek(dw + 1);
};
_dateDescriptor101.prototype.needAdjustInsertPos = function () {
return false;
};
return _dateDescriptor101;
})(DayOfMonthDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor10
var YearDateDescriptor = (function (_super) {
__extends(YearDateDescriptor, _super);
function YearDateDescriptor(owner, id) {
_super.call(this, owner, id);
}
YearDateDescriptor.prototype.inc = function () {
this._txtProvider.setYear(this._txtProvider.getYear() + 1, null, true);
};
YearDateDescriptor.prototype.dec = function () {
this._txtProvider.setYear(this._txtProvider.getYear() - 1, null, true);
};
return YearDateDescriptor;
})(_iDateDescriptor);
var _dateDescriptor10 = (function (_super) {
__extends(_dateDescriptor10, _super);
function _dateDescriptor10(owner, id) {
_super.call(this, owner, id);
this.name = 'Four-digit year';
this.type = DescriptorType.FourDigitYear;
this.maxLen = 4;
}
_dateDescriptor10.prototype.getText = function () {
return paddingZero(this._txtProvider.getYear(), 4);
};
_dateDescriptor10.prototype.setText = function (value, allowchangeotherpart, result) {
if(this._txtProvider._isSmartInputMode() && result) {
var startYear = 1900 + 100, startYearStr, endYear, curDate, thisYear, inputNum, century, addYear, s;
if(this._txtProvider.inputWidget.options.startYear) {
startYear = this._txtProvider.inputWidget.options.startYear;
}
endYear = startYear + 100 - 1;
startYearStr = this._txtProvider.paddingZero(startYear, 4);
endYear = this._txtProvider.paddingZero(endYear, 4);
if(result.pos === 0 || result.pos === 1) {
curDate = new Date();
thisYear = this._txtProvider.paddingZero(this._txtProvider.getYear(), 4);
if(thisYear.charAt(0) === '0' && thisYear.charAt(1) === '0' && result.pos <= 1) {
inputNum = result.val;
century = '00';
if(inputNum >= 5) {
century = startYearStr.slice(0, 2);
} else {
century = endYear.slice(0, 2);
}
addYear = result.val + thisYear.slice(3, 4);
s = century + addYear;
result.offset = 2 - result.pos;
this._txtProvider.setYear(s, result);
return true;
}
}
}
return this._txtProvider.setYear(value, result);
};
return _dateDescriptor10;
})(YearDateDescriptor);
var TwoDigitYearDescriptor = (function (_super) {
__extends(TwoDigitYearDescriptor, _super);
function TwoDigitYearDescriptor(owner, id) {
_super.call(this, owner, id);
}
TwoDigitYearDescriptor.prototype.setText = function (value, allowchangeotherpart, result) {
value = paddingZero(value);
var y = paddingZero(this._txtProvider.getYear(), 4), m, dom, h, min, s;
if(value === '00') {
m = this._txtProvider.getMonth();
dom = this._txtProvider.getDayOfMonth();
h = this._txtProvider.getHours();
min = this._txtProvider.getMinutes();
s = this._txtProvider.getSeconds();
if(m === 1 && dom === 1 && !h && !min && !s) {
y = '0001';
value = '01';
}
}
if(y.length >= 2) {
y = y.substr(0, 2) + value.substr(0, 2);
}
return this._txtProvider.setYear(y, result);
};
return TwoDigitYearDescriptor;
})(YearDateDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor1
var _dateDescriptor1 = (function (_super) {
__extends(_dateDescriptor1, _super);
function _dateDescriptor1(owner, id) {
_super.call(this, owner, id);
this.name = 'One-digit year';
this.type = DescriptorType.OneDigitYear;
}
_dateDescriptor1.prototype.getText = function () {
var y = paddingZero(this._txtProvider.getYear());
if(y[0] === '0') {
y = y[1];
}
return y;
};
return _dateDescriptor1;
})(TwoDigitYearDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor2
var _dateDescriptor2 = (function (_super) {
__extends(_dateDescriptor2, _super);
function _dateDescriptor2(owner, id) {
_super.call(this, owner, id);
this.name = 'Two-digit year';
this.type = DescriptorType.TwoDigitYear;
}
_dateDescriptor2.prototype.getText = function () {
return paddingZero(this._txtProvider.getYear(), 2);
};
return _dateDescriptor2;
})(TwoDigitYearDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor45
var HourDescriptor = (function (_super) {
__extends(HourDescriptor, _super);
function HourDescriptor(owner, id) {
_super.call(this, owner, id);
}
HourDescriptor.prototype.inc = function () {
this._txtProvider.setHours(this._txtProvider.getHours() + 1, true);
};
HourDescriptor.prototype.dec = function () {
this._txtProvider.setHours(this._txtProvider.getHours() - 1, true);
};
return HourDescriptor;
})(_iDateDescriptor);
var TwelveHourDescriptor = (function (_super) {
__extends(TwelveHourDescriptor, _super);
function TwelveHourDescriptor(owner, id) {
_super.call(this, owner, id);
}
TwelveHourDescriptor.prototype.setText = function (value, allowchangeotherpart, result) {
var h = this._txtProvider.getHours();
if(h > 12) {
value = ((value * 1) + 12);
}
return this._txtProvider.setHours(value, allowchangeotherpart);
};
return TwelveHourDescriptor;
})(HourDescriptor);
var _dateDescriptor45 = (function (_super) {
__extends(_dateDescriptor45, _super);
function _dateDescriptor45(owner, id) {
_super.call(this, owner, id);
this.name = 'h';
this.type = DescriptorType.h;
}
_dateDescriptor45.prototype.getText = function () {
var h = this._txtProvider.getHours();
if(h > 12) {
h = h - 12;
} else if(h === 0) {
h = 12;
}
return '' + h + '';
};
return _dateDescriptor45;
})(TwelveHourDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor46
var _dateDescriptor46 = (function (_super) {
__extends(_dateDescriptor46, _super);
function _dateDescriptor46(owner, id) {
_super.call(this, owner, id);
this.name = 'hh';
this.type = DescriptorType.hh;
}
_dateDescriptor46.prototype.getText = function () {
var h = this._txtProvider.getHours();
if(h > 12) {
h -= 12;
} else if(h === 0) {
return '12';
}
return paddingZero(h);
};
return _dateDescriptor46;
})(TwelveHourDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor47
var TwentyFourHourDescriptor = (function (_super) {
__extends(TwentyFourHourDescriptor, _super);
function TwentyFourHourDescriptor(owner, id) {
_super.call(this, owner, id);
}
TwentyFourHourDescriptor.prototype.setText = function (value, allowchangeotherpart, result) {
return this._txtProvider.setHours(value, allowchangeotherpart);
};
return TwentyFourHourDescriptor;
})(HourDescriptor);
var _dateDescriptor47 = (function (_super) {
__extends(_dateDescriptor47, _super);
function _dateDescriptor47(owner, id) {
_super.call(this, owner, id);
this.name = 'H';
this.type = DescriptorType.H;
}
_dateDescriptor47.prototype.getText = function () {
var h = this._txtProvider.getHours();
return '' + h + '';
};
return _dateDescriptor47;
})(TwentyFourHourDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor48
var _dateDescriptor48 = (function (_super) {
__extends(_dateDescriptor48, _super);
function _dateDescriptor48(owner, id) {
_super.call(this, owner, id);
this.name = 'HH';
this.type = DescriptorType.HH;
}
_dateDescriptor48.prototype.getText = function () {
return paddingZero(this._txtProvider.getHours());
};
return _dateDescriptor48;
})(TwentyFourHourDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor250
var AmPmDescriptor = (function (_super) {
__extends(AmPmDescriptor, _super);
function AmPmDescriptor(owner, id) {
_super.call(this, owner, id);
}
AmPmDescriptor.prototype.inc = function () {
var h = (this._txtProvider.getHours() + 12) % 24;
this._txtProvider.setHours(h, true);
};
AmPmDescriptor.prototype.dec = function () {
var h = (this._txtProvider.getHours() + 12) % 24;
this._txtProvider.setHours(h, true);
};
AmPmDescriptor.prototype.setText = function (value, allowchangeotherpart, result) {
var h;
if(value.toLowerCase().indexOf('a') >= 0) {
h = this._txtProvider.getHours() % 12;
this._txtProvider.setHours(h, true);
} else if(value.toLowerCase().indexOf('p') >= 0) {
// TODO: won't work with Japeneese symbols
h = this._txtProvider.getHours() % 12 + 12;
this._txtProvider.setHours(h, true);
}
return true;
};
return AmPmDescriptor;
})(_iDateDescriptor);
var _dateDescriptor250 = (function (_super) {
__extends(_dateDescriptor250, _super);
function _dateDescriptor250(owner, id) {
_super.call(this, owner, id);
this.name = 't';
this.type = DescriptorType.ShortAmPm;
}
_dateDescriptor250.prototype.getText = function () {
var hours = this._txtProvider.getHours(), culture = this._txtProvider._getCulture(), designator = culture.calendars.standard[hours < 12 ? "AM" : "PM"][0];
return designator.charAt(0) || " ";
};
return _dateDescriptor250;
})(AmPmDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor251
var _dateDescriptor251 = (function (_super) {
__extends(_dateDescriptor251, _super);
function _dateDescriptor251(owner, id) {
_super.call(this, owner, id);
this.name = 'tt';
this.type = DescriptorType.AmPm;
}
_dateDescriptor251.prototype.getText = function () {
var h = this._txtProvider.getHours(), ds = '', culture = this._txtProvider._getCulture();
if(h < 12) {
ds = culture.calendars.standard.AM[0];
} else {
ds = culture.calendars.standard.PM[0];
}
if(ds.length <= 0) {
ds = ' ';
}
return ds;
};
return _dateDescriptor251;
})(AmPmDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor50
var MinuteDescriptor = (function (_super) {
__extends(MinuteDescriptor, _super);
function MinuteDescriptor(owner, id) {
_super.call(this, owner, id);
this.delta = 1;
}
MinuteDescriptor.prototype.inc = function () {
this._txtProvider.setMinutes(this._txtProvider.getMinutes() + this.delta, true);
};
MinuteDescriptor.prototype.dec = function () {
this._txtProvider.setMinutes(this._txtProvider.getMinutes() - this.delta, true);
};
MinuteDescriptor.prototype.setText = function (value, allowchangeotherpart, result) {
if(result && result.isfullreset) {
value = '0';
}
return this._txtProvider.setMinutes(value, allowchangeotherpart);
};
return MinuteDescriptor;
})(_iDateDescriptor);
var _dateDescriptor50 = (function (_super) {
__extends(_dateDescriptor50, _super);
function _dateDescriptor50(owner, id) {
_super.call(this, owner, id);
this.name = 'mm';
this.type = DescriptorType.mm;
}
_dateDescriptor50.prototype.getText = function () {
return paddingZero(this._txtProvider.getMinutes());
};
return _dateDescriptor50;
})(MinuteDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor51
var _dateDescriptor51 = (function (_super) {
__extends(_dateDescriptor51, _super);
function _dateDescriptor51(owner, id) {
_super.call(this, owner, id);
this.name = 'm';
this.type = DescriptorType.m;
this.delta = 12;
}
_dateDescriptor51.prototype.getText = function () {
return this._txtProvider.getMinutes().toString();
};
return _dateDescriptor51;
})(MinuteDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor60
var SecondDescriptor = (function (_super) {
__extends(SecondDescriptor, _super);
function SecondDescriptor(owner, id) {
_super.call(this, owner, id);
}
SecondDescriptor.prototype.inc = function () {
this._txtProvider.setSeconds(this._txtProvider.getSeconds() + 12, true);
};
SecondDescriptor.prototype.dec = function () {
this._txtProvider.setSeconds(this._txtProvider.getSeconds() - 12, true);
};
SecondDescriptor.prototype.setText = function (value, allowchangeotherpart, result) {
if(result && result.isfullreset) {
value = '0';
}
return this._txtProvider.setSeconds(value, allowchangeotherpart);
};
return SecondDescriptor;
})(_iDateDescriptor);
var _dateDescriptor60 = (function (_super) {
__extends(_dateDescriptor60, _super);
function _dateDescriptor60(owner, id) {
_super.call(this, owner, id);
this.name = 'ss';
this.type = DescriptorType.ss;
}
_dateDescriptor60.prototype.getText = function () {
return paddingZero(this._txtProvider.getSeconds());
};
return _dateDescriptor60;
})(SecondDescriptor);
////////////////////////////////////////////////////////////////////////////////
// _dateDescriptor61
var _dateDescriptor61 = (function (_super) {
__extends(_dateDescriptor61, _super);
function _dateDescriptor61(owner, id) {
_super.call(this, owner, id);
this.name = 's';
this.type = DescriptorType.s;
}
_dateDescriptor61.prototype.getText = function () {
return this._txtProvider.getSeconds().toString();
};
return _dateDescriptor61;
})(SecondDescriptor);
})(wijmo.input || (wijmo.input = {}));
var input = wijmo.input;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="jquery.wijmo.wijinputcore.ts"/>
/*globals wijinputcore wijMaskedTextProvider wijCharDescriptor wijInputResult jQuery*/
/*
* Depends:
* jquery-1.4.2.js
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.position.js
* jquery.effects.core.js
* jquery.effects.blind.js
* globalize.js
* jquery.plugin.wijtextselection.js
* jquery.wijmo.wijpopup.js
* jquery.wijmo.wijinputcore.js
*
*/
(function (input) {
"use strict";
var $ = jQuery;
(function (wijchartype) {
wijchartype._map = [];
wijchartype.editOptional = 1;
wijchartype.editRequired = 2;
wijchartype.separator = 4;
wijchartype.literal = 8;
})(input.wijchartype || (input.wijchartype = {}));
var wijchartype = input.wijchartype;
/** @widget */
var wijinputmask = (function (_super) {
__extends(wijinputmask, _super);
function wijinputmask() {
_super.apply(this, arguments);
}
wijinputmask.prototype._createTextProvider = function () {
this._textProvider = new wijMaskedTextProvider(this, this.options.mask, false);
};
wijinputmask.prototype._checkMaskAndPassword = function () {
var noMask = !this.options.mask || this.options.mask.length < 0;
if(noMask && this._isPassword()) {
throw 'Option "passwordChar" requires a mask';
}
};
wijinputmask.prototype._updateIsPassword = function () {
var isPassword = this.options.passwordChar.length > 0 && this.element.attr('type') !== 'password';
this.element.data('isPassword', isPassword);
this._checkMaskAndPassword();
};
wijinputmask.prototype._beginUpdate = function () {
this.element.addClass(this.options.wijCSS.wijinputmask);
this._updateIsPassword();
this.element.data('defaultText', this.options.text);
};
wijinputmask.prototype._setOption = function (key, value) {
_super.prototype._setOption.call(this, key, value);
switch(key) {
case 'text':
this.setText(value);
break;
case 'mask':
case 'culture':
if(typeof (value) === 'undefined' || value.length <= 0) {
return;
}
this._checkMaskAndPassword();
var text = this.getText();
if(key === "mask") {
this._textProvider.mask = value;
this._textProvider.initialMask = value;
}
this._textProvider.initialize();
this._textProvider.set(text);
this._updateText();
break;
case 'promptChar':
if(this._textProvider) {
this._textProvider.updatePromptChar();
this._updateText();
}
break;
case 'hidePromptOnLeave':
case 'resetOnPrompt':
this._updateText();
break;
case 'passwordChar':
this._updateIsPassword();
this._updateText();
break;
}
};
wijinputmask.prototype._resetData = function () {
var txt = this.element.data('defaultText');
if(txt === undefined || txt === null) {
txt = this.element.data('elementValue');
}
if(txt === undefined || txt === null) {
txt = "";
}
this.setText(txt);
};
wijinputmask.prototype._isPassword = function () {
return !!this.element.data('isPassword');
};
wijinputmask.prototype._getTextWithPrompts = function () {
return !this._isInitialized() ? this.element.val() : this._textProvider.toString(true, true, false);
};
wijinputmask.prototype._getTextWithLiterals = function () {
return !this._isInitialized() ? this.element.val() : this._textProvider.toString(true, false, true);
};
wijinputmask.prototype._getTextWithPromptAndLiterals = function () {
return !this._isInitialized() ? this.element.val() : this._textProvider.toString(true, true, true);
};
wijinputmask.prototype._getTextWithPromptAndLiteralsAndPassword = function () {
return !this._isInitialized() ? this.element.val() : this._textProvider.toString(false, true, true);
};
wijinputmask.prototype._onChange = function () {
if(!this.element) {
return;
}
var val = this.element.val(), txt = this.getText();
if(this.getText() !== val && this._getTextWithPrompts() !== val && this._getTextWithPromptAndLiterals() !== val && this._getTextWithPromptAndLiteralsAndPassword() !== val) {
this.setText(val);
}
};
wijinputmask.prototype._afterFocused = // _onPaste(e) {
// if (this._textProvider && this._textProvider.noMask) { return; };
// wijinputcore._onPaste.apply(self, arguments);
// }
function () {
if(this._isNullText() || !!this.options.hidePromptOnLeave) {
this._doFocus();
}
};
return wijinputmask;
})(input.wijinputcore);
input.wijinputmask = wijinputmask;
var wijinputmask_options = (function () {
function wijinputmask_options() {
this.wijCSS = {
wijinputmask: input.wijinputcore.prototype.options.wijCSS.wijinput + "-mask"
};
/** Determines the default text. */
this.text = null;
/** Determines the input mask to use at run time.
* Mask must be a string composed of one or more of the masking elements.
*/
this.mask = "";
/** Determines the character that appears when the widget has focus but no input has been entered. */
this.promptChar = '_';
/** Indicates whether the prompt characters in the input mask
* are hidden when the input loses focus.
*/
this.hidePromptOnLeave = false;
/** Determines how an input character that matches
* the prompt character should be handled.
*/
this.resetOnPrompt = true;
/** Indicates whether promptChar can be entered as valid data by the user. */
this.allowPromptAsInput = false;
/** Determines the character to be substituted for
* the actual input characters.
*/
this.passwordChar = '';
/** Determines how a space input character should be handled. */
this.resetOnSpace = true;
/** Indicates whether the user is allowed to re-enter literal values. */
this.skipLiterals = true;
}
return wijinputmask_options;
})();
wijinputmask.prototype.options = $.extend(true, {
}, input.wijinputcore.prototype.options, new wijinputmask_options());
$.wijmo.registerWidget("wijinputmask", wijinputmask.prototype);
var wijMaskedTextProvider = (function (_super) {
__extends(wijMaskedTextProvider, _super);
function wijMaskedTextProvider(inputWidget, mask, asciiOnly) {
_super.call(this);
this.inputWidget = inputWidget;
this.mask = mask;
this.asciiOnly = asciiOnly;
this.testString = '';
this.assignedCharCount = 0;
this.requiredCharCount = 0;
this.noMask = false;
this.descriptors = [];
this.initialize();
}
wijMaskedTextProvider.prototype.initialize = function () {
this.noMask = (!this.mask || this.mask.length <= 0);
if(this.noMask) {
return;
}
this.testString = '';
this.assignedCharCount = 0;
this.requiredCharCount = 0;
this.descriptors = new Array(0);
var caseType = 'none', escape = false, index = 0, i, j, needDesc, charType = wijchartype.literal, text = '', ch, ch2, ch3, cd, culture = this.inputWidget._getCulture();
for(i = 0; i < this.mask.length; i++) {
needDesc = false;
ch = this.mask.charAt(i);
if(escape) {
escape = false;
needDesc = true;
}
if(!needDesc) {
ch3 = ch;
if(ch3 <= 'C') {
switch(ch3) {
case '#':
case '9':
case '?':
case 'C':
ch = this.getPromtChar();
charType = wijchartype.editOptional;
needDesc = true;
break;
case '$':
text = culture.numberFormat.currency.symbol;
charType = wijchartype.separator;
needDesc = true;
break;
case '%':
case '-':
case ';':
case '=':
case '@':
case 'B':
charType = wijchartype.literal;
needDesc = true;
break;
case '&':
case '0':
case 'A':
ch = this.getPromtChar();
charType = wijchartype.editRequired;
needDesc = true;
break;
case ',':
text = culture.numberFormat[','];
charType = wijchartype.separator;
needDesc = true;
break;
case '.':
text = culture.numberFormat['.'];
charType = wijchartype.separator;
needDesc = true;
break;
case '/':
text = culture.calendars.standard['/'];
charType = wijchartype.separator;
needDesc = true;
break;
case ':':
text = culture.calendars.standard[':'];
charType = wijchartype.separator;
needDesc = true;
break;
case '<':
caseType = 'lower';
continue;
case '>':
caseType = 'upper';
continue;
}
if(!needDesc) {
charType = wijchartype.literal;
needDesc = true;
}
}
if(!needDesc) {
if(ch3 <= '\\') {
switch(ch3) {
case 'L':
ch = this.getPromtChar();
charType = wijchartype.editRequired;
needDesc = true;
break;
case '\\':
escape = true;
charType = wijchartype.literal;
continue;
}
if(!needDesc) {
charType = wijchartype.literal;
needDesc = true;
}
}
if(!needDesc) {
if(ch3 === 'a') {
ch = this.getPromtChar();
charType = wijchartype.editOptional;
needDesc = true;
}
if(!needDesc) {
if(ch3 !== '|') {
charType = wijchartype.literal;
needDesc = true;
}
if(!needDesc) {
caseType = 'none';
continue;
}
}
}
}
}
if(needDesc) {
cd = new wijCharDescriptor(i, charType);
if(this.isEditDesc(cd)) {
cd.caseConversion = caseType;
}
if(charType !== wijchartype.separator) {
text = ch;
}
for(j = 0; j < text.length; j++) {
ch2 = text.charAt(j);
this.testString = this.testString + ch2;
this.descriptors[this.descriptors.length] = cd;
index++;
}
}
}
this.testString.Capacity = this.testString.length;
};
wijMaskedTextProvider.prototype.getAllowPromptAsInput = function () {
return !!this.inputWidget ? this.inputWidget.options.allowPromptAsInput : false;
};
wijMaskedTextProvider.prototype.getPasswordChar = function () {
return !!this.inputWidget ? this.inputWidget.options.passwordChar : '*';
};
wijMaskedTextProvider.prototype.isPassword = function () {
return !!this.inputWidget ? this.inputWidget._isPassword() : false;
};
wijMaskedTextProvider.prototype.getResetOnPrompt = function () {
return !!this.inputWidget ? this.inputWidget.options.resetOnPrompt : true;
};
wijMaskedTextProvider.prototype.getResetOnSpace = function () {
return !!this.inputWidget ? this.inputWidget.options.resetOnSpace : true;
};
wijMaskedTextProvider.prototype.getSkipLiterals = function () {
return !!this.inputWidget ? this.inputWidget.options.skipLiterals : true;
};
wijMaskedTextProvider.prototype.getHidePromptOnLeave = function () {
return !!this.inputWidget ? this.inputWidget.options.hidePromptOnLeave : false;
};
wijMaskedTextProvider.prototype._trueOR = function (n1, n2) {
return ((n1 >>> 1 | n2 >>> 1) * 2 + (n1 & 1 | n2 & 1));
};
wijMaskedTextProvider.prototype.setValue = function (val) {
return false;
};
wijMaskedTextProvider.prototype.getValue = function () {
return null;
};
wijMaskedTextProvider.prototype.getPromtChar = function () {
return !!this.inputWidget ? this.inputWidget.options.promptChar : '_';
};
wijMaskedTextProvider.prototype.updatePromptChar = function () {
if(this.noMask) {
return;
}
var i, cd;
for(i = 0; i < this.descriptors.length; i++) {
cd = this.descriptors[i];
if(cd.charType === wijchartype.editOptional || cd.charType === wijchartype.editRequired) {
if(!cd.isAssigned) {
this.testString = $.wij.charValidator.setChar(this.testString, this.getPromtChar(), i);
}
}
}
};
wijMaskedTextProvider.prototype.resetChar = function (pos) {
var cd = this.descriptors[pos];
if(this.isEditPos(pos) && cd.isAssigned) {
cd.isAssigned = false;
this.testString = $.wij.charValidator.setChar(this.testString, this.getPromtChar(), pos);
this.assignedCharCount--;
if(cd.charType === wijchartype.editRequired) {
this.requiredCharCount--;
}
}
};
wijMaskedTextProvider.prototype.getAdjustedPos = function (pos) {
if(this.noMask) {
if(pos >= this.testString.length) {
pos = this.testString.length - 1;
}
} else {
if(pos >= this.descriptors.length) {
pos = pos - 1;
}
}
return Math.max(0, pos);
};
wijMaskedTextProvider.prototype.incEnumPart = function (pos, rh, step) {
return !this.noMask;
};
wijMaskedTextProvider.prototype.decEnumPart = function (pos, rh, step) {
return !this.noMask;
};
wijMaskedTextProvider.prototype.findNonEditPositionInRange = function (start, end, direction) {
return this.findPositionInRange(start, end, direction, this._trueOR(wijchartype.literal, wijchartype.separator));
};
wijMaskedTextProvider.prototype.findPositionInRange = function (start, end, direction, charType) {
start = Math.max(0, start);
end = Math.min(end, this.testString.length - 1);
if(start <= end) {
while(start <= end) {
var pos = (direction) ? start++ : end--, cd = this.descriptors[pos];
if(((cd.charType & 4294967295) & (charType & 4294967295)) === cd.charType) {
return pos;
}
}
}
return -1;
};
wijMaskedTextProvider.prototype.findAssignedEditPositionInRange = function (start, end, direction) {
if(this.assignedCharCount === 0) {
return -1;
}
return this.findEditPositionInRange(start, end, direction, wijchartype.editRequired);
};
wijMaskedTextProvider.prototype.findEditPositionInRange = function (start, end, direction, assignedStatus) {
do {
var pos, cd;
pos = this.findPositionInRange(start, end, direction, this._trueOR(wijchartype.editRequired, wijchartype.editOptional));
if(pos === -1) {
break;
}
cd = this.descriptors[pos];
switch(assignedStatus) {
case wijchartype.editOptional:
if(!cd.isAssigned) {
return pos;
}
break;
case wijchartype.editRequired:
if(cd.isAssigned) {
return pos;
}
break;
default:
return pos;
}
if(direction) {
start++;
} else {
end--;
}
}while(start <= end);
return -1;
};
wijMaskedTextProvider.prototype.findAssignedEditPositionFrom = function (pos, direction) {
if(!this.assignedCharCount) {
return -1;
}
var start, end;
if(direction) {
start = pos;
end = this.testString.length - 1;
} else {
start = 0;
end = pos;
}
return this.findAssignedEditPositionInRange(start, end, direction);
};
wijMaskedTextProvider.prototype.findEditPositionFrom = function (pos, direction) {
var start, end;
if(direction) {
start = pos;
end = this.testString.length - 1;
} else {
start = 0;
end = pos;
}
return this.findEditPositionInRange(start, end, direction, 0);
};
wijMaskedTextProvider.prototype.setChar = function (strInput, pos, desc) {
pos = pos < 0 ? 0 : pos;
if(!desc) {
desc = this.descriptors[pos];
}
if(this.testEscapeChar(strInput, pos, desc)) {
this.resetChar(pos);
} else {
if($.wij.charValidator.isLetter(strInput)) {
if($.wij.charValidator.isUpper(strInput)) {
if(desc.caseConversion === 'lower') {
strInput = strInput.toLowerCase();
}
} else if(desc.caseConversion === 'upper') {
strInput = strInput.toUpperCase();
}
}
this.testString = $.wij.charValidator.setChar(this.testString, strInput, pos);
if(!desc.isAssigned) {
desc.isAssigned = true;
this.assignedCharCount++;
if(desc.charType === wijchartype.editRequired) {
this.requiredCharCount++;
}
}
}
};
wijMaskedTextProvider.prototype.internalInsertAt = function (strInput, pos, rh, testOnly) {
if(strInput.length === 0) {
rh.testPosition = pos;
rh.hint = rh.noEffect;
return true;
}
if(!this._testString(strInput, pos, rh)) {
return false;
}
var num1 = this.findEditPositionFrom(pos, true), flag1 = this.findAssignedEditPositionInRange(num1, rh.testPosition, true) !== -1, num2 = this.findAssignedEditPositionFrom(this.testString.length - 1, false), num3, hint1, repeat, cd, descriptor2;
if(flag1 && (rh.testPosition === (this.testString.length - 1))) {
rh.hint = rh.unavailableEditPosition;
rh.testPosition = this.testString.length;
return false;
}
num3 = this.findEditPositionFrom(rh.testPosition + 1, true);
if(flag1) {
hint1 = new input.wijInputResult();
hint1.hint = hint1.unknown;
repeat = true;
while(repeat) {
repeat = false;
if(num3 === -1) {
rh.hint = rh.unavailableEditPosition;
rh.testPosition = this.testString.length;
return false;
}
cd = this.descriptors[num1];
if(cd.isAssigned && !this.testChar(this.testString.charAt(num1), num3, hint1)) {
rh.hint = hint1.hint;
rh.testPosition = num3;
return false;
}
if(num1 !== num2) {
num1 = this.findEditPositionFrom(num1 + 1, true);
num3 = this.findEditPositionFrom(num3 + 1, true);
repeat = true;
continue;
}
}
if(hint1.hint > rh.hint) {
rh.hint = hint1.hint;
}
}
if(!testOnly) {
if(flag1) {
while(num1 >= pos) {
descriptor2 = this.descriptors[num1];
if(descriptor2.isAssigned) {
this.setChar(this.testString.charAt(num1), num3);
} else {
this.resetChar(num3);
}
num3 = this.findEditPositionFrom(num3 - 1, false);
num1 = this.findEditPositionFrom(num1 - 1, false);
}
}
this.setString(strInput, pos);
}
return true;
};
wijMaskedTextProvider.prototype.insertAt = function (strInput, pos, rh) {
if (typeof rh === "undefined") { rh = new input.wijInputResult(); }
if(strInput === undefined) {
throw 'InsertAt: input';
}
if(this.noMask) {
this.testString = this.testString.substring(0, pos) + strInput + this.testString.substring(pos, this.testString.length);
rh.testPosition = pos + strInput.length - 1;
return true;
}
if((pos >= 0) && (pos < this.testString.length)) {
return this.internalInsertAt(strInput, pos, rh, false);
}
rh.testPosition = pos;
rh.hint = rh.positionOutOfRange;
return false;
};
wijMaskedTextProvider.prototype.clear = function (rh) {
if(this.noMask) {
this.testString = '';
rh.hint = rh.success;
return;
}
if(!this.assignedCharCount) {
rh.hint = rh.noEffect;
} else {
rh.hint = rh.success;
for(var num1 = 0; num1 < this.testString.length; num1++) {
this.resetChar(num1);
}
}
};
wijMaskedTextProvider.prototype.isLiteral = function (desc) {
if(!desc) {
return false;
}
if(desc.charType !== wijchartype.literal) {
return (desc.charType === wijchartype.separator);
}
return true;
};
wijMaskedTextProvider.prototype.testEscapeChar = function (strInput, pos, desc) {
pos = pos < 0 ? 0 : pos;
if(!desc) {
desc = this.descriptors[pos];
}
if(this.isLiteral(desc)) {
if(this.getSkipLiterals()) {
return (strInput === this.testString.charAt(pos));
}
return false;
}
if((!this.getResetOnPrompt() || (strInput !== this.getPromtChar())) && (!this.getResetOnSpace() || (strInput !== ' '))) {
return false;
}
return true;
};
wijMaskedTextProvider.prototype.testChar = function (strInput, pos, rh) {
if(!$.wij.charValidator.isPrintableChar(strInput)) {
rh.hint = rh.invalidInput;
return false;
}
var cd = this.descriptors[pos];
if(!cd) {
return false;
}
if(this.isLiteral(cd)) {
if(this.getSkipLiterals() && (strInput === this.testString.charAt(pos))) {
rh.hint = rh.characterEscaped;
return true;
}
rh.hint = rh.nonEditPosition;
return false;
}
if(strInput === this.getPromtChar()) {
if(this.getResetOnPrompt()) {
if(this.isEditDesc(cd) && cd.isAssigned) {
rh.hint = rh.sideEffect;
} else {
rh.hint = rh.characterEscaped;
}
return true;
}
if(!this.getAllowPromptAsInput()) {
rh.hint = rh.promptCharNotAllowed;
return false;
}
}
if((strInput === ' ') && this.getResetOnSpace()) {
if(this.isEditDesc(cd) && cd.isAssigned) {
rh.hint = rh.sideEffect;
} else {
rh.hint = rh.characterEscaped;
}
return true;
}
switch(this.mask.charAt(cd.maskPosition)) {
case 'L':
if(!$.wij.charValidator.isLetter(strInput)) {
rh.hint = rh.letterExpected;
return false;
}
if(!$.wij.charValidator.isAsciiLetter(strInput) && this.asciiOnly) {
rh.hint = rh.asciiCharacterExpected;
return false;
}
break;
case 'a':
if(!$.wij.charValidator.isAlphanumeric(strInput) && (strInput !== ' ')) {
rh.hint = rh.alphanumericCharacterExpected;
return false;
}
if(!$.wij.charValidator.isAciiAlphanumeric(strInput) && this.asciiOnly) {
rh.hint = rh.asciiCharacterExpected;
return false;
}
break;
case '?':
if(!$.wij.charValidator.isLetter(strInput) && (strInput !== ' ')) {
rh.hint = rh.letterExpected;
return false;
}
if($.wij.charValidator.isAsciiLetter(strInput) || !this.asciiOnly) {
break;
}
rh.hint = rh.asciiCharacterExpected;
return false;
case 'A':
if(!$.wij.charValidator.isAlphanumeric(strInput)) {
rh.hint = rh.alphanumericCharacterExpected;
return false;
}
if($.wij.charValidator.isAciiAlphanumeric(strInput) || !this.asciiOnly) {
break;
}
rh.hint = rh.asciiCharacterExpected;
return false;
case 'C':
if((!$.wij.charValidator.isAscii(strInput) && this.asciiOnly) && (strInput !== ' ')) {
rh.hint = rh.asciiCharacterExpected;
return false;
}
break;
case '9':
if(!$.wij.charValidator.isDigit(strInput) && (strInput !== ' ')) {
rh.hint = rh.digitExpected;
return false;
}
break;
case '#':
if((!$.wij.charValidator.isDigit(strInput) && (strInput !== '-')) && ((strInput !== '+') && (strInput !== ' '))) {
rh.hint = rh.digitExpected;
return false;
}
break;
case '&':
if(!$.wij.charValidator.isAscii(strInput) && this.asciiOnly) {
rh.hint = rh.asciiCharacterExpected;
return false;
}
break;
case '0':
if(!$.wij.charValidator.isDigit(strInput)) {
rh.hint = rh.digitExpected;
return false;
}
break;
}
if((strInput === this.testString.charAt(pos)) && cd.isAssigned) {
rh.hint = rh.noEffect;
} else {
rh.hint = rh.success;
}
return true;
};
wijMaskedTextProvider.prototype._testString = function (strInput, pos, rh) {
rh.hint = rh.unknown;
rh.testPosition = pos;
if(strInput.length) {
var hint1 = new input.wijInputResult(), i, ch;
hint1.testPosition = rh.testPosition;
hint1.hint = rh.hint;
for(i = 0; i < strInput.length; i++) {
ch = strInput.charAt(i);
if(rh.testPosition > this.testString.length) {
rh.hint = rh.unavailableEditPosition;
return false;
}
if(!this.testEscapeChar(ch, rh.testPosition)) {
rh.testPosition = this.findEditPositionFrom(rh.testPosition, true);
if(rh.testPosition === -1) {
rh.testPosition = this.testString.length;
rh.hint = rh.unavailableEditPosition;
return false;
}
}
if(!this.testChar(ch, rh.testPosition, hint1)) {
rh.hint = hint1.hint;
return false;
}
if(hint1.hint > rh.hint) {
rh.hint = hint1.hint;
}
rh.testPosition += 1;
if(rh.testPosition === this.testString.length) {
break;
}
}
rh.testPosition -= 1;
}
return true;
};
wijMaskedTextProvider.prototype.set = function (strInput, rh) {
if (typeof rh === "undefined") { rh = new input.wijInputResult(); }
if(strInput === undefined) {
throw 'SetFromPos: input parameter is null or undefined.';
}
rh.hint = rh.unknown;
rh.testPosition = 0;
if(!strInput.length) {
this.clear(rh);
return true;
}
if(this.noMask) {
this.testString = strInput;
return true;
}
if(!this.testSetString(strInput, rh.testPosition, rh)) {
return false;
}
var num1 = this.findAssignedEditPositionFrom(rh.testPosition + 1, true);
if(num1 !== -1) {
this.resetString(num1, this.testString.length - 1);
}
return true;
};
wijMaskedTextProvider.prototype.resetString = function (start, end) {
if(this.noMask) {
this.testString = '';
return;
}
start = this.findAssignedEditPositionFrom(start, true);
if(start !== -1) {
end = this.findAssignedEditPositionFrom(end, false);
while(start <= end) {
start = this.findAssignedEditPositionFrom(start, true);
this.resetChar(start);
start++;
}
}
};
wijMaskedTextProvider.prototype.setString = function (strInput, pos) {
var i, ch;
for(i = 0; i < strInput.length; i++) {
ch = strInput.charAt(i);
if(!this.testEscapeChar(ch, pos)) {
pos = this.findEditPositionFrom(pos, true);
}
if(pos < 0 || pos >= this.testString.length) {
return;
}
this.setChar(ch, pos);
pos++;
}
};
wijMaskedTextProvider.prototype.testSetString = function (input, pos, rh) {
if(input.length > this.testString.length) {
input = input.substring(0, this.testString.length);
}
if(this._testString(input, pos, rh)) {
this.setString(input, pos);
return true;
}
return false;
};
wijMaskedTextProvider.prototype.toString = function (ignorePasswordChar, includePrompt, includeLiterals, start, len) {
var val = this.inputWidget.options.text || "", s, i, num1, result, builder1, num2, num5, ch, cd;
val = $.trim(val);
if(this.inputWidget.options.showNullText && !this.inputWidget.isFocused() && (val === "" || val === this.inputWidget.options.nullText)) {
return this.inputWidget.options.nullText;
}
ignorePasswordChar = (ignorePasswordChar === undefined) ? !this.isPassword() : ignorePasswordChar;
includePrompt = (includePrompt === undefined) ? (this.getHidePromptOnLeave() ? this.inputWidget.isFocused() : true) : includePrompt;
includeLiterals = (includeLiterals === undefined) ? true : includeLiterals;
if(this.noMask) {
if(!ignorePasswordChar) {
s = '';
for(i = 0; i < this.testString.length; i++) {
s += this.getPasswordChar();
}
return s;
}
return this.testString;
}
start = (start === undefined) ? 0 : start;
len = (len === undefined) ? this.testString.length : len;
if(len <= 0) {
return '';
}
if(start < 0) {
start = 0;
}
if(start >= this.testString.length) {
return '';
}
num1 = this.testString.length - start;
if(len > num1) {
len = num1;
}
if((!this.isPassword() || ignorePasswordChar) && (includePrompt && includeLiterals)) {
result = this.testString.substring(start, len - start);
return result;
}
builder1 = '';
num2 = (start + len) - 1;
for(num5 = start; num5 <= num2; num5++) {
ch = this.testString.charAt(num5);
cd = this.descriptors[num5];
switch(cd.charType) {
case wijchartype.editOptional:
case wijchartype.editRequired:
if(!cd.isAssigned) {
break;
}
if(!this.isPassword() || ignorePasswordChar) {
builder1 = builder1 + ch;
continue;
}
builder1 = builder1 + this.getPasswordChar();
continue;
case (wijchartype.editRequired | wijchartype.editOptional):
builder1 = builder1 + ch;
continue;
case wijchartype.separator:
case wijchartype.literal:
if(!includeLiterals) {
continue;
}
builder1 = builder1 + ch;
continue;
default:
builder1 = builder1 + ch;
continue;
}
if(includePrompt) {
builder1 = builder1 + ch;
continue;
}
builder1 = builder1 + ' ';
continue;
}
return builder1;
};
wijMaskedTextProvider.prototype.isEditDesc = function (desc) {
if(this.noMask) {
return true;
}
if(desc.charType !== wijchartype.editRequired) {
return (desc.charType === wijchartype.editOptional);
}
return true;
};
wijMaskedTextProvider.prototype.isEditPos = function (pos) {
if(this.noMask) {
return true;
}
if((pos < 0) || (pos >= this.testString.length)) {
return false;
}
var cd = this.descriptors[pos];
return this.isEditDesc(cd);
};
wijMaskedTextProvider.prototype.internalRemoveAt = function (start, end, rh, testOnly) {
if (typeof testOnly === "undefined") { testOnly = false; }
if(this.noMask) {
try {
this.testString = this.testString.substring(0, start) + this.testString.substring(end + 1, this.testString.length);
rh.testPosition = start;
} catch (e) {
}
return true;
}
var hint1 = new input.wijInputResult(), ch, ch2, i, flag1, num3, num4, repeat, cd, repeat2, descriptor2, num1 = this.findAssignedEditPositionFrom(this.testString.length - 1, false);
i = this.findEditPositionInRange(start, end, true, 0);
rh.hint = rh.noEffect;
if((i === -1) || (i > num1)) {
rh.testPosition = start;
return true;
}
rh.testPosition = start;
flag1 = end < num1;
if(this.findAssignedEditPositionInRange(start, end, true) !== -1) {
rh.hint = rh.success;
}
if(flag1) {
num3 = this.findEditPositionFrom(end + 1, true);
num4 = num3;
start = i;
repeat = true;
while(repeat) {
repeat = false;
ch = this.testString.charAt(num3);
cd = this.descriptors[num3];
if(((ch !== this.getPromtChar()) || cd.isAssigned) && !this.testChar(ch, i, hint1)) {
rh.hint = hint1.hint;
rh.testPosition = i;
return false;
}
if(num3 !== num1) {
num3 = this.findEditPositionFrom(num3 + 1, true);
i = this.findEditPositionFrom(i + 1, true);
repeat = true;
continue;
}
}
if(rh.sideEffect > rh.hint) {
rh.hint = rh.sideEffect;
}
if(testOnly) {
return true;
}
num3 = num4;
i = start;
repeat2 = true;
while(repeat2) {
repeat2 = false;
ch2 = this.testString.charAt(num3);
descriptor2 = this.descriptors[num3];
if((ch2 === this.getPromtChar()) && !descriptor2.isAssigned) {
this.resetChar(i);
} else {
this.setChar(ch2, i);
this.resetChar(num3);
}
if(num3 !== num1) {
num3 = this.findEditPositionFrom(num3 + 1, true);
i = this.findEditPositionFrom(i + 1, true);
repeat2 = true;
continue;
}
}
start = i + 1;
}
if(start <= end) {
this.resetString(start, end);
}
return true;
};
wijMaskedTextProvider.prototype.removeAt = function (start, end, rh) {
if (typeof end === "undefined") { end = start; }
if (typeof rh === "undefined") { rh = new input.wijInputResult(); }
if(end >= this.testString.length) {
rh.testPosition = end;
rh.hint = rh.positionOutOfRange;
return false;
}
if((start >= 0) && (start <= end)) {
var result = this.internalRemoveAt(start, end, rh, false);
return result;
}
rh.testPosition = start;
rh.hint = rh.positionOutOfRange;
return false;
};
return wijMaskedTextProvider;
})(input.wijTextProvider);
input.wijMaskedTextProvider = wijMaskedTextProvider;
////////////////////////////////////////////////////////////////////////////////
// wijCharDescriptor
var wijCharDescriptor = (function () {
function wijCharDescriptor(maskPos, charType) {
this.maskPos = maskPos;
this.charType = charType;
this.caseConversion = 'none';
this.isAssigned = false;
this.maskPosition = 0;
this.maskPosition = maskPos;
this.charType = charType;
}
return wijCharDescriptor;
})();
input.wijCharDescriptor = wijCharDescriptor;
})(wijmo.input || (wijmo.input = {}));
var input = wijmo.input;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="jquery.wijmo.wijinputcore.ts"/>
/*globals wijinputcore wijNumberTextProvider wijInputResult
wijNumberFormat window jQuery*/
/*
* Depends:
* jquery-1.4.2.js
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.position.js
* jquery.effects.core.js
* jquery.effects.blind.js
* globalize.js
* jquery.plugin.wijtextselection.js
* jquery.mousewheel.js
* jquery.wijmo.wijpopup.js
* jquery.wijmo.wijinputcore.js
*
*/
(function (input) {
"use strict";
var $ = jQuery;
/** @widget */
var wijinputnumber = (function (_super) {
__extends(wijinputnumber, _super);
function wijinputnumber() {
_super.apply(this, arguments);
}
wijinputnumber.prototype._createTextProvider = function () {
this._textProvider = new wijNumberTextProvider(this, this.options.type);
this._textProvider._nullvalue = this.element.val() === "" && this.options.value === null;
};
wijinputnumber.prototype._beginUpdate = function () {
var o = this.options;
this.element.addClass(o.wijCSS.wijinputnumber);
this.element.data({
defaultValue: o.value,
preValue: o.value
}).attr({
'aria-valuemin': o.minValue,
'aria-valuemax': o.maxValue,
'aria-valuenow': o.value || 0
});
};
wijinputnumber.prototype._setOption = function (key, value) {
_super.prototype._setOption.call(this, key, value);
switch(key) {
case 'minValue':
this.element.attr('aria-valuemin', value);
this._updateText();
break;
case 'maxValue':
this.element.attr('aria-valuemax', value);
this._updateText();
break;
case 'value':
this.setValue(value);
this._updateText();
break;
case 'showGroup':
case 'decimalPlaces':
case 'culture':
this._textProvider.updateStringFormat();
this._updateText();
break;
}
};
wijinputnumber.prototype._setData = function (val) {
this.setValue(val);
};
wijinputnumber.prototype._resetData = function () {
var val = this.element.data('defaultValue');
if(val === undefined || val === null) {
val = this.element.data('elementValue');
if(val === undefined || val === null && val === "") {
val = 0;
}
}
this.setValue(val);
};
wijinputnumber.prototype._validateData = function () {
if(!this._textProvider.checkAndRepairBounds(true, false)) {
this._updateText();
}
};
wijinputnumber.prototype._raiseDataChanged = function () {
var v = this.options.value, prevValue = this.element.data('preValue');
this.element.data('preValue', v);
if(prevValue !== v) {
this.element.attr('aria-valuenow', v);
this._trigger('valueChanged', null, {
value: v
});
}
};
wijinputnumber.prototype.getValue = /** Gets the value. */
function () {
var val = this._textProvider.getValue();
if(val === undefined || val === null) {
val = this.getText();
}
return val;
};
wijinputnumber.prototype.setValue = /** Sets the value.
* @example
* // set value of a wijinputnumber to 10
* $(".selector").wijinputnumber("setValue", 10, true);
*/
function (val, exact) {
if (typeof exact === "undefined") { exact = false; }
try {
exact = !!exact;
if(typeof val === 'boolean') {
val = val ? '1' : '0';
} else if(typeof val === 'string') {
val = this._textProvider.tryParseValue(val);
}
if(this._textProvider.setValue(val)) {
this._updateText();
} else {
if(exact) {
var prevVal = '', txt;
prevVal = this.getText();
this.setText(val);
val = val.trim();
txt = this.getText().trim();
if(txt !== val) {
this.setText(prevVal);
}
} else {
this.setText(val);
}
}
return true;
} catch (e) {
return false;
}
};
wijinputnumber.prototype.isValueNull = /** Determines whether the value is in null state. */
function () {
try {
return (this._textProvider).isValueNull();
} catch (e) {
return true;
}
};
wijinputnumber.prototype.getPostValue = /** Gets the text value when the container form is posted back to server. */
function () {
if(!this._isInitialized()) {
return this.element.val();
}
if(this.options.showNullText && this.isValueNull()) {
return "0";
}
var val = this.options.value ? this.options.value : 0;
if(this.options.type === "percent") {
val = (val / 100).toFixed(10);
}
return val.toString();
};
wijinputnumber.prototype._updateText = function (keepSelection) {
if (typeof keepSelection === "undefined") { keepSelection = false; }
if(!this._isInitialized()) {
return;
}
this.options.value = this._textProvider.getValue();
_super.prototype._updateText.call(this, keepSelection);
if(!this._textProvider.checkAndRepairBounds(false, false)) {
this._trigger('valueBoundsExceeded');
}
};
wijinputnumber.prototype._doSpin = function (up, repeating) {
if(!this._allowEdit()) {
return false;
}
if(repeating && this.element.data('breakSpinner')) {
return false;
}
var selRange = this.element.wijtextselection(), rh = new input.wijInputResult();
if(this.element.data('focusNotCalledFirstTime') !== -9 && (new Date().getTime() - this.element.data('focusNotCalledFirstTime')) < 600) {
this.element.data('focusNotCalledFirstTime', -9);
this.element.data('prevCursorPos', 0);
}
if(this.element.data('prevCursorPos') === -1) {
this.element.data('prevCursorPos', selRange.start);
} else {
selRange.start = (this.element.data('prevCursorPos'));
}
rh.testPosition = selRange.start;
this._textProvider[up ? 'incEnumPart' : 'decEnumPart'](selRange.start, rh, this.options.increment);
this._updateText();
this.element.data('prevCursorPos', rh.testPosition);
this.selectText(rh.testPosition, rh.testPosition);
if(repeating && !this.element.data('breakSpinner')) {
window.setTimeout($.proxy(function () {
this._doSpin(up, true);
}, this), this._calcSpinInterval());
}
return true;
};
wijinputnumber.prototype._deleteSelText = function (backspace) {
if (typeof backspace === "undefined") { backspace = false; }
var sel = this.element.wijtextselection(), everythingSelected = sel.start === 0 && sel.end === this.element.val().length, text;
if(sel.start === sel.end) {
// move right if "delete" key is pressed and there cursor is to left from a group/decimal separator symbol
if(!backspace) {
text = this._textProvider._stringFormat._currentText;
if(text.charAt(sel.end) === this._textProvider.getGroupSeparator() || text.charAt(sel.end) === this._textProvider.getDecimalSeparator()) {
sel.start++;
sel.end++;
this.element.wijtextselection(sel);
return;
}
}
}
_super.prototype._deleteSelText.call(this, backspace);
if(everythingSelected) {
// everything is selected
this._textProvider._nullvalue = true;
this._updateText(true);
}
};
return wijinputnumber;
})(input.wijinputcore);
input.wijinputnumber = wijinputnumber;
var wijinputnumber_options = (function () {
function wijinputnumber_options() {
this.wijCSS = {
wijinputnumber: input.wijinputcore.prototype.options.wijCSS.wijinput + "-numeric"
};
/** Determines the type of the number input.
* Possible values are: 'numeric', 'percent', 'currency'.
*/
this.type = 'numeric';
/** Determines the default numeric value. */
this.value = null;
/** Determines the minimal value that can be entered for
* numeric/percent/currency inputs.
*/
this.minValue = -1000000000;
/** Determines the maximum value that can be entered for
* numeric/percent/currency inputs.
*/
this.maxValue = 1000000000;
/** Indicates whether the thousands group separator will be
* inserted between between each digital group
* (number of digits in thousands group depends on the
* selected Culture).
*/
this.showGroup = false;
/** Indicates the number of decimal places to display.
* @remarks
* Possible values are integer from -2 to 8. They are:
* useDefault: -2,
* asIs: -1,
* zero: 0,
* one: 1,
* two: 2,
* three: 3,
* four: 4,
* five: 5,
* six: 6,
* seven: 7,
* eight: 8
*/
this.decimalPlaces = 2;
/** Determines how much to increase/decrease the input field. */
this.increment = 1;
/** The valueChanged event handler.
* A function called when the value of the input is changed.
* @event
* @dataKey value The new value */
this.valueChanged = null;
/** The valueBoundsExceeded event handler. A function called when
* the value of the input exceeds the valid range.
* @event
*/
this.valueBoundsExceeded = null;
}
return wijinputnumber_options;
})();
wijinputnumber.prototype.options = $.extend(true, {
}, input.wijinputcore.prototype.options, new wijinputnumber_options());
$.wijmo.registerWidget("wijinputnumber", wijinputnumber.prototype);
//==============================
var wijNumberTextProvider = (function (_super) {
__extends(wijNumberTextProvider, _super);
function wijNumberTextProvider(owner, type) {
_super.call(this);
this._type = 'numeric';
this._stringFormat = null;
this._nullvalue = false;
this.inputWidget = owner;
this._type = type;
this._stringFormat = new wijNumberFormat(this._type, this.inputWidget.options.decimalPlaces, this.inputWidget.options.showGroup, this._getCulture());
this._stringFormat._setValueFromJSFloat(this.getValue());
}
wijNumberTextProvider.prototype._getCulture = function () {
return this.inputWidget._getCulture();
};
wijNumberTextProvider.prototype.getDecimalSeparator = function () {
return this._getCulture().numberFormat['.'];
};
wijNumberTextProvider.prototype.getGroupSeparator = function () {
return this._getCulture().numberFormat[","];
};
wijNumberTextProvider.prototype.tryParseValue = function (value) {
return this._stringFormat.tryParseValue(value);
};
wijNumberTextProvider.prototype.toString = function () {
if(this.inputWidget.options.showNullText && !this.inputWidget.isFocused() && this.isValueNull()) {
return this.inputWidget.options.nullText;
}
return this._stringFormat.getFormattedValue();
};
wijNumberTextProvider.prototype.isValueNull = function () {
var o = this.inputWidget.options, nullValue = o.minValue;
//nullValue = Math.max(0, o.minValue);
return null === o.value || undefined === o.value || nullValue === o.value || this._nullvalue;
};
wijNumberTextProvider.prototype.set = function (input, rh) {
this.clear();
this.insertAt(input, 0, rh);
return true;
};
wijNumberTextProvider.prototype.clear = function () {
this._stringFormat.clear();
};
wijNumberTextProvider.prototype.checkAndRepairBounds = function (chkAndRepair, chkIsLessOrEqMin) {
var result = true, minValue, maxValue;
if(typeof (chkAndRepair) === 'undefined') {
chkAndRepair = false;
}
minValue = this.inputWidget.options.minValue;
maxValue = this.inputWidget.options.maxValue;
if(typeof (chkIsLessOrEqMin) !== 'undefined' && chkIsLessOrEqMin) {
return this._stringFormat.checkMinValue(minValue, false, true);
}
if(!this._stringFormat.checkMinValue(minValue, chkAndRepair, false)) {
result = false;
}
if(!this._stringFormat.checkMaxValue(maxValue, chkAndRepair)) {
result = false;
}
if(this.inputWidget.options.decimalPlaces >= 0) {
this._stringFormat.checkDigitsLimits(this.inputWidget.options.decimalPlaces);
}
return result;
};
wijNumberTextProvider.prototype.countSubstring = function (txt, subStr) {
var c = 0, pos = txt.indexOf(subStr);
while(pos !== -1) {
c++;
pos = txt.indexOf(subStr, pos + 1);
}
return c;
};
wijNumberTextProvider.prototype.getAdjustedPositionFromLeft = function (position) {
var currentText = this._stringFormat._currentText, i, ch;
for(i = 0; i < currentText.length; i++) {
ch = currentText.charAt(i);
if(!$.wij.charValidator.isDigit(ch) && (ch !== this.getGroupSeparator() && ch !== this.getDecimalSeparator()) || ch === '0') {
if(this._stringFormat.isZero()) {
if(position < i) {
position++;
}
} else {
if(position <= i) {
position++;
}
}
} else {
break;
}
}
return position;
};
wijNumberTextProvider.prototype.getDecimalSeparatorPos = function () {
var currentText = this._stringFormat._currentText;
return currentText.indexOf(this.getDecimalSeparator());
};
wijNumberTextProvider.prototype.removeLeadingZero = function (num) {
var pos = 0;
if(num.charAt(pos) === ' ' || num.charAt(pos) === this._getCulture().numberFormat.currency.symbol) {
pos++;
}
while(num.charAt(pos) === '0' && num.charAt(pos + 1) !== '.') {
num = num.substr(0, pos) + num.substr(pos + 1);
}
return num;
};
wijNumberTextProvider.prototype.insertAt = function (strInput, position, rh) {
var nf = this._getCulture().numberFormat, pos, slicePos, currentText, beginText, endText, newText, oldGroupSeparatorCount, newGroupSeparatorCount, leftPrevCh, leftCh;
if(!rh) {
rh = new input.wijInputResult();
} else {
this._nullvalue = false;
}
if(strInput.length === 1) {
if(strInput === '+') {
this._stringFormat.setPositiveSign();
this.checkAndRepairBounds(true, false);
return true;
}
if(strInput === '-' || strInput === ')' || strInput === '(') {
this._stringFormat.invertSign();
this.checkAndRepairBounds(true, false);
rh.testPosition = position;
if(this._stringFormat.isNegative()) {
rh.testPosition = position;
} else {
rh.testPosition = position - 2;
}
return true;
}
if(!$.wij.charValidator.isDigit(strInput)) {
if(strInput === this.getDecimalSeparator()) {
pos = this.getDecimalSeparatorPos();
if(pos >= 0) {
rh.testPosition = pos;
return true;
}
}
if(strInput !== this.getGroupSeparator() && strInput !== this.getDecimalSeparator() && strInput !== ')' && strInput !== '+' && strInput !== '-' && strInput !== '(' && strInput !== this.getDecimalSeparator()) {
if(this._type === 'percent' && strInput === nf.percent.symbol) {
rh.testPosition = position;
return true;
} else if(this._type === 'currency' && strInput === nf.currency.symbol) {
rh.testPosition = position;
return true;
} else {
return false;
}
}
}
}
position = this.getAdjustedPositionFromLeft(position);
slicePos = position;
currentText = this._stringFormat._currentText;
if(slicePos > currentText.length) {
slicePos = currentText.length - 1;
}
// if (input.length === 1) {
// if (currentText.charAt(slicePos) === input) {
// rh.testPosition = slicePos;
// return true;
// }
// }
beginText = this.removeLeadingZero(currentText.substring(0, slicePos));
endText = currentText.substring(slicePos, currentText.length);
if(this._stringFormat.isZero()) {
endText = endText.replace(/0/, '');
}
rh.testPosition = beginText.length + strInput.length - 1;
this._stringFormat.deFormatValue(beginText + strInput + endText);
newText = this._stringFormat._currentText;
//this.checkAndRepairBounds(true, false);
try {
if(this.inputWidget.options.showGroup) {
oldGroupSeparatorCount = this.countSubstring(beginText, this._stringFormat._groupSeparator);
newGroupSeparatorCount = this.countSubstring(newText.substring(0, beginText.length + strInput.length), this._stringFormat._groupSeparator);
rh.testPosition += newGroupSeparatorCount - oldGroupSeparatorCount;
} else if(strInput.length === 1) {
leftPrevCh = beginText.charAt(beginText.length - 1);
leftCh = newText.charAt(rh.testPosition - 1);
if(leftCh !== leftPrevCh) {
rh.testPosition--;
}
}
} catch (e) {
}
return true;
};
wijNumberTextProvider.prototype.removeAt = function (start, end, rh, skipCheck) {
if (typeof rh === "undefined") { rh = new input.wijInputResult(); }
if (typeof skipCheck === "undefined") { skipCheck = false; }
var nf = this._getCulture().numberFormat, curText, beginText, newText, decimalSepRemoved, oldGroupSeparatorCount, newGroupSeparatorCount;
rh.testPosition = start;
try {
curText = this._stringFormat._currentText;
if((start === end) && curText.substring(start, end + 1) === this.getDecimalSeparator()) {
return false;
}
beginText = curText.slice(0, start);
newText = beginText;
decimalSepRemoved = curText.slice(start, end + 1).indexOf(this.getDecimalSeparator()) >= 0;
if(decimalSepRemoved) {
newText += this.getDecimalSeparator();
}
newText += curText.slice(end + 1);
newText = newText || "0";
this._stringFormat.deFormatValue(newText);
newText = this._stringFormat._currentText;
this._nullvalue = false;
if(this.inputWidget.options.showGroup) {
if(decimalSepRemoved) {
rh.testPosition = newText.indexOf(this.getDecimalSeparator());
} else {
try {
oldGroupSeparatorCount = this.countSubstring(beginText, this._stringFormat._groupSeparator);
newGroupSeparatorCount = this.countSubstring(newText.substring(0, Math.max(0, start - 1)), this._stringFormat._groupSeparator);
rh.testPosition -= oldGroupSeparatorCount - newGroupSeparatorCount;
if(curText.indexOf(nf.currency.symbol) === rh.testPosition || curText.indexOf(nf.percent.symbol) === rh.testPosition) {
rh.testPosition++;
}
} catch (e1) {
}
}
}
// if (!skipCheck){
// this.checkAndRepairBounds(true, false);
// }
return true;
} catch (e2) {
}// if (!skipCheck){
// this.checkAndRepairBounds(true, false);
// }
return true;
};
wijNumberTextProvider.prototype.incEnumPart = function (position, rh, val) {
if(!rh) {
rh = new input.wijInputResult();
}
this._stringFormat.increment(val);
this._nullvalue = false;
return this.checkAndRepairBounds(true, false);
};
wijNumberTextProvider.prototype.decEnumPart = function (position, rh, val) {
if(!rh) {
rh = new input.wijInputResult();
}
this._stringFormat.decrement(val);
this._nullvalue = false;
return this.checkAndRepairBounds(true, false);
};
wijNumberTextProvider.prototype.getValue = function () {
return this._stringFormat.getJSFloatValue();
};
wijNumberTextProvider.prototype.setValue = function (val) {
try {
this._stringFormat._setValueFromJSFloat(val);
this.checkAndRepairBounds(true, false);
return true;
} catch (e) {
return false;
}
};
wijNumberTextProvider.prototype.updateStringFormat = function () {
var t = '0';
if(typeof (this._stringFormat) !== 'undefined') {
t = this._stringFormat._currentValueInString;
}
this._stringFormat = new wijNumberFormat(this._type, this.inputWidget.options.decimalPlaces, this.inputWidget.options.showGroup, this._getCulture());
this._stringFormat._currentValueInString = t;
};
return wijNumberTextProvider;
})(input.wijTextProvider);
input.wijNumberTextProvider = wijNumberTextProvider;
//============================
var wijNumberFormat = (function () {
function wijNumberFormat(type, digitsPlaces, showGroup, culture) {
this.type = type;
this.digitsPlaces = digitsPlaces;
this.showGroup = showGroup;
this.culture = culture;
// stripped value with en-US culture
this._currentValueInString = '0';
this._currentText = '0';
this._groupSeparator = ' ';
}
wijNumberFormat.prototype.decimalSeparator = function () {
return this.culture.numberFormat["."];
};
wijNumberFormat.prototype.isNegtive = function (value) {
return value.indexOf('-') !== -1 || value.indexOf('(') !== -1;
};
wijNumberFormat.prototype.stripValue = function (value) {
var nf = this.culture.numberFormat, specificFormat = nf[this.type] || nf, isNegative = this.isNegtive(value), groupSep = specificFormat[','], decimalSep = specificFormat['.'], stripRgx = new RegExp('[' + groupSep + nf.percent.symbol + nf.currency.symbol + ' ]', 'g'), match;
this._groupSeparator = groupSep;
value = this._removeNegativeSign(value);
value = value.replace(stripRgx, '');
value = value.replace(decimalSep, '.');
match = /([\d\.])+/.exec(value);
if(match) {
value = match[0];
}
if(isNegative) {
value = '-' + value;
}
return value;
};
wijNumberFormat.prototype.tryParseValue = function (value) {
try {
var result = parseFloat(this.stripValue(value));
if(isNaN(result)) {
result = 0;
}
return result;
} catch (e) {
return 0;
}
};
wijNumberFormat.prototype.deFormatValue = function (value) {
value = this.stripValue(value);
this._currentValueInString = value;
this._currentText = this.formatValue(value);
};
wijNumberFormat.prototype.formatValue = function (strippedValue) {
var nf = this.culture.numberFormat, specificFormat = nf[this.type] || nf, dp = this.digitsPlaces, isNegative = this.isNegtive(strippedValue), pattern = specificFormat.pattern[isNegative ? 0 : 1] || 'n', groupSep = specificFormat[','], decimalSep = specificFormat['.'], decimals = dp !== -2 ? dp : specificFormat.decimals, groupSizes = this.showGroup ? specificFormat.groupSizes : [
0
], digitsString;
strippedValue = this._removeLeadingZero(strippedValue);
digitsString = this.formatDigit(strippedValue, groupSep, decimalSep, decimals, groupSizes);
digitsString = this._removeLeadingZero(digitsString);
if(digitsString.indexOf(decimalSep) === 0) {
digitsString = '0' + digitsString;
}
if(digitsString === '') {
digitsString = '0';
}
this._currentValueInString = strippedValue;
this._currentText = this.applyFormatPattern(pattern, digitsString, nf.percent.symbol, nf.currency.symbol);
return this._currentText;
};
wijNumberFormat.prototype.getFormattedValue = function () {
return this.formatValue(this._currentValueInString);
};
wijNumberFormat.prototype.getJSFloatValue = function () {
try {
if(this._currentValueInString === '') {
return 0;
}
return parseFloat(this._currentValueInString);
} catch (e) {
return Number.NaN;
}
};
wijNumberFormat.prototype.clear = function () {
this._currentValueInString = '0';
this._currentText = '0';
};
wijNumberFormat.prototype._setValueFromJSFloat = function (value) {
var strValue = '' + value;
try {
this._currentValueInString = strValue;
this.formatValue(strValue);
return true;
} catch (e) {
return false;
}
};
wijNumberFormat.prototype.isZero = function (val) {
if (typeof val === "undefined") { val = this._currentValueInString; }
var test = this._removeNegativeSign(val), dbl;
if(!test) {
return true;
}
dbl = parseFloat(test);
return !isNaN(dbl) && !dbl;
};
wijNumberFormat.prototype.setPositiveSign = function () {
this._currentValueInString = this._removeNegativeSign(this._currentValueInString);
};
wijNumberFormat.prototype._removeNegativeSign = function (text) {
return text.replace(/[()\-]/g, "");
};
wijNumberFormat.prototype._removeLeadingZero = function (text) {
return text.replace(/^0+/, "");
};
wijNumberFormat.prototype.isNegative = function () {
return this._currentValueInString.indexOf('-') !== -1 || this._currentValueInString.indexOf('(') !== -1;
};
wijNumberFormat.prototype.invertSign = function () {
var isNegative = this.isNegative();
if(isNegative) {
this.setPositiveSign();
} else {
this._currentValueInString = (!this._currentValueInString.length) ? '0' : '-' + this._currentValueInString;
}
if(this.isZero()) {
this._currentValueInString = isNegative ? '0' : '-0';
}
this.formatValue(this._currentValueInString);
};
wijNumberFormat.prototype.parseNumber = function (strippedValue) {
if (typeof strippedValue === "undefined") { strippedValue = this._currentValueInString; }
var arr = strippedValue.split(".", 2);
return {
decimal: parseInt(arr[0], 10) || 0,
fraction: (arr.length > 1 ? parseInt(arr[1], 10) : 0) || 0
};
};
wijNumberFormat.prototype._change = function (delta) {
var num = this.parseNumber();
this._currentValueInString = "" + (num.decimal + delta) + "." + num.fraction;
};
wijNumberFormat.prototype.increment = function (val) {
if (typeof val === "undefined") { val = 1; }
this._change(val);
};
wijNumberFormat.prototype.decrement = function (val) {
if (typeof val === "undefined") { val = 1; }
this._change(-val);
};
wijNumberFormat.prototype.checkDigitsLimits = function (digitCount) {
var arr = this._currentValueInString.split("."), fraction = '';
if(!arr.length || (arr.length === 1 && arr[0] === '')) {
return;
}
if(arr.length > 1) {
fraction = arr[1];
}
fraction = fraction.substring(0, digitCount);
while(fraction.length < digitCount) {
fraction += "0";
}
this._currentValueInString = arr[0];
if(fraction) {
this._currentValueInString += "." + fraction;
}
};
wijNumberFormat.prototype.checkMinValue = function (val, chkAndRepair, chkIsLessOrEqMin) {
if (typeof chkIsLessOrEqMin === "undefined") { chkIsLessOrEqMin = false; }
var result = true, arr, s1, s2, sv1, sv2;
try {
arr = this._currentValueInString.split(".");
s1 = parseFloat((arr[0] === '' || arr[0] === '-') ? '0' : arr[0]);
s2 = 0;
if(arr.length > 1 && parseFloat(arr[1]) > 0) {
s2 = parseFloat('1.' + arr[1]);
}
if(s1 < 0 || arr[0] === '-') {
s2 = s2 * -1;
}
val = '' + val + '';
arr = val.split(".");
sv1 = parseFloat(arr[0]);
sv2 = 0;
if(arr.length > 1 && parseFloat(arr[1]) > 0) {
sv2 = parseFloat('1.' + arr[1]);
}
if(s1 > sv1) {
return true;
}
if(s1 < sv1 || (chkIsLessOrEqMin && s1 === sv1 && s2 <= sv2)) {
result = false;
} else if(s1 === sv1 && s1 < 0 && s2 > sv2) {
result = false;
} else if(s1 === sv1 && s1 >= 0 && s2 < sv2) {
result = false;
}
if(!result && chkAndRepair) {
this._currentValueInString = '' + val + '';
}
} catch (e) {
}
return result;
};
wijNumberFormat.prototype.checkMaxValue = function (val, chkAndRepair) {
var result = true, arr, s1, s2, sv1, sv2;
try {
arr = this._currentValueInString.split(".");
s1 = parseFloat((arr[0] === '' || arr[0] === '-') ? '0' : arr[0]);
s2 = 0;
if(arr.length > 1 && parseFloat(arr[1]) > 0) {
s2 = parseFloat('1.' + arr[1]);
}
if(s1 < 0 || arr[0] === '-') {
s2 = s2 * -1;
}
val = '' + val + '';
arr = val.split(".");
sv1 = parseFloat(arr[0]);
sv2 = 0;
if(arr.length > 1 && parseFloat(arr[1]) > 0) {
sv2 = parseFloat('1.' + arr[1]);
}
if(s1 < sv1) {
return true;
}
if(s1 > sv1) {
result = false;
}
if(s1 === sv1 && s1 >= 0 && s2 > sv2) {
result = false;
}
if(s1 === sv1 && s1 < 0 && s2 < sv2) {
result = false;
}
if(!result && chkAndRepair) {
this._currentValueInString = '' + val + '';
}
} catch (e) {
}
return result;
};
wijNumberFormat.prototype.applyFormatPattern = function (pattern, digitString, percentSymbol, currencySymbol) {
return pattern.replace(/n/g, digitString).replace(/%/g, percentSymbol).replace(/\$/g, currencySymbol);
};
wijNumberFormat.prototype.formatDigit = function (strippedValue, groupSep, decimalSep, decimals, groupSizes) {
var absValue = this._removeNegativeSign(strippedValue), decimalPos, result, groupSizeIndex, groupCount, ch, i;
decimalPos = absValue.indexOf('.');
if(decimalPos === -1) {
decimalPos = absValue.length;
}
result = '';
groupSizeIndex = 0;
groupCount = 0;
for(i = absValue.length - 1; i >= 0; i--) {
ch = absValue.charAt(i);
if(i < decimalPos) {
result = ch + result;
groupCount++;
if(groupCount === groupSizes[groupSizeIndex] * 1 && groupSizes[groupSizeIndex] * 1 && i) {
result = groupSep + result;
groupCount = 0;
if(groupSizes.length - 1 > groupSizeIndex) {
groupSizeIndex++;
}
}
}
}
if(decimals > 0) {
result = result + decimalSep;
for(i = 0; i < decimals; i++) {
ch = '0';
if(i + decimalPos + 1 < absValue.length) {
ch = absValue.charAt(i + decimalPos + 1);
}
result = result + ch;
}
}
if(decimals === -1) {
if(decimalPos < absValue.length - 1) {
result = result + decimalSep;
result = result + absValue.substr(decimalPos + 1);
}
}
return result;
};
return wijNumberFormat;
})();
input.wijNumberFormat = wijNumberFormat;
})(wijmo.input || (wijmo.input = {}));
var input = wijmo.input;
})(wijmo || (wijmo = {}));
;
/*
* Depends:
* jquery-1.9.1.js
* jquery.ui.core.js
* jquery.ui.widget.js
* globalize.js
* jquery.wijmo.widget.js
* jquery.wijmo.wijutil.js
* wijmo.data.js
*
* Optional dependencies for paging feature:
* jquery.wijmo.wijpager.js
*
* Optional dependencies for scrolling feature:
* jquery.wijmo.wijsuperpanel.js
*
* Optional dependencies for filtering feature:
* jquery.ui.position.js
* jquery.wijmo.wijinputdate.js
* jquery.wijmo.wijinputmask.js
* jquery.wijmo.wijinputnumber.js
* jquery.wijmo.wijlist.js
*
* Optional dependencies for column moving feature:
* jquery.ui.draggable.js
* jquery.ui.droppable.js
* jquery.ui.position.js
*
*/
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
function extendWidgetOptions(baseOptions, newOptions) {
var result = $.extend(true, {
}, baseOptions, newOptions);
delete result.constructor// Remove the constructor because the widget.options object is a ts class now (widgetName_options).
;
return result;
}
grid.extendWidgetOptions = extendWidgetOptions;
/** @widget
* Represents the wijgrid widget.
*/
var wijgrid = (function (_super) {
__extends(wijgrid, _super);
function wijgrid() {
_super.apply(this, arguments);
// private fields **
this._dataOffset = 0;
this._scrollingState = {
x: null,
y: // h. pos
null,
index: // v. pos
0
};// scroll index (virtual scrolling)
this._windowResizeTimer = 0;
}
wijgrid.prototype._createWidget = // stores the deficient filters (one of the filterOperator\ filterValue values is unknown) during the dataView round trip by the dataKey.
// * override
function (options, element) {
// Late binding, a fix for the case if options.data contains a complex object leading to stack overflow when $.extend is called in the widget factory.
var data = options && (wijmo).data.util.isClassInstance(options.data) && !((typeof wijdatasource === "function") && (options.data instanceof wijdatasource)) && options.data;
if(data) {
delete options.data;
}
_super.prototype._createWidget.apply(this, arguments);
if(data) {
options.data = data// restore option value (fixes an issue when a single options object is passed to multiple instances of the wijgrid: $("table").wijgrid({...});
;
this.option("data", data);
}
};
wijgrid.prototype._create = function () {
var self = this;
if(!this.element.is("table")) {
throw "invalid markup";
}
this._windowResizeTimer = 0;
this._dataOffset = 0;
this._scrollingState = {
x: null,
y: null,
index: 0
};
this._initialized = false;
this._destroyed = false;
this._rendered = false;
this._eventUID = undefined;
;
this._dataViewWrapper = undefined;
this._originalHtml = undefined;
this._originalAttr = undefined;
this._originalCssText = undefined;
this._autoHeight = undefined;
this._autoWidth = undefined;
this._renderCounter = 0;
this.$superPanelHeader = undefined;
this.$topPagerDiv = undefined;
this.$bottomPagerDiv = undefined;
this.$groupArea = undefined;
this.__uid = undefined;
this._wijDataView = undefined;
this.outerDiv = undefined;
this.sketchTable = undefined;
this.cellFormatter = undefined;
this.rowStyleFormatter = undefined;
this.cellStyleFormatter = undefined;
this._eventUID = wijmo.grid.getUID();
this._spinnerIsActivated = false;
this.deficientFilters = {
};
// ** jQuery UI 1.9.0 fix
var hasData = ("data" in this.options), data = hasData && this.options.data;
if(hasData) {
delete this.options.data;
}
this.options = $.extend(true, {
}, this.options);
if(hasData) {
this.options.data = data;
}
// jQuery UI 1.9.0 fix **
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
// handle juice objectValue serialize
if($.isFunction(window["wijmoASPNetParseOptions"])) {
window["wijmoASPNetParseOptions"](this.options);
}
this._initialized = false;
this._destroyed = false;
// culture
this._field("closestCulture", Globalize.findClosestCulture(this.options.culture) || Globalize.findClosestCulture("default"));
// initialize data
this._dataViewWrapper = new wijmo.grid.dataViewWrapper(this);
this._originalHtml = this.element.html()// store original html. Will be restored in the destroy() method.
;
this._originalAttr = {
};
this._originalCssText = this.element[0].style.cssText;
this.element.addClass("wijmo-wijgrid-root");
this.element.wrap("<div class=\"" + this.options.wijCSS.widget + " wijmo-wijgrid " + this.options.wijCSS.content + " " + this.options.wijCSS.cornerAll + "\"></div>")// outer div
;
this.outerDiv = this.element.parent();
var styleHeight = this.element[0].style.height, styleWidth = this.element[0].style.width;
if(styleHeight) {
this.outerDiv.css("height", styleHeight);
}
this._autoHeight = (styleHeight == "" || styleHeight == "auto");
if(styleWidth) {
this.outerDiv.css("width", this.element[0].style.width);
}
this._autoWidth = (styleWidth == "" || styleWidth == "auto");
this.element.css({
"height": "",
"width": ""
});
if(this.options.disabled) {
this.disable();
}
// formatters
this.cellFormatter = new wijmo.grid.cellFormatterHelper();
this.rowStyleFormatter = new wijmo.grid.rowStyleFormatterHelper(this);
this.cellStyleFormatter = new wijmo.grid.cellStyleFormatterHelper(this);
// * set bounds
this._field("viewRenderBounds", {
start: 0,
end: 0
});
if(this._allowVirtualScrolling()) {
this._field("viewRenderBounds").start = this._scrollingState.index// == 0 by default.
;
if(this._serverSideVirtualScrolling()) {
this._dataOffset = this._scrollingState.index;
}
}
// set bounds *
// wijObservable
if(this.element.wijAddVisibilityObserver) {
this.element.wijAddVisibilityObserver(function () {
//if (self.element.is(":visible")) {
if(self._initialized && !self._destroyed) {
self.setSize();
}
//}
}, "wijgrid");
}
this._renderCounter = 0;
};
wijgrid.prototype._destroy = function () {
var tmp, self = this;
try {
this._view().dispose();
this._detachEvents(true);
if(tmp = this._field("resizer")) {
tmp.dispose();
}
if(tmp = this._field("frozener")) {
tmp.dispose();
}
if(tmp = this._field("selectionui")) {
tmp.dispose();
}
if(tmp = this._field("dragndrop")) {
tmp.dispose();
}
this._dataViewWrapper.dispose();
// cleanup $data
wijmo.grid.remove$dataByPrefix(this.element, this._data$prefix);
if(this.element.wijRemoveVisibilityObserver) {
this.element.wijRemoveVisibilityObserver();
}
// ** restore original content
// restore content and destroy children widgets + data.
this.element.insertBefore(this.outerDiv);
this.outerDiv.remove();
this.element.html(this._originalHtml);
// restore attributes
$.each(this._originalAttr, function (key, value) {
if(value === undefined) {
self.element.removeAttr(key);
} else {
self.element.attr(key, value);
}
});
this.element.removeClass("wijmo-wijgrid-root");
this.element[0].style.cssText = this._originalCssText// restore style properties
;
// restore original content **
}finally {
this._destroyed = true;
}
};
wijgrid.prototype._init = function () {
this.$superPanelHeader = null;
this.$topPagerDiv = null;
this.$bottomPagerDiv = null;
this.$groupArea = null;
// culture
this._field("closestCulture", Globalize.findClosestCulture(this.options.culture) || Globalize.findClosestCulture("default"));
if(!this.options.data) {
// dataSource is a domTable
if(!this._field("thead")) {
// read tHead section
this._field("thead", wijmo.grid.readTableSection(this.element, 1));
}
if(!this._field("tfoot")) {
// read tFoot section
this._field("tfoot", wijmo.grid.readTableSection(this.element, 3));
}
}
/*if (this._serverSideVirtualScrolling()) {
this._dataOffset = this.options.pageIndex * this.options.pageSize;
}*/
this._initialized = this._initialized || false// to avoid reinitialization.
;
this.ensureControl(true);
};
wijgrid.prototype._setOption = function (key, value) {
var presetFunc = this["_preset_" + key], oldValue = this.options[key], optionChanged, postsetFunc;
if(presetFunc !== undefined) {
value = presetFunc.apply(this, [
value,
oldValue
]);
}
optionChanged = (value !== oldValue);
//$.Widget.prototype._setOption.apply(this, arguments); note: there is no dynamic linkage between the arguments and the formal parameter values when strict mode is used
_super.prototype._setOption.apply(this, [
key,
value
])// update this.options
;
if(optionChanged) {
postsetFunc = this["_postset_" + key];
if(postsetFunc !== undefined) {
postsetFunc.apply(this, [
value,
oldValue
]);
}
}
};
wijgrid.prototype.columns = // * override
// * public
/** Returns a one-dimensional array of widgets bound to visible column headers.
* @example
* var colWidgets = $("#element").wijgrid("columns");
* @remarks
* wijgrid columns are represented as widgets. This method returns a one-dimensional array of widgets that are bound to visible column headers.
*
* The column widget is initiated with values taken from the corresponding item in the wijgrid.options.columns array. However, the options of a column widget instance reference not the original object but a copy created by the widget factory. Due to that, changes to the wijgrid.options.columns options are not automatically propagated to the column widget options and vice versa.
* To solve this issue, the wijgrid synchronized the column widget option values with the source items. This synchronization occurs inside the ensureControl() method which is automatically called at each action requiring the wijgrid to enter.
*
* Still, there is a drawback. For example, a user may want to filter wijgrid data from user code as in this sample:
*
* $("#element").wijgrid("option", "columns")[0].filterValue = "newValue";
* $("#element").wijgrid("ensureControl", true); // make wijgrid re-shape data and re-render.
*
* In the sample above, nothing will happen since at synchronization user changes will be ignored.You need to change the filterValue of a column widget. This is what the columns() method is for:
*
* $("#element").wijgrid("columns")[0].options.filterValue = "newValue";
* $("#element").wijgrid("ensureControl", true); // make wijgrid re-shape data and re-render.
*
* Here's the best way to change the filterValue:
*
* $("#element").wijgrid("columns")[0].option("filterValue", "newValue"); // column widget handles all the needful.
*
* @returns {Object[]} A one-dimensional array of widgets bound to visible column headers.
*/
function () {
return this._field("columns") || [];
};
wijgrid.prototype.currentCell = // setter 2
/** @ignore */
function (a, b) {
var currentCell, view = this._view(), rows = this._rows();
if(arguments.length === 0) {
// getter
currentCell = this._field("currentCell");
if(!currentCell) {
this._field("currentCell", currentCell = wijmo.grid.cellInfo.outsideValue);
}
return currentCell;
} else {
// setter
currentCell = (arguments.length === 1) ? (a)._clone() : new wijmo.grid.cellInfo(a, b);
if(!currentCell.isEqual(wijmo.grid.cellInfo.outsideValue)) {
if(!currentCell._isValid()) {
throw "invalid arguments";
}
currentCell._clip(this._getDataCellsRange());
if(currentCell.rowIndex() >= 0) {
if(!(view._getRowInfo(rows.item(currentCell.rowIndex())).type & wijmo.grid.rowType.data)) {
return;
}
}
}
currentCell._setGridView(this);
this._changeCurrentCell(null, currentCell);
return this._field("currentCell");
}
};
wijgrid.prototype.data = /** Gets an array of underlying data.
* @example
* var data = $("#element").wijgrid("data");
* @returns {object[]} An array of underlying data.
*/
function () {
//return this._dataViewWrapper.dataView()();
return this._dataViewWrapper.dataView().getSource();
};
wijgrid.prototype.dataView = /** Gets an underlying wijdataview instance.
* @example
* var dataView = $("#element").wijgrid("dataView");
* @returns {wijmo.data.IDataView} An underlying wijdataview instance.
*/
function () {
return this._dataViewWrapper.dataView();
};
wijgrid.prototype.doRefresh = /** Re-renders wijgrid.
* @example
* $("#element").wijgrid("doRefresh");
*/
function (userData) {
if(!$.isPlainObject(userData)) {
userData = {
};
}
var leaves, self = this, uid = wijmo.grid.EXPANDO, virtualRefresh = userData && userData.virtualScrollData;
if(!this._initialized) {
try {
this._prepareColumnOptions(this.options.columns, this.options.columnsAutogenerationMode, this._dataViewWrapper.getFieldsInfo(), true, true)// prepare static and dynamic columns
;
} catch (e) {
throw e;
}finally {
//ownerise the column for bug 16936, 17079
this._ownerise(true);
this._initialized = true;
}
} else {
// if (userData && $.isFunction(userData.beforeRefresh)) {
// userData.beforeRefresh.apply(this);
// }
}
if(!virtualRefresh) {
// do not rebuild leaves during virtual scrolling callback
this._rebuildLeaves()// build leaves, visible leaves, set dataIndex etc
;
var dataSlice = this._dataViewWrapper.data();
var dataView = this._dataViewWrapper.dataView();
$.each(this._field("leaves"), function () {
// copy totals
this._totalsValue = (dataSlice.totals) ? dataSlice.totals[this.dataKey] : undefined;
});
// this._setPageCount(dataSlice);
this.sketchTable = [];
if(dataSlice.data && dataSlice.data.length) {
// process data items
leaves = this._field("leaves");
$.each(dataSlice.data, function (i, item) {
self.sketchTable.push(self._buildSketchRow(item, leaves));
});
} else {
if(dataSlice.emptyData) {
// process empty data row
leaves = this._field("visibleLeaves");
$.each(dataSlice.emptyData, function (i, item) {
self.sketchTable.push(self._buildSketchRowEmptyDataItem(item, leaves, i === dataSlice.emptyData.length - 1));
});
}
}
}
this._onRendering(userData);
if(!virtualRefresh) {
this._refresh(userData);
} else {
this._refreshVirtual(userData);
}
this._onRendered(userData);
if(userData && $.isFunction(userData.afterRefresh)) {
userData.afterRefresh.apply(this, [
userData
]);
}
};
wijgrid.prototype.beginEdit = /** Puts the current cell into edit mode, as long as the allowEditing option is set to "true."
* @example
* $("#element").wijgrid({}
* allowEditing: true,
* currentCellChanged: function (e, args) {
* if ($(e.target).wijgrid("option", "isLoaded")) {
* window.setTimeout(function () {
* $(e.target).wijgrid("beginEdit");
* }, 100);
* }
* }
* });
* @returns {Boolean} True if the cell is successfully put into edit mode, otherwise false.
*/
function () {
return this._beginEditInternal(null);
};
wijgrid.prototype.endEdit = /** Finishes editing the current cell.
* @example
* // endEdit is being called from within the saveChanges function
* function saveChanges() {
* $("#element").wijgrid("endEdit");
* }
* @returns {Boolean} True if the editing was finished successfully, othewise false.
*/
function () {
return this._endEditInternal(null);
};
wijgrid.prototype.ensureControl = /** Moves the column widget options to the wijgrid options and renders the wijgrid. Use this method when you need to re-render the wijgrid and reload remote data from the datasource.
* @example
* // Adds a new row to the viewModel and refreshes the wijgrid
* var len = viewModel.data().length;
* viewModel.data.push(new Person({ ID: len, Company: "New Company" + len, Name: "New Name" + len }));
* $("#element").wijgrid("ensureControl", true);
* @param {Boolean} loadData Determines if the wijgrid must load data from a linked data source before rendering.
*/
function (loadData, userData) {
this._loading();
if(!$.isPlainObject(userData)) {
userData = {
data: null,
afterRefresh: null,
beforeRefresh: null
};
}
userData._wijgridMarker = true;
if(this._initialized) {
this._convertWidgetsToOptions();
} else {
// this._prepareColumnOptions(false); // prepare static columns only
this._prepareColumnOptions(this.options.columns, this.options.columnsAutogenerationMode, this._dataViewWrapper.isDataLoaded() && this._dataViewWrapper.getFieldsInfo(), this._dataViewWrapper.isDataLoaded(), false);
if(!this._dataViewWrapper.isOwnDataView()) {
// map sorting\ filtering\ paging settings from external dataView to the grid's options during initialization stage
(new wijmo.grid.settingsManager(this)).MapDVToWG();
}
}
this._ownerise(true);
// * TODO: move to the doRefresh?
if(this._initialized) {
if(userData && $.isFunction(userData.beforeRefresh)) {
userData.beforeRefresh.apply(this);
}
}
// *
this._field("allowVirtualScrolling", null);
if(loadData === true) {
this._dataViewWrapper.load(userData);
} else {
this.doRefresh(userData);
this._loaded();
}
};
wijgrid.prototype.getCellInfo = /** Gets an instance of the wijmo.grid.cellInfo class that represents the grid's specified cell.
* @example
* var cellInfo = $("#element").wijgrid("getCellInfo", domCell);
* @param {Object} domCell A HTML DOM Table cell object
* @returns {wijmo.grid.cellInfo} Object that represents a cell of the grid.
*/
function (domCell) {
var cellInfo = null;
if(domCell && (domCell = this._findUntilOuterDiv(domCell, {
td: true,
th: true
}))) {
// test affinity
cellInfo = this._view().getAbsoluteCellInfo(domCell);
}
return cellInfo;
};
wijgrid.prototype.getFilterOperatorsByDataType = /** Returns a one-dimensional array of filter operators which are applicable to the specified data type.
* @example
* var operators = $("#element").wijgrid("getFilterOperatorsByDataType", "string");
* @param {String} dataType Specifies the type of data to which you apply the filter operators. Possible values are: "string", "number", "datetime", "currency" and "boolean".
* @returns {wijmo.grid.IFilterOperator[]} A one-dimensional array of filter operators.
*/
function (dataType) {
return (new wijmo.grid.filterOperatorsCache(this)).getByDataType(dataType || "string");
};
wijgrid.prototype.pageCount = /** Gets the number of pages.
* @example
* var pageCount = $("#element").wijgrid("pageCount");
* @returns {Number} The number of pages.
*/
function () {
if(this._customPagingEnabled()) {
return Math.ceil(this.options.totalRows / this.options.pageSize) || 1;
}
return this.options.allowPaging ? (this._dataViewWrapper.dataView()).pageCount() : 1;
};
wijgrid.prototype._serverShaping = function () {
// used to support asp.net C1GridView
return false;
};
wijgrid.prototype._pageIndexForDataView = function () {
/** Infrastructure */
return this.options.pageIndex;
};
wijgrid.prototype.setSize = /** Sets the size of the grid using the width and height parameters.
* @example
* $("#element").wijgrid("setSize", 200, 200);
* @param {String|Number} width Determines the width of the grid.
* @param {String|Number} height Determines the height of the grid.
*/
function (width, height) {
var view = this._view(), scrollValue = {
type: "",
hScrollValue: null,
vScrollValue: null
}, outerDiv = this.outerDiv, frozener = this._field("frozener"), visibleLeaves = this._field("visibleLeaves"), leavesWithFilter = [];
if(view && view.getScrollValue) {
scrollValue = view.getScrollValue();
}
if(width || (width === 0)) {
this._autoWidth = false;
outerDiv.width(width);
}
if(height || (height === 0)) {
this._autoHeight = false;
outerDiv.height(height);
}
$.each(visibleLeaves, function (index, leaf) {
var th = view.getHeaderCell(index), cols = view.getJoinedCols(index);
$(th).css("width", "");
$.each(cols, function (index, col) {
$(col).css("width", "");
});
});
// recalculate sizes
this._view().updateSplits(scrollValue);
if(frozener) {
frozener.refresh();
}
};
wijgrid.prototype.selection = /** Gets an object that manages selection in the grid.
* @example
* // Use the row index to add the row to the selection object
* var selection = $("#element").wijgrid("selection");
* selection.addRows(2);
* @remarks
* See the description of the wijmo.grid.selection class for more details.
* @returns {wijmo.grid.selection} Object that manages selection in the grid.
*/
function () {
var selection = this._field("selection");
if(!selection) {
this._field("selection", selection = new wijmo.grid.selection(this));
}
return selection;
};
wijgrid.prototype._onDataViewCurrentPositionChanged = // * public
function (e, args) {
var cellInfo = this._currentCellFromDataView(), selection = this.selection();
// move currentCell to the new position
cellInfo = this.currentCell(cellInfo);
// * move selection to the current position *
selection.beginUpdate();
selection.clear();
if(cellInfo._isValid()) {
// attach selection to the current cell
selection._startNewTransaction(cellInfo);
selection._selectRange(new wijmo.grid.cellInfoRange(cellInfo, cellInfo), false, false, 0/* none */ , null);
}
selection.endUpdate();
};
wijgrid.prototype._resetDataProperties = function () {
this.options.pageIndex = 0;
var bounds = this._field("viewRenderBounds");
bounds.start = bounds.end = 0;
};
wijgrid.prototype._onDataViewLoading = function () {
this._activateSpinner()// if data loading proccess was triggered outside the wijgrid.
;
this._trigger("dataLoading");
};
wijgrid.prototype._onDataViewReset = function (userData) {
(new wijmo.grid.settingsManager(this)).MapDVToWG();
this._trigger("dataLoaded");
this.doRefresh(userData);
this._loaded();
};
wijgrid.prototype._onDataViewLoaded = function () {
};
wijgrid.prototype._loading = function () {
this._activateSpinner();
this._trigger("loading");
};
wijgrid.prototype._loaded = function () {
this._deactivateSpinner();
this._trigger("loaded");
};
wijgrid.prototype._buildSketchRow = function (wrappedDataItem, leaves) {
var i, len, leaf, cellAttr, value, tmp, sketchRow = [], expando = wijmo.data.Expando.getFrom(wrappedDataItem.values, false), rowAttributes = expando ? expando[wijmo.grid.EXPANDO] : null;
for(i = 0 , len = leaves.length; i < len; i++) {
leaf = leaves[i];
if(wijmo.grid.validDataKey(leaf.dataKey)) {
cellAttr = (rowAttributes && rowAttributes.cellsAttributes) ? rowAttributes.cellsAttributes[leaf.dataKey] : {
};
value = this._dataViewWrapper.getValue(wrappedDataItem.values, leaf.dataKey);
sketchRow.push({
value: this.parse(leaf, value),
__attr: cellAttr || {
},
__style: {
}
});
}
}
(sketchRow).originalRowIndex = wrappedDataItem.originalRowIndex;
(sketchRow).rowType = wijmo.grid.rowType.data;
if(wrappedDataItem.originalRowIndex % 2 !== 0) {
(sketchRow).rowType |= wijmo.grid.rowType.dataAlt;
}
(sketchRow).__style = {
};
(sketchRow).__attr = (rowAttributes && rowAttributes.rowAttributes) ? rowAttributes.rowAttributes : {
};
return sketchRow;
};
wijgrid.prototype._buildSketchRowEmptyDataItem = function (dataItem, leaves, isLastRow) {
var i, len, sketchRow = [], leavesLen = leaves.length;
for(i = 0 , len = dataItem.length; i < len; i++) {
sketchRow.push({
html: dataItem[i],
__attr: {
colSpan: (leavesLen > 0 && isLastRow) ? leavesLen : 1
},
__style: {
}
});
}
(sketchRow).rowType = wijmo.grid.rowType.emptyDataRow;
(sketchRow).__style = {
};
(sketchRow).__attr = {
};
return sketchRow;
};
wijgrid.prototype._prepareColumnOptions = function (columns, generationMode, fieldsInfo, dataLoaded, finalStage) {
wijmo.grid.traverse(columns, function (column) {
column.isBand = ($.isArray(column.columns) || (column.clientType === "c1band"));
column._originalDataKey = column.dataKey;
column._originalHeaderText = column.headerText;
});
// set .isLeaf
new wijmo.grid.bandProcessor().getVisibleHeight(columns, true);
// prepare leaves
var leaves = [], headerRow = this._originalHeaderRowData(), footerRow = this._originalFooterRowData(), autogenerationMode = (generationMode || "").toLowerCase(), self = this;
if(dataLoaded) {
wijmo.grid.columnsGenerator.generate(autogenerationMode, fieldsInfo, columns);
}
wijmo.grid.setTraverseIndex(columns)// build indices (linearIdx, travIdx, parentIdx)
;
// * merge options with defaults and build "pure" leaves list.
wijmo.grid.traverse(columns, function (column) {
// merge options **
column.isBand = ($.isArray(column.columns) || (column.clientType === "c1band"));
wijmo.grid.shallowMerge(column, grid.c1basefield.prototype.options)// merge with the c1basefield default options
;
if(!column.isBand) {
wijmo.grid.shallowMerge(column, grid.c1field.prototype.options)// merge with the c1field default options
;
column.groupInfo = column.groupInfo || {
};
wijmo.grid.shallowMerge(column.groupInfo, grid.c1field.prototype.options.groupInfo);
if(!column.clientType) {
column.clientType = "c1field";
}
} else {
column.clientType = "c1band";
}
// ** merge options
if(column.isLeaf && !column.isBand) {
leaves.push(column);
}
});
this._field("leaves", leaves)// contains static columns only when dataLoaded == false, used by the "dynamic data load" feature during request initialization.
;
if(dataLoaded) {
// assume headerText and footerText
$.each(leaves, $.proxy(function (i, leaf) {
var thIndex = (typeof (leaf.dataKey) === "number") ? leaf.dataKey : i;
if(autogenerationMode === "merge" || leaf.dynamic === true) {
// assume headerText options of the static columns only when using "merge" mode.
if(leaf.headerText === undefined) {
if(self._dataViewWrapper && self._dataViewWrapper.isBoundedToDOM() && headerRow && (thIndex < headerRow.length)) {
leaf.headerText = $.trim(headerRow[thIndex])// copy th
;
} else {
if(wijmo.grid.validDataKey(leaf.dataKey)) {
leaf.headerText = "" + leaf.dataKey// copy dataKey
;
}
}
}
}
if(self._dataViewWrapper && self._dataViewWrapper.isBoundedToDOM() && footerRow && (thIndex < footerRow.length)) {
leaf._footerTextDOM = $.trim(footerRow[thIndex]);
}
}, this));
}
};
wijgrid.prototype._rebuildLeaves = function () {
var tmpColumns = [], leaves = [], tmp;
if(this.options.showRowHeader) {
// append rowHeader
tmp = wijmo.grid.createDynamicField({
clientType: "c1basefield",
dataIndex: -1,
travIdx: -1,
parentVis: true,
allowMoving: false,
allowSizing: false,
allowSort: false,
isRowHeader: true
});
tmp.owner = this;
tmpColumns.push(tmp);
}
$.each(this.options.columns, function (index, item) {
tmpColumns.push(item)// append columns
;
});
// generate span table and build leaves
this._columnsHeadersTable(new wijmo.grid.bandProcessor().generateSpanTable(tmpColumns, leaves));
this._field("leaves", leaves);
this._onLeavesCreated();
};
wijgrid.prototype._onLeavesCreated = function () {
var leaves = this._field("leaves"), fieldsInfo = this._dataViewWrapper.getFieldsInfo(), meta, dataIndex = 0, visLeavesIdx = 0, self = this;
// build visible leaves list, set dataParsers, dataIndices
this._field("visibleLeaves", $.grep(leaves, function (leaf, index) {
leaf.leavesIdx = index;
if(wijmo.grid.validDataKey(leaf.dataKey)) {
leaf.dataIndex = dataIndex++;
} else {
leaf.dataIndex = -1;
}
if(!leaf.isBand) {
meta = fieldsInfo[leaf.dataKey];
if(meta) {
leaf._underlyingDataType = meta.type;
leaf._underlyingDataFormatString = meta.format;
}
if($.isFunction(leaf.dataParser)) {
leaf.dataParser = new (leaf.dataParser)();
}
}
if(leaf.parentVis) {
leaf.visLeavesIdx = visLeavesIdx++;
return true;
}
return false;
}));
};
wijgrid.prototype._allowVirtualScrolling = function () {
var val = this._field("allowVirtualScrolling");
if(!val) {
val = this._field("allowVirtualScrolling", !this.options.allowPaging && this.options.allowVirtualScrolling && (this.options.staticRowIndex < 0) && (this.options.scrollMode !== "none") && !this._hasMerging());
}
return val;
};
wijgrid.prototype._dragndrop = function (force) {
if (typeof force === "undefined") { force = false; }
var dnd = this._field("dragndrop");
if(!dnd && force) {
this._field("dragndrop", dnd = new wijmo.grid.uiDragndrop(this));
}
return dnd;
};
wijgrid.prototype._headerRows = function () {
return this._view().headerRows();
};
wijgrid.prototype._filterRow = function () {
return this._view().filterRow();
};
wijgrid.prototype._rows = function () {
return this._view().bodyRows();
};
wijgrid.prototype._localizeFilterOperators = function (locArray) {
var self = this, helper = new wijmo.grid.filterOperatorsCache(this);
$.each(locArray, function (i, o) {
if(o.name) {
var fop = helper.getByName(o.name);
if(fop) {
fop.displayName = o.displayName;
}
}
});
};
wijgrid.prototype._selectionui = function (force) {
var selectionui = this._field("selectionui");
if(!selectionui && force) {
this._field("selectionui", selectionui = new wijmo.grid.uiSelection(this));
}
return selectionui;
};
wijgrid.prototype._postset_allowColMoving = /*_setPageCount (dataSlice) {
this._field("pageCount", Math.ceil(dataSlice.totalRows / this.options.pageSize) || 1);
},*/
// * propeties (pre-\ post-)
function (value, oldValue) {
var self = this;
$.each(this.columns(), function (idx, wijField) {
if(value) {
self._dragndrop(true).attach(wijField);
} else {
self._dragndrop(true).detach(wijField);
}
});
var groupedWidgets = this._field("groupedWidgets");
if(groupedWidgets) {
$.each(groupedWidgets, function (idx, wijField) {
if(value) {
self._dragndrop(true).attach(wijField);
} else {
self._dragndrop(true).detach(wijField);
}
});
}
};
wijgrid.prototype._postset_allowSorting = function (value, oldValue) {
this.ensureControl(false);
};
wijgrid.prototype._postset_columns = function (value, oldValue) {
this._initialized = false;
this.ensureControl(true);
};
wijgrid.prototype._postset_allowPaging = function (value, oldValue) {
this.ensureControl(true);
};
wijgrid.prototype._postset_culture = function (value, oldValue) {
//this._field("closestCulture", Globalize.findClosestCulture(this.options.culture));
throw "read-only";
};
wijgrid.prototype._postset_customFilterOperators = function (value, oldValue) {
var dataView = this._dataViewWrapper.dataView();
};
wijgrid.prototype._postset_data = function (value, oldValue) {
this._ownerise(false);
wijmo.grid.traverse(this.options.columns, function (column, columns) {
if(column.dynamic) {
// remove autogenerated columns
var idx = $.inArray(column, columns);
if(idx >= 0) {
columns.splice(idx, 1);
}
} else {
// restore original values
column.dataKey = column._originalDataKey;
column.headerText = column._originalHeaderText;
}
});
this._initialized = false;
// this._resetDataProperties();
if(this._dataViewWrapper) {
this._dataViewWrapper.dispose();
}
this._dataViewWrapper = new wijmo.grid.dataViewWrapper(this);
this.ensureControl(true);
};
wijgrid.prototype._postset_disabled = function (value, oldValue) {
// update children widgets
var self = this, view = this._view();
wijmo.grid.iterateChildrenWidgets(this.outerDiv, function (index, widget) {
if(widget !== self) {
widget.option("disabled", value);
}
});
if(view) {
view.ensureDisabledState();
}
};
wijgrid.prototype._postset_groupIndent = function (value, oldValue) {
this.ensureControl(false);
};
wijgrid.prototype._postset_groupAreaCaption = function (value, oldValue) {
var groupedColumns = this._groupedColumns();
if(this.$groupArea && (!groupedColumns || !groupedColumns.length)) {
// update html when the group area is empty only.
this.$groupArea.html(value || " ");
}
};
wijgrid.prototype._postset_highlightCurrentCell = function (value, oldValue) {
var currentCell = this.currentCell();
if(currentCell && currentCell._isValid()) {
this._highlightCellPosition(currentCell, value);
}
};
wijgrid.prototype._preset_pageIndex = function (value, oldValue) {
if(isNaN(value)) {
throw "out of range";
}
var pageCount = this.pageCount(), fn = function (val) {
if(val > pageCount - 1) {
val = pageCount - 1;
}
if(val < 0) {
val = 0;
}
return val;
}, args;
value = fn(value);
if(this.options.allowPaging && value !== oldValue) {
args = {
newPageIndex: value
};
if(!this._onPageIndexChanging(args)) {
value = oldValue;
} else {
value = fn(args.newPageIndex);
}
}
return value;
};
wijgrid.prototype._postset_pageIndex = function (value, oldValue) {
if(this.options.allowPaging) {
var args = {
newPageIndex: value
};
if(this._customPagingEnabled()) {
this._convertWidgetsToOptions();
this._onPageIndexChanged(args)// Allow user the ability to load a new data and refresh the grid.
;
} else {
this.ensureControl(true, {
afterRefresh: function () {
this._onPageIndexChanged(args);
}
});
}
}
};
wijgrid.prototype._preset_pageSize = function (value, oldValue) {
if(isNaN(value)) {
throw "out of range";
}
if(value <= 0) {
value = 1;
}
return value;
};
wijgrid.prototype._postset_pageSize = function (value, oldValue) {
this._resetDataProperties();
if(this.options.allowPaging && !this._customPagingEnabled()) {
this.ensureControl(true);
}
};
wijgrid.prototype._postset_pagerSettings = function (value, oldValue) {
this.ensureControl(false);
};
wijgrid.prototype._postset_scrollMode = function (value, oldValue) {
this.ensureControl(false);
};
wijgrid.prototype._postset_selectionMode = function (value, oldValue) {
var selection = this.selection(), currentCell = this.currentCell(), hasSelection = this.selection().selectedCells().length();
selection.beginUpdate();
selection.clear();
if(currentCell && currentCell._isValid() && hasSelection) {
selection._selectRange(new wijmo.grid.cellInfoRange(currentCell, currentCell), false, false, 0/* none */ , null);
}
selection.endUpdate();
this._view().toggleDOMSelection(value === "none")// disable or enable DOM selection
;
};
wijgrid.prototype._postset_showFilter = function (value, oldValue) {
this.ensureControl(false);
};
wijgrid.prototype._postset_showGroupArea = function (value, oldValue) {
this.ensureControl(false);
};
wijgrid.prototype._postset_showRowHeader = function (value, oldValue) {
this.ensureControl(false);
};
wijgrid.prototype._postset_staticRowIndex = function () {
if(this.options.scrollMode !== "none") {
// staticRowIndex is ignored when scrolling is turned off.
this.ensureControl(false);
}
};
wijgrid.prototype._postset_staticColumnIndex = function () {
if(this.options.scrollMode !== "none") {
this.ensureControl(false);
}
};
wijgrid.prototype._postset_allowVirtualScrolling = function (value, oldValue) {
this.ensureControl(false);
};
wijgrid.prototype._preset_allowVirtualScrolling = function (value, oldValue) {
if(isNaN(value) || value < 0) {
throw "out of range";
}
return value;
};
wijgrid.prototype._activateSpinner = // * propeties (pre-\ post-)
// * private
function () {
if(!this._spinnerIsActivated) {
var wijCSS = this.options.wijCSS, loadingText = this.outerDiv.append("<div class=\"wijmo-wijgrid-overlay " + wijCSS.overlay + "\"></div>" + "<span class=\"wijmo-wijgrid-loadingtext " + wijCSS.content + " " + wijCSS.cornerAll + "\">" + "<span class=\"" + wijCSS.icon + " ui-icon-clock\"></span>" + this.options.loadingText + "</span>").find("> .wijmo-wijgrid-loadingtext");
loadingText.position({
my: "center",
at: "center center",
of: this.outerDiv,
collision: "none"
});
this._spinnerIsActivated = true;
}
};
wijgrid.prototype._customPagingEnabled = function () {
return this.options.allowPaging && this.options.totalRows >= 0;
};
wijgrid.prototype._deactivateSpinner = function () {
if(this._spinnerIsActivated) {
try {
this.outerDiv.find("> .wijmo-wijgrid-overlay, > .wijmo-wijgrid-loadingtext").remove();
}finally {
this._spinnerIsActivated = false;
}
}
};
wijgrid.prototype._columnWidgetsFactory = function ($node, columnOpt) {
var columnWidget, clientType = columnOpt.clientType;
if(!clientType && columnOpt.isBand) {
clientType = "c1band";
}
columnOpt = $.extend({
}, columnOpt, {
disabled: this.options.disabled
});
try {
$.data($node[0], "wijgridowner", this)// pass owner to the widget constructor
;
switch(clientType) {
case "c1basefield":
columnWidget = $node.c1basefield(columnOpt);
break;
case "c1band":
columnWidget = $node.c1band(columnOpt);
break;
default:
columnWidget = $node.c1field(columnOpt);
}
}finally {
$.removeData($node[0], "wijgridowner");
}
return columnWidget;
};
wijgrid.prototype._convertWidgetsToOptions = function () {
if(this._initialized && this._mergeWidgetsWithOptions) {
this._ownerise(false);
this._widgetsToOptions();
this._ownerise(true);
}
};
wijgrid.prototype._field = function (name, value) {
return wijmo.grid.dataPrefix(this.element, this._data$prefix, name, value);
};
wijgrid.prototype._removeField = function (name) {
var internalDataName = this._data$prefix + name;
this.element.removeData(internalDataName);
};
wijgrid.prototype._prepareTotalsRequest = function (isLocal) {
var leaves = this._field("leaves"), result, test;
if(!leaves || !this.options.showFooter) {
return [];
}
result = $.map((leaves), function (element, index) {
if(!element.isBand && wijmo.grid.validDataKey(element.dataKey) && element.aggregate && element.aggregate !== "none") {
if(isLocal) {
return [
{
column: element,
aggregate: element.aggregate
}
];
} else {
return [
{
dataKey: element.dataKey,
aggregate: element.aggregate
}
];
}
}
return null;
});
return result;
};
wijgrid.prototype._widgetsToOptions = function () {
var colOptionsList = wijmo.grid.flatten(this.options.columns);
$.each(this.columns(), function (index, colWidget) {
delete colWidget.options.columns// only options of the column itself will be merged at the next step.
;
var congruentColOption = colOptionsList[colWidget.options.travIdx];
$.extend(true, congruentColOption, colWidget.options);
congruentColOption.filterValue = colWidget.options.filterValue;
congruentColOption.filterOperator = colWidget.options.filterOperator;
});
};
wijgrid.prototype._recreateColumnWidgets = function () {
$.each(this.columns(), function (index, item) {
item.destroy();
});
var columns = [], headerRows = this._headerRows(), visibleColumns, i, len, column, headerRowObj, th, columnWidget;
if(/* tHead.length*/ headerRows && headerRows.length()) {
visibleColumns = []// visible bands and leaves
;
wijmo.grid.traverse(this.options.columns, function (column) {
if(column.parentVis) {
visibleColumns.push(column);
}
});
for(i = 0 , len = visibleColumns.length; i < len; i++) {
column = visibleColumns[i];
headerRowObj = headerRows.item(column.thY);
th = wijmo.grid.rowAccessor.getCell(headerRowObj, column.thX);
columnWidget = this._columnWidgetsFactory($(th), column);
columns.push(columnWidget.data(wijmo.grid.widgetName(columnWidget)))// store actual widget instance
;
}
}
this._field("columns", columns);
};
wijgrid.prototype._groupedColumns = function (force) {
var result;
force = !(result = this._field("groupedColumns")) || force;
if(force) {
result = [];
var leaves = this._field("leaves") || [], rebuildIndexes = false, isGrouped = function (column) {
return column.groupInfo && column.groupInfo.position && (column.groupInfo.position !== "none");
};
$.each(leaves, function (i, column) {
if(isGrouped(column)) {
rebuildIndexes = rebuildIndexes || (column.groupedIndex === undefined);
if(!rebuildIndexes) {
result.push(column);
}
} else {
delete column.groupedIndex;
}
});
if(rebuildIndexes) {
$.each(leaves, function (i, column) {
if(isGrouped(column)) {
column.groupedIndex = result.length;
result.push(column);
}
});
} else {
result.sort(function (a, b) {
return a.groupedIndex - b.groupedIndex;
});
$.each(result, function (i, column) {
column.groupedIndex = i;
});
}
this._field("groupedColumns", result);
}
return result || [];
};
wijgrid.prototype._ownerise = function (flag) {
if(flag) {
var self = this;
wijmo.grid.traverse(this.options.columns, function (column) {
column.owner = self;
var tmp, i, len;
if((tmp = column.groupInfo)) {
tmp.owner = column;
if(tmp.expandInfo) {
for(i = 0 , len = tmp.expandInfo.length; i < len; i++) {
tmp.expandInfo[i].owner = tmp;
}
}
}
});
} else {
wijmo.grid.traverse(this.options.columns, function (column) {
delete column.owner;
var tmp, i, len;
if((tmp = column.groupInfo)) {
delete tmp.owner;
if(tmp.expandInfo) {
for(i = 0 , len = tmp.expandInfo.length; i < len; i++) {
delete tmp.expandInfo[i].owner;
}
}
}
});
}
};
wijgrid.prototype._ensureRenderBounds = function (bounds) {
var total = this._totalRowsCount();// sketchTable.length or totalRows -- depends on data mode.
if(bounds.start < 0) {
bounds.start = 0;
}
bounds.start = Math.min(bounds.start, total - 1);
if(bounds.end < 0) {
bounds.end = 0;
}
bounds.end = Math.min(bounds.end, total - 1);
return bounds;
};
wijgrid.prototype._refresh = function (userData) {
// apply grouping
new wijmo.grid.grouper().group(this, this.sketchTable, this._field("leaves"));
// apply merging
new wijmo.grid.merger().merge(this.sketchTable, this._field("visibleLeaves"));
var bounds = this._field("viewRenderBounds");
this._ensureRenderBounds(bounds);
// view
if(this.options.scrollMode !== "none") {
this._field("view", new wijmo.grid.fixedView(this, this._field("viewRenderBounds")));
} else {
this._field("view", new wijmo.grid.flatView(this, this._field("viewRenderBounds")));
}
this._render();
// (re)create iternal widgets
this._ownerise(false);
this._recreateColumnWidgets();
this._ownerise(true);
// pager
if(this.options.allowPaging) {
// top pager
if(this.$topPagerDiv) {
this.$topPagerDiv.wijpager(this._pagerSettings2PagerWidgetSettings()).css("zIndex", 5);
}
// bottom pager
if(this.$bottomPagerDiv) {
this.$bottomPagerDiv.wijpager(this._pagerSettings2PagerWidgetSettings()).css("zIndex", 5);
}
}
// (re)create iternal widgets
};
wijgrid.prototype._refreshVirtual = function (userData) {
var scrollData = userData.virtualScrollData, diffData = {
top: 0,
bottom: 0
};
if(scrollData.data) {
diffData = this._processVirtualData(scrollData);
}
this._updateRowInfos(scrollData, diffData);
this._renderVirtualIntoView(scrollData);
// debug
/*var rows = this._view().bodyRows();
for (var i = 0; i < rows.length(); i++) {
var ri = this._view()._getRowInfo(rows.item(i));
var innerDiv = ri.$rows.find("td:first .wijmo-wijgrid-innercell");
var html = innerDiv.html();
html = "d:" + ri.dataItemIndex + " s:" + ri.sectionRowIndex + " ||" + ri.data[0] + "|| " + html;
innerDiv.html(html);
}*/
// debug
/*if (scrollData.data && scrollData.mode === "reset") {
this._view().vsUI.scrollToRow(scrollData.newBounds.start, true); // original scrollIndex could change due pageSize alignment, so we need to re-set position of the vertical scrollbar.
}*/
};
wijgrid.prototype._updateRowInfos = function (scrollData, diffData) {
var bounds = this._field("viewRenderBounds"), view = this._view(), newBounds = scrollData.newBounds, rows = this._view().bodyRows(), relMatch, i, diff, rowInfo;
switch(scrollData.mode) {
case "reset":
break;
case "overlapBottom":
relMatch = {
start: // zero-based
newBounds.start - bounds.start,
end: bounds.end - bounds.start
};
diff = newBounds.start - bounds.start;
for(i = relMatch.start; i <= relMatch.end; i++) {
rowInfo = view._getRowInfo(rows.item(i), false);
rowInfo.sectionRowIndex -= diff;
rowInfo.dataItemIndex += diffData.top;
view._setRowInfo(rowInfo.$rows, rowInfo);
}
break;
case "overlapTop":
relMatch = {
start: // zero-based
bounds.start - bounds.start,
end: newBounds.end - bounds.start
};
diff = bounds.start - newBounds.start;
for(i = relMatch.start; i <= relMatch.end; i++) {
rowInfo = view._getRowInfo(rows.item(i), false);
rowInfo.sectionRowIndex += diff;
rowInfo.dataItemIndex += diffData.top;
view._setRowInfo(rowInfo.$rows, rowInfo);
}
break;
}
};
wijgrid.prototype._renderVirtualIntoView = function (scrollData) {
var bounds = this._field("viewRenderBounds"), view = this._view(), fnDataItemIndex = function (sketchRow) {
return (sketchRow.rowType & wijmo.grid.rowType.data) ? sketchRow.originalRowIndex : -1;
}, match, i, sketchRow, sectionRowIndex;
switch(scrollData.mode) {
case "reset":
// remove all rows
view._clearBody();
// add new rows
for(i = scrollData.newBounds.start; i <= scrollData.newBounds.end; i++) {
sketchRow = this.sketchTable[i - this._dataOffset];
view._insertBodyRow(sketchRow, -1, fnDataItemIndex(sketchRow), i);
}
view._rebuildOffsets();
break;
case "overlapBottom":
match = {
start: scrollData.newBounds.start,
end: bounds.end
};
// remove rows from the top
for(i = 0; i < match.start - bounds.start; i++) {
view._removeBodyRow(0, false);
}
// add new rows to the bottom
for(i = match.end + 1; i <= scrollData.newBounds.end; i++) {
sketchRow = this.sketchTable[i - this._dataOffset];
view._insertBodyRow(sketchRow, -1, fnDataItemIndex(sketchRow), i);
}
break;
case "overlapTop":
match = {
start: bounds.start,
end: scrollData.newBounds.end
};
// remove rows from the bottom
for(i = 0; i < bounds.end - scrollData.newBounds.end; i++) {
view._removeBodyRow(match.end - match.start + 1, false)// relative index starting from zero.
;
}
// add new tows to the top
sectionRowIndex = 0;
for(i = scrollData.newBounds.start; i < bounds.start; i++) {
sketchRow = this.sketchTable[i - this._dataOffset];
view._insertBodyRow(sketchRow, sectionRowIndex++, fnDataItemIndex(sketchRow), i);
}
break;
default:
// "none", same range
break;
}
};
wijgrid.prototype._processVirtualData = function (scrollData) {
var dvw = this._dataViewWrapper, source = dvw.dataView().getSource(), dataItem, leaves = this._field("leaves"), i, alignedViewBounds, cachedBounds, exceeded = 0, dataDiff = {
top: 0,
bottom: 0
}, rowAttributes, margin = this._serverSideVirtualScrollingMargin();
// * extend underlying data
switch(scrollData.mode) {
case "reset":
// clear
this.sketchTable.splice(0, this.sketchTable.length);
dvw._unsafeSplice(0, source.length);
//this._dataOffset = scrollData.newPageIndex * this.options.pageSize; //
this._dataOffset = scrollData.request.index;
// append
for(i = 0; i < scrollData.data.length; i++) {
dvw._unsafePush(dataItem = scrollData.data[i])// append rows to a dataStore
;
this.sketchTable.push(this._buildSketchRow(dvw._wrapDataItem(dataItem, i), leaves));
}
break;
case "overlapBottom":
// append
for(i = 0; i < scrollData.data.length; i++) {
dvw._unsafePush(dataItem = scrollData.data[i])// append rows to a dataStore
;
this.sketchTable.push(this._buildSketchRow(dvw._wrapDataItem(dataItem, source.length - 1), leaves));
}
dataDiff.bottom = scrollData.data.length;
break;
case "overlapTop":
// prepend
for(i = scrollData.data.length - 1; i >= 0; i--) {
dvw._unsafeSplice(0, 0, dataItem = scrollData.data[i]);
this.sketchTable.splice(0, 0, this._buildSketchRow(dvw._wrapDataItem(dataItem, i), leaves));
}
//this._dataOffset = scrollData.newPageIndex * this.options.pageSize;
this._dataOffset = scrollData.request.index;
dataDiff.top = scrollData.data.length;
break;
}
// extend underlying data *
// * remove cached items exceeded cached bounds
// [margin][pageSize = viewBounds][margin]
alignedViewBounds = this._ensureRenderBounds({
start: scrollData.newBounds.start,
end: scrollData.newBounds.end
});
//start: Math.floor(scrollData.newBounds.start / this.options.pageSize) * this.options.pageSize,
//end: Math.floor(scrollData.newBounds.start / this.options.pageSize) * this.options.pageSize + this.options.pageSize - 1
cachedBounds = {
start: this._dataOffset,
end: this._dataOffset + source.length - 1
};
// remove items from the bottom
exceeded = (cachedBounds.end - alignedViewBounds.end) - margin;
if(exceeded > 0) {
dataDiff.bottom -= exceeded;
dvw._unsafeSplice(source.length - exceeded, exceeded);
this.sketchTable.splice(this.sketchTable.length - exceeded, exceeded);
}
// remove items from the top
exceeded = (alignedViewBounds.start - cachedBounds.start) - margin;
if(exceeded > 0) {
dataDiff.top -= exceeded;
dvw._unsafeSplice(0, exceeded);
this.sketchTable.splice(0, exceeded);
this._dataOffset += exceeded;
}
// remove data exceeded cached bounds *
// * update metadata
for(i = 0; i < this.sketchTable.length; i++) {
this.sketchTable[i].originalRowIndex = i;
}
// update metadata *
dvw._refreshSilent();
return dataDiff;
};
wijgrid.prototype._needToCreatePagerItem = function () {
return this.options.allowPaging === true;
};
wijgrid.prototype._isMobileEnv = function () {
return this._isMobile;
};
wijgrid.prototype._render = function () {
var view = this._view(), o = this.options, wijCSS = this.options.wijCSS, content;
view.render();
// YK: for fixing pager is not align to top and bottom when header is fixed.
content = this.outerDiv;
if(o.scrollMode !== "none") {
// fixed header content
content = this.outerDiv.find("div.wijmo-wijgrid-scroller:first");
}
this.$superPanelHeader = null;
// ** top pager (top div)
if(this.$topPagerDiv) {
if(this.$topPagerDiv.data("wijmo-wijpager")) {
this.$topPagerDiv.wijpager("destroy");
}
this.$topPagerDiv.remove();
}
this.$topPagerDiv = null;
if(this._needToCreatePagerItem() && ((o.pagerSettings.position === "top") || (o.pagerSettings.position === "topAndBottom"))) {
if(!this.$topPagerDiv) {
content.prepend(this.$superPanelHeader = $("<div class=\"wijmo-wijsuperpanel-header\"></div>"));
this.$superPanelHeader.prepend(this.$topPagerDiv = $("<div class=\"wijmo-wijgrid-header " + wijCSS.header + " " + wijCSS.cornerTop + "\"></div>"));
}
}
// top pager **
if(o.showGroupArea) {
this._processGroupArea(content);
} else {
this.$groupArea = null;
}
// ** bottom pager (bottom div)
if(this.$bottomPagerDiv) {
if(this.$bottomPagerDiv.data("wijmo-wijpager")) {
this.$bottomPagerDiv.wijpager("destroy");
}
this.$bottomPagerDiv.remove();
}
this.$bottomPagerDiv = null;
if(this._needToCreatePagerItem() && ((o.pagerSettings.position === "bottom") || (o.pagerSettings.position === "topAndBottom"))) {
if(!this.$bottomPagerDiv) {
content.append(this.$bottomPagerDiv = $("<div class=\"wijmo-wijgrid-footer wijmo-wijsuperpanel-footer " + wijCSS.stateDefault + " " + wijCSS.cornerBottom + "\"></div>"));
}
}
// bottom pager **
};
wijgrid.prototype._processGroupArea = function (content) {
var self = this, groupCollection = this._groupedColumns(), groupWidgetCollection = [];
this.$groupArea = $("<div class=\"" + this.options.wijCSS.content + " " + this.options.wijCSS.helperClearFix + "\"></div>");
if(groupCollection.length > 0) {
$.each(groupCollection, function (index, item) {
var groupElement = $("<a href=\"#\"></a>").appendTo(self.$groupArea);
try {
$.data(groupElement[0], "wijgridowner", self)// pass owner to the constructor
;
groupElement.c1groupedfield($.extend({
}, {
allowMoving: item.allowMoving,
allowSort: item.allowSort,
dataIndex: item.dataIndex,
headerText: item.headerText,
isBand: item.isBand,
isLeaf: item.isLeaf,
linearIdx: item.linearIdx,
parentIdx: item.parentIdx,
sortDirection: item.sortDirection,
travIdx: item.travIdx,
groupedIndex: item.groupedIndex
}, {
disabled: self.options.disabled
}));
}finally {
$.removeData(groupElement[0], "wijgridowner");
}
groupWidgetCollection.push(groupElement.data("wijmo-c1groupedfield"));
});
} else {
this.$groupArea.addClass("wijmo-wijgrid-group-area").css("padding", 0).html(// disable padding (inherited)
this.options.groupAreaCaption || " ");
}
this._field("groupedWidgets", groupWidgetCollection);
if(!this.$superPanelHeader) {
content.prepend(this.$superPanelHeader = $("<div class=\"wijmo-wijsuperpanel-header\"></div>"));
}
this.$superPanelHeader.prepend(this.$groupArea);
this._dragndrop(true).attachGroupArea(this.$groupArea);
};
wijgrid.prototype._attachEvents = function () {
var view = this._view(), $fe = view.focusableElement(), self = this;
$fe.bind("keydown." + this.widgetName, $.proxy(this._onKeyDown, this));
$fe.bind("keypress." + this.widgetName, $.proxy(this._onKeyPress, this));
$.each(view.subTables(), function (index, element) {
var domTable = element.element();
if(domTable) {
if(domTable.tHead) {
$(domTable.tHead).bind("click." + self.widgetName, $.proxy(self._onClick, self));
}
if(domTable.tBodies.length) {
$(domTable.tBodies[0]).bind("click." + self.widgetName, $.proxy(self._onClick, self)).bind("dblclick." + self.widgetName, $.proxy(self._onDblClick, self)).bind("mousemove." + self.widgetName, $.proxy(self._onMouseMove, self)).bind("mouseout." + self.widgetName, $.proxy(self._onMouseOut, self));
}
}
});
$(window).bind("resize." + this.widgetName + "." + this._eventUID, $.proxy(this._onWindowResize, this));
};
wijgrid.prototype._detachEvents = function (destroy) {
var view = this._view(), self = this, $fe;
this._windowResizeTimer = 0;
$(window).unbind("resize." + this.widgetName + "." + this._eventUID);
if(view) {
$fe = view.focusableElement();
$fe.unbind("keydown." + this.widgetName);
$fe.unbind("keypress." + this.widgetName);
$.each(view.subTables(), function () {
var domTable = this.element();// item (this) is a htmlTableAccessor instance
if(domTable) {
if(domTable.tHead) {
$(domTable.tHead).unbind("." + self.widgetName);
}
if(domTable.tBodies.length) {
$(domTable.tBodies[0]).unbind("." + self.widgetName);
}
}
});
}
};
wijgrid.prototype._handleSort = function (column, multiSort) {
var columns = this.options.columns, travIdx = column.travIdx, newSortDirection, args;
//if (this.options.allowSorting && ($.inArray(columnWidget, columns) >= 0)) {
if(column && this.options.allowSorting) {
newSortDirection = ((column.sortDirection === "none") ? "ascending" : ((column.sortDirection === "ascending") ? "descending" : "ascending"));
args = {
column: column,
sortDirection: newSortDirection,
sortCommand: column.dataKey + " " + (newSortDirection === "ascending" ? "asc" : "desc")
};
if(this._onColumnSorting(args)) {
column.sortDirection = args.sortDirection;
if(multiSort) {
column.sortOrder = this._customSortOrder++;
} else {
this._customSortOrder = 1000// reset to default
;
// reset sortDirection for all column widgets except sorting one and grouped columns
$.each(this.columns(), function (index, item) {
item.options.sortOrder = 0;
if(item.options.travIdx !== travIdx && !(item.options.groupInfo && item.options.groupInfo.position !== "none")) {
item.options.sortDirection = "none";
}
});
// ensure invisible columns.
wijmo.grid.traverse(columns, function (item) {
item.sortOrder = 0;
if(item.travIdx !== travIdx && !(item.groupInfo && item.groupInfo.position !== "none")) {
item.sortDirection = "none";
}
});
}
args = {
column: column,
sortDirection: column.sortDirection,
sortCommand: column.dataKey + " " + (column.sortDirection === "ascending" ? "asc" : "desc")
};
if(this._customPagingEnabled()) {
this._convertWidgetsToOptions();
this._onColumnSorted(args)// Allow user the ability to load a new data and refresh the grid.
;
} else {
this.ensureControl(true, {
afterRefresh: function () {
this._onColumnSorted(args);
}
});
}
}
}
};
wijgrid.prototype._pagerSettings2PagerWidgetSettings = function () {
return $.extend({
}, this.options.pagerSettings, {
disabled: this.options.disabled,
pageCount: this.pageCount(),
pageIndex: this.options.pageIndex,
pageIndexChanging: $.proxy(this._onPagerWidgetPageIndexChanging, this),
pageIndexChanged: $.proxy(this._onPagerWidgetPageIndexChanged, this)
});
};
wijgrid.prototype._handleDragnDrop = function (dragTravIdx, dropTravIdx, at, dragInGroup, dropInGroup) {
var drag = wijmo.grid.getColumnByTravIdx(this.options.columns, dragTravIdx), drop = wijmo.grid.getColumnByTravIdx(this.options.columns, dropTravIdx), dragSource = dragInGroup ? "groupArea" : "columns", dropSource = dropInGroup ? "groupArea" : "columns";
if(dropInGroup) {
// drag is dropped into the group area
if(this._onColumnGrouping({
drag: drag.found,
drop: drop ? drop.found : null,
dragSource: dragSource,
dropSource: dropSource,
at: at
})) {
this.ensureControl(true, {
beforeRefresh: function () {
if(!drop) {
// drag is dropped into the empty group area.
drag.found.groupedIndex = 0;
} else {
switch(at) {
case "left":
drag.found.groupedIndex = drop.found.groupedIndex - 0.5;
break;
case "right":
drag.found.groupedIndex = drop.found.groupedIndex + 0.5;
break;
}
}
if(!dragInGroup) {
$.extend(true, drag.found, {
groupInfo: {
position: "header"
}
});
}
},
afterRefresh: function () {
this._onColumnGrouped({
drag: drag.found,
drop: drop ? drop.found : null,
dragSource: dragSource,
dropSource: dropSource,
at: at
});
}
});
}
} else {
if(this._onColumnDropping({
drag: drag.found,
drop: drop.found,
at: at
})) {
this.ensureControl(false, {
beforeRefresh: function () {
/* modifying the wijgrid.options.columns option */
drag.at.splice(drag.found.linearIdx, 1);
//because when drag is before drop, the index of drop is affected.
switch(at) {
case "left":
if(drag.at === drop.at && drag.found.linearIdx < drop.found.linearIdx) {
drop.at.splice(drop.found.linearIdx - 1, 0, drag.found);
} else {
drop.at.splice(drop.found.linearIdx, 0, drag.found);
}
break;
case "right":
if(drag.at === drop.at && drag.found.linearIdx < drop.found.linearIdx) {
drop.at.splice(drop.found.linearIdx, 0, drag.found);
} else {
drop.at.splice(drop.found.linearIdx + 1, 0, drag.found);
}
break;
case "center":
// drop is a band
drop.found.columns.push(drag.found);
break;
}
// rebuild indices (linearIdx, travIdx, parentIdx)
wijmo.grid.setTraverseIndex(this.options.columns);
},
afterRefresh: function () {
this._onColumnDropped({
drag: drag.found,
drop: drop.found,
at: at
});
}
});
}
}
};
wijgrid.prototype._handleFilter = function (column, rawOperator, rawValue) {
var operator = (new wijmo.grid.filterOperatorsCache(this)).getByName(rawOperator), value, ok, args;
if(operator) {
if(operator.arity > 1) {
// check value
value = this.parse(column.options, rawValue);
ok = (value !== null && (wijmo.grid.getDataType(column.options) === "string" || !isNaN(value)));
} else {
ok = true;
}
if(ok) {
args = {
column: column.options,
operator: operator.name,
value: value
};
if(this._onColumnFiltering(args)) {
column.options.filterValue = args.value;
column.options.filterOperator = args.operator;
this._resetDataProperties();
if(this._customPagingEnabled()) {
this._convertWidgetsToOptions();
this._onColumnFiltered({
column: column.options
})// Allow user the ability to load a new data and refresh the grid.
;
} else {
this.ensureControl(true, {
afterRefresh: function () {
this._onColumnFiltered({
column: column.options
});
}
});
}
}
}
}
};
wijgrid.prototype._handleUngroup = function (columnTravIdx) {
var column = wijmo.grid.getColumnByTravIdx(this.options.columns, columnTravIdx), result;
if(column && column.found) {
result = column.found;
if(this._onColumnUngrouping({
column: result
})) {
this.ensureControl(true, {
beforeRefresh: function () {
delete result.groupedIndex;
$.extend(true, result, {
groupInfo: {
position: "none"
}
});
},
afterRefresh: function () {
this._onColumnUngrouped({
column: result
});
}
});
}
}
};
wijgrid.prototype._onVirtualScrolling = function (newBounds, request, mode, scrollIndex, completeCallback, data/* opt*/ ) {
this.ensureControl(true, {
virtualScrollData: {
newBounds: newBounds,
request: request,
mode: mode,
data: data
},
afterRefresh: function (userData) {
var bounds = this._field("viewRenderBounds");
// set new bounds
$.extend(bounds, userData.virtualScrollData.newBounds);
this._view()._adjustRowsHeights();
completeCallback(scrollIndex);
}
});
};
wijgrid.prototype._handleVirtualScrolling = function (scrollIndex, completeCallback) {
var bounds = this._field("viewRenderBounds"), newBounds = this._ensureRenderBounds({
start: scrollIndex,
end: scrollIndex + this.options.pageSize - 1
}), cachedDataBounds = this._ensureRenderBounds({
start: this._dataOffset,
end: this._dataOffset + this._dataViewWrapper.dataView().count() - 1
}), request = null, mode;
// check viewBounds
if(newBounds.start > bounds.end || newBounds.end < bounds.start) {
// mode = "reset"
mode = "reset";
} else {
if(newBounds.start > bounds.start) {
mode = "overlapBottom";
} else {
if(newBounds.start < bounds.start) {
mode = "overlapTop";
} else {
// same range, "none"
}
}
}
// check dataBounds
if(this._serverSideVirtualScrolling()) {
switch(mode) {
case "reset":
// align view bounds by pageSize
request = {
index: scrollIndex,
maxCount: // (scrollIndex == newBounds.start)
this.options.pageSize
};
/*newPageIndex = Math.floor(scrollIndex / this.options.pageSize);
scrollIndex = newPageIndex * this.options.pageSize; // note: scrollIndex can change
newBounds = this._ensureRenderBounds({
start: scrollIndex,
end: scrollIndex + this.options.pageSize - 1
});*/
break;
case "overlapBottom":
if(newBounds.end > cachedDataBounds.end) {
request = {
index: cachedDataBounds.end + 1,
maxCount: this.options.pageSize
};
}
/*newPageIndex = Math.floor(newBounds.end / this.options.pageSize);
alignIndex = newPageIndex * this.options.pageSize;
if (alignIndex <= cachedDataBounds.end) {
newPageIndex = null;
}*/
break;
case "overlapTop":
if(newBounds.start < cachedDataBounds.start) {
request = {
index: Math.max(0, cachedDataBounds.start - this.options.pageSize),
maxCount: 0
};
request.maxCount = cachedDataBounds.start - request.index;
}
/*newPageIndex = Math.floor(newBounds.start / this.options.pageSize);
alignIndex = newPageIndex * this.options.pageSize;
if (alignIndex >= cachedDataBounds.start) {
newPageIndex = null;
}*/
break;
}
}
if(mode !== "none") {
//this._onVirtualScrolling(newBounds, newPageIndex, mode, scrollIndex, completeCallback); // note: scrollIndex could be changed
this._onVirtualScrolling(newBounds, request, mode, scrollIndex, completeCallback)// note: scrollIndex could be changed
;
}
};
wijgrid.prototype._serverSideVirtualScrolling = function () {
return false;
};
wijgrid.prototype._serverSideVirtualScrollingMargin = function () {
return this.options.pageSize * 2;
};
wijgrid.prototype._onColumnDropping = // * event handlers
function (args) {
return this._trigger("columnDropping", null, args);
};
wijgrid.prototype._onColumnDropped = function (args) {
this._trigger("columnDropped", null, args);
};
wijgrid.prototype._onColumnGrouping = function (args) {
return this._trigger("columnGrouping", null, args);
};
wijgrid.prototype._onColumnGrouped = function (args) {
this._trigger("columnGrouped", null, args);
};
wijgrid.prototype._onColumnUngrouping = function (args) {
return this._trigger("columnUngrouping", null, args);
};
wijgrid.prototype._onColumnUngrouped = function (args) {
this._trigger("columnUngrouped", null, args);
};
wijgrid.prototype._onColumnFiltering = function (args) {
return this._trigger("filtering", null, args);
};
wijgrid.prototype._onColumnFiltered = function (args) {
this._trigger("filtered", null, args);
};
wijgrid.prototype._onFilterOperatorsListShowing = function (args) {
this._trigger("filterOperatorsListShowing", null, args);
};
wijgrid.prototype._onColumnSorting = function (args) {
return this._trigger("sorting", null, args);
};
wijgrid.prototype._onColumnSorted = function (args) {
this._trigger("sorted", null, args);
};
wijgrid.prototype._onCurrentCellChanged = function (e) {
var o = this.options, currentCell = this._field("currentCell");
// notify dataView
var dataIndex = this._gridDataRowIndexToDataView(currentCell.rowIndex());
this._dataViewWrapper.currentPosition(dataIndex);
//if (o.allowKeyboardNavigation) {
if(o.scrollMode !== "none" && currentCell && !currentCell.isEqual(wijmo.grid.cellInfo.outsideValue)) {
(this._view()).scrollTo(currentCell);
}
//}
this._trigger("currentCellChanged");
if(e && ((e.type || "").toLowerCase() === "click") && this._editBySingleClick()) {
this._beginEditInternal(e);
}
};
wijgrid.prototype._onPageIndexChanging = function (args) {
return this._trigger("pageIndexChanging", null, args);
};
wijgrid.prototype._onPageIndexChanged = function (args) {
this._trigger("pageIndexChanged", null, args);
};
wijgrid.prototype._onPagerWidgetPageIndexChanging = function (sender, args) {
args.handled = true;
};
wijgrid.prototype._onPagerWidgetPageIndexChanged = function (sender, args) {
this._setOption("pageIndex", args.newPageIndex);
};
wijgrid.prototype._onRendering = function (userData) {
var view = this._view();
this._rendered = false;
if(userData.virtualScrollData) {
this.selection().clear()// clear selection
;
if(this.options.highlightCurrentCell) {
this._highlightCellPosition(this.currentCell(), false)// remove highlighning
;
}
} else {
if(view) {
view.dispose();
}
this._detachEvents(false);
this.element.detach();
this.element.empty();
this.outerDiv.empty();
this.outerDiv.append(this.element);
this._field("currentCell", null);
if(this._field("selectionui")) {
this._field("selectionui").dispose();
this._field("selectionui", null);
}
if(this._field("resizer")) {
this._field("resizer").dispose();
this._field("resizer", null);
}
if(this._field("frozener")) {
this._field("frozener").dispose();
this._field("frozener", null);
}
}
this._trigger("rendering");
};
wijgrid.prototype._onRendered = function (userData) {
var view = this._view(), currentCell, resizer, hasSelection = this.selection().selectedCells().length() > 0;
this._rendered = true;
// ** current cell
this._setAttr(view.focusableElement(), "tabIndex", 0)// to handle keyboard\ focus events
;
currentCell = this._currentCellFromDataView();
currentCell._isEdit(false);
if(!currentCell._isValid() || !(currentCell = this.currentCell(currentCell))) {
currentCell = this.currentCell(this._getFirstDataRowCell(0));
}
// current cell **
// ** selection
this._field("selection", null)// always recreate selection object
;
currentCell = this.currentCell();
if(currentCell._isValid() && (hasSelection || this.options.showSelectionOnRender)) {
// attach selection to the current cell
this.selection()._startNewTransaction(currentCell);
this.selection()._selectRange(new wijmo.grid.cellInfoRange(currentCell, currentCell), false, false, 0/* none */ , null);
}
// selection **
if(!userData.virtualScrollData) {
// attach events
this._attachEvents();
// selection ui
this._selectionui(true);
// initialize resizer
resizer = new wijmo.grid.uiResizer(this);
$.each(this.columns(), function (index, colWidget) {
var o = colWidget.options;
if(o.visible && o.parentVis && o.isLeaf) {
resizer.addElement(colWidget);
}
});
this._field("resizer", resizer);
view.updateSplits(this._scrollingState)// restore value
;
//frozener
if(this.options.scrollMode !== "none") {
this._field("frozener", new wijmo.grid.uiFrozener(this));
}
}
this._renderCounter++;
this._trigger("rendered");
};
wijgrid.prototype._onClick = function (e) {
if(!this._canInteract() || !e.target) {
return;
}
var view = this._view(), clickedCell = this._findUntilOuterDiv(e.target, {
td: true,
th: true
}), $row, clickedCellInfo, extendMode = 0, currentCell, selection;
// none
if(clickedCell) {
if($(e.target).hasClass("wijmo-wijgrid-grouptogglebtn")) {
this._onGroupBtnClick(e);
// #29676: stop event from bubbling up to the parent grid (if available)
e.stopPropagation();
return false;
}
$row = $(clickedCell).closest("tr");
if(!$row.length) {
return;
}
clickedCellInfo = view.getAbsoluteCellInfo(clickedCell);
if($row.hasClass("wijmo-wijgrid-datarow") || $row.hasClass("wijmo-wijgrid-headerrow")) {
if(clickedCellInfo.cellIndex() < 0 || clickedCellInfo.rowIndex() < 0) {
// header cell, rowheader cell or filter cell
if(clickedCellInfo.rowIndex() >= 0) {
// rowheader cell
// move current cell to the first cell of the clicked row
clickedCellInfo = new wijmo.grid.cellInfo(0, clickedCellInfo.rowIndex());
extendMode = 2// extend to row
;
} else {
// header cell
// move current cell to the first data cell of the clicked column
clickedCellInfo = this._getFirstDataRowCell(clickedCellInfo.cellIndex());
extendMode = 1// extend to column
;
}
}
this._changeCurrentCell(e, clickedCellInfo, !$(e.target).is(":focus"))// change current cell and set focus to it (if the target element is not already focused)
;
currentCell = this.currentCell();
selection = this.selection();
if(!e.shiftKey || (!selection._multipleRangesAllowed() && this.options.selectionMode.toLowerCase() !== "singlerange")) {
selection._startNewTransaction(currentCell);
}
selection.beginUpdate();
if(e.shiftKey && e.ctrlKey) {
selection._clearRange(new wijmo.grid.cellInfoRange(currentCell, currentCell), extendMode);
} else {
selection._selectRange(new wijmo.grid.cellInfoRange(selection._anchorCell(), currentCell), e.ctrlKey, e.shiftKey, extendMode, null);
}
selection.endUpdate();
}
var cellClickedArgs = {
cell: clickedCellInfo
};
this._trigger("cellClicked", null, cellClickedArgs);
}
};
wijgrid.prototype._onDblClick = function (e) {
if(!this._editBySingleClick()) {
this._beginEditInternal(e);
}
};
wijgrid.prototype._onGroupBtnClick = function (e) {
if(!this._canInteract()) {
return;
}
var $row = $(e.target).closest("tr"), gh = wijmo.grid.groupHelper, groupInfo = gh.getGroupInfo($row[0]), column, group;
if(groupInfo) {
column = gh.getColumnByGroupLevel(this._field("leaves"), groupInfo.level);
if(column) {
group = column.groupInfo.expandInfo[groupInfo.index];
if(group.isExpanded) {
group.collapse();
} else {
group.expand(e.shiftKey);
}
//this._view().ensureHeight(); /*dma*/
this.setSize()// recalculate sizes (#39295)
;
}
}
};
wijgrid.prototype._onKeyDown = function (e) {
if(!this._canInteract()) {
return true;
}
var tag = (e.target).tagName.toLowerCase(), canChangePos = false, curPos, currentCell, selection, keyCodeEnum = wijmo.grid.getKeyCodeEnum();
if((tag === "input" || tag === "option" || tag === "select" || tag === "textarea") && ($(e.target).closest("tr.wijmo-wijgrid-datarow").length === 0)) {
// not a datarow ?
return true;
}
if(this.options.allowEditing) {
// ESC: cancel editing, F2: finish editing
if((e.which === keyCodeEnum.ESCAPE || e.which === 113) && (this.currentCell()._isValid() && this.currentCell()._isEdit())) {
this._endEditInternal(e);
return false;
} else {
if(e.which === 113) {
// F2: start editing
this._beginEditInternal(e);
return false;
}
}
}
if(!this.options.allowKeyboardNavigation || (e.which === keyCodeEnum.TAB)) {
return true;
}
//switch (args.keyCode) {
switch(e.which) {
case keyCodeEnum.LEFT:
case keyCodeEnum.RIGHT:
case keyCodeEnum.DOWN:
case keyCodeEnum.UP:
case keyCodeEnum.PAGE_DOWN:
case keyCodeEnum.PAGE_UP:
case keyCodeEnum.HOME:
case keyCodeEnum.END:
case keyCodeEnum.TAB:
curPos = this._getNextCurrencyPos(this._getDataCellsRange(), this.currentCell(), e.keyCode, e.shiftKey);
canChangePos = this._canMoveToAnotherCell(e.target, e.which)// TODO: add tab navigation
;
break;
}
if(canChangePos) {
this._changeCurrentCell(e, new wijmo.grid.cellInfo(curPos.cellIndex, curPos.rowIndex), true)// change current cell and set focus to it
;
currentCell = this.currentCell();
// cell = currentCell.tableCell();
selection = this.selection();
if(!e.shiftKey || (!selection._multipleRangesAllowed() && this.options.selectionMode.toLowerCase() !== "singlerange")) {
selection._startNewTransaction(currentCell);
}
selection.beginUpdate();
selection._selectRange(new wijmo.grid.cellInfoRange(selection._anchorCell(), currentCell), false, e.shiftKey, 0/* none */ , null);
selection.endUpdate();
// TODO: tab navigation
return false;// stop bubbling
}
return true;
};
wijgrid.prototype._onKeyPress = function (e) {
if(this._canInteract() && this.options.allowEditing) {
var charCode = e.which, currentCell = this.currentCell(), tag, table, domSubTables;
if(charCode && currentCell._isValid() && !currentCell._isEdit()) {
tag = (e.target).tagName.toLowerCase();
if(tag !== "input" && tag !== "option" && tag !== "select" && tag !== "textarea") {
table = $(e.target).closest(".wijmo-wijgrid-table");
// if (table.length && (table[0] === this.$table[0])) {
if(table.length) {
domSubTables = $.map(this._view().subTables(), function (item, index) {
return item.element();
});
if($.inArray(table[0], domSubTables) >= 0) {
if($.wij.charValidator.isPrintableChar(String.fromCharCode(charCode))) {
//new wijmo.grid.cellEditorHelper().currentCellEditStart(this, args);
this._beginEditInternal(e);
return false;
}
}
}
}
}
}
};
wijgrid.prototype._onMouseMove = function (e) {
var view = this._view(), frozener = this._field("frozener"), hoveredCell, $hoveredRow, hoveredCellInfo, rowIndex, rowObj, rowInfo, $rs = wijmo.grid.renderState;
if(!this.options.highlightOnHover || !this._canInteract() || (frozener && frozener.inProgress())) {
return;
}
hoveredCell = this._findUntilOuterDiv(e.target, {
td: true,
th: true
});
if(hoveredCell) {
$hoveredRow = $(hoveredCell).closest("tr");
if(!$hoveredRow.length || !($hoveredRow.hasClass("wijmo-wijgrid-datarow") || $hoveredRow.hasClass("wijmo-wijgrid-headerrow"))) {
return;
}
hoveredCellInfo = view.getAbsoluteCellInfo(hoveredCell);
rowIndex = this._field("hoveredRow")// previous row index
;
if(hoveredCellInfo.rowIndex() !== rowIndex) {
// clear previous row
if(rowIndex !== undefined) {
rowObj = this._rows().item(rowIndex);
if(rowObj) {
rowInfo = view._getRowInfo(rowObj);
view._changeRowRenderState(rowInfo, $rs.hovered, false);
this.rowStyleFormatter.format(rowInfo);
}
}
// highlight current row
rowIndex = hoveredCellInfo.rowIndex();
this._field("hoveredRow", rowIndex);
if(rowIndex >= 0) {
rowObj = this._rows().item(rowIndex);
if(rowObj) {
rowInfo = view._getRowInfo(rowObj);
view._changeRowRenderState(rowInfo, $rs.hovered, true);
this.rowStyleFormatter.format(rowInfo);
}
}
}
}
};
wijgrid.prototype._onMouseOut = function (e) {
if(!this._canInteract()) {
return;
}
if($(e.relatedTarget).closest(".wijmo-wijgrid-data").length === 0) {
// remove hovering
var hovRowIndex = this._field("hoveredRow"), rowObj, rowInfo, view = this._view();
if(hovRowIndex >= 0) {
rowObj = this._rows().item(hovRowIndex);
if(rowObj) {
rowInfo = view._getRowInfo(rowObj);
view._changeRowRenderState(rowInfo, wijmo.grid.renderState.hovered, false);
this.rowStyleFormatter.format(rowInfo);
}
}
}
};
wijgrid.prototype._onWindowResize = function (e) {
var self = this;
// reset timer
if(this._windowResizeTimer > 0) {
window.clearTimeout(this._windowResizeTimer);
this._windowResizeTimer = 0;
}
if(this._windowResizeTimer !== -1) {
this._windowResizeTimer = window.setTimeout(function () {
self._windowResizeTimer = -1// lock
;
try {
if(!self._destroyed && self._initialized && self.element.parent().length) {
self.setSize();
}
}finally {
self._windowResizeTimer = 0// unlock
;
}
}, 50);
}
};
wijgrid.prototype._fieldResized = // * event handlers
// * resizing
function (fieldWidget, oldWidth, newWidth) {
if(oldWidth < 0) {
oldWidth = 0;
}
if(newWidth <= 0) {
newWidth = 1;
}
var resizingArgs = {
column: fieldWidget.options,
oldWidth: oldWidth,
newWidth: newWidth
};
if(this._trigger("columnResizing", null, resizingArgs) !== false) {
if(isNaN(resizingArgs.newWidth) || resizingArgs.newWidth < 0) {
resizingArgs.newWidth = 1;
}
fieldWidget.option("width", resizingArgs.newWidth)// update widget option first (tfs issue 32108)
;
var resizedArgs = {
column: fieldWidget.options
};
this._trigger("columnResized", null, resizedArgs);
}
};
wijgrid.prototype._changeCurrentCell = // * resizing
// * currentCell
function (e, cellInfo, setFocus) {
var currentCell = this.currentCell(), dataRange = this._getDataCellsRange(), currentCellChangingArgs, cellEditCompleted, highlight = this.options.highlightCurrentCell, domCell;
// if cellInfo has a valid value
if((dataRange._isValid() && dataRange._containsCellInfo(cellInfo)) || (cellInfo.isEqual(wijmo.grid.cellInfo.outsideValue))) {
// other cell than current cell
if(currentCell.cellIndex() !== cellInfo.cellIndex() || currentCell.rowIndex() !== cellInfo.rowIndex()) {
currentCellChangingArgs = {
cellIndex: cellInfo.cellIndex(),
rowIndex: cellInfo.rowIndex(),
oldCellIndex: currentCell.cellIndex(),
oldRowIndex: currentCell.rowIndex()
};
if(this._trigger("currentCellChanging", null, currentCellChangingArgs)) {
cellEditCompleted = false;
if(!this.options.allowEditing || !currentCell._isEdit() || (cellEditCompleted = this._endEditInternal(null))) {
if(dataRange._containsCellInfo(currentCell)) {
if(highlight) {
this._highlightCellPosition(currentCell, false)// remove the current one
;
}
if(domCell = currentCell.tableCell()) {
$(domCell).removeAttr("tabIndex");
}
}
currentCell = cellInfo._clone();
currentCell._setGridView(this);
if(highlight) {
this._highlightCellPosition(currentCell, true);
}
if(domCell = currentCell.tableCell()) {
$(domCell).attr("tabIndex", 0)// make cell focusable to pass correct target (table cell) into the keyPress event handler.
;
if(setFocus && !currentCell._isEdit()) {
// prevent moving focus from child editor
//$(domCell).focus(); <-- commented out due issue #39166 (+ fixedView.refreshPanel)
}
}
this._field("currentCell", currentCell)// set currentCell
;
this._onCurrentCellChanged(e);
}
}
} else {
// the same cell
if(highlight) {
this._highlightCellPosition(currentCell, true)// ensure
;
}
if(domCell = currentCell.tableCell()) {
$(domCell).attr("tabIndex", 0);
}
if(e && !currentCell._isEdit() && this._editBySingleClick()) {
this._beginEditInternal(e);
}
}
} else {
// cellInfo is invalid
// do nothing
// this._highlightCellPosition(currentCell, false);
// this._field("currentCell", currentCell.outsideValue); // set currentCell
}
};
wijgrid.prototype._highlightCellPosition = function (cellInfo, add) {
if(cellInfo && cellInfo._isValid()) {
var x = cellInfo.cellIndexAbs(), y = cellInfo.rowIndexAbs(), $rs = wijmo.grid.renderState, view = this._view(), rowInfo, obj, state;
// * column header cell *
obj = view.getHeaderCell(x);
if(obj) {
rowInfo = view._getRowInfo(this._headerRows().item(cellInfo.column().thY));
obj = $(obj);
state = view._changeCellRenderState(obj, $rs.current, add);
// highlight column header cell
this.cellStyleFormatter.format(obj, x, cellInfo.column(), rowInfo, state);
}
// * row header cell *
obj = view.getJoinedRows(y, 0);
if(obj) {
// change row state
rowInfo = view._getRowInfo(obj);
view._changeRowRenderState(rowInfo, $rs.current, add);
// highlight row header cell
this.rowStyleFormatter.format(rowInfo);
}
// * data cell *
obj = view.getCell(x, y);
if(obj) {
obj = $(obj);
state = view._changeCellRenderState(obj, $rs.current, add);
// highlight data cell
this.cellStyleFormatter.format(obj, x, cellInfo.column(), rowInfo, state)// rowInfo is taken from the previous step
;
}
}
};
wijgrid.prototype._beginEditInternal = // * currentCell
// * editing
function (e) {
if(this._canInteract() && this.options.allowEditing) {
var column = this.currentCell().column(), res;
if(column && !column.readOnly) {
res = new wijmo.grid.cellEditorHelper().currentCellEditStart(this, e);
if(res) {
// this._view().ensureWidth(undefined, column.visLeavesIdx);
}
return res;
}
}
return false;
};
wijgrid.prototype._endEditInternal = function (e) {
if(this._canInteract() && this.options.allowEditing) {
//var column = this.currentCell().column(),
var res = new wijmo.grid.cellEditorHelper().currentCellEditEnd(this, e);
if(res && !this._allowVirtualScrolling()) {
// avoid horizontal scrollbar movement.
this._view().ensureHeight(this.currentCell().rowIndex());
}
return res;
}
return false;
};
wijgrid.prototype._onViewInsertEmptyRow = // * editing
// * view handlers
function (rowType, sectionRowIndex, dataRowIndex, dataItemIndex, virtualDataItemIndex) {
return null;// default action
};
wijgrid.prototype._onViewCreateEmptyCell = function (rowInfo, dataCellIndex, column) {
return null;// default action
};
wijgrid.prototype._onViewCellRendered = function (rowInfo, $cell, cellIndex, column) {
};
wijgrid.prototype._onViewRowRendered = function (rowInfo) {
};
wijgrid.prototype._getDataParser = // view handlers *
// misc
function (column) {
return column.dataParser || wijmo.data.defaultParsers[column.dataType] || wijmo.data.defaultParsers.string;
};
wijgrid.prototype.parse = /** @ignore */
function (column, value) {
//// old behaviour
//var parser = this._getDataParser(column);
//return parser.parse(value, this._field("closestCulture"), column.dataFormatString, this.options.nullString, true);
var fromType = wijmo.grid.getDataType(column), toType = wijmo.grid.getDataType(column);
if($.isFunction(value)) {
value = value()// observable
;
}
value = wijmo.data.convert(value, fromType, toType, {
culture: this._field("closestCulture"),
format: column.dataFormatString || column._underlyingDataFormatString,
nullString: this.options.nullString,
parser: column.dataParser
});
// custom parser
return value;
};
wijgrid.prototype.toStr = /** @ignore */
function (column, value) {
//// old behaviour
//var parser = this._getDataParser(column);
//return parser.toStr(value, this._field("closestCulture"), column.dataFormatString, this.options.nullString, true);
var dataView = this._dataViewWrapper.dataView(), fromType = wijmo.grid.getDataType(column), toType = // column._underlyingDataType || "string",
"string";
value = wijmo.data.convert(value, fromType, toType, {
culture: this._field("closestCulture"),
format: column.dataFormatString || column._underlyingDataFormatString,
nullString: this.options.nullString,
parser: column.dataParser
});
// custom parser
return value;
};
wijgrid.prototype.parseFailed = /** @ignore */
function (column, value, dataItem, cell) {
return value;
};
wijgrid.prototype._funcOptions = function () {
return [
"cellStyleFormatter",
"rowStyleFormatter",
"afterCellEdit",
"afterCellUpdate",
"beforeCellEdit",
"beforeCellUpdate",
"cellClicked",
"columnDragging",
"columnDragged",
"columnDropping",
"columnDropped",
"columnResizing",
"columnResized",
"columnGrouping",
"columnGrouped",
"columnUngrouping",
"columnUngrouped",
"currentCellChanging",
"currentCellChanged",
"filtering",
"filtered",
"filterOperatorsListShowing",
"groupAggregate",
"groupText",
"invalidCellValue",
"pageIndexChanging",
"pageIndexChanged",
"selectionChanged",
"sorting",
"sorted",
/*"ajaxError",*/ "dataLoading",
"dataLoaded",
"loading",
"loaded",
"rendering",
"rendered"
];
};
wijgrid.prototype._canInteract = function () {
return !this.options.disabled;/* && this._dataViewWrapper.isLoaded();*/
};
wijgrid.prototype._canMoveToAnotherCell = function (domElement, keyCode) {
var tag = domElement.tagName.toLowerCase(), len, selectionRange, kc, res;
switch(tag) {
case "input":
if($(domElement).hasClass("wijgridinput")) {
var input = domElement;
if(input.type === "text") {
len = input.value.length;
selectionRange = new wijmo.grid.domSelection(input).getSelection();
kc = wijmo.grid.getKeyCodeEnum();
res = ((keyCode === kc.UP || keyCode === kc.DOWN || keyCode === kc.PAGE_DOWN || keyCode === kc.PAGE_UP) || (selectionRange.length === 0 && ((selectionRange.start === 0 && (keyCode === kc.LEFT || keyCode === kc.HOME)) || (selectionRange.end >= len && (keyCode === kc.RIGHT || keyCode === kc.END)))));
return res;
}
return true;
}
return false;
case "textarea":
case "select":
return false;
}
return true;
};
wijgrid.prototype._editBySingleClick = function () {
var value = (this.options.editingInitOption || "").toLowerCase();
switch(value) {
case "click":
case "doubleclick":
break;
case "auto":
default:
value = this._isMobileEnv() ? "click" : "doubleclick";
break;
}
return value === "click";
};
wijgrid.prototype._getDataToAbsOffset = function () {
var x = 0, y = 0, headerRows = this._headerRows();
if(this.options.showRowHeader) {
x++;
}
if(headerRows) {
y += headerRows.length();
}
if(this._filterRow()) {
y++;
}
return {
x: x,
y: y
};
};
wijgrid.prototype._gridDataRowIndexToDataView = function (value) {
var res = -1, $rt = wijmo.grid.rowType, rowInfo;
if(value < 0) {
return res;
}
rowInfo = this._view()._getRowInfo(this._rows().item(value));
return (rowInfo.type & wijmo.grid.rowType.data) ? rowInfo.dataItemIndex : -1;
};
wijgrid.prototype._currentCellFromDataView = function () {
var dataViewRowIndex = this._dataViewWrapper.currentPosition(), cellInfo = new wijmo.grid.cellInfo(this.currentCell().cellIndex(), this._dataViewDataRowIndexToGrid(dataViewRowIndex), null);
// normalize
if(cellInfo.rowIndex() < 0) {
cellInfo.cellIndex(-1);
} else {
if(cellInfo.cellIndex() < 0) {
cellInfo.cellIndex(0);
}
}
return cellInfo;
};
wijgrid.prototype._dataViewDataRowIndexToGrid = function (value) {
var $rt = wijmo.grid.rowType, view = this._view(), rows = this._rows(), i, len, rowInfo;
if(value < 0) {
return -1;
}
for(i = 0 , len = rows.length(); i < len; i++) {
rowInfo = view._getRowInfo(rows.item(i));
if((rowInfo.type & $rt.data) && (rowInfo.dataItemIndex === value)) {
return rowInfo.sectionRowIndex;
}
}
return -1;
};
wijgrid.prototype._getDataCellsRange = function () {
var minCol = 0, minRow = 0, maxCol = this._field("visibleLeaves").length - 1, maxRow = // = this._field("dataCache").<maxWidth>
(this._rendered) ? this._rows().length() - 1 : this.sketchTable.length - 1;
if(this.options.showRowHeader) {
maxCol--;
}
if(maxCol < 0 || maxRow < 0) {
minCol = minRow = maxCol = maxRow = -1;
}
return new wijmo.grid.cellInfoRange(new wijmo.grid.cellInfo(minCol, minRow, null), new wijmo.grid.cellInfo(maxCol, maxRow, null));
};
wijgrid.prototype._getDataItem = function (dataItemIndex) {
return this.dataView().item(dataItemIndex);
};
wijgrid.prototype._getFirstDataRowCell = function (absCellIndex) {
var rowIndex, len, rowInfo, view = this._view(), rows = this._rows(), $rt = wijmo.grid.rowType;
for(rowIndex = 0 , len = rows.length(); rowIndex < len; rowIndex++) {
rowInfo = view._getRowInfo(rows.item(rowIndex));
if(rowInfo.type & $rt.data) {
return new wijmo.grid.cellInfo(absCellIndex, rowIndex);
}
}
return wijmo.grid.cellInfo.outsideValue;
};
wijgrid.prototype._getNextCurrencyPos = function (dataRange, cellInfo, keyCode, shiftKeyPressed) {
var cellIndex = cellInfo.cellIndex(), rowIndex = cellInfo.rowIndex(), tmp, keyCodeEnum = wijmo.grid.getKeyCodeEnum();
switch(keyCode) {
case keyCodeEnum.PAGE_UP:
if(this._reverseKey && rowIndex === dataRange.topLeft().rowIndex()) {
rowIndex = dataRange.bottomRight().rowIndex();
} else {
rowIndex -= this._pageSizeKey;
if(rowIndex < (tmp = dataRange.topLeft().rowIndex())) {
rowIndex = tmp;
}
}
break;
case keyCodeEnum.PAGE_DOWN:
if(this._reverseKey && rowIndex === dataRange.bottomRight().rowIndex()) {
rowIndex = dataRange.topLeft().rowIndex();
} else {
rowIndex += this._pageSizeKey;
if(rowIndex > (tmp = dataRange.bottomRight().rowIndex())) {
rowIndex = tmp;
}
}
break;
case keyCodeEnum.END:
cellIndex = (this._reverseKey && cellIndex === dataRange.bottomRight().cellIndex()) ? dataRange.topLeft().cellIndex() : dataRange.bottomRight().cellIndex();
break;
case keyCodeEnum.HOME:
cellIndex = (this._reverseKey && cellIndex === dataRange.topLeft().cellIndex()) ? dataRange.bottomRight().cellIndex() : dataRange.topLeft().cellIndex();
break;
case keyCodeEnum.LEFT:
if(cellIndex > dataRange.topLeft().cellIndex()) {
cellIndex--;
} else if(this._reverseKey) {
cellIndex = dataRange.bottomRight().cellIndex();
}
break;
case keyCodeEnum.UP:
if(rowIndex > dataRange.topLeft().rowIndex()) {
rowIndex--;
} else if(this._reverseKey) {
rowIndex = dataRange.bottomRight().rowIndex();
}
break;
case keyCodeEnum.RIGHT:
if(cellIndex < dataRange.bottomRight().cellIndex()) {
cellIndex++;
} else if(this._reverseKey) {
cellIndex = dataRange.topLeft().cellIndex();
}
break;
case keyCodeEnum.ENTER:
case keyCodeEnum.DOWN:
if(rowIndex < dataRange.bottomRight().rowIndex()) {
rowIndex++;
} else {
if(this._reverseKey) {
rowIndex = dataRange.topLeft().rowIndex();
}
}
break;
case keyCodeEnum.TAB:
if(false/* TODO - tab navigation */ ) {
if(shiftKeyPressed) {
cellIndex--;
if(cellIndex < dataRange.topLeft().cellIndex()) {
cellIndex = dataRange.bottomRight().cellIndex();
rowIndex--;
if(rowIndex < dataRange.topLeft().rowIndex()) {
rowIndex = dataRange.bottomRight().rowIndex();
}
}
} else {
cellIndex++;
if(cellIndex > dataRange.bottomRight().cellIndex()) {
cellIndex = dataRange.topLeft().cellIndex();
rowIndex++;
if(rowIndex > dataRange.bottomRight().rowIndex()) {
rowIndex = dataRange.topLeft().rowIndex();
}
}
}
}
break;
}
return {
cellIndex: cellIndex,
rowIndex: rowIndex
};
};
wijgrid.prototype._findUntilOuterDiv = function (start, tagsToFind) {
var current = start, stopper, nodeName, item = null;
for(; current; current = current.parentNode) {
nodeName = current.nodeName.toLowerCase();
if(nodeName) {
if(current === this.outerDiv[0]) {
stopper = current;
break;
}
if(tagsToFind[nodeName]) {
item = current;
}
}
}
return stopper ? item : null;
};
wijgrid.prototype._getStaticIndex = function (bRow) {
var result, dataRange = this._getDataCellsRange();
if(this._hasSpannedCells()) {
return -1;// can't use static columns\ rows
}
if(bRow) {
result = Math.min(this.options.staticRowIndex, dataRange.bottomRight().rowIndex());
} else {
result = Math.min(this.options.staticColumnIndex, dataRange.bottomRight().cellIndex());
}
if(result < -1) {
result = -1;
}
return result;
};
wijgrid.prototype._getStaticOffsetIndex = function (isColumn) {
var index = 0;
if(isColumn) {
if(this.options.showRowHeader === true) {
// row header is always fixed
index++;
}
} else {
index = this._columnsHeadersTable().length//the whole header is fixed in case of staticRowIndex >= 0.
;
if(this.options.showFilter) {
index++// filter row is placed inside the header, so it is fixed too.
;
}
}
return index;
};
wijgrid.prototype._getRealStaticColumnIndex = // index of the fixed leaf inside the visibleLeaves collection.
function () {
var leaves, len, offsetStaticIndex = this._getStaticOffsetIndex(true), staticColumnIndex = this._getStaticIndex(false), resultIndex, tmp;
resultIndex = staticColumnIndex + offsetStaticIndex;
if(staticColumnIndex >= 0) {
leaves = this._field("visibleLeaves");
len = leaves.length;
// If child column of some band is fixed then the top and right-most column of the root band contained current column will be fixed.
tmp = resultIndex;
for(; resultIndex < len; resultIndex++) {
if(leaves[resultIndex].parentIdx === -1) {
// resultIndex is the index of the first leaf which is not contained inside a band.
if(resultIndex > tmp) {
resultIndex--;
}
break;
}
}
if(resultIndex >= len) {
resultIndex = len - 1;
}
}
return resultIndex;
};
wijgrid.prototype._getRealStaticRowIndex = function () {
var offsetStaticIndex = this._getStaticOffsetIndex(false);
return this._getStaticIndex(true) + offsetStaticIndex;
};
wijgrid.prototype._hasMerging = function () {
var leaves = this._field("leaves"), i, len, leaf, result = false;
if(leaves) {
for(i = 0 , len = leaves.length; (i < len) && !result; i++) {
leaf = leaves[i];
result = result || (leaf.parentVis && (leaf.rowMerge !== "none"))// merged visible column?
;
}
}
return result;
};
wijgrid.prototype._hasGrouping = function () {
var leaves = this._field("leaves"), i, len, leaf, result = false;
for(i = 0 , len = leaves.length; (i < len) && !result; i++) {
leaf = leaves[i];
result = leaf.groupInfo && (leaf.groupInfo.position !== "none")// grouped column?
;
}
return result;
};
wijgrid.prototype._hasSpannedCells = function () {
return this._hasGrouping() || this._hasMerging();
};
wijgrid.prototype._columnsHeadersTable = function (value) {
if(arguments.length) {
this._field("columnsHeadersTable", value);
}
return this._field("columnsHeadersTable");
};
wijgrid.prototype._view = function () {
return this._field("view");
};
wijgrid.prototype._originalFooterRowData = function () {
var footer = this._field("tfoot");
return (footer && footer.length) ? footer[0] : // first row only
null;
};
wijgrid.prototype._originalHeaderRowData = function () {
var header = this._field("thead");
return (header && header.length) ? header[0] : // first row only
null;
};
wijgrid.prototype._setAttr = // set one or more attribute and store original values in the this._originalAttr object if $element == this.element.
// (key, value), (map)
function ($element, key, value) {
var self = this;
if($element === this.element) {
// store original values
if(arguments.length === 2) {
// map
$.each(key, function (k, v) {
if(!(k in self._originalAttr)) {
self._originalAttr[k] = $element.attr(k);
}
});
return $element.attr(key);
} else {
// key, value
if(!(key in this._originalAttr)) {
this._originalAttr[key] = $element.attr(key);
}
return $element.attr(key, value);
}
} else {
return (arguments.length === 3) ? $element.attr(key, value) : $element.attr(key);// .attr(map)
}
return this;
};
wijgrid.prototype._totalRowsCount = // used by virtual scrolling
function () {
/*if (this._dataStore.isDynamic()) {
return this._dataStore.totalCount();
}*/
return this.sketchTable.length;
};
wijgrid.prototype._trackScrollingPosition = function (x, y) {
this._scrollingState.x = x;
this._scrollingState.y = y;
};
wijgrid.prototype._trackScrollingIndex = function (index) {
this._scrollingState.index = index;
};
wijgrid.prototype._uid = function () {
if(this.__uid === undefined) {
this.__uid = wijmo.grid.getUID();
}
return "wijgrid" + this.__uid;
};
return wijgrid;
})(wijmo.wijmoWidget);
grid.wijgrid = wijgrid;
wijgrid.prototype.widgetEventPrefix = "wijgrid";
wijgrid.prototype._data$prefix = "wijgrid";
wijgrid.prototype._customSortOrder = 1000;
wijgrid.prototype._reverseKey = false;
wijgrid.prototype._pageSizeKey = 10;
wijgrid.prototype._mergeWidgetsWithOptions = true;
var wijgrid_options = (function () {
function wijgrid_options() {
/** @ignore */
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body-c",
stateHover: "ui-btn-down-c",
stateActive: "ui-btn-down-c"
};
/** A value indicating whether columns can be moved.
* @example
* // Columns cannot be dragged and moved if this option is set to false
* $("#element").wijgrid({ allowColMoving: false });
* @remarks
* This option must be set to true in order to drag column headers to the group area.
*/
this.allowColMoving = false;
/** Determines whether the column width can be increased and decreased by dragging the sizing handle, or the edge of the column header, with the mouse.
* @example
* // The sizing handle cannot be dragged and column width cannot be changed if this option is set to false
* $("#element").wijgrid({ allowColSizing: false });
*/
this.allowColSizing = false;
/** Determines whether the user can make changes to cell contents in the grid.
* @example
* // Users cannot change cell contents in the grid if this option is set to false
* $("#element").wijgrid({ allowEditing: false });
*/
this.allowEditing = false;
/** Determines whether the user can move the current cell using the arrow keys.
* @example
* // Users cannot move the selection using arrow keys if this option is set to false
* $("#element").wijgrid({ allowKeyboardNavigation: false });
*/
this.allowKeyboardNavigation = true;
/** Determines whether the grid should display paging buttons. The number of rows on a page is determined by the pageSize option.
* @example
* // Grid displays paging buttons when allowPaging is true. The pageSize here sets 5 rows to a page.
* $("#element").wijgrid({ allowPaging: false, pageSize: 5 });
*/
this.allowPaging = false;
/** Determines whether the widget can be sorted by clicking the column header.
* @example
* // Sort a column by clicking its header when allowSorting is set to true
* $("#element").wijgrid({ allowSorting: false });
*/
this.allowSorting = false;
/** A value that indicates whether virtual scrolling is allowed. The pageSize option determines the limit of simultaneously rendered rows when virtual scrolling is used. Set allowVirtualScrolling to true when using large amounts of data to improve efficiency.
* @example
* $("#element").wijgrid({ allowVirtualScrolling: false });
* @remarks
* This option is ignored if the grid uses paging, columns merging or fixed rows. This option cannot be enabled when using dynamic wijdatasource.
*/
this.allowVirtualScrolling = false;
/** Function used for styling the cells in wijgrid.
* @example
* // Make the text of the current cell italic.
* $("#element").wijgrid({
* highlightCurrentCell: true,
* cellStyleFormatter: function(args) {
* if ((args.row.type & wijmo.grid.rowType.data)) {
* if (args.state & wijmo.grid.renderState.current) {
* args.$cell.css("font-style", "italic");
* } else {
* args.$cell.css("font-style", "normal");
* }
* }
* }
* });
* @param {wijmo.grid.ICellStyleFormaterArgs} args The data with this function.
*/
this.cellStyleFormatter = undefined;
/** An array of column options.
* @example
* $("#element").wijgrid({ columns: [ { headerText: "column0", allowSort: false }, { headerText: "column1", dataType: "number" } ] });
*/
this.columns = [];
/** Determines behavior for column autogeneration. Possible values are: "none", "append", "merge".
* @example
* $("#element").wijgrid({ columnsAutogenerationMode: "merge" });
* @remarks
* Possible values are:
* "none": Column auto-generation is turned off.
* "append": A column will be generated for each data field and added to the end of the columns collection.
* "merge": Each column having dataKey option not specified will be automatically bound to the first unreserved data field.For each data field not bound to any column a new column will be generated and added to the end of the columns collection.
*
* To prevent automatic binding of a column to a data field set its dataKey option to null.
*
* Note: columns autogeneration process affects the options of columns and the columns option itself.
*/
this.columnsAutogenerationMode = "merge";
/** Determines the culture ID.
* @example
* // This code sets the culture to English.
* $("#element").wijgrid({ culture: "en" });
* @remarks
* Please see the https://github.com/jquery/globalize for more information.
*/
this.culture = "";
/** An array of custom user filters. Use this option if you want to extend the default set of filter operators with your own. Custom filters will be shown in the filter dropdown.
* @example
* var oddFilterOp = {
* name: "customOperator-Odd",
* arity: 1,
* applicableTo: ["number"],
* operator: function(dataVal) { return (dataVal % 2 !== 0); }
* }
*
* $("#element").wijgrid({ customFilterOperators: [oddFilterOp] });
*/
this.customFilterOperators = [];
/** Determines the datasource.
* Possible datasources include:
* 1. A DOM table. This is the default datasource, used if the data option is null. Table must have no cells with rowSpan and colSpan attributes.
* 2. A two-dimensional array, such as [[0, "a"], [1, "b"]].
* 3. An array of objects, such as [{field0: 0, field1: "a"}, {field0: 1, field1: "b'}].
* 4. A wijdatasource.
* 5. A wijdataview.
* @example
* // DOM table
* $("#element").wijgrid();
* // two-dimensional array
* $("#element").wijgrid({ data: [[0, "a"], [1, "b"]] });
*/
this.data = null;
/** Determines an action to bring a cell in the editing mode. Possible values are: "click", "doubleClick", "auto".
* @example
* $("#element").wijgrid({ editingInitOption: "auto" });
* @remarks
* Possible values are:
* "click": cell is edited via a single click.
* "doubleClick": cell is edited via a double click.
* "auto": action is determined automatically depending upon user environment. If user has a mobile platform then "click" is used, "doubleClick" otherwise.
*/
this.editingInitOption = "auto";
/** Determines if the exact column width, in pixels, is used.
* @example
* $("#element").wijgrid({ ensureColumnsPxWidth: true });
* @remarks
* By default, wijgrid emulates the table element behavior when using a number as the width. This means wijgrid may not have the exact width specified. If exact width is needed, please set the ensureColumnsPxWidth option of wijgrid to true. If this option is set to true, wijgrid will not expand itself to fit the available space.Instead, it will use the width option of each column widget.
*/
this.ensureColumnsPxWidth = false;
/** Determines the order of items in the filter drop-down list.
* Possible values are: "none", "alphabetical", "alphabeticalCustomFirst" and "alphabeticalEmbeddedFirst"
* @example
* $("#element").wijgrid({ filterOperatorsSortMode: "alphabeticalCustomFirst" });
* @remarks
* Possible values are:
* "none": Operators follow the order of addition; built-in operators appear before custom ones.
* "alphabetical": Operators are sorted alphabetically.
* "alphabeticalCustomFirst": Operators are sorted alphabetically with custom operators appearing before built-in ones.
* "alphabeticalEmbeddedFirst": Operators are sorted alphabetically with built-in operators appearing before custom operators.
*
* "NoFilter" operator is always first.
*/
this.filterOperatorsSortMode = "alphabeticalCustomFirst";
/** Determines the caption of the group area.
* @example
* // Set the groupAreaCaption to a string and the text appears above the grid
* $("#element").wijgrid({ groupAreaCaption: "Drag a column here to group by that column." });
*/
this.groupAreaCaption = "Drag a column here to group by that column.";
/** Determines the indentation of the groups, in pixels.
* @example
* // Set the groupIndent option to the number of pixels to indent data when grouping.
* $("#element").wijgrid({ groupIndent: 15 });
*/
this.groupIndent = 10;
/** Determines whether the position of the current cell is highlighted or not.
* @example
* $("#element").wijgrid({ highlightCurrentCell: false });
*/
this.highlightCurrentCell = false;
/** Determines whether hovered row is highlighted or not.
* @example
* $("#element").wijgrid({ highlightCurrentCell: true });
*/
this.highlightOnHover = true;
/** Determines the text to be displayed when the grid is loading.
* @example
* $("#element").wijgrid({ loadingText: "Loading..."});
*/
this.loadingText = "Loading...";
/** Cell values equal to this property value are considered null values. Use this option if you want to change default representation of null values (empty strings) with something else.
* @example
* $("#element").wijgrid({ nullString: "" });
* @remarks
* Case-sensitive for built-in parsers.
*/
this.nullString = "";
/** Determines the zero-based index of the current page. You can use this to access a specific page, for example, when using the paging feature.
* @example
* $("#element").wijgrid({ pageIndex: 0 });
*/
this.pageIndex = 0;
/** Number of rows to place on a single page.
* The default value is 10.
* @example
* // The pageSize here sets 10 rows to a page. The allowPaging option is set to true so paging buttons appear.
* $("#element").wijgrid({ pageSize: 10 });
*/
this.pageSize = 10;
/** Determines the pager settings for the grid including the mode (page buttons or next/previous buttons), number of page buttons, and position where the buttons appear.
* @example
* // Display the pager at the top of the wijgrid.
* $("#element").wijgrid({ pagerSettings: { position: "top" } });
* @remarks
* See the wijpager documentation for more information on pager settings.
*/
this.pagerSettings = {
mode: "numeric",
pageButtonCount: 10,
position: "bottom"
};
/** A value indicating whether DOM cell attributes can be passed within a data value.
* @example
* // Render the style attribute passed within the data.
* $("#element").wijgrid({
* readAttributesFromData: false });
* data: [
* [ [1, { "style": "color: red" } ], a ]
* ]
* });
* @remarks
* This option allows binding collection of values to data and automatically converting them as attributes of corresponded DOM table cells during rendering.
* Values should be passed as an array of two items, where first item is a value of the data field, the second item is a list of values:
* $("#element").wijgrid({
* data: [
* [ [1, { "style": "color: red", "class": "myclass" } ], a ]
* ]
* });
*
* or
*
* $("#element").wijgrid({
* data: [
* { col0: [1, { "style": "color: red", "class": "myclass" }], col1: "a" }
* ]
* });
*
* Note: during conversion wijgrid extracts the first item value and makes it data field value, the second item (list of values) is removed:
* [ { col0: 1, col1: "a" } ]
*
* If DOM table is used as a datasource then attributes belonging to the cells in tBody section of the original table will be read and applied to the new cells.
*
* rowSpan and colSpan attributes are not allowed.
*/
this.readAttributesFromData = false;
/** Function used for styling rows in wijgrid.
* @example
* // Make text of the alternating rows italic.
* $("#demo").wijgrid({
* data: [
* [0, "Nancy"], [1, "Susan"], [2, "Alice"], [3, "Kate"]
* ],
* rowStyleFormatter (args) {
* if ((args.state === wijmo.grid.renderState.rendering) && (args.type & wijmo.grid.rowType.dataAlt)) {
* args.$rows.find("td").css("font-style", "italic");
* }
* }
* });
* @param {wijmo.grid.IRowInfo} args The data with this function.
*/
this.rowStyleFormatter = undefined;
/** Determines which scrollbars are active and if they appear automatically based on content size.
* Possbile values are: "none", "auto", "horizontal", "vertical", "both".
* @example
* // The horizontal and vertical scrollbars are active when the scrollMode is set to both.
* $("#element").wijgrid({ scrollMode: "both" });
* @remarks
* Possible values are:
* "none": Scrolling is not used; the staticRowIndex and staticColumnIndex values are ignored.
* "auto": Scrollbars appear automatically depending upon content size.
* "horizontal": The horizontal scrollbar is active.
* "vertical": The vertical scrollbar is active.
* "both": Both horizontal and vertical scrollbars are active.
*/
this.scrollMode = "none";
/** Determines which cells, range of cells, columns, or rows can be selected at one time.
* Possible values are: "none", "singleCell", "singleColumn", "singleRow", "singleRange", "multiColumn", "multiRow" and "multiRange".
* @example
* // Set selectionMode to muliColumn and users can select more than one column using the CTRL or SHIFT keys.
* $("#element").wijgrid({ selectionMode: "multiColumn" });
* @remarks
* Possible values are:
* "none": Selection is turned off.
* "singleCell": Only a single cell can be selected at a time.
* "singleColumn": Only a single column can be selected at a time.
* "singleRow": Only a single row can be selected at a time.
* "singleRange": Only a single range of cells can be selected at a time.
* "multiColumn": It is possible to select more than one row at the same time using the mouse and the CTRL or SHIFT keys.
* "multiRow": It is possible to select more than one row at the same time using the mouse and the CTRL or SHIFT keys.
* "multiRange": It is possible to select more than one cells range at the same time using the mouse and the CTRL or SHIFT keys.
*/
this.selectionMode = "singleRow";
/** A value indicating whether the filter row is visible.
* Filter row is used to display column filtering interface.
* @example
* // Set showFilter to true to view the filter row.
* $("#element").wijgrid({ showFilter: true });
*/
this.showFilter = false;
/** A value indicating whether the footer row is visible.
* Footer row is used for displaying of tfoot section of original table, and to show totals.
* @example
* // Set showFooter to true to view the footer row.
* $("#element").wijgrid({ showFooter: true });
*/
this.showFooter = false;
/** A value indicating whether group area is visible.
* Group area is used to display headers of groupped columns. User can drag columns from/to group area by dragging column headers with mouse, if allowColumnMoving option is on.
* @example
* // Set showGroupArea to true to display the group area.
* $("#element").wijgrid({ showGroupArea: true });
*/
this.showGroupArea = false;
/** A value indicating whether a selection will be automatically displayed at the current cell position when the wijgrid is rendered.
* Set this option to false if you want to prevent wijgrid from selecting the currentCell automatically.
* @example
* $("#element").wijgrid({ showSelectionOnRender: true });
*/
this.showSelectionOnRender = true;
/** A value indicating whether the row header is visible.
* @example
* $("#element").wijgrid({ showRowHeader: true });
*/
this.showRowHeader = false;
/** Indicates the index of columns that will always be shown on the left when the grid view is scrolled horizontally.
* Note that all columns before the static column will be automatically marked as static, too.
* This can only take effect when the scrollMode option is not set to "none".
* It will be considered "-1" when grouping or row merging is enabled. A "-1" means there is no data column but the row header is static. A zero (0) means one data column and row header are static.
* @example
* $("#element").wijgrid({ staticColumnIndex: -1 });
*/
this.staticColumnIndex = -1;
/** Indicates the index of data rows that will always be shown on the top when the wijgrid is scrolled vertically.
* Note, that all rows before the static row will be automatically marked as static, too.
* This can only take effect when the scrollMode option is not set to "none". This will be considered "-1" when grouping or row merging is enabled.
* A "-1" means there is no data row but the header row is static.A zero (0) means one data row and the row header are static.
* @example
* $("#element").wijgrid({ staticRowIndex: -1 });
*/
this.staticRowIndex = -1;
/** Gets or sets the virtual number of items in the wijgrid and enables custom paging.
* Setting option to a positive value activates custom paging, the number of displayed rows and the total number of pages will be determined by the totalRows and pageSize values.
* @example
* $("#element").wijgrid({ totalRows: -1 });
* @remarks
* In custom paging mode sorting, paging and filtering are not performed automatically.
* This must be handled manually using the sorted, pageIndexChanged, and filtered events. Load the new portion of data there followed by the ensureControl(true) method call.
*/
this.totalRows = -1;
/* --- events */
/** The afterCellEdit event handler is a function called after cell editing is completed.
* This function can assist you in completing many tasks, such as in making changes once editing is completed; in tracking changes in cells, columns, or rows; or in integrating custom editing functions on the front end.
* @event
* @example
* // Once cell editing is complete, the function calls the destroy method to destroy the wijcombobox widget and the wijinputnumber widget which are used as the custom editors.
* $("#element").wijgrid({
* afterCellEdit: function(e, args) {
* switch (args.cell.column().dataKey) {
* case "Position":
* args.cell.container().find("input").wijcombobox("destroy");
* break;
* case "Acquired":
* args.cell.container().find("input").wijinputnumber("destroy");
* break;
* }
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ afterCellEdit: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridaftercelledit", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IAfterCellEditEventArgs} args The data with this event.
*/
this.afterCellEdit = null;
/** The afterCellUpdate event handler is a function that is called after a cell has been updated. Among other functions, this event allows you to track and store the indices of changed rows or columns.
* @event
* @example
* // Once the cell has been updated, the information from the underlying data is dumped into the "#log" element.
* $("#element").wijgrid({
* afterCellUpdate: function(e, args) {
* $("#log").html(dump($("#demo").wijgrid("data")));
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ afterCellUpdate: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridaftercellupdate", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IAfterCellUpdateEventArgs} args The data with this event.
*/
this.afterCellUpdate = null;
/** The beforeCellEdit event handler is a function that is called before a cell enters edit mode.
* The beforeCellEdit event handler assists you in appending a widget, data, or other item to a wijgrid's cells before the cells enter edit mode. This event is cancellable.
* @event
* @example
* // Allow the user to change the price only if the product hasn't been discontinued:
* $("#element").wijgrid({
* beforeCellEdit: function(e, args) {
* return !((args.cell.column().dataKey === "Price") && args.cell.row().data.Discontinued);
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ beforeCellEdit: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridbeforecelledit", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IBeforeCellEditEventArgs} args The data with this event.
*/
this.beforeCellEdit = null;
/** The beforeCellUpdate event handler is a function that is called before the cell is updated with new or user-entered data. This event is cancellable.
* There are many instances where this event is helpful, such as when you need to check a cell's value before the update occurs or when you need to apply an alert message based on the cell's value.
* @event
* @example
* // In this sample, you use args.value to check the year that the user enters in the "Acquired" column.
* // If it's less than 1990 or greater than the current year, then the event handler will return false to cancel updating and show the user an alert message.
* $("#element").wijgrid({
* beforeCellUpdate: function(e, args) {
* switch (args.cell.column().dataKey) {
* case "Acquired":
* var $editor = args.cell.container().find("input"),
* value = $editor.wijinputnumber("getValue"),
* curYear = new Date().getFullYear();
*
* if (value < 1990 || value > curYear) {
* $editor.addClass("ui-state-error");
* alert("value must be between 1990 and " + curYear);
* $editor.focus();
* return false;
* }
*
* args.value = value;
* break;
* }
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ beforeCellUpdate: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridbeforecellupdate", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IBeforeCellUpdateEventArgs} args The data with this event.
*/
this.beforeCellUpdate = null;
/** The cellClicked event handler is a function that is called when a cell is clicked. You can use this event to get the information of a clicked cell using the args parameter.
* @event
* @example
* // The sample uses the cellClicked event to trigger an alert when the cell is clicked.
* $("#element").wijgrid({
* cellClicked: function (e, args) {
* alert(args.cell.value());
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ cellClicked: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridcellclicked", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.ICellClickedEventArgs} args The data with this event.
*/
this.cellClicked = null;
/** The columnDragging event handler is a function that is called when column dragging has been started, but before the wijgrid handles the operation. This event is cancellable.
* @event
* @example
* // Preventing a user from dragging a specific column
* $("#element").wijgrid({
* columnDragging: function (e, args) {
* return !(args.drag.dataKey == "ID");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ columnDragging: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridcolumndragging", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IColumnDraggingEventArgs} args The data with this event.
*/
this.columnDragging = null;
/** The columnDragged event handler is a function that is called when column dragging has been started. You can use this event to find the column being dragged or the dragged column's location.
* @event
* @example
* // Supply a callback function to handle the columnDragged event:
* $("#element").wijgrid({
* columnDragged: function (e, args) {
* alert("The '" + args.drag.headerText + "' column is being dragged from the '" + args.dragSource + "' location");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ columnDragged: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridcolumndragged", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IColumnDraggedEventArgs} args The data with this event.
*/
this.columnDragged = null;
/** The columnDropping event handler is a function that is called when a column is dropped into the columns area, but before wijgrid handles the operation. This event is cancellable.
* @event
* @example
* // Preventing user from dropping any column before the "ID" column.
* $("#element").wijgrid({
* columnDropping: function (e, args) {
* return !(args.drop.dataKey == "ID" && args.at == "left");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ columnDropping: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridcolumndropping", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IColumnDroppingEventArgs} args The data with this event.
*/
this.columnDropping = null;
/** The columnDropped event handler is a function that is called when a column has been dropped into the columns area.
* @event
* @example
* // Supply a callback function to handle the columnDropped event:
* $("#element").wijgrid({
* columnDropped: function (e, args) {
* "The '" + args.drag.headerText + "' column has been dropped onto the '" + args.drop.headerText + "' column at the '" + args.at + "' position"
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ columnDropped: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridcolumndropped", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IColumnDroppedEventArgs} args The data with this event.
*/
this.columnDropped = null;
/** The columnGrouping event handler is a function that is called when a column is dropped into the group area, but before the wijgrid handles the operation. This event is cancellable.
* @event
* @example
* // Preventing user from grouping the "UnitPrice" column.
* $("#element").wijgrid({
* columnGrouping: function (e, args) {
* return !(args.drag.headerText == "UnitPrice");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ columnGrouping: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridcolumngrouping", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IColumnGroupingEventArgs} args The data with this event.
*/
this.columnGrouping = null;
/** The columnGrouped event handler is a function that is called when a column has been dropped into the group area.
* @event
* @example
* // Supply a callback function to handle the columnGrouped event:
* $("#element").wijgrid({
* columnGrouped: function (e, args) {
* alert("The '" + args.drag.headerText "' column has been grouped");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ columnGrouped: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridcolumngrouped", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IColumnGroupedEventArgs} args The data with this event.
*/
this.columnGrouped = null;
/** The columnResizing event handler is called when a user resizes the column but before the wijgrid handles the operation. This event is cancellable.
* @event
* @example
* // Prevent setting the width of "ID" column less than 100 pixels
* $("#element").wijgrid({
* columnResizing: function (e, args) {
* if (args.column.dataKey == "ID" && args.newWidth < 100) {
* args.newWidth = 100;
* }
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ columnResizing: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridcolumnresizing", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IColumnResizingEventArgs} args The data with this event.
*/
this.columnResizing = null;
/** The columnResized event handler is called when a user has changed a column's size.
* @event
* @example
* // Supply a callback function to handle the columnGrouped event:
* $("#element").wijgrid({
* columnResized: function (e, args) {
* alert("The '" + args.column.headerText + "' has been resized");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ columnResized: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridcolumnresized", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IColumnResizedEventArgs} args The data with this event.
*/
this.columnResized = null;
/** The columnUngrouping event handler is called when a column has been removed from the group area but before the wjgrid handles the operation. This event is cancellable.
* @event
* @example
* // Preventing user from ungrouping the "UnitPrice" column.
* $("#element").wijgrid({
* columnUngrouping: function (e, args) {
* return !(args.column.headerText == "UnitPrice");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ columnUngrouping: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridcolumnungrouping", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IColumnUngroupingEventArgs} args The data with this event.
*/
this.columnUngrouping = null;
/** The columnUngrouped event handler is called when a column has been removed from the group area.
* @event
* @example
* // Supply a callback function to handle the columnGrouped event:
* $("#element").wijgrid({
* columnUngrouped: function (e, args) {
* alert("The '" + args.column.headerText + "' has been ungrouped");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ columnUngrouped: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridcolumnungrouped", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IColumnUngroupedEventArgs} args The data with this event.
*/
this.columnUngrouped = null;
/** The currentCellChanging event handler is called before the cell is changed. You can use this event to get a selected row or column or to get a data row bound to the current cell. This event is cancellable.
* @event
* @example
* // Gets the data row bound to the current cell.
* $("#element").wijgrid({
* currentCellChanging: function (e, args) {
* var rowObj = $(e.target).wijgrid("currentCell").row();
* if (rowObj) {
* var dataItem = rowObj.data; // current data item (before the cell is changed).
* }
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ currentCellChanging: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridcurrentcellchanging", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.ICurrentCellChangingEventArgs} args The data with this event.
*/
this.currentCellChanging = null;
/** The currentCellChanged event handler is called after the current cell is changed.
* @event
* @example
* // Gets the data row bound to the current cell.
* $("#element").wijgrid({
* currentCellChanged: function (e, args) {
* var rowObj = $(e.target).wijgrid("currentCell").row();
* if (rowObj) {
* var dataItem = rowObj.data; // current data item (after the cell is changed).
* }
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ currentCellChanged: function (e) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridcurrentcellchanged", function (e) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
*/
this.currentCellChanged = null;
/** The filterOperatorsListShowing event handler is a function that is called before the filter drop-down list is shown. You can use this event to customize the list of filter operators for your users.
* @event
* @example
* // Limit the filters that will be shown to the "Equals" filter operator
* $("#element").wijgrid({
* filterOperatorsListShowing: function (e, args) {
* args.operators = $.grep(args.operators, function(op) {
* return op.name === "Equals" || op.name === "NoFilter";
* }
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ filterOperatorsListShowing: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridfilteroperatorslistshowing", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IFilterOperatorsListShowingEventArgs} args The data with this event.
*/
this.filterOperatorsListShowing = null;
/** The filtering event handler is a function that is called before the filtering operation is started. For example, you can use this event to change a filtering condition before a filter will be applied to the data. This event is cancellable.
* @event
* @example
* // Prevents filtering by negative values
* $("#element").wijgrid({
* filtering: function (e, args) {
* if (args.column.dataKey == "Price" && args.value < 0) {
* args.value = 0;
* }
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ filtering: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridfiltering", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IFilteringEventArgs} args The data with this event.
*/
this.filtering = null;
/** The filtered event handler is a function that is called after the wijgrid is filtered.
* @event
* @example
* //
* $("#element").wijgrid({
* filtered: function (e, args) {
* alert("The filtered data contains: " + $(this).wijgrid("dataView").count() + " rows");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ filtered: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridfiltered", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IFilteredEventArgs} args The data with this event.
*/
this.filtered = null;
/** The groupAggregate event handler is a function that is called when groups are being created and the column object's aggregate option has been set to "custom". This event is useful when you want to calculate custom aggregate values.
* @event
* @example
* // This sample demonstrates using the groupAggregate event handler to calculate an average in a custom aggregate:
* $("#element").wijgrid({
* groupAggregate: function (e, args) {
* if (args.column.dataKey == "Price") {
* var aggregate = 0;
*
* for (var i = args.groupingStart; i <= args.groupingEnd; i++) {
* aggregate += args.data[i][args.column.dataIndex].value;
* }
*
* aggregate = aggregate/ (args.groupingEnd - args.groupingStart + 1);
* args.text = aggregate;
* }
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ groupAggregate: function (e, args) {
* // some code here
* }});
* Bind to the event by type:
*
* $("#element").bind("wijgridgroupaggregate", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IGroupAggregateEventArgs} args The data with this event.
*/
this.groupAggregate = null;
/** The groupText event handler is a function that is called when groups are being created and the groupInfo option has the groupInfo.headerText or the groupInfo.footerText options set to "custom". This event can be used to customize group headers and group footers.
* @event
* @example
* // The following sample sets the groupText event handler to avoid empty cells. The custom formatting applied to group headers left certain cells appearing as if they were empty. This code avoids that:
* $("#element").wijgrid({
* groupText: function (e, args) {
* if (!args.groupText) {
* args.text = "null";
* }
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ groupText: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridgrouptext", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IGroupTextEventArgs} args The data with this event.
*/
this.groupText = null;
/** The invalidCellValue event handler is a function called when a cell needs to start updating but the cell value is invalid. So if the value in a wijgrid cell can't be converted to the column target type, the invalidCellValue event will fire.
* @event
* @example
* // Adds a style to the cell if the value entered is invalid
* $("#element").wijgrid({
* invalidCellValue: function (e, args) {
* $(args.cell.container()).addClass("ui-state-error");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ invalidCellValue: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridinvalidcellvalue", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IInvalidCellValueEventArgs} args The data with this event.
*/
this.invalidCellValue = null;
/** The pageIndexChanging event handler is a function that is called before the page index is changed. This event is cancellable.
* @event
* @example
* // Cancel the event by returning false
* $("#element").wijgrid({
* pageIndexChanging: function (e, args) {
* return false;
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ pageIndexChanging: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridpageindexchanging", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IPageIndexChangingEventArgs} args The data with this event.
*/
this.pageIndexChanging = null;
/** The pageIndexChanged event handler is a function that is called after the page index is changed, such as when you use the numeric buttons to swtich between pages or assign a new value to the pageIndex option.
* @event
* @example
* // Supply a callback function to handle the pageIndexChanged event:
* $("#element").wijgrid({
* pageIndexChanged: function (e, args) {
* alert("The new pageIndex is: " + args.newPageIndex);
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ pageIndexChanged: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridpageindexchanged", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.IPageIndexChangedEventArgs} args The data with this event.
*/
this.pageIndexChanged = null;
/** The selectionChanged event handler is a function that is called after the selection is changed.
* @event
* @example
* // Get the value of the first cell of the selected row.
* $("#element").wijgrid({
* selectionMode: "singleRow",
* selectionChanged: function (e, args) {
* alert(args.addedCells.item(0).value());
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ selectionChanged: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridselectionchanged", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.ISelectionChangedEventArgs} args The data with this event.
*/
this.selectionChanged = null;
/** The sorting event handler is a function that is called before the sorting operation is started. This event is cancellable.
* The allowSorting option must be set to "true" for this event to fire.
* @event
* @example
* // Preventing user from sorting the "ID" column.
* $("#element").wijgrid({
* sorting: function (e, args) {
* return !(args.column.headerText === "ID");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ sorting: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridsorting", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.ISortingEventArgs} args The data with this event.
*/
this.sorting = null;
/** The sorted event handler is a function that is called after the widget is sorted. The allowSorting option must be set to "true" to allow this event to fire.
* @event
* @example
* // The following code handles the sorted event and will give you access to the column and the sort direction
* $("#element").wijgrid({
* sorted: function (e, args) {
* alert("Column " + args.column.headerText + " sorted in " + args.sortDirection + " order");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ sorted: function (e, args) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridsorted", function (e, args) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
* @param {wijmo.grid.ISortedEventArgs} args The data with this event.
*/
this.sorted = null;
/* events --- */
/* --- life-cycle events */
// /// <summary>
// /// The ajaxError event handler. A function called when wijgrid is bound to remote data and
// /// the ajax request fails.
// /// Default: null.
// /// Type: Function.
// /// Code example:
// /// Supply a callback function to handle the ajaxError event:
// /// $("#element").wijgrid({ ajaxError: function (e, args) { } });
// /// Bind to the event by type:
// /// $("#element").bind("wijgridajaxerror", function (e, args) { });
// /// </summary>
// /// <param name="e" type="Object">The jQuery.Event object.</param>
// /// <param name="args" type="Object">
// /// The data corresponded with this event.
// /// args.XMLHttpRequest: the XMLHttpRequest object.
// /// args.textStatus: a string describing the error type.
// /// args.errorThrown: an exception object.
// ///
// /// Refer to the jQuery.ajax.error event documentation for more details on this arguments.
// /// </param>
// ajaxError: null,
/** The dataLoading event handler is a function that is called when the wijgrid loads a portion of data from the underlying datasource. This can be used for modification of data sent to server if using dynamic remote wijdatasource.
* @event
* @example
* // This sample allows you to set the session ID when loading a portion of data from the remote wijdatasource:
* $("#element").wijgrid({
* data: new wijdatasource({
* proxy: new wijhttpproxy({
* // some code here
* })
* }),
* dataLoading: function (e) {
* var dataSource = $(this).wijgrid("option", "data");
* dataSource.proxy.options.data.sessionID = getSessionID();
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ dataLoading: function (e) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgriddataloading", function (e) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
*/
this.dataLoading = null;
/** The dataLoaded event handler is a function that is called when data is loaded.
* @event
* @example
* // Display the number of entries found
* $("#element").wijgrid({
* dataLoaded: function (e) {
* alert($(this).wijgrid("dataView").count());
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ dataLoaded: function (e) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgriddataloaded", function (e) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
*/
this.dataLoaded = null;
/** The loading event handler is a function that is called at the beginning of the wijgrid's lifecycle. You can use this event to activate a custom load progress indicator.
* @event
* @example
* // Creating an indeterminate progressbar during loading
* $("#element").wijgrid({
* loading: function (e) {
* $("#progressBar").show().progressbar({ value: false });
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ loading: function (e) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridloading", function (e) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
*/
this.loading = null;
/** The loaded event handler is a function that is called at the end the wijgrid's lifecycle when wijgrid is filled with data and rendered. You can use this event to manipulate the grid html content or to finish a custom load indication.
* @event
* @example
* // The loaded event in the sample below ensures that whatever is selected on load is cleared
* $("#element").wijgrid({
* loaded: function (e) {
* $(e.target).wijgrid("selection").clear(); // clear selection
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ loaded: function (e) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridloaded", function (e) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
*/
this.loaded = null;
/** The rendering event handler is a function that is called when the wijgrid is about to render. Normally you do not need to use this event.
* @event
* @example
* $("#element").wijgrid({
* rendering: function (e) {
* alert("rendering");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ rendering: function (e) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridrendering", function (e) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
*/
this.rendering = null;
/** The rendered event handler is a function that is called when the wijgrid is rendered. Normally you do not need to use this event.
* @event
* @example
* $("#element").wijgrid({
* rendered: function (e) {
* alert("rendered");
* }
* });
* @remarks
* You can bind to the event either by type or by name.
* Bind to the event by name:
* $("#element").wijgrid({ rendered: function (e) {
* // some code here
* }});
*
* Bind to the event by type:
* $("#element").bind("wijgridrendered", function (e) {
* // some code here
* });
* @param {Object} e The jQuery.Event object.
*/
this.rendered = null;
}
return wijgrid_options;
})();
//wijgrid.prototype.options = $.extend(true, {}, wijmoWidget.prototype.options, new wijgrid_options());
wijgrid.prototype.options = wijmo.grid.extendWidgetOptions(wijmo.wijmoWidget.prototype.options, new wijgrid_options());
$.wijmo.registerWidget("wijgrid", wijgrid.prototype);
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../../../Base/jquery.wijmo.widget.ts"/>
/// <reference path="interfaces.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @widget */
var c1basefield = (function (_super) {
__extends(c1basefield, _super);
function c1basefield() {
_super.apply(this, arguments);
}
c1basefield.prototype._create = function () {
var wijgrid = $.data(this.element[0], "wijgridowner");
this._field("owner", wijgrid);
wijmo.grid.widgetName(this.element[0], this.widgetFullName);
this._destroyed = false;
this.element.addClass(wijgrid.options.wijCSS.widget + " wijmo-c1basefield " + wijgrid.options.wijCSS.stateDefault);
if(this.options.disabled) {
this.disable();
}
if(wijgrid.options.allowColMoving) {
wijgrid._dragndrop(true).attach(this);
}
};
c1basefield.prototype._init = function () {
this.element.wrapInner("<div class='wijmo-wijgrid-innercell'></div>");
this._refreshHeaderCell();
};
c1basefield.prototype.destroy = function () {
try {
_super.prototype.destroy.apply(this, arguments);
}finally {
this._destroyed = true;
}
};
c1basefield.prototype._destroy = function () {
if(this._isDestroyed()) {
return;
}
var wijgrid = this._owner();
if(wijgrid && wijgrid._dragndrop(false)) {
wijgrid._dragndrop(false).detach(this);
}
wijmo.grid.remove$dataByPrefix(this.element, this._data$prefix);
this.element.removeClass(wijgrid.options.wijCSS.widget + " wijmo-c1basefield " + wijgrid.options.wijCSS.stateDefault).html(this.element.find(".wijmo-wijgrid-headertext").html())// restore initial cell content
;
};
c1basefield.prototype._field = function (name, value) {
return wijmo.grid.dataPrefix(this.element, this._data$prefix, name, value);
};
c1basefield.prototype._removeField = function (name) {
var internalDataName = this._data$prefix + name;
this.element.removeData(internalDataName);
};
c1basefield.prototype._setOption = //isInvokedOutside stands for whether setOption is invoked by related widget
function (key, value) {
var presetFunc = this["_preset_" + key], oldValue = this.options[key], optionChanged, postsetFunc;
if(presetFunc !== undefined) {
value = presetFunc.apply(this, [
value,
oldValue
]);
}
optionChanged = (value !== oldValue);
//$.Widget.prototype._setOption.apply(this, arguments); note: there is no dynamic linkage between the arguments and the formal parameter values when strict mode is used
_super.prototype._setOption.apply(this, [
key,
value
]);
if(optionChanged) {
if(this.options.groupedIndex !== undefined) {
var groupedWidget = this._owner()._field("groupedWidgets")[this.options.groupedIndex];
if(groupedWidget && (key in groupedWidget.options)) {
groupedWidget._setOption(key, value)// update linked grouped column widget
;
}
}
postsetFunc = this["_postset_" + key];
if(postsetFunc !== undefined) {
postsetFunc.apply(this, [
value,
oldValue
]);
}
}
};
c1basefield.prototype._postset_allowMoving = function (value, oldValue) {
//no need to detach because there is allowMoving judgment in draganddrop
/*
if (value) {
if (this._owner().options.allowColMoving) {
this._owner()._dragndrop(true).attach(this);
}
} else {
this._owner()._dragndrop(true).detach(this);
}
*/
};
c1basefield.prototype._preset_clientType = function (value, oldValue) {
throw "read-only";
};
c1basefield.prototype._postset_headerText = function (value, oldValue) {
this._refreshHeaderCell();
};
c1basefield.prototype._postset_visible = function (value, oldValue) {
this._owner().ensureControl(false);
};
c1basefield.prototype._postset_width = function (value, oldValue) {
var wijgrid = this._owner();
if(wijgrid) {
this.options.ensurePxWidth = true// prevent auto expanding
;
var found = wijmo.grid.getColumnByTravIdx(wijgrid.options.columns, this.options.travIdx);
if(found) {
// *update options *
found.found.width = value;
found.found.ensurePxWidth = true// prevent auto expanding
;
}
wijgrid.setSize()// recalculate sizes and auto expand other columns if possible.
;
}
/*// change width of column.
var view = this._owner()._view(),
index = this.options.visLeavesIdx,
oldRealValue = $(view.getHeaderCell(index)).outerWidth();
view.ensureWidth(index, value, oldRealValue);*/
};
c1basefield.prototype._owner = function () {
return this._field("owner");
};
c1basefield.prototype._canSize = function () {
return this.options.allowSizing && this._owner().options.allowColSizing;
};
c1basefield.prototype._canDrag = // drag-n-drop
function () {
return this.options.allowMoving === true;
};
c1basefield.prototype._canDropTo = function (wijField) {
// parent can't be dropped into a child
if(wijmo.grid.isChildOf(this._owner().options.columns, wijField, this)) {
return false;
}
return true;
};
c1basefield.prototype._createHeaderContent = function ($container) {
return $container.html(this.options.headerText || " ");// html(value) returns "" if value is undefined
};
c1basefield.prototype._decorateHeaderContent = function ($container) {
return $container.wrapInner("<span class=\"wijmo-wijgrid-headertext\" />");
};
c1basefield.prototype._refreshHeaderCell = function () {
var $container = this.element.children(".wijmo-wijgrid-innercell").empty();
this._createHeaderContent($container);
this._decorateHeaderContent($container);
};
c1basefield.prototype._isDestroyed = function () {
return this._destroyed;
};
return c1basefield;
})(wijmo.wijmoWidget);
grid.c1basefield = c1basefield;
c1basefield.prototype._data$prefix = "c1basefield";
var c1basefield_options = (function () {
function c1basefield_options() {
/** A value indicating whether the column can be moved.
* @example
* $("#element").wijgrid({ columns: [ { allowMoving: true } ] });
*/
this.allowMoving = true;
/** A value indicating whether the column can be sized.
* @example
* $("#element").wijgrid({ columns: [ { allowSizing: true } ] });
*/
this.allowSizing = true;
/** Function used for changing content, style and attributes of the column cells.
* @example
* // Add an image which URL is obtained from the "Url" data field to the column cells.
* $("#demo").wijgrid({
* data: [
* { ID: 0, Url: "/images/0.jpg" },
* { ID: 1, Url: "/images/1.jpg" }
* ],
* columns: [
* {},
* {
* cellFormatter: function (args) {
* if (args.row.type & wijmo.grid.rowType.data) {
* args.$container
* .empty()
* .append($("<img />")
* .attr("src", args.row.data.Url));
*
* return true;
* }
* }
* }
* ]
* });
* @remarks
* @type {Function}
* Important: cellFormatter should not alter content of header and filter row cells container.
* @param {wijmo.grid.IC1BaseFieldCellFormatterArgs} args The data with this function.
* @returns {Boolean} True if container content has been changed and wijgrid should not apply the default formatting to the cell.
*/
this.cellFormatter = undefined;
/** A value indicating the key of the data field associated with a column.
* If an array of objects is used as a datasource for wijgrid, this should be string value,
* otherwise this should be an integer determining an index of the field in the datasource.
* @type {String|Number}
* @example
* $("#element").wijgrid({ columns: [{ dataKey: "ProductID" }]});
*/
this.dataKey = undefined;
/** Determines whether to use number type column width as the real width of the column.
* @example
* $("#element").wijgrid({ columns: [{ ensurePxWidth: true }]});
* @remarks
* If this option is set to true, wijgrid will use the width option of the column widget.
* If this option is undefined, wijgrid will refer to the ensureColumnsPxWidth option.
*/
this.ensurePxWidth = undefined;
/** Gets or sets the footer text.
* The text may include a placeholder: "{0}" is replaced with the aggregate.
* @example
* $("#element").wijgrid({ columns: [{ footerText: "footer" }]});
* @remarks
* If the value is undefined the footer text will be determined automatically depending on the type of the datasource:
* DOM table - text in the footer cell.
*/
this.footerText = undefined;
/** Gets or sets the header text.
* @example
* $("#element").wijgrid({ columns: [ { headerText: "column0" } ] });
* @remarks
* If the value is undefined the header text will be determined automatically depending on the type of the datasource:
* DOM table - text in the header cell.
* Array of objects - dataKey (name of the field associated with column).
* Two-dimensional array - dataKey (index of the field associated with column).
*/
this.headerText = undefined;
/** Gets or sets the text alignment of data cells. Possible values are "left", "right", "center".
* @example
* $("#element").wijgrid({ columns: [{ textAligment: "right" }]});
*/
this.textAlignment = undefined;
/** A value indicating whether column is visible.
* @example
* $("#element").wijgrid({ columns: [{ visible: true }]});
*/
this.visible = true;
/** Determines the width of the column.
* @type {String|Number}
* @example
* $("#element").wijgrid({ columns: [ { width: 150 } ] });
* $("#element").wijgrid({ columns: [ { width: "10%" } ]});
* @remarks
* The option could either be a number of string.
* Use number to specify width in pixel, use string to specify width in percentage.
* By default, wijgrid emulates the table element behavior when using number as width. This means wijgrid may not have the exact width specified. If exact width is needed, please set ensureColumnsPxWidth option of wijgrid to true.
*/
this.width = undefined;
}
return c1basefield_options;
})();
grid.c1basefield_options = c1basefield_options;
;
//c1basefield.prototype.options = $.extend(true, {}, wijmoWidget.prototype.options, new c1basefield_options());
c1basefield.prototype.options = wijmo.grid.extendWidgetOptions(wijmo.wijmoWidget.prototype.options, new c1basefield_options());
$.wijmo.registerWidget("c1basefield", c1basefield.prototype);
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="c1basefield.ts"/>
/// <reference path="interfaces.ts"/>
/// <reference path="../../../wijinput/jquery.wijmo.wijinputdate.ts"/>
/// <reference path="../../../wijinput/jquery.wijmo.wijinputmask.ts"/>
/// <reference path="../../../wijinput/jquery.wijmo.wijinputnumber.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @widget */
var c1field = (function (_super) {
__extends(c1field, _super);
function c1field() {
_super.apply(this, arguments);
}
c1field.prototype._create = function () {
_super.prototype._create.apply(this, arguments);
var wijgrid = this._owner();
this.element.addClass(wijgrid.options.wijCSS.widget + " wijmo-c1field");
};
c1field.prototype._destroy = function () {
if(this._isDestroyed()) {
return;
}
var wijgrid = this._owner();
this.element.find("*").unbind("." + this.widgetName);
if(this.$filterEditor) {
this.$filterEditor.closest("td").find(// column filter cell
"*").unbind("." + this.widgetName);
switch(this._getInputEditorType(this.options)) {
case "date":
if(this.$filterEditor.data("wijmo-wijinputdate")) {
this.$filterEditor.wijinputdate("destroy");
}
break;
case "mask":
if(this.$filterEditor.data("wijmo-wijinputmask")) {
this.$filterEditor.wijinputmask("destroy");
}
break;
case "numberCurrency":
case "numberNumber":
case "numberPercent":
if(this.$filterEditor.data("wijmo-wijinputnumber")) {
this.$filterEditor.wijinputnumber("destroy");
}
break;
}
this.$filterEditor = null;
}
this.element.removeClass(wijgrid.options.wijCSS.widget + " wijmo-c1field");
this._removeDropDownFilterList();
_super.prototype._destroy.apply(this, arguments);
};
c1field.prototype._init = function () {
_super.prototype._init.apply(this, arguments);
this.$filterEditor = null;
var wijgrid = this._owner();
this.filterRow = wijgrid._filterRow();
if(wijgrid.options.showFilter && this.options.showFilter && (this.options.dataIndex >= 0)) {
this._prepareFilterCell();
}
};
c1field.prototype._postset_aggregate = function (value, oldValue) {
this._owner().ensureControl(false);
};
c1field.prototype._postset_allowSort = function (value, oldValue) {
//this.element.find("#contentCell").empty();
//this._headerTextDOM(this.options.headerText);
this._refreshHeaderCell();
};
c1field.prototype._postset_dataType = function (value, oldValue) {
throw "read-only";
};
c1field.prototype._postset_dataParser = function (value, oldValue) {
this._owner().ensureControl(false);
};
c1field.prototype._postset_dataFormatString = function (value, oldValue) {
this._owner().ensureControl(false);
};
c1field.prototype._postset_filterOperator = function (value, oldValue) {
this._owner().ensureControl(true);
};
c1field.prototype._postset_filterValue = function (value, oldValue) {
this._owner().ensureControl(true);
};
c1field.prototype._postset_groupInfo = function (value, oldValue) {
this._owner().ensureControl(true);
};
c1field.prototype._postset_rowMerge = function (value, oldValue) {
this._owner().ensureControl(false);
};
c1field.prototype._postset_showFilter = function (value, oldValue) {
this._owner().ensureControl(false);
};
c1field.prototype._postset_sortDirection = function (value, oldValue) {
this.options.sortOrder = 0;
this._owner().ensureControl(true);
};
c1field.prototype._postset_width = function (value, oldValue) {
_super.prototype._postset_width.apply(this, arguments);
};
c1field.prototype._canDropTo = function (wijField) {
if(_super.prototype._canDropTo.apply(this, arguments)) {
//the grouped column can't be dropped into group area
if(this.options.groupedIndex !== undefined && (wijField instanceof $.wijmo.c1groupedfield)) {
return false;
}
return true;
}
return false;
};
c1field.prototype._canSort = function () {
var grid = this._owner();
return (grid && grid.options.allowSorting && this.options.allowSort && (this.options.dataIndex >= 0));
};
c1field.prototype._decorateHeaderContent = function ($container) {
if(this._canSort()) {
var wijgrid = this._owner(), $anchor = $container.wrapInner("<a class=\"wijmo-wijgrid-headertext\" href=\"#\" role=\"button\" />").children("a");
$anchor.bind("click." + this.widgetName, this, $.proxy(this._onHrefClick, this));
switch(this.options.sortDirection) {
case // sorting icon
"ascending":
$container.append($("<span class=\"wijmo-wijgrid-sort-icon " + wijgrid.options.wijCSS.icon + " " + wijgrid.options.wijCSS.iconArrowUp + "\">ascending</span>"));
break;
case "descending":
$container.append($("<span class=\"wijmo-wijgrid-sort-icon " + wijgrid.options.wijCSS.icon + " " + wijgrid.options.wijCSS.iconArrowDown + "\">descending</span>"));
break;
}
} else {
_super.prototype._decorateHeaderContent.apply(this, arguments);
}
};
c1field.prototype._prepareFilterCell = function () {
var filterCellIndex = this.options.visLeavesIdx, wijgrid = this._owner(), filterCell = null, dataValue, editorOptions, self = this, editorType, inputType = wijmo.grid.HTML5InputSupport.getDefaultInputType(wijgrid._isMobileEnv(), this.options);
if(filterCellIndex >= 0) {
wijgrid = this._owner();
if(this.filterRow) {
filterCell = $(wijmo.grid.rowAccessor.getCell(this.filterRow, filterCellIndex));
} else {
throw "exception";
}
this.$filterEditor = filterCell.find("input");
//the problem of inputing in the filter textbox
filterCell.bind((($.support).selectstart ? "selectstart" : "mousedown"), function (event) {
event.stopPropagation();
});
dataValue = wijgrid.parse(this.options, wijmo.grid.filterHelper.getSingleValue(this.options.filterValue));
// set default value
if(dataValue === null || dataValue === "undefined") {
switch(wijmo.grid.getDataType(this.options)) {
case "boolean":
dataValue = false;
break;
case "number":
case "currency":
case "datetime":
dataValue = 0;
break;
default:
dataValue = "";
}
}
editorOptions = {
culture: wijgrid.options.culture,
disabled: wijgrid.options.disabled,
decimalPlaces: (function (pattern) {
// map decimal places specified within the dataFormatString option into the decimalPlaces option of the wijinputnumber.
var test = /^(n|p|c){1}(\d*)$/.exec(pattern);
if(test && test[2]) {
return parseInt(test[2], 10);
}
test = /^(d){1}(\d*)$/.exec(pattern);
if(test) {
return 0;// left padding is not supported by wijinputnumber
}
return 2;
})(this.options.dataFormatString)
};
// create editor
switch(editorType = this._getInputEditorType(this.options)) {
case "date":
if(inputType === "text") {
this.$filterEditor.wijinputdate($.extend(editorOptions, {
date: dataValue,
dateFormat: this.options.dataFormatString || undefined,
showTrigger: true
}));
} else {
// html5 editor
this._createHtmlEditor(this.$filterEditor, inputType, wijmo.grid.HTML5InputSupport.toStr(dataValue || new Date(), inputType));
}
break;
case "mask":
this.$filterEditor.wijinputmask({
text: dataValue + ""
});
break;
case "numberCurrency":
this.$filterEditor.wijinputnumber($.extend(editorOptions, {
type: "currency",
value: dataValue
}));
break;
case "numberNumber":
if(inputType === "text") {
this.$filterEditor.wijinputnumber($.extend(editorOptions, {
value: dataValue
}));
} else {
// html5 editor
this._createHtmlEditor(this.$filterEditor, inputType, wijmo.grid.HTML5InputSupport.toStr(dataValue, inputType));
}
break;
case "numberPercent":
this.$filterEditor.wijinputnumber($.extend(editorOptions, {
type: "percent",
value: dataValue * 100
}));
break;
default:
throw wijmo.grid.stringFormat("Unsupported editor type: \"{0}\"", editorType);
}
// create button
//var filterButton = filterCell.find(".filterBtn");
filterCell.find(".wijmo-wijgrid-filter-trigger").attr(// filter button
{
"role": "button",
"aria-haspopup": "true"
}).bind("mouseenter." + this.widgetName, function (e) {
if(!self.options.disabled) {
$(this).addClass(wijgrid.options.wijCSS.stateHover);
}
}).bind("mouseleave." + this.widgetName, function (e) {
if(!self.options.disabled) {
$(this).removeClass(wijgrid.options.wijCSS.stateHover + " " + wijgrid.options.wijCSS.stateActive);
}
}).bind("mouseup." + this.widgetName, this, function (e) {
if(!self.options.disabled) {
$(this).removeClass(wijgrid.options.wijCSS.stateActive);
}
}).bind("mousedown." + this.widgetName, {
column: this
}, this._onFilterBtnClick).bind("click." + this.widgetName, function (e) {
e.preventDefault();
})// prevent # being added to url.
;
}
};
c1field.prototype._createHtmlEditor = function (input, inputType, value) {
return input.wrap("<span class=\"wijgrid-input-wrapper\"></span").attr("type", inputType).val(value);
};
c1field.prototype._onFilterBtnClick = function (e) {
var column = e.data.column, maxItemsCount = 8, wijgrid = column._owner(), filterOpLowerCase, applicableFilters, args, items, key, operator, width, eventUID, zIndex, inputType = wijmo.grid.HTML5InputSupport.getDefaultInputType(wijgrid._isMobileEnv(), column.options);
if(column.options.disabled) {
return false;
}
if(column.$dropDownFilterList) {
// close the dropdown list
column._removeDropDownFilterList();
return false;
}
e.target.focus()//TFS #24253: In IE9, wijgrid is distorted on opening filter drop-down in a scrollable grid
;
filterOpLowerCase = wijmo.grid.filterHelper.getSingleOperatorName(column.options.filterOperator).toLowerCase();
applicableFilters = wijgrid.getFilterOperatorsByDataType(wijmo.grid.getDataType(column.options));
args = {
operators: $.extend(true, [], applicableFilters),
column: // make a copy, so user can localize operators without affecting other controls
column.options
};
wijgrid._onFilterOperatorsListShowing(args);
items = [];
if(args.operators) {
$.each(args.operators, function (key, operator) {
items.push({
label: operator.displayName || operator.name,
value: operator.name,
selected: operator.name.toLowerCase() === filterOpLowerCase
});
});
}
column.$dropDownFilterList = $("<div class=\"wijmo-wijgrid-filterlist\"></div").appendTo(document.body).wijlist({
autoSize: true,
maxItemsCount: maxItemsCount,
selected: function (data, arg) {
var filterValue, editorType;
switch(editorType = column._getInputEditorType(column.options)) {
case "date":
if(inputType === "text") {
filterValue = column.$filterEditor.wijinputdate("option", "date") || new Date()// current date
;
} else {
filterValue = wijmo.grid.HTML5InputSupport.parse(column.$filterEditor.val(), inputType) || new Date();
}
break;
case "mask":
filterValue = column.$filterEditor.wijinputmask("option", "text");
break;
case "numberNumber":
if(inputType !== "text") {
filterValue = wijmo.grid.HTML5InputSupport.parse(column.$filterEditor.val(), inputType) || 0;
break;
}
// fall through
case "numberCurrency":
case "numberPercent":
filterValue = column.$filterEditor.wijinputnumber("option", "value");
if(editorType === "numberPercent") {
filterValue /= 100;
}
break;
}
column._removeDropDownFilterList();
wijgrid._handleFilter(column, arg.item.value, filterValue);
}
});
// ** zIndex
if($.ui && $.fn.zIndex) {
zIndex = wijgrid.outerDiv.zIndex()// try to get zIndex of the first z-indexed element in order to display drop down list over it.
;
if(zIndex) {
zIndex++;
}
}
column.$dropDownFilterList.css("z-index", Math.max(zIndex || 0, 9999))// 9999 is the default value
;
// zIndex **
column.$dropDownFilterList.wijlist("setItems", items).wijlist("renderList");
width = column.$dropDownFilterList.width() | 150;
column.$dropDownFilterList.width(items.length > maxItemsCount ? width + 20 : width).wijlist("refreshSuperPanel").position({
of: $(this),
my: "left top",
at: "left bottom"
});
(column.$dropDownFilterList).$button = $(this);
eventUID = (column.$dropDownFilterList).eventUID = wijmo.grid.getUID();
$(document).bind("mousedown." + column.widgetName + "." + eventUID, {
column: column
}, column._onDocMouseDown);
};
c1field.prototype._onDocMouseDown = function (e) {
var $target = $(e.target), $filterList = $target.parents(".wijmo-wijgrid-filterlist:first"), $filterButton = $target.is(".wijmo-wijgrid-filter-trigger") ? $target : $target.parents(".wijmo-wijgrid-filter-trigger:first");
if(($filterButton.length && ($filterButton[0] === e.data.column.$dropDownFilterList.$button[0])) || ($filterList.length && ($filterList[0] === e.data.column.$dropDownFilterList[0]))) {
// do nothing
} else {
e.data.column._removeDropDownFilterList();
}
};
c1field.prototype._onHrefClick = function (args) {
if(args.data.options.disabled) {
return false;
}
if(args.data.options.allowSort) {
var wijgrid = args.data._owner();
wijgrid._handleSort(args.data.options, args.ctrlKey);
}
return false;
};
c1field.prototype._removeDropDownFilterList = function () {
if(this.$dropDownFilterList) {
var eventUID = (this.$dropDownFilterList).eventUID;
this.$dropDownFilterList.remove();
this.$dropDownFilterList = null;
$(document).unbind("mousedown." + this.widgetName + "." + eventUID, this._onDocMouseDown);
}
};
c1field.prototype._getInputEditorType = // "mask", "date", "numberNumber", "numberPercent", "numberCurrency"
function (column) {
switch(wijmo.grid.getDataType(column)) {
case "number":
return (column.dataFormatString && column.dataFormatString.indexOf("p") === 0) ? "numberPercent" : "numberNumber";
case "currency":
return "numberCurrency";
case "datetime":
return "date";
default:
return "mask";
}
};
return c1field;
})(grid.c1basefield);
grid.c1field = c1field;
var c1field_options = (function (_super) {
__extends(c1field_options, _super);
function c1field_options() {
_super.apply(this, arguments);
/** Causes the grid to calculate aggregate values on the column and place them in the column footer cell or group header and footer rows.
* Possible values are: "none", "count", "sum", "average", "min", "max", "std", "stdPop", "var", "varPop" and "custom".
* @example
* $("#element").wijgrid({ columns: [{ aggregate: "count" }]});
* @remarks
* Possible values are:
* "none": no aggregate is calculated or displayed.
* "count": count of non-empty values.
* "sum": sum of numerical values.
* "average": average of the numerical values.
* "min": minimum value (numerical, string, or date).
* "max": maximum value (numerical, string, or date).
* "std": standard deviation (using formula for Sample, n-1).
* "stdPop": standard deviation (using formula for Population, n).
* "var": variance (using formula for Sample, n-1).
* "varPop": variance (using formula for Population, n).
* "custom": custom value (causing grid to throw groupAggregate event).
*
* If the showFooter option is off or grid does not contain any groups, setting the "aggregate" option has no effect.
*/
this.aggregate = "none";
/** A value indicating whether column can be sorted.
* @example
* $("#element").wijgrid({ columns: [{ allowSort: true }] });
*/
this.allowSort = true;
/** Column data type. Used to determine the rules for sorting, grouping, aggregate calculation, and so on.
* Possible values are: "string", "number", "datetime", "currency" and "boolean".
* @example
* $("#element").wijgrid({ columns: [{ dataType: "string" }]});
* @remarks
* Possible values are:
* "string": if using built-in parser any values are acceptable; " " considered as an empty string, nullString as null.
* "number": if using built-in parser only numeric values are acceptable, also " ", "" and nullString which are considered as null. Any other value throws an exception.
* "datetime": if using built-in parser only date-time values are acceptable, also " ", "" and nullString which are considered as null. Any other value throws an exception.
* "currency": if using built-in parser only numeric and currency values are acceptable, also " ", "" and nullString which are considered as null. Any other value throws an exception.
* "boolean": if using built-in parser only "true" and "false" (case-insensitive) values are acceptable, also " ", "" and nullString which are considered as null. Any other value throws an exception.
*/
this.dataType = undefined;
/**
* Determines the type of html editor for filter and cells.
* Possible values are: "number", "date", "datetime", "datetime-local", "month", "time", "text".
* @example
* $("#element").wijgrid({ columns: [{ inputType: "text" }]});
* @remarks
* If the value is set then input type element is used with "type" attribute set to the value. If the value is not set then:
* - in desktop environment a "text" input element is used as the editor.
* - in mobile environment a "number" input element is used for columns having "number" and "currency" dataType; for columns where dataType = "datetime" a "datetime" input element is used, otherwise a "text" input element is shown.
*/
this.inputType = undefined;
/** Data converter that is able to translate values from a string representation to column data type and back.
* @example
* var myBoolParser = {
* parseDOM: function (value, culture, format, nullString) {
* return this.parse(value.innerHTML, culture, format, nullString);
* },
* parse: function (value, culture, format, nullString) {
* if (typeof (value) === "boolean") return value;
*
* if (!value || (value === " ") || (value === nullString)) {
* return null;
* }
*
* switch (value.toLowerCase()) {
* case "on": return true;
* case "off": return false;
* }
*
* return NaN;
* },
* toStr: function (value, culture, format, nullString) {
* if (value === null) return nullString;
* return (value) ? "on" : "off";
* }
* }
* }
*
* $("#element").wijgrid({ columns: [ { dataType: "boolean", dataParser: myBoolParser } ] });
* @remarks
* If undefined, than the built-in parser for supported datatypes will be used.
*/
this.dataParser = undefined;
/** A pattern used for formatting and parsing column values.
* @example
* $("#element").wijgrid({
* columns: [
* { dataType: "currency" },
* { dataType: "number" },
* { dataType: "number", dataFormatString: "p0" }
* ]
* });
* @remarks
* The default value is undefined ("n" pattern will be used for "number" dataType, "d" for "datetime", "c" for "currency").
* Please see the https://github.com/jquery/globalize for a full explanation and additional values.
*/
this.dataFormatString = undefined;
/** An operations set for filtering. Must be either one of the embedded operators or custom filter operator.
* Operator names are case insensitive.
*
* @example
* $("#element").wijgrid({ columns: [{ dataType: "number", filterOperator: "Equals", filterValue: 0 }]});
* @remarks
* Embedded filter operators include:
* "NoFilter": no filter.
* "Contains": applicable to "string" data type.
* "NotContain": applicable to "string" data type.
* "BeginsWith": applicable to "string" data type.
* "EndsWith": applicable to "string" data type.
* "Equals": applicable to "string", "number", "datetime", "currency" and "boolean" data types.
* "NotEqual": applicable to "string", "number", "datetime", "currency" and "boolean" data types.
* "Greater": applicable to "string", "number", "datetime", "currency" and "boolean" data types.
* "Less": applicable to "string", "number", "datetime", "currency" and "boolean" data types.
* "GreaterOrEqual": applicable to "string", "number", "datetime", "currency" and "boolean" data types.
* "LessOrEqual": applicable to "string", "number", "datetime", "currency" and "boolean" data types.
* "IsEmpty": applicable to "string".
* "NotIsEmpty": applicable to "string".
* "IsNull": applicable to "string", "number", "datetime", "currency" and "boolean" data types.
* "NotIsNull": applicable to "string", "number", "datetime", "currency" and "boolean" data types.
*
* Full option value is:
* [filterOperartor1, ..., filterOperatorN]
* where each filter item is an object of the following kind:
* { name: <operatorName>, condition: "or"|"and" }
* where:
* name: filter operator name.
* condition: logical condition to other operators, "or" is by default.
* Example:
* filterOperator: [ { name: "Equals" }, { name: "NotEqual", condition: "and" } ]
* It is possible to use shorthand notation, the following statements are equivalent:
* filterOperator: [ { name: "Equals" }, { name: "BeginsWith" } ]
* filterOperator: [ "Equals", "BeginsWith" ]
* In the case of a single operator option name may contain only filter operator name, the following statements are equivalent:
* filterOperator: [ { name: "Equals" } ]
* filterOperator: [ "Equals" ]
* filterOperator: "Equals"
*
* Note: wijgrid built-in filter editors do not support multiple filter operators.
*
*/
this.filterOperator = "nofilter";
/** A value set for filtering.
* @example
* $("#element").wijgrid({ columns: [{ dataType: "number", filterOperator: "Equals", filterValue: 0 }]});
* @remarks
* Full option value is:
* [filterValue1, ..., filterValueN]
* where each item is a filter value for the corresponding filter operator. Example:
* filterValue: [0, "a", "b"]
*
* Built-in filter operators support array of values as an argument. Example:
* filterOperator: ["Equals", "BeginsWith"]
* filterValue: [[0, 1, 2], "a"]
* As a result of filtering all the records having 0, 1, 2, or starting with "a" will be fetched.
*
* Shorthand notation allows omitting square brackets, the following statements are equivalent:
* filterValue: ["a"]
* filterValue: [["a"]]
* filterValue: "a"
*
* Note: wijgrid built-in filter editors do not support multiple filter values.
*/
this.filterValue = undefined;
/** Used to customize the appearance and position of groups.
* @example
* $("#element").wijgrid({ columns: [{ groupInfo: { position: "header" }}]});
*/
this.groupInfo = {
expandInfo: /** @ignore */
[],
level: // infrastructure
/** @ignore */
undefined,
groupSingleRow: // infrastructure
true,
collapsedImageClass: /** Determines the CSS used to show collapsed nodes on the grid.
* @default "ui-icon-triangle-1-e".
* @example
* $("#element").wijgrid({ columns: [{ groupInfo: { collapsedImageClass: "myClass" }}] });
*/
$.wijmo.wijCSS.iconArrowRight,
expandedImageClass: /** Determines the CSS used to show expanded nodes on the grid.
* @default "ui-icon-triangle-1-se".
* @example
* $("#element").wijgrid({ columns: [{ groupInfo: { expandedImageClass: "myClass" }}] });
*/
$.wijmo.wijCSS.iconArrowRightDown,
position: /** Determines whether the grid should insert group header and/or group footer rows for this column. Possible values are: "none", "header", "footer", "headerAndFooter".
* @example
* $("#element").wijgrid({ columns: [{ groupInfo: { position: "header" }}] });
* @remarks
* Possible values are:
* "none": disables grouping for the column.
* "header": inserts header rows.
* "footer": inserts footer rows.
* "headerAndFooter": inserts header and footer rows.
*/
"none",
outlineMode: /** Determines whether the user will be able to collapse and expand the groups by clicking on the group headers, and also determines whether groups will be initially collapsed or expanded.
* Possible values are: "none", "startCollapsed", "startExpanded".
* @example
* $("#element").wijgrid({ columns: [{ groupInfo: { outlineMode: "startExpanded" }}] });
* @remarks
* Possible values are:
* "none": disables collapsing and expanding.
* "startCollapsed": groups are initially collapsed.
* "startExpanded": groups are initially expanded.
*/
"startExpanded",
headerText: /** Determines the text that is displayed in the group header rows.
* @example
* $("#element").wijgrid({ columns: [{ groupInfo: { headerText: "{1}: {0}" }}] });
* @remarks
* The text may include up to three placeholders:
* "{0}" is replaced with the value being grouped on.
* "{1}" is replaced with the group's column header.
* "{2}" is replaced with the aggregate
* The text may be set to "custom". Doing so causes the grid groupText event to be raised when processing a grouped header.
*/
undefined,
footerText: /** Determines the text that is displayed in the group footer rows.
* @example
* $("#element").wijgrid({ columns: [{ groupInfo: { footerText: "{1}: {0}" }}] });
* @remarks
* The text may include up to three placeholders:
* "{0}" is replaced with the value being grouped on.
* "{1}" is replaced with the group's column header.
* "{2}" is replaced with the aggregate
* The text may be set to "custom". Doing so causes the grid groupText event to be raised when processing a grouped footer.
*/
undefined
};
/** A value indicating whether the cells in the column can be edited.
* @example
* $("#element").wijgrid({ columns: [ { readOnly: false } ] });
*/
this.readOnly = false;
/** Determines whether rows are merged. Possible values are: "none", "free" and "restricted".
* @example
* $("#element").wijgrid({ columns: [{ rowMerge: "none" }]});
* @remarks
* Possible values are:
* "none": no row merging.
* "free": allows row with identical text to merge.
* "restricted": keeps rows with identical text from merging if rows in the previous column are merged.
*/
this.rowMerge = "none";
/** A value indicating whether filter editor will be shown in the filter row.
* @example
* $("#element").wijgrid({ columns: [{ showFilter: true }]});
*/
this.showFilter = true;
/** Determines the sort direction. Possible values are: "none", "ascending" and "descending".
* @example
* $("#element").wijgrid({ columns: [{ sortDirection: "none" }]});
* @remarks
* Possible values are:
* "none": no sorting.
* "ascending": sort from smallest to largest.
* "descending": sort from largest to smallest.
*/
this.sortDirection = "none";
/** A value indicating whether null value is allowed during editing.
* @example
* $("#element").wijgrid({ columns: [{ valueRequired: false }]});
*/
this.valueRequired = false;
}
return c1field_options;
})(grid.c1basefield_options);
grid.c1field_options = c1field_options;
;
//c1field.prototype.options = $.extend(true, {}, c1basefield.prototype.options, new c1field_options());
c1field.prototype.options = wijmo.grid.extendWidgetOptions(grid.c1basefield.prototype.options, new c1field_options());
$.wijmo.registerWidget("c1field", $.wijmo.c1basefield, c1field.prototype);
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="c1field.ts"/>
/// <reference path="c1basefield.ts"/>
/// <reference path="interfaces.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @widget */
var c1band = (function (_super) {
__extends(c1band, _super);
function c1band() {
_super.apply(this, arguments);
}
c1band.prototype._create = function () {
_super.prototype._create.apply(this, arguments);
var wijgrid = this._owner();
this.element.addClass(wijgrid.options.wijCSS.widget + " wijmo-c1band");
};
c1band.prototype._canDropTo = function (wijField) {
if(_super.prototype._canDropTo.apply(this, arguments)) {
//band can't be dropped into group area
return !(wijField instanceof $.wijmo.c1groupedfield);
}
return false;
};
return c1band;
})(grid.c1basefield);
grid.c1band = c1band;
var c1band_options = (function (_super) {
__extends(c1band_options, _super);
function c1band_options() {
_super.apply(this, arguments);
/**
* Gets a array of objects representing the band columns.
* @example
* $("#element").wijgrid({
* columns: [{
* headerText: "Band",
* columns: [
* { headerText: "ID" },
* { headerText: "Name" }
* ]
* }]
* });
*/
this.columns = [];
}
return c1band_options;
})(grid.c1field_options);
;
//c1band.prototype.options = $.extend(true, {}, c1basefield.prototype.options, new c1band_options());
c1band.prototype.options = wijmo.grid.extendWidgetOptions(grid.c1basefield.prototype.options, new c1band_options());
$.wijmo.registerWidget("c1band", $.wijmo.c1basefield, c1band.prototype);
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="c1basefield.ts"/>
/// <reference path="interfaces.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var c1groupedfield = (function (_super) {
__extends(c1groupedfield, _super);
function c1groupedfield() {
_super.apply(this, arguments);
}
c1groupedfield.prototype._create = function () {
var wijgrid = $.data(this.element[0], "wijgridowner");
this._field("owner", wijgrid);
wijmo.grid.widgetName(this.element[0], this.widgetFullName);
this._destroyed = false;
this.element.addClass("wijmo-wijgrid-group-button " + wijgrid.options.wijCSS.stateDefault + " " + wijgrid.options.wijCSS.cornerAll);
if(this.options.disabled) {
this.disable();
}
if(wijgrid.options.allowColMoving) {
wijgrid._dragndrop(true).attach(this);
}
};
c1groupedfield.prototype._init = function () {
this._refreshHeaderCell();
};
c1groupedfield.prototype.destroy = function () {
try {
_super.prototype.destroy.apply(this, arguments);
}finally {
this._destroyed = true;
}
};
c1groupedfield.prototype._destroy = function () {
if(this._isDestroyed()) {
return;
}
this.element.find("*").unbind("." + this.widgetName);
var wijgrid = this._owner();
if(wijgrid && wijgrid._dragndrop(false)) {
wijgrid._dragndrop(false).detach(this);
}
wijmo.grid.remove$dataByPrefix(this.element, this._data$prefix);
};
c1groupedfield.prototype._field = function (name, value) {
return wijmo.grid.dataPrefix(this.element, this._data$prefix, name, value);
};
c1groupedfield.prototype._removeField = function (name) {
var internalDataName = this._data$prefix + name;
this.element.removeData(internalDataName);
};
c1groupedfield.prototype._setOption = function (key, value) {
var presetFunc = this["_preset_" + key], oldValue = this.options[key], optionChanged, postsetFunc;
if(presetFunc !== undefined) {
value = presetFunc.apply(this, [
value,
oldValue
]);
}
optionChanged = (value !== oldValue);
//$.Widget.prototype._setOption.apply(this, arguments); note: there is no dynamic linkage between the arguments and the formal parameter values when strict mode is used
_super.prototype._setOption.apply(this, [
key,
value
]);
if(optionChanged) {
postsetFunc = this["_postset_" + key];
if(postsetFunc !== undefined) {
postsetFunc.apply(this, [
value,
oldValue
]);
}
}
};
c1groupedfield.prototype._postset_headerText = function (value, oldValue, isInvokedOutside) {
this._refreshHeaderCell();
};
c1groupedfield.prototype._postset_allowSort = function (value, oldValue, isInvokedOutside) {
this._refreshHeaderCell();
};
c1groupedfield.prototype._owner = function () {
return this._field("owner");
};
c1groupedfield.prototype._canSize = function () {
return this.options.allowSizing && this._owner().options.allowColSizing;
};
c1groupedfield.prototype._canDrag = // drag-n-drop
function () {
return this.options.allowMoving === true;
};
c1groupedfield.prototype._canDropTo = function (wijField) {
//band can't be dropped into group area
if(!(wijField instanceof $.wijmo.c1groupedfield)) {
return false;
}
// parent can't be dropped into a child
if(wijmo.grid.isChildOf(this._owner().options.columns, wijField, this)) {
return false;
}
return true;
};
c1groupedfield.prototype._canSort = function () {
var grid = this._owner();
return (grid && grid.options.allowSorting && this.options.allowSort && (this.options.dataIndex >= 0));
};
c1groupedfield.prototype._refreshHeaderCell = function () {
var wijCSS = this._owner().options.wijCSS, $closeButton = $("<span class=\"wijmo-wijgrid-group-button-close " + wijCSS.stateDefault + " " + wijCSS.cornerAll + "\"><span class=\"" + wijCSS.icon + " " + wijCSS.iconClose + "\"></span></span>").bind("click." + this.widgetName, this, this._onCloseClick);
this.element.html(this.options.headerText || "").prepend(// html(value) returns "" if value is undefined
$closeButton).bind("click." + this.widgetName, this, $.proxy(this._onHrefClick, this));
if(this._canSort()) {
switch(this.options.sortDirection) {
case // sorting icon
"ascending":
this.element.append($("<span class=\"wijmo-wijgrid-group-button-sort " + wijCSS.icon + " " + wijCSS.iconArrowUp + "\"></span>"));
break;
case "descending":
this.element.append($("<span class=\"wijmo-wijgrid-group-button-sort " + wijCSS.icon + " " + wijCSS.iconArrowDown + "\"></span>"));
break;
}
}
};
c1groupedfield.prototype._onCloseClick = function (args) {
var options = args.data.options;
if(!options.disabled) {
(args.data._owner())._handleUngroup(args.data.options.travIdx);
}
return false;
};
c1groupedfield.prototype._onHrefClick = function (args) {
var wijgrid = args.data._owner(), options = args.data.options, column;
if(!(options).disabled && options.allowSort) {
//find the column according to the c1groupedfield widget
column = wijmo.grid.search(wijgrid.columns(), function (test) {
return test.options.travIdx === options.travIdx;
});
column = (!column.found) ? // grouped column is invisible?
wijmo.grid.getColumnByTravIdx(wijgrid.options.columns, options.travIdx).found : column.found.options;
if(column) {
wijgrid._handleSort(column, args.ctrlKey);
}
}
return false;
};
c1groupedfield.prototype._isDestroyed = function () {
return this._destroyed;
};
return c1groupedfield;
})(wijmo.wijmoWidget);
grid.c1groupedfield = c1groupedfield;
c1groupedfield.prototype._data$prefix = "c1groupedfield";
c1groupedfield.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, {
wijMobileCSS: {
header: "ui-header ui-bar-a",
content: "ui-body-c",
stateDefault: "ui-btn-up-c",
stateHover: "ui-btn-down-c",
stateActive: "ui-btn-down-c"
},
allowMoving: /// <summary>
/// A value indicating whether the column can be moved.
/// Default: true.
/// Type: Boolean.
/// Code example: $("#element").wijgrid({ columns: [ { allowMoving: true } ] });
/// </summary>
true,
allowSort: /// <summary>
/// A value indicating whether column can be sorted.
/// Default: true.
/// Type: Boolean.
/// Code example: $("#element").wijgrid({ columns: [{ allowSort: true }] });
/// </summary>
true,
headerText: /// <summary>
/// Gets or sets the header text.
/// Default: undefined.
/// Type: String.
/// Code example: $("#element").wijgrid({ columns: [ { headerText: "column0" } ] });
/// </summary>
/// <remarks>
/// If the value is undefined the header text will be determined automatically depending on the type of the datasource:
/// DOM table - text in the header cell.
/// Array of hashes - dataKey (name of the field associated with column).
/// Two-dimensional array - dataKey (index of the field associated with column).
/// </remarks>
undefined,
sortDirection: /// <summary>
/// Determines the sort direction.
/// Possible values are: "none", "ascending" and "descending".
///
/// "none": no sorting.
/// "ascending": sort from smallest to largest.
/// "descending": sort from largest to smallest.
///
/// Default: "none".
/// Type: String.
/// Code example: $("#element").wijgrid({ columns: [{ sortDirection: "none" }] });
/// </summary>
"none"
});
$.wijmo.registerWidget("c1groupedfield", c1groupedfield.prototype);
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var bandProcessor = (function () {
function bandProcessor() { }
bandProcessor.prototype.generateSpanTable = function (root, leaves) {
this._height = this._width = this._inc = this._shift = 0;
this._table = [];
this._traverseList = [];
this._savedXPos = [];
var spanTable = this._generateSpanTable(root, leaves, true);
return spanTable;
};
bandProcessor.prototype._generateSpanTable = function (root, leaves, parentVisibility) {
var i, j, self = this;
this._height = this.getVisibleHeight(root, parentVisibility);
leaves = leaves || [];
wijmo.grid.traverse(root, function (column) {
if(column.isLeaf) {
leaves.push(column);
}
self._traverseList.push(column);
});
this._width = leaves.length;
for(i = 0; i < this._height; i++) {
this._table[i] = [];
for(j = 0; j < this._width; j++) {
this._table[i][j] = {
column: null,
colSpan: 0,
rowSpan: 0
};
}
}
this._setTableValues(root, 0, 0);
return this._table;
};
bandProcessor.prototype.getVisibleHeight = function (root, parentVisibility) {
var i, len, colVis, tmp, result = 0;
if($.isArray(root)) {
// columns
for(i = 0 , len = root.length; i < len; i++) {
tmp = this.getVisibleHeight(root[i], parentVisibility);
result = Math.max(result, tmp);
}
} else {
// column
colVis = (root.visible === undefined) ? true : root.visible;
root.parentVis = colVis && parentVisibility;
if(root.isBand) {
// band
for(i = 0 , len = root.columns.length; i < len; i++) {
tmp = this.getVisibleHeight(root.columns[i], root.parentVis);
result = Math.max(result, tmp);
}
if(!root.parentVis) {
return result;
}
root.isLeaf = (result === 0);
result++;
} else {
// general column
root.isLeaf = true;
if(root.parentVis) {
result = 1;
}
}
}
return result;
};
bandProcessor.prototype._getVisibleParent = function (column) {
while(column) {
column = this._traverseList[column.parentIdx];
if(column && (column.parentVis || column.parentVis === undefined)) {
return column;
}
}
return null;
};
bandProcessor.prototype._setTableValues = function (root, y, x) {
var i, len, tx, posX, parentIsLeaf, visibleParent;
if($.isArray(root)) {
//
for(i = 0 , len = root.length; i < len; i++) {
this._setTableValues(root[i], y, x);
}
} else {
// column
if(root.travIdx === undefined) {
throw "undefined travIdx";
}
tx = x + this._shift;
if(root.parentVis) {
posX = tx + this._inc;
this._table[y][posX].column = root;
this._savedXPos[root.travIdx] = posX;
}
if(root.isBand) {
// band
for(i = 0 , len = root.columns.length; i < len; i++) {
this._setTableValues(root.columns[i], y + 1, x);
}
}
if(root.parentVis) {
if(this._shift - tx === 0) {
//root is column or band without visible nodes
this._table[y][this._savedXPos[root.travIdx]].rowSpan = this._height - y;
this._shift++;
} else {
// band with visible nodes
this._table[y][this._savedXPos[root.travIdx]].colSpan = this._shift - tx;
}
} else {
if(!root.isBand && this._height > 0) {
visibleParent = this._getVisibleParent(root);
parentIsLeaf = (visibleParent) ? visibleParent.isLeaf : false;
if(parentIsLeaf) {
this._inc++;
}
if(y >= this._height) {
y = this._height - 1;
}
posX = x + this._shift + this._inc;
this._table[y][posX].column = root;
if(!parentIsLeaf) {
if(visibleParent && (this._savedXPos[visibleParent.travIdx] === posX)) {
this._shiftTableElements(posX, y);
}
this._inc++;
}
}
}
}
};
bandProcessor.prototype._shiftTableElements = function (x, untilY) {
var i;
for(i = 0; i < untilY; i++) {
this._table[i][x + 1] = this._table[i][x];
this._table[i][x] = {
column: null,
colSpan: 0,
rowSpan: 0
};
if(this._table[i][x + 1].column) {
this._savedXPos[this._table[i][x + 1].column.travIdx]++;
}
}
};
return bandProcessor;
})();
grid.bandProcessor = bandProcessor;
/// returns both visible and invisible leaves.
function getAllLeaves(columns) {
var leaves = [];
_getAllLeaves(columns, leaves);
return leaves;
}
grid.getAllLeaves = getAllLeaves;
function _getAllLeaves(columns, leaves) {
var i, len, column, subColumns;
if(columns) {
for(i = 0 , len = columns.length; i < len; i++) {
column = columns[i];
if(column.options) {
// widget
column = column.options;
}
subColumns = column.columns;
if(subColumns && subColumns.length) {
_getAllLeaves(subColumns, leaves);
} else {
leaves.push(column);
}
}
}
}
// returns null or { found (object), at (array) } object.
function getColumnByTravIdx(columns, travIdx) {
var i, len, column, result = null;
if(columns && travIdx >= 0) {
for(i = 0 , len = columns.length; i < len && !result; i++) {
column = columns[i];
if(column.options) {
// widget
column = column.options;
}
if(column.travIdx === travIdx) {
return {
found: column,
at: columns
};
}
if(column.columns) {
result = this.getColumnByTravIdx(column.columns, travIdx);
}
}
}
return result;
}
grid.getColumnByTravIdx = getColumnByTravIdx;
function isChildOf(columns, child, parent) {
if(child.options) {
child = child.options;
}
if(parent.options) {
parent = parent.options;
}
if(parent.isBand && child.parentIdx >= 0) {
if(child.parentIdx === parent.travIdx) {
return true;
}
if(child.parentIdx > parent.travIdx) {
var traverse = this.flatten(columns);
while(true) {
child = traverse[child.parentIdx];
if(child.travIdx === parent.travIdx) {
return true;
}
if(child.parentIdx === -1) {
break;
}
}
}
}
return false;
}
grid.isChildOf = isChildOf;
function getLeaves(columns) {
var leaves = [];
_getLeaves(columns, leaves);
return leaves;
}
grid.getLeaves = getLeaves;
function _getLeaves(columns, leaves) {
var i, len, column;
if(columns) {
for(i = 0 , len = columns.length; i < len; i++) {
column = columns[i];
if(column.isLeaf) {
leaves.push(column);
}
if(column.columns) {
_getLeaves(column.columns, leaves);
}
}
}
}
function setTraverseIndex(columns) {
return _setTraverseIndex(columns, 0, -1);// -> columns length
}
grid.setTraverseIndex = setTraverseIndex;
function _setTraverseIndex(columns, idx, parentIdx) {
var i, len, column;
if(columns) {
for(i = 0 , len = columns.length; i < len; i++) {
column = columns[i];
if(column.options) {
// widget
column = column.options;
}
column.linearIdx = i;
column.travIdx = idx++;
column.parentIdx = parentIdx;
if(column.columns) {
idx = _setTraverseIndex(column.columns, idx, idx - 1);
}
}
}
return idx;
}
function flatten(columns) {
var result = [];
wijmo.grid.traverse(columns, function (column) {
result.push(column);
});
return result;
}
grid.flatten = flatten;
function traverse(columns, callback) {
var i, len, column;
if(columns && ($.isFunction(callback))) {
for(i = 0; i < columns.length; i++) {
column = columns[i];
if(column.options) {
// widget
column = column.options;
}
len = columns.length;
callback(column, columns);
if(columns.length !== len) {
// backoff
i--;
continue;
}
if(column.columns) {
// go deeper
wijmo.grid.traverse(column.columns, callback);
}
}
}
}
grid.traverse = traverse;
//export function getAriaHeaders(visibleLeaves: wijmo.grid.IColumn[], traverseList): string[] {
// var i, len, leaf, value, result = [];
// for (i = 0, len = visibleLeaves.length; i < len; i++) {
// leaf = visibleLeaves[i];
// value = "";
// do {
// value += (<any>window).escape(leaf.headerText) + " ";
// } while ((leaf = traverseList[leaf.parentIdx])/*&& leaf.parentVis*/);
// result[i] = $.trim(value);
// }
// return result;
//}
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
/// <reference path="filterOperators.ts"/>
/// <reference path="misc.ts"/>
/// <reference path="../../../data/src/dataView.ts"/>
/// <reference path="../../../data/src/filtering.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var settingsManager = (function () {
function settingsManager(wijgrid) {
this._dvFilteringSettings = undefined;
this._dvPagingSettings = undefined;
this._dvSortingSettings = undefined;
this._wgFilteringSettings = undefined;
this._wgPagingSettings = undefined;
this._wgSortingSettings = undefined;
if(!wijgrid) {
throw "exception";
}
this._wijgrid = wijgrid;
this._dataView = wijgrid._dataViewWrapper.dataView();
this._filterCache = new wijmo.grid.filterOperatorsCache(wijgrid);
}
settingsManager.prototype.compareSettings = function () {
var result = true, a, b, i, len;
// paging
result = ((a = this.DVPagingSettings()) === (b = this.WGPagingSettings()));
if(!result && a && b) {
result = (a.pageSize === b.pageSize && a.pageIndex === b.pageIndex);
}
// sorting
if(result) {
result = ((a = this.DVSortingSettings()) === (b = this.WGSortingSettings()));
if(!result && a && b && ((len = a.length) === b.length)) {
result = true;
for(i = 0; i < len && result; i++) {
result = ((a[i].dataKey === b[i].dataKey) && (a[i].sortDirection === b[i].sortDirection));
}
}
}
// filtering
if(result) {
a = this.DVFilteringSettings();
b = this.WGFilteringSettings();
result = wijmo.grid.compareObj(a, b);
}
return result;
};
settingsManager.prototype.DVFilteringSettings = function () {
function traverse(filter, normalizedItem) {
var condition;
$.each(filter, function (i, item) {
if(typeof (item) === "string") {
// "or"\ "and"
condition = item;
} else {
if($.isArray(item)) {
traverse(item, normalizedItem);
} else {
// single filter object - { property, operator, value }
normalizedItem.filterValue.push(item.value);
normalizedItem.filterOperator.push({
name: item.originalOperator || // unwrap proxy operator
item.operator,
condition: condition
});
}
}
});
}
if(this._dvFilteringSettings === undefined) {
var foo = [], filter = this._dataView.filter();
if(filter) {
$.each(filter, function (dataKey, item) {
var normalizedItem = {
dataKey: dataKey
};
if($.isArray(item)) {
normalizedItem.filterValue = [];
normalizedItem.filterOperator = [];
traverse(item, normalizedItem);
} else if($.isPlainObject(item)) {
normalizedItem.filterValue = item.value;
normalizedItem.filterOperator = item.originalOperator || // unwrap proxy operator
item.operator || "Equals";
} else {
normalizedItem.filterValue = item;
normalizedItem.filterOperator = "Equals";
}
foo.push(normalizedItem);
});
}
this._dvFilteringSettings = (foo.length) ? foo : null;
}
return this._dvFilteringSettings;
};
settingsManager.prototype.DVPagingSettings = function () {
if(this._dvPagingSettings === undefined) {
var pageableDataView = wijmo.grid.asPagedDataView(this._dataView);
if(pageableDataView) {
var pageSize = pageableDataView.pageSize();
this._dvPagingSettings = (pageSize > 0) ? {
pageSize: pageableDataView.pageSize(),
pageIndex: pageableDataView.pageIndex()
} : null;
}
}
return this._dvPagingSettings;
};
settingsManager.prototype.DVSortingSettings = function () {
if(this._dvSortingSettings === undefined) {
var foo = [];
if(true/*this._dataView.canSort()*/ ) {
var sortDescription = wijmo.data.sorting.compile(this._dataView.sort()).normalized;
if(sortDescription) {
$.each(sortDescription, function (key, prop) {
if(prop !== null) {
foo.push({
dataKey: (typeof (prop) === "string") ? prop : prop.property,
sortDirection: prop.asc || prop.asc === undefined ? "ascending" : "descending"
});
}
});
}
}
this._dvSortingSettings = (foo.length) ? foo : null;
}
return this._dvSortingSettings;
};
settingsManager.prototype.WGFilteringSettings = function () {
if(this._wgFilteringSettings === undefined) {
var foo = [], leaves = this._wijgrid._field("leaves"), self = this;
if(leaves) {
$.each(leaves, function (key, leaf) {
if(wijmo.grid.validDataKey(leaf.dataKey) && leaf.filterOperator) {
var fvToVerify = (wijmo.grid.deepExtend({
}, {
foo: leaf.filterValue
})).foo, fopToVerify = // to avoid string values reconstruction ("abc" -> ["a", "b", "c"])
(wijmo.grid.deepExtend({
}, {
foo: leaf.filterOperator
})).foo, verifiedFop = wijmo.grid.filterHelper.verify(fopToVerify, fvToVerify, leaf.dataType, self._filterCache);
if(verifiedFop) {
foo.push({
owner: leaf,
dataKey: leaf.dataKey,
filterValue: verifiedFop.filterValue,
filterOperator: verifiedFop.filterOperator
});
}
}
});
}
this._wgFilteringSettings = (foo.length) ? foo : null;
}
return this._wgFilteringSettings;
};
settingsManager.prototype.WGPagingSettings = function () {
if(this._wgPagingSettings === undefined) {
this._wgPagingSettings = this._wijgrid.options.allowPaging ? {
pageSize: this._wijgrid.options.pageSize,
pageIndex: this._wijgrid.options.pageIndex
} : null;
}
return this._wgPagingSettings;
};
settingsManager.prototype.WGSortingSettings = function () {
if(this._wgSortingSettings === undefined) {
var sortDictionary = {
}, sortArray = [], groupedColumns = this._wijgrid._groupedColumns(true), leaves = // grouped columns ordered by the groupedIndex
this._wijgrid._field("leaves") || [], canSort = function (column) {
return (!column.isBand && column.allowSort && wijmo.grid.validDataKey(column.dataKey));
}, sortOrder = 0;
if(this._wijgrid.options.allowSorting) {
// fill the sortedDictionary with the grouped columns first
$.each(groupedColumns, function (i, leaf) {
if(canSort(leaf)) {
if(leaf.sortDirection === "none") {
leaf.sortDirection = "ascending"// use "ascending" for grouped columns by default
;
}
sortDictionary[leaf.dataKey] = {
dataKey: leaf.dataKey,
sortDirection: leaf.sortDirection,
sortOrder: sortOrder++
};
}
});
sortOrder++;
// add other columns
$.each(leaves, function (i, leaf) {
if(canSort(leaf)) {
if(leaf.sortDirection === "ascending" || leaf.sortDirection === "descending") {
if(!sortDictionary[leaf.dataKey]) {
// skip grouped columns or columns with the same dataKey
sortDictionary[leaf.dataKey] = {
dataKey: leaf.dataKey,
sortDirection: leaf.sortDirection,
sortOrder: (leaf.sortOrder || 0) + sortOrder
};
}
}
}
});
// convert {} to []
$.each(sortDictionary, function (key, value) {
sortArray.push(value);
});
// sort by sortOrder
sortArray.sort(function (a, b) {
return a.sortOrder - b.sortOrder;
});
$.each(sortArray, function (i, item) {
delete item.sortOrder;
});
}
this._wgSortingSettings = (sortArray.length) ? sortArray : null;
}
return this._wgSortingSettings;
};
settingsManager.prototype.MapWGToDV = function () {
var _this = this;
var result = {
}, foo, newDVFilterOption;
// * paging *
if(this._mapPagingParams() && (foo = this.WGPagingSettings())) {
result.pageIndex = foo.pageIndex;
result.pageSize = foo.pageSize;
} else {
result.pageSize = -1// cancel paging
;
}
// ** sorting
if(this._mapSortingParams()) {
result.sort = []// clear sorting
;
if(foo = this.WGSortingSettings()) {
result.sort = [];
$.each(foo, function (key, o) {
result.sort.push({
property: o.dataKey,
asc: o.sortDirection === "ascending"
});
});
}
}
// sorting **
this._wijgrid.deficientFilters = {
};
// ** filtering
if(this._mapFilteringParams()) {
// fill the deficientFilters
$.each(this._wijgrid._field("leaves"), function (key, leaf) {
if(wijmo.grid.validDataKey(leaf.dataKey) && ((leaf.filterOperator === undefined) ^ (leaf.filterValue === undefined))) {
_this._wijgrid.deficientFilters[leaf.dataKey] = {
filterOperator: leaf.filterOperator,
filterValue: leaf.filterValue
};
}
});
result.filter = {
};
// set filtering
if(foo = this.WGFilteringSettings()) {
result.filter = this._convertFilterToDV(foo);
}
if($.isEmptyObject(result.filter)) {
result.filter = null// must be null to clear filtering.
;
}
}
// filtering **
return result;
};
settingsManager.prototype.MapDVToWG = function () {
var foo, leavesByDataKey = {
}, mapSortingParams = this._mapSortingParams(), mapPagingParams = this._mapPagingParams(), mapFilteringParams = this._mapFilteringParams(), pagedDataView = wijmo.grid.asPagedDataView(this._dataView), self = this;
$.each(this._wijgrid._field("leaves"), function (key, leaf) {
// clear sorting
if(mapSortingParams) {
leaf.sortOrder = 0;
leaf.sortDirection = "none";
}
// clear filtering
if(mapFilteringParams) {
leaf.filterOperator = "nofilter";
leaf.filterValue = undefined;
}
leavesByDataKey[leaf.dataKey] = leaf;
});
if(mapPagingParams && pagedDataView) {
this._wijgrid.options.pageSize = pagedDataView.pageSize();
this._wijgrid.options.pageIndex = pagedDataView.pageIndex();
}
if(mapSortingParams && (foo = this.DVSortingSettings())) {
$.each(foo, function (idx, o) {
var leaf;
if((leaf = leavesByDataKey[o.dataKey])) {
leaf.sortDirection = o.sortDirection;
leaf.sortOrder = idx// restore sort order
;
}
});
}
if(mapFilteringParams) {
if(foo = this.DVFilteringSettings()) {
$.each(foo, function (key, o) {
var leaf;
if((leaf = leavesByDataKey[o.dataKey])) {
leaf.filterValue = o.filterValue;
leaf.filterOperator = o.filterOperator;
if($.isPlainObject(leaf.filterOperator)) {
// custom operator, convert operator object to operator name.
leaf.filterOperator = leaf.filterOperator.name;
}
delete self._wijgrid.deficientFilters[leaf.dataKey]// unary operator?
;
}
});
}
$.each(this._wijgrid.deficientFilters, function (dataKey, defFilter) {
leavesByDataKey[dataKey].filterOperator = defFilter.filterOperator;
leavesByDataKey[dataKey].filterValue = defFilter.filterValue;
});
}
};
settingsManager.prototype._mapPagingParams = function () {
return this._wijgrid.options.allowPaging && !this._wijgrid._customPagingEnabled() && !this._wijgrid._serverShaping();// used by c1gridview. Disable client paging because source data are paged already and contains items of the current page only.
};
settingsManager.prototype._mapSortingParams = function () {
return this._wijgrid.options.allowSorting && !this._wijgrid._serverShaping();// used by c1gridview. Disable client sorting because source data are sorted already.
};
settingsManager.prototype._mapFilteringParams = function () {
return !this._wijgrid._serverShaping();// used by c1gridview. Disable client filtering because source data are filtered already.
};
settingsManager.prototype.makeProxyFilter = function (owner, prop, name, value) {
name = name.toLowerCase();
var self = this, isDateColumn = (owner.dataType === "datetime"), result = {
originalOperator: undefined,
property: prop,
operator: name,
value: // name or filter object
value
};
var internalOp = this._filterCache.getByNameInt(name);
var builtinOp = wijmo.data.filtering.ops[name];
if((name !== "nofilter") && (internalOp.isCustom || isDateColumn)) {
// need to create a proxy filter
result.originalOperator = result.operator;
if(internalOp.isCustom) {
result.operator = $.extend(true, {
}, internalOp.op);
result.operator.apply = result.operator.operator// wijdata requires apply() function instead of operator().
;
} else {
// date column
result.operator = $.extend(true, {
}, builtinOp);
var filterRequirements = owner.inputType ? wijmo.grid.TimeUnitConverter.convertInputType(owner.inputType) : // inputType takes precedence
wijmo.grid.TimeUnitConverter.convertFormatString(owner.dataFormatString);
result.operator.apply = function (a, b) {
if(!(a instanceof Date)) {
a = self._wijgrid.parse(owner, a);
}
if(!(b instanceof Date)) {
b = self._wijgrid.parse(owner, b);
}
wijmo.grid.TimeUnitConverter.cutDate(a, filterRequirements);
wijmo.grid.TimeUnitConverter.cutDate(b, filterRequirements);
// compare formatted values
//a = self._wijgrid.toStr(owner, a);
//b = self._wijgrid.toStr(owner, b);
return builtinOp.apply(a, b);
};
}
}
return result;
};
settingsManager.prototype._convertFilterToDV = // conversion from wijgrid format
function (normalizedFilter) {
var result = {
}, manager = this;
$.each(normalizedFilter, function (i, group) {
var prop = group.dataKey, currConds = [], currConn = "and", conn, operators, values, conds;
if(!$.isPlainObject(group)) {
return;
}
operators = group.filterOperator;
values = group.filterValue;
if(operators == null) {
return;
}
if(!$.isArray(operators)) {
operators = [
operators
];
}
if(!$.isArray(values)) {
values = [
values
];
}
if(operators.length != values.length) {
throw "The number of filter operators must match the number of filter values";
}
if(operators.length == 0) {
return;
}
$.each(operators, function (i, operator) {
var value;
if(typeof operator === "string") {
operator = {
name: operator
};
}
if(!$.isPlainObject(operator) || !operator.name) {
throw "Invalid filter operator";
}
value = values[i];
if(!$.isArray(value)) {
value = [
value
];
}
conds = $.map(value, function (operand) {
return manager.makeProxyFilter(group.owner, prop, operator.name, operand);
});
function adjustConds() {
if(conds.length > 1) {
conds.splice(0, 0, "or");
} else {
conds = conds[0];
}
}
function adjustCurrConds() {
if(currConn == null) {
currConn = conn;
currConds.splice(0, 0, conn);
}
}
currConn = null;
conn = operator.condition || "or";
if(currConds.length <= 1 || currConn == conn) {
if(conds.length == 1 || currConds.length <= 1 || currConn == "or") {
currConds = currConds.concat(conds);
adjustCurrConds();
} else {
adjustConds();
currConds.push(conds);
adjustCurrConds();
}
} else {
adjustConds();
currConds = [
currConds,
conds
];
adjustCurrConds();
}
});
$.each(currConds, function (j, cond) {
if($.isArray(cond) && cond.length == 2) {
currConds[j] = cond[1];
}
});
if(currConds.length == 2 && typeof (currConds[0] === "string")) {
currConds.shift();
}
if(currConds.length == 1) {
currConds = currConds[0]// unwrap single filter
;
}
result[prop] = currConds;
})// $.each(normalizedFilter)
;
return result;
};
return settingsManager;
})();
grid.settingsManager = settingsManager;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="../../../data/src/dataView.ts"/>
/// <reference path="../data/dataViewAdapter.ts"/>
/// <reference path="interfaces.ts"/>
/// <reference path="misc.ts"/>
/// <reference path="wijgrid.ts"/>
/// <reference path="settingsManager.ts"/>
/// <reference path="htmlTableAccessor.ts"/>
/// <reference path="tally.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var dataViewWrapper = (function () {
function dataViewWrapper(wijgrid) {
this._domSource = null;
this._ignoreAllEvents = false;
this._ignoreChangeEvent = false;
this._ignoreCurrentChangedEvent = false;
this._sharedDataItems = null;
this._userData = null;
this._totals = null;
this._changeTimer = 0;
this._toDispose = [];
this._isOwnDataView = false;
this._isWijdatasource = false;
this._isDynamicWijdatasource = false;
this._wijgrid = wijgrid;
this._createDataViewWrapper()// set _dataView
;
}
dataViewWrapper.prototype.data = function () {
var dataView = this._getDataViewInst(), pagedDataView = wijmo.grid.asPagedDataView(dataView);
return {
data: this._getSharedDataItems(),
totalRows: // totalRows: dataView().length,
pagedDataView != null ? pagedDataView.totalItemCount() : (dataView.getSource() || []).length,
totals: this._getTotals(),
emptyData: this.isBoundedToDOM() ? this._domSource.emptyData : null
};
};
dataViewWrapper.prototype.dataView = function () {
return this._getDataViewInst();
};
dataViewWrapper.prototype.dispose = function () {
var dataView = this._getDataViewInst();
this._propChangeListener.dispose();
$.each(this._toDispose, function (_, disposable) {
disposable.dispose();
});
if(dataView && this._isOwnDataView) {
dataView.dispose();
}
this._wijgrid._wijDataView = null;
};
dataViewWrapper.prototype.ignoreChangeEvent = function (value) {
if(arguments.length) {
this._ignoreChangeEvent = (value === true);
} else {
return this._ignoreChangeEvent;
}
};
dataViewWrapper.prototype.ignoreCurrentChangedEvent = function (value) {
if(arguments.length) {
this._ignoreCurrentChangedEvent = (value === true);
} else {
return this._ignoreCurrentChangedEvent;
}
};
dataViewWrapper.prototype.isDataLoaded = function () {
var dataView = this._getDataViewInst();
return dataView.isLoaded();
};
dataViewWrapper.prototype.isOwnDataView = function () {
return this._isOwnDataView;
};
dataViewWrapper.prototype.getFieldsInfo = function () {
var dataView = this._getDataViewInst();
return this._propDescriptorsToFieldsInfo(dataView.getProperties());
};
dataViewWrapper.prototype._propDescriptorsToFieldsInfo = function (propDescriptors) {
var result = {
};
if(propDescriptors) {
$.each(propDescriptors, function (_, prop) {
if(prop.name === "$$hash") {
// exclude $$hash property (Angular).
return;
}
result[prop.name] = {
name: prop.name,
type: prop.type || "string"
};
});
}
return result;
};
dataViewWrapper.prototype.isBoundedToDOM = function () {
return this._domSource !== null;
};
dataViewWrapper.prototype.load = function (userData) {
this._userData = userData;
var dataView = this._getDataViewInst();
if(!dataView) {
this._createDataViewWrapper();
dataView = this._getDataViewInst();
}
this._onDataViewLoading();
var sm = new wijmo.grid.settingsManager(this._wijgrid);
if(this._needToLoad(sm)) {
var loadParams = sm.MapWGToDV(), local = false;
if(this._isWijdatasource && !this._isDynamicWijdatasource && dataView.isLoaded()) {
local = true;
}
this.ignoreCurrentChangedEvent(true)// The currentPositionChanged event fires before the change event, stop listening. Listening will be restored in the _onDataViewReset method.
;
dataView.refresh(loadParams, local);
} else {
if(this.isDataLoaded()) {
this._onDataViewLoaded();
this._onDataViewReset()// suppose that data is loaded, send notification to wijgrid.
;
}
}
};
dataViewWrapper.prototype.currentPosition = function (rowIndex) {
var dataView = this._getDataViewInst();
if(!arguments.length) {
return dataView.currentPosition();
}
this.ignoreCurrentChangedEvent(true);
try {
dataView.currentPosition(rowIndex);
}finally {
this.ignoreCurrentChangedEvent(false);
}
};
dataViewWrapper.prototype.getValue = function (indexOrItem, key) {
var dataView = this._getDataViewInst();
if(typeof (key) === "number") {
key = key + "";
}
return dataView.getProperty(indexOrItem, key);
};
dataViewWrapper.prototype.setValue = function (indexOrItem, key, value) {
var dataView = this._getDataViewInst();
this.ignoreChangeEvent(true);
try {
if(typeof (key) === "number") {
key = key + "";
}
dataView.setProperty(indexOrItem, key, value);
}finally {
this.ignoreChangeEvent(false);
}
};
dataViewWrapper.prototype.makeDirty = function () {
this._propChangeListener.removeAll()// remove old subscriptions
;
this._totals = null;
this._sharedDataItems = null;
};
dataViewWrapper.prototype._createDataViewWrapper = function () {
var dataItemToGetProperties, data = this._wijgrid.options.data, dataView = this._getDataViewInst(), isWijdatasource = false;
if(dataView) {
return;
}
if(!data) {
// DOM
this._domSource = this._processDOM(this._wijgrid.element, this._wijgrid.options.readAttributesFromData);
data = this._domSource.items;
}
isWijdatasource = (typeof (wijdatasource) !== "undefined" && (data instanceof wijdatasource));
this._isOwnDataView = ($.isArray(data) || isWijdatasource);
this._isWijdatasource = !!(this._isOwnDataView && isWijdatasource);
//this._isRemoteWijdatasource = !!(this._isOwnDataView && isWijdatasource && data.proxy);
this._isDynamicWijdatasource = !!(this._isOwnDataView && isWijdatasource && data.dynamic);
if(this._isOwnDataView) {
if(!this._domSource && this._wijgrid.options.readAttributesFromData) {
this._moveAttributesToExpando(data);
}
var tBody = this.isBoundedToDOM() && wijmo.grid.getTableSection(this._wijgrid.element, wijmo.grid.rowScope.body);
dataView = wijmo.grid.GridDataView.create(wijmo.data.asDataView(this._parseOwnData(data, tBody)));
} else {
dataView = data;
}
this._wijgrid._wijDataView = dataView;
this._toDispose.push(dataView.isLoading.subscribe($.proxy(this._onDataViewLoadingInternal, this)));
this._toDispose.push(dataView.isLoaded.subscribe($.proxy(this._onDataViewLoadedInternal, this)));
this._toDispose.push(dataView.subscribe($.proxy(this._onDataViewChangeInternal, this)));
this._toDispose.push(dataView.currentPosition.subscribe($.proxy(this._onDataViewCurrentChangedInternal, this)));
this._propChangeListener = new wijmo.grid.propChangeListener($.proxy(this._onPropertyChanged, this));
};
dataViewWrapper.prototype._parseOwnData = function (data, tbody) {
var self = this;
if(data && data.length) {
var columns = $.extend(true, [], this._wijgrid.options.columns), props = wijmo.data.ArrayDataViewBase._getProps(data[0]) || [], fieldsInfo = this._propDescriptorsToFieldsInfo(props), dataLeaves = [];
this._wijgrid._prepareColumnOptions(columns, "merge", fieldsInfo, true, true);
wijmo.grid.traverse(columns, function (column) {
if(wijmo.grid.validDataKey(column.dataKey)) {
dataLeaves.push(column);
}
});
if(columns.length/*dataLen*/ ) {
$.each(data, function (i, dataItem) {
wijmo.grid.dataViewWrapper._parseDataItem(self._wijgrid, dataItem, (tbody && tbody.rows[i]), dataLeaves);
});
}
}
return data;
};
dataViewWrapper._parseDataItem = function _parseDataItem(parseHandler, dataItem, domRow, leaves) {
$.each(leaves, function (i, leaf) {
if((wijmo.grid.getDataType(leaf) !== "string") && wijmo.grid.validDataKey(leaf.dataKey)) {
var value = dataItem[leaf.dataKey], newValue = parseHandler.parse(leaf, value);
if(isNaN(newValue)) {
// failed
var domCell = null;
if(domRow) {
domCell = domRow.cells[leaf.dataKey];
}
newValue = parseHandler.parseFailed(leaf, value, dataItem, domCell);
}
dataItem[leaf.dataKey] = newValue;
}
});
return dataItem;
};
dataViewWrapper.prototype._getDataViewInst = function () {
return this._wijgrid._wijDataView;
};
dataViewWrapper.prototype._needToLoad = function (settingsManager) {
var dataView = this._getDataViewInst();
if(this._isDynamicWijdatasource || (this._isWijdatasource && !dataView.isLoaded())) {
return true;
}
if(this._isOwnDataView && !this._isWijdatasource && this.isDataLoaded()) {
// TFS Issue #36277
return true;
}
if(this.isDataLoaded() || dataView.isLoading()) {
// data is loaded already or loading, check reshaping settings
return !settingsManager.compareSettings();
}
return true;// data is not loaded yet or user want to load them manually
};
dataViewWrapper.prototype._validateSettings = function (settingsManager) {
if(!this._isOwnDataView && this._wijgrid.options.allowPaging && ((settingsManager.DVPagingSettings() || {
}).pageSize !== (settingsManager.WGPagingSettings() || {
}).pageSize)) {
throw "The pageSize option of the external dataView can't be changed.";
}
};
dataViewWrapper.prototype._onDataViewLoadingInternal = // ** dataView events handlers
function (isLoading) {
if(this._ignoreAllEvents) {
return;
}
if(isLoading) {
if(!this._userData) {
// triggered outside
this._onDataViewLoading();
}
}
};
dataViewWrapper.prototype._onDataViewLoadedInternal = function (isLoaded) {
if(this._ignoreAllEvents) {
return;
}
if(isLoaded) {
this._onDataViewLoaded();
}
};
dataViewWrapper.prototype._onDataViewChangeInternal = function (args) {
var self = this;
if(this._ignoreAllEvents || this._ignoreChangeEvent) {
return;
}
if(args.changes) {
if(args.length && args[0].entityState() === "detached")// check first item only, suppose that other items have the same entityState.
{
return;// do not handle the detached items
}
$.each(args.changes, function (_, change) {
switch(change.changeType) {
case "remove":
self._propChangeListener.remove(change.index);
break;
case "add":
self._propChangeListener.insert(change.index, change.element);
break;
}
});
}
this._onDataViewChange.apply(this, arguments);
};
dataViewWrapper.prototype._onDataViewCurrentChangedInternal = function () {
if(this._ignoreAllEvents || this._ignoreCurrentChangedEvent) {
return;
}
this._onDataViewCurrentChanged.apply(this, arguments);
};
dataViewWrapper.prototype._onDataViewReset = // dataView events handlers **
// ** event handlers
function () {
try {
this.ignoreCurrentChangedEvent(false)// restore listening (see the load() method).
;
this.makeDirty()// force to recreate the _totals and _sharedDataItems fields when the this.data() method will be called.
;
this._wijgrid._onDataViewReset(this._userData);
}finally {
this._userData = null;
}
};
dataViewWrapper.prototype._onPropertyChanged = function (newValue) {
var self = this;
if(this._changeTimer > 0) {
window.clearTimeout(this._changeTimer);
this._changeTimer = 0;
}
if(this._changeTimer != -1) {
this._changeTimer = window.setTimeout(function () {
self._changeTimer = -1;
if(!self._wijgrid._destroyed) {
self._onDataViewChange();
}
self._changeTimer = 0;
}, 100);
}
};
dataViewWrapper.prototype._onDataViewChange = // args can be empty
function (args) {
this._onDataViewReset()// force re-rendering. TODO: handle "add", "remove", "modify" etc.
;
};
dataViewWrapper.prototype._onDataViewCurrentChanged = function (e, args) {
this._wijgrid._onDataViewCurrentPositionChanged(e, args);
};
dataViewWrapper.prototype._onDataViewLoading = function () {
this._wijgrid._onDataViewLoading();
};
dataViewWrapper.prototype._onDataViewLoaded = function () {
this._wijgrid._onDataViewLoaded();
};
dataViewWrapper.prototype._getSharedDataItems = // event handlers **
function () {
if(!this._sharedDataItems) {
var dataView = this._getDataViewInst(), len = dataView.count();
this._sharedDataItems = [];
for(var i = 0; i < len; i++) {
var dataItem = dataView.item(i);
this._propChangeListener.insert(i, dataItem);
this._sharedDataItems.push(this._wrapDataItem(dataItem, i));
}
}
if(!this._sharedDataItems) {
this._sharedDataItems = [];
}
return this._sharedDataItems;
};
dataViewWrapper.prototype._getTotals = function () {
if(!this._totals) {
var dataView = this._getDataViewInst();
this._totals = this._prepareTotals(dataView, this._wijgrid._prepareTotalsRequest(true));
}
if(!this._totals) {
this._totals = {
};
}
return this._totals;
};
dataViewWrapper.prototype._prepareTotals = function (dataView, request) {
if(!request || request.length === 0) {
return {
};
}
var i, len, j, len2, tallies = [], result = {
};
for(i = 0 , len = request.length; i < len; i++) {
tallies.push(new wijmo.grid.tally());
}
for(i = 0 , len = dataView.count(); i < len; i++) {
for(j = 0 , len2 = tallies.length; j < len2; j++) {
tallies[j].add(this._wijgrid.parse(request[j].column, this.getValue(i, request[j].column.dataKey)));
}
}
for(i = 0 , len = tallies.length; i < len; i++) {
result[request[i].column.dataKey] = tallies[i].getValueString(request[i].column);
}
return result;
};
dataViewWrapper.prototype._processDOM = // ** DOM
function ($obj, readAttributes) {
var result = {
items: [],
emptyData: [],
header: wijmo.grid.readTableSection($obj, wijmo.grid.rowScope.head)
};
if(wijmo.grid.getTableSectionLength($obj, 2) === 1 && $(wijmo.grid.getTableSectionRow($obj, 2, 0)).hasClass("wijmo-wijgrid-emptydatarow")) {
// special case - empty data row
result.emptyData = wijmo.grid.readTableSection($obj, wijmo.grid.rowScope.body);
} else {
// read data rows
result.items = wijmo.grid.readTableSection($obj, wijmo.grid.rowScope.body, readAttributes);
}
return result;
};
dataViewWrapper.prototype._moveAttributesToExpando = // DOM **
function (rawData) {
$.each(rawData, function (i, item) {
var expando = (wijmo).data.Expando.getFrom(item, true), rowMeta;
rowMeta = expando[wijmo.grid.EXPANDO] = {
cellsAttributes: {
},
rowAttributes: {
}
}// store attributes within the original item using Expando
;
if(item.rowAttributes) {
rowMeta.rowAttributes = item.rowAttributes;
delete item.rowAttributes;
}
;
$.each(item, function (dataKey, dataValue) {
if($.isArray(dataValue)) {
rowMeta.cellsAttributes[dataKey] = dataValue[1];
item[dataKey] = dataValue[0];
}
});
});
};
dataViewWrapper.prototype._wrapDataItem = function (dataItem, dataItemIndex) {
return {
values: dataItem,
originalRowIndex: dataItemIndex
};
};
dataViewWrapper.prototype._refreshSilent = // ** used by c1gridview to update underlying data during callbacks.
function () {
// used by c1gridview to refresh underlying data during callbacks.
var dataView = this._getDataViewInst();
if(dataView) {
try {
this._ignoreAllEvents = true;
dataView.refresh();
}finally {
this._ignoreAllEvents = false;
}
}
};
dataViewWrapper.prototype._unsafeReplace = function (index, newItem) {
var dataView = this._getDataViewInst();
if(!(dataView instanceof wijmo.grid.GridDataView)) {
"operation is not supported";
}
dataView._unsafeReplace(index, newItem);
};
dataViewWrapper.prototype._unsafeSplice = function (index, count, item) {
var dataView = this._getDataViewInst();
if(!(dataView instanceof wijmo.grid.GridDataView)) {
"operation is not supported";
}
if(arguments.length === 2) {
dataView._unsafeSplice(index, count);
} else {
dataView._unsafeSplice(index, count, item);
}
};
dataViewWrapper.prototype._unsafePush = function (item) {
var dataView = this._getDataViewInst();
if(!(dataView instanceof wijmo.grid.GridDataView)) {
"operation is not supported";
}
dataView._unsafePush(item);
};
return dataViewWrapper;
})();
grid.dataViewWrapper = dataViewWrapper;
// used by c1gridview to refresh underlying data during callbacks **
/** @ignore */
function asPagedDataView(dataView) {
return dataView && ("pageCount" in dataView) ? dataView : null;
}
grid.asPagedDataView = asPagedDataView;
/** @ignore */
function asEditableDataView(dataView) {
return dataView && ("commitEdit" in dataView) ? dataView : null;
}
grid.asEditableDataView = asEditableDataView;
/** @ignore */
var propChangeListener = (function () {
function propChangeListener(callback) {
this._subscriptions = [];
this._callback = callback;
}
propChangeListener.prototype.insert = function (index, dataViewItem) {
var itemSubscrArray = [], self = this;
this._subscriptions.splice(index, 0, itemSubscrArray);
$.each(dataViewItem, function (key, value) {
if(self._isValidPropName(key) && value && $.isFunction(value.subscribe)) {
itemSubscrArray.push(value.subscribe(self._callback));
}
});
};
propChangeListener.prototype.remove = function (index) {
var subscrArray = this._subscriptions[index];
if(subscrArray) {
$.each(subscrArray, function (key, propSubscr) {
propSubscr.dispose();
subscrArray[key] = null;
});
}
this._subscriptions[index] = null;
this._subscriptions.splice(index, 1);
};
propChangeListener.prototype.removeAll = function () {
var len, subscr;
while(len = this._subscriptions.length) {
this.remove(len - 1);
}
this._subscriptions = [];
};
propChangeListener.prototype.dispose = function () {
this.removeAll();
};
propChangeListener.prototype._isValidPropName = function (name) {
if(name && (typeof (name) === "string")) {
return name.match("^entityState|jQuery") === null;
}
return true;
};
return propChangeListener;
})();
grid.propChangeListener = propChangeListener;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
/// <reference path="merger.ts"/>
/// <reference path="wijgrid.ts"/>
/// <reference path="groupHelper.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var groupRange = (function () {
function groupRange(expanded, range, sum, position, hasHeaderOrFooter) {
this.cr = new wijmo.grid.cellRange(-1, -1);
this.isExpanded = false;
this._value = -1;
this._sum = -1;
this._position = "none";
this._hasHeaderOrFooter = true;
if(expanded !== undefined) {
this.isExpanded = expanded;
}
if(range !== undefined) {
this.cr = range;
}
if(sum !== undefined) {
this._sum = sum;
}
if(position !== undefined) {
this._position = position;
}
if(hasHeaderOrFooter !== undefined) {
this._hasHeaderOrFooter = hasHeaderOrFooter;
}
}
groupRange.prototype.isSubRange = function (groupRange) {
return ((this.cr.r1 >= groupRange.cr.r1) && (this.cr.r2 <= groupRange.cr.r2));
};
groupRange.prototype.toString = function () {
return this.cr.r1 + "-" + this.cr.r2;
};
groupRange.prototype.getHeaderImageClass = function (expanded) {
var groupInfo = this.owner;
if(groupInfo) {
return expanded ? groupInfo.expandedImageClass || grid.c1field.prototype.options.groupInfo.expandedImageClass : groupInfo.collapsedImageClass || grid.c1field.prototype.options.groupInfo.collapsedImageClass;
}
return null;
};
groupRange.prototype.collapse = function () {
var groupInfo, column, grid, leaves, groupedColumnsCnt;
if((groupInfo = this.owner) && (column = groupInfo.owner) && (grid = column.owner)) {
leaves = grid._field("leaves");
if(wijmo.grid.groupHelper.isParentExpanded(leaves, this.cr, groupInfo.level)) {
if((groupInfo.position !== "footer") && (groupInfo.outlineMode !== "none")) {
// do not collapse groups with .position == "footer"
groupedColumnsCnt = wijmo.grid.groupHelper.getGroupedColumnsCount(leaves);
this._collapse(grid._rows(), leaves, this, groupedColumnsCnt, grid._field("viewRenderBounds").start);
}
}
}
};
groupRange.prototype.expand = function (expandChildren) {
var groupInfo, column, grid, leaves, groupedColumnsCnt;
if((groupInfo = this.owner) && (column = groupInfo.owner) && (grid = column.owner)) {
leaves = grid._field("leaves");
if(wijmo.grid.groupHelper.isParentExpanded(leaves, this.cr, groupInfo.level)) {
groupedColumnsCnt = wijmo.grid.groupHelper.getGroupedColumnsCount(leaves);
/*var tbody = grid.$table.find("> tbody")[0];*/
this._expand(grid._rows(), leaves, this, groupedColumnsCnt, expandChildren, true, grid._field("viewRenderBounds").start);
}
}
};
groupRange.prototype._collapse = function (rowAccessor, leaves, groupRange, groupedColumnsCnt, virtualOffset) {
var groupInfo = groupRange.owner, dataStart = groupRange.cr.r1, dataEnd = groupRange.cr.r2, i, len, childRanges, childRange, j;
switch(groupInfo.position) {
case "header":
case "headerAndFooter":
this._toggleRowVisibility(rowAccessor.item(groupRange.cr.r1 - virtualOffset), undefined, false);
dataStart++;
break;
}
// hide child rows
for(i = dataStart; i <= dataEnd; i++) {
this._toggleRowVisibility(rowAccessor.item(i - virtualOffset), false);
}
// update isExpanded property
groupRange.isExpanded = false;
this._updateHeaderIcon(rowAccessor, groupRange, virtualOffset);
for(i = groupInfo.level + 1; i <= groupedColumnsCnt; i++) {
childRanges = wijmo.grid.groupHelper.getChildGroupRanges(leaves, groupRange.cr, /*groupRange.owner.level*/ i - 1);
for(j = 0 , len = childRanges.length; j < len; j++) {
childRange = childRanges[j];
childRange.isExpanded = false;
switch(childRange.owner.position) {
case "header":
case "headerAndFooter":
this._toggleRowVisibility(rowAccessor.item(childRange.cr.r1 - virtualOffset), undefined, false);
break;
}
this._updateHeaderIcon(rowAccessor, childRange, virtualOffset);
}
}
};
groupRange.prototype._expand = function (rowAccessor, leaves, groupRange, groupedColumnsCnt, expandChildren, isRoot, virtualOffset) {
var groupInfo = groupRange.owner, dataStart = groupRange.cr.r1, dataEnd = groupRange.cr.r2, i, len, childRanges, childRange, childIsRoot;
switch(groupInfo.position) {
case "header":
this._toggleRowVisibility(rowAccessor.item(dataStart - virtualOffset), true, isRoot || expandChildren);
dataStart++;
break;
case "footer":
this._toggleRowVisibility(rowAccessor.item(dataEnd - virtualOffset), true);
dataEnd--;
break;
case "headerAndFooter":
this._toggleRowVisibility(rowAccessor.item(dataStart - virtualOffset), true, isRoot || expandChildren);
if(isRoot) {
this._toggleRowVisibility(rowAccessor.item(dataEnd - virtualOffset), true);
}
dataStart++;
dataEnd--;
break;
}
if(isRoot) {
groupRange.isExpanded = true;
this._updateHeaderIcon(rowAccessor, groupRange, virtualOffset);
} else {
return;
}
if(groupRange.owner.level === groupedColumnsCnt) {
// show data rows
for(i = dataStart; i <= dataEnd; i++) {
this._toggleRowVisibility(rowAccessor.item(i - virtualOffset), true);
}
} else {
childRanges = wijmo.grid.groupHelper.getChildGroupRanges(leaves, groupRange.cr, groupRange.owner.level);
if(childRanges.length && (dataStart !== childRanges[0].cr.r1)) {
//
// a space between parent groupHeader and first child range - show single rows (groupSingleRow = false)
for(i = dataStart; i < childRanges[0].cr.r1; i++) {
this._toggleRowVisibility(rowAccessor.item(i - virtualOffset), true);
}
}
if(expandChildren) {
// throw action deeper
for(i = 0 , len = childRanges.length; i < len; i++) {
childRange = childRanges[i];
this._expand(rowAccessor, leaves, childRange, groupedColumnsCnt, expandChildren, true, virtualOffset);
}
} else {
// show only headers of the child groups or fully expand child groups with .position == "footer"\ .outlineMode == "none"
for(i = 0 , len = childRanges.length; i < len; i++) {
childRange = childRanges[i];
childIsRoot = (childRange.owner.position === "footer" || childRange.owner.outlineMode === "none") ? true : false;
this._expand(rowAccessor, leaves, childRange, groupedColumnsCnt, false, childIsRoot, virtualOffset);
}
}
}
};
groupRange.prototype._toggleRowVisibility = function (rowObj, visible, expanded) {
if(rowObj) {
if(rowObj[0]) {
if(visible !== undefined) {
rowObj[0].style.display = visible ? "" : "none";
rowObj[0]["aria-hidden"] = visible ? "false" : "true";
}
if(expanded !== undefined) {
rowObj[0]["aria-expanded"] = expanded ? "true" : "false";
}
}
if(rowObj[1]) {
if(visible !== undefined) {
rowObj[1].style.display = visible ? "" : "none";
rowObj[1]["aria-hidden"] = visible ? "false" : "true";
}
if(expanded !== undefined) {
rowObj[1]["aria-expanded"] = expanded ? "true" : "false";
}
}
}
};
groupRange.prototype._updateHeaderIcon = function (rowAccessor, groupRange, virtualOffset) {
if(groupRange.owner.position !== "footer") {
var rowObj = rowAccessor.item(groupRange.cr.r1 - virtualOffset);
if(rowObj) {
$.each(rowObj, function (i, row) {
if(row) {
var imageDiv = $(row).find("div.wijmo-wijgrid-grouptogglebtn:first-child");
if(imageDiv && imageDiv.length) {
imageDiv.toggleClass(groupRange.getHeaderImageClass(!groupRange.isExpanded), false);
imageDiv.toggleClass(groupRange.getHeaderImageClass(groupRange.isExpanded), true);
}
}
});
}
}
};
return groupRange;
})();
grid.groupRange = groupRange;
/** @ignore */
var grouper = (function () {
function grouper() {
this._groupRowIdx = 0;
}
grouper.prototype.group = function (grid, data, leaves) {
var _this = this;
this._grid = grid;
this._data = data;
this._leaves = leaves;
this._groupRowIdx = 0;
$.each(leaves, function (i, column) {
if(column.groupInfo) {
delete column.groupInfo.level;
delete column.groupInfo.expandInfo;
}
});
var groupedColumns = this._grid._groupedColumns(true), level = 1;
$.each(groupedColumns, function (i, column) {
_this._groupRowIdx = 0;
if(/*(leaf.dynamic !== true) && */ column.groupInfo && (column.groupInfo.position && (column.groupInfo.position !== "none")) && (column.dataIndex >= 0)) {
column.groupInfo.level = level;
column.groupInfo.expandInfo = [];
_this._processRowGroup(column, level++);
}
});
delete this._grid;
delete this._data;
delete this._leaves;
};
grouper.prototype._processRowGroup = function (leaf, level) {
var row, cellRange, isExpanded, startCollapsed, indentRow, groupRange, isParentCollapsed, header, footer, i, firstVisibleLeafIdx = 0, hasHeaderOrFooter = true;
$.each(this._leaves, function (i, leaf) {
if(leaf.parentVis) {
firstVisibleLeafIdx = i;
return false;
}
});
for(row = 0; row < this._data.length; row++) {
if(!(this._data[row].rowType & wijmo.grid.rowType.data)) {
continue;
}
cellRange = this._getGroupCellRange(row, leaf, level);
isExpanded = true;
startCollapsed = (leaf.groupInfo.outlineMode === "startCollapsed");
if(startCollapsed || wijmo.grid.groupHelper.isParentCollapsed(this._leaves, cellRange, level)) {
if((leaf.groupInfo.groupSingleRow === false) && (cellRange.r1 === cellRange.r2)) {
continue;
}
isExpanded = false;
}
// indent
if(level && this._grid.options.groupIndent) {
for(indentRow = cellRange.r1; indentRow <= cellRange.r2; indentRow++) {
this._addIndent(this._data[indentRow][firstVisibleLeafIdx], level);
}
}
hasHeaderOrFooter = !(leaf.groupInfo.groupSingleRow === false && (cellRange.r1 === cellRange.r2));
// insert group header/ group footer
switch(leaf.groupInfo.position) {
case "header":
groupRange = this._addGroupRange(leaf.groupInfo, cellRange, isExpanded, hasHeaderOrFooter);
for(i = cellRange.r1; i <= cellRange.r2; i++) {
this._data[i].__attr["aria-level"] = level + 1;
if(!isExpanded) {
this._data[i].__style.display = "none";
this._data[i].__attr["aria-hidden"] = true;
}
}
if(!hasHeaderOrFooter) {
break;
}
this._updateByGroupRange(groupRange, level);
isParentCollapsed = wijmo.grid.groupHelper.isParentCollapsed(this._leaves, groupRange.cr, level);
header = this._buildGroupRow(groupRange, cellRange, true, isParentCollapsed);
this._data.splice(cellRange.r1, 0, header)// insert group header
;
header.__attr["arial-level"] = level;
header.__attr["aria-expanded"] = isExpanded;
if(isParentCollapsed) {
header.__style.display = "none";
header.__attr["aria-hidden"] = true;
}
row = cellRange.r2 + 1;
break;
case "footer":
groupRange = this._addGroupRange(leaf.groupInfo, cellRange, true, hasHeaderOrFooter);
if(!hasHeaderOrFooter) {
break;
}
this._updateByGroupRange(groupRange, level);
footer = this._buildGroupRow(groupRange, cellRange, false, false);
footer.__attr["aria-level"] = level;
this._data.splice(cellRange.r2 + 1, 0, footer);
row = cellRange.r2 + 1;
isParentCollapsed = wijmo.grid.groupHelper.isParentCollapsed(this._leaves, groupRange.cr, level);
if(isParentCollapsed) {
footer.__style.display = "none";
footer.__attr["aria-hidden"] = true;
}
break;
case "headerAndFooter":
groupRange = this._addGroupRange(leaf.groupInfo, cellRange, isExpanded, hasHeaderOrFooter);
for(i = cellRange.r1; i <= cellRange.r2; i++) {
this._data[i].__attr["aria-level"] = level + 1;
if(!isExpanded) {
this._data[i].__style.display = "none";
this._data[i].__attr["aria-hidden"] = true;
}
}
if(!hasHeaderOrFooter) {
break;
}
this._updateByGroupRange(groupRange, level);
isParentCollapsed = wijmo.grid.groupHelper.isParentCollapsed(this._leaves, groupRange.cr, level);
header = this._buildGroupRow(groupRange, cellRange, true, isParentCollapsed);
footer = this._buildGroupRow(groupRange, cellRange, false, false);
this._data.splice(cellRange.r2 + 1, 0, footer);
footer.__attr["aria-level"] = level;
if(isParentCollapsed || !isExpanded) {
footer.__style.display = "none";
footer.__attr["aria-hidden"] = true;
}
this._data.splice(cellRange.r1, 0, header);
header.__attr["aria-level"] = level;
header.__attr["aria-expanded"] = isExpanded;
if(isParentCollapsed) {
header.__style.display = "none";
header.__attr["aria-hidden"] = true;
}
row = cellRange.r2 + 2;
break;
default:
throw wijmo.grid.stringFormat("Unknown Position value: \"{0}\"", leaf.groupInfo.position);
}
this._groupRowIdx++;
}
};
grouper.prototype._buildGroupRow = function (groupRange, cellRange, isHeader, isParentCollapsed) {
//when some column is hidden, the group row is not correct.
var groupInfo = groupRange.owner, leaf = groupInfo.owner, gridView = leaf.owner, row = [], groupByText = "", aggregate = //headerOffset = 0,
"", tmp, cell, caption, args, span, col, bFirst, agg;
(row).__style = {
};
(row).__attr = {
};
(row).__attr.id = ((isHeader) ? "GH" : "GF") + this._groupRowIdx + "-" + groupInfo.level;
(row).rowType = (isHeader) ? wijmo.grid.rowType.groupHeader : //"groupHeader"
wijmo.grid.rowType.groupFooter// "groupFooter";
;
//if (cellRange.c1 > -1 && ((tmp = this._data[cellRange.r1][cellRange.c1].value) !== null)) {
if((leaf.dataIndex >= 0) && ((tmp = this._data[cellRange.r1][leaf.dataIndex].value) !== null)) {
groupByText = gridView.toStr(leaf, tmp);
}
if(this._grid.options.showRowHeader) {
row.push({
html: " "
});
}
// create the summary cell
cell = {
html: "",
__attr: {
},
__style: {
}
};
if(isHeader && groupInfo.outlineMode !== "none") {
if(groupRange.isExpanded) {
cell.html = "<div class=\"" + gridView.options.wijCSS.icon + " " + groupRange.getHeaderImageClass(true) + " wijmo-wijgrid-grouptogglebtn\"> </div>";
} else {
cell.html = "<div class=\"" + gridView.options.wijCSS.icon + " " + groupRange.getHeaderImageClass(false) + " wijmo-wijgrid-grouptogglebtn\"> </div>";
}
}
row.push(cell);
// add group header text
if(leaf.aggregate && (leaf.aggregate !== "none")) {
//aggregate = this._getAggregate(cellRange, leaf, groupInfo.owner, isHeader, groupByText);
aggregate = this._getAggregate(cellRange, leaf, leaf, isHeader, groupByText);
//if (leaf.parentVis) {
// headerOffset = 1;
//}
}
caption = (isHeader) ? groupInfo.headerText : groupInfo.footerText;
// format caption
// The text may include up to three placeholders:
// "{0}" is replaced with the value being grouped on and
// "{1}" is replaced with the group's column header
// "{2}" is replaced with the aggregate
if(caption === "custom") {
args = {
data: this._data,
column: // data object.
leaf,
groupByColumn: // column that is being grouped.
groupInfo.owner,
groupText: // column initiated grouping.
groupByText,
text: // text that is being grouped.
"",
groupingStart: // text that will be displayed in the groupHeader or Footer.
cellRange.r1,
groupingEnd: // first index for the data being grouped.
cellRange.r2,
isGroupHeader: // last index for the data being grouped.
isHeader,
aggregate: aggregate
};
if(this._grid._trigger("groupText", null, args)) {
caption = args.text;
}
} else {
if((caption === undefined) || (caption === null)) {
// use default formatting
if(isHeader) {
caption = "{1}: {0}";
}
if(aggregate || (aggregate === 0)) {
caption = caption ? caption + " {2}" : "{2}";
}
}
caption = wijmo.grid.stringFormat(caption, groupByText, leaf && leaf.headerText ? leaf.headerText : "", aggregate.toString());
}
if(!caption) {
caption = " ";
}
cell.html += "<span>" + caption + "</span>";
this._addIndent(cell, groupInfo.level - 1);
// summary cells span until the end of the row or the first aggregate
//span = headerOffset;
span = 1;
col = (this._grid.options.showRowHeader) ? 1 : 0;
//for (; col < cellRange.c1; col++) { // c1 is an index of the leaf inside the this._leaves
// if (this._leaves[col].parentVis) {
// span++;
// }
//}
//col = cellRange.c1 + headerOffset;
bFirst = true;
for(; col < this._leaves.length; col++) {
tmp = this._leaves[col];
if(tmp.parentVis) {
if(bFirst) {
bFirst = false;
continue;
}
if((tmp.dynamic !== true) && tmp.aggregate && (tmp.aggregate !== "none")) {
break;
}
span++;
}
}
// add aggregates (or blanks) until the end of the row
for(; col < this._leaves.length; col++) {
tmp = this._leaves[col];
if(tmp.parentVis) {
agg = this._getAggregate(cellRange, tmp, groupInfo.owner, isHeader, groupByText);
if(!agg && (agg !== 0)) {
agg = " ";
}
row.push({
html: agg.toString(),
__attr: {
groupInfo: {
leafIndex: tmp.leavesIdx,
purpose: wijmo.grid.groupRowCellPurpose.aggregateCell
}
}
});
// will be passed into the cellStyleFormatter
}
}
cell.__attr.colSpan = span;
cell.__attr.groupInfo = {
leafIndex: leaf.leavesIdx,
purpose: wijmo.grid.groupRowCellPurpose.groupCell
}// will be passed into the cellStyleFormatter
;
return row;
};
grouper.prototype._getAggregate = function (cellRange, column, groupByColumn, isGroupHeader, groupByText) {
var aggregate = "", args, tally, row;
if(!column.aggregate || (column.aggregate === "none")) {
return aggregate;
}
if(column.aggregate === "custom") {
args = {
data: this._data,
column: // data object
column,
groupByColumn: // column that is being grouped.
groupByColumn,
groupText: // column initiated grouping.
groupByText,
text: // text that is being grouped.
"",
groupingStart: // text that will be displayed in the groupHeader or groupFooter.
cellRange.r1,
groupingEnd: // first index for the data being grouped.
cellRange.r2,
isGroupHeader: // last index for the data being grouped.
isGroupHeader
};
if(this._grid._trigger("groupAggregate", null, args)) {
aggregate = args.text;
}
} else {
tally = new wijmo.grid.tally();
for(row = cellRange.r1; row <= cellRange.r2; row++) {
tally.add(this._data[row][column.dataIndex].value);
}
aggregate = tally.getValueString(column);
}
return aggregate;
};
grouper.prototype._getGroupCellRange = function (row, leaf, level) {
var idx = leaf.leavesIdx, range = // $.inArray(leaf, this._leaves);
new wijmo.grid.cellRange(row, idx), parentRange = wijmo.grid.groupHelper.getParentGroupRange(this._leaves, range, level), value, nextValue, count;
//if (this._data[row].rowType === "data") {
if(this._data[row].rowType & wijmo.grid.rowType.data) {
value = this._data[row][leaf.dataIndex].value;
if(value instanceof Date) {
value = value.getTime();
}
for(range.r2 = row , count = this._data.length - 1; range.r2 < count; range.r2++) {
//if ((this._data[range.r2 + 1].rowType !== "data") || (parentRange && (range.r2 + 1 > parentRange.r2))) {
if(!(this._data[range.r2 + 1].rowType & wijmo.grid.rowType.data) || (parentRange && (range.r2 + 1 > parentRange.cr.r2))) {
break;
}
nextValue = this._data[range.r2 + 1][leaf.dataIndex].value;
if(nextValue instanceof Date) {
nextValue = nextValue.getTime();
}
if(value !== nextValue) {
break;
}
}
}
return range;
};
grouper.prototype._addGroupRange = function (groupInfo, cellRange, isExpanded, hasHeaderOrFooter) {
var result = null, idx = wijmo.grid.groupHelper.getChildGroupIndex(cellRange, groupInfo.expandInfo), range, expandState, r1, r2;
if(idx >= 0 && idx < groupInfo.expandInfo.length) {
result = groupInfo.expandInfo[idx];
} else {
range = new wijmo.grid.cellRange(cellRange.r1, cellRange.r1, cellRange.r2, cellRange.r2)// clone
;
expandState = (groupInfo.position === "footer" || !hasHeaderOrFooter) ? true : isExpanded && (groupInfo.outlineMode !== "startCollapsed");
result = new wijmo.grid.groupRange(expandState, range, -1, groupInfo.position, hasHeaderOrFooter);
result.owner = groupInfo;
groupInfo.expandInfo.push(result);
}
if(result && hasHeaderOrFooter) {
r1 = cellRange.r1;
r2 = cellRange.r2;
if(groupInfo.position === "headerAndFooter") {
r2 += 2;
}
if(groupInfo.position !== "headerAndFooter") {
r2++;
}
result.cr.r2 = r2;
}
return result;
};
grouper.prototype._updateByGroupRange = function (groupRange, level) {
var i, len, groupInfo, len2, j, cur, delta;
for(i = 0 , len = this._leaves.length; i < len; i++) {
groupInfo = this._leaves[i].groupInfo;
if(groupInfo && (groupInfo.level < level)) {
len2 = (groupInfo.expandInfo) ? groupInfo.expandInfo.length : 0;
for(j = 0; j < len2; j++) {
cur = groupInfo.expandInfo[j];
delta = (groupRange.position === "headerAndFooter") ? 2 : 1;
if(cur.cr.r1 >= groupRange.cr.r1 && !((cur.cr.r1 === groupRange.cr.r1) && (cur.position === "footer"))) {
cur.cr.r1 += delta;
}
if(cur.cr.r2 >= groupRange.cr.r1) {
cur.cr.r2 += delta;
}
}
}
}
};
grouper.prototype._addIndent = function (cellObj, level) {
var indent;
if(level > 0 && (indent = this._grid.options.groupIndent)) {
cellObj.__style.paddingLeft = (indent * level) + "px";
}
};
return grouper;
})();
grid.grouper = grouper;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
/// <reference path="merger.ts"/>
/// <reference path="grouper.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var groupHelper = (function () {
function groupHelper() { }
groupHelper._getGroupInfoRegExp = new RegExp(".*G([HF]){1}(\\d+)-(\\d+)$");
groupHelper.getGroupInfo = function getGroupInfo(row) {
if(row) {
var info = wijmo.grid.groupHelper._getGroupInfoRegExp.exec(row.id), level, index, isHeader;
if(info) {
level = parseInt(info[3], 10);
index = parseInt(info[2], 10);
isHeader = (info[1] === "H");
return {
level: level,
index: index,
isHeader: isHeader,
toString: function () {
return (isHeader ? "GH" : "GF") + index + "-" + level;
}
};
}
}
return null;
};
groupHelper.getColumnByGroupLevel = function getColumnByGroupLevel(leaves, level) {
var i, len, leaf;
for(i = 0 , len = leaves.length; i < len; i++) {
leaf = leaves[i];
if(leaf.groupInfo && (leaf.groupInfo.level === level)) {
return leaf;
}
}
return null;
};
groupHelper.getGroupedColumnsCount = function getGroupedColumnsCount(leaves) {
var result = 0, i, len, groupInfo;
for(i = 0 , len = leaves.length; i < len; i++) {
groupInfo = leaves[i].groupInfo;
if(groupInfo && (groupInfo.position === "header" || groupInfo.position === "headerAndFooter" || groupInfo.position === "footer")) {
result++;
}
}
return result;
};
groupHelper.getChildGroupIndex = // cellRange cellRange
// groupRange[] childExpandInfo
function getChildGroupIndex(cellRange, childExpandInfo) {
var left = 0, right = childExpandInfo.length - 1, median, cmp;
while(left <= right) {
median = ((right - left) >> 1) + left;
cmp = childExpandInfo[median].cr.r1 - cellRange.r1;
if(cmp === 0) {
return median;
}
if(cmp < 0) {
left = median + 1;
} else {
right = median - 1;
}
}
return left;
//return ~left;
};
groupHelper.getParentGroupIndex = function getParentGroupIndex(cellRange, parentExpandInfo) {
var idx = wijmo.grid.groupHelper.getChildGroupIndex(cellRange, parentExpandInfo);
if(idx > 0) {
idx--;
}
return (idx < parentExpandInfo.length) ? idx : -1;
};
groupHelper.getChildGroupRanges = // level: 1-based level of the cellRange;
function getChildGroupRanges(leaves, cellRange, level) {
var result = [], childRanges, childRange, i, len, firstChildIdx, childGroupedColumn = wijmo.grid.groupHelper.getColumnByGroupLevel(leaves, level + 1);
if(childGroupedColumn) {
childRanges = childGroupedColumn.groupInfo.expandInfo;
firstChildIdx = wijmo.grid.groupHelper.getChildGroupIndex(cellRange, childRanges);
for(i = firstChildIdx , len = childRanges.length; i < len; i++) {
childRange = childRanges[i];
if(childRange.cr.r2 <= cellRange.r2) {
result.push(childRange);
} else {
break;
}
}
}
return result;
};
groupHelper.getParentGroupRange = // level: 1-based level of the cellRange; optional.
function getParentGroupRange(leaves, cellRange, level) {
var i, groupInfo, idx;
if(level === undefined) {
level = 0xFFFF;
}
if(level - 2 >= 0) {
for(i = leaves.length - 1; i >= 0; i--) {
groupInfo = leaves[i].groupInfo;
if(!groupInfo || !groupInfo.expandInfo || (groupInfo.level < 0) || (groupInfo.level !== level - 1)) {
continue;
}
idx = wijmo.grid.groupHelper.getParentGroupIndex(cellRange, groupInfo.expandInfo);
if(idx >= 0) {
return groupInfo.expandInfo[idx];
}
}
}
return null;
};
groupHelper.isParentCollapsed = // level: 1-based level of the cellRange.
function isParentCollapsed(leaves, cellRange, level) {
var i, parentGroupRange;
if(level === 1) {
return false;
}
for(i = level; i > 1; i--) {
parentGroupRange = wijmo.grid.groupHelper.getParentGroupRange(leaves, cellRange, i);
if(parentGroupRange && !parentGroupRange.isExpanded) {
return true;
}
cellRange = parentGroupRange.cr;
}
return false;
};
groupHelper.isParentExpanded = // level: 1-based level of the cellRange.
function isParentExpanded(leaves, cellRange, level) {
var i, parentGroupRange;
if(level === 1) {
return true;
}
for(i = level; i > 1; i--) {
parentGroupRange = wijmo.grid.groupHelper.getParentGroupRange(leaves, cellRange, i);
if(parentGroupRange && parentGroupRange.isExpanded) {
return true;
}
cellRange = parentGroupRange.cr;
}
return false;
};
return groupHelper;
})();
grid.groupHelper = groupHelper;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var cellRange = (function () {
function cellRange(row1, col1, row2, col2) {
switch(arguments.length) {
case 2:
this.r1 = this.r2 = row1;
this.c1 = this.c2 = col1;
break;
case 4:
this.r1 = row1;
this.r2 = row2;
this.c1 = col1;
this.c2 = col2;
break;
default:
this.r1 = 0;
this.r2 = 0;
this.c1 = 0;
this.c2 = 0;
}
}
cellRange.prototype.isSingleCell = function () {
return ((this.r1 === this.r2) && (this.c1 === this.c2));
};
return cellRange;
})();
grid.cellRange = cellRange;
/** @ignore */
var merger = (function () {
function merger() {
}
merger.prototype.merge = function (data, visibleLeaves) {
this._leaves = visibleLeaves;
this._data = data;
var i, len, leaf;
for(i = 0 , len = this._leaves.length; i < len; i++) {
leaf = this._leaves[i];
if((leaf.dataIndex >= 0) && !leaf.isBand && (leaf.rowMerge === "free" || leaf.rowMerge === "restricted")) {
this._mergeColumn(leaf);
}
}
delete this._data;
delete this._leaves;
};
merger.prototype._mergeColumn = function (column) {
var dataIdx = column.dataIndex, i, len, range, span, spannedRow;
for(i = 0 , len = this._data.length; i < len; i++) {
//if (this.data[i].rowType !== "data") {
if(!(this._data[i].rowType & wijmo.grid.rowType.data)) {
continue;
}
range = this._getCellRange(i, column);
if(range.r1 !== range.r2) {
span = range.r2 - range.r1 + 1;
//this.data[range.r1][dataIdx].rowSpan = span;
this._data[range.r1][dataIdx].__attr.rowSpan = span;
for(spannedRow = range.r1 + 1; spannedRow <= range.r2; spannedRow++) {
//this.data[spannedRow][dataIdx] = null;
this._data[spannedRow][dataIdx].visible = false;
}
}
i = range.r2;
}
};
merger.prototype._getCellRange = function (rowIdx, column) {
var columnIdx = column.dataIndex, range = new wijmo.grid.cellRange(rowIdx, columnIdx), str = (this._data[rowIdx][columnIdx].value || "").toString(), dataLen = this._data.length, dataItem, leafIdx, prevLeaf, range2;
for(range.r2 = rowIdx; range.r2 < dataLen - 1; range.r2++) {
dataItem = this._data[range.r2 + 1];
//if ((dataItem.rowType !== "data") || (dataItem[columnIdx].value !== str)) {
if(!(dataItem.rowType & wijmo.grid.rowType.data) || ((dataItem[columnIdx].value || "").toString() !== str)) {
break;
}
}
leafIdx = column.leavesIdx// $.inArray(column, this.leaves);
;
if(leafIdx > 0 && column.rowMerge === "restricted") {
prevLeaf = this._leaves[leafIdx - 1];
if(prevLeaf.dataIndex >= 0) {
range2 = this._getCellRange(rowIdx, prevLeaf);
range.r1 = Math.max(range.r1, range2.r1);
range.r2 = Math.min(range.r2, range2.r2);
}
}
return range;
};
return merger;
})();
grid.merger = merger;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
grid.EXPANDO = "__wijgrid";
/**
* Specifies the type of a row in the grid.
*/
(function (rowType) {
rowType._map = [];
/** The header row. */
rowType.header = 1;
/** Data row. */
rowType.data = 2;
/** Alternating data row (used only as modifier of the rowType.data, not as an independent value). */
rowType.dataAlt = 4;
/** Filter row. */
rowType.filter = 8;
/** Group header row. */
rowType.groupHeader = 16;
/** Group footer row. */
rowType.groupFooter = 32;
/** Footer row. */
rowType.footer = 64;
/** Infrastructure. */
rowType.emptyDataRow = 128;
})(grid.rowType || (grid.rowType = {}));
var rowType = grid.rowType;
/**
* Determines an object render state. This enumeration can be used with the cellStyleFormatter and rowStyleFormatter options to get a formatted object state.
*/
(function (renderState) {
renderState._map = [];
/** This is the normal state. The object is rendered and not hovered, selected, or one of the elements determining the current position of the wijgrid. */
renderState.none = 0;
/** The object is being rendered. In the cellStyleFormatter, the rendered object is a table cell. In the rowStyleFormatter, the object is a table row. */
renderState.rendering = 1;
/** The object is one of the elements determining the current position of the wijgrid. */
renderState.current = 2;
/** The object is hovered over. */
renderState.hovered = 4;
/** The object is selected. */
renderState.selected = 8;
})(grid.renderState || (grid.renderState = {}));
var renderState = grid.renderState;
/**
* Infrastructure.
* @ignore
*/
(function (rowScope) {
rowScope._map = [];
rowScope.table = 0;
rowScope.head = 1;
rowScope.body = 2;
rowScope.foot = 3;
})(grid.rowScope || (grid.rowScope = {}));
var rowScope = grid.rowScope;
/**
* Infrastructure.
* @ignore
*/
(function (cellRangeExtendMode) {
cellRangeExtendMode._map = [];
cellRangeExtendMode.none = 0;
cellRangeExtendMode.toColumn = 1;
cellRangeExtendMode.toRow = 2;
})(grid.cellRangeExtendMode || (grid.cellRangeExtendMode = {}));
var cellRangeExtendMode = grid.cellRangeExtendMode;
/**
* Infrastructure.
* @ignore
*/
(function (objectMode) {
objectMode._map = [];
objectMode.createIfNull = 0;
objectMode.createAlways = 1;
objectMode.dispose = 2;
})(grid.objectMode || (grid.objectMode = {}));
var objectMode = grid.objectMode;
/**
* Determines purpose of the group row cells.
* @ignore
*/
(function (groupRowCellPurpose) {
groupRowCellPurpose._map = [];
groupRowCellPurpose.groupCell = 0;
groupRowCellPurpose.aggregateCell = 1;
})(grid.groupRowCellPurpose || (grid.groupRowCellPurpose = {}));
var groupRowCellPurpose = grid.groupRowCellPurpose;
/** @ignore */
function compareObj(a, b) {
var i, len, flag;
if($.isArray(a) && $.isArray(b)) {
if(a.length === b.length) {
flag = true;
for(i = 0 , len = a.length; i < len && flag; i++) {
flag = wijmo.grid.compareObj(a[i], b[i]);
}
return flag;
}
} else {
if($.isPlainObject(a) && $.isPlainObject(b)) {
for(i in a) {
if(a.hasOwnProperty(i)) {
if(!wijmo.grid.compareObj(a[i], b[i])) {
return false;
}
}
}
for(i in b) {
if(b.hasOwnProperty(i)) {
if(!wijmo.grid.compareObj(a[i], b[i])) {
return false;
}
}
}
return true;
} else {
if(a instanceof Date) {
a = a.getTime();
}
if(b instanceof Date) {
b = b.getTime();
}
}
}
return a === b;
}
grid.compareObj = compareObj;
/** @ignore */
function stringFormat(pattern) {
var params = [];
for (var _i = 0; _i < (arguments.length - 1); _i++) {
params[_i] = arguments[_i + 1];
}
var i, len;
if(!pattern) {
return "";
}
for(i = 0 , len = params.length; i < len; i++) {
pattern = pattern.replace(new RegExp("\\{" + i + "\\}", "gm"), params[i]);
}
return pattern;
}
grid.stringFormat = stringFormat;
/** @ignore */
function validDataKey(dataKey) {
return (dataKey && !(dataKey < 0)) || (dataKey === 0);
}
grid.validDataKey = validDataKey;
/** @ignore */
function validDate(date) {
if(date && (date instanceof Date)) {
return !isNaN(date.getTime());
}
return false;
}
grid.validDate = validDate;
/** @ignore */
function getDataType(column) {
return column.dataType || column._underlyingDataType || "string";
}
grid.getDataType = getDataType;
/** @ignore */
function iterateChildrenWidgets(item, callback) {
if(item && callback) {
item.find(".ui-widget").each(function (index, dom) {
$.each($(dom).data(), function (dataKey, dataValue) {
if(dataValue.widgetName) {
callback(index, dataValue);
}
});
return true;
});
}
}
grid.iterateChildrenWidgets = iterateChildrenWidgets;
/** @ignore */
function remove$dataByPrefix(element, prefix) {
var data$keys = [];
$.each(element.data(), function (key) {
if(key.indexOf(prefix) === 0) {
data$keys.push(key);
}
});
$.each(data$keys, function (idx, key) {
element.removeData(key);
});
}
grid.remove$dataByPrefix = remove$dataByPrefix;
/** @ignore */
var domSelection = (function () {
function domSelection(dom) {
this._dom = dom;
}
domSelection.prototype.getSelection = // The 'dom' must be an input element
function () {
var start = 0, end = 0, textRange;
if(this._dom.selectionStart !== undefined) {
// DOM3
start = this._dom.selectionStart;
end = this._dom.selectionEnd;
} else {
if(document.selection) {
// IE
textRange = document.selection.createRange().duplicate();
end = textRange.text.length// selection length
;
start = Math.abs(textRange.moveStart("character", -this._dom.value.length))// move selection to the beginning
;
end += start;
}
}
return {
start: start,
end: end,
length: end - start
};
};
domSelection.prototype.setSelection = // The 'dom' must be an input element
function (range) {
if(this._dom.selectionStart !== undefined) {
// DOM3
this._dom.setSelectionRange(range.start, range.end);
} else {
// IE
var textRange = this._dom.createTextRange();
textRange.collapse(true);
textRange.moveStart("character", range.start);
textRange.moveEnd("character", range.end);
textRange.select();
}
};
domSelection.prototype.toggleSelection = function (enable) {
var $dom = $(this._dom), useSelectStart = "onselectstart" in this._dom;
if(enable) {
if(useSelectStart) {
$dom.unbind(".wijgrid-disableSelection");
} else {
$dom.css({
"MozUserSelect": "",
"WebkitUserSelect": ""
});
}
} else {
if(useSelectStart) {
$dom.bind("selectstart.wijgrid-disableSelection", function (e) {
e.preventDefault();
});
} else {
$dom.css({
"MozUserSelect": "-moz-none",
"WebkitUserSelect": "none"
});
}
}
};
return domSelection;
})();
grid.domSelection = domSelection;
/** @ignore */
function createDynamicField(options) {
return $.extend(true, {
}, grid.c1basefield.prototype.options, grid.c1field.prototype.options, {
dynamic: true,
isLeaf: true,
isBand: false,
parentIdx: -1
}, options);
}
grid.createDynamicField = createDynamicField;
/** @ignore */
function bounds(element, client) {
if(element) {
var $dom = element.nodeType ? $(element) : element, offset = $dom.offset();
if(offset) {
if(client) {
return {
top: offset.top,
left: offset.left,
width: $dom[0].clientWidth || 0,
height: $dom[0].clientHeight || 0
};
}
return {
top: offset.top,
left: offset.left,
width: $dom.outerWidth(),
height: $dom.outerHeight()
};
}
}
return null;
}
grid.bounds = bounds;
// maxDepth = -1 -- iterate through all child elements
// default value = 3
/** @ignore */
function _getDOMText(dom, maxDepth, ignoreTextNodes) {
if(maxDepth === undefined) {
maxDepth = 3// default value
;
}
if(dom && maxDepth !== 0) {
if(!ignoreTextNodes && dom.nodeType === 3) {
// text node
return dom.nodeValue;
}
if(dom.nodeType === 1) {
// element
switch((dom).type) {
case "button":
case "text":
case "textarea":
case "select-one":
return (dom).value;
case "checkbox":
return (dom).checked.toString();
}
// go deeper
var result = "", i = 0, child;
while(child = dom.childNodes[i++]) {
result += wijmo.grid._getDOMText(child, maxDepth - 1);
}
return result;
}
}
return "";
}
grid._getDOMText = _getDOMText;
// obj, prefix, name (opt), value (opt)
/** @ignore */
function dataPrefix(obj, prefix, name, value) {
var treatAsArray = (obj.jquery || $.isArray(obj)), i, len, tmp, internalName = // arrays of jQuery objects is not supported
prefix + name;
if(arguments.length === 3) {
// getter
if(treatAsArray) {
return $.data(obj[0], internalName);// first item only
}
return $.data(obj, internalName);
} else {
// setter
if(treatAsArray) {
for(i = 0 , len = obj.length; i < len; i++) {
tmp = $.data(obj[i], internalName, value);
}
return tmp;
}
return $.data(obj, internalName, value);
}
}
grid.dataPrefix = dataPrefix;
/** @ignore */
function shallowMerge(target, src) {
if(src && target) {
var name, value, typeOf;
for(name in src) {
if(src.hasOwnProperty(name)) {
value = src[name];
typeOf = typeof (value);
if((typeOf === "string" || typeOf === "boolean" || typeOf === "number") && (target[name] === undefined)) {
target[name] = value;
}
}
}
}
}
grid.shallowMerge = shallowMerge;
/** @ignore */
function isCustomObject(value) {
return (value && (typeof (value) === "object") && !(value instanceof Date));
}
grid.isCustomObject = isCustomObject;
/** @ignore */
function search(value, test) {
var key, foo, isFunc = $.isFunction(test);
for(key in value) {
if(value.hasOwnProperty(key)) {
foo = isFunc ? test(value[key]) : (value[key] === test);
if(foo === true) {
return {
at: key,
found: value[key]
};
}
}
}
return {
at: null,
found: null
};
}
grid.search = search;
/** @ignore */
function getAttributes(dom, prevent) {
if(dom) {
var i, len, cnt = 0, result = {
}, attrValue, attrName;
for(i = 0 , len = dom.attributes.length; i < len; i++) {
attrName = dom.attributes[i].name;
if(attrName && (!prevent || !prevent(attrName))) {
attrValue = dom.getAttribute(attrName);
if(attrName === "style") {
attrValue = (typeof (attrValue) === "object") ? attrValue.cssText : attrValue;
}
if(!attrValue && attrName === "class") {
attrValue = dom.getAttribute("className");
}
if(attrValue && (typeof (attrValue) !== "function")) {
result[attrName] = attrValue;
cnt++;
}
}
}
if(cnt) {
return result;
}
}
return null;
}
grid.getAttributes = getAttributes;
// unlike the jQuery.extend(true) function the deepExtend() function doesn't skips undefined values.
/** @ignore */
function deepExtend(source, target) {
var key, src, dst, isArray, clone;
if(source) {
if(typeof (target) !== "object" && !$.isFunction(target)) {
target = {
};
}
for(key in source) {
src = source[key];
dst = target[dst];
if(src === target) {
continue;
}
if(src && ($.isPlainObject(src) || (isArray = $.isArray(src)))) {
if(isArray) {
isArray = false;
clone = dst && $.isArray(dst) ? dst : [];
} else {
clone = dst && $.isPlainObject(dst) ? dst : {
};
}
target[key] = wijmo.grid.deepExtend(src, clone);
} else {
target[key] = src;
}
}
}
return target;
}
grid.deepExtend = deepExtend;
/** @ignore */
function getKeyCodeEnum() {
if($.ui && $.ui.keyCode) {
return $.ui.keyCode;
}
if($.mobile && $.mobile.keyCode) {
return $.mobile.keyCode;
}
throw "keyCode object is not found";
}
grid.getKeyCodeEnum = getKeyCodeEnum;
/** @ignore */
function widgetName(element, name) {
if(element && element.jquery) {
element = element[0];
}
if(element) {
return (arguments.length === 1) ? $.data(element, "wijgridwidgetName") : $.data(element, "wijgridwidgetName", name);
}
return undefined;
}
grid.widgetName = widgetName;
/** @ignore */
var HTML5InputSupport = (function () {
function HTML5InputSupport() { }
HTML5InputSupport._requiresExtendedSupport = {
"date": "",
"datetime": "",
"datetime-local": "",
"month": "",
"time": ""
};
HTML5InputSupport.isExtendSupportRequired = function isExtendSupportRequired(inputType) {
inputType = (inputType || "").toLowerCase();
return (inputType in wijmo.grid.HTML5InputSupport._requiresExtendedSupport);
};
HTML5InputSupport.getDefaultInputType = function getDefaultInputType(mobileEnvironment, column) {
var inputType = column.inputType;
if(!inputType) {
// determine the editor's type automatically
inputType = "text"// default
;
if(mobileEnvironment) {
switch(wijmo.grid.getDataType(column)) {
case "number":
case "currency":
inputType = "number";
break;
case "datetime":
inputType = "datetime";
break;
}
}
}
return inputType;
};
HTML5InputSupport.toStr = function toStr(value, inputType) {
var result = value;
inputType = (inputType || "").toLowerCase();
if(wijmo.grid.HTML5InputSupport.isExtendSupportRequired(inputType)) {
switch(inputType) {
case "datetime":
result = (value) ? result = Globalize.format(value, "yyyy-MM-ddTHH:mm:ssZ") : "";
break;
case "datetime-local":
result = (value) ? result = Globalize.format(value, "yyyy-MM-ddTHH:mm:ss") : "";
break;
case "date":
result = (value) ? result = Globalize.format(value, "yyyy-MM-dd") : "";
break;
case "month":
result = (value) ? result = Globalize.format(value, "yyyy-MM") : "";
break;
case "time":
result = (value) ? result = Globalize.format(value, "HH:mm:ss") : "";
break;
}
} else {
result = value + "";
}
return result;
};
HTML5InputSupport.parse = function parse(value, inputType) {
var result, fallback = function (date) {
date = new Date(date);
if(!wijmo.grid.validDate(date)) {
date = null;
}
return date;
};
inputType = (inputType || "").toLowerCase();
if(wijmo.grid.HTML5InputSupport.isExtendSupportRequired(inputType)) {
switch(inputType) {
case "datetime":
result = Globalize.parseDate(value, "yyyy-MM-ddTHH:mm:ssZ") || Globalize.parseDate(value, "yyyy-MM-ddTHH:mmZ") || fallback(value);
break;
case "datetime-local":
result = Globalize.parseDate(value, "yyyy-MM-ddTHH:mm:ss") || Globalize.parseDate(value, "yyyy-MM-ddTHH:mm") || fallback(value);
break;
case "date":
result = Globalize.parseDate(value, "yyyy-MM-dd") || fallback(value);
break;
case "month":
result = Globalize.parseDate(value, "yyyy-MM");
break;
case "time":
result = Globalize.parseDate(value, "HH:mm:ss") || Globalize.parseDate(value, "HH:mm");
;
break;
case "number":
result = parseFloat(value);
}
} else {
result = value;
}
return result;
};
HTML5InputSupport.extend = function extend(value, extendWith, inputType) {
if(!value) {
value = extendWith;
} else {
inputType = (inputType || "").toLowerCase();
switch(inputType) {
case "date":
value.setFullYear(extendWith.getFullYear(), extendWith.getMonth(), extendWith.getDate());
break;
case "month":
value.setFullYear(extendWith.getFullYear(), extendWith.getMonth());
break;
case "time":
value.setHours(extendWith.getHours());
value.setMinutes(extendWith.getMinutes());
value.setSeconds(extendWith.getSeconds());
break;
default:
value = extendWith;
}
}
return value;
};
return HTML5InputSupport;
})();
grid.HTML5InputSupport = HTML5InputSupport;
// * taken from jQuery UI
/** @ignore */
function isOverAxis(x, reference, size) {
// Determines when x coordinate is over "b" element axis
return (x > reference) && (x < (reference + size));
}
grid.isOverAxis = isOverAxis;
/** @ignore */
function isOver(y, x, top, left, height, width) {
// Determines when x, y coordinates is over "b" element
return wijmo.grid.isOverAxis(y, top, height) && wijmo.grid.isOverAxis(x, left, width);
}
grid.isOver = isOver;
// taken from jQuery UI *
// ** uid
var __uid = 0;
/** @ignore */
function getUID() {
return "uid" + __uid++;
}
grid.getUID = getUID;
// uid **
// * compatibility: export members to the $.wijmo.wijgrid "namespace" *
$.extend($.wijmo.wijgrid, {
rowType: wijmo.grid.rowType,
renderState: wijmo.grid.renderState,
bounds: wijmo.grid.bounds
});
// used by unit tests. TODO: remove
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
(function (grid) {
/** @ignore */
(function (TimeUnit) {
TimeUnit._map = [];
TimeUnit.Millisecond = 1;
TimeUnit.Second = 2;
TimeUnit.Minute = 4;
TimeUnit.Hour = 8;
TimeUnit.Day = 16;
TimeUnit.Month = 32;
TimeUnit.Year = 64;
TimeUnit.DATE = TimeUnit.Year | TimeUnit.Month | TimeUnit.Day;
TimeUnit.TIME = TimeUnit.Hour | TimeUnit.Minute | TimeUnit.Second | TimeUnit.Millisecond;
TimeUnit.ALL = TimeUnit.DATE | TimeUnit.TIME;
})(grid.TimeUnit || (grid.TimeUnit = {}));
var TimeUnit = grid.TimeUnit;
;
/** @ignore */
var TimeUnitConverter = (function () {
function TimeUnitConverter() { }
TimeUnitConverter.convertInputType = /**
* @param inputType One of the HTML input type values (date-time).
*/
function convertInputType(inputType) {
var formatString = wijmo.grid.TimeUnitConverter.convertInputTypeToFormatString(inputType), result = wijmo.grid.TimeUnitConverter.convertFormatString(formatString);
return result;
};
TimeUnitConverter.convertInputTypeToFormatString = function convertInputTypeToFormatString(inputType) {
// specific format values are not important here.
switch((inputType || "").toLowerCase()) {
case "datetime":
case "datetime-local":
return "f";// long date, short time
case "date":
return "d";// short date
case "month":
return "Y";// year-and-month
case "time":
return "t";// short time
}
return "";
};
TimeUnitConverter.convertFormatString = /**
* @param dateFormatString
*/
function convertFormatString(dateFormatString) {
var result = 0;
if(dateFormatString) {
// ** check one-char standard formats **
if(dateFormatString.length === 1) {
switch(dateFormatString[0]) {
case "t":
// short Time
return TimeUnit.Hour | TimeUnit.Minute;
case "T":
// long Time
return TimeUnit.TIME;
case "d":
// short Date
case "D":
// long Date
return TimeUnit.DATE;
case "Y":
// month/year
return TimeUnit.Month | TimeUnit.Year;
case "M":
// month/day
return TimeUnit.Month | TimeUnit.Day;
case "f" , "F" , "S":
return TimeUnit.ALL;
}
}
// ** check custom tokens **
var quoteFirst, quoteLast;
// remove quoted text
if(((quoteFirst = dateFormatString.indexOf("'")) >= 0) && ((quoteLast = dateFormatString.lastIndexOf("'")) >= 0) && (quoteFirst !== quoteLast)) {
dateFormatString = dateFormatString.substr(0, quoteFirst) + dateFormatString.substring(quoteLast + 1, dateFormatString.length - 1);
}
// the validness of the string is not a subject to check
for(var i = 0, len = dateFormatString.length; i < len; i++) {
switch(dateFormatString[i]) {
case "d":
// day: d, dd, ddd, dddd
result |= TimeUnit.Day;
break;
case "M":
// month: M, MM, MMM, MMMM
result |= TimeUnit.Month;
break;
case "y":
// year: yy, yyyy
result |= TimeUnit.Year;
break;
case "m":
// minute: m, mm
result |= TimeUnit.Minute;
break;
case "h":
// hour: h, hh
case "H":
// hour: H, HH
result |= TimeUnit.Hour;
break;
case "s":
// second: s, ss
result |= TimeUnit.Second;
break;
case "f":
// milliseconds: f, ff, fff
result |= TimeUnit.Millisecond;
break;
}
}
}
return result || TimeUnit.ALL;
};
TimeUnitConverter.cutDate = function cutDate(date, timeUnit) {
if(date) {
timeUnit = ~timeUnit;
if(timeUnit & TimeUnit.Millisecond) {
date.setMilliseconds(0);
}
if(timeUnit & TimeUnit.Second) {
date.setSeconds(0);
}
if(timeUnit & TimeUnit.Minute) {
date.setMinutes(0);
}
if(timeUnit & TimeUnit.Hour) {
date.setHours(0);
}
if(timeUnit & TimeUnit.Day) {
date.setDate(1);
}
if(timeUnit & TimeUnit.Month) {
date.setMonth(0);
}
if(timeUnit & TimeUnit.Year) {
date.setFullYear(0);
}
}
return date;
};
return TimeUnitConverter;
})();
grid.TimeUnitConverter = TimeUnitConverter;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="wijgrid.ts"/>
/// <reference path="interfaces.ts"/>
/// <reference path="../../../data/src/dataView.ts"/>
/// <reference path="../../../data/src/filtering.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var builtInFilterOperators = (function () {
function builtInFilterOperators() { }
builtInFilterOperators.NoFilterOp = {
applicableTo: null,
name: // any type
"NoFilter",
arity: 1,
operator: function () {
return true;
}
};
return builtInFilterOperators;
})();
/** @ignore */
var filterOperatorsCache = (function () {
function filterOperatorsCache(wijgrid) {
this._cache = {
};
var self = this;
this._wijgrid = wijgrid;
this._addOperator(null, builtInFilterOperators.NoFilterOp);
$.each(wijmo.data.filtering.ops, function (name, op) {
self._addOperator(name, op);
});
$.each(wijgrid.options.customFilterOperators, function (key, fop) {
self._addOperator(null, fop, true);
});
}
filterOperatorsCache.prototype.getByName = function (name) {
var fop = this.getByNameInt(name);
return (fop) ? fop.op : null;
};
filterOperatorsCache.prototype.getByNameInt = function (name) {
return this._cache[(name || "").toLowerCase()];
};
filterOperatorsCache.prototype.getByDataType = function (dataType) {
var intResult = [], result;
$.each(this._cache, function (key, val) {
var fop = val.op;
if(!fop.applicableTo/* NoFilter*/ || $.inArray(dataType, fop.applicableTo) >= 0) {
intResult.push(val);
}
});
switch(this._wijgrid.options.filterOperatorsSortMode.toLowerCase()) {
case "alphabetical":
intResult.sort(this._sortAlpha);
break;
case "alphabeticalcustomfirst":
intResult.sort(this._sortAlphaCustomFirst);
break;
case "alphabeticalembeddedFirst":
intResult.sort(this._sortAlphaEmbeddedFirst);
break;
case "none":
// do nothing
break;
default:
break;
}
result = $.map(intResult, function (val, key) {
return val.op;
});
return result;
};
filterOperatorsCache.prototype._addOperator = function (name, fop, isCustom) {
if (typeof isCustom === "undefined") { isCustom = false; }
if(name && !fop.name) {
fop.name = name;
}
name = (name || fop.name).toLowerCase();
if(!this._cache[name]) {
this._cache[name] = {
op: fop,
isCustom: (isCustom === true)
};
}
};
filterOperatorsCache.prototype._sortAlpha = function (a, b) {
var n1 = a.op.name.toLowerCase(), n2 = b.op.name.toLowerCase();
if(n1 !== n2) {
if(n1 === "nofilter") {
return -1;
}
if(n2 === "nofilter") {
return 1;
}
}
if(n1 === n2) {
return 0;
}
return (n1 < n2) ? -1 : 1;
};
filterOperatorsCache.prototype._sortAlphaEmbeddedFirst = function (a, b) {
var n1 = a.op.name.toLowerCase(), n2 = b.op.name.toLowerCase();
if(n1 !== n2) {
if(n1 === "nofilter") {
return -1;
}
if(n2 === "nofilter") {
return 1;
}
}
if(a.isCustom !== b.isCustom) {
if(a.isCustom) {
return 1;
}
if(b.isCustom) {
return -1;
}
}
if(n1 === n2) {
return 0;
}
return (n1 < n2) ? -1 : 1;
};
filterOperatorsCache.prototype._sortAlphaCustomFirst = function (a, b) {
var n1 = a.op.name.toLowerCase(), n2 = b.op.name.toLowerCase();
if(n1 !== n2) {
if(n1 === "nofilter") {
return -1;
}
if(n2 === "nofilter") {
return 1;
}
}
if(a.isCustom !== b.isCustom) {
if(a.isCustom) {
return -1;
}
if(b.isCustom) {
return 1;
}
}
if(n1 === n2) {
return 0;
}
return (n1 < n2) ? -1 : 1;
};
return filterOperatorsCache;
})();
grid.filterOperatorsCache = filterOperatorsCache;
/** @ignore */
var filterHelper = (function () {
function filterHelper() { }
filterHelper.marker = "_wijgrid";
filterHelper.getSingleValue = // filterValue
// [filterValue, ..., filterValue]
// [[filterValue, ..., filterValue], ..., [filterValue, ..., filterValue]]
function getSingleValue(filterValue) {
if($.isArray(filterValue)) {
filterValue = filterValue[0];
if($.isArray(filterValue)) {
filterValue = filterValue[0];
}
}
return filterValue;
};
filterHelper.getSingleOperatorName = // filterOperator -> name | { name, condition }
// filterOperator -> filterOperator | [ filterOperator, ..., filterOperator]
function getSingleOperatorName(filterOperator) {
if($.isArray(filterOperator)) {
filterOperator = filterOperator[0];
}
return filterOperator.name || filterOperator || "";
};
filterHelper.verify = // filterOperator: opName | [opName, ..., opName] | [ { name, condition }, ..., { name, condition } ]
// filterValue: filterValue | [filterValue, ... , filterValue] | [[], ..., []]
function verify(filterOperator, filterValue, dataType, cache) {
if(filterOperator) {
if($.isArray(filterOperator)) {
var i, len, fop = [], fval = [];
if(!$.isArray(filterValue)) {
filterValue = [
filterValue
];
}
for(i = 0 , len = filterOperator.length; i < len; i++) {
if(wijmo.grid.filterHelper._verifySingleOp(filterOperator[i], filterValue[i], dataType, cache)) {
fop.push({
name: filterOperator[i].name || filterOperator[i],
condition: filterOperator[i].condition || "or"
});
fval.push(filterValue ? filterValue[i] : undefined);
}
}
if(fop.length) {
return {
filterOperator: fop,
filterValue: fval
};
}
} else {
if(wijmo.grid.filterHelper._verifySingleOp(filterOperator, filterValue, dataType, cache)) {
return {
filterOperator: // compatibility with old model
filterOperator,
filterValue: filterValue
};
}
}
}
return null;
};
filterHelper._verifySingleOp = // filterOpeator: name | { name, condition }
function _verifySingleOp(filterOperator, filterValue, dataType, cache) {
if(filterOperator && (filterOperator = (filterOperator.name || filterOperator))) {
var fop;
filterOperator = (filterOperator || "").toLowerCase();
if((filterOperator !== "nofilter" || filterValue !== undefined) && (fop = cache.getByName(filterOperator))) {
if(fop.applicableTo === null/*NoFilter*/ || $.inArray(dataType || "string", fop.applicableTo) >= 0) {
if(fop.arity === 1 || (fop.arity > 1 && wijmo.grid.filterHelper.getSingleValue(filterValue) !== undefined)) {
return true;
}
}
}
}
return false;
};
return filterHelper;
})();
grid.filterHelper = filterHelper;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
/// <reference path="misc.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
function getTableSection(table, scope) {
if(table && !table.nodeType) {
table = table[0];
}
if(table) {
switch(scope) {
case wijmo.grid.rowScope.head:
return table.tHead;
case wijmo.grid.rowScope.body:
if(table.tBodies) {
return table.tBodies[0] || null;
}
break;
case wijmo.grid.rowScope.foot:
return table.tFoot;
default:
return table;
}
}
return null;
}
grid.getTableSection = getTableSection;
/** @ignore */
function getTableSectionLength(table, scope) {
var section;
if(table && !table.nodeType) {
table = table[0]// jQuery
;
}
return (table && (section = this.getTableSection(table, scope))) ? section.rows.length : 0;
}
grid.getTableSectionLength = getTableSectionLength;
/** @ignore */
function getTableSectionRow(table, scope, rowIndex) {
var section;
if(table && !table.nodeType) {
table = table[0]// jQuery
;
}
return (table && (section = this.getTableSection(table, scope))) ? (section.rows[rowIndex] || null) : null;
}
grid.getTableSectionRow = getTableSectionRow;
/** @ignore */
function readTableSection(table, scope, readAttributes) {
var ri, rowLen, ci, celLen, domRow, row, expando, rowAttributes, result = [], prevent = function (attrName) {
attrName = attrName.toLowerCase();
return attrName === "rowspan" || attrName === "colspan";
}, section;
if(table && !table.nodeType) {
table = table[0]// jQuery
;
}
if(table && (section = this.getTableSection(table, scope))) {
for(ri = 0 , rowLen = section.rows.length; ri < rowLen; ri++) {
domRow = section.rows[ri];
row = [];
if(readAttributes) {
expando = (wijmo).data.Expando.getFrom(row, true);
rowAttributes = expando[wijmo.grid.EXPANDO] = {
cellsAttributes: {
},
rowAttributes: wijmo.grid.getAttributes(domRow) || {
}
};
}
for(ci = 0 , celLen = domRow.cells.length; ci < celLen; ci++) {
row[ci] = $.trim((domRow.cells[ci]).innerHTML);
if(readAttributes) {
rowAttributes.cellsAttributes[ci] = wijmo.grid.getAttributes(domRow.cells[ci], prevent) || {
};
}
}
result[ri] = row;
}
}
return result;
}
grid.readTableSection = readTableSection;
/** @ignore */
var htmlTableAccessor = (function () {
function htmlTableAccessor(domTable, skipOffsets, ensureTBody, ensureColgroup) {
this._width = 0;
this._table = domTable;
this._offsets = [];
if(ensureColgroup) {
// important: colGroup must preceed tBody in a table
this.ensureColGroup();
}
if(ensureTBody) {
this.ensureTBody();
}
if(!skipOffsets) {
this._buildOffsets();
}
}
htmlTableAccessor.prototype.element = function () {
return this._table;
};
htmlTableAccessor.prototype.width = function () {
return this._width;
};
htmlTableAccessor.prototype.getCellIdx = function (colIdx, rowIdx) {
return (colIdx < this._width) ? this._offsets[rowIdx][colIdx].cellIdx : -1;
};
htmlTableAccessor.prototype.getColumnIdx = function (cellIdx, rowIdx) {
if(typeof (cellIdx) !== "number") {
// domCell
var domCell = cellIdx;
cellIdx = domCell.cellIndex;
rowIdx = domCell.parentNode.rowIndex;
}
return (cellIdx < this._width) ? this._offsets[rowIdx][cellIdx].colIdx : -1;
};
htmlTableAccessor.prototype.clearSection = function (scope) {
var start, end, section = wijmo.grid.getTableSection(this._table, scope);
switch(scope) {
case wijmo.grid.rowScope.body:
start = this.getSectionLength(wijmo.grid.rowScope.table);
end = start + this.getSectionLength(scope) - 1;
break;
case wijmo.grid.rowScope.foot:
start = this.getSectionLength(wijmo.grid.rowScope.table) + this.getSectionLength(wijmo.grid.rowScope.head);
end = start + this.getSectionLength(scope) - 1;
break;
default:
// header or whole table
start = 0;
end = this.getSectionLength(scope) - 1;
}
// update DOM
while(section.rows.length) {
section.deleteRow(0);
}
// update offsets
this._offsets.splice(start, end - start + 1);
};
htmlTableAccessor.prototype.getSectionLength = function (scope) {
return wijmo.grid.getTableSectionLength(this._table, scope);
};
htmlTableAccessor.prototype.getSectionRow = function (rowIndex, scope) {
return wijmo.grid.getTableSectionRow(this._table, scope, rowIndex);
};
htmlTableAccessor.prototype.forEachColumnCellNatural = // iterates through the table rows using natural cells order
function (columnIdx, callback, param) {
var i, rowLen, row, result;
for(i = 0 , rowLen = this._table.rows.length; i < rowLen; i++) {
row = this._table.rows[i];
if(columnIdx < row.cells.length) {
result = callback(row.cells[columnIdx], i, param);
if(result !== true) {
return result;
}
}
}
return true;
};
htmlTableAccessor.prototype.forEachColumnCell = // iterates through the table rows using colSpan\rowSpan offsets
function (columnIdx, callback, param) {
var i, rowLen, row, offsetCellIdx, result;
for(i = 0 , rowLen = this._offsets.length; i < rowLen; i++) {
row = this._table.rows[i];
offsetCellIdx = this.getCellIdx(columnIdx, i);
if(offsetCellIdx >= 0) {
result = callback(row.cells[offsetCellIdx], i, param);
if(result !== true) {
return result;
}
}
}
return true;
};
htmlTableAccessor.prototype.forEachRowCell = // iterates throw the cells of a table row
function (rowIndex, callback, param) {
var row = this._table.rows[rowIndex], i, celLen, result;
for(i = 0 , celLen = row.cells.length; i < celLen; i++) {
result = callback(row.cells[i], i, param);
if(result !== true) {
return result;
}
}
return true;
};
htmlTableAccessor.prototype.colGroupTag = function () {
var cgs = this._table.getElementsByTagName("colgroup");
return ((cgs && cgs[0])) || null;
};
htmlTableAccessor.prototype.colTags = function () {
var colGroup = this.colGroupTag();
return (colGroup && colGroup.getElementsByTagName("col")) || [];
};
htmlTableAccessor.prototype.ensureTBody = function () {
return ((this._table.tBodies && this._table.tBodies[0]) || this._table.appendChild(document.createElement("tbody")));
};
htmlTableAccessor.prototype.ensureTHead = function () {
return (this._table.tHead && this._table.tHead[0]) || this._table.createTHead();
};
htmlTableAccessor.prototype.ensureTFoot = function () {
return (this._table.tFoot && this._table.tFoot[0]) || this._table.createTFoot();
};
htmlTableAccessor.prototype.ensureColGroup = function () {
var colGroup = this._table.getElementsByTagName("colgroup");
return ((colGroup && colGroup[0]) || this._table.appendChild(document.createElement("colgroup")));
};
htmlTableAccessor.prototype.appendCol = function (domCol/*opt*/ ) {
var colGroup = this.ensureColGroup();
return ((domCol && colGroup.appendChild(domCol)) || colGroup.appendChild(document.createElement("col")));
};
htmlTableAccessor.prototype.removeOffset = function (idx) {
if(idx >= 0 && idx < this._offsets.length) {
if(idx < 0 || (!idx && idx !== 0)) {
idx = this._offsets.length - 1// last row
;
}
this._offsets.splice(idx, 1);
}
};
htmlTableAccessor.prototype.insertOffset = function (idx) {
var row, i;
if(this._width > 0) {
row = [];
for(i = 0; i < this._width; i++) {
row.push({
cellIdx: i,
colIdx: i
});
}
if(idx < 0 || (!idx && idx !== 0)) {
idx = this._offsets.length// append row
;
}
this._offsets.splice(idx, 0, row);
}
};
htmlTableAccessor.prototype.rebuildOffsets = function () {
this._offsets = [];
this._width = 0;
this._buildOffsets();
};
htmlTableAccessor.prototype._buildOffsets = function () {
var rowSpan = [], rowOffsets, i, rowLen, row, j, jOffset, celLen, cell, cs, rowSpanLen;
for(i = 0 , rowLen = this._table.rows.length; i < rowLen; i++) {
rowOffsets = [];
this._offsets[i] = rowOffsets;
row = this._table.rows[i];
for(j = 0 , jOffset = 0 , celLen = row.cells.length; j < celLen; j++ , jOffset++) {
cell = row.cells[j];
// process rowspan
for(; rowSpan[jOffset] > 1; jOffset++) {
rowSpan[jOffset]--;
rowOffsets[jOffset] = {
cellIdx: -1,
colIdx: -1
};
}
if(!(rowSpan[jOffset] > 1)) {
rowSpan[jOffset] = cell.rowSpan;
}
rowOffsets[jOffset] = {
cellIdx: j,
colIdx: -1
};
rowOffsets[j].colIdx = jOffset;
// process colspan
cs = cell.colSpan;
for(; cs > 1; cs--) {
rowOffsets[++jOffset] = {
cellIdx: -1,
colIdx: -1
};
}
}
rowSpanLen = rowSpan.length;
for(; jOffset < rowSpanLen; jOffset++) {
rowSpan[jOffset]--;
rowOffsets[jOffset] = {
cellIdx: -1,
colIdx: -1
};
}
this._width = Math.max(this._width, rowSpanLen);
}
};
return htmlTableAccessor;
})();
grid.htmlTableAccessor = htmlTableAccessor;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts" />
/// <reference path="wijgrid.ts" />
/// <reference path="misc.ts" />
(function (grid) {
"use strict";
var $ = jQuery;
/** An object that represents a single cell. */
var cellInfo = (function () {
/** Creates an object that represents a single cell. Normally you do not need to use this method.
* @example
* var cell = new wijmo.grid.cellInfo(0, 0, $("#demo").data("wijmo-wijgrid"));
* @param {Number} cellIndex The zero-based index of the required cell inside the corresponding row.
* @param {Number} rowIndex The zero-based index of the row that contains required cell.
* @param {Object} wijgrid The wijgrid instance.
* @returns {wijmo.grid.cellInfo} Object that represents a single cell.
*/
function cellInfo(cellIndex, rowIndex, wijgrid, absolute) {
if (typeof wijgrid === "undefined") { wijgrid = null; }
if (typeof absolute === "undefined") { absolute = false; }
this.__isEdit = false;
this._wijgrid = wijgrid;
if(absolute) {
this._cia = cellIndex;
this._ria = rowIndex;
} else {
this._ci = cellIndex;
this._ri = rowIndex;
}
}
cellInfo.outsideValue = new cellInfo(-1, -1, null, true);
cellInfo.prototype.cellIndexAbs = // public
/** @ignore */
function (value) {
if(arguments.length === 0) {
this._ensureCia();
return this._cia;
}
this._ci = undefined;
this._cia = value;
};
cellInfo.prototype.rowIndexAbs = /** @ignore */
function (value) {
if(arguments.length === 0) {
this._ensureRia();
return this._ria;
}
this._ri = undefined;
this._ria = value;
};
cellInfo.prototype.cellIndex = /** @ignore */
function (value) {
if(arguments.length === 0) {
this._ensureCi();
return this._ci;
}
this._cia = undefined;
this._ci = value;
};
cellInfo.prototype.column = /** Gets the associated column object.
* @example
* var column = cellInfoObj.column();
* @returns {wijmo.grid.IColumn} The associated column object.
*/
function () {
if(this._wijgrid && this._isValid()) {
return this._wijgrid._field("visibleLeaves")[this.cellIndexAbs()];
}
return null;
};
cellInfo.prototype.container = /** Returns the jQuery object containing a cell content.
* @example
* var $container = cellInfoObj.container();
* @returns {Object} The jQuery object containing a cell content.
*/
function () {
var tableCell = this.tableCell(), $innerDiv;
if(tableCell) {
$innerDiv = $(tableCell).children("div.wijmo-wijgrid-innercell");
if($innerDiv) {
return $innerDiv;
}
}
return null;
};
cellInfo.prototype.isEqual = /** Compares the current object with an object you have specified and indicates whether they are identical
* @example
* var isEqual = cellInfoObj1.isEqual(cellInfoObj2);
* @param {wijmo.grid.cellInfo} value The object to compare
* @returns {Boolean} True if the objects are identical, otherwise false.
*/
function (value) {
return (value && (value.rowIndex() === this.rowIndex()) && (value.cellIndex() === this.cellIndex()));
};
cellInfo.prototype.row = /** Gets the accociated row's information.
* @example
* var row = cellInfoObj.row();
* @returns {wijmo.grid.IRowInfo} Information about associated row.
*/
function () {
var rowObj = null, result = null;
if(this._wijgrid) {
rowObj = this._wijgrid._view().rows().item(this.rowIndexAbs());
if(rowObj && rowObj.length) {
result = this._wijgrid._view()._getRowInfo(rowObj);
}
}
return result;
};
cellInfo.prototype.rowIndex = /** @ignore */
function (value) {
if(arguments.length === 0) {
this._ensureRi();
return this._ri;
}
this._ria = undefined;
this._ri = value;
};
cellInfo.prototype.tableCell = /** Returns the table cell element corresponding to this object.
* @example
* var domCell = cellInfoObj.tableCell();
* @returns {HTMLTableCellElement} The table cell element corresponding to this object.
*/
function () {
if(this._wijgrid && this._isValid()) {
return this._wijgrid._view().getCell(this.cellIndexAbs(), this.rowIndexAbs());
}
return null;
};
cellInfo.prototype.value = /** @ignore */
function (value/*opt*/ ) {
var column, rowInfo, colVal;
if(this._wijgrid && this._isValid()) {
rowInfo = this._wijgrid._view()._getRowInfo(this._wijgrid._rows().item(this.rowIndex()));
if(rowInfo.type & wijmo.grid.rowType.data) {
column = this.column();
if(arguments.length === 0) {
// getter
colVal = this._wijgrid._dataViewWrapper.getValue(rowInfo.data, column.dataKey);
return this._wijgrid.parse(column, colVal);
} else {
// setter
// validation
value = this._wijgrid.parse(column, value);
if((value === null && column.valueRequired) || ((wijmo.grid.getDataType(column) !== "string") && isNaN(value))) {
throw "invalid value";
}
this._wijgrid._dataViewWrapper.setValue(rowInfo.dataItemIndex, column.dataKey, value);
}
}
}
};
cellInfo.prototype.toString = /** @ignore */
function () {
return this.cellIndex() + ":" + this.rowIndex();
};
cellInfo.prototype._clip = // internal
function (range, absolute) {
if (typeof absolute === "undefined") { absolute = false; }
var flag = false, val;
if(absolute) {
if(this.cellIndexAbs() < (val = range.topLeft().cellIndexAbs())) {
flag = true;
this._cia = val;
this._ci = undefined;
}
if(this.cellIndexAbs() > (val = range.bottomRight().cellIndexAbs())) {
flag = true;
this._cia = val;
this._ci = undefined;
}
if(this.rowIndexAbs() < (val = range.topLeft().rowIndexAbs())) {
flag = true;
this._ria = val;
this._ri = undefined;
}
if(this.rowIndexAbs() > (val = range.bottomRight().rowIndexAbs())) {
flag = true;
this._ria = val;
this._ri = undefined;
}
} else {
if(this.cellIndex() < (val = range.topLeft().cellIndex())) {
flag = true;
this._ci = val;
this._cia = undefined;
}
if(this.cellIndex() > (val = range.bottomRight().cellIndex())) {
flag = true;
this._ci = val;
this._cia = undefined;
}
if(this.rowIndex() < (val = range.topLeft().rowIndex())) {
flag = true;
this._ri = val;
this._ria = undefined;
}
if(this.rowIndex() > (val = range.bottomRight().rowIndex())) {
flag = true;
this._ri = val;
this._ria = undefined;
}
}
return flag;
};
cellInfo.prototype._clone = function () {
return new wijmo.grid.cellInfo(this.cellIndex(), this.rowIndex(), this._wijgrid);
};
cellInfo.prototype._isValid = function () {
return this.cellIndex() >= 0 && this.rowIndex() >= 0;
};
cellInfo.prototype._isEdit = function (value) {
if(!arguments.length) {
return this.__isEdit;
}
this.__isEdit = value;
};
cellInfo.prototype._setGridView = function (value) {
this._wijgrid = value;
};
cellInfo.prototype._ensureCia = // internal *
// * private
function () {
if(this._cia === undefined) {
if(this._ci === null) {
throw "relative index value is undefined";
}
if(this._ci >= 0) {
if(!this._wijgrid) {
throw "wijgrid is null";
}
this._cia = this._ci + this._wijgrid._getDataToAbsOffset().x;
} else {
this._cia = this._ci;
}
if(this._cia < 0) {
this._cia = -1;
}
}
};
cellInfo.prototype._ensureRia = function () {
if(this._ria === undefined) {
if(this._ri === undefined) {
throw "relative index value is undefined";
}
if(this._ri >= 0) {
if(!this._wijgrid) {
throw "wijgrid is null";
}
this._ria = this._ri + this._wijgrid._getDataToAbsOffset().y;
} else {
this._ria = this._ri;
}
if(this._ria < 0) {
this._ria = -1;
}
}
};
cellInfo.prototype._ensureCi = function () {
if(this._ci === undefined) {
if(this._cia === undefined) {
throw "absolute index value is undefined";
}
if(this._cia >= 0) {
if(!this._wijgrid) {
throw "wijgrid is null";
}
this._ci = this._cia - this._wijgrid._getDataToAbsOffset().x;
} else {
this._ci = this._cia;
}
if(this._ci < 0) {
this._ci = -1;
}
}
};
cellInfo.prototype._ensureRi = function () {
if(this._ri === undefined) {
if(this._ria === undefined) {
throw "relative index value is undefined";
}
if(this._ria >= 0) {
if(!this._wijgrid) {
throw "wijgrid is null";
}
this._ri = this._ria - this._wijgrid._getDataToAbsOffset().y;
} else {
this._ri = this._ria;
}
if(this._ri < 0) {
this._ri = -1;
}
}
};
return cellInfo;
})();
grid.cellInfo = cellInfo;
// private *
/** An object that specifies a range of cells determined by two cells. */
var cellInfoRange = (function () {
/** Creates an object that specifies a range of cells determined by two cells. Normally you do not need to use this method.
* @example
* var range = wijmo.grid.cellInfoRange(new wijmo.grid.cellInfo(0, 0), new wijmo.grid.cellInfo(0, 0));
* @param {wijmo.grid.cellInfo} topLeft Object that represents the top left cell of the range.
* @param {wijmo.grid.cellInfo} bottomRight Object that represents the bottom right cell of the range.
* @returns {wijmo.grid.cellInfoRange} Object that specifies a range of cells determined by two cells.
*/
function cellInfoRange(topLeft, bottomRight) {
if(!topLeft || !bottomRight) {
throw "invalid arguments";
}
this._topLeft = topLeft._clone();
this._bottomRight = bottomRight._clone();
}
cellInfoRange.prototype.bottomRight = /** Gets the object that represents the bottom right cell of the range.
* @example
* var cellInfoObj = range.bottomRight();
* @returns {wijmo.grid.cellInfo} The object that represents the bottom right cell of the range.
*/
function () {
return this._bottomRight;
};
cellInfoRange.prototype.isEqual = /** Compares the current range with a specified range and indicates whether they are identical.
* @example
* var isEqual = range1.isEqual(range2);
* @param {wijmo.grid.cellInfoRange} range Range to compare.
* @returns True if the ranges are identical, otherwise false.
*/
function (range) {
return (range && this._topLeft.isEqual(range.topLeft()) && this._bottomRight.isEqual(range.bottomRight()));
};
cellInfoRange.prototype.topLeft = /** Gets the object that represents the top left cell of the range.
* @example
* var cellInfoObj = range.topLeft();
* @returns {wijmo.grid.cellInfo} The object that represents the top left cell of the range.
*/
function () {
return this._topLeft;
};
cellInfoRange.prototype.toString = /** @ignore */
function () {
return this._topLeft.toString() + " - " + this._bottomRight.toString();
};
cellInfoRange.prototype._isIntersect = // public *
// internal
function (range) {
var rangeH, thisH, rangeW, thisW;
if(range) {
rangeH = range.bottomRight().rowIndex() - range.topLeft().rowIndex() + 1;
thisH = this._bottomRight.rowIndex() - this._topLeft.rowIndex() + 1;
if((range.topLeft().rowIndex() + rangeH) - this._topLeft.rowIndex() < rangeH + thisH) {
rangeW = range.bottomRight().cellIndex() - range.topLeft().cellIndex() + 1;
thisW = this._bottomRight.cellIndex() - this._topLeft.cellIndex() + 1;
return ((range.topLeft().cellIndex() + rangeW) - this._topLeft.cellIndex() < rangeW + thisW);
}
}
return false;
};
cellInfoRange.prototype._isValid = function () {
return this._topLeft._isValid() && this._bottomRight._isValid();
};
cellInfoRange.prototype._clip = function (clipBy, absolute) {
if (typeof absolute === "undefined") { absolute = false; }
var a = this._topLeft._clip(clipBy, absolute);
var b = this._bottomRight._clip(clipBy, absolute);
return a || b;
};
cellInfoRange.prototype._clone = function () {
return new cellInfoRange(this._topLeft._clone(), this._bottomRight._clone());
};
cellInfoRange.prototype._containsCellInfo = function (info) {
return (info && info.cellIndex() >= this._topLeft.cellIndex() && info.cellIndex() <= this._bottomRight.cellIndex() && info.rowIndex() >= this._topLeft.rowIndex() && info.rowIndex() <= this._bottomRight.rowIndex());
};
cellInfoRange.prototype._containsCellRange = function (range) {
return (range && this._containsCellInfo(range.topLeft()) && this._containsCellInfo(range.bottomRight()));
};
cellInfoRange.prototype._extend = function (mode, borders) {
if(mode === wijmo.grid.cellRangeExtendMode.toColumn) {
this._topLeft.rowIndex(borders.topLeft().rowIndex());
this._bottomRight.rowIndex(borders.bottomRight().rowIndex());
} else {
if(mode === wijmo.grid.cellRangeExtendMode.toRow) {
this._topLeft.cellIndex(borders.topLeft().cellIndex());
this._bottomRight.cellIndex(borders.bottomRight().cellIndex());
}
}
return this;
};
cellInfoRange.prototype._normalize = function () {
var x0 = this._topLeft.cellIndex(), y0 = this._topLeft.rowIndex(), x1 = this._bottomRight.cellIndex(), y1 = this._bottomRight.rowIndex();
this._topLeft.cellIndex(Math.min(x0, x1));
this._topLeft.rowIndex(Math.min(y0, y1));
this._bottomRight.cellIndex(Math.max(x0, x1));
this._bottomRight.rowIndex(Math.max(y0, y1));
};
return cellInfoRange;
})();
grid.cellInfoRange = cellInfoRange;
// internal *
// * compatibility: export members to the $.wijmo.wijgrid "namespace" *
$.extend($.wijmo.wijgrid, {
cellInfo: wijmo.grid.cellInfo,
cellInfoRange: wijmo.grid.cellInfoRange
});
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts" />
/// <reference path="wijgrid.ts" />
/// <reference path="misc.ts" />
/// <reference path="rowAccessor.ts" />
/// <reference path="filterOperators.ts" />
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var baseView = (function () {
function baseView(wijgrid, renderBounds) {
this._rowHeaderSize = 22;
this._sizesAdjCache = {
th: 0,
col: 0,
subTable: 0
};
if(!wijgrid) {
throw "'wijgrid' must be specified";
}
this._wijgrid = wijgrid;
this._bounds = renderBounds;
this._wijgrid.element.addClass("wijmo-wijgrid-table");
}
baseView.prototype.dispose = function () {
this.toggleDOMSelection(true);
this._wijgrid.element.removeClass("wijmo-wijgrid-table");
};
baseView.prototype.ensureDisabledState = function () {
var disabledClass = "wijmo-wijgrid" + "-disabled " + this._wijgrid.options.wijCSS.stateDisabled, disabled = this._wijgrid.options.disabled, self = this;
$.each(this.subTables(), function (key, table) {
if(table) {
var $table = $(table.element());
if(disabled) {
$table.addClass(disabledClass);
self._wijgrid._setAttr($table, "aria-disabled", true);
} else {
$table.removeClass(disabledClass);
self._wijgrid._setAttr($table, "aria-disabled", false);
}
}
});
};
baseView.prototype.ensureWidth = function (index, value, oldValue) {
this._setColumnWidth(index, value);
};
baseView.prototype.ensureHeight = function (rowIndex) {
};
baseView.prototype.getScrollValue = function () {
return null;
};
baseView.prototype.getVisibleAreaBounds = function () {
throw "not implemented";
};
baseView.prototype.getFixedAreaVisibleBounds = function () {
throw "not implemented";
};
baseView.prototype.render = function () {
this._ensureRenderBounds();
this._preRender();
var display = this._wijgrid.outerDiv.css("display");// hide outer element to improve performance.
this._wijgrid.outerDiv.css("display", "none");
this._renderContent();
this._wijgrid.outerDiv.css("display", display);
this._postRender();
};
baseView.prototype.toggleDOMSelection = function (enable) {
$.each(this.subTables(), function (index, htmlTableAccessor) {
(new wijmo.grid.domSelection(htmlTableAccessor.element())).toggleSelection(enable);
});
(new wijmo.grid.domSelection(this._wijgrid.outerDiv)).toggleSelection(enable);
};
baseView.prototype.updateSplits = function (scrollValue) {
throw "not implemented";
};
baseView.prototype.bodyRows = // public **
// ** DOMTable abstraction
// ** rows accessors
function () {
if(!this._bodyRowsAccessor) {
this._bodyRowsAccessor = new wijmo.grid.rowAccessor(this, wijmo.grid.rowScope.body, 0, 0);
}
return this._bodyRowsAccessor;
};
baseView.prototype.filterRow = function () {
if(this._wijgrid.options.showFilter) {
var accessor = new wijmo.grid.rowAccessor(this, wijmo.grid.rowScope.head, 0, 0);
return accessor.item(accessor.length() - 1);// filter is the last row in the tHead section
}
return null;
};
baseView.prototype.headerRows = function () {
var bottomOffset;
if(!this._headerRowsAccessor) {
bottomOffset = this._wijgrid.options.showFilter ? 1 : 0;
this._headerRowsAccessor = new wijmo.grid.rowAccessor(this, wijmo.grid.rowScope.head, 0, bottomOffset);
}
return this._headerRowsAccessor;
};
baseView.prototype.rows = function () {
if(!this._rowsAccessor) {
this._rowsAccessor = new wijmo.grid.rowAccessor(this, wijmo.grid.rowScope.table, 0, 0);
}
return this._rowsAccessor;
};
baseView.prototype.focusableElement = // rows accessors **
function () {
throw "not implemented";
};
baseView.prototype.forEachColumnCell = function (columnIndex, callback, param) {
throw "not implemented";
};
baseView.prototype.forEachRowCell = function (rowIndex, callback, param) {
throw "not implemented";
};
baseView.prototype.getAbsoluteCellInfo = function (domCell) {
throw "not implemented";
};
baseView.prototype.getAbsoluteRowIndex = function (domRow) {
throw "not implemented";
};
baseView.prototype.getCell = function (absColIdx, absRowIdx) {
throw "not implemented";
};
baseView.prototype.getColumnIndex = function (domCell) {
throw "not implemented";
};
baseView.prototype.getHeaderCell = function (absColIdx) {
throw "not implemented";
};
baseView.prototype.getJoinedCols = // [col, col]
function (columnIndex) {
throw "not implemented";
};
baseView.prototype.getJoinedRows = // [row, row]
function (rowIndex, rowScope) {
throw "not implemented";
};
baseView.prototype.getJoinedTables = // [table, table, offset:number]
function (byColumn, index) {
throw "not implemented";
};
baseView.prototype.subTables = function () {
throw "not implemented";
};
baseView.prototype._getMappedScrollMode = // DOMTable abstraction **
// ** private abstract
function () {
var scrollMode = this._wijgrid.options.scrollMode, vScrollBarVisibility = "auto", hScrollBarVisibility = "auto";
switch(scrollMode) {
case "horizontal":
vScrollBarVisibility = "hidden";
hScrollBarVisibility = "visible";
break;
case "vertical":
vScrollBarVisibility = "visible";
hScrollBarVisibility = "hidden";
break;
case "both":
vScrollBarVisibility = "visible";
hScrollBarVisibility = "visible";
break;
}
return {
vScrollBarVisibility: vScrollBarVisibility,
hScrollBarVisibility: hScrollBarVisibility
};
};
baseView.prototype._postRender = // ** rendering
function () {
this.ensureDisabledState();
// ** cache some values to speedup sizes manipulation (using IE especially) **
// reset
this._sizesAdjCache.col = 0;
this._sizesAdjCache.th = 0;
this._sizesAdjCache.subTable = 0;
// set a new values
var leaves = this._wijgrid._field("visibleLeaves");
if(leaves.length > 0) {
// note: we assume that the margins, paddings and borders are common to all of the th\ col elements.
var th = this.getHeaderCell(0), cols = this.getJoinedCols(0);
if(th) {
this._sizesAdjCache.th = $(th).leftBorderWidth() + $(th).rightBorderWidth();
}
if(cols && cols.length) {
this._sizesAdjCache.col = $(cols[0]).leftBorderWidth() + $(cols[0]).rightBorderWidth();
}
}
var subTable = this.subTables()[0];
this._sizesAdjCache.subTable = $(subTable.element()).leftBorderWidth() + $(subTable.element()).rightBorderWidth();
};
baseView.prototype._preRender = function () {
throw "not implemented";
};
baseView.prototype._ensureRenderBounds = function () {
var dataRange = this._wijgrid._getDataCellsRange();
// render all items of the sketchTable
this._bounds.start = 0;
this._bounds.end = dataRange.bottomRight().rowIndex();
};
baseView.prototype._renderContent = function () {
this._renderCOLS();
this._renderHeader();
if(this._wijgrid.options.showFilter) {
this._renderFilter();
}
this._renderBody();
if(this._wijgrid.options.showFooter) {
this._renderFooter();
}
};
baseView.prototype._renderCOLS = function () {
var visibleLeaves = this._wijgrid._field("visibleLeaves"), leaf, domCol, i, len;
for(i = 0 , len = visibleLeaves.length; i < len; i++) {
leaf = visibleLeaves[i];
domCol = this._createCol(leaf, i);
this._appendCol(domCol, leaf, i);
}
};
baseView.prototype._renderHeader = function () {
var $rt = wijmo.grid.rowType, cht = this._wijgrid._columnsHeadersTable(), i, height, rowInfo;
if(cht && (height = cht.length)) {
for(i = 0; i < height; i++) {
rowInfo = this._insertEmptyRow($rt.header, i, -1, -1, -1);
this._renderRow(rowInfo, null, cht[i]);
}
}
};
baseView.prototype._renderFilter = function () {
var rowInfo = this._insertEmptyRow(wijmo.grid.rowType.filter, -1, -1, -1, -1);
this._renderRow(rowInfo, this._wijgrid._field("visibleLeaves"), null);
};
baseView.prototype._renderBody = function () {
var $rt = wijmo.grid.rowType, visibleLeaves = this._wijgrid._field("visibleLeaves"), sketch = this._wijgrid.sketchTable, dataRowIndex = -1, virtualDataItemIndexBase = 0, cnt = 0, i, rowInfo, sketchRow, isDataRow, dataOffset = this._wijgrid._dataOffset;
// >= 0 when server-side virtual scrolling is used.
/*if (this._wijgrid._dataStore.dataMode() === $.wijmo.wijgrid.dataMode.dynamical) {
virtualDataItemIndexBase = this._wijgrid.options.pageIndex * this._wijgrid.options.pageSize;
}*/
// render rows
if(this._bounds.start >= 0) {
for(i = this._bounds.start; i <= this._bounds.end; i++) {
sketchRow = sketch[i - dataOffset];
isDataRow = (sketchRow.rowType & $rt.data) !== 0;
rowInfo = this._insertEmptyRow(sketchRow.rowType, cnt++, // sectionRowIndex
isDataRow ? ++dataRowIndex : -1, isDataRow ? sketchRow.originalRowIndex : -1, isDataRow ? virtualDataItemIndexBase + sketchRow.originalRowIndex : -1);
this._renderRow(rowInfo, visibleLeaves, sketchRow);
}
}
};
baseView.prototype._renderFooter = function () {
var rowInfo = this._insertEmptyRow(wijmo.grid.rowType.footer, -1, -1, -1, -1);
this._renderRow(rowInfo, this._wijgrid._field("visibleLeaves"), null);
};
baseView.prototype._insertEmptyRow = function (rowType, sectionRowIndex, dataRowIndex, dataItemIndex, virtualDataItemIndex) {
var domRow = this._wijgrid._onViewInsertEmptyRow.apply(this._wijgrid, arguments), domRowArr = this._insertRow(rowType, sectionRowIndex, domRow);
return this._createRowInfo(domRowArr, rowType, wijmo.grid.renderState.rendering, sectionRowIndex, dataRowIndex, dataItemIndex, virtualDataItemIndex);
};
baseView.prototype._createEmptyCell = function (rowInfo, dataCellIndex, column) {
var rt = wijmo.grid.rowType, domCell = this._wijgrid._onViewCreateEmptyCell.apply(this._wijgrid, arguments);
return this._createCell(rowInfo.type, domCell);
};
baseView.prototype._insertRow = // override
function (rowType, sectionRowIndex, domRow/* optional, used by c1gridview to clone rows of the original table */ ) {
throw "not implemented";
};
baseView.prototype._createCell = function (rowType, domCell/* optional, used by c1gridview to clone cells of the original table */ ) {
var rt = wijmo.grid.rowType, innerContainer;
if(!domCell) {
if(rowType === rt.header) {
domCell = document.createElement("th");
} else {
domCell = document.createElement("td");
}
}
if(rowType !== rt.filter) {
// * analogue of domCell.wrapInner("<div class=\"wijmo-wijgrid-innercell\"></div>")
innerContainer = document.createElement("div");
innerContainer.className = "wijmo-wijgrid-innercell";
if(domCell.firstChild) {
// move nodes from domCell to innerContainer
while(domCell.firstChild) {
innerContainer.appendChild(domCell.firstChild);
}
}
domCell.appendChild(innerContainer);
}
return $(domCell);
};
baseView.prototype._appendCell = function (rowInfo, cellIndex, $cell) {
throw "not implemented";
};
baseView.prototype._createCol = function (column, visibleIdx) {
throw "not implemented";
};
baseView.prototype._appendCol = function (domCol, column, visibleIdx) {
throw "not implemented";
};
baseView.prototype._renderRow = // item is a sketchRow
function (rowInfo, visibleLeaves, item) {
var $rt = wijmo.grid.rowType, rowAttr, rowStyle;
switch(rowInfo.type) {
case $rt.filter:
this._renderFilterRow(rowInfo, visibleLeaves);
break;
case $rt.footer:
this._renderFooterRow(rowInfo, visibleLeaves);
break;
case $rt.header:
this._renderHeaderRow(rowInfo, item);
break;
case $rt.data:
case $rt.data | $rt.dataAlt:
this._renderDataRow(rowInfo, visibleLeaves, item);
rowAttr = item.__attr;
rowStyle = item.__style;
break;
case $rt.emptyDataRow:
case $rt.groupHeader:
case $rt.groupFooter:
this._renderSpannedRow(rowInfo, visibleLeaves, item);
rowAttr = item.__attr;
rowStyle = item.__style;
break;
default:
throw "unknown rowType";
}
this._rowRendered(rowInfo, rowAttr, rowStyle);
};
baseView.prototype._renderCell = function (rowInfo, cellIndex, value, useHtml, leaf, attr, style) {
var $cell = this._createEmptyCell(rowInfo, leaf.dataIndex, leaf);
var $container = (rowInfo.type === wijmo.grid.rowType.filter) ? $cell : $($cell[0].firstChild);// $cell.children("div"); -- slow
this._appendCell(rowInfo, cellIndex, $cell);
if(useHtml) {
$container.html(value);
} else {
this._wijgrid.cellFormatter.format($container, leaf, value, rowInfo);
}
this._cellRendered(rowInfo, $cell, cellIndex, leaf, attr, style);
};
baseView.prototype._renderDataRow = function (rowInfo, visibleLeaves, sketchRow) {
var i, len, leaf, dataIndex, cellValue, cellAttr, cellStyle, useHtml = false;
for(i = 0 , len = visibleLeaves.length; i < len; i++) {
leaf = visibleLeaves[i];
dataIndex = leaf.dataIndex;
cellValue = null;
if(dataIndex >= 0 && (!sketchRow[dataIndex] || (sketchRow[dataIndex].visible === false))) {
continue;// spanned cell?
}
cellValue = (dataIndex >= 0) ? this._wijgrid.toStr(leaf, sketchRow[dataIndex].value) : null// unbounded column
;
cellAttr = (dataIndex >= 0) ? sketchRow[dataIndex].__attr : null;
cellStyle = (dataIndex >= 0) ? sketchRow[dataIndex].__style : null;
this._renderCell(rowInfo, i, cellValue, useHtml, leaf, cellAttr, cellStyle);
}
};
baseView.prototype._renderFilterRow = function (rowInfo, visibleLeaves) {
var i, len, leaf;
for(i = 0 , len = visibleLeaves.length; i < len; i++) {
leaf = visibleLeaves[i];
this._renderCell(rowInfo, i, wijmo.grid.filterHelper.getSingleValue(leaf.filterValue), false, leaf);
}
};
baseView.prototype._renderFooterRow = function (rowInfo, visibleLeaves) {
var i, len;
for(i = 0 , len = visibleLeaves.length; i < len; i++) {
this._renderCell(rowInfo, i, "", false, visibleLeaves[i]);
}
};
baseView.prototype._renderHeaderRow = function (rowInfo, item) {
var i, len, thX = 0, headerInfo;
for(i = 0 , len = item.length; i < len; i++) {
headerInfo = item[i];
if(headerInfo.column && headerInfo.column.parentVis) {
headerInfo.column.thX = thX++;
headerInfo.column.thY = rowInfo.sectionRowIndex;
this._renderCell(rowInfo, i, headerInfo.column.headerText, false, headerInfo.column, {
colSpan: headerInfo.colSpan,
rowSpan: headerInfo.rowSpan
});
}
}
};
baseView.prototype._renderSpannedRow = function (rowInfo, visibleLeaves, sketchRow) {
var i, leaf, len = Math.min(visibleLeaves.length, sketchRow.length);
for(i = 0; i < len; i++) {
this._renderCell(rowInfo, i, sketchRow[i].html, true, visibleLeaves[i], sketchRow[i].__attr, sketchRow[i].__style);
}
};
baseView.prototype._cellRendered = function (rowInfo, $cell, cellIndex, leaf, attr, style) {
this._wijgrid.cellStyleFormatter.format($cell, cellIndex, leaf, rowInfo, wijmo.grid.renderState.rendering, attr, style);
this._changeCellRenderState($cell, wijmo.grid.renderState.rendering, false);
this._wijgrid._onViewCellRendered(rowInfo, $cell, cellIndex, leaf);
};
baseView.prototype._rowRendered = function (rowInfo, rowAttr, rowStyle) {
this._wijgrid.rowStyleFormatter.format(rowInfo, rowAttr, rowStyle);
// change renderState AND associate rowInfo object with DOMRow
//this._changeRowRenderState(rowInfo, $.wijmo.wijgrid.renderState.rendering, false);
rowInfo.state &= ~wijmo.grid.renderState.rendering;
this._setRowInfo(rowInfo.$rows, rowInfo);
this._wijgrid._onViewRowRendered(rowInfo);
};
baseView.prototype._isBodyRow = function (rowInfo) {
var $rt = wijmo.grid.rowType, type = rowInfo.type;
return ((type & $rt.data) || (type === $rt.groupHeader) || (type === $rt.groupFooter) || (type === $rt.emptyDataRow));
};
baseView.prototype._changeRowRenderState = function (rowInfo, state, combine) {
if(combine) {
// combine
rowInfo.state |= state;
} else {
// clear
rowInfo.state &= ~state;
}
this._setRowInfo(rowInfo.$rows, rowInfo);
};
baseView.prototype._changeCellRenderState = function ($obj, state, combine) {
var $dp = wijmo.grid.dataPrefix, prefix = this._wijgrid._data$prefix, prevState = $dp($obj, prefix, "renderState");
if(combine) {
// combine
state = prevState | state;
$dp($obj, prefix, "renderState", state);
} else {
// clear
state = prevState & ~state;
$dp($obj, prefix, "renderState", state);
}
return state;
};
baseView.prototype._adjustWidthArray = // rendering **
// ** sizing
function (maxWidthArray, minWidthArray, expectedWidth, ensureColumnsPxWidth) {
var maxWidth = this._sumWidthArray(maxWidthArray), minWidth = this._sumWidthArray(minWidthArray), widthArray = [], adjustWidth, expandCount = 0, expandWidth, remainingWidth, bFirst = true;
if(maxWidth <= expectedWidth) {
$.extend(true, widthArray, maxWidthArray);
if(maxWidth === expectedWidth || ensureColumnsPxWidth) {
return widthArray;
} else {
adjustWidth = expectedWidth - maxWidth;
}
} else {
$.extend(true, widthArray, minWidthArray);
if(minWidth >= expectedWidth) {
return widthArray;
} else {
adjustWidth = expectedWidth - minWidth;
}
}
$.each(widthArray, function (index, colWidth) {
if(!colWidth.real) {
expandCount++;
}
});
if(expandCount !== 0) {
expandWidth = Math.floor(adjustWidth / expandCount);
remainingWidth = adjustWidth - expandWidth * expandCount;
$.each(widthArray, function (index, colWidth) {
if(!colWidth.real) {
colWidth.width += expandWidth;
if(bFirst) {
colWidth.width += remainingWidth;
bFirst = false;
}
}
});
}
return widthArray;
};
baseView.prototype._getColumnWidth = function (index) {
var result, leaf, joinedTables, relIdx, i, table, rows, cell, row, j, len;
leaf = this._wijgrid._field("visibleLeaves")[index];
if(leaf._realWidth !== undefined) {
result = {
width: leaf._realWidth,
real: true
};
} else if(leaf.isRowHeader) {
result = {
width: this._rowHeaderSize,
real: true
};
} else {
var maxW = 0;
joinedTables = this.getJoinedTables(true, index);
relIdx = joinedTables[2];
for(i = 0; i < 2; i++) {
table = joinedTables[i];
if(table !== null) {
rows = table.element().rows;
if(len = rows.length) {
// try to find a row which doesn't contains a spanned cells
for(j = len - 1 , row = null; j >= 0; j--) {
if(rows[j].cells.length === table.width()) {
row = rows[j];
break;
}
}
if(row) {
cell = row.cells[relIdx];
maxW = Math.max(maxW, $(cell).outerWidth());
}
}
}
}
result = {
width: maxW,
real: false
};
}
return result;
};
baseView.prototype._setColumnWidth = function (index, px) {
var th = this.getHeaderCell(index), cols = this.getJoinedCols(index), value;
if(px) {
var self = this;
// $(th).setOutWidth(px); // very slow in IE9
if(th) {
value = px - this._sizesAdjCache.th;
if(value < 0) {
value = 0;
}
th.style.width = value + "px";
}
$.each(cols, function (i, col) {
if(col) {
// $(col).setOutWidth(px); // very slow in IE9
value = px - self._sizesAdjCache.col;
if(value < 0) {
value = 0;
}
col.style.width = value + "px";
}
});
}
};
baseView.prototype._setTableWidth = function (subTables, expectedWidth, expandColumnWidth, expandIndex) {
var after, diff, self = this;
$.each(subTables, function (index, table) {
//table.css("table-layout", "fixed").setOutWidth(expectedWidth); // very slow in IE9
table[0].style.tableLayout = "fixed";
table[0].style.width = (expectedWidth - self._sizesAdjCache.subTable) + "px";
});
after = subTables[0].outerWidth();
diff = after - expectedWidth;
if(diff !== 0) {
this._setColumnWidth(expandIndex, expandColumnWidth - diff);
}
};
baseView.prototype._sumWidthArray = function (widthArray, startIndex, endIndex) {
var result = 0;
$.each(widthArray, function (index, colWidth) {
if(startIndex !== undefined && endIndex !== undefined && (index < startIndex || index > endIndex)) {
return true;
}
result += colWidth.width;
});
return result;
};
baseView.prototype._clearBody = // sizing **
// private abstract **
function () {
$.each(this.subTables(), function (key, table) {
table.clearSection(2);
});
};
baseView.prototype._rebuildOffsets = function () {
$.each(this.subTables(), function (key, table) {
table.rebuildOffsets();
});
};
baseView.prototype._removeBodyRow = function (sectionRowIndex, affectMetadata) {
var $rt = wijmo.grid.rowType, rows = this._wijgrid._rows(), i, len, rowInfo, ex, cmp, absRowIdx, joinedTables;
if((sectionRowIndex >= 0) && (sectionRowIndex < (len = rows.length()))) {
if(affectMetadata) {
for(i = 0; i < len; i++) {
rowInfo = this._getRowInfo(rows.item(i));
cmp = rowInfo.sectionRowIndex - sectionRowIndex;
if(rowInfo.sectionRowIndex > sectionRowIndex) {
rowInfo.sectionRowIndex--;
if(rowInfo.type & $rt.data) {
if(rowInfo.type & $rt.dataAlt) {
rowInfo.type &= ~$rt.dataAlt;
} else {
rowInfo.type |= $rt.dataAlt;
}
rowInfo.dataItemIndex--;
rowInfo.dataRowIndex--;
rowInfo.virtualDataItemIndex--;
}
// this._wijgrid.rowStyleFormatter.format(rowInfo); ??
this._setRowInfo(rowInfo.$rows, rowInfo);
}
}// for
}// if (affectMetadata)
// remove DOMRows
rowInfo = this._getRowInfo(rows.item(sectionRowIndex), false);
absRowIdx = this.getAbsoluteRowIndex(rowInfo.$rows[0]);
rowInfo.$rows.remove();
// ** update offsets
joinedTables = this.getJoinedTables(false, absRowIdx);
if(joinedTables[0]) {
joinedTables[0].removeOffset(joinedTables[2]);
}
if(joinedTables[1]) {
joinedTables[1].removeOffset(joinedTables[2]);
}
// update offsets **
}
};
baseView.prototype._insertBodyRow = function (sketchRow, sectionRowIndex, dataItemIndex, virtualDataItemIndex) {
var visibleLeaves = this._wijgrid._field("visibleLeaves"), $rt = wijmo.grid.rowType, view = this._wijgrid._view(), rows = this._wijgrid._rows(), len = rows.length(), isDataRow = ((sketchRow.rowType & $rt.data) !== 0), rowInfo, absRowIdx, joinedTables;
if(sectionRowIndex < 0 || sectionRowIndex >= len || (!sectionRowIndex && sectionRowIndex !== 0)) {
sectionRowIndex = len// append
;
}
rowInfo = this._insertEmptyRow(sketchRow.rowType, sectionRowIndex, -1, // TODO: dataRowIndex
dataItemIndex, virtualDataItemIndex);
this._renderRow(rowInfo, visibleLeaves, sketchRow);
// ** update offsets
absRowIdx = this.getAbsoluteRowIndex(rowInfo.$rows[0]);
joinedTables = this.getJoinedTables(false, absRowIdx);
if(joinedTables[0]) {
joinedTables[0].insertOffset(absRowIdx);
}
if(joinedTables[1]) {
joinedTables[1].insertOffset(absRowIdx);
}
// update offsets **
return rowInfo;
};
baseView.prototype._findRowInfo = function (callback) {
var rowsAccessor = this.bodyRows(), i = 0, len = rowsAccessor.length(), rowInfo;
if($.isFunction(callback)) {
for(i = 0; i < len; i++) {
rowInfo = this._getRowInfo(rowsAccessor.item(i));
if(callback(rowInfo) === true) {
return rowInfo;
}
}
}
return null;
};
baseView.prototype._setRowInfo = function (obj, rowInfo) {
var hasRows = "$rows" in rowInfo, hasData = "data" in rowInfo, tmpRows, tmpData;
if(hasRows) {
tmpRows = rowInfo.$rows;
delete rowInfo.$rows;
}
if(hasData) {
tmpData = rowInfo.data;
delete rowInfo.data;
}
wijmo.grid.dataPrefix(obj, this._wijgrid._data$prefix, "rowInfo", rowInfo);
if(hasRows) {
rowInfo.$rows = tmpRows;
}
if(hasData) {
rowInfo.data = tmpData;
}
};
baseView.prototype._getRowInfo = function (rowObj, retrieveDataItem) {
if (typeof retrieveDataItem === "undefined") { retrieveDataItem = true; }
var wijgrid = this._wijgrid, $rows = rowObj[1] ? $(rowObj) : $(rowObj[0]), rowInfo = wijmo.grid.dataPrefix($rows, wijgrid._data$prefix, "rowInfo"), tmp;
// add $rows property
rowInfo.$rows = $rows;
// set data property
if(retrieveDataItem && (rowInfo.dataItemIndex >= 0) && (rowInfo.type & wijmo.grid.rowType.data)) {
rowInfo.data = wijgrid._getDataItem(rowInfo.dataItemIndex);
}
return rowInfo;
};
baseView.prototype._createRowInfo = function (row, type, state, sectionRowIndex, dataRowIndex, dataItemIndex, virtualDataItemIndex) {
var tmp, rowInfo = {
type: type,
state: state,
sectionRowIndex: sectionRowIndex,
dataRowIndex: dataRowIndex,
dataItemIndex: dataItemIndex,
virtualDataItemIndex: virtualDataItemIndex,
$rows: $(row)
};
// set data property
if((dataItemIndex >= 0) && (type & wijmo.grid.rowType.data)) {
rowInfo.data = this._wijgrid._getDataItem(dataItemIndex);
}
return rowInfo;
};
return baseView;
})();
grid.baseView = baseView;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts" />
/// <reference path="wijgrid.ts" />
/// <reference path="misc.ts" />
/// <reference path="baseView.ts" />
/// <reference path="htmlTableAccessor.ts" />
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var flatView = (function (_super) {
__extends(flatView, _super);
function flatView(wijgrid, renderBounds) {
_super.call(this, wijgrid, renderBounds);
this._dataTable = null;
this._contentArea = null;
}
flatView.prototype.dispose = function () {
this._wijgrid.outerDiv.unbind("scroll", this._onScroll);
_super.prototype.dispose.call(this);
};
flatView.prototype.ensureWidth = function (index, value, oldValue) {
var $table = $(this._dataTable.element()), tableWidth = $table.width() + value - oldValue;
_super.prototype.ensureWidth.call(this, index, value, oldValue);
this._setTableWidth([
$table
], tableWidth, value, index);
};
flatView.prototype.getVisibleAreaBounds = function () {
var dataTableBounds = wijmo.grid.bounds(this._dataTable.element()), splitSEBounds;
if(this._wijgrid.options.scrollMode === "none") {
return dataTableBounds;
} else {
splitSEBounds = wijmo.grid.bounds(this._wijgrid.outerDiv.find(".wijmo-wijgrid-split-area-se:first")[0]);
return {
top: dataTableBounds.top,
left: dataTableBounds.left,
width: Math.min(splitSEBounds.width, dataTableBounds.width),
height: Math.min(splitSEBounds.height, dataTableBounds.height)
};
}
};
flatView.prototype.updateSplits = function (scrollValue) {
var self = this, wijgrid = this._wijgrid, o = wijgrid.options, gridElement = wijgrid.element, maxWidthArray = [], minWidthArray = [], resultWidthArray = [], visibleLeaves = wijgrid._field("visibleLeaves"), outerDiv = wijgrid.outerDiv, headerWidth, expandIndex;
gridElement.css({
"table-layout": "",
"width": ""
});
$.each(visibleLeaves, function (index, leaf) {
var isPercentage, w = leaf.width;
if(w || (w === 0)) {
isPercentage = ((typeof (w) === "string") && (w.length > 1) && (w[w.length - 1] === "%"));
//convert percent to value
if(isPercentage) {
w = outerDiv.width() * parseFloat(w) / 100;
} else {
w = parseFloat(w);
}
if(leaf.ensurePxWidth || (leaf.ensurePxWidth === undefined && o.ensureColumnsPxWidth)) {
leaf._realWidth = w;
}
self._setColumnWidth(index, w);
}
});
// read column widths.
$.each(visibleLeaves, function (index, leaf) {
maxWidthArray.push(self._getColumnWidth(index));
});
gridElement.css("width", "1px");
$.each(visibleLeaves, function (index, leaf) {
minWidthArray.push(self._getColumnWidth(index));
});
headerWidth = outerDiv.width()// using width() instead of innerWidth() to exclude padding.
;
resultWidthArray = this._adjustWidthArray(maxWidthArray, minWidthArray, headerWidth, o.ensureColumnsPxWidth);
$.each(resultWidthArray, function (index, colWidth) {
var leaf = visibleLeaves[index];
if(leaf._realWidth !== undefined) {
delete leaf._realWidth;
return;
}
self._setColumnWidth(index, colWidth.width);
});
expandIndex = resultWidthArray.length - 1;
if(expandIndex !== -1) {
this._setTableWidth([
gridElement
], this._sumWidthArray(resultWidthArray, 0, expandIndex), resultWidthArray[expandIndex].width, expandIndex);
}
};
flatView.prototype.focusableElement = // public **
// ** DOMTable abstraction
function () {
return $(this._dataTable.element());
};
flatView.prototype.forEachColumnCell = function (columnIndex, callback, param) {
return this._dataTable.forEachColumnCell(columnIndex, callback, param);
};
flatView.prototype.forEachRowCell = function (rowIndex, callback, param) {
return this._dataTable.forEachRowCell(rowIndex, callback, param);
};
flatView.prototype.getAbsoluteCellInfo = function (domCell) {
return new wijmo.grid.cellInfo(this.getColumnIndex(domCell), (domCell.parentNode).rowIndex, this._wijgrid, true);
};
flatView.prototype.getAbsoluteRowIndex = function (domRow) {
return domRow.rowIndex;
};
flatView.prototype.getCell = function (absColIdx, absRowIdx) {
var cellIdx = this._dataTable.getCellIdx(absColIdx, absRowIdx), rowObj;
if(cellIdx >= 0) {
rowObj = this.getJoinedRows(absRowIdx, 0);
if(rowObj[0]) {
return rowObj[0].cells[cellIdx];
}
}
return null;
};
flatView.prototype.getColumnIndex = function (domCell) {
return this._dataTable.getColumnIdx(domCell);
};
flatView.prototype.getHeaderCell = function (absColIdx) {
var leaf = this._wijgrid._field("visibleLeaves")[absColIdx], headerRow;
if(leaf && (headerRow = this._wijgrid._headerRows())) {
return wijmo.grid.rowAccessor.getCell(headerRow.item(leaf.thY), leaf.thX);
}
return null;
};
flatView.prototype.getJoinedCols = function (columnIndex) {
var $colGroup = $(this._dataTable.element()).find("> colgroup");
if($colGroup.length) {
if(columnIndex < $colGroup[0].childNodes.length) {
return [
$colGroup[0].childNodes[columnIndex],
null
];
}
}
return [
null,
null
];
};
flatView.prototype.getJoinedRows = function (rowIndex, rowScope) {
return [
this._dataTable.getSectionRow(rowIndex, rowScope),
null
];
};
flatView.prototype.getJoinedTables = function (byColumn, index) {
return [
this._dataTable,
null,
index
];
};
flatView.prototype.subTables = function () {
return [
this._dataTable
];
};
flatView.prototype._preRender = // DOMTable abstraction **
// ** private abstract
// ** render
function () {
this._dataTable = new wijmo.grid.htmlTableAccessor(this._wijgrid.element[0], true, true, true)// skip offsets, ensure tbody + colgroup
;
};
flatView.prototype._postRender = function () {
this._wijgrid.element.find("> tbody").addClass(this._wijgrid.options.wijCSS.content + " wijmo-wijgrid-data");
this._dataTable = new wijmo.grid.htmlTableAccessor(this._wijgrid.element[0])// create with offsets
;
this._wijgrid._setAttr(this._wijgrid.element, {
role: "grid",
cellpadding: "0",
border: "0",
cellspacing: "0"
});
this._wijgrid.element.css("border-collapse", "separate");
// Synchronize footer and header elements. The outerDiv element (overflow: hidden) can be scrolled when current cell position is changed.
this._wijgrid.outerDiv.bind("scroll", {
wijgrid: this._wijgrid
}, $.proxy(this._onScroll, this));
_super.prototype._postRender.call(this);
};
flatView.prototype._insertRow = function (rowType, sectionRowIndex, domRow/* optional, used by c1gridview to clone rows of the original table */ ) {
var $rt = wijmo.grid.rowType, tableSection;
switch(rowType) {
case $rt.header:
case $rt.filter:
tableSection = this._dataTable.ensureTHead();
break;
case $rt.footer:
tableSection = this._dataTable.ensureTFoot();
break;
default:
// tbody
tableSection = this._dataTable.ensureTBody();
}
if(domRow) {
// append only
return [
tableSection.appendChild(domRow)
];
} else {
if(sectionRowIndex > tableSection.rows.length) {
sectionRowIndex = -1;
}
return [
tableSection.insertRow(sectionRowIndex)
];
}
};
flatView.prototype._rowRendered = function (rowInfo, rowAttr, rowStyle) {
var domRow = rowInfo.$rows[0];
if(!domRow.cells.length && this._isBodyRow(rowInfo)) {
domRow.parentNode.removeChild(domRow);
} else {
_super.prototype._rowRendered.call(this, rowInfo, rowAttr, rowStyle);
}
};
flatView.prototype._appendCell = function (rowInfo, cellIndex, $cell) {
rowInfo.$rows[0].appendChild($cell[0]);
//rowInfo.$rows.append($cell);
};
flatView.prototype._createCol = function (column, visibleIdx) {
return [
document.createElement("col")
];
};
flatView.prototype._appendCol = function (domCol, column, visibleIdx) {
this._dataTable.appendCol(domCol[0]);
};
flatView.prototype._onScroll = // render **
// private abstract **
// ** private specific
function (e) {
if(e.data.wijgrid.$superPanelHeader) {
e.data.wijgrid.$superPanelHeader.css("left", e.target.scrollLeft);
}
if(e.data.wijgrid.$bottomPagerDiv) {
e.data.wijgrid.$bottomPagerDiv.css("left", e.target.scrollLeft);
}
};
return flatView;
})(grid.baseView);
grid.flatView = flatView;
// private specific **
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../../../wijsuperpanel/jquery.wijmo.wijsuperpanel.ts" />
/// <reference path="../../../wijlist/jquery.wijmo.wijlist.ts" />
/// <reference path="interfaces.ts" />
/// <reference path="wijgrid.ts" />
/// <reference path="misc.ts" />
/// <reference path="baseView.ts" />
/// <reference path="uiVirtualScroller.ts" />
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var fixedView = (function (_super) {
__extends(fixedView, _super);
function fixedView(wijgrid, renderBounds) {
_super.call(this, wijgrid, renderBounds);
this._verScrollBarSize = 18;
this._viewTables = {
};
// rendered DOM tables
this._splitAreas = {
};
this.element = wijgrid.element// table element
;
this._allowVirtualScrolling = wijgrid._allowVirtualScrolling() , this._staticDataRowIndex = wijgrid._getStaticIndex(true);
this._staticRowIndex = wijgrid._getRealStaticRowIndex();
this._staticColumnIndex = wijgrid._getRealStaticColumnIndex();
this._staticAllColumnIndex = (this._staticColumnIndex === -1) ? -1 : wijgrid._field("visibleLeaves")[this._staticColumnIndex].leavesIdx;
this._mouseWheelHandler = $.proxy(this._onMouseWheel, this);
}
fixedView.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this._wijgrid.outerDiv.unbind("mousewheel", this._mouseWheelHandler);
};
fixedView.prototype.ensureWidth = function (index, value, oldValue) {
var wijgrid = this._wijgrid, o = wijgrid.options, staticColumnIndex = this._staticColumnIndex, bWest = index <= staticColumnIndex, $tableNW = $(this._viewTables.nw.element()), $tableNE = $(this._viewTables.ne.element()), $tableSW = $(this._viewTables.sw.element()), $tableSE = $(this._viewTables.se.element()), tableArray = bWest ? [
$tableNW,
$tableSW
] : [
$tableNE,
$tableSE
], tableWidth = (bWest ? $tableNW.width() : $tableNE.width()) + value - oldValue, frozener = wijgrid._field("frozener"), scrollValue = this.getScrollValue();
this._destroySuperPanel();
_super.prototype.ensureWidth.call(this, index, value, oldValue);
this._setTableWidth(tableArray, tableWidth, value, index);
try {
if(staticColumnIndex >= 0) {
o.splitDistanceX = $tableNW[0].offsetWidth;
} else {
o.splitDistanceX = 0;
}
} catch (ex) {
}
this._updateSplitAreaBounds(0);
this._adjustRowsHeights();
try {
if(this._staticRowIndex >= 0) {
o.splitDistanceY = Math.max($tableNW[0].offsetHeight, $tableNE[0].offsetHeight);
} else {
o.splitDistanceY = 0;
}
} catch (ex) {
}
this._updateSplitAreaBounds(1);
this.refreshPanel(scrollValue);
frozener.refresh();
};
fixedView.prototype.ensureHeight = function (rowIndex) {
var rowObjsArray, wijgrid = this._wijgrid, o = wijgrid.options, $tableNW = $(this._viewTables.nw.element()), $tableNE = $(this._viewTables.ne.element()), $tableSW = $(this._viewTables.sw.element()), $tableSE = $(this._viewTables.se.element()), frozener = wijgrid._field("frozener"), scrollValue = this.getScrollValue(), maxHeight;
this._destroySuperPanel();
if(arguments.length > 0) {
rowObjsArray = this.getJoinedRows(rowIndex, 2);
this._setRowHeight(rowObjsArray, this._getRowHeight(rowObjsArray));
}
$tableSE.css("height", "");
$tableSW.css("height", "");
maxHeight = Math.max($tableSE.height(), $tableSW.height());
$tableSE.height(maxHeight);
$tableSW.height(maxHeight);
try {
if(this._staticRowIndex >= 0) {
o.splitDistanceY = Math.max($tableNW[0].offsetHeight, $tableNE[0].offsetHeight);
} else {
o.splitDistanceY = 0;
}
} catch (ex) {
}
this._updateSplitAreaBounds(1);
this.refreshPanel(scrollValue);
frozener.refresh();
};
fixedView.prototype.getScrollValue = // {x, y} or null
function () {
var superPanelObj = this._getSuperPanel();
return superPanelObj ? {
x: superPanelObj.options.hScroller.scrollValue,
y: superPanelObj.options.vScroller.scrollValue
} : null;
};
fixedView.prototype.getVisibleAreaBounds = function () {
var bounds = wijmo.grid.bounds(this._wijgrid.outerDiv.find(".wijmo-wijsuperpanel-contentwrapper:first"));
if(!bounds) {
// .wijmo-wijsuperpanel-contentwrapper is not available -- grid is invisible.
bounds = wijmo.grid.bounds(this._wijgrid.outerDiv);
}
return bounds;
};
fixedView.prototype.getFixedAreaVisibleBounds = function () {
var bounds = this.getVisibleAreaBounds(), neBounds = wijmo.grid.bounds(this._splitAreas.ne), nwBounds = wijmo.grid.bounds(this._splitAreas.nw), horBounds = null, verBounds = null;
if(neBounds.height || nwBounds.height) {
horBounds = {
left: bounds.left,
top: bounds.top,
width: bounds.width,
height: Math.min(neBounds.height || nwBounds.height, bounds.height)
};
}
if(nwBounds.width) {
verBounds = {
left: bounds.left,
top: bounds.top,
width: Math.min(nwBounds.width, bounds.width),
height: bounds.height
};
}
return [
horBounds,
verBounds
];
};
fixedView.prototype.refreshPanel = function (scrollValue) {
var self = this, wijgrid = this._wijgrid, options = wijgrid.options, gridWidth = this._getGridWidth(options.scrollMode), panelModes = this._getMappedScrollMode(), needVBar = this._testNeedVBar(wijgrid.outerDiv, wijgrid.element, $(this._viewTables.ne.element()), options.scrollMode, wijgrid._autoHeight), hScrollValue = scrollValue ? scrollValue.x : null, vScrollValue = scrollValue ? scrollValue.y : null, isTouchEnabled = ($.support.isTouchEnabled && $.support.isTouchEnabled());
this._scroller.width(gridWidth);
this._splitAreas.ne.width(gridWidth - options.splitDistanceX - (needVBar && !isTouchEnabled ? this._verScrollBarSize : 0));
if(!this._scroller.data("wijmo-wijsuperpanel")) {
if(this._allowVirtualScrolling) {
this.vsUI = new wijmo.grid.uiVirtualScroller(wijgrid, this._splitAreas.se, // content to scroll
options.splitDistanceY)// fixed area height
;
}
this._scroller.wijsuperpanel({
disabled: wijgrid.options.disabled,
scroll: $.proxy(this._onScroll, this),
bubbleScrollingEvent: true,
customScrolling: this._allowVirtualScrolling,
vScroller: {
scrollBarVisibility: panelModes.vScrollBarVisibility,
"scrollValue": scrollValue ? scrollValue.y : null
},
hScroller: {
scrollBarVisibility: panelModes.hScrollBarVisibility,
"scrollValue": scrollValue ? scrollValue.x : null
},
hScrollerActivating: function (e, data) {
// auto adjusting height with hscrollbar shown
var diff;
if(wijgrid._autoHeight) {
diff = wijgrid.element.height() + options.splitDistanceY - data.contentLength;
if(diff > 0) {
self._scroller.height(self._scroller.height() + diff);
self._scroller.wijsuperpanel("paintPanel");
return false;
}
}
self._splitAreas.sw.height(data.contentLength - options.splitDistanceY);
}
});
// issue #39166 - commented out.
//this._scroller.find(".wijmo-wijsuperpanel-contentwrapper:first").scroll(function (e) {
// // * prevent native scrolling to avoid disalignment of the fixed and unfixed areas in IE\ Chrome when partially visible cell gets focus *
// if ((<Element>e.target).scrollLeft) {
// (<Element>e.target).scrollLeft = 0;
// }
// if ((<Element>e.target).scrollTop) {
// (<Element>e.target).scrollTop = 0;
// }
// e.preventDefault();
//});
if(this._allowVirtualScrolling) {
this.vsUI.attach(this._scroller);
}
} else {
this._scroller.wijsuperpanel("paintPanel");
}
this._scroller.find(".wijmo-wijsuperpanel-hbarcontainer, .wijmo-wijsuperpanel-vbarcontainer").css("zIndex", 5);
};
fixedView.prototype.scrollTo = function (currentCell) {
if(!currentCell.tableCell()) {
return;
}
var wijgrid = this._wijgrid, o = wijgrid.options, superPanelObj = this._getSuperPanel(), tableCell = currentCell.tableCell(), $tableCell = tableCell.nodeType ? $(tableCell) : tableCell, resultLeft = null, resultTop = null;
if(superPanelObj && $tableCell.is(":visible")) {
var contentElement = (superPanelObj).getContentElement(), wrapperElement = contentElement.parent(), visibleLeft = parseInt((contentElement.css("left") + "").replace("px", ""), 10) * -1, visibleTop = parseInt((contentElement.css("top") + "").replace("px", ""), 10) * -1, visibleWidth = wrapperElement.outerWidth() - o.splitDistanceX, visibleHeight = wrapperElement.outerHeight() - o.splitDistanceY, elementPosition = $tableCell.position(), elementLeft = elementPosition.left, elementTop = elementPosition.top, elementWidth = $tableCell.outerWidth(), elementHeight = $tableCell.outerHeight(), staticRowIndex = wijgrid._getStaticIndex(true), staticColumnIndex = wijgrid._getStaticIndex(false), currentRowIndex = currentCell.rowIndex(), currentCellIndex = currentCell.cellIndex();
if(currentRowIndex <= staticRowIndex) {
if(currentCellIndex <= staticColumnIndex) {
resultLeft = 0;
resultTop = 0;
} else {
elementLeft += visibleLeft;
if(elementLeft + elementWidth > visibleLeft + visibleWidth) {
visibleLeft = resultLeft = elementLeft + elementWidth - visibleWidth;
}
if(elementLeft < visibleLeft) {
resultLeft = elementLeft;
}
resultTop = 0;
}
} else {
if(currentCellIndex <= staticColumnIndex) {
// elementTop += visibleTop;
elementTop += this._splitAreas.sw.scrollTop();
if(elementTop + elementHeight > visibleTop + visibleHeight) {
visibleTop = resultTop = elementTop + elementHeight - visibleHeight;
}
if(elementTop < visibleTop) {
resultTop = elementTop;
}
resultLeft = 0;
} else {
elementLeft -= o.splitDistanceX;
if(elementTop + elementHeight > visibleTop + visibleHeight) {
visibleTop = resultTop = elementTop + elementHeight - visibleHeight;
}
if(elementLeft + elementWidth > visibleLeft + visibleWidth) {
visibleLeft = resultLeft = elementLeft + elementWidth - visibleWidth;
}
if(elementTop < visibleTop) {
resultTop = elementTop;
}
if(elementLeft < visibleLeft) {
resultLeft = elementLeft;
}
}
}
if(resultLeft !== null) {
(superPanelObj).hScrollTo(resultLeft);
}
if(resultTop !== null) {
if(this._allowVirtualScrolling) {
//TODO: this.vsUI.scrollToRow(currentCell.row().virtualDataItemIndex);
} else {
(superPanelObj).vScrollTo(resultTop);
}
}
}
};
fixedView.prototype.updateSplits = function (scrollValue) {
var wijgrid = this._wijgrid, o = wijgrid.options, headerWidth, self = this, resultWidthArray = [], minWidthArray = [], maxWidthArray = [], staticColumnIndex = // set width to top table th and bottom table td in first row.
this._staticColumnIndex, expandIndex, mode = o.scrollMode, visibleLeaves = wijgrid._field("visibleLeaves"), $tableSE = $(this._viewTables.se.element()), $tableNE = $(this._viewTables.ne.element()), $tableSW = $(this._viewTables.sw.element()), $tableNW = $(this._viewTables.nw.element()), outerDiv = wijgrid.outerDiv, tmp, i, hasDataRows;
this._destroySuperPanel();
outerDiv.unbind("mousewheel", this._mouseWheelHandler);
/*if (!$tableSE.find("tbody .wijmo-wijgrid-row:not(.wijmo-wijgrid-groupheaderrow):first").length) {
wijgrid.element.css("width", "100%");
}*/
// * if there is no data in a table, we must enlarge the table to prevent the width from being 0
if((tmp = self._viewTables.se.element().tBodies) && (tmp = tmp[0])) {
// tmp = tBodies[0]
hasDataRows = false;
for(i = 0; i < tmp.rows.length; i++) {
if(!$(tmp.rows[i]).hasClass("wijmo-wijgrid-groupheaderrow")) {
hasDataRows = true;
break;
}
}
if(!hasDataRows) {
wijgrid.element.css("width", "100%");
}
}
$.each([
$tableSE,
$tableNE,
$tableSW,
$tableNW
], function (index, table) {
table.css({
"table-layout": "",
"width": ""
});
});
// if any column has width option, we will set the width for inner cells.
$.each(visibleLeaves, function (index, leaf) {
var isPercentage, w = leaf.width;
if(w || (w === 0)) {
isPercentage = ((typeof (w) === "string") && (w.length > 1) && (w[w.length - 1] === "%"));
//convert percent to value
if(isPercentage) {
w = outerDiv.width() * parseFloat(w) / 100;
} else {
w = parseFloat(w);
}
if(leaf.ensurePxWidth || (leaf.ensurePxWidth === undefined && o.ensureColumnsPxWidth)) {
leaf._realWidth = w;
}
self._setColumnWidth(index, w);
}
});
$.each(visibleLeaves, function (index, leaf) {
maxWidthArray.push(self._getColumnWidth(index));
});
$.each([
$tableNW,
$tableNE,
$tableSW,
$tableSE
], function (index, table) {
table.css({
"width": "1px"
});
});
$.each(visibleLeaves, function (index, leaf) {
minWidthArray.push(self._getColumnWidth(index));
});
headerWidth = outerDiv.width()// using width() instead of innerWidth() to exclude padding.
;
resultWidthArray = this._adjustWidthArray(maxWidthArray, minWidthArray, headerWidth, o.ensureColumnsPxWidth);
$.each(resultWidthArray, function (index, colWidth) {
var leaf = visibleLeaves[index];
if(leaf._realWidth !== undefined) {
delete leaf._realWidth;
return;
}
self._setColumnWidth(index, colWidth.width);
});
if(staticColumnIndex >= 0) {
expandIndex = staticColumnIndex;
this._setTableWidth([
$tableNW,
$tableSW
], this._sumWidthArray(resultWidthArray, 0, expandIndex), resultWidthArray[expandIndex].width, expandIndex);
}
//set the size of area after setting the width of column
try {
if(staticColumnIndex >= 0) {
o.splitDistanceX = $tableNW[0].offsetWidth;
} else {
o.splitDistanceX = 0;
}
} catch (ex) {
}
this._updateSplitAreaBounds(0)//width
;
if(!o.ensureColumnsPxWidth) {
$tableNE.parent().width(headerWidth - o.splitDistanceX);
}
expandIndex = resultWidthArray.length - 1;
if(expandIndex !== -1) {
this._setTableWidth([
$tableNE,
$tableSE
], this._sumWidthArray(resultWidthArray, staticColumnIndex + 1, expandIndex), resultWidthArray[expandIndex].width, expandIndex);
}
this._adjustRowsHeights();
//set the size of area after setting the width of column
try {
if(this._staticRowIndex >= 0) {
o.splitDistanceY = Math.max($tableNW[0].offsetHeight, $tableNE[0].offsetHeight);
} else {
o.splitDistanceY = 0;
}
} catch (ex) {
}
this._updateSplitAreaBounds(1)//height
;
//adjust width if showing vertical scrollbar
if(!o.ensureColumnsPxWidth) {
if(this._testNeedVBar(wijgrid.outerDiv, $tableSE, $tableNE, mode, wijgrid._autoHeight)) {
headerWidth -= this._verScrollBarSize;
resultWidthArray = this._adjustWidthArray(maxWidthArray, minWidthArray, headerWidth, o.ensureColumnsPxWidth);
$.each(resultWidthArray, function (index, colWidth) {
if(!colWidth.real) {
self._setColumnWidth(index, colWidth.width);
}
});
if(staticColumnIndex >= 0) {
expandIndex = staticColumnIndex;
this._setTableWidth([
$tableNW,
$tableSW
], this._sumWidthArray(resultWidthArray, 0, expandIndex), resultWidthArray[expandIndex].width, expandIndex);
}
//set the size of area after setting the width of column
try {
if(staticColumnIndex >= 0) {
o.splitDistanceX = $tableNW[0].offsetWidth;
} else {
o.splitDistanceX = 0;
}
} catch (ex) {
}
this._updateSplitAreaBounds(0)//width
;
$tableNE.parent().width(headerWidth - o.splitDistanceX);
expandIndex = resultWidthArray.length - 1;
if(expandIndex !== -1) {
this._setTableWidth([
$tableNE,
$tableSE
], this._sumWidthArray(resultWidthArray, staticColumnIndex + 1, expandIndex), resultWidthArray[expandIndex].width, expandIndex);
}
this._adjustRowsHeights();
//set the size of area after setting the width of column
try {
if(this._staticRowIndex >= 0) {
o.splitDistanceY = Math.max($tableNW[0].offsetHeight, $tableNE[0].offsetHeight);
} else {
o.splitDistanceY = 0;
}
} catch (ex) {
}
this._updateSplitAreaBounds(1)//height
;
}
}
this.refreshPanel(scrollValue)// refresh super panel after width is set.
;
outerDiv.bind("mousewheel", $.proxy(this._mouseWheelHandler, this));
};
fixedView.prototype._clearBody = // public **
// ** DOMTable abstraction
function () {
_super.prototype._clearBody.call(this);
};
fixedView.prototype.bodyRows = function () {
var accessor = _super.prototype.bodyRows.call(this);
return accessor;
};
fixedView.prototype.focusableElement = function () {
return this._wijgrid.outerDiv;
};
fixedView.prototype.forEachColumnCell = function (columnIndex, callback, param) {
var joinedTables = this.getJoinedTables(true, columnIndex), relIdx, callbackRes;
if(joinedTables[0] !== null) {
relIdx = joinedTables[2];
callbackRes = joinedTables[0].forEachColumnCell(relIdx, callback, param);
if(callbackRes !== true) {
return callbackRes;
}
if(joinedTables[1] !== null) {
callbackRes = joinedTables[1].forEachColumnCell(relIdx, callback, param);
if(callbackRes !== true) {
return callbackRes;
}
}
}
return true;
};
fixedView.prototype.forEachRowCell = function (rowIndex, callback, param) {
var joinedTables = this.getJoinedTables(false, rowIndex), table0 = joinedTables[0], table1 = joinedTables[1], relIdx, callbackResult;
if(table0 !== null) {
relIdx = joinedTables[2];
if(relIdx < table0.element().rows.length) {
callbackResult = table0.forEachRowCell(relIdx, callback, param);
if(callbackResult !== true) {
return callbackResult;
}
}
if((table1 !== null) && (relIdx < table1.element().rows.length)) {
callbackResult = table1.forEachRowCell(relIdx, callback, param);
if(callbackResult !== true) {
return callbackResult;
}
}
}
HTMLTableCellElement;
return true;
};
fixedView.prototype.getAbsoluteCellInfo = function (domCell) {
return new wijmo.grid.cellInfo(this.getColumnIndex(domCell), this.getAbsoluteRowIndex(domCell.parentNode), this._wijgrid, true);
};
fixedView.prototype.getAbsoluteRowIndex = function (domRow) {
var index = domRow.rowIndex, table = domRow.parentNode;
while(table.tagName.toLowerCase() !== "table") {
table = table.parentNode;
}
return (table === this._viewTables.nw.element() || table === this._viewTables.ne.element()) ? index : index + this._staticRowIndex + 1;
};
fixedView.prototype.getCell = function (absColIdx, absRowIdx) {
var joinedTablesRow = this.getJoinedTables(false, absRowIdx), joinedTablesCol, relRowIdx, relColIdx, table, cellIdx;
if(joinedTablesRow[0] !== null) {
joinedTablesCol = this.getJoinedTables(true, absColIdx);
if(joinedTablesCol[0] !== null) {
relRowIdx = joinedTablesRow[2];
relColIdx = joinedTablesCol[2];
table = null;
if(joinedTablesRow[1] !== null) {
table = (absColIdx === relColIdx) ? joinedTablesRow[0] : joinedTablesRow[1];
} else {
table = joinedTablesRow[0];
}
cellIdx = table.getCellIdx(relColIdx, relRowIdx);
if(cellIdx >= 0) {
return table.element().rows[relRowIdx].cells[cellIdx];
}
}
}
return null;
};
fixedView.prototype.getColumnIndex = function (domCell) {
var owner = null, htmlTable = null, flag = false, colIdx;
for(owner = domCell.parentNode; owner.tagName.toLowerCase() !== "table"; owner = owner.parentNode) {
}
if(owner !== null) {
if(owner === this._viewTables.nw.element()) {
htmlTable = this._viewTables.nw;
} else {
if(owner === this._viewTables.ne.element()) {
htmlTable = this._viewTables.ne;
flag = true;
} else {
if(owner === this._viewTables.sw.element()) {
htmlTable = this._viewTables.sw;
} else {
if(owner === this._viewTables.se.element()) {
htmlTable = this._viewTables.se;
flag = true;
}
}
}
}
if(htmlTable !== null) {
colIdx = htmlTable.getColumnIdx(domCell);
if(flag) {
colIdx += this._staticColumnIndex + 1;
}
return colIdx;
}
}
return -1;
};
fixedView.prototype.getHeaderCell = function (absColIdx) {
var leaf = this._wijgrid._field("visibleLeaves")[absColIdx], headerRow;
if(leaf && (headerRow = this._wijgrid._headerRows())) {
return wijmo.grid.rowAccessor.getCell(headerRow.item(leaf.thY), leaf.thX);
}
return null;
};
fixedView.prototype.getJoinedCols = function (columnIndex) {
var result = [], joinedTables = this.getJoinedTables(true, columnIndex), relIndex = joinedTables[2];
joinedTables.splice(joinedTables.length - 1, 1);
$.each(joinedTables, function (index, table) {
result.push(table ? $(table.element()).find("col")[relIndex] : null);
});
return result;
};
fixedView.prototype.getJoinedRows = function (rowIndex, rowScope) {
var row0 = null, row1 = null, table0 = null, table1 = null, fixedRowIdx = this._staticRowIndex, fixedColIdx = this._staticColumnIndex, lastColIdx = this._wijgrid._field("visibleLeaves").length - 1, lastRowIdx = this._rowsCountRaw() - 1, allRowsFixed = (fixedRowIdx === lastRowIdx), allsRowUnfixed = (fixedRowIdx < 0), rowsFixedSlice = !allRowsFixed && !allsRowUnfixed, sectionLength = 0;
if(allRowsFixed || rowsFixedSlice) {
if(fixedColIdx >= 0 && fixedColIdx < lastColIdx) {
table0 = this._viewTables.nw;
table1 = this._viewTables.ne;
} else {
table0 = (fixedColIdx < 0) ? this._viewTables.ne : this._viewTables.nw;
}
sectionLength = table0.getSectionLength(rowScope);
if(rowIndex < sectionLength) {
row0 = table0.getSectionRow(rowIndex, rowScope);
if(table1 !== null) {
row1 = table1.getSectionRow(rowIndex, rowScope);
}
}
}
if(allsRowUnfixed || (rowsFixedSlice && (row0 === null))) {
if(!allsRowUnfixed) {
rowIndex -= sectionLength;
}
if(fixedColIdx >= 0 && fixedColIdx < lastColIdx) {
table0 = this._viewTables.sw;
table1 = this._viewTables.se;
} else {
table0 = (fixedColIdx < 0) ? this._viewTables.se : this._viewTables.sw;
}
row0 = table0.getSectionRow(rowIndex, rowScope);
if(table1 !== null) {
row1 = table1.getSectionRow(rowIndex, rowScope);
}
}
return (row0 === null && row1 === null) ? null : [
row0,
row1
];
};
fixedView.prototype.getJoinedTables = function (byColumn, index) {
var t0 = null, t1 = null, idx = index, wijgrid = this._wijgrid, fixedRowIdx = this._staticRowIndex, fixedColIdx = this._staticColumnIndex;
if(byColumn) {
if(index <= fixedColIdx) {
t0 = this._viewTables.nw;
t1 = this._viewTables.sw;
} else {
t0 = this._viewTables.ne;
t1 = this._viewTables.se;
idx = idx - (fixedColIdx + 1);
}
if(fixedRowIdx < 0) {
t0 = null;
}
if(fixedRowIdx === this._rowsCountRaw() - 1)// fixed row is the last row
{
t1 = null;
}
} else {
if(index <= fixedRowIdx) {
t0 = this._viewTables.nw;
t1 = this._viewTables.ne;
} else {
t0 = this._viewTables.sw;
t1 = this._viewTables.se;
idx = idx - (fixedRowIdx + 1);
}
if(fixedColIdx < 0) {
t0 = null;
}
if(fixedColIdx === wijgrid._field("leaves").length - 1) {
t1 = null;
}
}
if(t0 === null) {
t0 = t1;
t1 = null;
}
return [
t0,
t1,
idx
];
};
fixedView.prototype.subTables = function () {
return [
this._viewTables.nw,
this._viewTables.ne,
this._viewTables.sw,
this._viewTables.se
];
};
fixedView.prototype._getGridWidth = // DOMTable abstraction **
// ** private abstract
function (mode) {
var wijgrid = this._wijgrid, tableWidth = wijgrid.element.outerWidth(true) + wijgrid.options.splitDistanceX, outWidth = wijgrid.outerDiv.innerWidth();
if(this._testNeedVBar(wijgrid.outerDiv, wijgrid.element, $(this._viewTables.ne.element()), mode, wijgrid._autoHeight)) {
tableWidth += this._verScrollBarSize;
}
if(tableWidth > outWidth) {
tableWidth = outWidth;
}
return tableWidth;
};
fixedView.prototype._getSuperPanel = function () {
return this._scroller ? this._scroller.data("wijmo-wijsuperpanel") : null;
};
fixedView.prototype._ensureRenderBounds = // ** render
function () {
if(this._wijgrid._allowVirtualScrolling()) {
this._wijgrid._ensureRenderBounds(this._bounds);
if(this._wijgrid._serverSideVirtualScrolling()) {
//this._bounds.start = this._wijgrid.options.pageIndex * this._wijgrid.options.pageSize;
}
this._bounds.end = this._bounds.start + this._wijgrid.options.pageSize - 1;
this._wijgrid._ensureRenderBounds(this._bounds);
} else {
_super.prototype._ensureRenderBounds.call(this)// render all items
;
}
};
fixedView.prototype._renderContent = function () {
_super.prototype._renderContent.call(this);
};
fixedView.prototype._preRender = function () {
var docFragment = document.createDocumentFragment(), HTA = wijmo.grid.htmlTableAccessor;
this._wijgrid.outerDiv.wrapInner("<div class=\"wijmo-wijgrid-fixedview\"><div class=\"wijmo-wijgrid-scroller\"><div class=\"wijmo-wijgrid-split-area-se wijmo-wijgrid-content-area\"></div></div></div>");
this._scroller = this._wijgrid.outerDiv.find(".wijmo-wijgrid-scroller");
this._scroller.css("padding", 0)// disable padding (inherited)
;
this._scroller.after(this._splitAreas.nw = $("<div class=\"wijmo-wijgrid-split-area wijmo-wijgrid-split-area-nw\" style=\"overflow:hidden;position:absolute;z-index:4;top:0px;left:0px;\"></div>"));
this._scroller.after(this._splitAreas.ne = $("<div class=\"wijmo-wijgrid-split-area wijmo-wijgrid-split-area-ne\" style=\"overflow:hidden;position:absolute;z-index:4;top:0px;left:0px;\"></div>"));
this._scroller.after(this._splitAreas.sw = $("<div class=\"wijmo-wijgrid-split-area wijmo-wijgrid-split-area-sw\" style=\"overflow:hidden;position:absolute;z-index:4;top:0px;left:0px;\"></div>"));
this._splitAreas.se = this._scroller.find(".wijmo-wijgrid-split-area-se:first");
this._viewTables = {
nw: // skip offsets, ensure tbody + colgroup
new HTA(docFragment.appendChild(document.createElement("table")), true, true, true),
ne: new HTA(docFragment.appendChild(document.createElement("table")), true, true, true),
sw: new HTA(docFragment.appendChild(document.createElement("table")), true, true, true),
se: new HTA(docFragment.appendChild(this._wijgrid.element[0]), true, true, true)
};
};
fixedView.prototype._postRender = function () {
var t00, t01, t10, t11, HTA = wijmo.grid.htmlTableAccessor, self = this;
this._viewTables = {
nw: // rebuild with offsets
new HTA(t00 = this._viewTables.nw.element()),
ne: new HTA(t01 = this._viewTables.ne.element()),
sw: new HTA(t10 = this._viewTables.sw.element()),
se: new HTA(t11 = this._viewTables.se.element())
};
this._splitAreas.nw.empty().append(t00);
this._splitAreas.ne.empty().append(t01);
this._splitAreas.sw.empty().append(t10);
this._splitAreas.se.empty().append(t11);
$.each(this._viewTables, function (idx, hta) {
var $element = $(hta.element());
self._wijgrid._setAttr($element, {
role: "grid",
border: "0",
cellpadding: "0",
cellspacing: "0"
});
$element.addClass("wijmo-wijgrid-table").css("border-collapse", "separate").find(// use separate instead of collapse to avoid a disalignment issue in chrome.
"> tbody").addClass(self._wijgrid.options.wijCSS.content + " wijmo-wijgrid-data");
});
_super.prototype._postRender.call(this);
};
fixedView.prototype._rowsCountRaw = function () {
var t00 = this._viewTables.nw.element(), t01 = this._viewTables.ne.element(), t10 = this._viewTables.sw.element(), t11 = this._viewTables.se.element(), res;
res = Math.max(t00.rows.length, t01.rows.length) + Math.max(t10.rows.length, t11.rows.length);
return res;
};
fixedView.prototype._createCol = function (column, visibleIdx) {
return [
document.createElement("col"),
document.createElement("col")
];
};
fixedView.prototype._appendCol = function (domCol, column, visibleIdx) {
if(visibleIdx <= this._staticColumnIndex) {
this._viewTables.nw.appendCol(domCol[0]);
this._viewTables.sw.appendCol(domCol[1]);
} else {
this._viewTables.ne.appendCol(domCol[0]);
this._viewTables.se.appendCol(domCol[1]);
}
};
fixedView.prototype._insertRow = function (rowType, sectionRowIndex, domRow/* optional, used by c1gridview to clone rows of the original table */ ) {
var $rt = wijmo.grid.rowType, leftSection, rightSection, vt = this._viewTables;
switch(rowType) {
case $rt.header:
case $rt.filter:
leftSection = vt.nw.ensureTHead();
rightSection = vt.ne.ensureTHead();
break;
case $rt.footer:
leftSection = vt.sw.ensureTFoot();
rightSection = vt.se.ensureTFoot();
break;
default:
// tbody
if(sectionRowIndex <= this._staticDataRowIndex) {
leftSection = vt.nw.ensureTBody();
rightSection = vt.ne.ensureTBody();
} else {
sectionRowIndex -= this._staticDataRowIndex + 1// subtracts fixed offset
;
leftSection = vt.sw.ensureTBody();
rightSection = vt.se.ensureTBody();
}
}
if(domRow) {
// append only
return [
leftSection.appendChild(domRow),
rightSection.appendChild(domRow.cloneNode(false))
];
} else {
return [
leftSection.insertRow(sectionRowIndex > leftSection.rows.length ? -1 : sectionRowIndex),
rightSection.insertRow(sectionRowIndex > rightSection.rows.length ? -1 : sectionRowIndex)
];
}
};
fixedView.prototype._rowRendered = function (rowInfo, rowAttr, rowStyle) {
var leftRow = rowInfo.$rows[0], rightRow = rowInfo.$rows[1];
// Do not remove empty rows from header. The number of header rows in the fixed and unfixed tables should be empty to handle unbanded columns headers correctly when the staticSolumnIndex option is used:
//
// row0 | band | | col2 | (rowSpan = 2)
// |---------| |--------|
// row1 |col0|col1| | | <- empty row
if(!leftRow.cells.length && this._isBodyRow(rowInfo)) {
leftRow.parentNode.removeChild(leftRow);
leftRow = null;
}
if(!rightRow.cells.length && this._isBodyRow(rowInfo)) {
rightRow.parentNode.removeChild(rightRow);
rightRow = null;
}
if(leftRow || rightRow) {
if(!leftRow || !rightRow) {
// handle changes
rowInfo.$rows = leftRow ? $(leftRow) : $(rightRow);
}
_super.prototype._rowRendered.call(this, rowInfo, rowAttr, rowStyle);
}
};
fixedView.prototype._appendCell = function (rowInfo, cellIndex, $cell) {
var staticColIndex = (rowInfo.type !== wijmo.grid.rowType.header) ? this._staticColumnIndex : this._staticAllColumnIndex;
if(cellIndex <= staticColIndex) {
rowInfo.$rows[0].appendChild($cell[0]);
} else {
rowInfo.$rows[1].appendChild($cell[0]);
}
};
fixedView.prototype._getRowHeight = // render **
function (rowObj, ignoreSpannedCells) {
if(rowObj[0] && rowObj[1]) {
// static columns are used
var lRow = rowObj[0], rRow = rowObj[1], $lRow = $(lRow), $rRow = $(rRow), lRowH, rRowH, customHeight, getRowHeightUsingUnspannedCells = function ($row) {
var i, domRow = $row[0], domCell;
for(i = 0; i < domRow.cells.length; i++) {
domCell = domRow.cells[i];
if(!domCell.rowSpan || domCell.rowSpan === 1) {
return $(domCell).outerHeight();
}
}
;
return $row.height();
};
if(customHeight = $.data(lRow, "customHeight")) {
// user-defined (inline) height
lRowH = rRowH = parseInt(customHeight);
} else {
$lRow.css("height", "");
$rRow.css("height", "");
if(ignoreSpannedCells) {
// used for header rows
lRowH = getRowHeightUsingUnspannedCells($lRow);
rRowH = getRowHeightUsingUnspannedCells($rRow);
} else {
lRowH = $lRow.height();
rRowH = $rRow.height();
}
}
return Math.max(lRowH, rRowH);
}
return null;
};
fixedView.prototype._setRowHeight = function (rowObj, maxHeight) {
if(rowObj[0] && rowObj[1]) {
var $rowObj = [
$(rowObj[0]),
$(rowObj[1])
], dif;
if(maxHeight === null) {
return;
}
maxHeight += 1;
$.each($rowObj, function (index, $el) {
$el.height(maxHeight);
dif = maxHeight - $el.height();
if(dif) {
$el.height(maxHeight + dif);
}
});
}
};
fixedView.prototype._adjustRowHeight = function () {
var wijgrid = this._wijgrid, fixedColIdx = this._staticColumnIndex, lastColIdx = wijgrid._field("visibleLeaves").length - 1, fixedRowIdx, lastRowIdx, tables, tableNE, tableNEParent, tableNW, tableNWParent, tableSE, tableSEParent, tableSW, tableSWParent, rowCount, i, j, leftRows, rightRows, heightArray = [];
// setting row height only if grid is divided into leftern and rightern parts
if(fixedColIdx > -1 && fixedColIdx < lastColIdx) {
fixedRowIdx = this._staticRowIndex;
lastRowIdx = this._rowsCountRaw() - 1;
tables = this._viewTables;
// getting the height of northern tables
if(fixedRowIdx > -1 && fixedRowIdx <= lastRowIdx) {
tableNE = tables.ne.element();
tableNEParent = tableNE.parentNode;
tableNW = tables.nw.element();
tableNWParent = tableNW.parentNode;
leftRows = tableNW.rows;
rightRows = tableNE.rows;
rowCount = leftRows.length;
for(i = 0; i < rowCount; i++) {
heightArray.push(this._getRowHeight([
leftRows[i],
rightRows[i]
], true))// row height will be calculated using unspanned cells (TFS issue #33399).
;
}
}
// getting the height of southern tables
if(fixedRowIdx >= -1 && fixedRowIdx < lastRowIdx) {
tableSE = tables.se.element();
tableSEParent = tableSE.parentNode;
tableSW = tables.sw.element();
tableSWParent = tableSW.parentNode;
leftRows = tableSW.rows;
rightRows = tableSE.rows;
rowCount = leftRows.length;
for(i = 0; i < rowCount; i++) {
heightArray.push(this._getRowHeight([
leftRows[i],
rightRows[i]
]));
}
}
// removing elments from dom to improve performance
if(fixedRowIdx > -1 && fixedRowIdx <= lastRowIdx) {
tableNWParent.removeChild(tableNW);
tableNEParent.removeChild(tableNE);
}
if(fixedRowIdx >= -1 && fixedRowIdx < lastRowIdx) {
tableSWParent.removeChild(tableSW);
tableSEParent.removeChild(tableSE);
}
// setting the height of northern tables
if(fixedRowIdx > -1 && fixedRowIdx <= lastRowIdx) {
leftRows = tableNW.rows;
rightRows = tableNE.rows;
rowCount = leftRows.length;
for(i = 0 , j = 0; i < rowCount; i++) {
this._setRowHeight([
leftRows[i],
rightRows[i]
], heightArray[j++]);
}
}
// setting the height of southern tables
if(fixedRowIdx >= -1 && fixedRowIdx < lastRowIdx) {
leftRows = tableSW.rows;
rightRows = tableSE.rows;
rowCount = leftRows.length;
for(i = 0; i < rowCount; i++) {
this._setRowHeight([
leftRows[i],
rightRows[i]
], heightArray[j++]);
}
}
// adding elments back to dom to improve performance
if(fixedRowIdx > -1 && fixedRowIdx <= lastRowIdx) {
tableNWParent.appendChild(tableNW);
tableNEParent.appendChild(tableNE);
}
if(fixedRowIdx >= -1 && fixedRowIdx < lastRowIdx) {
tableSWParent.appendChild(tableSW);
tableSEParent.appendChild(tableSE);
}
}
};
fixedView.prototype._adjustRowsHeights = // private abstract **
// ** private specific
function () {
var $tableSW = $(this._viewTables.sw.element()), $tableSE = $(this._viewTables.se.element()), height;
$tableSE.css("height", "");
$tableSW.css("height", "");
this._adjustRowHeight();
height = Math.max($tableSE.height(), $tableSW.height());
$tableSW.height(height);
$tableSE.height(height);
};
fixedView.prototype._destroySuperPanel = function () {
if(this._scroller.data("wijmo-wijsuperpanel")) {
if(this.vsUI) {
this.vsUI.dispose();
}
this._scroller.wijsuperpanel("destroy");
}
};
fixedView.prototype._onScroll = function (event, data) {
var spInstance = this._getSuperPanel();
if(this._allowVirtualScrolling) {
if(data.dir === "h") {
// do horizontal scrolling
this._setFixedAreaPosition((spInstance).getContentElement(), data.dir, data.position, data.animationOptions, false);
this._setFixedAreaPosition(this._splitAreas.ne, data.dir, data.position, data.animationOptions, true);
}
} else {
this._setFixedAreaPosition(data.dir === "h" ? this._splitAreas.ne : this._splitAreas.sw, data.dir, data.position, data.animationOptions, true);
}
this._wijgrid._trackScrollingPosition(spInstance.options.hScroller.scrollValue, spInstance.options.vScroller.scrollValue);
};
fixedView.prototype._onMouseWheel = function (e, delta) {
// force superpanel to do scrolling when cursor is placed over then non-scrollable (fixed) areas of the wijgrid.
var bounds, dir = (delta > 0) ? "top" : "bottom", isOverFixedArea = false, vPos;
if(this._wijgrid._canInteract()) {
bounds = this.getFixedAreaVisibleBounds()// an array
;
$.each(bounds, function (i, o) {
if(o && wijmo.grid.isOver(e.pageY, e.pageX, o.top, o.left, o.height, o.width)) {
isOverFixedArea = true;
return false;// break
}
});
if(isOverFixedArea && this._scroller.data("wijmo-wijsuperpanel")) {
vPos = this._scroller.wijsuperpanel("option", "vScroller").scrollValue;
this._scroller.wijsuperpanel("doScrolling", dir);
// simulate wijsuperpanel behaviour: prevent window scrolling until superpanel is not scrolled to the end.
if(vPos !== this._scroller.wijsuperpanel("option", "vScroller").scrollValue) {
e.stopPropagation();
e.preventDefault();
}
}
}
};
fixedView.prototype._setFixedAreaPosition = function (element, direction, position, animation, useScrollProp) {
var prop = {
}, key;
if(direction === "h") {
key = useScrollProp ? "scrollLeft" : "left";
} else {
key = useScrollProp ? "scrollTop" : "top";
}
if(!useScrollProp) {
position = -position// invert
;
}
if(animation) {
prop[key] = position;
element.animate(prop, animation);
} else {
if(useScrollProp) {
element[0][key] = position;
} else {
element.css(key, position);
}
}
};
fixedView.prototype._testNeedVBar = function (outerDiv, gridElement, tableNE, mode, autoHeight) {
var excludeVBarWidth, wijgrid = this._wijgrid, gridWidth = tableNE.width() + wijgrid.options.splitDistanceX, gridHeight = gridElement.height() + wijgrid.options.splitDistanceY, outerWidth = outerDiv.width(), outerHeight = outerDiv.height(), contentHeight, topHeight = 0, bottomHeight = 0;
if(this._allowVirtualScrolling && wijgrid._totalRowsCount() > 1) {
// special case -- always display vbar is wijgrid contains more than 1 row.
return true;
}
if(wijgrid.$superPanelHeader !== null) {
topHeight = wijgrid.$superPanelHeader.outerHeight(true);
}
if(wijgrid.$bottomPagerDiv !== null) {
bottomHeight = wijgrid.$bottomPagerDiv.outerHeight(true);
}
contentHeight = outerHeight - topHeight - bottomHeight;
if(mode === "both" || mode === "vertical") {
excludeVBarWidth = true;
} else {
excludeVBarWidth = (mode === "auto") && ((gridHeight > contentHeight) || (!autoHeight && gridWidth > outerWidth && gridHeight > contentHeight - this._verScrollBarSize))// When the height needs to be auto adjusted, the vertical scrollbar should not be shown
;
}
return excludeVBarWidth;
};
fixedView.prototype._updateSplitAreaBounds = //bSet: 0-width, 1-height, 2-all
function (bSet) {
var wijgrid = this._wijgrid, o = wijgrid.options, controlHeight, contentHeight, topHeight = 0, bottomHeight = 0;
if(bSet === 0 || bSet === 2) {
this._splitAreas.nw.width(o.splitDistanceX);
this._splitAreas.sw.width(o.splitDistanceX);
this._splitAreas.se.css("marginLeft", o.splitDistanceX);
this._splitAreas.ne.css("marginLeft", o.splitDistanceX);
}
if(bSet === 1 || bSet === 2) {
this._scroller.css("height", "");
this._splitAreas.se.css("marginTop", 0);
controlHeight = wijgrid.outerDiv.height();
if(!wijgrid._autoHeight) {
this._scroller.height(controlHeight);
} else {
// no height is set for outer div, we need to expand the grid.
this._scroller.height(controlHeight + o.splitDistanceY);
//this._noHeight = true;
}
this._splitAreas.nw.height(o.splitDistanceY);
this._splitAreas.ne.height(o.splitDistanceY);
if(wijgrid.$superPanelHeader !== null) {
topHeight = wijgrid.$superPanelHeader.outerHeight(true);
}
if(wijgrid.$bottomPagerDiv !== null) {
bottomHeight = wijgrid.$bottomPagerDiv.outerHeight(true);
}
contentHeight = controlHeight - topHeight - bottomHeight;
if(wijgrid.$superPanelHeader !== null) {
this._splitAreas.nw.css("top", topHeight + "px");
this._splitAreas.ne.css("top", topHeight + "px");
}
if(!wijgrid._autoHeight) {
this._splitAreas.sw.height(contentHeight - o.splitDistanceY);
} else {
this._splitAreas.sw.height(contentHeight);
}
this._splitAreas.sw.css("top", o.splitDistanceY + topHeight);
this._splitAreas.se.css("marginTop", o.splitDistanceY);
}
};
return fixedView;
})(grid.baseView);
grid.fixedView = fixedView;
// private specific **
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts" />
/// <reference path="wijgrid.ts" />
/// <reference path="misc.ts" />
(function (grid) {
"use strict";
var $ = jQuery;
/** An object that represents selection in the grid. You do not need to create instances of this class. */
var selection = (function () {
/** Creates an object that represents selection in the grid. Normally you do not need to use this method.
* @example
* var selection = new wijmo.grid.selection(wijgrid);
* @param {wijmo.wijgrid} wijgrid wijgrid
* @returns {wijmo.grid.selection} Object that represents selection in the grid
*/
function selection(wijgrid) {
this._updates = 0;
this._selectedColumns = null;
// ?
this._selectedRows = null;
// ?
// n: none (0), c: extendToColumn (1), r: extendToRow (2)
//
// extendMode
// selectionMode| n | c | r
// ------------------------
// singlecell | n | n | n
// singlecolumn | c | c | c
// singlerow | r | r | r
// singlerange | n | c | r
// multicolumn | c | c | c
// multirow | r | r | r
// multirange | n | c | r
this._extend_rules = {
"singlecell": [
0,
0,
0
],
"singlecolumn": [
1,
1,
1
],
"singlerow": [
2,
2,
2
],
"singlerange": [
0,
1,
2
],
"multicolumn": [
1,
1,
1
],
"multirow": [
2,
2,
2
],
"multirange": [
0,
1,
2
]
};
if(!wijgrid) {
throw "invalid arguments";
}
this._wijgrid = wijgrid;
this._addedCells = new cellInfoOrderedCollection(wijgrid);
this._removedCells = new cellInfoOrderedCollection(wijgrid);
this._selectedCells = new cellInfoOrderedCollection(wijgrid);
this._addedDuringCurTransactionCells = new cellInfoOrderedCollection(wijgrid);
}
selection.prototype.selectedCells = /** Gets a read-only collection of the selected cells.
* @example
* var selectedCells = selectionObj.selectedCells();
* for (var i = 0, len = selectedCells.length(); i < len; i++) {
* alert(selectedCells.item(i).value().toString());
* }
* @returns {wijmo.grid.cellInfoOrderedCollection} A read-only collection of the selected cells.
*/
function () {
return this._selectedCells;
};
selection.prototype.addColumns = /** Adds a column range to the current selection.
* Usage:
* 1. addColumns(0)
* 2. addColumns(0, 2)
* @example
* // Add the first column to the current selection.
* selectionObj.addColumns(0);
* @remarks
* The result depends upon the chosen selection mode in the grid. For example, if current selection mode does not allow multiple selection the previous selection will be removed.
* @param {Number} start The index of the first column to select.
* @param {Number} end The index of the last column to select.
*/
function (start, end/* opt */ ) {
if(!end && end !== 0) {
end = start;
}
this.addRange(start, 0, end, 0xFFFFFF);
};
selection.prototype.addRange = /** @ignore */
function (cellRange/* x0 */ , y0/* opt */ , x1/* opt */ , y1/* opt */ ) {
if(!cellRange && (arguments.length === 1)) {
throw "invalid argument";
}
var range = (arguments.length === 4) ? new wijmo.grid.cellInfoRange(new wijmo.grid.cellInfo(cellRange/* ie x0 */ , y0), new wijmo.grid.cellInfo(x1, y1)) : cellRange._clone();
range._normalize();
if(!range._isValid()) {
throw "invalid argument";
}
this.beginUpdate();
this._startNewTransaction(this._wijgrid._field("currentCell"));
this._selectRange(range, false, true, 0/* none*/ , null);
this.endUpdate();
};
selection.prototype.addRows = /** Adds a row range to the current selection.
* Usage:
* 1. addRows(0)
* 2. addRows(0, 2)
* @example
* // Add the first row to the selection.
* selectionObj.addRows(0);
* @remarks
* The result depends upon the chosen selection mode in the grid. For example, if current selection mode does not allow multiple selection the previous selection will be removed.
* @param {Number} start The index of the first row to select.
* @param {Number} end The index of the last row to select.
*/
function (start, end/* opt */ ) {
if(!end && end !== 0) {
end = start;
}
this.addRange(0, start, 0xFFFFFF, end);
};
selection.prototype.removeRange = /** @ignore */
function (cellRange/* x0 */ , y0/* opt */ , x1/* opt */ , y1/* opt */ ) {
if(!cellRange && (arguments.length === 1)) {
throw "invalid argument";
}
var range = (arguments.length === 4) ? new wijmo.grid.cellInfoRange(new wijmo.grid.cellInfo(cellRange, y0), new wijmo.grid.cellInfo(x1, y1)) : cellRange._clone();
range._normalize();
if(!range._isValid()) {
throw "invalid argument";
}
this.beginUpdate();
this._startNewTransaction(this._wijgrid._field("currentCell"));
this._clearRange(range, 0/* none */ );
this.endUpdate();
};
selection.prototype.removeColumns = /**
* Removes a range of columns from the current selection.
* Usage:
* 1. removeColumns(0)
* 2. removeColumns(0, 2)
* @example
* // Remove the first columm from the selection.
* selectionObj.removeColumns(0);
* @remarks
* The result depends upon the chosen selection mode in the grid.
* @param {Number} start The index of the first column to remove.
* @param {Number} end The index of the last column to remove.
*/
function (start, end/* opt */ ) {
if(!end && end !== 0) {
end = start;
}
this.removeRange(start, 0, end, 0xFFFFFF);
};
selection.prototype.removeRows = /** Removes a range of rows from the current selection.
* Usage:
* 1. removeRows(0)
* 2. removeRows(0, 2)
* @example
* // Remove the first row from the selection.
* selectionObj.removeRows(0);
* @remarks
* The result depends upon the chosen selection mode in the grid.
* @param {Number} start The index of the first row to remove.
* @param {Number} end The index of the last row to remove.
*/
function (start, end/* opt */ ) {
if(!end && end !== 0) {
end = start;
}
this.removeRange(0, start, 0xFFFFFF, end);
};
selection.prototype.clear = /**
* Clears the selection.
* @example
* // Clear the selection.
* selectionObj.clear();
*/
function () {
this.beginUpdate();
this._removedCells._clear();
this._removedCells._addFrom(this._selectedCells);
this.endUpdate();
};
selection.prototype.selectAll = /**
* Selects all the cells in a grid.
* @example
* selectionObj.selectAll();
* @remarks
* The result depends upon the chosen selection mode in the grid. For example, if the selection mode is set to "singleCell", then only the top left cell will be selected.
*/
function () {
this.beginUpdate();
this._selectRange(this._wijgrid._getDataCellsRange(), false, false, 0/* none */ , null);
this.endUpdate();
};
selection.prototype.beginUpdate = /**
* Begins the update. Any changes won't take effect until endUpdate() is called.
* @example
* selectionObj.beginUpdate();
*/
function () {
this._updates++;
};
selection.prototype.endUpdate = /**
* Ends the update. The pending changes are executed and the selectionChanged event is raised.
* @example
* selectionObj.endUpdate();
*/
function () {
if(this._updates > 0) {
this._updates--;
if(this._updates === 0) {
this.doSelection()// values must be clipped before this step
;
if(this._addedCells.length() || this._removedCells.length()) {
if(this._selectedColumns !== null) {
this._selectedColumns.UnderlyingDataChanged()// notify
;
}
if(this._selectedRows !== null) {
this._selectedRows.UnderlyingDataChanged()// notify
;
}
this._wijgrid._trigger("selectionChanged", null, {
addedCells: this._addedCells,
removedCells: this._removedCells
});
}
this._addedCells = new wijmo.grid.cellInfoOrderedCollection(this._wijgrid);
this._removedCells._clear();
}
}
};
selection.prototype._multipleRangesAllowed = // * internal
function () {
var mode = this._wijgrid.options.selectionMode;
return (mode && ((mode = mode.toLowerCase()) === "multicolumn" || mode === "multirow" || mode === "multirange"));
};
selection.prototype._anchorCell = function () {
return this.__anchorCell;
};
selection.prototype._startNewTransaction = function (dataCellInfo) {
if(dataCellInfo) {
this.__anchorCell = dataCellInfo._clone();
this._addedDuringCurTransactionCells = new wijmo.grid.cellInfoOrderedCollection(this._wijgrid);
}
};
selection.prototype._clearRange = function (range, extendMode) {
var selectionMode = this._wijgrid.options.selectionMode.toLowerCase(), rangeToClear, rowsLen, cellsLen, flag, row, cell, i, len, cellInfo, dataRange = this._wijgrid._getDataCellsRange();
if(range._isValid() && (selectionMode !== "none") && (this._selectedCells.length() > 0)) {
rangeToClear = range._clone();
rangeToClear._normalize();
rangeToClear._clip(dataRange);
if(!range._isValid()) {
return;
}
// extend
rangeToClear._extend(this._extend_rules[selectionMode][extendMode], dataRange);
this.beginUpdate();
// remove selected cells only, do not use doRange(rangeToClear, false) here.
for(i = 0 , len = this._selectedCells.length(); i < len; i++) {
cellInfo = this._selectedCells.item(i);
if(rangeToClear._containsCellInfo(cellInfo)) {
this._removedCells._add(cellInfo);
}
}
this.endUpdate();
}
};
selection.prototype._selectRange = function (range, ctrlKey, shiftKey, extendMode, endPoint) {
var selectionMode = this._wijgrid.options.selectionMode.toLowerCase(), rangeToSelect, dataRange = this._wijgrid._getDataCellsRange();
if((selectionMode !== "none") && range._isValid()) {
rangeToSelect = range._clone();
rangeToSelect._normalize();
rangeToSelect._clip(dataRange);
if(!rangeToSelect._isValid()) {
return;
}
this.beginUpdate();
if(!this._multipleRangesAllowed()) {
this.clear();
} else {
if(ctrlKey || shiftKey) {
if(shiftKey) {
this._removedCells._clear();
this._removedCells._addFrom(this._addedDuringCurTransactionCells);
}
} else {
this.clear();
}
}
// truncate range by selectionMode
switch(selectionMode) {
case "singlecell":
case "singlecolumn":
case "singlerow":
rangeToSelect = (endPoint === null) ? new wijmo.grid.cellInfoRange(rangeToSelect.topLeft(), rangeToSelect.topLeft()) : // top-left cell only is taken into consideration.
new wijmo.grid.cellInfoRange(endPoint, endPoint);
break;
}
// extend
rangeToSelect._extend(this._extend_rules[selectionMode][extendMode], dataRange);
// do selection
this.doRange(rangeToSelect, true);
this.endUpdate();
}
};
selection.prototype.doSelection = // * internal
// * private
function () {
var offsets = this._wijgrid._getDataToAbsOffset(), cellOffset = offsets.x, rowOffset = offsets.y, view = this._wijgrid._view(), i, len, info, cell, $cell, index, $rs = wijmo.grid.renderState, rowInfo, state, prevRowIndex = -1;
for(i = 0 , len = this._removedCells.length(); i < len; i++) {
info = this._removedCells.item(i);
if(this._addedCells.indexOf(info) < 0) {
cell = view.getCell(info.cellIndex() + cellOffset, info.rowIndex() + rowOffset);
if(cell) {
if(prevRowIndex !== info.rowIndex()) {
rowInfo = info.row();
prevRowIndex = info.rowIndex();
}
$cell = $(cell);
state = view._changeCellRenderState($cell, $rs.selected, false);
this._wijgrid.cellStyleFormatter.format($cell, info.cellIndex(), info.column(), rowInfo, state);
}
this._selectedCells._remove(info);
this._addedDuringCurTransactionCells._remove(info);
} else {
this._removedCells._removeAt(i);
i--;
len--;
}
}
prevRowIndex = -1;
for(i = 0 , len = this._addedCells.length(); i < len; i++) {
info = this._addedCells.item(i);
index = this._selectedCells.indexOf(info);
if(index < 0) {
cell = view.getCell(info.cellIndex() + cellOffset, info.rowIndex() + rowOffset);
if(cell) {
if(prevRowIndex !== info.rowIndex()) {
rowInfo = info.row();
prevRowIndex = info.rowIndex();
}
$cell = $(cell);
state = view._changeCellRenderState($cell, $rs.selected, true);
this._wijgrid.cellStyleFormatter.format($cell, info.cellIndex(), info.column(), rowInfo, state);
}
this._selectedCells._insertUnsafe(info, ~index);
this._addedDuringCurTransactionCells._add(info);
} else {
this._addedCells._removeAt(i);
i--;
len--;
}
}
};
selection.prototype.doRange = function (range, add) {
var x0 = range.topLeft().cellIndex(), y0 = range.topLeft().rowIndex(), x1 = range.bottomRight().cellIndex(), y1 = range.bottomRight().rowIndex(), cnt, row, col, cell, view = this._wijgrid._view(), rowInfo, rows;
if(add) {
cnt = this._addedCells.length();
rows = this._wijgrid._rows();
for(row = y0; row <= y1; row++) {
rowInfo = view._getRowInfo(rows.item(row));
if(rowInfo.type & wijmo.grid.rowType.data) {
for(col = x0; col <= x1; col++) {
cell = new wijmo.grid.cellInfo(col, row);
if(cnt === 0) {
this._addedCells._appendUnsafe(cell);
} else {
this._addedCells._add(cell);
}
}
}
}
} else {
cnt = this._removedCells.length();
for(row = y0; row <= y1; row++) {
for(col = x0; col <= x1; col++) {
cell = new wijmo.grid.cellInfo(col, row);
if(cnt === 0) {
this._removedCells._appendUnsafe(cell);
} else {
this._removedCells._add(cell);
}
}
}
}
};
return selection;
})();
grid.selection = selection;
// * private
/** An ordered read-only collection of wijmo.grid.cellInfo objects */
var cellInfoOrderedCollection = (function () {
/**
* Creates an ordered read-only collection of wijmo.grid.cellInfo objects. Normally you do not need to use this method.
* @example
* var collection = new wijmo.grid.cellInfoOrderedCollection(wijgrid);
* @param {wijmo.wijgrid} wijgrid wijgrid
* @returns {wijmo.grid.cellInfoOrderedCollection} An ordered read-only collection of wijmo.grid.cellInfo objects
*/
function cellInfoOrderedCollection(wijgrid) {
this._clear = function () {
this._list.length = 0;
};
if(!wijgrid) {
throw "invalid arguments";
}
this._wijgrid = wijgrid;
this._list = [];
}
cellInfoOrderedCollection.prototype.item = // public
/** Gets an item at the specified index.
* @example
* var cellInfoObj = collection.item(0);
* @param {Number} index The zero-based index of the item to get.
* @returns {wijmo.grid.cellInfo} The wijmo.grid.cellInfo object at the specified index.
*/
function (index) {
return this._list[index];
};
cellInfoOrderedCollection.prototype.length = /** Gets the total number of the items in the collection.
* @example
* var len = collection.length();
* @returns {Number} The total number of the items in the collection.
*/
function () {
return this._list.length;
};
cellInfoOrderedCollection.prototype.indexOf = /** @ignore */
function (cellIndex, rowIndex) {
if(arguments.length === 1) {
rowIndex = cellIndex.rowIndex();
cellIndex = cellIndex.cellIndex();
}
var lo = 0, hi = this._list.length - 1, med, current, cmp;
while(lo <= hi) {
med = lo + ((hi - lo) >> 1);
current = this._list[med];
cmp = current.rowIndex() - rowIndex;
if(cmp === 0) {
cmp = current.cellIndex() - cellIndex;
}
if(cmp < 0) {
lo = med + 1;
} else {
if(cmp > 0) {
hi = med - 1;
} else {
return med;
}
}
}
return ~lo;
};
cellInfoOrderedCollection.prototype.toString = /** @ignore */
function () {
var val = "", i, len;
for(i = 0 , len = this._list.length; i < len; i++) {
val += this._list[i].toString() + "\n";
}
return val;
};
cellInfoOrderedCollection.prototype._add = // public *
// internal
function (value) {
var idx = this.indexOf(value);
if(idx < 0) {
this._list.splice(~idx, 0, value);
value._setGridView(this._wijgrid);
return true;
}
return false;
};
cellInfoOrderedCollection.prototype._addFrom = function (addFrom) {
if(addFrom) {
var fromLen = addFrom.length(), thisLen = this._list.length, i;
if(thisLen === 0) {
this._list.length = fromLen;
for(i = 0; i < fromLen; i++) {
this._list[i] = addFrom.item(i);
this._list[i]._setGridView(this._wijgrid);
}
} else {
for(i = 0; i < fromLen; i++) {
this._add(addFrom.item(i));
}
}
}
};
cellInfoOrderedCollection.prototype._appendUnsafe = function (value) {
this._list[this._list.length] = value;
value._setGridView(this._wijgrid);
};
cellInfoOrderedCollection.prototype._insertUnsafe = function (value, index) {
this._list.splice(index, 0, value);
};
cellInfoOrderedCollection.prototype._remove = function (value) {
var idx = this.indexOf(value);
if(idx >= 0) {
this._list.splice(idx, 1);
return true;
}
return false;
};
cellInfoOrderedCollection.prototype._removeAt = function (index) {
this._list.splice(index, 1);
};
cellInfoOrderedCollection.prototype._getColumnsIndicies = function () {
var columns = [], len = this._list.length, tmpColumns, i, len2;
if(len) {
tmpColumns = [];
for(i = 0; i < len; i++) {
tmpColumns[this._list[i].cellIndex()] = 1;
}
len = tmpColumns.length;
len2 = 0;
for(i = 0; i < len; i++) {
if(tmpColumns[i]) {
columns[len2++] = i;
}
}
}
return columns;
};
cellInfoOrderedCollection.prototype._getSelectedRowsIndicies = function () {
var rows = [], len = this._list.length, tmpRows, i, len2;
if(len) {
tmpRows = [];
for(i = 0; i < len; i++) {
tmpRows[this._list[i].rowIndex()] = 1;
}
len = tmpRows.length;
len2 = 0;
for(i = 0; i < len; i++) {
if(tmpRows[i]) {
rows[len2++] = i;
}
}
}
return rows;
};
cellInfoOrderedCollection.prototype._rectangulate = function () {
var len = this._list.length, x0 = 0xFFFFFFFF, y0 = 0xFFFFFFFF, x1 = 0, y1 = 0, i, cellInfo;
if(len) {
for(i = 0; i < len; i++) {
cellInfo = this._list[i];
x0 = Math.min(x0, cellInfo.cellIndex());
y0 = Math.min(y0, cellInfo.rowIndex());
x1 = Math.max(x1, cellInfo.cellIndex());
y1 = Math.max(y1, cellInfo.rowIndex());
}
return new wijmo.grid.cellInfoRange(new wijmo.grid.cellInfo(x0, y0), new wijmo.grid.cellInfo(x1, y1));
}
return null;
};
return cellInfoOrderedCollection;
})();
grid.cellInfoOrderedCollection = cellInfoOrderedCollection;
// internal *
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
/// <reference path="wijgrid.ts"/>
/// <reference path="cellInfo.ts"/>
/// <reference path="rowAccessor.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var uiSelection = (function () {
function uiSelection(wijgrid) {
this._gap_to_start = 10;
this._inProgress = false;
this._additionalEventsAttached = false;
this._wijgrid = wijgrid;
this._evntFormat = "{0}." + this._wijgrid.widgetName + ".selectionui";
this._addedCells = new wijmo.grid.cellInfoOrderedCollection(this._wijgrid);
this._view = this._wijgrid._view();
this._rootElement = this._view.focusableElement();
this._visLeavesLen = this._wijgrid._field("visibleLeaves").length;
this._rootElement.bind(this._eventKey("mousedown"), $.proxy(this._onGridMouseDown, this));
}
uiSelection.prototype.dispose = function () {
this._rootElement.unbind(this._eventKey("mousedown"), this._onGridMouseDown);
this._detachAdditionalEvents();
};
uiSelection.prototype._onGridMouseDown = function (args) {
if(!this._wijgrid._canInteract() || this._wijgrid.options.selectionMode.toLowerCase() === "none") {
return;
}
var visibleBounds = this._view.getVisibleAreaBounds(), mouse = {
x: args.pageX,
y: args.pageY
}, tag = ((args.target && (args.target).tagName !== undefined) ? (args.target).tagName.toLowerCase() : undefined), $target = $(args.target);
if((!tag || $target.is("td.wijgridtd, th.wijgridtd, div.wijmo-wijgrid-innercell")) && (mouse.x > visibleBounds.left && mouse.x < visibleBounds.left + visibleBounds.width) && (mouse.y > visibleBounds.top && mouse.y < visibleBounds.top + visibleBounds.height)) {
this._attachAdditionalEvents();
this._startPos = mouse;
this._startCellInfo = this._coordToDataCellInfo(this._startPos);
}
};
uiSelection.prototype._onDocumentMouseMove = function (args) {
if(!this._startCellInfo || !this._startCellInfo._isValid()) {
return;
}
var mouse = {
x: args.pageX,
y: args.pageY
}, tmp, info, range, dataOffset, desiredCells, rowsLen, cellsLen, row, cell, i, len, $cell, rowInfo, prevRowIndex, state, view = this._wijgrid._view(), rows = this._wijgrid._rows(), $rs = wijmo.grid.renderState;
if(!this._inProgress) {
this._inProgress = (Math.abs(this._startPos.x - mouse.x) > this._gap_to_start) || (Math.abs(this._startPos.y - mouse.y) > this._gap_to_start);
}
if(this._inProgress) {
tmp = this._coordToDataCellInfo(mouse);
if(!tmp._isValid()) {
return;
}
this._endCellInfo = tmp;
range = new wijmo.grid.cellInfoRange(this._startCellInfo, this._endCellInfo);
range._normalize();
range._clip(this._wijgrid._getDataCellsRange());
if(range._isValid() && !range.isEqual(this._prevMouseMoveRange)) {
dataOffset = this._wijgrid._getDataToAbsOffset();
this._prevMouseMoveRange = range;
desiredCells = new wijmo.grid.cellInfoOrderedCollection(this._wijgrid);
rowsLen = range.bottomRight().rowIndex();
cellsLen = range.bottomRight().cellIndex();
for(row = range.topLeft().rowIndex(); row <= rowsLen; row++) {
rowInfo = view._getRowInfo(rows.item(row));
if(rowInfo.type & wijmo.grid.rowType.data) {
for(cell = range.topLeft().cellIndex(); cell <= cellsLen; cell++) {
desiredCells._appendUnsafe(new wijmo.grid.cellInfo(cell, row));
}
}
}
prevRowIndex = -1;
for(i = 0 , len = this._addedCells.length(); i < len; i++) {
info = this._addedCells.item(i);
if(desiredCells.indexOf(info) < 0)// remove css
{
if(this._wijgrid.selection().selectedCells().indexOf(info) < 0) {
cell = this._view.getCell(info.cellIndex() + dataOffset.x, info.rowIndex() + dataOffset.y);
if(cell) {
if(prevRowIndex !== info.rowIndex()) {
rowInfo = info.row();
prevRowIndex = info.rowIndex();
}
$cell = $(cell);
state = view._changeCellRenderState($cell, $rs.selected, false);
this._wijgrid.cellStyleFormatter.format($cell, info.cellIndex(), info.column(), rowInfo, state);
}
}
this._addedCells._removeAt(i);
i--;
len--;
}
}
prevRowIndex = -1;
for(i = 0 , len = desiredCells.length(); i < len; i++) {
info = desiredCells.item(i);
if(this._addedCells.indexOf(info) < 0 && this._wijgrid.selection().selectedCells().indexOf(info) < 0) {
if(this._addedCells._add(info)) {
cell = this._view.getCell(info.cellIndex() + dataOffset.x, info.rowIndex() + dataOffset.y);
if(cell) {
if(prevRowIndex !== info.rowIndex()) {
rowInfo = info.row();
prevRowIndex = info.rowIndex();
}
$cell = $(cell);
state = view._changeCellRenderState($cell, $rs.selected, true);
this._wijgrid.cellStyleFormatter.format($cell, info.cellIndex(), info.column(), rowInfo, state);
}
}
}
}
}// end if
}
};
uiSelection.prototype._onDocumentMouseUp = function (args) {
this._detachAdditionalEvents();
if(this._inProgress) {
this._inProgress = false;
if(this._prevMouseMoveRange && this._prevMouseMoveRange._isValid()) {
this._wijgrid._changeCurrentCell(args, this._endCellInfo);
if(!args.shiftKey || (!this._wijgrid.selection()._multipleRangesAllowed() && this._wijgrid.options.selectionMode.toLowerCase() !== "singleRange")) {
this._wijgrid.selection()._startNewTransaction(this._startCellInfo);
}
this._wijgrid.selection().beginUpdate();
this._wijgrid.selection()._selectRange(this._prevMouseMoveRange, args.shiftKey, args.ctrlKey, 0/* none */ , this._endCellInfo);
this._wijgrid.selection().endUpdate();
var view = this._wijgrid._view(), dataOffset = this._wijgrid._getDataToAbsOffset(), i, len, info, cell, $cell, prevRowIndex = -1, rowInfo, state, $rs = wijmo.grid.renderState;
// clear remained cells
for(i = 0 , len = this._addedCells.length(); i < len; i++) {
info = this._addedCells.item(i);
if(this._wijgrid.selection().selectedCells().indexOf(info) < 0) {
cell = view.getCell(info.cellIndex() + dataOffset.x, info.rowIndex() + dataOffset.y);
if(cell !== null) {
if(prevRowIndex !== info.rowIndex()) {
rowInfo = info.row();
prevRowIndex = info.rowIndex();
}
$cell = $(cell);
state = view._changeCellRenderState($cell, $rs.selected, false);
this._wijgrid.cellStyleFormatter.format($cell, info.cellIndex(), info.column(), rowInfo, state);
}
}
}
this._addedCells._clear();
this._startCellInfo = this._endCellInfo = this._prevMouseMoveRange = null;
return false;// cancel bubbling
}
}
};
uiSelection.prototype._attachAdditionalEvents = function () {
if(!this._additionalEventsAttached) {
try {
this._view.toggleDOMSelection(false)// disable selection
;
$(document).bind(this._eventKey("mousemove"), $.proxy(this._onDocumentMouseMove, this)).bind(this._eventKey("mouseup"), $.proxy(this._onDocumentMouseUp, this));
}finally {
this._additionalEventsAttached = true;
}
}
};
uiSelection.prototype._detachAdditionalEvents = function () {
if(this._additionalEventsAttached) {
try {
this._view.toggleDOMSelection(true)// enable selection
;
$(document).unbind(this._eventKey("mousemove"), this._onDocumentMouseMove).unbind(this._eventKey("mouseup"), this._onDocumentMouseUp);
}finally {
this._additionalEventsAttached = false;
}
}
};
uiSelection.prototype._eventKey = function (eventType) {
return wijmo.grid.stringFormat(this._evntFormat, eventType);
};
uiSelection.prototype._coordToDataCellInfo = function (pnt) {
var left = 0, right = this._visLeavesLen - 1, median = 0, cellIdx = -1, bounds, gridRowsAccessor = new wijmo.grid.rowAccessor(this._view, 2/* tbody */ , 0, 0), rowIdx, rowObj, dataOffset, result;
// get cell index
while(left <= right) {
median = ((right - left) >> 1) + left;
bounds = wijmo.grid.bounds(this._view.getHeaderCell(median))// get header cell
;
if(!bounds) {
// no header?
rowObj = gridRowsAccessor.item(0);
bounds = wijmo.grid.bounds(wijmo.grid.rowAccessor.getCell(rowObj, median))// get data cell
;
}
if(!bounds) {
break;
}
if(pnt.x < bounds.left) {
// -1
right = median - 1;
} else if(pnt.x > bounds.left + bounds.width) {
// 1
left = median + 1;
} else {
// 0
cellIdx = median;
break;
}
}
if(cellIdx === -1) {
return wijmo.grid.cellInfo.outsideValue;
}
gridRowsAccessor = new wijmo.grid.rowAccessor(this._view, 0/* all */ , 0, 0);
rowIdx = -1;
left = 0;
right = gridRowsAccessor.length() - 1;
median = 0;
// get row index
while(left <= right) {
median = ((right - left) >> 1) + left;
rowObj = gridRowsAccessor.item(median);
bounds = wijmo.grid.bounds(wijmo.grid.rowAccessor.getCell(rowObj, 0));
if(pnt.y < bounds.top) {
// -1
right = median - 1;
} else if(pnt.y > bounds.top + bounds.height) {
// 1
left = median + 1;
} else {
// 0
rowIdx = median;
break;
}
}// end while { }
if(rowIdx === -1) {
return wijmo.grid.cellInfo.outsideValue;
}
dataOffset = this._wijgrid._getDataToAbsOffset();
result = new wijmo.grid.cellInfo(cellIdx - dataOffset.x, rowIdx - dataOffset.y);
result._clip(this._wijgrid._getDataCellsRange());
return result;
};
return uiSelection;
})();
grid.uiSelection = uiSelection;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
/// <reference path="baseView.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/**
* Class for convenient access to rows of a wijgrid.
* @ignore
*/
var rowAccessor = (function () {
function rowAccessor(view, scope, offsetTop, offsetBottom) {
this._view = view;
this._scope = scope;
this._offsetBottom = offsetBottom;
this._offsetTop = offsetTop;
}
rowAccessor.prototype.item = /** Gets an array of the table row elements that represents a wijgrid widget row at the specified index.
* size of returning array is always two.
* @param {Number} index The zero-based index of the row to retrieve.
* @returns {Object[]} The array of the table row elements at the specified index.
* @remarks
*/
function (index) {
var len = this.length();
return (index < len) ? this._view.getJoinedRows(index + this._offsetTop, this._scope) : null;
};
rowAccessor.prototype.length = /**
* Gets the total number of elements.
* @returns {Number} The total number of elements.
*/
function () {
var joinedTables = this._view.getJoinedTables(true, 0), len = 0, htmlAccessor;
if(htmlAccessor = joinedTables[0]) {
len = htmlAccessor.getSectionLength(this._scope);
}
if(htmlAccessor = joinedTables[1]) {
len += htmlAccessor.getSectionLength(this._scope);
}
len -= this._offsetTop + this._offsetBottom;
if(len < 0) {
len = 0;
}
return len;
};
rowAccessor.iterateCells = /** Sequentially iterates the cells in a rowObj argument.
* @param {Array} rowObj Array of rows to be iterated.
* @param {Function} callback Function that will be called each time a new cell is reached.
* @param {Object} param Parameter that can be handled within the callback function.
*/
function iterateCells(rowObj, callback, param) {
if(rowObj && callback) {
var globCellIdx = 0, i, len, domRow, j, cellLen, result;
for(i = 0 , len = rowObj.length; i < len; i++) {
domRow = rowObj[i];
if(domRow) {
for(j = 0 , cellLen = domRow.cells.length; j < cellLen; j++) {
result = callback(domRow.cells[j], globCellIdx++, param);
if(result !== true) {
return;
}
}
}
}
}
};
rowAccessor.getCell = /** Gets a cell by its global index in a row's array passed in rowObj.
* @example:
* Suppose rows is an array containing the following data: [ ["a", "b"], ["c", "d", "e"] ]
* "a" symbol has a global index 0.
* "c" symbol has a global index 2.
* @param {Array} rowObj Array of table row elements.
* @param {Number} index Zero-based global index of a cell.
* @returns {HTMLTableCellElement} A cell or null if a cell with provided index is not found.
*/
function getCell(rowObj, globCellIndex) {
var domRow, cellLen;
if(rowObj && (domRow = rowObj[0])) {
cellLen = domRow.cells.length;
if(globCellIndex < cellLen) {
return domRow.cells[globCellIndex];
}
globCellIndex -= cellLen;
if(domRow = rowObj[1]) {
cellLen = domRow.cells.length;
if(globCellIndex < cellLen) {
return domRow.cells[globCellIndex];
}
}
}
return null;
};
rowAccessor.cellsCount = /** Gets the number of cells in a array of table row elements.
* @param {Array} rowObj Array of table row elements.
* @returns {Number} The number of cells in a array of table row elements.
*/
function cellsCount(rowObj) {
var res = 0, domRow;
if(rowObj && (domRow = rowObj[0])) {
res = domRow.cells.length;
if(domRow = rowObj[1]) {
res += domRow.cells.length;
}
}
return res;
};
return rowAccessor;
})();
grid.rowAccessor = rowAccessor;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts" />
/// <reference path="wijgrid.ts" />
/// <reference path="misc.ts" />
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var cellEditorHelper = (function () {
function cellEditorHelper() {
this._timeout = 25;
}
cellEditorHelper.prototype.currentCellEditStart = function (grid, e) {
var result = false, currentCell = grid.currentCell(), view = grid._view(), rowInfo, args, $innerDiv, rowType;
if(currentCell._isValid() && !currentCell._isEdit() && (currentCell.column().dataIndex >= 0)) {
rowInfo = currentCell.row();
if(rowInfo) {
rowType = rowInfo.type;
if(rowType & wijmo.grid.rowType.data) {
args = {
cell: currentCell,
event: e,
handled: false
};
if(result = grid._trigger("beforeCellEdit", null, args)) {
// todo
if(!args.handled) {
result = this._defaultBeforeCellEdit(grid, args);
}
}
if(result) {
currentCell._isEdit(true);
if(grid.options.showRowHeader) {
$innerDiv = $((rowInfo.$rows[0]).cells[0]).children("div.wijmo-wijgrid-innercell");
if($innerDiv.length) {
$innerDiv.empty();
$innerDiv.append($("<div> </div>").addClass(grid.options.wijCSS.icon + " ui-icon-pencil"));
}
}
}
}
}
}
return result;
};
cellEditorHelper.prototype.currentCellEditEnd = function (grid, e) {
var currentCell = grid.currentCell(), column = currentCell.column(), result = false, view = grid._view(), rowInfo, rowType, escPressed, a, b, domCell, keyCodeEnum = wijmo.grid.getKeyCodeEnum(), inputType;
if(!currentCell._isValid() || !currentCell._isEdit()) {
return;
}
rowInfo = currentCell.row();
if(rowInfo) {
rowType = rowInfo.type;
if(!(rowType & wijmo.grid.rowType.data)) {
return result;
}
escPressed = (e && e.which === keyCodeEnum.ESCAPE);
if(!e || (!escPressed)) {
var bcuArgs = {
cell: currentCell,
value: undefined
};
if(result = grid._trigger("beforeCellUpdate", null, bcuArgs)) {
if(bcuArgs.value === undefined) {
bcuArgs.value = this._getCellValue(grid, currentCell)// get raw value from editor using the default implementation.
;
}
a = bcuArgs.value// new value
;
b = currentCell.value()// old value
;
try {
inputType = this._getHTMLInputElementType(currentCell);
// xxx
if(wijmo.grid.HTML5InputSupport.isExtendSupportRequired(inputType)) {
bcuArgs.value = wijmo.grid.HTML5InputSupport.parse(bcuArgs.value, inputType);
bcuArgs.value = wijmo.grid.HTML5InputSupport.extend(b, bcuArgs.value, inputType);
} else {
// xxx
bcuArgs.value = grid.parse(currentCell.column(), bcuArgs.value)// try to parse raw value
;
}
a = bcuArgs.value;
} catch (ex) {
bcuArgs.value = a// restore raw value
;
}
if(wijmo.grid.getDataType(column) === "datetime") {
if(a instanceof Date) {
a = a.getTime();
}
if(b instanceof Date) {
b = b.getTime();
}
}
if(a !== b) {
// value is changed
// update datasource
try {
currentCell.value(bcuArgs.value);
} catch (ex) {
var icvArgs = {
cell: currentCell,
value: bcuArgs.value
};
result = false;
grid._trigger("invalidCellValue", null, icvArgs);
}
if(result) {
var acuArgs = {
cell: currentCell
};
grid._trigger("afterCellUpdate", null, acuArgs);
}
}
}
} else {
// ESC key
result = true;
}
if(result) {
var aceArgs = {
cell: currentCell,
event: e,
handled: false
};
grid._trigger("afterCellEdit", null, aceArgs);
if(!aceArgs.handled) {
result = this._defaultAfterCellEdit(grid, aceArgs);
}
if(result) {
currentCell._isEdit(false);
}
if(grid.options.showRowHeader) {
$((rowInfo.$rows[0]).cells[0]).children("div.wijmo-wijgrid-innercell").html(" ")// remove ui-icon-pencil
;
}
window.setTimeout(function () {
// using the setTimeout here to workaround IE issue.
if(!grid._destroyed) {
currentCell = grid.currentCell();
if(domCell = currentCell.tableCell()) {
$(domCell).attr("tabIndex", 0).focus()// ensure focus on current cell
;
} else {
$(grid._view().focusableElement()).focus()// to listen keypress\ keydown events
;
}
}
}, this._timeout);
}
}
return result;
};
cellEditorHelper.prototype._defaultBeforeCellEdit = // private
function (grid, args) {
var column = args.cell.column(), result = false, value, strValue, $container, $input, len, kbEvent, keyCodeEnum = wijmo.grid.getKeyCodeEnum(), inputType = // xxx
wijmo.grid.HTML5InputSupport.getDefaultInputType(grid._isMobileEnv(), column);
// xxx
if(column.dataIndex >= 0) {
value = args.cell.value();
result = true;
try {
$container = args.cell.container();
if(wijmo.grid.getDataType(column) === "boolean") {
$input = $container.children("input");
$input.focus();
if(args.event && args.event.type === "keypress") {
$input.one("keyup", function (e) {
if(e.which === keyCodeEnum.SPACE) {
e.preventDefault();
($input[0]).checked = !value;
}
});
}
} else {
$input = $("<input />").attr(// xxx
"type", inputType).addClass(// xxx
//.attr("type", "text")
"wijgridinput wijmo-wijinput " + grid.options.wijCSS.stateFocus).bind("keydown", grid, $.proxy(this._checkBoxOrInputKeyDown, this));
//the problem of inputing
$input.bind((($.support).selectstart ? "selectstart" : "mousedown"), function (event) {
event.stopPropagation();
});
if(args.event && args.event.type === "keypress" && args.event.which) {
$input.val(String.fromCharCode(args.event.which));
} else {
switch(wijmo.grid.getDataType(column)) {
case "currency":
case "number":
if(value !== null) {
$input.val(value)// ignore formatting
;
break;
}
case "datetime":
// xxx
if(wijmo.grid.HTML5InputSupport.isExtendSupportRequired(inputType)) {
$input.val(wijmo.grid.HTML5InputSupport.toStr(value, inputType));
break;
}
// xxx
// fall through
default:
$input.val(grid.toStr(column, value));
break;
}
}
$container.empty().append($input);
len = $input.val().length;
if(inputType === "text") {
// move caret to the end of the text
new wijmo.grid.domSelection($input[0]).setSelection({
start: len,
end: len
});
}
$input.focus();
setTimeout(function () {
// IE fix
$input.focus();
}, this._timeout * 2);
// issue seems to be fixed
// // FF issue: text does not track to the new position of the caret
// if ($.browser.mozilla && document.createEvent && $input[0].dispatchEvent) {
// kbEvent = document.createEvent("KeyboardEvent");
// kbEvent.initKeyEvent("keypress", false, true, null, false, false, false, false, 0, keyCodeEnum.SPACE);
// $input[0].dispatchEvent(kbEvent);
// kbEvent = document.createEvent("KeyboardEvent");
// kbEvent.initKeyEvent("keypress", false, true, null, false, false, false, false, keyCodeEnum.BACKSPACE, 0);
// $input[0].dispatchEvent(kbEvent);
// }
}
} catch (ex) {
alert(ex.message);
result = false;
}
}
return result;
};
cellEditorHelper.prototype._defaultAfterCellEdit = function (grid, args) {
var leafOpt = args.cell.column(), result = false, $container, cellValue, $input, rowInfo, view;
if(leafOpt.dataIndex >= 0) {
result = true;
view = grid._view();
try {
$container = args.cell.container();
cellValue = grid.toStr(leafOpt, args.cell.value());
rowInfo = view._getRowInfo(grid._rows().item(args.cell.rowIndex()));
if(wijmo.grid.getDataType(leafOpt) === "boolean") {
$input = $container.children("input");
if(cellValue === "true") {
$input.attr("checked", "checked");
} else {
$input.removeAttr("checked");
}
} else {
grid.cellFormatter.format($container, leafOpt, cellValue, rowInfo);
}
} catch (ex) {
alert("defaultAfterCellEdit: " + ex.message);
result = false;
}
}
return result;
};
cellEditorHelper.prototype._checkBoxOrInputKeyDown = function (args) {
var keyCodeEnum = wijmo.grid.getKeyCodeEnum();
if(args.which === keyCodeEnum.ENTER) {
// stop editing when Enter key is pressed
var grid = args.data;
if(grid) {
grid._endEditInternal(args);
return false;// prevent submit behaviour.
}
}
};
cellEditorHelper.prototype._getCellValue = function (grid, currentCell) {
var $input = currentCell.container().find(":input:first"), result = null;
if($input.length) {
result = ($input.attr("type") === "checkbox") ? ($input[0]).checked : $input.val();
}
return result;
};
cellEditorHelper.prototype._getHTMLInputElementType = function (currentCell) {
return currentCell.container().find(":input:first").attr("type");
};
return cellEditorHelper;
})();
grid.cellEditorHelper = cellEditorHelper;
// private *
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts" />
/// <reference path="wijgrid.ts" />
/// <reference path="misc.ts" />
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var cellFormatterHelper = (function () {
function cellFormatterHelper() { }
cellFormatterHelper._div = document.createElement("div");
cellFormatterHelper.prototype.format = function ($container, column, formattedValue, rowInfo) {
if(rowInfo.type & wijmo.grid.rowType.footer) {
if(column.aggregate && (column.aggregate !== "none")) {
formattedValue = wijmo.grid.stringFormat(column.footerText || "{0}", column._totalsValue || "");
} else {
formattedValue = column.footerText || column._footerTextDOM || "";
}
}
var useDefault = true, defaultFormatter = null, args = {
$container: $container,
column: column,
formattedValue: formattedValue,
row: rowInfo,
afterDefaultCallback: null
}, temp;
if($.isFunction(column.cellFormatter)) {
useDefault = !column.cellFormatter(args);
}
if(useDefault) {
switch(wijmo.grid.getDataType(column)) {
case "boolean":
defaultFormatter = this._boolFormatter;
break;
default:
defaultFormatter = this._textFormatter;
}
if(defaultFormatter) {
defaultFormatter.call(this, args);
if($.isFunction(temp = args.afterDefaultCallback)) {
// args.afterDefaultCallback(args); // compile error: value of type "any" is not callable
temp(args);
}
}
}
};
cellFormatterHelper.prototype._textFormatter = // * private
function (args) {
var domContainer;
switch(args.row.type) {
case wijmo.grid.rowType.filter:
this._defFormatFilterCell(args);
break;
default:
// args.$container.html(args.formattedValue || " "); // -- very slow in IE when table content is recreated more than once (after paging, sorting etc, especially in flat mode).
domContainer = args.$container[0];
// reset content
if(domContainer.firstChild) {
while(domContainer.firstChild) {
domContainer.removeChild(domContainer.firstChild);
}
}
wijmo.grid.cellFormatterHelper._div.innerHTML = args.formattedValue || " ";
while(wijmo.grid.cellFormatterHelper._div.firstChild) {
domContainer.appendChild(wijmo.grid.cellFormatterHelper._div.firstChild);
}
}
};
cellFormatterHelper.prototype._boolFormatter = function (args) {
var grid, allowEditing, disableStr = "disabled='disabled'", targetElement, currentCell, $rt = wijmo.grid.rowType, keyCodeEnum = wijmo.grid.getKeyCodeEnum();
switch(args.row.type) {
case $rt.data:
case $rt.data | $rt.dataAlt:
grid = args.column.owner;
allowEditing = grid.options.allowEditing && (args.column.readOnly !== true);
if(allowEditing) {
disableStr = "";
}
if(grid.parse(args.column, grid._dataViewWrapper.getValue(args.row.data, args.column.dataKey)) === true) {
args.$container.html("<input class='wijgridinput' type='checkbox' checked='checked' " + disableStr + " />");
} else {
args.$container.html("<input class='wijgridinput' type='checkbox' " + disableStr + " />");
}
if(allowEditing) {
args.$container.children("input").bind("mousedown", function (e) {
targetElement = args.$container.parent()[0];
currentCell = grid.currentCell();
if(currentCell.tableCell() !== targetElement) {
grid._onClick({
target: targetElement
});
}
if(!currentCell._isEdit()) {
grid.beginEdit();
}
}).bind("keydown", function (e) {
if(e.which === keyCodeEnum.ENTER) {
grid._endEditInternal(e);
return false;
}
});
}
break;
default:
this._textFormatter(args);
}
};
cellFormatterHelper.prototype._defFormatFilterCell = function (args) {
var grid = args.column.owner, wijCSS = grid.options.wijCSS;
args.$container.addClass(wijCSS.widget + " " + wijCSS.stateDefault);
if((args.column.dataIndex >= 0) && !args.column.isBand && args.column.showFilter) {
// args.$container.html("<div class=\"wijmo-wijgrid-filter " + wijCSS.cornerAll + "\"><input type=\"text\" class=\"wijmo-wijgrid-filter-input\" style=\"width:100%\" /><a class=\"wijmo-wijgrid-filter-trigger " + wijCSS.cornerRight + " " + wijCSS.stateDefault + "\" href=\"#\"><span class=\"" + wijCSS.icon + " " + wijCSS.iconArrowDown + "\"></span></a></div>");
args.$container.html("<table cellPadding=\"0\" cellSpacing=\"0\" class=\"wijmo-wijgrid-filter " + wijCSS.cornerAll + "\"><tr><td style=\"width:100%\"><input type=\"text\" class=\"wijmo-wijgrid-filter-input\" style=\"width:100%\" /></td><td class=\"wijmo-wijgrid-filter-trigger " + wijCSS.cornerRight + " " + wijCSS.stateDefault + "\"><span class=\"" + wijCSS.icon + " " + wijCSS.iconArrowDown + "\"></span></td></tr></table>");
} else {
args.$container.html(" ");
}
};
return cellFormatterHelper;
})();
grid.cellFormatterHelper = cellFormatterHelper;
// * private
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
/// <reference path="wijgrid.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var uiResizer = (function () {
function uiResizer(wijgrid) {
this.MIN_WIDTH = 5;
this._elements = [];
this._gap = 10;
this._step = 1;
this._inProgress = false;
this._hoveredField = null;
this._startLocation = null;
this._lastLocation = null;
this._proxy = null;
this._wijgrid = wijgrid;
this._evntFormat = "{0}." + this._wijgrid.widgetName + ".resizer";
}
uiResizer.prototype.addElement = function (c1basefield) {
if(c1basefield && c1basefield.element) {
c1basefield.element.bind(this._eventKey("mousemove"), $.proxy(this._onMouseMove, this)).bind(this._eventKey("mousedown"), $.proxy(this._onMouseDown, this)).bind(this._eventKey("mouseout"), $.proxy(this._onMouseOut, this));
this._elements.push(c1basefield);
}
};
uiResizer.prototype.dispose = function () {
var self = this;
$.each(this._elements, function (index, c1basefield) {
c1basefield.element.unbind(self._eventKey("mousemove"), self._onMouseMove).unbind(self._eventKey("mousedown"), self._onMouseDown).unbind(self._eventKey("mouseout"), self._onMouseOut);
});
this._detachDocEvents();
};
uiResizer.prototype.inProgress = function () {
return this._inProgress;
};
uiResizer.prototype._onMouseMove = function (e) {
if(!this._inProgress) {
var hoveredField = this._getFieldByPos({
x: e.pageX,
y: e.pageY
});
if(hoveredField && hoveredField._canSize() && this._wijgrid._canInteract()) {
hoveredField.element.css("cursor", "e-resize");
//hoveredField.element.find("> a").css("cursor", "e-resize");
this._hoveredField = hoveredField;
// prevent frozener from taking effect
e.stopPropagation();
} else {
this._onMouseOut(e);
}
}
};
uiResizer.prototype._onMouseOut = function (e) {
if(!this._inProgress) {
if(this._hoveredField) {
this._hoveredField.element.css("cursor", "");
//_hoveredField.element.find("> a").css("cursor", "");
this._hoveredField = null;
}
}
};
uiResizer.prototype._onMouseDown = function (e) {
this._hoveredField = this._getFieldByPos({
x: e.pageX,
y: e.pageY
});
if(this._hoveredField && (this._hoveredField)._canSize() && this._wijgrid._canInteract()) {
try {
this._hoveredField.element.css("cursor", "");
// _hoveredField.element.find("> a").css("cursor", "");
this._docCursor = document.body.style.cursor;
document.body.style.cursor = "e-resize";
this._startLocation = this._lastLocation = wijmo.grid.bounds(this._hoveredField.element);
this._proxy = $("<div class=\"wijmo-wijgrid-resizehandle " + this._wijgrid.options.wijCSS.stateHightlight + "\"> </div>");
var visibleAreaBounds = this._wijgrid._view().getVisibleAreaBounds();
this._proxy.css({
"left": e.pageX,
"top": this._startLocation.top,
"height": visibleAreaBounds.height + visibleAreaBounds.top - this._startLocation.top
});
$(document.body).append(this._proxy);
}finally {
this._attachDocEvents();
this._inProgress = true;
// prevent frozener from taking effect
e.stopPropagation();
}
}
};
uiResizer.prototype._onDocumentMouseMove = function (e) {
var deltaX = this._step * Math.round((e.pageX - this._lastLocation.left) / this._step);
this._lastLocation = {
left: this._lastLocation.left + deltaX,
top: e.pageY,
width: undefined,
height: undefined
};
this._proxy.css("left", this._lastLocation.left);
};
uiResizer.prototype._onDocumentMouseUp = function (e) {
try {
document.body.style.cursor = this._docCursor;
// destroy proxy object
this._proxy.remove();
if(this._startLocation !== this._lastLocation) {
this._wijgrid._fieldResized(this._hoveredField, this._startLocation.width, Math.max(this._lastLocation.left - this._startLocation.left, this.MIN_WIDTH));
}
}finally {
this._hoveredField = null;
this._proxy = null;
this._detachDocEvents();
this._inProgress = false;
}
};
uiResizer.prototype._onSelectStart = function (e) {
e.preventDefault();
};
uiResizer.prototype._attachDocEvents = function () {
if(!this._inProgress) {
$(document).bind(this._eventKey("mousemove"), $.proxy(this._onDocumentMouseMove, this)).bind(this._eventKey("mouseup"), $.proxy(this._onDocumentMouseUp, this));
if($.fn.disableSelection) {
$(document.body).disableSelection();
}
if("onselectstart" in document) {
// $.support.selectstart ?
$(document.body).bind("selectstart", this._onSelectStart);
}
}
};
uiResizer.prototype._detachDocEvents = function () {
if(this._inProgress) {
$(document).unbind(this._eventKey("mousemove"), this._onDocumentMouseMove).unbind(this._eventKey("mouseup"), this._onDocumentMouseUp);
if($.fn.enableSelection) {
$(document.body).enableSelection();
}
if("onselectstart" in document) {
// $.support.selectstart ?
$(document.body).unbind("selectstart", this._onSelectStart);
}
}
};
uiResizer.prototype._getFieldByPos = function (mouse) {
var i, len, c1basefield, bounds, res;
for(i = 0 , len = this._elements.length; i < len; i++) {
c1basefield = this._elements[i];
bounds = wijmo.grid.bounds(c1basefield.element);
res = wijmo.grid.isOver(mouse.y, mouse.x, bounds.top, bounds.left + bounds.width - this._gap, bounds.height, this._gap);
if(res) {
return c1basefield;
}
}
return null;
};
uiResizer.prototype._eventKey = function (eventType) {
return wijmo.grid.stringFormat(this._evntFormat, eventType);
};
return uiResizer;
})();
grid.uiResizer = uiResizer;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
/// <reference path="wijgrid.ts" />
/// <reference path="c1groupedfield.ts" />
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var uiDragndrop = (function () {
function uiDragndrop(wijgrid) {
this._scope_guid = "scope_" + wijmo.grid.getUID();
// to use inside the draggable.drag event.
this._dragEnd = false;
this._wijgrid = wijgrid;
this._wijCSS = this._wijgrid.options.wijCSS;
this._wrapHtml = "<div class=\"" + this._wijCSS.widget + " wijmo-wijgrid " + this._wijCSS.content + " " + this._wijCSS.cornerAll + "\">" + "<table class=\"wijmo-wijgrid-root wijmo-wijgrid-table\">" + "<tr class=\"wijmo-wijgrid-headerrow\">" + "</tr>" + "</table>" + "</div>";
}
uiDragndrop.prototype.attachGroupArea = function (element) {
var draggedWijField, self = this;
if(!($.ui).droppable || !($.ui).draggable) {
return;
}
element.droppable({
scope: this._scope_guid,
tolerance: "pointer",
greedy: true,
accept: function (draggable) {
if(self._wijgrid.options.allowColMoving) {
draggedWijField = self._getWijFieldInstance(draggable);
if(draggedWijField) {
// The rightmost column header in the the group area can't be dragged to the end of the group area again.
if((draggedWijField instanceof $.wijmo.c1groupedfield) && (draggedWijField.options.groupedIndex === self._wijgrid._groupedColumns().length - 1)) {
return false;
}
return !draggedWijField.options.isBand && (draggedWijField.options.groupedIndex === undefined || (draggedWijField instanceof $.wijmo.c1groupedfield));
}
}
return false;
},
drop: function (e, ui) {
if(!self._isInElement(e, ui.draggable) && (draggedWijField = self._getWijFieldInstance(ui.draggable))) {
self._dragEnd = true;
}
},
over: function (e, ui) {
var cnt = self._wijgrid._field("groupedWidgets").length;
self._dropTargetRedirected = (cnt > 0);
self._droppableWijField = (cnt > 0) ? self._wijgrid._field("groupedWidgets")[cnt - 1] : // use the rightmost header as a drop target
element// special case, the drop target is the group area itself
;
element.data("thisDroppableWijField", self._droppableWijField);
},
out: function (e, ui) {
if(self._droppableWijField === element.data("thisDroppableWijField")) {
self._droppableWijField = null;
}
//if (draggedWijField = _getWijFieldInstance(ui.draggable)) {
// _hideArrows();
//}
}
});
};
uiDragndrop.prototype.attach = function (wijField) {
var element, draggedWijField, self = this;
if(!($.ui).droppable || !($.ui).draggable) {
return;
}
if(!wijField || !(element = wijField.element)) {
return;
}
element.draggable({
helper: function (e) {
if(wijField instanceof $.wijmo.c1groupedfield) {
return element.clone().addClass("wijmo-wijgrid-dnd-helper");
} else {
return element.clone().wrap(self._wrapHtml).width(element.width()).height(element.height()).closest(".wijmo-wijgrid").addClass("wijmo-wijgrid-dnd-helper");
/*return element
.clone()
.width(element.width())
.height(element.height())
.addClass("wijmo-wijgrid-dnd-helper");*/
}
},
appendTo: "body",
scope: //cursor: "pointer",
self._scope_guid,
drag: function (e, ui) {
self._hideArrows();
if(self._droppableWijField && !self._isInElement(e, element)) {
// indicate insertion position
var $arrowsTarget = self._droppableWijField.element;
if(!$arrowsTarget) {
// _droppableWijField is the group area element
$arrowsTarget = (self._droppableWijField);
}
self._showArrows($arrowsTarget, self._getPosition(wijField, self._droppableWijField, e, ui));
}
},
start: function (e, ui) {
if(self._wijgrid._canInteract() && self._wijgrid.options.allowColMoving && !self._wijgrid._field("resizer").inProgress()) {
//return (wijField._canDrag() === true);
var column = wijField.options, travIdx = wijField.options.travIdx, dragInGroup = (wijField instanceof $.wijmo.c1groupedfield), dragSource = dragInGroup ? "groupArea" : "columns";
if(dragInGroup) {
column = wijmo.grid.search(self._wijgrid.columns(), function (test) {
return test.options.travIdx === travIdx;
});
column = (!column.found) ? // grouped column is invisible?
wijmo.grid.getColumnByTravIdx(self._wijgrid.options.columns, travIdx).found : column.found.options;
}
if(wijField._canDrag() && self._wijgrid._trigger("columnDragging", null, {
drag: column,
dragSource: dragSource
})) {
self._wijgrid._trigger("columnDragged", null, {
drag: column,
dragSource: dragSource
});
return true;
}
}
return false;
},
stop: function (e, ui) {
self._hideArrows();
try {
if(self._dragEnd) {
if(!self._droppableWijField.element) {
// _droppableWijField is the group area element
self._wijgrid._handleDragnDrop(wijField.options.travIdx, -1, "left", wijField instanceof $.wijmo.c1groupedfield, true);
} else {
self._wijgrid._handleDragnDrop(wijField.options.travIdx, self._droppableWijField.options.travIdx, self._getPosition(wijField, self._droppableWijField, e, ui), wijField instanceof $.wijmo.c1groupedfield, self._droppableWijField instanceof $.wijmo.c1groupedfield);
}
}
}finally {
self._droppableWijField = null;
self._dragEnd = false;
}
}
}).droppable(// ~draggable
{
hoverClass: self._wijCSS.stateHover,
scope: self._scope_guid,
tolerance: "pointer",
greedy: true,
accept: function (draggable) {
if(self._wijgrid.options.allowColMoving) {
if(element[0] !== draggable[0]) {
// different DOM elements
draggedWijField = self._getWijFieldInstance(draggable)// dragged column
;
if(draggedWijField) {
return draggedWijField._canDropTo(wijField);
}
}
}
return false;
},
drop: function (e, ui) {
if(draggedWijField = self._getWijFieldInstance(ui.draggable)) {
// As droppable.drop fires before draggable.stop, let draggable to finish action.
// Otherwise exception is thrown as during re-rendering element bound to draggable will be already deleted.
self._dragEnd = true;
// an alternative:
//window.setTimeout(function () {
//wijgrid._handleDragnDrop(draggedWijField, wijField, _getPosition(draggedWijField, wijField, e, ui));
//}, 100);
}
},
over: function (e, ui) {
self._dropTargetRedirected = false;
self._droppableWijField = wijField;
// to track when droppable.over event of other element fires before droppable.out of that element.
element.data("thisDroppableWijField", self._droppableWijField);
},
out: function (e, ui) {
if(self._droppableWijField === wijField.element.data("thisDroppableWijField")) {
self._droppableWijField = null;
}
//if (draggedWijField = _getWijFieldInstance(ui.draggable)) {
// _hideArrows();
//}
}
})// ~droppable
;
};
uiDragndrop.prototype.detach = function (wijField) {
var element;
if(wijField && (element = wijField.element)) {
if(element.data("ui-draggable")) {
element.draggable("destroy");
}
if(element.data("ui-droppable")) {
element.droppable("destroy");
}
}
};
uiDragndrop.prototype.dispose = function () {
if(this._$topArrow) {
this._$topArrow.remove();
this._$topArrow = null;
}
if(this._$bottomArrow) {
this._$bottomArrow.remove();
this._$bottomArrow = null;
}
};
uiDragndrop.prototype._getWijFieldInstance = // private
function (draggable) {
var widgetName = wijmo.grid.widgetName(draggable);
if(!widgetName) {
throw "widgetName is undedined";
}
return draggable.data(widgetName);
};
uiDragndrop.prototype._showArrows = // position: "left", "right", "center"
function (element, position) {
this._topArrow().show().position({
my: "center",
at: position + " top",
of: element,
collision: "none"
});
this._bottomArrow().show().position({
my: "center",
at: position + " bottom",
of: element,
collision: "none"
});
};
uiDragndrop.prototype._hideArrows = function () {
this._topArrow().hide();
this._bottomArrow().hide();
};
uiDragndrop.prototype._topArrow = function () {
if(!this._$topArrow) {
this._$topArrow = $("<div />").addClass("wijmo-wijgrid-dnd-arrow-top").append($("<span />").addClass(this._wijCSS.icon + " ui-icon-arrowthick-1-s")).hide().appendTo(document.body);
}
return this._$topArrow;
};
uiDragndrop.prototype._bottomArrow = function () {
if(!this._$bottomArrow) {
this._$bottomArrow = $("<div />").addClass("wijmo-wijgrid-dnd-arrow-bottom").append($("<span />").addClass(this._wijCSS.icon + " ui-icon-arrowthick-1-n")).hide().appendTo(document.body);
}
return this._$bottomArrow;
};
uiDragndrop.prototype._isInElement = function (e, element) {
var bounds = wijmo.grid.bounds(element, false);
return ((e.pageX > bounds.left && e.pageX < bounds.left + bounds.width) && (e.pageY > bounds.top && e.pageY < bounds.top + bounds.height));
};
uiDragndrop.prototype._getPosition = function (drag, drop, e, dragui) {
if(!drop.element) {
// drop is the group area element
return "left";
}
if(this._dropTargetRedirected) {
return "right";
}
var bounds = wijmo.grid.bounds(drop.element, false), sixth = bounds.width / 6, centerX = bounds.left + (bounds.width / 2), result = "right", distance;
if(e.pageX < centerX) {
result = "left";
}
if(drop instanceof $.wijmo.c1groupedfield) {
// drag is moved over a grouped column
if(drag instanceof $.wijmo.c1groupedfield) {
// drag is a grouped column too
distance = drop.options.groupedIndex - drag.options.groupedIndex;
if(Math.abs(distance) === 1) {
result = (distance < 0) ? "left" : "right";
}
}
return result;
}
// both drag and drop are non-grouped columns
distance = drop.options.linearIdx - drag.options.linearIdx;
if(drop.options.isBand && (drag.options.parentIdx !== drop.options.travIdx) && // drag is not an immediate child of drop
(Math.abs(e.pageX - centerX) < sixth)) {
return "center";
}
// drag and drop are contiguous items of the same level
if(drag.options.parentIdx === drop.options.parentIdx && Math.abs(distance) === 1) {
result = (distance < 0) ? "left" : "right";
}
return result;
};
return uiDragndrop;
})();
grid.uiDragndrop = uiDragndrop;
// ~private
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts" />
/// <reference path="wijgrid.ts" />
/// <reference path="misc.ts" />
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var cellStyleFormatterHelper = (function () {
function cellStyleFormatterHelper(wijgrid) {
if(!wijgrid) {
throw "invalid arguments";
}
this._wijgrid = wijgrid;
}
cellStyleFormatterHelper.prototype.format = function ($cell, cellIndex, column, rowInfo, state, cellAttr, cellStyle) {
var $rs = wijmo.grid.renderState, $rt = wijmo.grid.rowType, rowType = rowInfo.type, args, groupRowCellInfo = null;
if(cellIndex === 0 && this._wijgrid.options.showRowHeader) {
column = null;
}
if(rowType === $rt.groupHeader || rowType === $rt.groupFooter) {
column = null;
if(cellAttr && (groupRowCellInfo = cellAttr.groupInfo)) {
column = this._wijgrid._field("leaves")[groupRowCellInfo.leafIndex]// replace "column" with the one associated with the $cell's content
;
delete cellAttr.groupInfo;
}
}
args = {
$cell: $cell,
state: state,
row: rowInfo,
column: column,
_cellIndex: cellIndex,
_purpose: groupRowCellInfo ? groupRowCellInfo.purpose : undefined
};
if(state === $rs.rendering) {
this._renderingStateFormatter(args, cellAttr, cellStyle);
} else {
this._currentStateFormatter(args, state & $rs.current);
//hoveredStateFormatter(args, state & $rs.hovered);
this._selectedStateFormatter(args, state & $rs.selected);
}
if($.isFunction(this._wijgrid.options.cellStyleFormatter)) {
this._wijgrid.options.cellStyleFormatter(args);
}
};
cellStyleFormatterHelper.prototype._renderingStateFormatter = // private ---
function (args, cellAttr, cellStyles) {
var $rt = wijmo.grid.rowType, key, value, leaf = args.column, rowType = args.row.type;
switch(rowType) {
case $rt.header:
args.$cell.addClass("wijgridth");
break;
default:
args.$cell.addClass("wijgridtd");
}
if((rowType & $rt.data) && leaf && leaf.textAlignment) {
// set text alignment
switch(leaf.textAlignment.toLowerCase()) {
case "left":
args.$cell.addClass("wijalign-left");
break;
case "right":
args.$cell.addClass("wijalign-right");
break;
case "center":
args.$cell.addClass("wijalign-center");
break;
}
}
// copy attributes
if(cellAttr) {
for(key in cellAttr) {
if(cellAttr.hasOwnProperty(key)) {
value = cellAttr[key];
if((key === "colSpan" || key === "rowSpan") && !(value > 1)) {
continue;
}
if(key === "class") {
args.$cell.addClass(value);
} else {
args.$cell.attr(key, value);
}
}
}
}
// copy inline css
if(cellStyles) {
for(key in cellStyles) {
if(cellStyles.hasOwnProperty(key)) {
if(key === "paddingLeft") {
// groupIndent
args.$cell.children(".wijmo-wijgrid-innercell").css(key, cellStyles[key]);
continue;
}
args.$cell.css(key, cellStyles[key]);
}
}
}
if(args._cellIndex === 0 && this._wijgrid.options.showRowHeader) {
args.$cell.attr({
"role": "rowheader",
"scope": "row"
}).addClass(this._wijgrid.options.wijCSS.stateDefault + " " + this._wijgrid.options.wijCSS.content + " wijmo-wijgrid-rowheader");
} else {
switch(rowType) {
case ($rt.header):
args.$cell.attr({
"role": "columnheader",
"scope": "col"
});
break;
case ($rt.footer):
args.$cell.attr({
"role": "columnfooter",
"scope": "col"
});
break;
default:
args.$cell.attr("role", "gridcell");
}
}
//if ((rowType & $rt.data) === $rt.data) {
if(rowType & $rt.data) {
if(args._cellIndex >= 0 && leaf/* && leaf.dataParser*/ ) {
args.$cell.attr("headers", (window).escape(leaf.headerText));
if(leaf.readOnly) {
args.$cell.attr("aria-readonly", true);
}
if(leaf.dataIndex >= 0) {
args.$cell.addClass("wijdata-type-" + wijmo.grid.getDataType(leaf));
}
}
}
if(rowType === $rt.groupHeader || rowType === $rt.groupFooter) {
// append wijdata-type class only to the aggregate cells of the group row, not grouped cells.
if(leaf && args._purpose === wijmo.grid.groupRowCellPurpose.aggregateCell) {
args.$cell.addClass("wijdata-type-" + wijmo.grid.getDataType(leaf));
}
}
};
cellStyleFormatterHelper.prototype._currentStateFormatter = function (args, add) {
var $rt = wijmo.grid.rowType;
if(add) {
args.$cell.addClass(this._wijgrid.options.wijCSS.stateActive);
if(args.row.type === $rt.header) {
args.$cell.addClass("wijmo-wijgrid-current-headercell");
} else {
args.$cell.addClass("wijmo-wijgrid-current-cell");
}
} else {
args.$cell.removeClass(this._wijgrid.options.wijCSS.stateActive);
if(args.row.type === $rt.header) {
args.$cell.removeClass("wijmo-wijgrid-current-headercell");
} else {
args.$cell.removeClass("wijmo-wijgrid-current-cell");
}
}
};
cellStyleFormatterHelper.prototype._hoveredStateFormatter = function (args, add) {
if(add) {
} else {
}
};
cellStyleFormatterHelper.prototype._selectedStateFormatter = function (args, add) {
if(add) {
args.$cell.addClass(this._wijgrid.options.wijCSS.stateHightlight).attr("aria-selected", "true");
} else {
args.$cell.removeClass(this._wijgrid.options.wijCSS.stateHightlight).removeAttr("aria-selected");
}
};
return cellStyleFormatterHelper;
})();
grid.cellStyleFormatterHelper = cellStyleFormatterHelper;
// --- private
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts" />
/// <reference path="wijgrid.ts" />
/// <reference path="misc.ts" />
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var rowStyleFormatterHelper = (function () {
function rowStyleFormatterHelper(wijgrid) {
if(!wijgrid) {
throw "invalid arguments";
}
this._wijgrid = wijgrid;
}
rowStyleFormatterHelper.prototype.format = function (rowInfo, rowAttr, rowStyle) {
var $rs = wijmo.grid.renderState, $rt = wijmo.grid.rowType, state = rowInfo.state, args = rowInfo;
if(state === $rs.rendering) {
this._renderingStateFormatter(args, rowAttr, rowStyle);
} else {
this._currentStateFormatter(args, (state & $rs.current) !== 0);
this._hoveredStateFormatter(args, (state & $rs.hovered) !== 0);
this._selectedStateFormatter(args, (state & $rs.selected) !== 0);
}
if($.isFunction(this._wijgrid.options.rowStyleFormatter)) {
this._wijgrid.options.rowStyleFormatter(args);
}
};
rowStyleFormatterHelper.prototype._renderingStateFormatter = // * private
function (args, rowAttr, rowStyle) {
var className = "wijmo-wijgrid-row " + this._wijgrid.options.wijCSS.content, contentClass = "wijmo-wijgrid-row " + this._wijgrid.options.wijCSS.content, $rt = wijmo.grid.rowType, key;
args.$rows.attr("role", "row");
// copy attributes
if(rowAttr) {
for(key in rowAttr) {
if(rowAttr.hasOwnProperty(key)) {
if(key === "class") {
args.$rows.addClass(rowAttr[key]);
} else {
args.$rows.attr(key, rowAttr[key]);
if(args.$rows[0].style.height) {
args.$rows.each(function () {
$.data(this, "customHeight", this.style.height);
return true;
});
}
}
}
}
}
// copy inline css
if(rowStyle) {
for(key in rowStyle) {
if(rowStyle.hasOwnProperty(key)) {
args.$rows.css(key, rowStyle[key]);
}
}
}
switch(args.type & ~$rt.dataAlt) {
case // clear dataAlt modifier
($rt.header):
className = "wijmo-wijgrid-headerrow";
break;
case ($rt.data):
className = contentClass + " wijmo-wijgrid-datarow";
if(args.type & $rt.dataAlt) {
className += " wijmo-wijgrid-alternatingrow";
}
break;
case ($rt.emptyDataRow):
className = contentClass + " wijmo-wijgrid-emptydatarow";
break;
case ($rt.filter):
className = "wijmo-wijgrid-filterrow";
break;
case ($rt.groupHeader):
className = contentClass + " wijmo-wijgrid-groupheaderrow";
break;
case ($rt.groupFooter):
className = contentClass + " wijmo-wijgrid-groupfooterrow";
break;
case ($rt.footer):
className = "wijmo-wijgrid-footerrow " + this._wijgrid.options.wijCSS.stateHightlight;
break;
default:
throw wijmo.grid.stringFormat("unknown rowType: {0}", args.type);
}
args.$rows.addClass(className);
};
rowStyleFormatterHelper.prototype._currentStateFormatter = function (args, flag) {
if(this._wijgrid.options.showRowHeader) {
// make deal with the row header cell
if(flag) {
// add formatting
$((args.$rows[0]).cells[0]).addClass(this._wijgrid.options.wijCSS.stateActive + " wijmo-wijgrid-current-rowheadercell");
} else {
// remove formatting
$((args.$rows[0]).cells[0]).removeClass(this._wijgrid.options.wijCSS.stateActive + " wijmo-wijgrid-current-rowheadercell");
}
}
};
rowStyleFormatterHelper.prototype._hoveredStateFormatter = function (args, flag) {
if(flag) {
// add formatting
args.$rows.addClass(this._wijgrid.options.wijCSS.stateHover);
} else {
// remove formatting
args.$rows.removeClass(this._wijgrid.options.wijCSS.stateHover);
}
};
rowStyleFormatterHelper.prototype._selectedStateFormatter = function (args, flag) {
if(flag) {
// add formatting
} else {
// remove formatting
}
};
return rowStyleFormatterHelper;
})();
grid.rowStyleFormatterHelper = rowStyleFormatterHelper;
// private *
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var tally = (function () {
function tally() {
this._sum = 0;
this._sum2 = 0;
this._cntNumbers = 0;
this._cntStrings = 0;
this._cntDates = 0;
this._max = 0;
this._min = 0;
this._minDate = 0;
this._maxDate = 0;
}
tally.prototype.add = function (value) {
if(value === null || value === "") {
return;
}
var foo, typeOf = (value instanceof Date) ? "datetime" : typeof (value);
// * count strings *
foo = value.toString()// value = _parseValue(value);
;
if(this._cntStrings++ === 0) {
this._minString = this._maxString = foo;
}
if(foo < this._minString) {
this._minString = foo;
}
if(foo > this._maxString) {
this._maxString = foo;
}
// * count numbers *
if(typeOf === "number") {
if(this._cntNumbers++ === 0) {
this._min = this._max = value;
}
this._sum += value;
this._sum2 += value * value;
if(value < this._min) {
this._min = value;
}
if(value > this._max) {
this._max = value;
}
} else {
// * count dates *
if(typeOf === "datetime") {
foo = value.getTime();
if(this._cntDates++ === 0) {
this._minDate = this._maxDate = foo;
}
if(foo < this._minDate) {
this._minDate = foo;
}
if(foo > this._maxDate) {
this._maxDate = foo;
}
}
}
};
tally.prototype.getValueString = function (column) {
var wijgrid = column.owner;
if(this._cntNumbers && (column.dataType === "number" || column.dataType === "currency")) {
var value = this._getValue(column.aggregate);
return wijgrid.toStr(column, value);
}
// we only support max/min and count for dates
if(this._cntDates && (column.dataType === "datetime")) {
// we only support max/min and count for dates
switch(column.aggregate) {
case "max":
return wijgrid.toStr(column, new Date(this._maxDate));
case "min":
return wijgrid.toStr(column, new Date(this._minDate));
case "count":
return this._cntStrings + "";
}
}
// we only support max/min and count for strings
if(this._cntStrings) {
switch(column.aggregate) {
case "max":
return this._maxString;
case "min":
return this._minString;
case "count":
return this._cntStrings + "";
}
}
return "";
};
tally.prototype._getValue = function (aggregate) {
switch(aggregate) {
case "average":
return (this._cntNumbers === 0) ? 0 : this._sum / this._cntNumbers;
case "count":
return this._cntStrings;
case "max":
return this._max;
case "min":
return this._min;
case "sum":
return this._sum;
case "std":
if(this._cntNumbers <= 1) {
return 0;
}
return Math.sqrt(this._getValue("var"));
case "stdPop":
if(this._cntNumbers <= 1) {
return 0;
}
return Math.sqrt(this._getValue("varPop"));
case "var":
if(this._cntNumbers <= 1) {
return 0;
}
return this._getValue("varPop") * this._cntNumbers / (this._cntNumbers - 1);
case "vapPop":
if(this._cntNumbers <= 1) {
return 0;
}
var tmp = this._sum / this._cntNumbers;
return this._sum2 / this._cntNumbers - tmp * tmp;
}
return 0;
};
return tally;
})();
grid.tally = tally;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
/// <reference path="wijgrid.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var uiFrozener = (function () {
function uiFrozener(wijgrid) {
this._docEventsUID = "wijgridfrozener" + wijmo.grid.getUID();
this._docEventsAttached = false;
this._newStaticIndex = -1;
// depends on e.data value (staticRowIndex or staticColumnIndex)
this._staticColumnIndex = -1;
this._staticRowIndex = -1;
this._staticOffsetH = 0;
this._staticOffsetV = 0;
this._inProgress = false;
this._wijgrid = wijgrid;
this.refresh();
}
uiFrozener.prototype.inProgress = function () {
return this._inProgress;
};
uiFrozener.prototype.refresh = function () {
this.dispose();
this._$outerDiv = this._wijgrid.outerDiv.find(".wijmo-wijgrid-fixedview");
this._superPanel = (this._wijgrid._view())._getSuperPanel();
this._staticOffsetH = this._wijgrid._getStaticOffsetIndex(false);
this._staticOffsetV = this._wijgrid._getStaticOffsetIndex(true);
this._staticColumnIndex = this._wijgrid._getStaticIndex(false);
this._staticRowIndex = this._wijgrid._getStaticIndex(true);
this._visibleBounds = this._wijgrid._view().getVisibleAreaBounds();
var allFixedAreaBounds = wijmo.grid.bounds(this._$outerDiv.find(".wijmo-wijgrid-split-area-nw")), containerBounds = wijmo.grid.bounds(this._$outerDiv);
this._createVBar(this._visibleBounds, allFixedAreaBounds, containerBounds);
if(!this._wijgrid._serverSideVirtualScrolling()) {
this._createHBar(this._visibleBounds, allFixedAreaBounds, containerBounds);
}
};
uiFrozener.prototype.dispose = function () {
if(this._$hBar) {
this._$hBar.remove();
this._$hBar = null;
}
if(this._$vBar) {
this._$vBar.remove();
this._$vBar = null;
}
if(this._$proxy) {
this._$proxy.remove();
this._$proxy = null;
}
this._$outerDiv = null;
this._superPanel = null;
this._detachDocEvents();
};
uiFrozener.prototype._createVBar = function (visibleBounds, allFixedAreaBounds, containerBounds) {
var leftPos = allFixedAreaBounds.width + allFixedAreaBounds.left, self = this;
if(leftPos <= visibleBounds.left + visibleBounds.width) {
this._$vBar = $("<div><div></div></div>").addClass("wijmo-wijgrid-frozener-v").css({
left: leftPos - containerBounds.left,
top: allFixedAreaBounds.top - containerBounds.top,
height: visibleBounds.height + visibleBounds.top - allFixedAreaBounds.top
}).bind("mousedown", function (e) {
e.data = true// vertical bar
;
self._onBarMouseDown.apply(self, arguments);
}).appendTo(this._$outerDiv);
// content
this._$vBar.find("div").addClass(this._wijgrid.options.wijCSS.header).css({
width: 0,
height: "100%"
});
}
};
uiFrozener.prototype._createHBar = function (visibleBounds, allFixedAreaBounds, containerBounds) {
var topPos = allFixedAreaBounds.top + allFixedAreaBounds.height, self = this;
if(topPos <= visibleBounds.top + visibleBounds.height) {
this._$hBar = $("<div><div></div></div>").addClass("wijmo-wijgrid-frozener-h").css({
left: allFixedAreaBounds.left - containerBounds.left,
top: topPos - containerBounds.top,
width: visibleBounds.width + visibleBounds.left - allFixedAreaBounds.left
}).bind("mousedown", function (e) {
e.data = false// horizontal bar
;
self._onBarMouseDown.apply(self, arguments);
}).appendTo(this._$outerDiv);
// content
this._$hBar.find("div").addClass(this._wijgrid.options.wijCSS.header).css({
width: "100%",
height: 0
});
}
};
uiFrozener.prototype._onBarMouseDown = // e.data.vertical
function (e) {
if(this._wijgrid.options.disabled) {
return false;
}
this._visibleBounds = this._wijgrid._view().getVisibleAreaBounds();
this._newStaticIndex = e.data ? this._staticColumnIndex : this._staticRowIndex;
this._$proxy = $("<div class=\"wijmo-wijgrid-resizehandle " + this._wijgrid.options.wijCSS.header + "\"></div>").appendTo(document.body);
this._attachDocEvents(e.data);
this._inProgress = true;
// prevent selectionUI from taking effect
e.stopPropagation();
};
uiFrozener.prototype._onDocumentMouseMove = function (e) {
if(e.data && this._superPanel.options.hScroller.scrollValue) {
(this._superPanel).hScrollTo(0);
} else if(!e.data && this._superPanel.options.vScroller.scrollValue) {
(this._superPanel).vScrollTo(0);
}
this._showPosition(e);
};
uiFrozener.prototype._onDocumentMouseUp = function (e) {
try {
if(this._$proxy) {
this._$proxy.remove();
}
this._detachDocEvents();
if(e.data) {
// vertical bar
if(this._newStaticIndex !== this._staticColumnIndex) {
this._wijgrid.option("staticColumnIndex", this._newStaticIndex);
}
} else {
// horizontal bar
if(this._newStaticIndex !== this._staticRowIndex) {
this._wijgrid.option("staticRowIndex", this._newStaticIndex);
}
}
}finally {
this._$proxy = null;
this._inProgress = false;
}
};
uiFrozener.prototype._attachDocEvents = function (verticalBarTouched) {
if(!this._docEventsAttached) {
try {
if($.fn.disableSelection) {
$(document.body).disableSelection();
}
this._wijgrid._view().toggleDOMSelection(false);
$(document).bind(this._docEventKey("mousemove"), verticalBarTouched, $.proxy(this._onDocumentMouseMove, this)).bind(this._docEventKey("mouseup"), verticalBarTouched, $.proxy(this._onDocumentMouseUp, this));
}finally {
this._docEventsAttached = true;
}
}
};
uiFrozener.prototype._detachDocEvents = function () {
if(this._docEventsAttached) {
try {
if($.fn.enableSelection) {
$(document.body).enableSelection();
}
this._wijgrid._view().toggleDOMSelection(true);
$(document).unbind("." + this._docEventsUID);
}finally {
this._docEventsAttached = false;
}
}
};
uiFrozener.prototype._docEventKey = function (eventName) {
return wijmo.grid.stringFormat("{0}.{1}", eventName, this._docEventsUID);
};
uiFrozener.prototype._showPosition = function (e) {
var element, elementBounds, centerXOrY, currentIdx, prevIdx, leftOrTop, position, barBounds;
if(e.data) {
// vertical
barBounds = wijmo.grid.bounds(this._$vBar);
if(Math.abs(e.pageX - (barBounds.left + barBounds.width / 2)) < barBounds.width) {
this._$proxy.hide();
return;
}
if((element = this._getFieldByPos({
x: e.pageX,
y: e.pageY
}))) {
// get column widget
elementBounds = wijmo.grid.bounds(element.element);
centerXOrY = elementBounds.left + elementBounds.width / 2;
currentIdx = element.options.visLeavesIdx - this._staticOffsetV;
prevIdx = Math.max(currentIdx - 1, -1);
leftOrTop = e.pageX < centerXOrY ? (prevIdx !== this._staticColumnIndex) : (currentIdx === this._staticColumnIndex);
position = leftOrTop ? elementBounds.left : elementBounds.left + elementBounds.width;
if(!wijmo.grid.isOverAxis(position, this._visibleBounds.left - 1, this._visibleBounds.width + 2)) {
return;
}
this._newStaticIndex = leftOrTop ? prevIdx : currentIdx;
this._$proxy.show().css({
left: position,
top: elementBounds.top,
width: 3,
height: this._visibleBounds.height + this._visibleBounds.top - elementBounds.top
});
}
} else {
// horizontal
barBounds = wijmo.grid.bounds(this._$hBar);
if(Math.abs(e.pageY - (barBounds.top + barBounds.height / 2)) < barBounds.height) {
this._$proxy.hide();
return;
}
if((element = this._getRowByPos({
x: e.pageX,
y: e.pageY
}))) {
elementBounds = wijmo.grid.bounds(element);
centerXOrY = elementBounds.top + elementBounds.height / 2;
currentIdx = this._wijgrid._view().getAbsoluteRowIndex(element) - this._staticOffsetH;
prevIdx = Math.max(currentIdx - 1, -1);
leftOrTop = e.pageY < centerXOrY ? (prevIdx !== this._staticRowIndex) : (currentIdx === this._staticRowIndex);
position = leftOrTop ? elementBounds.top : elementBounds.top + elementBounds.height;
if(!wijmo.grid.isOverAxis(position, this._visibleBounds.top - 1, this._visibleBounds.height + 2)) {
return;
}
this._newStaticIndex = leftOrTop ? prevIdx : currentIdx;
this._$proxy.show().css({
left: elementBounds.left,
top: position,
width: this._visibleBounds.width + this._visibleBounds.left - elementBounds.left,
height: 3
});
}
}
};
uiFrozener.prototype._getFieldByPos = function (pos) {
var columns = this._wijgrid.columns(), i, len, colWidget, o, bounds;
for(i = 0 , len = columns.length; i < len; i++) {
colWidget = columns[i];
o = colWidget.options;
if(o.isLeaf) {
bounds = wijmo.grid.bounds(colWidget.element);
if(wijmo.grid.isOverAxis(pos.x, bounds.left, bounds.width)) {
return colWidget;
}
}
}
return null;
};
uiFrozener.prototype._getRowByPos = function (pos) {
var rows = this._wijgrid._rows(), i, len, row, bounds;
for(i = 0 , len = rows.length(); i < len; i++) {
row = rows.item(i)[0];
bounds = wijmo.grid.bounds($(row));
if(wijmo.grid.isOverAxis(pos.y, bounds.top, bounds.height)) {
return row;
}
}
return null;
};
return uiFrozener;
})();
grid.uiFrozener = uiFrozener;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
/// <reference path="bands_traversing.ts"/>
/// <reference path="misc.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var columnsGenerator = (function () {
function columnsGenerator() { }
columnsGenerator.generate = function generate(mode, fieldsInfo, columns) {
switch(mode) {
case "append":
columnsGenerator._processAppendMode(fieldsInfo, columns);
break;
case "merge":
columnsGenerator._processMergeMode(fieldsInfo, columns);
break;
case "none":
break;
default:
throw wijmo.grid.stringFormat("Unsupported value: \"{0}\"", mode);
}
};
columnsGenerator._processAppendMode = function _processAppendMode(fieldsInfo, columns) {
var autoColumns = {
};
wijmo.grid.traverse(columns, function (column) {
if(column.dynamic && wijmo.grid.validDataKey(column.dataKey)) {
autoColumns[column.dataKey] = true;
}
});
$.each(fieldsInfo, function (key, fieldInfo) {
if(("name" in fieldInfo) && !autoColumns[fieldInfo.name]) {
var leaf = columnsGenerator._createAutoField(fieldInfo);
columns.push(leaf);
}
});
};
columnsGenerator._processMergeMode = function _processMergeMode(fieldsInfo, columns) {
var columnsHasNoDataKey = [], i;
wijmo.grid.traverse(columns, function (column) {
if(column.isLeaf && !column.isBand) {
var dataKey = column.dataKey;
if(wijmo.grid.validDataKey(dataKey)) {
if(fieldsInfo[dataKey] !== undefined) {
delete fieldsInfo[dataKey];
}
} else {
if(dataKey !== null) {
// don't linkup with any data field if dataKey is null
columnsHasNoDataKey.push(column);
}
}
}
});
if(columnsHasNoDataKey.length) {
i = 0;
$.each(fieldsInfo, function (key, info) {
var leaf = columnsHasNoDataKey[i++];
if(leaf) {
leaf.dataKey = info.name;
delete fieldsInfo[key];
}
});
}
$.each(fieldsInfo, function (key, info) {
var leaf = columnsGenerator._createAutoField(info);
columns.push(leaf);
});
};
columnsGenerator._createAutoField = function _createAutoField(fieldInfo) {
return wijmo.grid.createDynamicField({
dataKey: fieldInfo.name
});
};
return columnsGenerator;
})();
grid.columnsGenerator = columnsGenerator;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="interfaces.ts"/>
(function (grid) {
"use strict";
var $ = jQuery;
/** @ignore */
var uiVirtualScroller = (function () {
function uiVirtualScroller(wijgrid, $content, fixedAreaHeight) {
this._timer = 0;
this._timeout = 50;
// msec
this._ignoreScrollEvents = false;
this._wijgrid = wijgrid;
this._fixedAreaHeight = fixedAreaHeight;
this._view = this._wijgrid._view();
this._N = this._wijgrid._totalRowsCount();
var rowH = 20, height = // empirically
this._wijgrid.outerDiv.height() + this._N * rowH;
// total height
$content.height(height - fixedAreaHeight - (this._N > 0 ? rowH : 0))// height of the scrollable content
;
this._view._splitAreas.sw.height(height);
}
uiVirtualScroller.prototype.attach = function ($scroller) {
this._$scroller = $scroller;
this._panelInst = $scroller.data("wijmo-wijsuperpanel");
var tmp, $view = $scroller.find(".wijmo-wijsuperpanel-contentwrapper:first"), contentHeight = (this._panelInst).getContentElement().height()/*$content.height()*/ , totalHeight = this._fixedAreaHeight + contentHeight, viewHeight = $view.innerHeight(), smallChange = (101 / (this._N - 1)) * ((totalHeight - viewHeight) / totalHeight);
// set scrollSmallChange value
tmp = this._panelInst.options.vScroller;
tmp.scrollSmallChange = smallChange;
this._panelInst.option("vScroller", tmp);
$scroller.bind("wijsuperpanelscrolled.wijgrid", $.proxy(this._onSuperpanelScrolled, this));
$scroller.bind("wijsuperpanelscrolling.wijgrid", $.proxy(this._onSuperpanelScrolling, this));
$scroller.bind("wijsuperpanelscrolled.wijgrid", $.proxy(this._onSuperpanelPostScrolled, this))// manipulate with the _ignoreScrollEvents property.
;
};
uiVirtualScroller.prototype.dispose = function () {
this._$scroller.unbind(".wijgrid");
this._clearTimer();
};
uiVirtualScroller.prototype._clearTimer = function () {
window.clearTimeout(this._timer);
this._timer = 0;
};
uiVirtualScroller.prototype._onSuperpanelScrolling = function (e, args) {
if(this._ignoreScrollEvents || (args.dir !== "v")) {
return;
}
if(this._timer === -1) {
return false;// cancel while scrolling will not be handled.
}
};
uiVirtualScroller.prototype._onSuperpanelScrolled = function (e, args) {
var self = this;
if(this._ignoreScrollEvents || (args.dir !== "v")) {
return;
}
if(this._timer > 0) {
this._clearTimer();
}
if(this._timer !== -1) {
this._timer = window.setTimeout(function () {
self._timer = -1// lock
;
var scrollToIndex = Math.round(args.newValue / self._panelInst.options.vScroller.scrollSmallChange), oldScrollIndex = self._view._bounds.start;
if(scrollToIndex < 0) {
scrollToIndex = 0;
}
if(scrollToIndex >= self._N) {
scrollToIndex = self._N - 1;
}
if(scrollToIndex !== oldScrollIndex) {
self._wijgrid._handleVirtualScrolling(scrollToIndex, $.proxy(self._scrollingCompleted, self));
} else {
self._log();
self._clearTimer()// unlock
;
}
}, this._timeout);
}
};
uiVirtualScroller.prototype._scrollingCompleted = function (scrollIndex) {
this._wijgrid._trackScrollingIndex(scrollIndex);
this._log();
this._clearTimer()// unlock
;
};
uiVirtualScroller.prototype._onSuperpanelPostScrolled = function () {
if($.isFunction(this._postScrolled)) {
this._postScrolled.apply(this, arguments);
}
};
uiVirtualScroller.prototype._log = function () {
/*if (window.console) {
var bounds = wijgrid._view()._bounds;
window.console.log("bounds: [" + bounds.start + ", " + bounds.end + "], scrollTo: " + bounds.start);
}*/
};
return uiVirtualScroller;
})();
grid.uiVirtualScroller = uiVirtualScroller;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="../../../data/src/core.ts"/>
/// <reference path="../../../data/src/util.ts"/>
/// <reference path="../../../data/src/errors.ts"/>
/// <reference path="../../../external/declarations/globalize.d.ts"/>
(function (data) {
var $ = jQuery, glob = Globalize;
function convert(val, fromType, toType, options) {
var origValue = val;
options = $.extend({
nullString: "",
format: ""
}, options);
function getParser(type) {
options.parser = options.parser || data.defaultParsers[type];
if(!options.parser && val != null) {
data.errors.noParser(type);
}
return options.parser;
}
fromType = fromType || val != null && typeof val;
toType = toType || fromType;
if(!toType) {
return val;
}
if(toType == "string") {
getParser(fromType);
if(!options.parser) {
return val;
}
return options.parser.toStr(val, options.culture, options.format, options.nullString, true);
}
getParser(toType);
if(!options.parser) {
return val;
}
val = options.parser.parse(val, options.culture, options.format, options.nullString, true);
if(isNaN(val) && val != null && data.util.isNumeric(val)) {
if(options.ignoreError) {
return origValue;
}
data.errors.cantConvert(toType, origValue);
}
return val;
}
data.convert = convert;
data.defaultParsers = {
string: {
parse: // string -> string
function (value, culture, format, nullString, convertEmptyStringToNull) {
switch(value) {
case null:
return null;
case nullString:
if(convertEmptyStringToNull) {
return null;
}
case undefined:
case " ":
return "";
default:
return "" + value;
}
},
toStr: // string -> string
function (value, culture, format, nullString, convertEmptyStringToNull) {
if(value === null && convertEmptyStringToNull) {
return nullString;
}
return "" + value;
}
},
number: {
parse: // string/number -> number
function (value, culture, format, nullString, convertEmptyStringToNull) {
var type = typeof (value);
if(type === "number") {
return isNaN(value) ? NaN : value;
}
if((!value && value !== 0) || (value === " ") || (value === nullString && convertEmptyStringToNull)) {
return null;
}
return glob.parseFloat(value, 10, culture.name);
},
toStr: // number -> string
function (value, culture, format, nullString, convertEmptyStringToNull) {
if(value === null && convertEmptyStringToNull) {
return nullString;
}
return glob.format(value, format || "n", culture.name);
}
},
currency: {
parse: // string/number -> number
function (value, culture, format, nullString, convertEmptyStringToNull) {
var type = typeof (value);
if(type === "number") {
return isNaN(value) ? NaN : value;
}
if((!value && value !== 0) || (value === " ") || (value === nullString && convertEmptyStringToNull)) {
return null;
}
if(type === "string") {
value = value.replace(culture.numberFormat.currency.symbol, "");
}
return glob.parseFloat(value, 10, culture.name);
},
toStr: // number -> string (currency)
function (value, culture, format, nullString, convertEmptyStringToNull) {
if(value === null && convertEmptyStringToNull) {
return nullString;
}
return glob.format(value, format || "c", culture.name);
}
},
datetime: {
parse: // string/datetime -> datetime
function (value, culture, format, nullString, convertEmptyStringToNull) {
var match;
if(value instanceof Date) {
return value;
}
if(!value || (value === " ") || (value === nullString && convertEmptyStringToNull)) {
return null;
}
match = /^\/Date\((\d+)\)\/$/.exec(value);
if(match) {
return new Date(parseInt(match[1], 10));
}
var date = glob.parseDate(value, format, culture.name);
if(date == null || isNaN(date)) {
date = Date.parse(value);
date = isNaN(date) ? NaN : new Date(date);
}
return date;
},
toStr: // datetime -> string
function (value, culture, format, nullString, convertEmptyStringToNull) {
if(value === null && convertEmptyStringToNull) {
return nullString;
}
return glob.format(value, format || "d", culture.name);
}
},
boolean: {
parse: // string/bool -> bool
function (value, culture, format, nullString, convertEmptyStringToNull) {
var valType = typeof (value);
if(valType === "number") {
return value != 0;
}
if(valType === "boolean") {
return value;
}
if(valType === "string") {
value = $.trim(value);
}
if(!value || (value === " ") || (value === nullString && convertEmptyStringToNull)) {
return null;
}
switch(value.toLowerCase()) {
case "true":
return true;
case "false":
return false;
}
return NaN;
},
toStr: // bool -> string
function (value, culture, format, nullString, convertEmptyStringToNull) {
if(value === null && convertEmptyStringToNull) {
return nullString;
}
return (value) ? "true" : "false";
}
}
};
function checkGlob(func) {
return function () {
if(!glob) {
data.util.logError(data.errors.noGlobalize.create().message);
}
return func.apply(this, arguments);
};
}
$.each(data.defaultParsers, function (_, parser) {
parser.parse = parser.parse && checkGlob(parser.parse);
parser.toStr = parser.toStr && checkGlob(parser.toStr);
});
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
(function (data) {
(function (filtering) {
/// <reference path="../../../data/src/arrayDataView.ts"/>
/** Provides compilation of the Extended Filtering Format
*
* @remarks
* Some examples of extended filter format:
* [{ property: "name", value: "John" }, { property: "age", operator: "<", value: 10 }]
* ["or", { property: "name", value: "John" }, { property: "age", operator: "<", value: 10 }]
* ["and",
* ["or", { property: "name", value: "John" }, { property: "name", operator: "BeginsWith", value: "A" } ],
* { property: "age", operator: "<", value: 10 }]
* ]
*/
(function (extended) {
extended.Connective = {
AND: "and",
OR: "or"
};
function normalizeFilter(filter) {
function norm(filter) {
var result = [];
if(filter.length === 0) {
return result;
}
var connective = extended.Connective.AND;
data.util.each(filter, function (i, cond) {
if(i == 0 && data.util.isString(cond)) {
var lowerConnective = cond.toLowerCase();
if(lowerConnective == extended.Connective.AND || lowerConnective == extended.Connective.OR) {
connective = lowerConnective;
return;
}
}
if($.isArray(cond)) {
cond = norm(cond);
if(!cond) {
return;
}
if(cond[0] === connective || cond.length == 2) {
cond.shift();
result = result.concat(cond);
return;
}
} else {
var predicate = filtering.normalizeCondition(cond);
if(!predicate) {
return;
}
predicate.property = cond.property;
cond = predicate;
}
result.push(cond);
});
if(result.length == 0) {
return null;
} else {
result.unshift(connective);
return result;
}
}
return norm(filter);
}
function compilAsExtended(extendedFilter) {
if(!$.isArray(extendedFilter)) {
return null;
}
var result = {
original: extendedFilter,
normalized: normalizeFilter(extendedFilter),
func: null
};
if(result.normalized == null) {
result.func = function (x) {
return true;
};
} else {
result.func = function (x) {
function check(filter) {
var isAnd = filter[0] === extended.Connective.AND, checker = isAnd ? data.util.every : data.util.some;
return checker(filter, function (cond, i) {
if(i === 0) {
return isAnd;
}
if($.isArray(cond)) {
return check(cond);
} else {
var value = data.util.getProperty(x, cond.property);
return cond.op.apply(value, cond.value);
}
});
}
return check(result.normalized);
};
}
return result;
}
function compile(filter) {
return compilAsExtended(filter) || data.filtering.compile(filter);
}
extended.compile = compile;
})(filtering.extended || (filtering.extended = {}));
var extended = filtering.extended;
})(data.filtering || (data.filtering = {}));
var filtering = data.filtering;
})(wijmo.data || (wijmo.data = {}));
var data = wijmo.data;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
/// <reference path="../../../data/src/arrayDataView.ts"/>
/// <reference path="wijmo.data.filtering.extended.ts"/>
(function (grid) {
var $ = jQuery;
var wijdata = wijmo.data;
var filterExt = wijdata.filtering.extended;
// in fact implements IDataView in run-time, but not at compile-time
var GridDataView = (function () {
function GridDataView(real) {
this.real = real;
this._updatingFilter = false;
this._overrideFilter();
this._makeMemberProxies();
}
GridDataView.prototype._overrideFilter = function () {
var _this = this;
this.filter = wijdata.observable(this.real.filter());
this.filter.subscribe(function (newValue) {
if(_this.real.filter() !== newValue && !_this._updatingFilter) {
_this.refresh({
filter: newValue
});
}
});
this.real.filter.subscribe(function (newValue) {
// Do not update this.filter if it is the same filter we've assigned to the underlying dataView.
// Otherwise we may end up replacing a property filter with a function
if(newValue !== _this._lastSetFilter) {
_this.filter(newValue);
}
});
};
GridDataView.prototype.refresh = function (shape, local) {
if (typeof local === "undefined") { local = false; }
shape = $.extend({
}, shape);
var origFilter = shape.filter;
shape.filter = this._coerceFilter(shape.filter);
this._lastSetFilter = shape.filter;
this._updatingFilter = true;
try {
if($.isFunction(shape.filter) && !$.isFunction(origFilter)) {
// it became a function. It means that the filter was complex
this.filter(origFilter);
} else {
this.filter(shape.filter);
}
}finally {
this._updatingFilter = false;
}
return this.real.refresh(shape, local);
};
GridDataView.prototype._makeMemberProxies = function () {
var _this = this;
// make proxy methods for those that are not defined manually
wijdata.util.each(this.real, function (key, value) {
if(!$.isFunction(value) || _this[key] || key.charAt(0) === "_") {
return;
}
_this[key] = $.isFunction(value.subscribe) ? value : function () {
return value.apply(_this.real, arguments);
};
});
};
GridDataView.create = function create(dataView) {
return new GridDataView(dataView);
};
GridDataView.prototype._convertComplexPropertyFilterToExtendedFilterFormat = function (filter) {
var result = [];
$.each(filter, function (prop, condList) {
if(!$.isArray(condList)) {
condList = [
condList
];
} else {
var connective = wijdata.util.isString(condList[0]) && condList[0].toLowerCase();
if(connective === filterExt.Connective.AND || connective === filterExt.Connective.OR) {
result.push(condList);
return;
}
}
var normCondList = [];
$.each(condList, function (_, cond) {
var normCond = wijdata.filtering.normalizeCondition(cond);
if(normCond) {
normCond.property = prop;
normCondList.push(normCond);
}
});
if(normCondList.length > 0) {
result.push(normCondList);
}
});
return result.length > 0 ? result : null;
};
GridDataView.prototype._coerceFilter = function (filter) {
if($.isArray(filter)) {
// assume extended
return filterExt.compile(filter).func;
} else if(!$.isPlainObject(filter)) {
return filter;
}
filter = $.extend(true, {
}, filter);
var simpleFilter = {
};
$.each(filter, function (prop, cond) {
if(!$.isArray(cond)) {
cond = [
cond
];
}
if(simpleFilter) {
var possibleConnective = wijdata.util.isString(cond[0]) && cond[0].toLowerCase();
if(cond.length == 1 || cond.length == 2 && (possibleConnective === "and" || possibleConnective === "or")) {
simpleFilter[prop] = cond[cond.length - 1];
return;
}
}
filter[prop] = cond;
simpleFilter = null;
});
if(simpleFilter) {
return simpleFilter;
}
var extendedFilter = this._convertComplexPropertyFilterToExtendedFilterFormat(filter);
return filterExt.compile(extendedFilter).func;
};
GridDataView.prototype._unsafeReplace = function (index, newItem) {
(this.real).sourceArray[index] = newItem;
(this.real).local[index] = newItem;
};
GridDataView.prototype._unsafeSplice = function (index, count, item) {
if(arguments.length === 2) {
(this.real).sourceArray.splice(index, count);
(this.real).local.splice(index, count);
} else {
(this.real).sourceArray.splice(index, count, item);
(this.real).local.splice(index, count, item);
}
};
GridDataView.prototype._unsafePush = function (item) {
(this.real).sourceArray.push(item);
(this.real).local.push(item);
};
return GridDataView;
})();
grid.GridDataView = GridDataView;
})(wijmo.grid || (wijmo.grid = {}));
var grid = wijmo.grid;
})(wijmo || (wijmo = {}));
;
/// <reference path="../External/declarations/jquery.d.ts"/>
/// <reference path="../External/declarations/raphael.d.ts"/>
/// <reference path="../External/declarations/globalize.d.ts"/>
var wijmo;
(function (wijmo) {
var $ = jQuery;
var ExtendJQuery = (function () {
function ExtendJQuery() { }
ExtendJQuery.prototype.round = function (val, digits) {
if(!val) {
return 0;
}
//var value = Globalize.format(val, "N" + digits);
//return Globalize.parseFloat(value);
return Globalize.parseFloat(val.toFixed(digits), 10, Globalize.culture("en"));
};
ExtendJQuery.prototype.toOADate = function (time) {
var day = 24 * 60 * 60 * 1000, oaDate = time - new Date(1900, 0, 1) + 2 * day;
return oaDate;
};
ExtendJQuery.prototype.fromOADate = function (oaDate) {
var day = 24 * 60 * 60 * 1000, time = new Date(oaDate - 2 * day + new Date(1900, 0, 1).getTime());
return time;
};
ExtendJQuery.prototype.arrayClone = function (arr) {
var result = [];
$.each(arr, function (i, n) {
result.push($.extend(true, {
}, n));
});
return result;
};
return ExtendJQuery;
})();
var WijRaphael = (function () {
function WijRaphael() { }
WijRaphael.prototype.isSVGElem = function (node) {
var svgNS = "http://www.w3.org/2000/svg";
return (node.nodeType === 1 && node.namespaceURI === svgNS);
};
WijRaphael.prototype.addClass = function (ele, classNames) {
classNames = classNames || '';
var self = this;
$.each(ele, function () {
if(self.isSVGElem(this)) {
var node = this;
$.each(classNames.split(/\s+/), function (i, className) {
var classes = (node.className ? node.className.baseVal : node.getAttribute('class'));
if($.inArray(className, classes.split(/\s+/)) === -1) {
classes += (classes ? ' ' : '') + className;
if(node.className) {
node.className.baseVal = classes;
} else {
node.setAttribute('class', classes);
}
}
});
} else {
$(this).addClass(classNames);
}
});
};
WijRaphael.prototype.clearRaphaelCache = // to do this methods
function () {
// the raphael.d.ts not support.
//Raphael.path2curve.cache = null;
//Raphael.path2curve.count = null;
//Raphael.parseTransformString.cache = null;
//Raphael.parseTransformString.count = null;
//Raphael.parsePathString.cache = null;
//Raphael.parsePathString.count = null;
//Raphael._pathToAbsolute.cache = null;
//Raphael._pathToAbsolute.count = null;
};
WijRaphael.prototype.getPositionByAngle = function (cx, cy, r, angle) {
var point = {
x: 0,
y: 0
}, rad = Raphael.rad(angle);
point.x = cx + r * Math.cos(-1 * rad);
point.y = cy + r * Math.sin(-1 * rad);
return point;
};
WijRaphael.prototype.hasClass = function (ele, className) {
if(!className || className.length === 0) {
return false;
}
if(this.isSVGElem(ele)) {
var cName = ele.className ? ele.className.baseVal : ele.getAttribute('class'), hasClass = false;
$.each(cName.split(/\s+/), function (i, c) {
if(c === className) {
hasClass = true;
return false;
}
});
return hasClass;
//return !!cName.match(new RegExp(className));
} else {
return $(ele).hasClass(className);
}
};
WijRaphael.prototype.sector = function (cx, cy, r, startAngle, endAngle) {
var start = this.getPositionByAngle(cx, cy, r, startAngle), end = this.getPositionByAngle(cx, cy, r, endAngle);
return [
"M",
cx,
cy,
"L",
start.x,
start.y,
"A",
r,
r,
0,
+(endAngle - startAngle > 180),
0,
end.x,
end.y,
"z"
];
};
return WijRaphael;
})();
$.extend(ExtendJQuery.prototype);
$.extend({
wijraphael: WijRaphael.prototype
});
var whitespace = "[\\x20\\t\\r\\n\\f]";
var jqueryFilterCLASS = $.expr.filter.CLASS;
var compareVersion = function (version, versionToCompare) {
var arrVer = version.split("."), arrVerTC = versionToCompare.split("."), len = Math.max(arrVer.length, arrVerTC.length), result = 0, i, v1, v2;
for(i = 0; i < len; i++) {
v1 = arrVer[i] ? parseInt(arrVer[i]) : 0;
v2 = arrVerTC[i] ? parseInt(arrVerTC[i]) : 0;
if(v1 > v2) {
result = 1;
break;
} else if(v1 < v2) {
result = -1;
break;
}
}
return result;
};
$.expr.filter.CLASS = function (elem, match) {
if(compareVersion($.fn.jquery, "1.8") < 0) {
var className = (!($.wijraphael && $.wijraphael.isSVGElem(elem)) ? elem.className : (elem.className ? elem.className.baseVal : elem.getAttribute('class')));
return (' ' + className + ' ').indexOf(match) > -1;
} else {
//return jqueryFilterCLASS(elem);
var pattern = new RegExp("(^|" + whitespace + ")" + elem + "(" + whitespace + "|$)");
return function (ele) {
var className = (!($.wijraphael && $.wijraphael.isSVGElem(ele)) ? ele.className : (ele.className ? ele.className.baseVal : ele.getAttribute('class')));
return pattern.test(className);
};
}
};
if(compareVersion($.fn.jquery, "1.8") < 0) {
$.expr.preFilter.CLASS = function (match, curLoop, inplace, result, not, isXML) {
var i = 0, elem = null, className = null;
match = ' ' + match[1].replace(/\\/g, '') + ' ';
if(isXML) {
return match;
}
for(i = 0 , elem = {
}; elem; i++) {
elem = curLoop[i];
if(!elem) {
try {
elem = curLoop.item(i);
} catch (e) {
}
}
if(elem) {
className = (!($.wijraphael && $.wijraphael.isSVGElem(elem)) ? elem.className : (elem.className ? elem.className.baseVal : '') || elem.getAttribute('class'));
if(not ^ (className && (' ' + className + ' ').indexOf(match) > -1)) {
if(!inplace) {
result.push(elem);
}
} else if(inplace) {
curLoop[i] = false;
}
}
}
return false;
};
}
Raphael.fn.tri = function (x, y, length) {
var x1 = x, y1 = y - length, offsetX = Math.cos(30 * Math.PI / 180) * length, offsetY = Math.tan(60 * Math.PI / 180) * offsetX, x2 = x + offsetX, y2 = y + offsetY, x3 = x - offsetX, y3 = y + offsetY, arrPath = [
"M",
x1.toString(),
y1.toString(),
"L",
x2.toString(),
y2.toString(),
"L",
x3.toString(),
y3.toString(),
"z"
];
return this.path(arrPath.join(" "));
};
Raphael.fn.invertedTri = function (x, y, length) {
var x1 = x, y1 = y + length, offsetX = Math.cos(30 * Math.PI / 180) * length, offsetY = Math.tan(60 * Math.PI / 180) * offsetX, x2 = x + offsetX, y2 = y - offsetY, x3 = x - offsetX, y3 = y - offsetY, arrPath = [
"M",
x1.toString(),
y1.toString(),
"L",
x2.toString(),
y2.toString(),
"L",
x3.toString(),
y3.toString(),
"z"
];
return this.path(arrPath.join(" "));
};
Raphael.fn.box = function (x, y, length) {
var offset = Math.cos(45 * Math.PI / 180) * length, arrPath = [
"M",
x - offset,
y - offset,
"L",
x + offset,
y - offset,
"L",
x + offset,
y + offset,
"L",
x - offset,
y + offset,
"z"
];
return this.path(arrPath.join(" "));
};
Raphael.fn.diamond = function (x, y, length) {
var arrPath = [
"M",
x,
y - length,
"L",
x + length,
y,
"L",
x,
y + length,
"L",
x - length,
y,
"z"
];
return this.path(arrPath.join(" "));
};
Raphael.fn.cross = function (x, y, length) {
var offset = Math.cos(45 * Math.PI / 180) * length, arrPath = [
"M",
x - offset,
y - offset,
"L",
x + offset,
y + offset,
"M",
x - offset,
y + offset,
"L",
x + offset,
y - offset
];
return this.path(arrPath.join(" "));
};
Raphael.fn.paintMarker = function (type, x, y, length) {
var self = this, marker = null;
if(!type) {
type = "circle";
}
switch(type) {
case "circle":
marker = self.circle(x, y, length);
break;
case "tri":
marker = self.tri(x, y, length);
break;
case "invertedTri":
marker = self.invertedTri(x, y, length);
break;
case "box":
marker = self.box(x, y, length);
break;
case "diamond":
marker = self.diamond(x, y, length);
break;
case "cross":
marker = self.cross(x, y, length);
break;
}
return marker;
};
Raphael.fn.htmlText = function (x, y, text, attrs, wordSpace, lineSpace) {
var applyStyle = function (txt, sp, attrs) {
var strongRegx = /<(b|strong)>/, italicRegx = /<(i|em)>/, hrefRegex = /href=[\"\']([^\"\']+)[\"\']/, aRegex = /<a/;
if(attrs) {
txt.attr(attrs);
}
if(strongRegx.test(sp)) {
txt.attr("font-weight", "bold");
}
if(italicRegx.test(sp)) {
txt.attr("font-style", "italic");
}
if(aRegex.test(sp)) {
if(sp.match(hrefRegex)[1]) {
txt.attr("href", sp.match(hrefRegex)[1]);
}
}
};
var texts = text.toString().split(/<br\s?\/>|\\r/i), self = this, st = self.set(), totalX = 0, totalY = 0;
//set default value of word spacing and line spacing
wordSpace = wordSpace || 3;
lineSpace = lineSpace || 5;
$.each(texts, function (ridx, item) {
var maxHeight = 0, spans = item.split('|||');
item = item.replace(/<([A-Za-z]+(.|\n)*?)>/g, '|||<$1>').replace(/<\/([A-Za-z]*)>/g, '</$1>|||');
$.each(spans, function (cidx, span) {
var temp = null, box = null, offsetX = 0, txtEl, offsetY = 0;
if(span !== '') {
temp = span;
temp = $.trim(temp.replace(/<(.|\n)*?>/g, ''));
txtEl = self.text(0, 0, temp);
applyStyle(txtEl, span, attrs);
box = txtEl.wijGetBBox();
offsetX = box.width / 2 + totalX;
offsetY = -box.height / 2 + totalY;
totalX = totalX + box.width + wordSpace;
txtEl.translate(offsetX, offsetY);
st.push(txtEl);
if(maxHeight < box.height) {
maxHeight = box.height;
}
}
});
totalY += maxHeight + lineSpace;
totalX = maxHeight = 0;
});
totalY = 0;
//st.translate(x - st.getBBox().x, y - st.getBBox().y);
st.transform(Raphael.format("...t{0},{1}", x - st.getBBox().x, y - st.getBBox().y));
return st;
};
Raphael.fn.line = function (startX, startY, endX, endY) {
return this.path([
"M",
startX.toString(),
startY.toString(),
"L",
endX.toString(),
endY.toString()
]);
};
Raphael.fn.roundRect = function (x, y, width, height, tlCorner, lbCorner, brCorner, rtCorner) {
var rs = [], posFactors = [
-1,
1,
1,
1,
1,
-1,
-1,
-1
], orientations = [
"v",
"h",
"v",
"h"
], pathData = null, lens = null;
$.each([
tlCorner,
lbCorner,
brCorner,
rtCorner
], function (idx, corner) {
if(typeof (corner) === "number") {
rs = rs.concat([
{
x: corner,
y: corner
}
]);
} else if(typeof (corner) === "object") {
rs = rs.concat(corner);
} else {
rs = rs.concat([
{
x: 0,
y: 0
}
]);
}
});
pathData = [
"M",
x + rs[0].x,
y
];
lens = [
height - rs[0].y - rs[1].y,
width - rs[1].x - rs[2].x,
rs[2].y + rs[3].y - height,
rs[3].x + rs[0].x - width
];
$.each(rs, function (idx, r) {
if(r.x && r.y) {
pathData = pathData.concat("a", r.x, r.y, 0, 0, 0, posFactors[2 * idx] * r.x, posFactors[2 * idx + 1] * r.y);
}
pathData = pathData.concat(orientations[idx], lens[idx]);
});
pathData.push("z");
return this.path(pathData);
};
Raphael.fn.wrapText = function (x, y, text, width, textAlign, textStyle) {
var self = this, rotation = textStyle.rotation, style = rotation ? $.extend(true, {
}, textStyle, {
rotation: 0
}) : textStyle, top = y, texts = self.set(), bounds = null, center = null, textBounds = [];
if(typeof text === "undefined") {
text = "";
}
function splitString(text, width, textStyle) {
var tempText = null, bounds = null, words = text.toString().split(' '), lines = [], line = [], tempTxt = "";
while(words.length) {
tempTxt += ' ' + words[0];
tempText = self.text(-1000, -1000, tempTxt);
tempText.attr(textStyle);
bounds = tempText.wijGetBBox();
if(bounds.width > width) {
if(line.length) {
lines.push(line);
tempTxt = words[0];
}
line = [
words.shift()
];
} else {
line.push(words.shift());
}
if(words.length === 0) {
lines.push(line);
}
tempText.wijRemove();
tempText = null;
}
return lines;
}
$.each(splitString(text, width, style), function (idx, line) {
var lineText = line.join(' '), align = textAlign || "near", txt = self.text(x, top, lineText), offsetX = 0, offsetY = 0;
txt.attr(style);
bounds = txt.wijGetBBox();
switch(align) {
case "near":
offsetX = width - bounds.width / 2;
//offsetY += bounds.height / 2;
//top += bounds.height;
break;
case "center":
offsetX += width / 2;
//offsetY += bounds.height / 2;
//top += bounds.height;
break;
case "far":
offsetX += bounds.width / 2;
//offsetY += bounds.height / 2;
//top += bounds.height;
break;
}
//add comments to fix tfs issue 19384
if(rotation) {
offsetY += bounds.height / 2 / Math.abs(Math.sin(rotation));
top += bounds.height / Math.abs(Math.sin(rotation));
} else {
offsetY += bounds.height / 2;
top += bounds.height;
}
//end comments
bounds.x += offsetX;
bounds.y += offsetY;
if(rotation) {
txt.attr({
x: txt.attr("x") + offsetX,
y: txt.attr("y") + offsetY
});
} else {
txt.transform(Raphael.format("...T{0},{1}", offsetX, offsetY));
}
texts.push(txt);
textBounds.push(bounds);
});
if(rotation) {
bounds = texts.wijGetBBox();
if(texts.length > 1) {
$.each(texts, function (idx, txt) {
txt.attr({
y: txt.attr("y") - bounds.height / 2
});
textBounds[idx].y -= bounds.height / 2;
});
center = {
x: bounds.x + bounds.width / 2,
y: bounds.y + bounds.height / 2
};
$.each(texts, function (idx, txt) {
var math = Math, tb = textBounds[idx], txtCenter = {
x: tb.x + tb.width / 2,
y: tb.y + tb.height / 2
}, len = math.sqrt(math.pow(txtCenter.x - center.x, 2) + math.pow(txtCenter.y - center.y, 2)), theta = 0, rotatedTB = null, newTxtCenter = null;
txt.attr({
rotation: rotation
});
if(len === 0) {
return true;
}
rotatedTB = txt.wijGetBBox();
theta = Raphael.deg(math.asin(math.abs(txtCenter.y - center.y) / len));
if(txtCenter.y > center.y) {
if(txtCenter.x > center.x) {
theta -= 360;
} else {
theta = -1 * (theta + 180);
}
} else {
if(txtCenter.x > center.x) {
theta *= -1;
} else {
theta = -1 * (180 - theta);
}
}
newTxtCenter = $.wijraphael.getPositionByAngle(center.x, center.y, len, -1 * (rotation + theta));
txt.attr({
y: txt.attr("y") + newTxtCenter.y - rotatedTB.y - rotatedTB.height / 2
});
});
} else {
texts[0].transform(Raphael.format("...R{0}", rotation));
}
}
return texts;
};
Raphael.fn.getSVG = function () {
function createSVGElement(type, options) {
var element = '<' + type + ' ', val = null, styleExist = false;
$.each(options, function (name, val) {
if(name === "text" || name === "opacity" || name === "transform" || name === "path" || name === "w" || name === "h" || name === "translation") {
return true;
}
if(val) {
if(name === "stroke" && val === 0) {
val = "none";
}
element += name + "='" + val + "' ";
}
});
/*
for (name in options) {
if (name === "text" || name === "opacity" ||
name === "transform" || name === "path" ||
name === "w" || name === "h" || name === "translation") {
continue;
}
if ((val = options[name]) !== null) {
if (name === "stroke" && val === 0) {
val = "none";
}
element += name + "='" + val + "' ";
}
}
*/
if(options.opacity) {
val = options.opacity;
element += "opacity='" + val + "' style='opacity:" + val + ";";
styleExist = true;
}
if(options.transform && options.transform.length > 0) {
val = options.transform;
if(styleExist) {
element += "transform:" + val;
} else {
element += "style='transform:" + val;
styleExist = true;
}
}
if(styleExist) {
element += "'";
}
if(options.text) {
val = options.text;
element += "><tspan>" + val + "</tspan>";
} else {
element += ">";
}
element += "</" + type + ">";
return element;
}
var paper = this, svg = '<svg xmlns="http://www.w3.org/2000/svg" ' + 'xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="' + paper.canvas.offsetWidth + '" height="' + paper.canvas.offsetHeight + '"><desc>Created with Raphael</desc><defs></defs>', node, path = "", trans, group, value, idx = 0, len1 = 0, index = 0, len2 = 0;
for(node = paper.bottom; node; node = node.next) {
if(node && node.type) {
switch(node.type) {
case "path":
for(idx = 0 , len1 = node.attrs.path.length; idx < len1; idx++) {
group = node.attrs.path[idx];
for(index = 0 , len2 = group.length; index < len2; index++) {
value = group[index];
if(index < 1) {
path += value;
} else {
if(index === (len2 - 1)) {
path += value;
} else {
path += value + ',';
}
}
}
}
if(path && path.length > 0) {
node.attrs.d = path.replace(/,/g, ' ');
}
break;
case "text":
if(!node.attrs["text-anchor"]) {
node.attrs["text-anchor"] = "middle";
}
break;
case "image":
trans = node.transformations;
node.attrs.transform = trans ? trans.join(' ') : '';
break;
case "ellipse":
case "rect":
svg += createSVGElement(node.type, node.attrs);
break;
}
}
}
svg += '</svg>';
return svg;
};
Raphael.el.wijRemove = function () {
var self = this, jqobj;
if(self.removed) {
return;
}
if(self.node.parentNode) {
jqobj = $(self.node);
self.stop().remove();
jqobj.remove();
}
};
Raphael.el.wijGetBBox = function () {
return this.getBBox();
};
Raphael.el.wijAnimate = function (params, ms, easing, callback) {
if(!params || $.isEmptyObject(params)) {
return;
}
var shadow = this.shadow, offset = 0, jQEasing = {
easeInCubic: ">",
easeOutCubic: "<",
easeInOutCubic: "<>",
easeInBack: "backIn",
easeOutBack: "backOut",
easeOutElastic: "elastic",
easeOutBounce: "bounce"
};
if(jQEasing[easing]) {
easing = jQEasing[easing];
}
this.animate(params, ms, easing, callback);
jQEasing = null;
if(shadow && shadow.offset) {
offset = shadow.offset;
if(params.x) {
params.x += offset;
}
if(params.y) {
params.y += offset;
}
this.shadow.animate(params, ms, easing, callback);
}
} , Raphael.el.wijAttr = function (name, value) {
this.attr(name, value);
if(this.shadow) {
if(typeof (name) === "object") {
var newName = $.extend(true, {
}, name);
if(newName.fill) {
delete newName.fill;
}
if(newName.stroke) {
delete newName.stroke;
}
if(newName["stroke-width"]) {
delete newName["stroke-width"];
}
this.shadow.attr(newName, value);
} else if(typeof (name) === "string") {
switch(name) {
case "clip-rect":
case "cx":
case "cy":
case "fill-opacity":
case "font":
case "font-family":
case "font-size":
case "font-weight":
case "height":
case "opacity":
case "path":
case "r":
case "rotation":
case "rx":
case "ry":
case "scale":
case "stroke-dasharray":
case "stroke-linecap":
case "stroke-linejoin":
case "stroke-miterlimit":
case "stroke-opacity":
case "stroke-width":
case "translation":
case "width":
this.shadow.attr(name, value);
break;
case "x":
this.shadow.attr(name, value);
//this.shadow.attr("translation", "1 0");
this.shadow.attr("transform", "...t1,0");
break;
case "y":
this.shadow.attr(name, value);
//this.shadow.attr("translation", "0 1");
this.shadow.attr("transform", "...t0,1");
break;
default:
break;
}
}
}
};
Raphael.st.wijRemove = function () {
$.each(this, function (idx, obj) {
if(obj.wijRemove && !obj.removed) {
obj.wijRemove();
}
});
};
Raphael.st.wijAttr = function (name, value) {
$.each(this.items, function (idx, item) {
item.wijAttr(name, value);
});
return this;
};
Raphael.st.wijAnimate = function (params, ms, easing, callback) {
var i = 0, ii = 0, item = null;
for(i = 0 , ii = this.items.length; i < ii; i++) {
item = this.items[i];
if(!item.removed) {
item.wijAnimate(params, ms, easing, callback);
}
}
return this;
};
Raphael.st.wijGetBBox = function () {
var x = [], y = [], w = [], h = [], bx, by, mmax = Math.max, mmin = Math.min, push = "push", apply = "apply", box = null, i = 0;
for(i = this.items.length - 1; i >= 0; i--) {
box = this.items[i].wijGetBBox();
x[push](box.x);
y[push](box.y);
w[push](box.x + box.width);
h[push](box.y + box.height);
}
bx = mmin[apply](0, x);
by = mmin[apply](0, y);
return {
x: bx,
y: by,
x2: undefined,
y2: undefined,
width: mmax[apply](0, w) - bx,
height: mmax[apply](0, h) - by
};
};
// fixed an issue that when set to width/height/r to negative value,
// the browser will throw exception in console. This issue is found in
// bar chart seriesTransition animation when the easing is backIn.
var raphaelAttr = Raphael.el.attr;
Raphael.el.attr = function (name, value) {
if($.isPlainObject(name)) {
$.each(name, function (key, val) {
if(key === "width" || key === "height" || key === "r") {
if(!isNaN(val) && val < 0) {
name[key] = 0;
}
}
});
}
if(name === "width" || name === "height" || name === "r") {
if(!isNaN(value) && value < 0) {
value = 0;
}
}
return raphaelAttr.apply(this, arguments);
};
//var raphaelAttr = Raphael.el.attr;
//Raphael.el.attr = function (name, value) {
// var el: HTMLElement = this.node, ret,
// setFill = function (n: string, v: any) {
// var attrV: string = $(el).attr(n),
// reg = /url\(\#(.*)\)/;
// if (reg.test(attrV)) {
// attrV = "url(" + attrV.replace(reg, location.href + "#$1") + ")";
// $(el).attr(n, attrV);
// }
// };
// ret = raphaelAttr.apply(this, arguments);
// if (name && Raphael.svg && !$.browser.msie) {
// if ($.isPlainObject(name)) {
// $.each(name, function (key: string, val: any) {
// if (key === "fill") {
// setFill(key, val);
// }
// })
// }
// else if (name === "fill") {
// setFill(name, value);
// }
// }
// return ret;
//}
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/// <reference path="../wijutil/jquery.wijmo.raphael.ts"/>
/// <reference path="../external/declarations/globalize.d.ts"/>
/*globals $, Raphael, jQuery, document, window, Globalize, wijmoASPNetParseOptions*/
/*
* Depends:
* raphael.js
* globalize.js
* jquery.svgdom.js
* jquery.ui.widget.js
*
*/
(function (chart) {
var $ = jQuery;
/** @ignore */
var ChartUtil = (function () {
function ChartUtil() { }
ChartUtil.getDiffAttrs = function getDiffAttrs(attrs, newAttrs) {
var result = {
};
$.each(newAttrs, function (key, attr) {
if(typeof (attrs) === "undefined") {
return true;
} else if(typeof (attrs[key]) === "undefined") {
result[key] = newAttrs[key];
} else if(attrs[key] !== newAttrs[key]) {
result[key] = newAttrs[key];
}
});
return result;
};
ChartUtil.paintShadow = //To do: make sure what is the type of the element.
function paintShadow(element, offset, stroke) {
if(element.removed || $(element.node).parent().length === 0) {
return;
}
var shadow = element.clone(), newOffset = offset || 1, newStroke = stroke || "#cccccc";
shadow.insertBefore(element);
shadow.attr({
transform: // translation: newOffset + " " + newOffset,
Raphael.format("...T{0},{1}", newOffset, newOffset),
stroke: newStroke,
"stroke-width": newOffset
});
shadow.toBack();
shadow.offset = newOffset;
element.shadow = shadow;
};
ChartUtil.getScaling = function getScaling(isVertical, max, min, length) {
var dx = max - min;
if(dx === 0) {
dx = 1;
}
if(isVertical) {
dx = -dx;
}
return length / dx;
};
ChartUtil.getTranslation = function getTranslation(isVertical, location, max, min, scaling) {
var translation = 0;
if(isVertical) {
translation = location.y;
translation -= scaling * max;
} else {
translation = location.x;
translation -= scaling * min;
}
return translation;
};
ChartUtil.getXSortedPoints = function getXSortedPoints(series) {
var seriesX = series.data.x, tempX = [].concat(seriesX), tempY = [].concat(series.data.y), points = [], sortedX = seriesX;
if(seriesX === undefined || seriesX.length === 0) {
return;
}
function sortNumber(a, b) {
return a - b;
}
if(typeof (seriesX[0]) === "number") {
sortedX = [].concat(seriesX).sort(sortNumber);
}
$.each(sortedX, function (i, nSortedX) {
$.each(tempX, function (j, nx) {
if(nSortedX === nx) {
if(typeof (nx) !== "number") {
nx = i;
}
points.push({
x: nx,
y: tempY[j]
});
tempX.splice(j, 1);
tempY.splice(j, 1);
return false;
}
});
});
return points;
};
ChartUtil.sector = function sector(cx, cy, r, startAngle, endAngle) {
var start = $.wijraphael.getPositionByAngle(cx, cy, r, startAngle), end = $.wijraphael.getPositionByAngle(cx, cy, r, endAngle);
return [
"M",
cx,
cy,
"L",
start.x,
start.y,
"A",
r,
r,
0,
+(endAngle - startAngle > 180),
0,
end.x,
end.y,
"z"
];
};
ChartUtil.donut = function donut(cx, cy, outerR, innerR, startAngle, endAngle) {
var outerS = $.wijraphael.getPositionByAngle(cx, cy, outerR, startAngle), outerE = $.wijraphael.getPositionByAngle(cx, cy, outerR, endAngle), innerS = $.wijraphael.getPositionByAngle(cx, cy, innerR, startAngle), innerE = $.wijraphael.getPositionByAngle(cx, cy, innerR, endAngle), largeAngle = endAngle - startAngle > 180;
return [
"M",
outerS.x,
outerS.y,
"A",
outerR,
outerR,
0,
+largeAngle,
0,
outerE.x,
outerE.y,
"L",
innerE.x,
innerE.y,
"A",
innerR,
innerR,
0,
+largeAngle,
1,
innerS.x,
innerS.y,
"L",
outerS.x,
outerS.y,
"z"
];
};
ChartUtil.getFirstValidListValue = function getFirstValidListValue(values) {
var val;
$.each(values, function (idx, value) {
if(value === null) {
return true;
} else if(typeof value === "undefined") {
return true;
} else if(typeof value === "number" && isNaN(value)) {
return true;
}
val = value;
return false;
});
return val;
};
ChartUtil.getLastValidListValue = function getLastValidListValue(values) {
var vals = [].concat(values).reverse();
return ChartUtil.getFirstValidListValue(vals);
};
ChartUtil.isHolefunction = function isHolefunction(val, hole) {
if(val === null) {
return true;
} else if(typeof val === "undefined") {
return true;
} else if(typeof val === "number" && isNaN(val)) {
return true;
}
if(hole === null) {
return false;
}
if(typeof val !== "undefined") {
// for datetime, if use val === hole it returns false.
if(val - hole === 0) {
return true;
}
return false;
}
return false;
};
return ChartUtil;
})();
chart.ChartUtil = ChartUtil;
/** @ignore */
var ChartDataUtil = (function () {
function ChartDataUtil() { }
ChartDataUtil.roundTime = function roundTime(timevalue, unit, roundup) {
var self = this, tunit = // tunit = unit * self._tmInc.day,
unit, tv = $.fromOADate(timevalue), th, td, tx, tz;
if(tunit > 0) {
th = {
year: tv.getFullYear(),
month: tv.getMonth(),
day: tv.getDate(),
hour: tv.getHours(),
minute: tv.getMinutes(),
second: tv.getSeconds()
};
if(tunit < self.tmInc.minute) {
th.second = self.tround(th.second, tunit, roundup);
return self.getTimeAsDouble(th);
}
th.second = 0;
if(tunit < self.tmInc.hour) {
tunit /= self.tmInc.minute;
th.minute = self.tround(th.minute, tunit, roundup);
return self.getTimeAsDouble(th);
}
th.minute = 0;
if(tunit < self.tmInc.day) {
tunit /= self.tmInc.hour;
th.hour = self.tround(th.hour, tunit, roundup);
return self.getTimeAsDouble(th);
}
th.hour = 0;
if(tunit < self.tmInc.month) {
tunit /= self.tmInc.day;
th.day = self.tround(th.day, tunit, roundup);
return self.getTimeAsDouble(th);
}
th.day = 1;
if(tunit < self.tmInc.year) {
tunit /= self.tmInc.month;
th.month = self.tround(th.month, tunit, roundup);
return self.getTimeAsDouble(th);
}
// th.month = 1;
th.month = 0// the month start from 0 in javascript.
;
tunit /= self.tmInc.year;
th.year = self.tround(th.year, tunit, roundup);
return self.getTimeAsDouble(th);
} else {
td = tv;
tx = td - tunit;
tz = parseInt((tx / unit).toString(), 10) * unit;
if(roundup && tz !== tx) {
tz += unit;
}
td = tunit + tz;
return td;
}
};
ChartDataUtil.tround = function tround(tval, tunit, roundup) {
var test = parseInt(((tval / tunit) * tunit).toString(), 10);
if(roundup && test !== tval) {
test += parseInt(tunit, 10);
}
return test;
};
ChartDataUtil.getTimeAsDouble = function getTimeAsDouble(th) {
var smon = 0, sday = 0, newDate = null;
if(th.day < 1) {
sday = -1 - th.day;
th.day = 1;
} else if(th.day > 28) {
sday = th.day - 28;
th.day = 28;
}
/*
* if (th.month < 1) { smon = -1 - th.day; th.month = 1; } else if
* (th.month > 12) { smon = th.month - 12; th.month = 12; }
*/
// the month start from 0 & end with 11 in javascript.
if(th.month < 0) {
smon = -1 - th.day;
th.month = 0;
} else if(th.month > 11) {
smon = th.month - 11;
th.month = 11;
}
newDate = new Date(th.year, th.month, th.day, th.hour, th.minute, th.second);
newDate.setDate(newDate.getDate() + sday);
newDate.setMonth(newDate.getMonth() + smon);
return $.toOADate(newDate);
};
ChartDataUtil.getTimeDefaultFormat = function getTimeDefaultFormat(max, min) {
var self = this, range = // range = (max - min) * self._tmInc.day,
max - min, format = "d";
// format = "s";
if(range > 2 * self.tmInc.year) {
format = "yyyy";
} else if(range > self.tmInc.year) {
format = "MMM yy";
} else if(range > 3 * self.tmInc.month) {
format = "MMM";
} else if(range > 2 * self.tmInc.week) {
format = "MMM d";
} else if(range > 2 * self.tmInc.day) {
format = "ddd d";
} else if(range > self.tmInc.day) {
format = "ddd H:mm";
} else if(range > self.tmInc.hour) {
format = "H:mm";
} else if(range >= 1000) {
format = "H:mm:ss";
}
/*
* else if (range > 0) { //TODO: return millisecond }
*/
return format;
};
ChartDataUtil.niceTimeUnit = function niceTimeUnit(timeinc, manualFormat) {
var self = this, tsRange = // tsRange = timeinc * self._tmInc.day;
timeinc;
tsRange = self.niceTimeSpan(tsRange, manualFormat);
// return tsRange / self._tmInc.day;
return tsRange;
};
ChartDataUtil.niceTimeSpan = function niceTimeSpan(range, manualFormat) {
var self = this, minSpan = self.manualTimeInc(manualFormat), tsinc = 0, tinc = 0;
/*
* if (minSpan < this._tmInc.second) { //TODO: calculate when
* millisecond }
*/
tsinc = Math.ceil(range);
if(tsinc === 0) {
return self.timeSpanFromTmInc(minSpan);
}
tinc = 1;
if(minSpan < self.tmInc.minute) {
if(tsinc < self.tmInc.minute) {
tinc = self.getNiceInc([
1,
2,
5,
10,
15,
30
], tsinc, minSpan);
if(tinc !== 0) {
return tinc;
}
}
minSpan = self.tmInc.minute;
}
if(minSpan < self.tmInc.hour) {
if(tsinc < self.tmInc.hour) {
tinc = self.getNiceInc([
1,
2,
5,
10,
15,
30
], tsinc, minSpan);
if(tinc !== 0) {
return tinc;
}
}
minSpan = self.tmInc.hour;
}
if(minSpan < self.tmInc.day) {
if(tsinc < self.tmInc.day) {
tinc = self.getNiceInc([
1,
3,
6,
12
], tsinc, minSpan);
if(tinc !== 0) {
return tinc;
}
}
minSpan = self.tmInc.day;
}
if(minSpan < self.tmInc.month) {
if(tsinc < self.tmInc.month) {
tinc = self.getNiceInc([
1,
2,
7,
14
], tsinc, minSpan);
if(tinc !== 0) {
return tinc;
}
}
minSpan = self.tmInc.month;
}
if(minSpan < self.tmInc.year) {
if(tsinc < self.tmInc.year) {
tinc = self.getNiceInc([
1,
2,
3,
4,
6
], tsinc, minSpan);
if(tinc !== 0) {
return tinc;
}
}
minSpan = self.tmInc.year;
}
tinc = 100 * self.tmInc.year;
if(tsinc < tinc) {
tinc = self.getNiceInc([
1,
2,
5,
10,
20,
50
], tsinc, minSpan);
if(tinc === 0) {
tinc = 100 * self.tmInc.year;
}
}
return tinc;
};
ChartDataUtil.getNiceInc = function getNiceInc(tik, ts, mult) {
var i = 0, tikm = 0, ii = tik.length;
for(i = 0; i < ii; i++) {
tikm = tik[i] * mult;
if(ts <= tikm) {
return tikm;
}
}
return 0;
};
ChartDataUtil.timeSpanFromTmInc = function timeSpanFromTmInc(ti) {
var rv = 1000, rti = ti, ticks = 1;
if(ti !== this.tmInc.maxtime) {
if(ti > this.tmInc.tickf1) {
rv = ti;
} else {
ti += 7;
while(rti > 0) {
ticks *= 10;
rti--;
}
rv = ticks;
}
}
return rv;
};
ChartDataUtil.manualTimeInc = function manualTimeInc(manualFormat) {
var self = this, minSpan = self.tmInc.second;
if(!manualFormat || manualFormat.length === 0) {
return minSpan;
}
// var f = manualFormat.indexOf("f");
// if (f > 0) {
// //TODO: when _getTimeDefaultFormat return millisecond
// }
// else if (manualFormat.indexOf("s") >= 0) {
if(manualFormat.indexOf("s") >= 0) {
minSpan = self.tmInc.second;
} else if(manualFormat.indexOf("m") >= 0) {
minSpan = self.tmInc.minute;
} else if(manualFormat.indexOf("h") >= 0 || manualFormat.indexOf("H") >= 0) {
minSpan = self.tmInc.hour;
} else if(manualFormat.indexOf("d") >= 0) {
minSpan = self.tmInc.day;
} else if(manualFormat.indexOf("M") >= 0) {
minSpan = self.tmInc.month;
} else if(manualFormat.indexOf("y") >= 0) {
minSpan = self.tmInc.year;
}
return minSpan;
};
ChartDataUtil.tmInc = {
tickf7: -7000,
tickf6: -6000,
tickf5: -5000,
tickf4: -4000,
tickf3: -3000,
tickf2: -2000,
tickf1: -1,
second: 1000,
minute: 60 * 1000,
hour: 60 * 60 * 1000,
day: 24 * 60 * 60 * 1000,
week: 7 * 24 * 60 * 60 * 1000,
month: 31 * 24 * 60 * 60 * 1000,
year: 365 * 24 * 60 * 60 * 1000,
maxtime: 2147483647
};
ChartDataUtil.niceTickNumber = function niceTickNumber(x) {
if(parseFloat(x) === 0.0) {
return x;
} else if(x < 0) {
x = -x;
}
var log10 = Math.log(x) / Math.log(10), exp = parseInt(this.signedFloor(log10).toString(), 10), f = x / Math.pow(10.0, exp), nf = 10.0;
if(f <= 1.0) {
nf = 1.0;
} else if(f <= 2.0) {
nf = 2.0;
} else if(f <= 5.0) {
nf = 5.0;
}
return (nf * Math.pow(10.0, exp));
};
ChartDataUtil.niceNumber = function niceNumber(x, exp, round) {
if(parseFloat(x) === 0.0) {
return x;
} else if(x < 0) {
x = -x;
}
var f = x / Math.pow(10.0, exp), nf = 10.0;
if(round) {
if(f < 1.5) {
nf = 1.0;
} else if(f < 3.0) {
nf = 2.0;
} else if(f < 7.0) {
nf = 5.0;
}
} else {
if(f <= 1.0) {
nf = 1.0;
} else if(f <= 2.0) {
nf = 2.0;
} else if(f <= 5.0) {
nf = 5.0;
}
}
return (nf * Math.pow(10.0, exp));
};
ChartDataUtil.nicePrecision = function nicePrecision(range) {
if(range <= 0 || typeof (range) !== "number") {
return 0;
}
var log10 = Math.log(range) / Math.log(10), exp = parseInt(this.signedFloor(log10).toString(), 10), f = range / Math.pow(10.0, exp);
if(f < 3.0) {
exp = -exp + 1;
}
return exp;
};
ChartDataUtil.precCeil = function precCeil(prec, value) {
var f = Math.pow(10.0, prec), x = value / f;
x = Math.ceil(x);
return x * f;
};
ChartDataUtil.precFloor = function precFloor(prec, value) {
var f = Math.pow(10.0, prec), x = value / f;
x = Math.floor(x);
return x * f;
};
ChartDataUtil.signedCeiling = function signedCeiling(val) {
if(val < 0.0) {
return Math.floor(val);
}
return Math.ceil(val);
};
ChartDataUtil.signedFloor = function signedFloor(val) {
if(val < 0.0) {
return Math.ceil(val);
}
return Math.floor(val);
};
return ChartDataUtil;
})();
chart.ChartDataUtil = ChartDataUtil;
Raphael.fn.closeBtn = function (x, y, length) {
var offset = Math.cos(45 * Math.PI / 180) * length, set = this.set(), arrPath = [
"M",
x - offset,
y - offset,
"L",
x + offset,
y + offset,
"M",
x - offset,
y + offset,
"L",
x + offset,
y - offset
], path = this.path(arrPath.join(" ")), rect = null;
path.attr({
cursor: "pointer"
});
set.push(path);
rect = this.rect(x - length, y - length, length * 2, length * 2);
rect.attr({
fill: "white",
"fill-opacity": 0,
cursor: "pointer",
stroke: "none"
});
set.push(rect);
return set;
};
//export enum ToolTipCompass {
// east,
// eastnorth,
// eastsouth,
// west,
// westnorth,
// westsouth,
// north,
// northeast,
// northwest,
// south,
// southeast,
// southwest
//}
/** @ignore */
var ChartTooltip = (function () {
function ChartTooltip(paper, targets, options) {
this.options = {
content: "",
contentStyle: {
},
title: "",
titleStyle: {
},
style: {
fill: "white",
"fill-opacity": 0.5
},
closeBehavior: "auto",
mouseTrailing: true,
triggers: "hover",
animated: "fade",
showAnimated: null,
hideAnimated: null,
duration: 500,
showDuration: 500,
hideDuration: 500,
easing: null,
showEasing: null,
hideEasing: null,
showDelay: 150,
hideDelay: 150,
relativeTo: "mouse",
compass: "east",
offsetX: 0,
offsetY: 0,
showCallout: true,
calloutFilled: false,
calloutFilledStyle: {
fill: "black"
},
calloutLength: 12,
calloutOffset: 0,
calloutAnimation: {
easing: null,
duration: 500
},
windowCollisionDetection: "flip",
calloutSide: null,
width: null,
height: null,
beforeShowing: null
};
this.paper = paper;
this.targets = targets;
$.extend(this.options, options);
this.init();
}
ChartTooltip.prototype.init = function () {
var o = this.options;
this.calloutOffset = o.calloutOffset;
this.offsetLength = 0;
this.gapLength = o.calloutLength / 2;
this.width = o.width;
this.height = o.height;
this.offset = {
x: 0,
y: 0
};
if(this.targets) {
this._bindLiveEvent(this.targets);
}
if(this.selector) {
this._bindLiveEventBySelector(this.selector);
}
};
ChartTooltip.prototype._getShowPoint = function (raphaelObj, compass) {
var box = raphaelObj.getBBox(), point = {
x: 0,
y: 0
};
switch(compass.toLowerCase()) {
case "east":
point.x = box.x + box.width;
point.y = box.y + box.height / 2;
break;
case "eastnorth":
point.x = box.x + box.width;
point.y = box.y;
break;
case "eastsouth":
point.x = box.x + box.width;
point.y = box.y + box.height;
break;
case "west":
point.x = box.x;
point.y = box.y + box.height / 2;
break;
case "westnorth":
point.x = box.x;
point.y = box.y;
break;
case "westsouth":
point.x = box.x;
point.y = box.y + box.height;
break;
case "north":
point.x = box.x + box.width / 2;
point.y = box.y;
break;
case "northeast":
point.x = box.x + box.width;
point.y = box.y;
break;
case "northwest":
point.x = box.x;
point.y = box.y;
break;
case "south":
point.x = box.x + box.width / 2;
point.y = box.y + box.height;
break;
case "southeast":
point.x = box.x + box.width;
point.y = box.y + box.height;
break;
case "southwest":
point.x = box.x;
point.y = box.y + box.height;
break;
}
return point;
};
ChartTooltip.prototype._clearIntentTimer = function (timer) {
if(timer) {
window.clearTimeout(timer);
timer = null;
}
};
ChartTooltip.prototype._removeTooltip = function (duration) {
var _this = this;
var self = this, elements = this.elements, o = self.options, animated, d, op;
if(elements) {
if(o.hideAnimated || o.animated) {
animated = o.hideAnimated;
if(!animated) {
animated = o.animated;
}
if(animated && ChartTooltip.animations[animated]) {
op = {
animated: animated,
duration: o.hideDuration || o.duration,
easing: o.hideEasing || o.easing,
context: elements,
show: false
};
ChartTooltip.animations[animated](op);
}
}
d = o.hideDuration || o.duration;
if(duration) {
d = duration;
}
window.setTimeout(function () {
var i, ii;
if(_this.content) {
_this.content.wijRemove();
_this.content = null;
}
if(_this.title) {
_this.title.wijRemove();
_this.title = null;
}
if(_this.container) {
_this.container.wijRemove();
_this.container = null;
}
if(_this.closeBtn) {
for(i = 0 , ii = _this.closeBtn.length; i < ii; i++) {
_this.closeBtn[i].unclick();
}
_this.closeBtn.wijRemove();
_this.closeBtn = null;
}
if(_this.callout) {
_this.callout.wijRemove();
_this.callout = null;
}
self.lastPoint = null;
elements = null;
}, d);
}
};
ChartTooltip.prototype._clearTimers = function () {
if(this.intentShowTimer) {
this._clearIntentTimer(this.intentShowTimer);
}
if(this.intentHideTimer) {
this._clearIntentTimer(this.intentHideTimer);
}
};
ChartTooltip.prototype._hide = function (e) {
var self = this;
self._clearTimers();
if(self.options.hideDelay) {
self.intentHideTimer = window.setTimeout(function () {
self._removeTooltip();
}, self.options.hideDelay);
} else {
self._removeTooltip();
}
};
ChartTooltip.prototype._convertCompassToPosition = function (compass) {
var position = "", offset = {
x: 0,
y: 0
};
switch(compass.toLowerCase()) {
case "east":
position = "right-middle";
offset.x = 2;
offset.y = 0;
break;
case "eastnorth":
position = "right-top";
offset.x = 2;
offset.y = -2;
break;
case "eastsouth":
position = "right-bottom";
offset.x = 2;
offset.y = 2;
break;
case "west":
position = "left-middle";
offset.x = -2;
offset.y = 0;
break;
case "westnorth":
position = "left-top";
offset.x = -2;
offset.y = -2;
break;
case "westsouth":
position = "left-bottom";
offset.x = -2;
offset.y = 2;
break;
case "north":
position = "top-middle";
offset.x = 0;
offset.y = -2;
break;
case "northeast":
position = "top-right";
offset.x = 2;
offset.y = -2;
break;
case "northwest":
position = "top-left";
offset.x = -2;
offset.y = -2;
break;
case "south":
position = "bottom-middle";
offset.x = 0;
offset.y = 2;
break;
case "southeast":
position = "bottom-right";
offset.x = 2;
offset.y = 2;
break;
case "southwest":
position = "bottom-left";
offset.x = -2;
offset.y = 2;
break;
}
this.offset = offset;
return position;
};
ChartTooltip.prototype._getCalloutArr = function (p, offset) {
var arr = [], o = this.options, compass = o.compass;
if(o.calloutSide) {
compass = o.calloutSide;
}
switch(compass.toLowerCase()) {
case "east":
case "eastsouth":
case "eastnorth":
arr = [
"M",
p.x + offset,
p.y + offset,
"l",
-offset,
-offset,
"l",
offset,
-offset,
"Z"
];
break;
case "west":
case "westsouth":
case "westnorth":
arr = [
"M",
p.x - offset,
p.y - offset,
"l",
offset,
offset,
"l",
-offset,
offset,
"Z"
];
break;
case "north":
case "northeast":
case "northwest":
arr = [
"M",
p.x - offset,
p.y - offset,
"l",
offset,
offset,
"l",
offset,
-offset,
"Z"
];
break;
case "south":
case "southeast":
case "southwest":
arr = [
"M",
p.x - offset,
p.y + offset,
"l",
offset,
-offset,
"l",
offset,
offset,
"Z"
];
break;
}
return arr;
};
ChartTooltip.prototype._getFuncText = function (text, e) {
if($.isFunction(text)) {
var fmt = null, objTar, obj = {
target: null,
fmt: text
}, t;
if(e && e.target) {
// obj.target = $(e.target).data("raphaelObj");
// objTar = $(e.target).data("raphaelObj");
// if (!objTar) {
// objTar = $(e.target.parentNode).data("raphaelObj");
// }
// obj.target = objTar;
t = e.target;
if(!t.raphael || !t.raphaelid) {
t = t.parentNode;
}
if(t.raphael && t.raphaelid) {
objTar = this.paper.getById(t.raphaelid);
obj.target = objTar;
} else {
obj.target = e.target;
}
}
fmt = $.proxy(obj.fmt, obj);
return fmt().toString();
}
return text;
};
ChartTooltip.prototype._translateCallout = function (duration) {
var o = this.options, width = this.width, height = this.height, gapLength = this.gapLength, offsetLength = this.offsetLength, calloutOffset = this.calloutOffset, callout = this.tooltipElements.callout;
if(o.calloutSide) {
var offset = gapLength || offsetLength;
switch(o.calloutSide) {
case "south":
case "north":
if(duration) {
callout.animate({
"translation": (-width / 2 + offset + calloutOffset) + ",0"
}, duration);
} else {
callout.translate(-width / 2 + offset + calloutOffset, 0);
}
break;
case "east":
case "west":
if(duration) {
callout.animate({
"translation": "0," + (-height / 2 + offset + calloutOffset)
}, duration);
} else {
callout.translate(0, -height / 2 + offset + calloutOffset);
}
break;
}
}
};
ChartTooltip.replacer = function replacer(all, key, obj) {
var res = obj, objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g;
key.replace(objNotationRegex, function (all, name, quote, quotedName, isFunc) {
name = name || quotedName;
if(res) {
if(res[name] !== typeof ('undefined')) {
res = res[name];
}
if(typeof res === "function" && isFunc) {
res = res();
}
}
});
res = (res === null || res === obj ? all : res).toString();
return res;
};
ChartTooltip.fill = function fill(str, obj) {
var tokenRegex = /\{([^\}]+)\}/g;
return String(str).replace(tokenRegex, function (all, key) {
return ChartTooltip.replacer(all, key, obj);
});
};
ChartTooltip.prototype._createPath = function (point, position, set) {
var pos = position.split("-"), r = 5, bb = set.getBBox(), o = this.options, p = o.padding, gapLength = this.gapLength, offsetLength = this.offsetLength, padding = p && !isNaN(p) ? parseInt(p) : 0, w = Math.round(bb.width + padding * 2), h = Math.round(bb.height + padding * 2), x = Math.round(bb.x - padding) - r, y = Math.round(bb.y - padding) - r, gap = 0, off = 0, dx = 0, dy = 0, shapes = null, mask = null, out = null;
if(o.width) {
w = w > o.width ? w : o.width;
}
if(o.height) {
h = h > o.height ? h : o.height;
}
this.width = w;
this.height = h;
gap = Math.min(h / 4, w / 4, gapLength);
if(offsetLength) {
offsetLength = Math.min(h / 4, w / 4, offsetLength);
}
if(offsetLength) {
off = offsetLength;
shapes = {
top: "M{x},{y}h{w4},{w4},{w4},{w4}a{r},{r},0,0,1,{r},{r}" + "v{h4},{h4},{h4},{h4}a{r},{r},0,0,1,-{r},{r}l-{right}," + "0-{offset},0,-{left},0a{r},{r},0,0,1-{r}-{r}" + "v-{h4}-{h4}-{h4}-{h4}a{r},{r},0,0,1,{r}-{r}z",
bottom: "M{x},{y}l{left},0,{offset},0,{right},0a{r},{r}," + "0,0,1,{r},{r}v{h4},{h4},{h4},{h4}a{r},{r},0,0,1,-{r}," + "{r}h-{w4}-{w4}-{w4}-{w4}a{r},{r},0,0,1-{r}-{r}" + "v-{h4}-{h4}-{h4}-{h4}a{r},{r},0,0,1,{r}-{r}z",
right: "M{x},{y}h{w4},{w4},{w4},{w4}a{r},{r},0,0,1,{r},{r}" + "v{h4},{h4},{h4},{h4}a{r},{r},0,0,1,-{r},{r}" + "h-{w4}-{w4}-{w4}-{w4}a{r},{r},0,0,1-{r}-{r}" + "l0-{bottom},0-{offset},0-{top}a{r},{r},0,0,1,{r}-{r}z",
left: "M{x},{y}h{w4},{w4},{w4},{w4}a{r},{r},0,0,1,{r},{r}" + "l0,{top},0,{offset},0,{bottom}a{r},{r},0,0,1,-{r}," + "{r}h-{w4}-{w4}-{w4}-{w4}a{r},{r},0,0,1-{r}-{r}" + "v-{h4}-{h4}-{h4}-{h4}a{r},{r},0,0,1,{r}-{r}z"
};
} else {
shapes = {
top: "M{x},{y}h{w4},{w4},{w4},{w4}a{r},{r},0,0,1,{r},{r}" + "v{h4},{h4},{h4},{h4}a{r},{r},0,0,1,-{r},{r}" + "l-{right},0-{gap},{gap}-{gap}-{gap}-{left},0a{r},{r},0,0,1" + "-{r}-{r}v-{h4}-{h4}-{h4}-{h4}a{r},{r},0,0,1,{r}-{r}z",
bottom: "M{x},{y}l{left},0,{gap}-{gap},{gap},{gap},{right},0" + "a{r},{r},0,0,1,{r},{r}v{h4},{h4},{h4},{h4}a{r},{r},0,0,1," + "-{r},{r}h-{w4}-{w4}-{w4}-{w4}a{r},{r},0,0," + "1-{r}-{r}v-{h4}-{h4}-{h4}-{h4}a{r},{r},0,0,1,{r}-{r}z",
right: "M{x},{y}h{w4},{w4},{w4},{w4}a{r},{r},0,0,1,{r},{r}" + "v{h4},{h4},{h4},{h4}a{r},{r},0,0,1,-{r},{r}h-{w4}-{w4}" + "-{w4}-{w4}a{r},{r},0,0,1-{r}-{r}l0-{bottom}-{gap}-{gap}," + "{gap}-{gap},0-{top}a{r},{r},0,0,1,{r}-{r}z",
left: "M{x},{y}h{w4},{w4},{w4},{w4}a{r},{r},0,0,1,{r},{r}" + "l0,{top},{gap},{gap}-{gap},{gap},0,{bottom}a{r},{r},0,0,1," + "-{r},{r}h-{w4}-{w4}-{w4}-{w4}a{r},{r},0,0,1-{r}-{r}" + "v-{h4}-{h4}-{h4}-{h4}a{r},{r},0,0,1,{r}-{r}z"
};
}
mask = [
{
x: x + r,
y: y,
w: w,
w4: w / 4,
h4: h / 4,
left: 0,
right: w - gap * 2 - off * 2,
top: 0,
bottom: h - gap * 2 - off * 2,
r: r,
h: h,
gap: gap,
offset: off * 2
},
{
x: x + r,
y: y,
w: w,
w4: w / 4,
h4: h / 4,
left: w / 2 - gap - off,
right: w / 2 - gap - off,
top: h / 2 - gap - off,
bottom: h / 2 - gap - off,
r: r,
h: h,
gap: gap,
offset: off * 2
},
{
x: x + r,
y: y,
w: w,
w4: w / 4,
h4: h / 4,
right: 0,
left: w - gap * 2 - off * 2,
bottom: 0,
top: h - gap * 2 - off * 2,
r: r,
h: h,
gap: gap,
offset: off * 2
}
][pos[1] === "middle" ? 1 : ((pos[1] === "left" || pos[1] === "top") ? 1 : 0) * 2];
out = this.paper.path(ChartTooltip.fill(shapes[pos[0]], mask));
switch(pos[0]) {
case "top":
dx = point.x - (x + r + mask.left + gap + offsetLength);
dy = point.y - (y + r + h + r + gap + offsetLength);
break;
case "bottom":
dx = point.x - (x + r + mask.left + gap + offsetLength);
dy = point.y - (y - gap - offsetLength);
break;
case "left":
dx = point.x - (x + r + w + r + gap + offsetLength);
dy = point.y - (y + r + mask.top + gap + offsetLength);
break;
case "right":
dx = point.x - (x - gap - off);
dy = point.y - (y + r + mask.top + gap + off);
break;
}
out.translate(dx, dy);
//set.translate(dx, dy);
set.transform(Raphael.format("...t{0},{1}", dx, dy));
return out;
};
ChartTooltip.prototype._isWindowCollision = function (container, compass, offsetX, offsetY, ox, oy, windowCollisionDetection) {
var box = container.getBBox(), counter = 0, cps = compass.toLowerCase(), x = box.x + ox, y = box.y + oy, w = this.paper.width, h = this.paper.height, offX = offsetX, offY = offsetY, strokeWidth = container.attr("stroke-width"), flip = windowCollisionDetection === true || windowCollisionDetection === "flip";
if(Raphael.vml) {
w = $(this.paper.canvas).width();
h = $(this.paper.canvas).height();
}
if(x - strokeWidth < 0) {
// counter++;
if(flip) {
if(cps.toLowerCase().indexOf("west") === -1) {
// check if window collision after change compass.
if(x + box.width / 2 + box.width - offsetX <= w) {
counter++;
cps = cps.toLowerCase() + "east";
offX = 0 - offsetX;
}
} else {
if(x + box.width + box.width - offsetX <= w) {
counter++;
cps = cps.toLowerCase().replace("west", "east");
offX = 0 - offsetX;
}
}
} else {
//fit
counter++;
offX = 0 - x + strokeWidth + offsetX;
}
}
if(y - strokeWidth < 0) {
if(flip) {
// counter++;
if(cps.toLowerCase().indexOf("north") === -1) {
// check if window collision after change compass.
if(y + box.height / 2 + box.height - offsetY <= h) {
counter++;
cps = cps.toLowerCase() + "south";
offY = 0 - offsetY;
}
} else {
if(y + box.height + box.height - offsetY <= h) {
counter++;
cps = cps.toLowerCase().replace("north", "south");
offY = 0 - offsetY;
}
}
} else {
//fit
counter++;
offY = 0 - y + strokeWidth + offsetY;
}
}
if(x + box.width + strokeWidth > w) {
if(flip) {
// counter++;
if(cps.toLowerCase().indexOf("east") === -1) {
// check if window collision after change compass.
if(x - box.width / 2 - offsetX >= 0) {
counter++;
cps = cps.toLowerCase() + "west";
offX = 0 - offsetX;
}
} else {
if(x - box.width - offsetX >= 0) {
counter++;
cps = cps.toLowerCase().replace("east", "west");
offX = 0 - offsetX;
}
}
} else {
//fit
counter++;
offX = w - (x + box.width + strokeWidth) + offsetX;
}
}
if(y + box.height + strokeWidth > h) {
if(flip) {
// counter++;
if(cps.toLowerCase().indexOf("south") === -1) {
// check if window collision after change compass.
if(y - box.height / 2 - offsetY >= 0) {
counter++;
cps = cps.toLowerCase() + "north";
offY = 0 - offsetY;
}
} else {
if(y - box.height - offsetY >= 0) {
counter++;
cps = cps.toLowerCase().replace("south", "north");
offY = 0 - offsetY;
}
}
} else {
//fit
counter++;
offY = h - (y + box.height + strokeWidth) + offsetY;
}
}
if(counter) {
return {
compass: cps,
offsetX: offX,
offsetY: offY
};
}
return false;
};
ChartTooltip.prototype._createTooltipEles = function (point, tit, cont, windowCollisionDetection, compass, offsetX, offsetY) {
var _this = this;
var titleBox, contentBox, position, set = this.paper.set(), arrPath = null, animated = null, o = this.options, closeBtnLength = this.closeBtnLength, calloutOffset = this.calloutOffset, op = null, ox = 0, oy = 0, duration = 250, idx = 0, len = 0, isWindowCollision, newPoint = {
x: point.x,
y: point.y
}, offset = this.offset, anim = null, trans = null;
$.wijraphael.clearRaphaelCache();
position = this._convertCompassToPosition(compass);
newPoint.x += offsetX + offset.x;
newPoint.y += offsetY + offset.y;
this.elements = this.paper.set();
if(this.title) {
$.each(this.title, function (i, t) {
$(t.node).unbind(".Rtooltip");
});
this.title.wijRemove();
}
if(tit && tit.length > 0) {
this.title = this.paper.htmlText(-1000, -1000, tit, o.titleStyle);
this.elements.push(this.title);
titleBox = this.title.getBBox();
} else {
titleBox = {
left: -1000,
top: -1000,
width: 0,
height: 0
};
}
if(this.content) {
$.each(this.content, function (i, c) {
$(c.node).unbind(".Rtooltip");
});
this.content.wijRemove();
}
if(cont && cont.length > 0) {
this.content = this.paper.htmlText(-1000, -1000, cont, o.contentStyle);
this.elements.push(this.content);
contentBox = this.content.getBBox();
} else {
contentBox = {
left: -1000,
top: -1000,
width: 0,
height: 0
};
}
if(this.closeBtn) {
for(idx = 0 , len = this.closeBtn.length; idx < len; idx++) {
this.closeBtn[idx].unclick();
}
this.closeBtn.wijRemove();
}
if(this.content) {
// content.translate(0, titleBox.height / 2 +
// contentBox.height / 2);
this.content.transform(Raphael.format("T0,{0}", titleBox.height / 2 + contentBox.height / 2));
}
if(this.title) {
// content.translate(0, titleBox.height / 2 +
// contentBox.height / 2);
this.title.transform(Raphael.format("T0,{0}", 0));
}
if(o.closeBehavior === "sticky") {
this.closeBtn = this.paper.closeBtn(-1000, -1000, closeBtnLength);
this.elements.push(this.closeBtn);
if(o.width && o.width > titleBox.width + closeBtnLength * 2 && o.width > contentBox.width + closeBtnLength * 2) {
// closeBtn.translate(o.width - closeBtnLength,
// closeBtnLength);
this.closeBtn.transform(Raphael.format("T{0},{1}", o.width - closeBtnLength, closeBtnLength));
} else if(titleBox.width >= contentBox.width - closeBtnLength * 2) {
// closeBtn.translate(titleBox.width +
// closeBtnLength, closeBtnLength);
this.closeBtn.transform(Raphael.format("T{0},{1}", titleBox.width + closeBtnLength, closeBtnLength));
} else {
// closeBtn.translate(contentBox.width -
// closeBtnLength, closeBtnLength);
this.closeBtn.transform(Raphael.format("T{0},{1}", contentBox.width - closeBtnLength, closeBtnLength));
}
// bind click event.
$.each(this.closeBtn, function (i, btn) {
var self = _this;
btn.click(function (e) {
self._hide(e);
});
});
}
if(this.title) {
set.push(this.title);
if(o.relatedElement) {
this.title.insertBefore(o.relatedElement);
}
}
if(this.content) {
set.push(this.content);
if(o.relatedElement) {
this.content.insertBefore(o.relatedElement);
}
}
if(this.closeBtn) {
set.push(this.closeBtn);
if(o.relatedElement) {
this.closeBtn.insertBefore(o.relatedElement);
}
}
if(!o.showCallout) {
this.gapLength = 0;
}
if(o.calloutSide || o.calloutFilled) {
this.gapLength = 0;
this.offsetLength = o.calloutLength / 2;
if(o.calloutSide) {
position = this._convertCompassToPosition(o.calloutSide);
}
}
if(o.calloutSide && set.length === 0) {
this.content = this.paper.htmlText(-1000, -1000, " ");
set.push(this.content);
if(o.relatedElement) {
this.content.insertBefore(o.relatedElement);
}
}
if(this.callout) {
$(this.callout.node).unbind(".Rtooltip");
this.callout.wijRemove();
}
if(this.container) {
$(this.container.node).unbind(".Rtooltip");
this.container.wijRemove();
}
// container = self.path();
if(this.lastPoint) {
if(o.showCallout && (o.calloutSide || o.calloutFilled)) {
arrPath = this._getCalloutArr(this.lastPoint, this.offsetLength);
this.callout = this.paper.path(arrPath.concat(" "));
if(o.relatedElement) {
this.callout.insertBefore(o.relatedElement);
}
if(o.calloutFilled) {
this.callout.attr(o.calloutFilledStyle);
}
if(o.calloutSide) {
this._translateCallout(0);
}
}
this.container = this._createPath(this.lastPoint, position, set);
if(o.relatedElement) {
this.container.insertBefore(o.relatedElement);
}
if(windowCollisionDetection) {
isWindowCollision = this._isWindowCollision(this.container, compass, offsetX, offsetY, newPoint.x - this.lastPoint.x, newPoint.y - this.lastPoint.y, windowCollisionDetection);
// TODO: window collision
if(isWindowCollision) {
this._createTooltipEles(point, tit, cont, false, isWindowCollision.compass, isWindowCollision.offsetX, isWindowCollision.offsetY);
return;
}
}
this.elements.push(this.callout);
this.elements.push(this.container);
ox = newPoint.x - this.lastPoint.x;
oy = newPoint.y - this.lastPoint.y;
trans = Raphael.format("...T{0},{1}", ox, oy);
anim = Raphael.animation({
transform: trans
}, duration);
if(this.container) {
// container.animate({ "translation": ox + "," + oy },
// duration);
if(o.showAnimated || o.animated) {
this.container.animate(anim);
} else {
this.container.attr("transform", trans);
}
}
if(this.title) {
// title.animate({ "translation": ox + "," + oy },
// duration);
if(o.showAnimated || o.animated) {
this.title.animate(anim);
} else {
this.title.attr("transform", trans);
}
}
if(this.content) {
// content.animate({ "translation": ox + "," + oy },
// duration);
if(o.showAnimated || o.animated) {
this.content.animate(anim);
} else {
this.content.attr("transform", trans);
}
}
if(this.closeBtn) {
// closeBtn.animate({ "translation": ox + "," + oy },
// duration);
if(o.showAnimated || o.animated) {
this.closeBtn.animate(anim);
} else {
this.closeBtn.attr("transform", trans);
}
}
if(this.callout) {
// callout.animate({ "translation": ox + "," + oy },
// duration);
if(o.showAnimated || o.animated) {
this.callout.animate(anim);
} else {
this.callout.attr("transform", trans);
}
}
} else {
if(o.showCallout && (o.calloutSide || o.calloutFilled)) {
arrPath = this._getCalloutArr(newPoint, this.offsetLength);
this.callout = this.paper.path(arrPath.concat(" "));
if(o.relatedElement) {
this.callout.insertBefore(o.relatedElement);
}
if(o.calloutFilled) {
this.callout.attr(o.calloutFilledStyle);
}
if(o.calloutSide) {
this._translateCallout(0);
}
}
this.container = this._createPath(newPoint, position, set);
if(o.relatedElement) {
this.container.insertBefore(o.relatedElement);
}
if(windowCollisionDetection) {
isWindowCollision = this._isWindowCollision(this.container, compass, offsetX, offsetY, 0, 0, windowCollisionDetection);
// TODO: window collision
if(isWindowCollision) {
this._createTooltipEles(point, tit, cont, false, isWindowCollision.compass, isWindowCollision.offsetX, isWindowCollision.offsetY);
return;
}
}
this.elements.push(this.callout);
this.elements.push(this.container);
if(o.showAnimated || o.animated) {
animated = o.showAnimated;
if(!animated) {
animated = o.animated;
}
if(animated && ChartTooltip.animations[animated]) {
op = {
animated: animated,
duration: o.showDuration || o.duration,
easing: o.showEasing || o.easing,
context: this.elements,
show: true
};
ChartTooltip.animations[animated](op);
}
}
}
this.lastPoint = newPoint;
this.container.attr(o.style);
// container.toFront();
if(o.relatedElement) {
if(this.title) {
this.title.insertBefore(o.relatedElement);
}
if(this.content) {
this.content.insertBefore(o.relatedElement);
}
if(this.closeBtn) {
this.closeBtn.insertBefore(o.relatedElement);
}
} else {
set.toFront();
}
// set.toFront();
/*
* if (o.closeBehavior === "auto") {
* $(container.node).bind("mouseover.Rtooltip", function (e) {
* _clearTimers(); }).bind("mouseout.Rtooltip", function (e) {
* _hide(e); }); if (title) { $.each(title, function (i, t) {
* $(t.node).bind("mouseover.Rtooltip", function (e) {
* _clearTimers(); }).bind("mouseout.Rtooltip", function (e) {
* _hide(e); }); }); } if (content) { $.each(content, function
* (i, c) { $(c.node).bind("mouseover.Rtooltip", function (e) {
* _clearTimers(); }).bind("mouseout.Rtooltip", function (e) {
* _hide(e); }); }); } if (callout) {
* $(callout.node).bind("mouseover.Rtooltip", function (e) {
* _clearTimers(); }).bind("mouseout.Rtooltip", function (e) {
* _hide(e); }); } }
*/
};
ChartTooltip.prototype._createTooltip = function (point, e) {
var tit = null, cont = null, fmt = null, obj = null, o = this.options, objTar, t;
if($.isFunction(o.beforeShowing)) {
fmt = null;
obj = {
target: null,
options: o,
fmt: o.beforeShowing
};
if(e && e.target) {
// objTar = $(e.target).data("raphaelObj");
// if (!objTar) {
// objTar = $(e.target.parentNode).data("raphaelObj");
// }
// obj.target = objTar;
t = e.target;
if(!t.raphael || !t.raphaelid) {
t = t.parentNode;
}
if(t.raphael && t.raphaelid) {
objTar = this.paper.getById(t.raphaelid);
obj.target = objTar;
} else {
objTar = e.target;
obj.target = objTar;
}
}
fmt = $.proxy(obj.fmt, obj);
if(fmt() === false) {
return;
}
;
}
tit = o.title;
cont = o.content;
tit = this._getFuncText(tit, e);
cont = this._getFuncText(cont, e);
if(!tit && !cont) {
return;
}
this._createTooltipEles(point, tit, cont, o.windowCollisionDetection, o.compass, o.offsetX, o.offsetY);
};
ChartTooltip.prototype._showAt = function (point, e) {
var o = this.options, self = this;
this._clearTimers();
if(o.showDelay) {
this.intentShowTimer = window.setTimeout(function () {
self._createTooltip(point, e);
}, o.showDelay);
} else {
this._createTooltip(point, e);
}
};
ChartTooltip.prototype._show = function (e) {
var position = $(this.paper.canvas.parentNode).offset(), offsetX = position.left, offsetY = position.top, o = this.options, relativeTo = o.relativeTo, point = {
x: 0,
y: 0
}, raphaelObj = null, t = e.target;
switch(relativeTo) {
case "mouse":
point.x = e.pageX - offsetX;
point.y = e.pageY - offsetY;
break;
case "element":
if(!t.raphael || !t.raphaelid) {
t = t.parentNode;
}
if(t.raphael && t.raphaelid) {
raphaelObj = this.paper.getById(t.raphaelid);
point = this._getShowPoint(raphaelObj, o.compass);
}
break;
}
this._showAt(point, e);
};
ChartTooltip.prototype._bindEvent = function (tar) {
var o = this.options, self = this;
switch(o.triggers) {
case "hover":
$(tar.node).bind("mouseover.Rtooltip", function (e) {
self._show(e);
}).bind("mouseout.Rtooltip", function (e) {
if(o.closeBehavior === "auto") {
self._hide(e);
}
});
if(o.mouseTrailing && o.relativeTo === "mouse") {
$(tar.node).bind("mousemove.Rtooltip", function (e) {
self._show(e);
});
}
break;
case "click":
$(tar.node).bind("click.Rtooltip", function (e) {
self._show(e);
});
break;
case "custom":
break;
/*
* case "rightClick": $(tar.node).bind("contextmenu.Rtooltip",
* function (e) { _show(e); }); break;
*/
}
};
ChartTooltip.prototype._bindLiveEvent = function (tars) {
var i, ii;
if(tars) {
if(tars.length) {
for(i = 0 , ii = tars.length; i < ii; i++) {
this._bindEvent(tars[i]);
}
} else {
this._bindEvent(tars);
}
}
};
ChartTooltip.prototype._bindLiveEventBySelector = function (selector) {
var o = this.options, self = this;
if(selector) {
switch(o.triggers) {
case "hover":
selector.on("mouseover.Rtooltip", function (e) {
self._show(e);
}).on("mouseout.Rtooltip", function (e) {
if(o.closeBehavior === "auto") {
self._hide(e);
}
});
if(o.mouseTrailing && o.relativeTo === "mouse") {
selector.on("mousemove.Rtooltip", function (e) {
self._show(e);
});
}
break;
case "click":
selector.on("click.Rtooltip", function (e) {
self._show(e);
});
break;
case "custom":
break;
}
}
};
ChartTooltip.prototype._unbindLiveEvent = function (targets, selector) {
var i, ii;
if(targets) {
if(targets.length) {
for(i = 0 , ii = targets.length; i < ii; i++) {
$(targets[i].node).unbind(".Rtooltip");
}
} else {
$(targets.node).unbind(".Rtooltip");
}
}
if(selector) {
selector.off("Rtooltip").off(// for jQuery 1.7.1
".Rtooltip");
}
};
ChartTooltip.prototype._destroy = function () {
this._unbindLiveEvent(this.targets, this.selector);
this._removeTooltip(0);
};
ChartTooltip.prototype.hide = function () {
this._hide();
};
ChartTooltip.prototype.showAt = function (point, e) {
this._showAt(point, e);
};
ChartTooltip.prototype.resetCalloutOffset = function (offset) {
var o = this.options, currentOffset = o.calloutOffset, side = o.calloutSide, ani = o.calloutAnimation, tooltipElements = this.tooltipElements;
if(tooltipElements.callout) {
if(side === "south" || side === "north") {
tooltipElements.callout.animate({
"translation": (offset - currentOffset) + ",0"
}, ani.duration, ani.easing);
} else if(side === "east" || side === "west") {
tooltipElements.callout.animate({
"translation": "0," + (offset - currentOffset)
}, ani.duration, ani.easing);
}
}
o.calloutOffset = offset;
};
ChartTooltip.prototype.destroy = function () {
this._destroy();
};
ChartTooltip.prototype.getOptions = function () {
return this.options;
};
ChartTooltip.prototype.setTargets = function (targets) {
this.targets = targets;
this._bindLiveEvent(targets);
};
ChartTooltip.prototype.setSelector = function (selector) {
this.selector = selector;
this._bindLiveEventBySelector(selector);
};
ChartTooltip.prototype.setOptions = function (opts) {
$.extend(true, this.options, opts);
};
ChartTooltip.animations = {
fade: function (options) {
var eles = options.context;
if(options.show) {
eles.attr({
"opacity": 0
});
eles.wijAnimate({
"opacity": 1
}, options.duration, options.easing);
} else {
eles.wijAnimate({
"opacity": 0
}, options.duration, options.easing);
}
}
};
return ChartTooltip;
})();
chart.ChartTooltip = ChartTooltip;
//for original API
Raphael.fn.tooltip = {
animations: ChartTooltip.animations
};
/** @ignore */
var AdjustLabel = (function () {
function AdjustLabel(bBox) {
this.labels = [];
this.crossLabels = {
};
this.bBox = bBox;
}
AdjustLabel.prototype.push = function (label) {
var bBox = label.wijGetBBox();
this.labels.push({
ele: label,
x: bBox.x,
y: bBox.y,
width: bBox.width,
height: bBox.height,
overlaps: [],
bakBBox: bBox
});
};
AdjustLabel.prototype.pushCross = function (idx1, idx2) {
var label1, label2, dx, dy, tmp;
if(!this.crossLabels[Raphael.format("{0}-{1}", idx1, idx2)] && !this.crossLabels[Raphael.format("{0}-{1}", idx2, idx1)]) {
label1 = this.labels[idx1];
label2 = this.labels[idx2];
this.crossLabels[Raphael.format("{0}-{1}", idx1, idx2)] = {
label1: label1,
label2: label2,
dx: this._getAdjust(label1, label2, "h"),
dy: this._getAdjust(label1, label2, "v")
};
}
};
AdjustLabel.prototype._detect = function (label1, label2) {
return ((label1.x + label1.width > label2.x && label1.x < label2.x) || (label2.x + label2.width > label1.x && label2.x < label1.x)) && ((label1.y + label1.height > label2.y && label1.y < label2.y) || (label2.y + label2.height > label1.y && label2.y < label1.y));
};
AdjustLabel.prototype._resetOverlaps = function () {
this.crossLabels = {
};
};
AdjustLabel.prototype._detects = function () {
var len = this.labels.length, label1, label2;
for(var i = 0; i < len; i++) {
for(var j = i + 1; j < len; j++) {
label1 = this.labels[i];
label2 = this.labels[j];
if(this._detect(label1, label2)) {
this.pushCross(i, j);
}
}
}
};
AdjustLabel.prototype._getAdjust = function (label1, label2, dir) {
var obj = {
dx: 0,
needRevert: false
};
if(dir === "h") {
if(label1.x < label2.x) {
obj.dx = label1.x + label1.width - label2.x;
} else {
obj.dx = label2.x + label2.width - label1.x;
obj.needRevert = true;
}
} else {
if(label1.y < label2.y) {
obj.dx = label1.y + label1.height - label2.y;
} else {
obj.dx = label2.y + label2.height - label1.y;
obj.needRevert = true;
}
}
return obj;
};
AdjustLabel.prototype._adjustlabel = function (label1, label2, dx, dir) {
if(dir === "h") {
label1.x -= dx / 2;
label2.x += dx / 2;
if(this.bBox) {
if(label1.x < this.bBox.x) {
label1.x = this.bBox.x;
label2.x = label2.x + (this.bBox.x - label1.x);
} else if(label2.x > this.bBox.x + this.bBox.width) {
label2.x = this.bBox.x + this.bBox.width;
label1.x -= label2.x - this.bBox.x + this.bBox.width;
}
}
} else {
label1.y -= dx / 2;
label2.y += dx / 2;
if(this.bBox) {
if(label1.y < this.bBox.y) {
label1.y = this.bBox.y;
label2.y = label2.y + (this.bBox.y - label1.y);
} else if(label2.y > this.bBox.y + this.bBox.height) {
label2.y = this.bBox.y + this.bBox.height;
label1.y -= label2.y - this.bBox.y + this.bBox.height;
}
}
}
};
AdjustLabel.prototype._adjustInternal = function () {
var _this = this;
$.each(this.crossLabels, function (i, labelObj) {
var label1 = labelObj.label1, label2 = labelObj.label2, dx = labelObj.dx, dy = labelObj.dy;
if(dx.dx < dy.dx) {
if(dy.needRevert) {
_this._adjustlabel(label2, label1, dy.dx, "v");
} else {
_this._adjustlabel(label1, label2, dy.dx, "v");
}
} else {
if(dx.needRevert) {
_this._adjustlabel(label2, label1, dx.dx, "h");
} else {
_this._adjustlabel(label1, label2, dx.dx, "h");
}
}
});
};
AdjustLabel.prototype._adjustTheEdge = function () {
var _this = this;
if(this.bBox) {
$.each(this.labels, function (i, label) {
if(label.x < _this.bBox.x) {
label.x = _this.bBox.x;
} else if(label.x + label.width > _this.bBox.x + _this.bBox.width) {
label.x = _this.bBox.x + _this.bBox.width - label.width;
}
if(label.y < _this.bBox.y) {
label.y = _this.bBox.y;
} else if(label.y + label.height > _this.bBox.y + _this.bBox.height) {
label.y = _this.bBox.y + _this.bBox.height - label.height;
}
});
}
};
AdjustLabel.prototype._translateLabels = function () {
$.each(this.labels, function (i, label) {
if(label.x !== label.bakBBox.x) {
label.ele.attr("x", label.x + label.width / 2);
label.bakBBox.x = label.x;
}
if(label.y !== label.bakBBox.y) {
label.ele.attr("y", label.y + label.height / 2);
label.bakBBox.y = label.y;
}
});
};
AdjustLabel.prototype.adjust = function () {
var maxCalculate = 1000;
while(maxCalculate > 0) {
this._resetOverlaps();
this._adjustTheEdge();
this._detects();
if($.isEmptyObject(this.crossLabels)) {
break;
}
maxCalculate--;
this._adjustInternal();
}
console.log(maxCalculate);
this._translateLabels();
};
return AdjustLabel;
})();
chart.AdjustLabel = AdjustLabel;
/** @widget */
var wijchartcore = (function (_super) {
__extends(wijchartcore, _super);
function wijchartcore() {
_super.apply(this, arguments);
this.innerState = {
};
}
wijchartcore.prototype._setOption = function (key, value) {
var self = this, o = self.options, ev = null, len = 0, idx = 0, oldXMajorFactor = o.axis.x.tickMajor.factor, oldXMinorFactor = o.axis.x.tickMinor.factor, oldYMajorFactor, oldYMinorFactor, bakYAxis, newYAxis, hoverStyleLen, baseAxis = // oldYMajorFactor = o.axis.y.tickMajor.factor,
// oldYMinorFactor = o.axis.y.tickMinor.factor,
wijchartcore.prototype.options.axis, oldYAxis;
/*
if (key === "dataSource" || key === "data") {
self.seriesTransition = true;
o.dataSource = value;
//restore the binded data
if (self.seriesList) {
o.seriesList = $.arrayClone(self.seriesList);
}
self._init();
}
*/
if(key === "dataSource") {
self.seriesTransition = true;
o.dataSource = value;
//restore the binded data
if(self.seriesList) {
o.seriesList = $.arrayClone(self.seriesList);
}
self._init();
} else if(key === "data") {
self.seriesTransition = true;
o.data = value;
//restore the binded data
if(self.seriesList) {
o.seriesList = $.arrayClone(self.seriesList);
}
self._init();
} else if(key === "seriesList") {
if(!value) {
value = [];
}
ev = $.Event("beforeserieschange");
if(self._trigger("beforeSeriesChange", ev, {
oldSeriesList: o.seriesList,
newSeriesList: value
}) === false) {
return false;
}
o.seriesList = value;
self.seriesList = $.arrayClone(value);
self._trigger("seriesChanged", null, value);
self.seriesTransition = true;
self._init();
} else {
if($.isPlainObject(o[key])) {
if(key === "axis") {
if($.isArray(o.axis.y)) {
bakYAxis = $.arrayClone(o.axis.y);
} else {
bakYAxis = $.extend(true, {
}, o.axis.y);
}
}
//extend the axis from base chartcore.
if(key === "axis") {
$.extend(true, o.axis.x, value.x || {
});
if($.isArray(o.axis.y) || $.isArray(value.y)) {
oldYAxis = {
};
} else {
oldYAxis = o.axis.y;
}
if($.isArray(value.y)) {
$.each(value.y, function (i, _yaxis) {
value.y[i] = $.extend(true, {
}, baseAxis.y, oldYAxis, _yaxis);
});
o.axis.y = value.y;
} else {
o.axis.y = $.extend(true, {
}, baseAxis.y, oldYAxis, value.y);
}
} else {
$.extend(true, o[key], value);
}
if(key === "indicator") {
this._unbindCanvasEvents();
this._bindCanvasEvents();
}
if(key === "axis") {
newYAxis = o.axis.y;
if(o.axis.x.tickMajor.factor < 0) {
o.axis.x.tickMajor.factor = oldXMajorFactor;
}
if(o.axis.x.tickMinor.factor < 0) {
o.axis.x.tickMinor.factor = oldXMinorFactor;
}
//case origin y is object, now is object
if(!$.isArray(newYAxis)) {
if($.isArray(bakYAxis)) {
oldYMajorFactor = bakYAxis[0].tickMajor.factor;
oldYMinorFactor = bakYAxis[0].tickMinor.factor;
} else {
oldXMajorFactor = bakYAxis.tickMajor.factor;
oldXMinorFactor = bakYAxis.tickMinor.factor;
}
if(o.axis.y.tickMajor && o.axis.y.tickMajor.factor !== undefined && o.axis.y.tickMajor.factor < 0) {
o.axis.y.tickMajor.factor = oldYMajorFactor;
}
if(o.axis.y.tickMinor && o.axis.y.tickMinor.factor !== undefined && o.axis.y.tickMinor.factor < 0) {
o.axis.y.tickMinor.factor = oldYMinorFactor;
}
} else// case newYAxis is array
{
if(!$.isArray(bakYAxis)) {
bakYAxis = [
bakYAxis
];
}
$.each(newYAxis, function (i, yAxis) {
var baky = bakYAxis[i] || {
};
if(baky.tickMajor && baky.tickMajor.factor && yAxis.tickMajor && yAxis.tickMajor.factor) {
if(yAxis.tickMajor.factor < 0) {
yAxis.tickMajor.factor = baky.tickMajor.factor;
}
}
if(baky.tickMinor && baky.tickMinor.factor && yAxis.tickMinor && yAxis.tickMinor.factor) {
if(yAxis.tickMinor.factor < 0) {
yAxis.tickMinor.factor = baky.tickMinor.factor;
}
}
});
}
}
} else {
_super.prototype._setOption.call(this, key, value);
// o[key] = value;
}
}
// Add for support disabled option at 2011/7/8
if(key === "disabled") {
self._handleDisabledOption(value, self.chartElement);
}
// end for disabled option
// fixed a issue that when set the disabled option,
// because the chart is paint by
// wij***chart plugin, and the disabled set to the plugin
// as a value, not a refrence,
// so the plugin's disabled value can't change
// when set the disabled to charts.
// now, we just repaint the chart.
if(key === "seriesTransition" || key === "animation") {
//||
// key === "disabled") {
return;
}
if(key === "hint") {
self._resetTooltip();
return;
}
len = o.seriesList.length;
if(key === "seriesList" || key === "seriesStyles" || key === "seriesHoverStyles") {
//backup the styles. when drawed the charts, restore the styles.
if(key !== "seriesList") {
self._handleChartStyles();
}
self.styles = {
style: [].concat(o.seriesStyles.slice(0, o.seriesStyles.length)),
hoverStyles: [].concat(o.seriesHoverStyles.slice(0, o.seriesHoverStyles.length))
};
self._initStyles();
}
if(key === "seriesList" || key === "seriesHoverStyles") {
hoverStyleLen = o.seriesHoverStyles.length;
for(idx = hoverStyleLen; idx < len; idx++) {
o.seriesHoverStyles[idx] = o.seriesHoverStyles[idx % hoverStyleLen];
}
}
// fixed an issue that if set height and width option,
// the chart element's height is not reset.
if(key === "height" || key === "width") {
self.chartElement[key](value);
}
self.redraw();
};
wijchartcore.prototype._preHandleSeriesData = function () {
};
wijchartcore.prototype._initStyles = function () {
var o = this.options, styles = o.seriesStyles, hoverStyles = o.seriesHoverStyles, stylesLen, seriesLen, hoverStylesLen, i;
if(o.seriesList) {
seriesLen = o.seriesList.length || 0;
}
if(o.seriesStyles) {
stylesLen = o.seriesStyles.length || 0;
}
if(o.seriesHoverStyles) {
hoverStylesLen = o.seriesHoverStyles.length || 0;
}
if(seriesLen > stylesLen && stylesLen) {
for(i = stylesLen; i < seriesLen; i++) {
styles[i] = styles[i % stylesLen];
}
}
if(seriesLen > hoverStylesLen && hoverStylesLen) {
for(i = hoverStylesLen; i < seriesLen; i++) {
hoverStyles[i] = hoverStyles[i % hoverStylesLen];
}
}
};
wijchartcore.prototype._create = function () {
var self = this, o = self.options, width = o.width || self.element.width(), height = o.height || self.element.height(), newEle = null, canvas;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
self.updating = 0;
self.innerState = {
};
self.axisCompass = {
};
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
self.redraw();
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
}, "wijchart");
}
// Add for parse date options for jUICE. D.H
// TO DO
if($.isFunction(window["wijmoASPNetParseOptions"])) {
window["wijmoASPNetParseOptions"](o);
}
// backup the styles. when drawed the charts, restore the styles.
// when postback the styles, if doesn't clone the styles,
// the serverside will get the extended styles. when the add a series data,
// the extend style will wrong.
self.styles = {
style: [].concat(o.seriesStyles.slice(0, o.seriesStyles.length)),
hoverStyles: [].concat(o.seriesHoverStyles.slice(0, o.seriesHoverStyles.length))
};
// Extend seriesStyle
self._initStyles();
if(o.hint && typeof o.hint.content === "string" && window[o.hint.content]) {
o.hint.content = window[o.hint.content];
}
if(o.hint && typeof o.hint.title === "string" && window[o.hint.title]) {
o.hint.title = window[o.hint.title];
}
self.headerEles = [];
self.footerEles = [];
self.legendEles = [];
self.axisEles = [];
self.legends = [];
self.legendIcons = [];
self.legendDots = [];
self.chartLabelEles = [];
self.seriesEles = [];
if(self.element.length > 0) {
if(self.element.is("table")) {
self._parseTable();
newEle = $("<div></div>");
if(width) {
newEle.css("width", width);
}
if(height) {
newEle.css("height", height);
}
self.element.after(newEle);
self.chartElement = newEle;
} else {
self.chartElement = self.element;
}
// end for bug 16039
self.chartElement.addClass("ui-widget");
// if fail to create canvas, move element to body and recreate it
// the issue that creating canvas in ie9 when element is invisible.
try {
canvas = Raphael(self.chartElement[0], width, height);
} catch (e) {
var displayCss = self.chartElement.css("display");
newEle = $("<div></div>").insertBefore(self.chartElement).append(self.chartElement);
self.chartElement.addClass("ui-helper-hidden-accessible").appendTo($('body'));
if(displayCss === "none") {
self.chartElement.css("display", "block");
}
canvas = Raphael(self.chartElement[0], width, height);
self.chartElement.appendTo(newEle).unwrap().removeClass("ui-helper-hidden-accessible");
if(displayCss === "none") {
self.chartElement.css("display", "none");
}
}
self.canvas = canvas;
//add comments to fix tfs issue 27816, if element's height is not set,
//element's height will be 4px larger than canvas's,
//so set height to element is height is 0;
if(height === 0 && o.height !== 0) {
self.element.height(canvas.height);
}
// end comments.
// add for fixing bug 16039 by wuhao 2011/7/7
if(o.disabled) {
self.disable();
}
// add custom attribute to canvas
// fixed the issue 20422 by dail on 2012-3-12, If user set
// rotation and scale. the transform will only effect on scale.
canvas.customAttributes.rotation = function (num) {
//return {transform: "...R" + num};
this.transform("...R" + num);
};
canvas.customAttributes.scale = function (num) {
//return {transform: "...S" + num};
this.transform("...S" + num);
};
canvas.customAttributes.translation = function (x, y) {
//return {transform: Raphael.format("...T{0},{1}", x, y)};
this.transform(Raphael.format("...T{0},{1}", x, y));
};
// end
self._bindLiveEvents();
}
};
wijchartcore.prototype._handleChartStyles = function () {
this._extendArrayFromBase("seriesStyles");
this._extendArrayFromBase("seriesHoverStyles");
var o = this.options, defFill = this._getDefFill();
$.each(o.seriesStyles, function (idx, style) {
if(!style.fill) {
style.fill = defFill[idx];
}
});
};
wijchartcore.prototype._extendArrayFromBase = function (optionName) {
var result = $.extend(true, {
}, wijchartcore.prototype.options[optionName], this.options[optionName]), newArr = [];
$.each(result, function (i, n) {
newArr.push(n);
});
this.options[optionName] = newArr;
};
wijchartcore.prototype._getDefFill = function () {
var defFill = [
"#00cc00",
"#0099cc",
"#0055cc",
"#2200cc",
"#8800cc",
"#d9007e",
"#ff0000",
"#ff6600",
"#ff9900",
"#ffcc00",
"#ffff00",
"#ace600"
];
return defFill;
};
wijchartcore.prototype._getCulture = function (name) {
return Globalize.findClosestCulture(name || this.options.culture);
};
wijchartcore.prototype._handleDisabledOption = function (disabled, element) {
var self = this;
if(disabled) {
if(!self.disabledDiv) {
self.disabledDiv = self._createDisabledDiv(element);
}
self.disabledDiv.appendTo("body");
} else {
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
}
};
wijchartcore.prototype._createDisabledDiv = function (outerEle) {
var self = this, o = self.options, ele = // Change your outerelement here
outerEle || self.element, eleOffset = ele.offset(), disabledWidth = o.width || ele.outerWidth(), disabledHeight = o.height || ele.outerHeight(), disabledDiv;
disabledDiv = $("<div></div>").css({
"z-index": "99999",
position: "absolute",
width: disabledWidth,
height: disabledHeight,
left: eleOffset.left,
top: eleOffset.top
});
if(Raphael.vml) {
disabledDiv.addClass(o.wijCSS.stateDisabled).css("background-color", "#fff");
}
return disabledDiv;
};
wijchartcore.prototype._bindData = function () {
var self = this, o = self.options, dataSource = o.dataSource, seriesList = o.seriesList, shareData = o.data, sharedXList;
$.each(seriesList, function (i, series) {
var data = series.data, dataX, dataY, dataY1, ds = series.dataSource || dataSource;
if(ds && data) {
dataX = data.x;
dataY = data.y;
dataY1 = data.y1;
if(dataX && dataX.bind) {
data.x = self._getBindData(ds, dataX.bind);
} else if(shareData && shareData.x && shareData.x.bind) {
if(sharedXList === undefined) {
sharedXList = self._getBindData(ds, shareData.x.bind);
}
data.x = sharedXList;
}
if(dataY && dataY.bind) {
data.y = self._getBindData(ds, dataY.bind);
}
if(dataY1 && dataY1.bind) {
data.y1 = self._getBindData(ds, dataY1.bind);
}
}
});
};
wijchartcore.prototype._getBindData = function (dataSource, bind) {
if($.isArray(dataSource)) {
var arr = [];
$.each(dataSource, function (i, data) {
if(data && data[bind] !== undefined) {
arr.push(data[bind]);
}
});
return arr;
}
return null;
};
wijchartcore.prototype._hanldSharedXData = function () {
var self = this, o = self.options, seriesList = o.seriesList, data = o.data;
if(data) {
$.each(seriesList, function (i, series) {
var d = series.data;
if(d.x === undefined || d.x === null && $.isArray(data.x)) {
d.x = data.x;
}
});
}
};
wijchartcore.prototype._init = function () {
var self = this, o = self.options;
// back up the seriesList
if(!self.rendered) {
self.seriesList = $.arrayClone(o.seriesList);
}
// bind dataSource
self._bindData();
self._hanldSharedXData();
$.each(o.seriesList, function (i, series) {
var data = series.data, idx;
if(typeof data === 'undefined' || data === null) {
idx = $.inArray(series, o.seriesList);
o.seriesList.splice(idx, 1);
}
});
/*
* o.seriesList = $.grep(o.seriesList, function(series, i) { var
* data = series.data; if (typeof data === 'undefined' || data ===
* null) { return false; } return true; });
*/
if(!self.rendered) {
self._paint();
}
//super._init();
};
wijchartcore.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this, o = self.options;
self._unbindLiveEvents();
self._clearChartElement();
self.chartElement.removeClass("ui-widget");
$("." + o.wijCSS.canvasObject, self.chartElement[0]).off(self.widgetName).off(// for jQuery 1.7.1
"." + self.widgetName);
if(self.element !== self.chartElement) {
self.chartElement.remove();
}
self.element.empty();
if(self.styles) {
self.styles = null;
}
// Add for fixing bug 16039
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
// end for bug 16039
_super.prototype.destroy.call(this);
};
wijchartcore.prototype.getCanvas = /**
* Returns a reference to the Raphael canvas object.
* @returns {Raphael} Reference to raphael canvas object.
* @example
* $("#chartcore").wijchartcore("getCanvas")
*/
function () {
return this.canvas;
};
wijchartcore.prototype.addSeriesPoint = /**
* Add series point to the series list.
* @param {number} seriesIndex The index of the series that the point will be inserted to.
* @param {object} point The point that will be inserted to.
* @param {Boolean} shift A value that indicates whether to shift the first point.
*/
function (seriesIndex, point, shift) {
var seriesList = this.options.seriesList, series = null, data = null;
if(seriesIndex >= seriesList.length) {
return;
}
series = seriesList[seriesIndex];
data = series.data || [];
data.x.push(point.x);
data.y.push(point.y);
if(shift) {
data.x.shift();
data.y.shift();
}
this._setOption("seriesList", seriesList);
};
wijchartcore.prototype.beginUpdate = /**
* Suspend automatic updates to the chart while reseting the options.
*/
function () {
var self = this;
self.updating++;
};
wijchartcore.prototype.endUpdate = /**
* Restore automatic updates to the chart after the options has been reset.
*/
function () {
var self = this;
self.updating--;
self.redraw();
};
wijchartcore.prototype.redraw = /**
* This method redraws the chart.
* @param {?Boolean} drawIfNeeded A value that indicates whether to redraw the chart regardless of whether
* the chart already exists. If true, then the chart is redrawn only if it was not already created. If false,
* then the chart is redrawn, even if it already exists.
*/
function (drawIfNeeded) {
var self = this, o = self.options, width = 0, height = 0;
if(self.updating > 0) {
return;
}
if(drawIfNeeded && self.rendered) {
return;
}
width = o.width || self.element.width();
height = o.height || self.element.height();
if(width < 1 || height < 1) {
return;
}
self.canvas.setSize(width, height);
self._paint();
};
wijchartcore.prototype._parseTable = function () {
if(!this.element.is("table")) {
return;
}
var self = this, ele = self.element, o = self.options, captions = // header & footer
$("caption", ele), theaders = $("thead th", ele), seriesList = [], sList = $("tbody tr", ele);
if(captions.length) {
o.header = $.extend({
visible: true,
text: $.trim($(captions[0]).text())
}, o.header);
if(captions.length > 1) {
o.footer = $.extend({
visibel: true,
text: $.trim($(captions[1]).text())
}, o.footer);
}
}
// legend
o.legend = $.extend({
visible: true
}, o.legend);
self._getSeriesFromTR(theaders, sList, seriesList);
self.options.seriesList = seriesList;
};
wijchartcore.prototype._getSeriesFromTR = function (theaders, sList, seriesList) {
var valuesX = [], val = null, series = null;
// seriesList
if(theaders.length) {
theaders.each(function () {
val = $.trim($(this).text());
valuesX.push(val);
});
}
if(sList.length) {
sList.each(function () {
var th = $("th", $(this)), label = $.trim(th.text()), valuesY = [], tds = $("td", $(this));
if(tds.length) {
tds.each(function (idx, ele) {
var td = $(this);
valuesY.push(parseFloat($.trim(td.text())));
});
}
series = {
label: label,
legendEntry: true,
data: {
x: valuesX,
y: valuesY
}
};
seriesList.push(series);
});
}
};
wijchartcore.prototype._destroyRaphaelArray = function (objs) {
if(!objs) {
return;
}
var len = objs.length, i = 0, ele, obj;
for(; len && i < len; i++) {
ele = objs[i];
if(ele && ele[0]) {
obj = $(ele.node);
obj.unbind().removeData();
ele.wijRemove();
obj.remove();
obj = null;
}
objs[i] = null;
}
};
wijchartcore.prototype._clearChartElement = function () {
var self = this, fields = self.chartElement.data("fields");
self._destroyRaphaelArray(self.headerEles);
self._destroyRaphaelArray(self.footerEles);
self._destroyRaphaelArray(self.legendEles);
self._destroyRaphaelArray(self.legends);
self._destroyRaphaelArray(self.legendIcons);
self._destroyRaphaelArray(self.legendDots);
self._destroyRaphaelArray(self.axisEles);
self._destroyRaphaelArray(self.chartLabelEles);
if(self.tooltip) {
self.tooltip.destroy();
self.tooltip = null;
}
self.dataPoints = null;
self.pointXs = null;
if(fields && fields.trackers) {
self._destroyRaphaelArray(fields.trackers);
fields.trackers = null;
}
self.headerEles = [];
self.footerEles = [];
self.legendEles = [];
self.legends = [];
self.legendIcons = [];
self.legendDots = [];
self.axisEles = [];
self.chartLabelEles = [];
if(fields && fields.chartElements) {
$.each(fields.chartElements, function (key, eles) {
self._destroyRaphaelArray(eles);
});
fields.chartElements = null;
}
if(fields && fields.seriesEles) {
fields.seriesEles = null;
}
if(self.seriesEles) {
self.seriesEles = [];
}
self.canvas.clear();
self.innerState = null;
self.axisInfo = null;
self.seriesGroup = null;
self.lastAxisOffset = null;
self.innerState = {
};
};
wijchartcore.prototype._text = function (x, y, text) {
var textElement = this.canvas.text(x, y, text);
if(this.options.disableDefaultTextStyle) {
textElement.node["style"].cssText = "";
}
return textElement;
};
wijchartcore.prototype._paint = function () {
var self = this, o = self.options, element = self.element, hidden = element.css("display") === "none" || element.css("visibility") === "hidden", oldLeft = {
}, oldPosition = null;
// ev = $.Event("beforepaint");
if(hidden) {
oldLeft = element.css("left");
oldPosition = element.css("position");
element.css("left", "-10000px");
element.css("position", "absolute");
element.show();
}
if(element.is(":hidden")) {
if(hidden) {
element.css("left", oldLeft);
element.css("position", oldPosition);
element.hide();
}
return;
}
self._clearChartElement();
if(self._trigger("beforePaint") === false) {
return;
}
// self._trigger("beforepaint", ev);
self._preHandleSeriesData();
self.canvasBounds = {
startX: 0,
endX: o.width || element.width(),
startY: 0,
endY: o.height || element.height()
};
self._paintHeader();
self._paintFooter();
self._paintLegend();
self._paintChartArea();
//self._paintChartLabels();
if(o.indicator && o.indicator.visible) {
if(this.pointXs) {
this.pointXs = this.pointXs.sort(function (a, b) {
return a - b;
});
}
}
self._paintTooltip();
self._trigger("painted");
self.rendered = true;
// restore the backup options.
if(self.styles) {
o.seriesStyles = self.styles.style;
o.seriesHoverStyles = self.styles.hoverStyles;
}
//$.wijraphael.clearRaphaelCache();
if(hidden) {
element.css("left", oldLeft);
element.css("position", oldPosition);
element.hide();
}
};
wijchartcore.prototype._paintIndicater = // indicator tooltip
function () {
};
wijchartcore.prototype._calculatePosition = function (compass, width, height) {
var point = {
x: 0,
y: 0
}, marginX = 5, marginY = 5, canvasBounds = this.canvasBounds;
switch(compass) {
case "north":
point.x = (canvasBounds.endX - canvasBounds.startX) / 2;
point.y = canvasBounds.startY + height / 2 + marginY;
canvasBounds.startY = canvasBounds.startY + marginY * 2 + height;
break;
case "south":
point.x = (canvasBounds.endX - canvasBounds.startX) / 2;
point.y = canvasBounds.endY - height / 2 - marginY;
canvasBounds.endY = canvasBounds.endY - marginY * 2 - height;
break;
case "east":
point.x = canvasBounds.endX - width / 2 - marginX;
point.y = (canvasBounds.endY - canvasBounds.startY) / 2;
canvasBounds.endX = canvasBounds.endX - marginX * 2 - width;
break;
case "west":
point.x = canvasBounds.startX + width / 2 + marginX;
point.y = (canvasBounds.endY - canvasBounds.startY) / 2;
canvasBounds.startX = canvasBounds.startX + marginX * 2 + width;
break;
}
return point;
};
wijchartcore.prototype._paintHeader = function () {
var headerMargin = 2, self = this, o = self.options, header = o.header, compass = null, headerText = null, textStyle = null, bBox = null, point = null, box = null, rotation = 0, headerContainer = null;
if(header.text && header.text.length > 0 && header.visible) {
compass = header.compass;
headerText = self._text(0, 0, header.text);
$.wijraphael.addClass($(headerText.node), o.wijCSS.headerText);
// update for fixing bug 15884 at 2011/7/5
// textStyle = $.extend(true, {}, o.textStyle,
// header.textStyle);
rotation = self._getRotationByCompass(compass);
textStyle = $.extend(true, {
}, o.textStyle, header.textStyle);
// end for fixing bug 15884.
headerText.attr(textStyle);
headerText.transform("...R" + rotation);
bBox = headerText.wijGetBBox();
point = self._calculatePosition(compass, bBox.width, bBox.height);
// headerText.translate(point.x, point.y);
headerText.transform(Raphael.format("...T{0},{1}", point.x, point.y));
box = headerText.wijGetBBox();
headerContainer = self.canvas.rect(box.x - headerMargin, box.y - headerMargin, box.width + 2 * headerMargin, box.height + 2 * headerMargin);
$.wijraphael.addClass($(headerContainer.node), o.wijCSS.headerContainer);
headerContainer.attr(header.style);
headerContainer.toBack();
self.headerEles.push(headerText);
self.headerEles.push(headerContainer);
}
};
wijchartcore.prototype._paintFooter = function () {
var footerMargin = 2, self = this, o = self.options, footer = o.footer, compass = null, footerText = null, textStyle = null, bBox = null, point = null, box = null, rotation = 0, footerContainer = null;
if(footer.text && footer.text.length > 0 && footer.visible) {
compass = footer.compass;
footerText = self._text(0, 0, footer.text);
$.wijraphael.addClass($(footerText.node), o.wijCSS.footerText);
// update for fixing bug 15884 at 2011/7/5
// textStyle = $.extend(true, {}, o.textStyle,
// footer.textStyle);
rotation = self._getRotationByCompass(compass);
textStyle = $.extend(true, {
}, o.textStyle, footer.textStyle);
// end for fixing bug 15884
footerText.attr(textStyle);
footerText.transform("...R" + rotation);
bBox = footerText.wijGetBBox();
point = self._calculatePosition(compass, bBox.width, bBox.height);
// footerText.translate(point.x, point.y);
footerText.transform(Raphael.format("...T{0},{1}", point.x, point.y));
box = footerText.wijGetBBox();
footerContainer = self.canvas.rect(box.x - footerMargin, box.y - footerMargin, box.width + 2 * footerMargin, box.height + 2 * footerMargin);
$.wijraphael.addClass($(footerContainer.node), o.wijCSS.footerContainer);
footerContainer.attr(footer.style);
footerContainer.toBack();
self.footerEles.push(footerText);
self.footerEles.push(footerContainer);
}
};
wijchartcore.prototype._getRotationByCompass = function (compass) {
var rotation = 0;
if(compass === "east") {
rotation = 90;
} else if(compass === "west") {
rotation = -90;
}
return rotation;
};
wijchartcore.prototype._paintLegendIcon = function (x, y, width, height, style, legendIndex, seriesIndex, legendCss, series, leg) {
var self = this, icon = self.canvas.rect(x, y, width, height);
$(icon.node).data("legendIndex", legendIndex).data("index", seriesIndex);
self.legendIcons.push(icon);
if(style) {
icon.attr(style);
}
$.wijraphael.addClass($(icon.node), legendCss);
return icon;
};
wijchartcore.prototype._paintLegend = function () {
if(!this.options.legend.visible) {
return;
}
var self = this, o = self.options, legend = $.extend(true, {
size: {
width: 22,
height: 10
}
}, o.legend), legendMargin = 2, seriesStyles = o.seriesStyles, tempSeriesList = [].concat(o.seriesList), compass = legend.compass, orientation = legend.orientation, legendTitle, textStyle, legendLen, textMargin, canvasBounds = self.canvasBounds, canvasWidth = canvasBounds.endX - canvasBounds.startX, canvasHeight = canvasBounds.endY - canvasBounds.startY, iconWidth = legend.size.width, iconHeight = legend.size.height, titleBox, titleHeight = 0, titleWidth = 0, maxWidth = 0, maxHeight = 0, totalWidth = 0, totalHeight = 0, columnNum = 1, rowNum = 0, width = 0, height = 0, offsetY = 0, index = 0, point, left, top, legendContainer, legendIconStyles = [], idx = 0, legendIndex = 0, totalLengedLength = 0, legendSeries = [];
if(legend.text && legend.text.length) {
legendTitle = self._text(0, 0, legend.text);
$.wijraphael.addClass($(legendTitle.node), o.wijCSS.legendTitle);
textStyle = $.extend(true, {
}, o.textStyle, legend.textStyle, legend.titleStyle);
legendTitle.attr(textStyle);
self.legendEles.push(legendTitle);
}
if(legend.reversed) {
tempSeriesList = tempSeriesList.reverse();
}
// fixed an issue that if the chart is compositechart, and if it contains piechart,
// the pie is a single series. so the total legend length is not the seriesList's length.
totalLengedLength = tempSeriesList.length;
if(self.widgetName === "wijcompositechart") {
totalLengedLength = 0;
$.each(tempSeriesList, function (i, series) {
if(series.type === "pie") {
totalLengedLength += series.data.length;
} else {
totalLengedLength++;
}
});
}
$.each(tempSeriesList, function (i, series) {
// support hole.
series = $.extend(true, {
legendEntry: true,
display: "show"
}, series);
// series = $.extend(true, { legendEntry: true }, series);
// end comments.
function drawSeriesLegend(series) {
var index = legend.reversed ? totalLengedLength - 1 - idx : idx, seriesStyle = seriesStyles[index], chartStyle = $.extend(true, {
fill: "none",
opacity: 1,
stroke: "black"
}, seriesStyle), text, textStyle, chtStyle, isline = false, seriesType = series.type, icon;
// if (series.legendEntry) {
if(series.legendEntry && series.display !== "exclude") {
//text = self._text(0, 0, series.label);
//$.wijraphael.addClass($(text.node),
//"wijchart-legend-text wijchart-legend");
textStyle = $.extend(true, {
}, o.textStyle, legend.textStyle);
//text.attr(textStyle);
if(legend.textWidth) {
text = self.canvas.wrapText(0, 0, series.label, legend.textWidth, "far", textStyle);
} else {
text = self._text(0, 0, series.label);
text.attr(textStyle);
}
$.wijraphael.addClass($(text.node), o.wijCSS.legendText + " " + o.wijCSS.legend);
self.legends.push(text);
chtStyle = $.extend(chartStyle, {
"stroke-width": 1
});
//icon = self.canvas.rect(0, 0, iconWidth, iconHeight);
//$.wijraphael.addClass($(icon.node),
//o.wijCSS.legendIcon + " " + o.wijCSS.legend);
//icon.attr(chtStyle);
//self.legendIcons.push(icon);
legendIconStyles.push(chtStyle);
legendSeries.push(series);
if(self.widgetName === "wijcompositechart") {
isline = seriesType === "line" || seriesType === "spline" || seriesType === "bezier" || seriesType === "area";
} else {
isline = self.widgetName === "wijlinechart";
}
if(legend.textWidth) {
$.each(text, function (i, t) {
if(series.visible === false && !isline) {
$(t.node).data("hidden", true).data("textOpacity", t.attr("opacity") || 1);
t.attr("opacity", 0.3);
}
$.wijraphael.addClass($(t.node), o.wijCSS.legendText + " " + o.wijCSS.legend);
$(t.node).data("legendIndex", legendIndex).data("index", idx);
});
} else {
if(series.visible === false && !isline) {
$(text.node).data("hidden", true).data("textOpacity", text.attr("opacity") || 1);
text.attr("opacity", 0.3);
}
$.wijraphael.addClass($(text.node), o.wijCSS.legendText + " " + o.wijCSS.legend);
$(text.node).data("legendIndex", legendIndex).data("index", idx);
}
//$(text.node).data("legendIndex", legendIndex)
// .data("index", idx);
////$(icon.node).data("legendIndex", legendIndex)
//// .data("index", idx);
legendIndex++;
}
idx++;
}
if(series.type === "pie" && series.legendEntry) {
$.each(series.data, function (j, data) {
data = $.extend({
legendEntry: series.legendEntry
}, data);
drawSeriesLegend(data);
});
} else if(self._isPieChart()) {
//fix tfs issue 20705
drawSeriesLegend(series);
} else if(self._isStockChart() && self._validateSeriesData(series)) {
drawSeriesLegend(series);
} else {
if((series.data.x === undefined && series.data.xy === undefined) || (series.data.xy === undefined && series.data.y === undefined)) {
return true;
}
drawSeriesLegend(series);
}
});
legendLen = self.legends.length;
textMargin = legend.textMargin;
if(legendTitle) {
titleBox = legendTitle.wijGetBBox();
titleHeight = titleBox.height;
titleWidth = titleBox.width;
}
$.each(self.legends, function (idx, legend) {
var bBox = legend.wijGetBBox();
if(bBox.width > maxWidth) {
maxWidth = bBox.width;
}
if(bBox.height > maxHeight) {
maxHeight = bBox.height;
}
});
if(compass === "east" || compass === "west") {
if(orientation === "horizontal") {
totalWidth = legendLen * (maxWidth + iconWidth + legendMargin) + legendLen * (textMargin.left + textMargin.right);
if(totalWidth > canvasWidth / 2) {
columnNum = Math.floor(canvasWidth / 2 / maxWidth);
if(columnNum < 1) {
columnNum = 1;
}
} else {
columnNum = legendLen;
}
} else if(orientation === "vertical") {
totalHeight = maxHeight * legendLen + titleHeight + legendLen * (textMargin.top + textMargin.bottom);
if(totalHeight > canvasHeight) {
columnNum = Math.ceil(totalHeight / canvasHeight);
} else {
columnNum = 1;
}
}
} else if(compass === "south" || compass === "north") {
if(orientation === "horizontal") {
totalWidth = (maxWidth + iconWidth + legendMargin) * legendLen + legendLen * (textMargin.left + textMargin.right);
if(totalWidth > canvasWidth) {
columnNum = Math.floor(legendLen / totalWidth * canvasWidth);
if(columnNum < 1) {
columnNum = 1;
}
} else {
columnNum = legendLen;
}
} else if(orientation === "vertical") {
totalHeight = maxHeight * legendLen + titleHeight + legendLen * (textMargin.top + textMargin.bottom);
if(totalHeight > canvasHeight / 2) {
rowNum = Math.floor(canvasHeight - titleHeight) / 2 / maxHeight;
columnNum = Math.ceil(legendLen / rowNum);
} else {
columnNum = 1;
}
}
}
// Fixed issue 20405 by dail. If all series 's legendEntry set to false.
// and the compass set to south or north, the columnNum is zero.
if(columnNum === 0) {
columnNum = 1;
}
width = columnNum * (maxWidth + iconWidth + legendMargin) + columnNum * (textMargin.left + textMargin.right);
height = maxHeight * Math.ceil(legendLen / columnNum) + titleHeight + Math.ceil(legendLen / columnNum) * (textMargin.top + textMargin.bottom);
//fix tfs 20705
width = width > titleWidth ? width : titleWidth;
//end comments
point = self._calculatePosition(compass, width, height);
left = point.x - width / 2;
top = point.y - height / 2;
legendContainer = self.canvas.rect(left - legendMargin, top - legendMargin, width + 2 * legendMargin, height + 2 * legendMargin);
$.wijraphael.addClass($(legendContainer.node), o.wijCSS.legendContainer);
legendContainer.attr(legend.style);
legendContainer.toBack();
self.legendEles.push(legendContainer);
if(legendTitle) {
// legendTitle.translate(left + width / 2, top + titleHeight /
// 2);
legendTitle.transform(Raphael.format("...T{0},{1}", left + width / 2, top + titleHeight / 2));
}
offsetY = titleHeight;
$.each(self.legends, function (idx, leg) {
chtStyle = legendIconStyles[idx];
var bBox = leg.wijGetBBox(), icon, strokeWidth = //icon = self.legendIcons[idx],
// if the icon has an stroke-width,
// the width / height is not the same as the bbox
chtStyle["stroke-width"] || 0, x = left + index * (iconWidth + strokeWidth * 2 + maxWidth + legendMargin) + (index + 1) * textMargin.left + index * textMargin.right, y = top + offsetY + bBox.height / 2 + textMargin.top + maxHeight / 2 - bBox.height / 2, iconY = y - iconHeight / 2 - strokeWidth, chtStyle, legCover, leg0 = leg;
// icon.translate(x, y - icon.wijGetBBox().height / 2);
// icon.transform(Raphael.format("...T{0},{1}", x, y -
// icon.wijGetBBox().height / 2));
//icon.wijRemove();
//icon = null;
//icon = self.canvas.rect(x, iconY, iconWidth, iconHeight);
if(legend.textWidth) {
leg0 = leg[0];
}
//$(icon.node).data("legendIndex", $(leg0.node).data("legendIndex"))
// .data("index", $(leg0.node).data("index"));
//$(icon.node).data("index", seriesIdx);
//$.wijraphael.addClass($(icon.node),
//o.wijCSS.legendIcon + " " + o.wijCSS.legend);
//self.legendIcons[idx] = icon;
icon = self._paintLegendIcon(x, iconY, iconWidth, iconHeight, chtStyle, $(leg0.node).data("legendIndex"), $(leg0.node).data("index"), o.wijCSS.legendIcon + " " + o.wijCSS.legend, legendSeries[$(leg0.node).data("legendIndex")], leg0);
if($(leg0.node).data("hidden") === true) {
$(leg0.node).data("iconOpacity", icon.attr("opacity") || 1);
icon.attr("opacity", 0.3);
}
if(legend.textStyle["text-anchor"] === "start") {
x -= bBox.width / 2;
}
// leg.translate(x + iconWidth + legendMargin + bBox.width / 2,
// y);
if(legend.textWidth) {
leg.transform(Raphael.format("...T{0},{1}", x + iconWidth + legendMargin, y - bBox.height / 2));
} else {
leg.transform(Raphael.format("...T{0},{1}", x + iconWidth + legendMargin + bBox.width / 2, y));
}
//It's hard to click the text in vml,
// so add a rect to cover it for clicking.
if(Raphael.vml) {
legCover = self.canvas.rect(x + iconWidth + legendMargin, y - bBox.height / 2, bBox.width, bBox.height).attr({
stroke: "none",
fill: "#000000",
opacity: 0.01
});
$.wijraphael.addClass($(legCover.node), o.wijCSS.legendTextCover + " " + o.wijCSS.legend);
$(legCover.node).data("legendIndex", $(leg0.node).data("legendIndex"));
$(legCover.node).data("index", $(leg0.node).data("index"));
self.legendEles.push(legCover);
}
//end
leg.toFront();
//$(leg.node).data("index", seriesIdx);
index++;
if(index === columnNum) {
index = 0;
offsetY += maxHeight + textMargin.top + textMargin.bottom;
}
});
};
wijchartcore.prototype._getLegendStyle = function (seriesStyle) {
return seriesStyle;
};
wijchartcore.prototype._hasAxes = function () {
if(this.widgetName === "wijpiechart") {
return false;
}
return true;
};
wijchartcore.prototype._applyAxisText = function (axisOptions, axisInfo) {
var self = this, text = axisOptions.text, textBounds = null, tempText = null, textStyle = null, textMarginVer = 0, textMarginHor = 0, canvasBounds = axisInfo.bounds || self.canvasBounds;
if(text !== null && text !== undefined && text.length > 0) {
tempText = self._text(-100, -100, text);
textStyle = $.extend(true, {
}, self.options.textStyle, axisOptions.textStyle);
tempText.attr(textStyle);
textBounds = tempText.wijGetBBox();
if(textStyle["margin-left"]) {
textMarginHor += parseFloat(textStyle["margin-left"]);
}
if(textStyle["margin-top"]) {
textMarginVer += parseFloat(textStyle["margin-top"]);
}
if(textStyle["margin-right"]) {
textMarginHor += parseFloat(textStyle["margin-right"]);
}
if(textStyle["margin-bottom"]) {
textMarginVer += parseFloat(textStyle["margin-bottom"]);
}
switch(axisOptions.compass) {
case "north":
canvasBounds.startY += (textBounds.height + textMarginVer);
break;
case "south":
canvasBounds.endY -= (textBounds.height + textMarginVer);
break;
case "east":
canvasBounds.endX -= (textBounds.height + textMarginHor);
break;
case "west":
canvasBounds.startX += (textBounds.height + textMarginHor);
break;
}
tempText.wijRemove();
tempText = null;
}
return textBounds;
};
wijchartcore.prototype._isSeriesDataEmpty = function () {
var self = this, sl = self.options.seriesList;
if(!sl || sl.length === 0) {
return true;
}
$.each(sl, function (idx, s) {
if(!s.data || ((!s.data.x || !s.data.y) && !s.data.xy)) {
return true;
}
});
return false;
};
wijchartcore.prototype._setTooltipContent = function (obj) {
var self = this, tooltipObjs, title, content, tooltip = self.tooltip, hintOptions, newOptions = {
}, hint = self.options.hint, isFunction = $.isFunction;
if(tooltip) {
// if the chart is line chart or compositechart, the data.x value is the marker position.
// change the value to the x value.
tooltipObjs = [];
$.each(obj, function (i, tooltipObj) {
var valX = tooltipObj.valX, valY = tooltipObj.valY;
if(valX && valY) {
tooltipObjs.push($.extend({
}, tooltipObj, {
x: valX,
y: valY
}));
} else {
tooltipObjs.push(tooltipObj);
}
});
hintOptions = tooltip.getOptions();
title = hint.title;
content = hint.content;
if(isFunction(title)) {
newOptions.title = function () {
return title.call(tooltipObjs);
};
}
if(isFunction(content)) {
newOptions.content = function () {
return content.call(tooltipObjs);
};
}
tooltip.setOptions(newOptions);
}
};
wijchartcore.prototype._setTooltip = function () {
var self = this, o = self.options, tooltip = self.tooltip, obj;
if(tooltip) {
obj = {
closeBehavior: "none",
style: {
stroke: o.indicator.style.stroke
},
animated: false,
showDelay: 0,
hideDelay: 0,
windowCollisionDetection: "fit",
beforeShowing: function (e, d) {
if(this.target && self.indicatorLine) {
return false;
}
}
};
if(o.horizontal) {
obj.compass = "east";
}
tooltip.setOptions(obj);
}
};
wijchartcore.prototype._resetTooltip = // when mouse up in plot area, reset the tooltip options.
function () {
var self = this, o = self.options, hint = o.hint, title = hint.title, content = hint.content, tooltip = self.tooltip, isFunction = $.isFunction, obj = $.extend(true, {
}, this.options.hint);
if(tooltip) {
obj.animated = hint.animated;
obj.showDelay = hint.showDelay;
obj.hideDelay = hint.hideDelay;
obj.title = hint.title;
obj.content = hint.content;
obj.closeBehavior = hint.closeBehavior || "auto";
obj.windowCollisionDetection = "fit";
if(isFunction(title)) {
obj.title = function () {
return self._getTooltipText(title, this.target);
};
}
if(isFunction(content)) {
obj.content = function () {
return self._getTooltipText(content, this.target);
};
}
obj.beforeShowing = function () {
self._onBeforeTooltipShowing(this);
};
tooltip.setOptions(obj);
}
};
wijchartcore.prototype._fotmatTooltip = function (val) {
var self = this;
if(self._isDate(val)) {
return Globalize.format(val, "f", self._getCulture());
} else if(!isNaN(val)) {
return Globalize.format(parseFloat(val), "n", self._getCulture());
} else {
return val;
}
};
wijchartcore.prototype._paintTooltip = function () {
var self = this, o = self.options, hint = o.hint, hintEnable = !o.disabled && hint.enable, hintEx = hint, title, content, isFunction = $.isFunction;
if(hintEnable && !self.tooltip) {
hintEx = $.extend(true, {
}, hint, {
});
// closeBehavior: "none",
// triggers: "custom"
title = hint.title;
content = hint.content;
// set default hint.
if(!content) {
content = hint.content = function () {
var label;
if($.isArray(this)) {
var str = "";
$.each(this, function (i, data) {
label = data.label;
if(data.lineSeries && data.lineSeries.label) {
label = data.lineSeries.label;
}
str += label + ":" + self._fotmatTooltip(data.y) + "\n";
});
return str;
} else {
label = this.label;
if(this.lineSeries && this.lineSeries.label) {
label = this.lineSeries.label;
}
return label + ":" + self._fotmatTooltip(this.y);
}
};
}
if(isFunction(title)) {
hintEx.title = function () {
return self._getTooltipText(title, this.target);
};
}
if(isFunction(content)) {
hintEx.content = function () {
return self._getTooltipText(content, this.target);
};
}
hintEx.beforeShowing = function () {
self._onBeforeTooltipShowing(this);
};
self.tooltip = new ChartTooltip(self.canvas, null, hintEx);
}
};
wijchartcore.prototype._getTooltipText = function (fmt, target) {
var dataObj = $(target.node).data("wijchartDataObj"), obj = {
data: dataObj,
label: dataObj.label,
x: dataObj.x,
y: dataObj.y,
target: target,
fmt: fmt
};
return $.proxy(fmt, obj)();
};
wijchartcore.prototype._onBeforeTooltipShowing = function (tooltip) {
var target = tooltip.target, hintStyle = this.options.hint.style;
if(target) {
tooltip.options.style.stroke = hintStyle.stroke || target.attrs.stroke || target.attrs.fill;
}
};
wijchartcore.prototype._paintChartArea = function () {
var self = this, o = self.options, axisOption = o.axis, axisTextOffset = // The value is used to offset the tick major
// text from the tick rect.
2, xTextBounds = null, yTextBounds = null, extremeValue = {
}, maxtries = 5, offsetX = 0, offsetY = 0, isMultiYAxis = $.isArray(axisOption.y), yAxisCount = 0, yIdx, yaxisOpt, key;
self._applyMargins();
self.isMultiYAxis = isMultiYAxis;
if(self._isSeriesDataEmpty()) {
return;
}
if(isMultiYAxis) {
$.each(axisOption.y, function (i, yaxis) {
axisOption.y[i] = $.extend(true, {
alignment: "center",
style: {
stroke: "#999999",
"stroke-width": 0.5
},
visible: false,
textVisible: true,
text: "",
textStyle: {
fill: "#888",
"font-size": 15,
"font-weight": "bold"
},
labels: {
style: {
fill: "#333",
"font-size": 11
},
textAlign: "center",
width: null
},
compass: "west",
autoMin: true,
autoMax: true,
min: null,
max: null,
origin: null,
autoMajor: true,
autoMinor: true,
unitMajor: null,
unitMinor: null,
gridMajor: {
visible: true,
style: {
stroke: "#999999",
"stroke-width": "0.5",
"stroke-dasharray": "none"
}
},
gridMinor: {
visible: false,
style: {
stroke: "#CACACA",
"stroke-dasharray": "- "
}
},
tickMajor: {
position: "none",
style: {
fill: "black"
},
factor: 1
},
tickMinor: {
position: "none",
style: {
fill: "black"
},
factor: 1
},
annoMethod: "values",
annoFormatString: "",
valueLabels: []
}, yaxis);
});
}
if(self._hasAxes()) {
// Restore from cache.
if(self.innerState.axisInfo) {
self.axisInfo = self.innerState.axisInfo;
self.canvasBounds = self.innerState.canvasBounds;
} else {
xTextBounds = self._applyAxisText(axisOption.x, {
});
self.axisInfo = {
x: {
id: "x",
tprec: 0,
isTime: false,
offset: 0,
vOffset: 0,
max: 0,
min: 0,
majorTickRect: null,
minorTickRect: null,
annoFormatString: null,
textBounds: xTextBounds,
axisTextOffset: axisTextOffset,
autoMax: true,
autoMin: true,
autoMajor: true,
autoMinor: true,
annoMethod: axisOption.x.annoMethod,
valueLabels: axisOption.x.valueLabels || []
},
y: {
}
};
self.axisCompass[axisOption.x.compass] = true;
if(isMultiYAxis) {
$.each(axisOption.y, function (i, axisY) {
yTextBounds = self._applyAxisText(axisY, {
});
self.axisInfo.y[i.toString()] = {
id: "y" + i,
tprec: 0,
isTime: false,
offset: 0,
vOffset: 0,
max: 0,
min: 0,
majorTickRect: null,
minorTickRect: null,
annoFormatString: null,
textBounds: yTextBounds,
axisTextOffset: axisTextOffset,
autoMax: true,
autoMin: true,
autoMajor: true,
autoMinor: true,
annoMethod: axisY.annoMethod,
valueLabels: axisY.valueLabels || []
};
if(!self.axisCompass[axisY.compass]) {
self.axisCompass[axisY.compass] = true;
}
});
} else {
yTextBounds = self._applyAxisText(axisOption.y, {
});
self.axisInfo.y["0"] = {
id: "y",
tprec: 0,
isTime: false,
offset: 0,
vOffset: 0,
max: 0,
min: 0,
majorTickRect: null,
minorTickRect: null,
annoFormatString: null,
textBounds: yTextBounds,
axisTextOffset: axisTextOffset,
autoMax: true,
autoMin: true,
autoMajor: true,
autoMinor: true,
annoMethod: axisOption.y.annoMethod,
valueLabels: axisOption.y.valueLabels || []
};
if(!self.axisCompass[axisOption.y.compass]) {
self.axisCompass[axisOption.y.compass] = true;
}
}
self._getSeriesGroup(isMultiYAxis);
extremeValue = self._getDataExtreme(isMultiYAxis);
self.extremeValue = extremeValue;
// handle x axis.
if(axisOption.x.autoMin && self.axisInfo.x.autoMin) {
axisOption.x.min = extremeValue.txn;
} else if(axisOption.x.min && self._isDate(axisOption.x.min)) {
// if is date time, convert to number.
axisOption.x.min = $.toOADate(axisOption.x.min);
}
if(axisOption.x.autoMax && self.axisInfo.x.autoMax) {
axisOption.x.max = extremeValue.txx;
} else if(axisOption.x.max && self._isDate(axisOption.x.max)) {
// if is date time, convert to number.
axisOption.x.max = $.toOADate(axisOption.x.max);
}
$.each(extremeValue.y, function (key, exval) {
yAxisCount++;
});
for(yIdx = 0; yIdx < (axisOption.y.length || 1); yIdx++) {
yaxisOpt = axisOption.y[yIdx] || axisOption.y;
key = yIdx.toString();
if(yaxisOpt.autoMin && self.axisInfo.y[key].autoMin && extremeValue.y[key]) {
yaxisOpt.min = extremeValue.y[key].tyn;
} else if(yaxisOpt.min && self._isDate(yaxisOpt.min)) {
// if is date time, convert to number.
yaxisOpt.min = $.toOADate(yaxisOpt.min);
}
if(yaxisOpt.autoMax && self.axisInfo.y[key].autoMax && extremeValue.y[key]) {
yaxisOpt.max = extremeValue.y[key].tyx || 0;
} else if(yaxisOpt.max && self._isDate(yaxisOpt.max)) {
// if is date time, convert to number.
yaxisOpt.max = $.toOADate(yaxisOpt.max);
}
do {
offsetY = self._autoPosition(self.axisInfo, axisOption, "y", key);
offsetX = self._autoPosition(self.axisInfo, axisOption, "x", key);
if(offsetY === self.axisInfo.y[key].offset && offsetX === self.axisInfo.x.offset) {
maxtries = 0;
break;
}
if(!isNaN(offsetX) && !isNaN(offsetY)) {
if(offsetY !== self.axisInfo.y[key].offset && offsetY !== 0) {
self.axisInfo.y[key].offset = offsetY;
self.axisInfo.y[key].vOffset = offsetX;
}
if(offsetX !== self.axisInfo.x.offset && offsetX !== 0) {
self.axisInfo.x.offset = offsetX;
self.axisInfo.x.vOffset = offsetY;
}
}
maxtries--;
}while(maxtries > 0);
}
self._adjustPlotArea(axisOption.x, self.axisInfo.x);
self._adjustPlotArea(axisOption.y, self.axisInfo.y, true);
self.innerState.axisInfo = self.axisInfo;
self.innerState.canvasBounds = self.canvasBounds;
}
self._paintAxes();
self._paintPlotArea();
} else {
self._paintPlotArea();
}
};
wijchartcore.prototype._getSeriesGroup = function (isMultiYAxis) {
var self = this, o = self.options, group = {
};
$.each(o.seriesList, function (i, serie) {
if(serie.yAxis && isMultiYAxis) {
if(group[serie.yAxis.toString()]) {
group[serie.yAxis.toString()].push(serie);
} else {
group[serie.yAxis.toString()] = [
serie
];
}
} else {
if(group["0"]) {
group["0"].push(serie);
} else {
group["0"] = [
serie
];
}
}
});
self.seriesGroup = group;
};
wijchartcore.prototype._adjustPlotArea = function (axisOptions, axisInfo, isYAxis) {
var canvasBounds = this.canvasBounds, maxKey, maxOffsets = {
east: Number.MIN_VALUE,
west: Number.MIN_VALUE,
south: Number.MIN_VALUE,
north: Number.MIN_VALUE
};
if(isYAxis) {
$.each(axisInfo, function (key, axisInf) {
maxKey = key;
});
$.each(axisInfo, function (key, axisInf) {
var opt = axisOptions[key] || axisOptions, compass = opt.compass;
opt.max = axisInf.max;
opt.min = axisInf.min;
switch(compass) {
case "north":
maxOffsets.north = Math.max(axisInf.offset, maxOffsets.north);
break;
case "south":
maxOffsets.south = Math.max(axisInf.offset, maxOffsets.south);
break;
case "east":
maxOffsets.east = Math.max(axisInf.offset, maxOffsets.east);
break;
case "west":
maxOffsets.west = Math.max(axisInf.offset, maxOffsets.west);
break;
}
});
if(maxOffsets.north !== Number.MIN_VALUE) {
canvasBounds.startY += maxOffsets.north;
}
if(maxOffsets.south !== Number.MIN_VALUE) {
canvasBounds.endY -= maxOffsets.south;
}
if(maxOffsets.east !== Number.MIN_VALUE) {
canvasBounds.endX -= maxOffsets.east;
}
if(maxOffsets.west !== Number.MIN_VALUE) {
canvasBounds.startX += maxOffsets.west;
}
} else {
axisOptions.max = axisInfo.max;
axisOptions.min = axisInfo.min;
switch(axisOptions.compass) {
case "north":
canvasBounds.startY += axisInfo.offset;
break;
case "south":
canvasBounds.endY -= axisInfo.offset;
break;
case "east":
canvasBounds.endX -= axisInfo.offset;
break;
case "west":
canvasBounds.startX += axisInfo.offset;
break;
}
}
};
wijchartcore.prototype._autoPosition = function (axisInfo, axisOptions, dir, key) {
// this._adjustCartesianCompass();
// base._autoPosition();
return this._autoPositionCartesianAxis(axisInfo, axisOptions, dir, key);
};
wijchartcore.prototype._autoPositionCartesianAxis = function (axisInfo, axisOptions, dir, key) {
var self = this, extent = null, innerAxisInfo, innerAxisOptions, oppositeAxisInfo, oppositeAxisOptions, compass, origin, max, min, lastAxisOffset = //bounds = self.canvasBounds,
//oppositeDir = dir === "x" ? "y" : "x",
self.lastAxisOffset || {
}, offset, lastOffset;
//origin = axisOptions[oppositeDir].origin,
//max = axisInfo[oppositeDir].max,
//min = axisInfo[oppositeDir].min,
//d = 0,
if(dir === "y") {
innerAxisInfo = axisInfo.y[key];
innerAxisOptions = axisOptions.y[key] || axisOptions.y;
oppositeAxisOptions = axisOptions.x;
oppositeAxisInfo = axisInfo.x;
} else {
innerAxisInfo = axisInfo.x;
innerAxisOptions = axisOptions.x;
oppositeAxisInfo = axisInfo.y[key];
oppositeAxisOptions = axisOptions.y[key] || axisOptions.y;
}
compass = innerAxisOptions.compass;
origin = oppositeAxisOptions.origin;
max = oppositeAxisInfo.max;
min = oppositeAxisInfo.min;
if(origin !== null && self._isDate(origin)) {
origin = $.toOADate(origin);
}
self._calculateParameters(innerAxisInfo, innerAxisOptions);
extent = self._getMaxExtents(innerAxisInfo, innerAxisOptions);
switch(compass) {
case "north":
case "south":
offset = extent.height;
innerAxisInfo.maxExtent = offset;
//
// if (origin !== null && origin >= min && origin <= max) {
// if (compass === "south") {
// d = (origin - min) / (max - min) * (bounds.endY - bounds.startY);
// } else {
// d = (max - origin) / (max - min) * (bounds.endY - bounds.startY);
// }
// offset -= d;
// if (offset < 0) {
// offset = 0;
// }
// }
break;
case "east":
case "west":
offset = extent.width;
innerAxisInfo.maxExtent = offset;
// if (origin !== null && origin >= min && origin <= max) {
// if (compass === "west") {
// d = (origin - min) / (max - min) * (bounds.endX - bounds.startX);
// } else {
// d = (max - origin) / (max - min) * (bounds.endX - bounds.startX);
// }
// offset -= d;
// if (offset < 0) {
// offset = 0;
// }
// }
break;
}
if(dir === "y" && lastAxisOffset[compass]) {
$.each(lastAxisOffset[compass], function (k, offsetObj) {
if(k !== key) {
lastOffset = offsetObj;
}
});
if(lastOffset && !innerAxisInfo.isPartAxis) {
innerAxisInfo.preStartOffset = lastOffset;
offset += (lastOffset);
}
}
if(dir === "y") {
if(lastAxisOffset[compass] === undefined) {
lastAxisOffset[compass] = {
};
}
lastAxisOffset[compass][key] = offset + self._getAxisLabelBox(innerAxisOptions).width;
self.lastAxisOffset = lastAxisOffset;
}
return offset;
};
wijchartcore.prototype._getAxisLabelBox = function (axisOption) {
var self = this, o = self.options, text = axisOption.text, marginTop = 0, marginRight = 0, marginLeft = 0, marginBottom = 0, textElement, bbox, isVertical = self._isVertical(axisOption.compass), textStyle = $.extend(true, {
}, o.textStyle, axisOption.textStyle);
if(textStyle["margin-top"]) {
marginTop = parseFloat(textStyle["margin-top"]);
}
if(textStyle["margin-left"]) {
marginLeft = parseFloat(textStyle["margin-left"]);
}
if(textStyle["margin-right"]) {
marginRight = parseFloat(textStyle["margin-right"]);
}
if(textStyle["margin-bottom"]) {
marginBottom = parseFloat(textStyle["margin-bottom"]);
}
textElement = self._text(0, 0, text);
textElement.attr(textStyle);
if(isVertical) {
textElement.transform("...R-90");
}
bbox = textElement.wijGetBBox();
textElement.wijRemove();
textElement = null;
return {
width: bbox.width + marginLeft + marginRight,
height: bbox.height + marginBottom + marginTop
};
};
wijchartcore.prototype._getMaxExtents = function (axisInfo, axisOptions, axisRect) {
var self = this, o = self.options, majorTickValues = null, maxExtent = {
width: 0,
height: 0
}, min = axisInfo.min, max = axisInfo.max, isTime = axisInfo.isTime, formatString = axisOptions.annoFormatString, is100pc = o.is100Percent, index = 0, compass = axisOptions.compass, labels = axisOptions.labels, textStyle, hasDefaultRotation = false, canvasBounds = axisInfo.bounds || self.canvasBounds, width, transform;
axisInfo.majorTickRect = self._getTickRect(axisInfo, axisOptions, true, true, axisRect);
axisInfo.minorTickRect = self._getTickRect(axisInfo, axisOptions, false, true, axisRect);
majorTickValues = self._getMajorTickValues(axisInfo, axisOptions);
if(!axisOptions.textVisible) {
return maxExtent;
}
if(!formatString || formatString.length === 0) {
formatString = axisInfo.annoFormatString;
}
textStyle = $.extend(true, {
}, o.textStyle, axisOptions.textStyle, labels.style);
transform = textStyle.transform;
if(transform && transform.length) {
$.each(transform, function (i, t) {
if(t[0].toLowerCase() === "r") {
hasDefaultRotation = true;
return false;
}
});
}
// hasDefaultRotation = typeof (textStyle.rotation) !== "undefined";
textStyle = $.extend(true, textStyle, axisInfo.textStyle);
width = canvasBounds.endX - canvasBounds.startX - axisInfo.vOffset - axisInfo.axisTextOffset;
if(majorTickValues && majorTickValues.length) {
width = width / (majorTickValues.length - 1);
$.each(majorTickValues, function (idx, mtv) {
var txt, size, txtClone;
if(mtv < min || mtv > max) {
return true;
}
//if (axisOptions.annoMethod === "valueLabels") {
if(axisInfo.annoMethod === "valueLabels") {
if(mtv < 0) {
return true;
}
//if (index >= axisOptions.valueLabels.length) {
if(index >= axisInfo.valueLabels.length) {
return false;
}
//// mtv = axisOptions.valueLabels[index].text;
//mtv = axisOptions.valueLabels[index];
mtv = axisInfo.valueLabels[index];
if(mtv.text) {
mtv = mtv.text;
} else if(typeof mtv.value !== "undefined") {
mtv = mtv.value;
if(formatString && formatString.length) {
// mtv = $.format(mtv, formatString);
mtv = Globalize.format(mtv, formatString, self._getCulture());
}
}
} else if(axisInfo.annoMethod === "values") {
//} else if (axisOptions.annoMethod === "values") {
if(formatString && formatString.length) {
if(isTime) {
mtv = $.fromOADate(mtv);
}
// mtv = $.format(mtv, formatString);
mtv = Globalize.format(mtv, formatString, self._getCulture());
} else if(is100pc && axisInfo.id === "y") {
// mtv = $.format(mtv, "p0");
mtv = Globalize.format(mtv, "p0", self._getCulture());
}
}
if(labels.width) {
txt = self.canvas.wrapText(-100, -100, mtv, labels.width, labels.textAlign, textStyle);
} else {
txt = self._text(-100, -100, mtv).attr(textStyle);
}
size = txt.wijGetBBox();
if(!self._isVertical(compass) && !hasDefaultRotation && axisInfo.annoMethod === "valueLabels") {
//axisOptions.annoMethod === "valueLabels") {
if(size.width > width) {
txt.attr({
transform: "r-45"
});
size = txt.wijGetBBox();
/*
* if (!txt.attr().rotation) { txt.attr({ rotation:
* -45 }); textStyle.rotation = -45;
* axisInfo.textStyle = { rotation: -45 }; size =
* txt.wijGetBBox(); }
*/
if(idx === 0) {
textStyle.transform = "r-45";
axisInfo.textStyle = {
transform: "r-45"
};
txtClone = txt.clone();
txtClone.attr({
transform: "r0"
});
size = txtClone.wijGetBBox();
if(Math.sqrt(2) * size.height > width) {
txt.attr({
transform: "r-90"
});
// textStyle.transform.push(["r", -90]);
textStyle.transform = "r-90";
axisInfo.textStyle = {
transform: "r-90"
};
}
txtClone.wijRemove();
txtClone = null;
size = txt.wijGetBBox();
}
}
/*
* if (idx === 0 && txt.attr().rotation &&
* txt.attr().rotation === -45) { txtClone =
* txt.clone(); txtClone.attr({ rotation: 0 }); size =
* txtClone.wijGetBBox(); if (Math.sqrt(2) * size.height >
* width) { txt.attr({ rotation: -90 });
* textStyle.rotation = -90; axisInfo.textStyle = {
* rotation: -90 }; } txtClone.wijRemove(); size =
* txt.wijGetBBox(); }
*/
}
txt.wijRemove();
txt = null;
if(size.width > maxExtent.width) {
maxExtent.width = size.width;
}
if(size.height > maxExtent.height) {
maxExtent.height = size.height;
}
index++;
});
}
if(maxExtent.width < labels.width) {
maxExtent.width = labels.width;
}
axisInfo.labelWidth = maxExtent.width;
return maxExtent;
};
wijchartcore.prototype._getMajorTickValues = function (axisInfo, axisOptions) {
var rc = [], valueLabels = //valueLabels = axisOptions.valueLabels;
axisInfo.valueLabels;
if(valueLabels && valueLabels.length > 0) {
$.each(valueLabels, function (idx, valueLabel) {
if(typeof valueLabel.text !== "undefined" || typeof valueLabel.value !== "undefined") {
return false;
}
if(typeof valueLabel === "string") {
valueLabels[idx] = {
text: valueLabel,
gridLine: false
};
} else {
valueLabels[idx] = {
value: valueLabel,
gridLine: false
};
}
});
}
//if (axisOptions.annoMethod === "valueLabels" &&
if(axisInfo.annoMethod === "valueLabels" && valueLabels && valueLabels.length > 0 && typeof valueLabels[0].value !== "undefined") {
rc = this._getSortedDataValues(axisInfo, axisOptions);
return rc;
}
// rc = this._getTickValues(axisInfo.max, axisInfo.min,
// axisOptions.unitMajor, axisInfo.tprec, !axisInfo.isTime);
rc = this._getTickValues(axisInfo.max, axisInfo.min, axisOptions.unitMajor, axisInfo.tprec, !axisInfo.isTime, axisOptions.autoMajor);
return rc;
};
wijchartcore.prototype._getSortedDataValues = function (axisInfo, axisOptions) {
var self = this, rc = [], valueLabels = // isXAxis = (axisInfo.id === "x"),
axisInfo.valueLabels;
//valueLabels = axisOptions.valueLabels;
$.each(valueLabels, function (idx, label) {
var val = label.value;
if(self._isDate(val)) {
rc.push($.toOADate(val));
} else if(typeof val === 'number') {
rc.push(val);
} else {
rc.push(idx);
}
// if (self._isDate(label)) {
// rc.push($.toOADate(label));
// } else if (typeof label === 'number') {
// rc.push(label);
// } else {
// rc.push(idx);
// }
});
// TODO: ignore blank labels.
return rc;
};
wijchartcore.prototype._getMinorTickValues = function (axisInfo, axisOptions) {
var rc = [];
// rc = this._getTickValues(axisInfo.max, axisInfo.min,
// axisOptions.unitMinor, axisInfo.tprec, !axisInfo.isTime);
rc = this._getTickValues(axisInfo.max, axisInfo.min, axisOptions.unitMinor, axisInfo.tprec, !axisInfo.isTime, axisOptions.autoMinor);
return rc;
};
wijchartcore.prototype._getTickValues = // _getTickValues: function (smax, smin, unit, tickprec, round) {
function (smax, smin, unit, tickprec, round, autoTick) {
var self = this, vals = [], sminOriginal = smin, i = 0, xs = 0, imax = 0, imin = 0, n = 0, smin2 = 0;
try {
if(unit === 0) {
vals = [
smax,
smin
];
} else {
if(autoTick) {
if(tickprec + 1 < 0) {
tickprec = -1;
} else if(tickprec + 1 > 15) {
tickprec = 14;
}
smin2 = $.round(ChartDataUtil.signedCeiling(smin / unit) * unit, tickprec + 1);
if(smin2 < smax) {
smin = smin2;
}
imax = parseInt($.round(smax / unit, 5).toString(), 10);
imin = parseInt($.round(smin / unit, 5).toString(), 10);
n = parseInt((imax - imin + 1).toString(), 10);
if(n > 1) {
xs = imin * unit;
if(xs < smin) {
n--;
smin += unit;
}
xs = smin + (n - 1) * unit;
if(xs > smax) {
n--;
}
}
if(n < 1) {
n = 2;
smin = sminOriginal;
unit = smax - smin;
}
} else {
n = parseInt(((smax - smin) / unit + 1).toString(), 10);
if(n > 1) {
xs = smin + (n - 1) * unit;
if(xs > smax) {
n--;
}
}
if(n < 1) {
n = 2;
unit = smax - smin;
}
}
for(i = 0; i < n; i++) {
if(round) {
// vals[i] = $.round(smin + i * unit, tickprec + 1);
if(autoTick) {
vals[i] = $.round(smin + i * unit, tickprec + 1);
} else {
vals[i] = smin + i * unit;
}
} else {
vals[i] = smin + i * unit;
}
}
}
} catch (error) {
}
return vals;
};
wijchartcore.prototype._getTickRect = // to do
function (axisInfo, axisOptions, isMajor, inAxisRect, axisRect) {
var compass = axisOptions.compass, sizeFactor = 0, tick = null, majorSizeFactor = 3, minorSizeFactor = 2, thickness = 2, majorFactor = axisOptions.tickMajor.factor, minorFactor = axisOptions.tickMinor.factor, r = {
x: 0,
y: 0,
width: 0,
height: 0
};
if(isMajor) {
tick = axisOptions.tickMajor.position;
majorFactor = majorFactor > 0 ? majorFactor : 1;
sizeFactor = (majorSizeFactor * majorFactor);
} else {
tick = axisOptions.tickMinor.position;
minorFactor = minorFactor > 0 ? minorFactor : 1;
sizeFactor = (minorSizeFactor * minorFactor);
}
if(tick === "none" || (tick === "inside" && inAxisRect)) {
sizeFactor = 0;
}
// if(isVertical) {
if(compass === "east" || compass === "west") {
r = {
x: 0,
y: -1,
width: sizeFactor * thickness,
height: thickness
};
if((compass === "east" && (tick === "outside" || (tick === "cross" && inAxisRect))) || (compass === "west" && tick === "inside")) {
// r.x = axisRect.x;
// if(inAxisRect) {
// r.x += axisRect.width;
// }
// else {
// r.width += axisRect.width;
// }
r.width += 2// default value of axisRect is 2.
;
} else {
// r.x = axisRect.x - sizeFactor * thickness;
if(!inAxisRect) {
if(tick === "cross") {
r.width <<= 1;
}
// r.width += axisRect.width;
r.width += 2;
}
}
} else {
r = {
x: -1,
y: 0,
width: thickness,
height: sizeFactor * thickness
};
if((compass === "south" && (tick === "outside" || (tick === "corss" && inAxisRect))) || (compass === "north" && tick === "inside")) {
// r.y = axisRect.y;
// if(inAxisRect) {
// r.y += axisRect.height;
// }
// else {
// r.height += axisRect.height;
// }
r.height += 2;
} else {
// r.y = axisRect.y - sizeFactor * thickness;
if(!inAxisRect) {
if(tick === "cross") {
r.height <<= 1;
}
// r.height += axisRect.height;
r.height += 2;
}
}
}
return r;
};
wijchartcore.prototype._applyMargins = function () {
var self = this, o = self.options, canvasBounds = self.canvasBounds;
canvasBounds.startX += o.marginLeft;
canvasBounds.endX -= o.marginRight;
canvasBounds.startY += o.marginTop;
canvasBounds.endY -= o.marginBottom;
};
wijchartcore.prototype._paintAxes = function () {
// paint x axis
var self = this, axis = self.options.axis, axisInfo = self.axisInfo, ox = axis.x, oy = axis.y, x = axisInfo.x, y = axisInfo.y, axisElements;
axisElements = self._paintAxis(ox, x);
$.each(y, function (key, yaxis) {
var opt = oy[key] || oy;
if(opt.origin !== null) {
self._translateAxisIfNeeded(axisElements, ox.compass, opt.origin, opt.compass, yaxis.max, yaxis.min);
}
});
// if (oy.origin !== null) {
// self._translateAxisIfNeeded(axisElements, ox.compass,
// oy.origin, oy.compass, y.max, y.min);
// }
$.each(y, function (key, yaxis) {
var opt = oy[key] || oy;
axisElements = self._paintAxis(opt, yaxis);
if(ox.origin !== null) {
self._translateAxisIfNeeded(axisElements, opt.compass, ox.origin, ox.compass, x.max, x.min);
}
});
};
wijchartcore.prototype._translateAxisIfNeeded = function (xAxisElements, xCompass, yOrigin, yCompass, yMax, yMin) {
var self = this, isVertical = yCompass === "west" || yCompass === "east", bounds = self.canvasBounds, origin = yOrigin, offset;
if(self._isDate(origin)) {
origin = $.toOADate(origin);
}
if(!isVertical) {
if(xCompass === "west") {
offset = (origin - yMin) / (yMax - yMin) * (bounds.endX - bounds.startX);
} else {
offset = (origin - yMax) / (yMax - yMin) * (bounds.endX - bounds.startX);
}
$.each(xAxisElements, function (idx, element) {
// element.translate(offset, 0);
element.transform(Raphael.format("...T{0},{1}", offset, 0));
});
} else {
if(xCompass === "south") {
offset = (yMin - origin) / (yMax - yMin) * (bounds.endY - bounds.startY);
} else {
offset = (yMax - origin) / (yMax - yMin) * (bounds.endY - bounds.startY);
}
$.each(xAxisElements, function (idx, element) {
// element.translate(0, offset);
element.transform(Raphael.format("...T{0},{1}", 0, offset));
});
}
};
wijchartcore.prototype._paintAxis = function (axisOptions, axisInfo) {
var self = this, o = self.options, canvasBounds = // for stock composite chart, get the bounds from axis
axisInfo.bounds || self.canvasBounds, startPoint = {
x: 0,
y: 0
}, endPoint = {
x: 0,
y: 0
}, compass = axisOptions.compass, thickness = 2, isVertical = true, ax = null, majorTickValues = // paint tick & ticklabel
[], tempMinorTickValues = [], minorTickValues = [], max = axisInfo.max, min = axisInfo.min, unitMajor = axisOptions.unitMajor, unitMinor = axisOptions.unitMinor, tickMajor = axisOptions.tickMajor.position, tickMinor = axisOptions.tickMinor.position, axisSize = axisInfo.maxExtent, tickMajorStyle = // axisInfo.offset,
axisOptions.tickMajor.style, tickMinorStyle = axisOptions.tickMinor.style, tickRectMajor = axisInfo.majorTickRect, tickRectMinor = axisInfo.minorTickRect, axisTextOffset = axisInfo.axisTextOffset, gridMajor = axisOptions.gridMajor, gridMinor = axisOptions.gridMinor, labels = axisOptions.labels, maxLen = 0, textInfos = [], index = 0, formatString = axisOptions.annoFormatString, textStyle = null, axisElements = [];
tickRectMajor = self._getTickRect(axisInfo, axisOptions, true, false);
tickRectMinor = self._getTickRect(axisInfo, axisOptions, false, false);
if(!formatString || formatString.length === 0) {
formatString = axisInfo.annoFormatString;
}
majorTickValues = self._getMajorTickValues(axisInfo, axisOptions);
//if (tickMinor !== "none") {
tempMinorTickValues = self._getMinorTickValues(axisInfo, axisOptions);
minorTickValues = self._resetMinorTickValues(tempMinorTickValues, majorTickValues);
//}
//add comments here to fix tfs issue 20415,paint the axis inside the plotarea.
switch(compass) {
case "south":
startPoint.x = canvasBounds.startX;
startPoint.y = canvasBounds.endY;
endPoint.x = canvasBounds.endX;
endPoint.y = canvasBounds.endY;
isVertical = false;
break;
case "north":
startPoint.x = canvasBounds.startX;
startPoint.y = canvasBounds.startY - thickness;
endPoint.x = canvasBounds.endX;
endPoint.y = canvasBounds.startY - thickness;
isVertical = false;
break;
case "east":
//startPoint.x = canvasBounds.endX;
startPoint.x = canvasBounds.endX - thickness;
if(axisInfo.preStartOffset) {
startPoint.x += axisInfo.preStartOffset;
}
startPoint.y = canvasBounds.endY;
//endPoint.x = canvasBounds.endX;
endPoint.x = canvasBounds.endX - thickness;
endPoint.y = canvasBounds.startY;
break;
case "west":
//startPoint.x = canvasBounds.startX - thickness;
startPoint.x = canvasBounds.startX;
if(axisInfo.preStartOffset) {
startPoint.x -= axisInfo.preStartOffset;
}
startPoint.y = canvasBounds.endY;
//endPoint.x = canvasBounds.startX - thickness;
endPoint.x = canvasBounds.startX;
endPoint.y = canvasBounds.startY;
break;
}
if(axisOptions.visible) {
ax = self.canvas.line(startPoint.x, startPoint.y, endPoint.x, endPoint.y).attr(axisOptions.style);
$.wijraphael.addClass($(ax.node), o.wijCSS.axis);
self.axisEles.push(ax);
axisElements.push(ax);
}
$.each(majorTickValues, function (idx, val) {
var text = val, isTime = axisInfo.isTime, is100Percent = o.is100Percent, retInfo, textInfo, vlGridLine = false, vlGridLineStyle = {
};
if(val < min || val > max) {
index++;
return true;
}
if(axisInfo.annoMethod === "valueLabels") {
//if (axisOptions.annoMethod === "valueLabels") {
// if (val < 0) {
// return true;
// }
//if (index >= axisOptions.valueLabels.length) {
if(index >= axisInfo.valueLabels.length) {
return false;
}
//// text = axisOptions.valueLabels[index].text;
//text = axisOptions.valueLabels[index];
text = axisInfo.valueLabels[index];
vlGridLine = text.gridLine;
vlGridLineStyle = text.gridLineStyle;
if(text.text) {
text = text.text;
} else if(typeof text.value !== "undefined") {
text = text.value;
if(formatString && formatString.length) {
// text = $.format(text, formatString);
text = Globalize.format(text, formatString, self._getCulture());
}
}
} else if(axisInfo.annoMethod === "values") {
//} else if (axisOptions.annoMethod === "values") {
if(formatString && formatString.length) {
if(isTime) {
text = $.fromOADate(val);
}
// text = $.format(text, formatString);
text = Globalize.format(text, formatString, self._getCulture());
} else if(is100Percent && axisInfo.id === "y") {
// text = $.format(val, "p0");
text = Globalize.format(val, "p0", self._getCulture());
}
}
/*
* //TODO: mixed else { }
*/
textStyle = $.extend(true, {
}, o.textStyle, axisOptions.textStyle, labels.style, axisInfo.textStyle);
if(axisInfo.id === "x") {
text = self._getTickText(text);
}
retInfo = self._paintMajorMinor(axisOptions.origin, max, min, val, tickMajor, unitMajor, tickRectMajor, compass, startPoint, endPoint, axisSize, axisTextOffset, tickMajorStyle, text, gridMajor, axisOptions.textVisible, textStyle, labels.textAlign, labels.width ? axisInfo.labelWidth : null, vlGridLine, vlGridLineStyle);
if(retInfo) {
if(retInfo.elements) {
axisElements = axisElements.concat(retInfo.elements);
}
textInfo = retInfo.textInfo;
}
if(textInfo) {
textInfos.push(textInfo);
if(maxLen < textInfo.len) {
maxLen = textInfo.len;
}
}
index++;
});
if(!labels.width) {
$.each(textInfos, function (idx, textInfo) {
var textElement = textInfo.text, offset = (textInfo.len - maxLen) / 2;
offset = labels.textAlign === "near" ? offset * -1 : offset;
if(isVertical) {
//textElement.translate(offset, 0);
textElement.transform(Raphael.format("...T{0},{1}", offset, 0));
} else {
//textElement.translate(0, offset);
textElement.transform(Raphael.format("...T{0},{1}", 0, offset));
}
});
}
$.each(minorTickValues, function (idx, val) {
var retInfo;
if(val > min && val < max) {
retInfo = self._paintMajorMinor(axisOptions.origin, max, min, val, tickMinor, unitMinor, tickRectMinor, compass, startPoint, endPoint, axisSize, axisTextOffset, tickMinorStyle, null, gridMinor, axisOptions.textVisible, textStyle, labels.textAlign, labels.width ? axisInfo.labelWidth : null);
if(retInfo && retInfo.elements) {
axisElements = axisElements.concat(retInfo.elements);
}
}
});
if(axisOptions.text && axisOptions.text.length > 0) {
axisElements.push(self._paintAxisText(axisOptions, axisInfo));
}
if(axisInfo.isPartAxis && !axisInfo.isLastAxis) {
axisElements.push(self.canvas.path([
"M",
startPoint.x.toString(),
startPoint.y.toString() + (axisInfo.vOffset / 2).toString,
"H",
(startPoint.x + axisInfo.maxExtent * 2).toString()
].join()));
}
return axisElements;
};
wijchartcore.prototype._paintAxisText = function (axisOptions, axisInfo) {
if(!axisOptions.text || axisOptions.text.length === 0) {
return;
}
var self = this, o = self.options, text = axisOptions.text, compass = axisOptions.compass, align = axisOptions.alignment, canvasBounds = axisInfo.bounds || self.canvasBounds, startX = canvasBounds.startX, startY = canvasBounds.startY, endX = canvasBounds.endX, endY = canvasBounds.endY, x = startX, y = startY, textBounds = axisInfo.textBounds, isVertical = self._isVertical(compass), axisTextOffset = axisInfo.axisTextOffset, tickRectMajor = axisInfo.majorTickRect, tick = axisOptions.tickMajor.position, tickLength = isVertical ? tickRectMajor.width : tickRectMajor.height, textStyle = null, textElement = null, marginTop = 0, marginLeft = 0, marginRight = 0, marginBottom = 0;
textStyle = $.extend(true, {
}, self.options.textStyle, axisOptions.textStyle);
if(textStyle["margin-top"]) {
marginTop = parseFloat(textStyle["margin-top"]);
}
if(textStyle["margin-left"]) {
marginLeft = parseFloat(textStyle["margin-left"]);
}
if(textStyle["margin-right"]) {
marginRight = parseFloat(textStyle["margin-right"]);
}
if(textStyle["margin-bottom"]) {
marginBottom = parseFloat(textStyle["margin-bottom"]);
}
if(tick === "cross") {
tickLength = tickLength / 2;
} else if(tick === "inside") {
tickLength = 0;
}
if(isVertical) {
switch(align) {
case "near":
y = endY - textBounds.width / 2;
break;
case "center":
y = (startY + endY) / 2;
break;
case "far":
y = startY + textBounds.width / 2;
break;
}
if(compass === "west") {
x = startX - (axisInfo.offset + axisTextOffset + tickLength + textBounds.height / 2 + marginRight);
} else {
x = endX + axisInfo.offset + axisTextOffset + tickLength + textBounds.height / 2 + marginLeft;
}
} else {
switch(align) {
case "near":
x = startX + textBounds.width / 2;
break;
case "center":
x = (startX + endX) / 2;
break;
case "far":
x = endX - textBounds.width / 2;
break;
}
if(compass === "north") {
y = startY - (axisInfo.offset + axisTextOffset + tickLength + textBounds.height / 2 + marginBottom);
} else {
y = endY + axisInfo.offset + axisTextOffset + tickLength + textBounds.height / 2 + marginTop;
}
}
textElement = self._text(x, y, text);
$.wijraphael.addClass($(textElement.node), o.wijCSS.axisText);
self.axisEles.push(textElement);
textElement.attr(textStyle);
if(isVertical) {
// textElement.rotate(-90);
textElement.transform("...R-90");
}
return textElement;
};
wijchartcore.prototype._resetMinorTickValues = function (minorTickValues, majorTickValues) {
var i = 0, j = 0, minorTickValue = null, majorTickValue = null;
for(i = minorTickValues.length - 1; i >= 0; i--) {
minorTickValue = minorTickValues[i];
for(j = majorTickValues.length - 1; j >= 0; j--) {
majorTickValue = majorTickValues[j];
if(minorTickValue === majorTickValue) {
minorTickValues.splice(i, 1);
}
}
}
return minorTickValues;
};
wijchartcore.prototype._getTickText = function (txt) {
return txt;
};
wijchartcore.prototype._paintMajorMinor = function (origin, max, min, val, tick, unit, tickRect, compass, startPoint, endPoint, axisSize, axisTextOffset, tickStyle, text, grid, textVisible, textStyle, textAlign, labelWidth, vlGridLine, vlGridLineStyle) {
var self = this, x = startPoint.x, y = startPoint.y, o = self.options, tickX = -1, tickY = -1, isVertical = true, bs = self.canvasBounds, textInfo = null, tickElement = null, pathArr = [], arrPath = [], p = null, style = {
"stroke-width": 2
}, txt = {
text: null,
len: 0
}, textBounds = null, retInfo = {
}, majorMinorElements = [], axisCompass = self.axisCompass;
switch(compass) {
case "south":
if(tick === "inside") {
y -= tickRect.height;
} else if(tick === "cross") {
y -= tickRect.height / 2;
}
if(labelWidth) {
tickY = y + axisTextOffset + tickRect.height;
} else {
tickY = y + axisTextOffset + tickRect.height + axisSize / 2;
}
isVertical = false;
break;
case "west":
if(tick === "outside") {
x -= tickRect.width;
} else if(tick === "cross") {
x -= tickRect.width / 2;
}
if(labelWidth) {
tickX = x - (axisTextOffset + axisSize);
} else {
tickX = x - (axisTextOffset + axisSize / 2);
}
break;
case "north":
if(tick === "outside") {
y -= tickRect.height;
} else if(tick === "cross") {
y -= tickRect.height / 2;
}
if(labelWidth) {
tickY = y - (axisTextOffset + axisSize);
} else {
tickY = y - (axisTextOffset + axisSize / 2);
}
isVertical = false;
break;
case "east":
if(tick === "inside") {
x -= tickRect.width;
} else if(tick === "cross") {
x -= tickRect.width / 2;
}
if(labelWidth) {
tickX = x + axisTextOffset + tickRect.width;
} else {
tickX = x + axisTextOffset + tickRect.width + axisSize / 2;
}
break;
}
if(isVertical) {
y += (val - min) / (max - min) * (endPoint.y - startPoint.y);
arrPath = [
"M",
bs.startX,
y,
"H",
bs.endX
];
if(grid.visible) {
//if ((y !== bs.startY && compass === "east") ||
// (y !== bs.endY && compass === "west")) {
if((y !== bs.startY || !axisCompass["north"]) && (y !== bs.endY || !axisCompass["south"]) || origin !== val) {
p = self.canvas.path(arrPath.join(" "));
$.wijraphael.addClass($(p.node), o.wijCSS.axisGridLine);
p.attr(grid.style);
self.axisEles.push(p);
}
}
if(vlGridLine) {
//if ((y !== bs.startY && compass === "east") ||
// (y !== bs.endY && compass === "west")) {
if((y !== bs.startY || !axisCompass["north"]) && (y !== bs.endY || !axisCompass["south"]) || origin !== val) {
p = self.canvas.path(arrPath.join(" "));
$.wijraphael.addClass($(p.node), o.wijCSS.axisGridLine);
p.attr($.extend(true, grid.style, vlGridLineStyle));
self.axisEles.push(p);
}
}
tickY = y;
if(tick !== "none") {
pathArr = [
"M",
x,
y,
"h",
tickRect.width
];
tickStyle["stroke-width"] = tickRect.height;
}
} else {
x += (val - min) / (max - min) * (endPoint.x - startPoint.x);
arrPath = [
"M",
x,
bs.startY,
"V",
bs.endY
];
if(grid.visible) {
//if ((x !== bs.startX && compass === "south") ||
// (x !== bs.endX && compass === "north")) {
if((x !== bs.startX || !axisCompass["west"]) && (x !== bs.endX || !axisCompass["east"]) || origin !== val) {
p = self.canvas.path(arrPath.join(" "));
$.wijraphael.addClass($(p.node), o.wijCSS.axisGridLine);
p.attr(grid.style);
self.axisEles.push(p);
}
}
if(vlGridLine) {
//if ((y !== bs.startY && compass === "south") ||
// (y !== bs.endY && compass === "north")) {
if((x !== bs.startX || !axisCompass["west"]) && (x !== bs.endX || !axisCompass["east"]) || origin !== val) {
p = self.canvas.path(arrPath.join(" "));
$.wijraphael.addClass($(p.node), o.wijCSS.axisGridLine);
p.attr($.extend(true, {
}, grid.style, vlGridLineStyle));
self.axisEles.push(p);
}
}
if(labelWidth) {
tickX = x - labelWidth / 2;
} else {
tickX = x;
}
if(tick !== "none") {
pathArr = [
"M",
x,
y,
"v",
tickRect.height
];
tickStyle["stroke-width"] = tickRect.width;
}
}
if(tick !== "none") {
tickElement = self.canvas.path(pathArr.join(" "));
$.wijraphael.addClass($(tickElement.node), o.wijCSS.axisTick);
style = $.extend(style, tickStyle);
tickElement.attr(style);
self.axisEles.push(tickElement);
majorMinorElements.push(tickElement);
}
if(text !== null && textVisible) {
if(labelWidth) {
txt = self.canvas.wrapText(tickX, tickY, text.toString(), labelWidth, textAlign, textStyle);
$.wijraphael.addClass($(txt.node), o.wijCSS.axisLabel);
//if (isVertical) {
// txt.translate(0, -txt.getBBox().height / 2);
//txt.transform(Raphael.format("...T{0},{1}", 0,
//-txt.getBBox().height / 2));
//}
} else {
txt = self._text(tickX, tickY, text.toString());
$.wijraphael.addClass($(txt.node), o.wijCSS.axisLabel);
txt.attr(textStyle);
}
self.axisEles.push(txt);
majorMinorElements.push(txt);
if(!textVisible) {
txt.hide();
}
if(textAlign !== "center") {
textBounds = txt.getBBox();
textInfo = {
text: txt,
len: isVertical ? textBounds.width : textBounds.height
};
}
}
retInfo = {
textInfo: textInfo,
elements: majorMinorElements
};
return retInfo;
};
wijchartcore.prototype._paintPlotArea = function () {
};
wijchartcore.prototype._paintChartLabels = function () {
var self = this, chartLabels = self.options.chartLabels;
if(chartLabels && chartLabels.length) {
$.each(chartLabels, function (idx, chartLabel) {
var point;
chartLabel = $.extend(true, {
compass: "east",
attachMethod: "coordinate",
attachMethodData: {
seriesIndex: -1,
pointIndex: -1,
x: -1,
y: -1
},
offset: 0,
visible: false,
text: "",
connected: false
}, chartLabel);
if(chartLabel.visible) {
point = self._getChartLabelPointPosition(chartLabel);
if(typeof (point.x) !== "number" || typeof (point.y) !== "number") {
return false;
}
self._setChartLabel(chartLabel, point);
}
});
}
};
wijchartcore.prototype._getChartLabelPointPosition = function (chartLabel) {
};
wijchartcore.prototype._setChartLabel = function (chartLabel, point, angle, calloutStyle) {
var self = this, compass = chartLabel.compass, o = self.options, textStyle = $.extend(true, {
}, o.textStyle, o.chartLabelStyle), text = self._text(0, 0, chartLabel.text).attr(textStyle), offset = chartLabel.offset, transX = 0, transY = 0, position = null, p = null;
$.wijraphael.addClass($(text.node), o.wijCSS.labelText);
self.chartLabelEles.push(text);
position = self._getCompassTextPosition(compass, text.wijGetBBox(), offset, point, angle);
if(offset && chartLabel.connected) {
p = self.canvas.path("M" + point.x + " " + point.y + "L" + position.endPoint.x + " " + position.endPoint.y);
$.wijraphael.addClass($(p.node), o.wijCSS.labelConnect);
p.attr(calloutStyle);
self.chartLabelEles.push(p);
}
transX = position.endPoint.x + position.offsetX;
transY = position.endPoint.y + position.offsetY;
// text.translate(transX, transY)
// .toFront();
text.transform(Raphael.format("...T{0},{1}", transX, transY)).toFront();
};
wijchartcore.prototype._getCompassTextPosition = function (compass, box, offset, point, angle) {
var offsetX = 0, offsetY = 0, endPoint = {
x: 0,
y: 0
};
switch(compass.toLowerCase()) {
case "east":
angle = 0;
break;
case "west":
angle = 180;
break;
case "north":
angle = 90;
break;
case "south":
angle = 270;
break;
case "northeast":
angle = 45;
break;
case "northwest":
angle = 135;
break;
case "southeast":
angle = 315;
break;
case "southwest":
angle = 225;
break;
}
if((angle >= 0 && angle < 45 / 2) || (angle > 675 / 2 && angle < 360)) {
offsetX = box.width / 2;
} else if(angle >= 45 / 2 && angle < 135 / 2) {
offsetX = box.width / 2;
offsetY = -1 * box.height / 2;
} else if(angle >= 135 / 2 && angle < 225 / 2) {
offsetY = -1 * box.height / 2;
} else if(angle >= 225 / 2 && angle < 315 / 2) {
offsetX = -1 * box.width / 2;
offsetY = -1 * box.height / 2;
} else if(angle >= 315 / 2 && angle < 405 / 2) {
offsetX = -1 * box.width / 2;
} else if(angle >= 405 / 2 && angle < 495 / 2) {
offsetX = -1 * box.width / 2;
offsetY = box.height / 2;
} else if(angle >= 495 / 2 && angle < 585 / 2) {
offsetY = box.height / 2;
} else {
offsetX = box.width / 2;
offsetY = box.height / 2;
}
endPoint = $.wijraphael.getPositionByAngle(point.x, point.y, offset, angle);
return {
endPoint: endPoint,
offsetX: offsetX,
offsetY: offsetY
};
};
wijchartcore.prototype._mouseDown = function (e, args) {
this._trigger("mouseDown", e, args);
};
wijchartcore.prototype._mouseUp = function (e, args) {
this._trigger("mouseUp", e, args);
};
wijchartcore.prototype._mouseOver = function (e, args) {
this._trigger("mouseOver", e, args);
};
wijchartcore.prototype._mouseOut = function (e, args) {
this._trigger("mouseOut", e, args);
};
wijchartcore.prototype._mouseMove = function (e, args) {
this._trigger("mouseMove", e, args);
};
wijchartcore.prototype._click = function (e, args) {
this._trigger("click", e, args);
};
wijchartcore.prototype._mouseMoveInsidePlotArea = function (e, mousePos) {
var self = this, o = self.options, indicator = o.indicator, canvas = self.canvas, point, bounds, path, offset = 0, tooltipObj = [], horizontal = o.horizontal;
if(indicator && indicator.visible && this.isPlotAreaMouseDown) {
if(horizontal) {
point = this._calculatePositionByX(mousePos.top);
} else {
point = this._calculatePositionByX(mousePos.left);
}
if(point && this.indicatorLine) {
if(point.x !== this.lastIndicatorPosition) {
$.each(point.data, function (i, obj) {
if(obj.visible) {
tooltipObj.push(obj);
}
});
if(tooltipObj.length > 0) {
bounds = self.canvasBounds;
if(horizontal) {
this.indicatorLine.transform("T0 " + point.x);
} else {
this.indicatorLine.transform("T" + point.x + " 0");
}
// if (this.tooltip) {
// this.tooltip.destroy();
// this.tooltip = null;
// }
//this.tooltip.hide();
//this._paintIndicatorTooltip(tooltipObj);
this._setTooltipContent(tooltipObj);
if(horizontal) {
this.tooltip.showAt({
x: bounds.endX,
y: point.x
});
} else {
this.tooltip.showAt({
x: point.x,
y: bounds.startY
});
}
this.lastIndicatorPosition = point.x;
self._indicatorLineShowing(tooltipObj);
this.lastIndicatorObjects = tooltipObj;
}
}
}
}
};
wijchartcore.prototype._calculatePositionByX = // return a chart element point which is near the mouse.
function (x) {
var self = this, xArr = self.pointXs, position, points = self.dataPoints;
if(xArr && xArr.length > 0) {
position = this._calculatePositionByXInternal(x, xArr);
}
if(points) {
return {
x: position,
data: points[position.toString()]
};
}
return null;
};
wijchartcore.prototype._calculatePositionByXInternal = function (x, arr) {
var len = arr.length, half, subArr;
if(len === 1) {
return arr[0];
} else if(len === 2) {
if(Math.abs(x - arr[0]) > Math.abs(x - arr[1])) {
return arr[1];
} else {
return arr[0];
}
} else {
half = parseInt((len / 2).toString());
if(x > arr[half]) {
subArr = arr.slice(half);
} else {
subArr = arr.slice(0, half + 1);
}
return this._calculatePositionByXInternal(x, subArr);
}
};
wijchartcore.prototype._mouseMoveOutsidePlotArea = function (e, mousePos) {
if(this.indicatorLine) {
this.indicatorLine.wijRemove();
this.indicatorLine = null;
if(this.tooltip) {
this.tooltip.hide();
}
this._resetTooltip();
}
};
wijchartcore.prototype._mouseDownInsidePlotArea = function (e, mousePos) {
this.isPlotAreaMouseDown = true;
var self = this, o = self.options, indicator = o.indicator, canvas = self.canvas, point, bounds, path, tooltipObj = [], horizontal = o.horizontal;
if(indicator && indicator.visible && this.isPlotAreaMouseDown) {
self._setTooltip();
if(horizontal) {
point = this._calculatePositionByX(mousePos.top);
} else {
point = this._calculatePositionByX(mousePos.left);
}
if(point) {
// for each the points, if the element is not visible,
// don't show the indicator.
$.each(point.data, function (i, obj) {
if(obj.visible) {
tooltipObj.push(obj);
}
});
if(tooltipObj.length > 0) {
bounds = self.canvasBounds;
if(horizontal) {
path = [
"M",
bounds.startX,
0,
"H",
bounds.endX
];
} else {
path = [
"M",
0,
bounds.startY,
"V",
bounds.endY
];
}
if(this.indicatorLine) {
this.indicatorLine.wijRemove();
}
this.indicatorLine = canvas.path(path);
this.indicatorLine.attr(indicator.style);
if(horizontal) {
this.indicatorLine.transform("T0 " + point.x);
} else {
this.indicatorLine.transform("T" + point.x + " 0");
}
// if (this.tooltip) {
// this.tooltip.destroy();
// this.tooltip = null;
// }
// show tooltip
//this.tooltip.hide();
this._setTooltipContent(tooltipObj);
//this._paintIndicatorTooltip(tooltipObj);
if(horizontal) {
this.tooltip.showAt({
x: bounds.endX,
y: point.x
});
} else {
this.tooltip.showAt({
x: point.x,
y: bounds.startY
});
}
this.lastIndicatorPosition = point.x;
self._indicatorLineShowing(tooltipObj);
this.lastIndicatorObjects = tooltipObj;
}
}
e.preventDefault();
}
};
wijchartcore.prototype._indicatorLineShowing = function (obj) {
if(this.lastIndicatorObjects) {
this._removeIndicatorStyles(this.lastIndicatorObjects);
}
};
wijchartcore.prototype._removeIndicatorStyles = function (lastIndicatorObjects) {
};
wijchartcore.prototype._mouseUpInsidePlotArea = function (e, mousePos) {
this.isPlotAreaMouseDown = false;
if(this.indicatorLine) {
this.indicatorLine.wijRemove();
this.indicatorLine = null;
if(this.tooltip) {
this.tooltip.hide();
}
this._resetTooltip();
}
if(this.lastIndicatorObjects) {
this._removeIndicatorStyles(this.lastIndicatorObjects);
this.lastIndicatorObjects = null;
}
};
wijchartcore.prototype._bindLiveEvents = function () {
this._bindLegendEvents();
this._bindCanvasEvents();
};
wijchartcore.prototype._bindCanvasEvents = function () {
var self = this, element = self.chartElement, touchEventPre = "", namespace = "." + this.widgetName;
if(window.navigator.msPointerEnabled) {
element.css("-ms-touch-action", "none");
}
// if support touch.
if($.support.isTouchEnabled && $.support.isTouchEnabled()) {
touchEventPre = "wij";
}
element.bind(touchEventPre + "mousemove" + namespace, function (e) {
var elePos = element.offset(), cBounds = self.canvasBounds, mousePos = {
left: e.pageX - elePos.left,
top: e.pageY - elePos.top
}, disabled = self.options.disabled;
if(disabled) {
return;
}
if(mousePos.left >= cBounds.startX && mousePos.left <= cBounds.endX && mousePos.top >= cBounds.startY && mousePos.top <= cBounds.endY) {
self._mouseMoveInsidePlotArea(e, mousePos);
} else {
self._mouseMoveOutsidePlotArea(e, mousePos);
}
});
if(self.options.indicator && self.options.indicator.visible) {
element.bind(touchEventPre + "mousedown" + namespace, function (e) {
var elePos = element.offset(), cBounds = self.canvasBounds, mousePos = {
left: e.pageX - elePos.left,
top: e.pageY - elePos.top
}, disabled = self.options.disabled;
if(disabled) {
return;
}
if(mousePos.left >= cBounds.startX && mousePos.left <= cBounds.endX && mousePos.top >= cBounds.startY && mousePos.top <= cBounds.endY) {
self._mouseDownInsidePlotArea(e, mousePos);
}
}).bind(touchEventPre + "mouseup" + namespace, function (e) {
var elePos = element.offset(), cBounds = self.canvasBounds, mousePos = {
left: e.pageX - elePos.left,
top: e.pageY - elePos.top
}, disabled = self.options.disabled;
if(disabled) {
return;
}
if(mousePos.left >= cBounds.startX && mousePos.left <= cBounds.endX && mousePos.top >= cBounds.startY && mousePos.top <= cBounds.endY) {
self._mouseUpInsidePlotArea(e, mousePos);
}
});
}
};
wijchartcore.prototype._unbindCanvasEvents = function () {
if(window.navigator.msPointerEnabled) {
this.element.css("-ms-touch-action", "");
}
this.element.unbind("." + this.widgetName);
};
wijchartcore.prototype._bindLegendEvents = function () {
var self = this, element = self.chartElement;
element.delegate("." + self.options.wijCSS.legend, "click.wijchartcore", function (e) {
if(self.options.disabled) {
return;
}
var tar = $(e.target);
if(tar[0].tagName && tar[0].tagName === "tspan") {
tar = tar.parent();
}
self._legendClick(tar);
});
//$(".wijchart-legend", element[0])
// .live("click." + widgetName, function (e) {
// if (self.options.disabled) {
// return;
// }
// var tar = $(e.target);
// if (tar[0].tagName && tar[0].tagName === "tspan") {
// tar = tar.parent();
// }
// self._legendClick(tar);
// });
};
wijchartcore.prototype._legendClick = function (obj) {
if(typeof obj.data("index") === "undefined") {
return;
}
var self = this, l = self.options.legend, i = obj.data("index"), legendIndex = obj.data("legendIndex"), fields = self.chartElement.data("fields"), seriesEles = self.seriesEles, seriesEle, legendIcon = self.legendIcons[legendIndex], legend = self.legends[legendIndex], legendNode = l.textWidth ? $(legend[0].node) : $(legend.node), idx = i, legendDot;
if(fields && fields.seriesEles) {
seriesEles = fields.seriesEles;
}
if(self.legendDots && self.legendDots.length > i) {
legendDot = self.legendDots[i];
}
if(l.reversed) {
idx = self.legends.length - 1 - i;
}
seriesEle = seriesEles[idx];
if(seriesEle) {
if(!legendNode.data("hidden")) {
self._hideSerieEles(seriesEle);
if(!legendNode.data("textOpacity")) {
if(l.textWidth) {
legendNode.data("textOpacity", legend[0].attr("opacity") || 1);
} else {
legendNode.data("textOpacity", legend.attr("opacity") || 1);
}
}
if(!legendNode.data("iconOpacity")) {
legendNode.data("iconOpacity", legendIcon.attr("opacity") || 1);
}
if(legendDot && !legendNode.data("dotOpacity")) {
legendNode.data("dotOpacity", legendIcon.attr("opacity") || 1);
}
legend.attr("opacity", "0.3");
legendIcon.attr("opacity", "0.3");
if(legendDot) {
legendDot.attr("opacity", "0.3");
}
legendNode.data("hidden", true);
} else {
self._showSerieEles(seriesEle);
legend.attr("opacity", legendNode.data("textOpacity"));
legendIcon.attr("opacity", legendNode.data("iconOpacity"));
if(legendDot) {
legendDot.attr("opacity", legendNode.data("dotOpacity"));
}
legendNode.data("hidden", false);
}
}
};
wijchartcore.prototype._showSerieEles = function (seriesEle) {
};
wijchartcore.prototype._hideSerieEles = function (seriesEle) {
};
wijchartcore.prototype._unbindLiveEvents = function () {
var self = this, o = self.options, element = this.chartElement, widgetName = self.widgetName;
element.undelegate("." + o.wijCSS.legend, ".wijchartcore").undelegate("." + o.wijCSS.legend, "wijchartcore");
this._unbindCanvasEvents();
};
wijchartcore.prototype._isBarChart = function () {
return false;
};
wijchartcore.prototype._isPieChart = function () {
};
wijchartcore.prototype._isStockChart = function () {
};
wijchartcore.prototype._validateSeriesData = function (series) {
return false;
};
wijchartcore.prototype._calculateParameters = // methods for Axis
function (axisInfo, axisOptions) {
var self = this, maxData = axisOptions.max, minData = axisOptions.min, autoMax = axisOptions.autoMax && axisInfo.autoMax, autoMin = axisOptions.autoMin && axisInfo.autoMin, autoMajor = axisOptions.autoMajor && axisInfo.autoMajor, autoMinor = axisOptions.autoMinor && axisInfo.autoMinor, axisAnno = null, prec = null, isVL = axisInfo.annoMethod === "valueLabels", major = //isVL = axisOptions.annoMethod === "valueLabels",
0, newmax = 0, newmin = 0, dx = 0, tinc = 0, isTime = axisInfo.isTime, adjustMinValue = self.options.adjustMinValue;
if(autoMax && maxData !== Number.MIN_VALUE) {
if(axisInfo.id !== "x" && self._isBarChart()) {
if(maxData < 0.0 && (0.5 * (maxData - minData) > -maxData)) {
maxData = 0.0;
}
}
}
if(autoMin && minData !== Number.MAX_VALUE) {
if(axisInfo.id !== "x" && self._isBarChart()) {
if(minData > 0.0 && (0.5 * (maxData - minData) > minData)) {
minData = 0.0;
}
}
}
if(maxData === minData) {
if(minData !== 0) {
minData -= 1;
}
maxData += 1;
}
dx = maxData - minData;
if(isTime) {
axisAnno = axisOptions.annoFormatString;
if(!axisAnno || axisAnno.length === 0) {
axisAnno = ChartDataUtil.getTimeDefaultFormat(maxData, minData);
axisInfo.annoFormatString = axisAnno;
}
tinc = ChartDataUtil.niceTimeUnit(0.0, axisAnno);
}
prec = ChartDataUtil.nicePrecision(dx);
axisInfo.tprec = prec;
if(autoMax) {
if(isTime) {
newmax = ChartDataUtil.roundTime(maxData, tinc, true);
if(newmax < maxData) {
maxData = newmax + tinc;
} else {
maxData = newmax;
}
} else {
newmax = ChartDataUtil.precCeil(-prec, maxData);
if(typeof (newmax) === "number") {
maxData = newmax;
}
}
}
if(autoMin) {
if(isTime) {
newmin = ChartDataUtil.roundTime(minData, tinc, false);
if(newmin > minData) {
minData = newmin - tinc;
} else {
minData = newmin;
}
} else {
newmin = ChartDataUtil.precFloor(-prec, minData);
if(typeof (newmin) === "number") {
minData = newmin;
}
}
}
axisInfo.max = maxData;
axisInfo.min = minData;
axisInfo.annoFormatString = axisAnno;
axisInfo.tinc = tinc;
if(autoMajor || autoMinor) {
dx = maxData - minData;
self._calculateMajorMinor(axisOptions, axisInfo);
// var minor = axisOptions.unitMinor;
major = axisOptions.unitMajor;
if(autoMax && major !== 0 && !isTime && !isVL) {
dx = maxData - parseInt((maxData / major).toString(), 10) * major;
if(dx !== 0) {
maxData += (major - dx);
maxData = ChartDataUtil.precCeil(-prec, maxData);
}
}
if(autoMin && major !== 0 && !isTime && !isVL) {
dx = minData - parseInt((minData / major).toString(), 10) * major;
if(dx !== 0) {
if(dx < 0) {
dx += major;
}
minData -= Math.abs(dx)// should always be less.
;
minData = ChartDataUtil.precFloor(-prec, minData);
}
}
if(autoMin && major !== 0 && !isVL && (typeof adjustMinValue === "undefined" || adjustMinValue === false) && autoMin && minData === axisOptions.min && minData - major >= 0 && axisInfo.id === "y") {
minData -= major;
}
}
/*
* //TODO: if (!autoMajor || !autoMinor) { }
*/
axisInfo.max = maxData;
axisInfo.min = minData;
};
wijchartcore.prototype._supportStacked = function () {
return false;
};
wijchartcore.prototype._getDataExtreme = function (isMultiYAxis) {
var val = {
txx: 0,
txn: 0,
tyx: 0,
tyn: 0
}, valGroup;
valGroup = this._getDataExtremes(val, isMultiYAxis);
if(valGroup) {
if(valGroup.txn > valGroup.txx) {
valGroup.txn = 0;
valGroup.txx = 1;
}
return valGroup;
} else {
if(val.txn > val.txx) {
val.txn = 0;
val.txx = 1;
}
return val;
}
};
wijchartcore.prototype._getDataExtremes = function (val, isMultiYAxis) {
var self = this, o = self.options, seriesList = o.seriesList, stacked = o.stacked && self._supportStacked(), is100Percent = o.is100Percent, axis = o.axis, axisInfo = self.axisInfo, valuesX = [], lastValuesY = [], valueLabels = [], validValue, valGroup = {
y: {
}
}, xValueLabels = axis.x.valueLabels, xAnnoMethod = axisInfo.x.annoMethod, yAnnoMethod = axisInfo.y.annoMethod;
if(!seriesList || seriesList.length === 0) {
return val;
}
//handle the seriesList's xy data
$.each(seriesList, function (i, series) {
var data = series.data, vxs = [], vys = [], len, k = 0;
if(data.xy && $.isArray(data.xy)) {
len = data.xy.length;
while(k < len) {
vxs.push(data.xy[k]);
vys.push(data.xy[k + 1]);
k += 2;
}
data.x = vxs;
data.y = vys;
}
});
if(self.seriesGroup) {
$.each(self.seriesGroup, function (key, seriesL) {
var valuesY = [], k = parseInt(key, 10);
$.each(seriesL, function (i, series) {
if(series.type === "pie") {
return true;
}
// support hole.
series = $.extend(true, {
display: "show"
}, series);
// end comments
var data = series.data, index = 0, k = 0, valuesXY = [].concat(data.xy), len = valuesXY.length, xMinMax, yMinMax;
// support hole.
if(series.display === "exclude") {
return true;
}
// end comments
valuesX = [].concat(data.x);
valuesY = [].concat(data.y);
if(data.xy && len) {
valuesX = [];
valuesY = [];
while(k < len) {
valuesX[index] = valuesXY[k];
valuesY[index] = valuesXY[k + 1];
k += 2;
index++;
data.x = valuesX;
data.y = valuesY;
}
} else if(!data.x) {
valuesX = [];
$.each(valuesY, function (i) {
valuesX.push(i);
});
data.x = valuesX;
}
if(stacked && i > 0) {
$.each(valuesY, function (j) {
// if (j === 0) {
// return true;
// }
// valuesY[j] += valuesY[j - 1];
valuesY[j] += lastValuesY[j];
});
}
lastValuesY = valuesY;
xMinMax = self._getMinMaxValue(valuesX);
yMinMax = self._getMinMaxValue(valuesY);
if(i === 0) {
val.txx = xMinMax.max;
val.txn = xMinMax.min;
val.tyx = yMinMax.max;
val.tyn = yMinMax.min;
} else {
if(val.txx < xMinMax.max) {
val.txx = xMinMax.max;
}
if(val.txn > xMinMax.min) {
val.txn = xMinMax.min;
}
if(val.tyx < yMinMax.max) {
val.tyx = yMinMax.max;
}
if(val.tyn > yMinMax.min) {
val.tyn = yMinMax.min;
}
}
i++;
});
if(is100Percent) {
val.tyx = 1;
val.tyn = 0;
}
valGroup.y[key] = {
tyx: val.tyx,
tyn: val.tyn
};
valGroup.txx = val.txx;
valGroup.txn = val.txn;
val.tyx = 0;
val.tyn = 0;
//val = {txx: val.txx, txn: val.txn, tyx: 0, tyn: 0 };
if(valuesY.length) {
validValue = ChartUtil.getFirstValidListValue(valuesY);
if(self._isDate(validValue)) {
axisInfo.y[key].isTime = true;
} else if(typeof (validValue) === "undefined") {
return true;
} else if(typeof (validValue) !== "number") {
$.each(valuesY, function (idx, valueY) {
// valueLabels.push({
// text: valueY,
// value: idx
// });
// Add comments by RyanWu@20110707.
// For fixing the issue#15881.
// valueLabels.push(valueY);
var formatString = axis.y.annoFormatString, value = valueY;
if(formatString && formatString.length > 0) {
// value = $.format(value, formatString);
value = Globalize.format(value, formatString, self._getCulture());
} else {
value = value.toString();
}
// valueLabels.push(value);
valueLabels.push({
text: value,
value: valueY,
gridLine: false
});
// end by RyanWu@20110707.
});
//axis.y[k].annoMethod = "valueLabels";
axisInfo.y[key].annoMethod = "valueLabels";
if(!axis.y[k].valueLabels && axis.y[k].valueLabels.length === 0) {
//axis.y[k].valueLabels = valueLabels;
axisInfo.y[key].valueLabels = valueLabels;
} else {
axisInfo.y[key].valueLabels = axis.y[k].valueLabels;
}
//axis.y[parseInt(key, 10)].valueLabels = valueLabels;
axis.x.max = valuesY.length - 1;
axis.x.min = 0;
axis.y[k].unitMajor = 1;
axis.x.unitMinor = 0.5;
axisInfo.y[key].autoMax = false;
axisInfo.y[key].autoMin = false;
axisInfo.y[key].autoMajor = false;
axisInfo.y[key].autoMinor = false;
}
}
});
}
if(valuesX.length) {
validValue = ChartUtil.getFirstValidListValue(valuesX);
if(xAnnoMethod === "valueLabels" && xValueLabels && xValueLabels.length > 0) {
axisInfo.x.valueLabels = xValueLabels;
}
if(self._isDate(validValue)) {
axisInfo.x.isTime = true;
} else if(typeof (validValue) !== "number") {
$.each(valuesX, function (idx, valueX) {
var vLabel = {
}, xvl, xvlType;
if(xAnnoMethod === "valueLabels" && xValueLabels && xValueLabels.length && idx < xValueLabels.length) {
xvl = xValueLabels[idx];
xvlType = typeof xvl;
if(xvlType === "string") {
xvl = {
text: xvl
};
} else if(xvlType === "number" || self._isDate(xvl)) {
xvl = {
value: xvl
};
}
}
vLabel = $.extend({
text: valueX,
value: idx,
gridLine: false
}, xvl);
valueLabels.push(vLabel);
// valueLabels.push(valueX);
});
//axis.x.annoMethod = "valueLabels";
//axis.x.valueLabels = valueLabels;
axis.x.max = valuesX.length - 1;
axis.x.min = 0;
axis.x.unitMajor = 1;
axis.x.unitMinor = 0.5;
axisInfo.x.annoMethod = "valueLabels";
axisInfo.x.valueLabels = valueLabels;
axisInfo.x.autoMax = false;
axisInfo.x.autoMin = false;
axisInfo.x.autoMajor = false;
axisInfo.x.autoMinor = false;
}
}
return valGroup;
//return val;
};
wijchartcore.prototype._isVertical = function (compass) {
return compass === "west" || compass === "east";
};
wijchartcore.prototype._isDate = function (obj) {
if(!obj) {
return false;
}
return (typeof obj === 'object') && obj.constructor === Date;
};
wijchartcore.prototype._getMinMaxValue = function (array) {
var self = this, val = {
min: 0,
max: 0
}, i = 0, validValue;
if(!array.length) {
return val;
}
validValue = ChartUtil.getFirstValidListValue(array);
if(typeof (validValue) !== "number") {
if(self._isDate(validValue)) {
val.min = validValue;
val.max = validValue;
} else {
val.min = 0;
val.max = array.length - 1;
return val;
}
} else {
val.min = validValue;
val.max = validValue;
}
for(i = 0; i < array.length; i++) {
if(array[i] === null || typeof array[i] === "undefined") {
continue;
}
if(typeof array[i] === "number" && isNaN(array[i])) {
continue;
}
if(array[i] < val.min) {
val.min = array[i];
} else if(array[i] > val.max) {
val.max = array[i];
}
}
if(self._isDate(val.min)) {
val.min = $.toOADate(val.min);
val.max = $.toOADate(val.max);
}
return val;
};
wijchartcore.prototype._calculateMajorMinor = function (axisOptions, axisInfo) {
var self = this, o = self.options, canvasBounds = axisInfo.bounds || self.canvasBounds, autoMajor = axisOptions.autoMajor, autoMinor = axisOptions.autoMinor, maxData = axisInfo.max, minData = axisInfo.min, isTime = axisInfo.isTime, tinc = axisInfo.tinc, formatString = axisInfo.annoFormatString, maxText = null, minText = null, sizeMax = null, sizeMin = null, mx = null, mn = null, prec = null, _prec = null, textStyle = null, dx = maxData - minData, width = 0, height = 0, nticks = 0, major = 0;
if(autoMajor) {
textStyle = $.extend(true, {
}, o.textStyle, axisOptions.textStyle, axisOptions.labels.style);
if(isTime) {
// maxText = $.format($.fromOADate(maxData), formatString);
maxText = Globalize.format($.fromOADate(maxData), formatString, self._getCulture());
// minText = $.format($.fromOADate(minData), formatString);
minText = Globalize.format($.fromOADate(minData), formatString, self._getCulture());
mx = self._text(-1000, -1000, maxText).attr(textStyle);
mn = self._text(-1000, -1000, minText).attr(textStyle);
sizeMax = mx.wijGetBBox();
sizeMin = mn.wijGetBBox();
mx.wijRemove();
mx = null;
mn.wijRemove();
mn = null;
} else {
prec = ChartDataUtil.nicePrecision(dx);
_prec = prec + 1;
if(_prec < 0 || _prec > 15) {
_prec = 0;
}
mx = self._text(-1000, -1000, $.round(maxData, _prec).toString()).attr(textStyle);
mn = self._text(-1000, -1000, $.round(minData, _prec).toString()).attr(textStyle);
sizeMax = mx.wijGetBBox();
sizeMin = mn.wijGetBBox();
mx.wijRemove();
mx = null;
mn.wijRemove();
mn = null;
}
if(sizeMax.width < sizeMin.width) {
sizeMax.width = sizeMin.width;
}
if(sizeMax.height < sizeMin.height) {
sizeMax.height = sizeMin.height;
}
if(!self._isVertical(axisOptions.compass)) {
// Add comments by RyanWu@20100907.
// Subtract axisTextOffset because we must left
// the space between major text and major rect.
width = canvasBounds.endX - canvasBounds.startX - axisInfo.vOffset - axisInfo.axisTextOffset;
major = width / sizeMax.width;
if(Number.POSITIVE_INFINITY === major) {
nticks = 0;
} else {
nticks = parseInt(major.toString(), 10);
}
} else {
height = canvasBounds.endY - canvasBounds.startY - axisInfo.vOffset - axisInfo.axisTextOffset;
major = height / sizeMax.height;
if(Number.POSITIVE_INFINITY === major) {
nticks = 0;
} else {
nticks = parseInt(major.toString(), 10);
}
}
major = dx;
if(nticks > 0) {
dx /= nticks;
if(isTime) {
if(dx < tinc) {
major = tinc;
} else {
major = ChartDataUtil.niceTimeUnit(dx, axisInfo.annoFormatString);
}
} else {
axisInfo.tprec = ChartDataUtil.nicePrecision(dx);
major = ChartDataUtil.niceNumber(2 * dx, -prec, true);
if(major < dx) {
major = ChartDataUtil.niceNumber(dx, -prec + 1, false);
}
if(major < dx) {
major = ChartDataUtil.niceTickNumber(dx);
}
}
}
axisOptions.unitMajor = major;
}
if(autoMinor && axisOptions.unitMajor && !isNaN(axisOptions.unitMajor)) {
axisOptions.unitMinor = axisOptions.unitMajor / 2;
}
};
return wijchartcore;
})(wijmo.wijmoWidget);
chart.wijchartcore = wijchartcore;
var wijchartcore_options = (function () {
function wijchartcore_options() {
/**
* Sets the width of the chart in pixels.
* @remarks
* Note that this value overrides any value you may set in the <div> element that
* you use in the body of the HTML page
* If you specify a width in the <div> element that is different from this value,
* the chart and its border go out of synch.
* @type {?number}
*/
this.width = null;
/**
* Sets the height of the barchart in pixels.
* @remarks
* Note that this value overrides any value you may set in the <div> element that
* you use in the body of the HTML page. If you specify a height in the <div> element that
* is different from this value, the chart and its border go out of synch.
* @type {?number}
*/
this.height = null;
/**
* this option uses internal
* @ignore
*/
this.wijCSS = {
headerText: "wijchart-header-text",
headerContainer: "wijchart-header-container",
footerText: "wijchart-footer-text",
footerContainer: "wijchart-footer-container",
legendTitle: "wijchart-legend-title",
legendText: "wijchart-legend-text",
legend: "wijchart-legend",
legendDot: "chart-legend-dot",
legendIcon: "wijchart-legend-icon",
legendContainer: "wijchart-legend-container",
legendTextCover: "wijchart-legend-textCover",
axis: "wijchart-axis",
axisText: "wijchart-axis-text",
axisGridLine: "wijchart-axis-gridline",
axisTick: "wijchart-axis-tick",
axisLabel: "wijchart-axis-label",
labelText: "wijchart-label-text",
labelConnect: "wijchart-label-connect",
canvasObject: "wijchart-canvas-object"
};
/** A value that indicator the culture to format the chart text. */
this.culture = "";
/**
* Creates an array of series objects that contain data values and labels to display in the chart.
*/
this.seriesList = [];
/**
* Sets an array of style objects to use in rendering the bars for each series in the chart.
* @remarks
* Each style object in the array applies to one series in your seriesList,
* so you need specify only as many style objects as you have series objects
* in your seriesList. The style is also used in the legend entry for the series
* in your seriesList. The style is also used in the legend entry for the series
*/
this.seriesStyles = [
{
stroke: "#00cc00",
opacity: 0.9,
"stroke-width": 1
},
{
stroke: "#0099cc",
opacity: 0.9,
"stroke-width": 1
},
{
stroke: "#0055cc",
opacity: 0.9,
"stroke-width": 1
},
{
stroke: "#2200cc",
opacity: 0.9,
"stroke-width": 1
},
{
stroke: "#8800cc",
opacity: 0.9,
"stroke-width": 1
},
{
stroke: "#d9007e",
opacity: 0.9,
"stroke-width": 1
},
{
stroke: "#ff0000",
opacity: 0.9,
"stroke-width": 1
},
{
stroke: "#ff6600",
opacity: 0.9,
"stroke-width": 1
},
{
stroke: "#ff9900",
opacity: 0.9,
"stroke-width": 1
},
{
stroke: "#ffcc00",
opacity: 0.9,
"stroke-width": 1
},
{
stroke: "#ffff00",
opacity: 0.9,
"stroke-width": 1
},
{
stroke: "#ace600",
opacity: 0.9,
"stroke-width": 1
}
];
/**
* Sets an array of styles to use in rendering bars in the chart when you hover over them.
* @remarks
* Each style object in the array applies to a series in your seriesList,so you need
* specify only as many style objects as you have series objects in your seriesList
*/
this.seriesHoverStyles = [
{
opacity: 1,
"stroke-width": 1.5
},
{
opacity: 1,
"stroke-width": 1.5
},
{
opacity: 1,
"stroke-width": 1.5
},
{
opacity: 1,
"stroke-width": 1.5
},
{
opacity: 1,
"stroke-width": 1.5
},
{
opacity: 1,
"stroke-width": 1.5
},
{
opacity: 1,
"stroke-width": 1.5
},
{
opacity: 1,
"stroke-width": 1.5
},
{
opacity: 1,
"stroke-width": 1.5
},
{
opacity: 1,
"stroke-width": 1.5
},
{
opacity: 1,
"stroke-width": 1.5
},
{
opacity: 1,
"stroke-width": 1.5
}
];
/**
* Sets the amount of space in pixels between the chart area and the top edge of the <div> that defines the widget
*/
this.marginTop = 25;
/**
* Sets the amount of space in pixels between the chart area and the right edge of the <div> that defines the widget
*/
this.marginRight = 25;
/**
* Sets the amount of space in pixels between the chart area and the bottom edge of the <div> that defines the widget.
*/
this.marginBottom = 25;
/**
* Sets the amount of space in pixels between the chart area and the left edge of the <div> that defines the widget
*/
this.marginLeft = 25;
/**
* Creates an object to use for the fallback style of any chart text that does not
* have other style options set.
* @remarks
* Each type of text in the chart has a different set of styles applied by default, but if those styles are set to null,
* or if a particular style option is not set by default, the chart falls back on any style options you set in this option.
* Styles for specific types of chart text that may use this option as a fallback style are set in the following options:
* axis x labels style
* axis x textStyle
* axis y labels style
* axis y textStyle
* chartLabelStyle
* footer textStyle
* header textStyle
* hint contentStyle
* hint titleStyle
* legend textStyle
* legend titleStyle
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
this.textStyle = {
fill: "#888",
"font-size": 10,
stroke: "none"
};
/** Sets up the object to use as the header of the barchart.*/
this.header = {
text: /**
* A value that indicates the text to display in the header.
* @remarks
* If you leave this as an empty string, no header renders, regardless of any other header attributes.
*/
"",
style: /**
* A value that indicates all of the style attributes to use in rendering the header.
* @remarks
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr
* The style is the “attr” method’s parameters.
*/
{
fill: "none",
stroke: "none"
},
textStyle: /**
* A value that indicates the style of the header text.
* @remarks
* Note: Any style options set in the fallback textStyle option are used for any
* style options that are not set explicitly (or set by default) in this option.
*/
{
"font-size": 18,
fill: "#666",
stroke: "none"
},
compass: /**
* A value that indicates the position of the header in relation to the chart.
* @remarks
* Valid Values:
* "north" Renders the header above the chart.
* "south" Renders the header below the chart.
* "east" Renders the header to the right of the chart, with the text rotated 90 degrees.
* "west" Renders the header to the left of the chart, with the text rotated 270 degrees.
*/
"north",
visible: /**
* A value that indicates the visibility of the header.
*/
true
};
/**
* Sets up the object to use as the footer of the barchart.
*/
this.footer = {
text: /**
* A value that indicates the text to display in the footer.
* @remarks
* If you leave this as an empty string, no footer renders, regardless of any other footer attributes.
*/
"",
style: /**
* A value that indicates all of the style attributes to use in rendering the footer.
* @remarks
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
fill: "#fff",
stroke: "none"
},
textStyle: /**
* A value that indicates the style of the footer text.
* @remarks
* Note: Any style options set in the fallback textStyle option are used for
* any style options that are not set explicitly (or set by default) in this option.
* The style is defined in Raphael here is the documentation:http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
fill: "#000",
stroke: "none"
},
compass: /**
* A value that indicates the position of the footer in relation to the chart.
* @remarks
* Valid Values:
* "north" Renders the footer above the chart.
* "south" Renders the footer below the chart.
* "east" Renders the footer to the right of the chart, with the text rotated 90 degrees.
* "west" Renders the footer to the left of the chart, with the text rotated 270 degrees.
*/
"south",
visible: /**
* A value that indicates the visibility of the footer.
*/
false
};
/**
* Creates a legend object to display with the chart.
* @remarks
* By default, each series that you create in the seriesList is represented by a color in the legend,
* using the seriesList label that you specify. If you do not specify a label,
* it is labeled "undefined." If you do not want a series to appear in the legend,
* you can set the seriesList legendEntry attribute to false.
* By default, users can click a legend entry to toggle the data series it
* represents in the chart.See Clickable Legend for code that allows you to disable this function.
* @example
* // This code creates a chart with a legend that is positioned below the chart (south),
* // with series labels and colors in a row (horizontal), a grey outline and lighter
* // grey fill (style), has a title that reads "Legend" (text), has 5 pixels of
* // space around the text (textMargin), has series labels in a black 12-point font
* // (textStyle), and has a 14-point font title (titleStyle)
* $(document).ready(function () {
* $("#wijbarchart").wijbarchart({
* legend: {
* compass: "south",
* orientation: "horizontal",
* style: {fill: "gainsboro", stroke: "grey"},
* text: "Legend",
* textMargin: {left: 5, top: 5, right: 5, bottom: 5 },
* textStyle: {fill: "black", "font-size": 12},
* titleStyle: {"font-size": 14}
* },
* seriesList: [{
* label: "US",
* data: {
* x: ['PS3', 'XBOX360', 'Wii'],
* y: [12.35, 21.50, 30.56]
* }
* },
* {
* label: "Japan",
* data: {
* x: ['PS3', 'XBOX360', 'Wii'],
* y: [4.58, 1.23, 9.67]
* }
* },
* {
* label: "Other",
* data: {
* x: ['PS3', 'XBOX360', 'Wii'],
* y: [31.59, 37.14, 65.32]
* }
* }],
* });
* });
*/
this.legend = {
text: // / <summary>
/**
* A value that indicates the text to use as the title at the top of the legend.
* @remarks
* Set style properties on this text using the titleStyle attribute.
*/
"",
textMargin: /**
* A value in pixels that indicates the amount of space to leave around the text inside the legend.
*/
{
left: 2,
top: 2,
right: 2,
bottom: 2
},
style: /**
* A value that indicates the background color (fill) and border (stroke) of the legend.
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the 'attr' method's parameters.
*/
{
fill: "none",
stroke: "none"
},
textWidth: /**
* A value that indicates the width of the legend text.
*/
null,
textStyle: /**
* A value that indicates the style of the series label text. The text values come from the seriesList labels.
* @remarks
* Note: Any style options set in the fallback textStyle option are used for
* any style options that are not set explicitly (or set by default) in this option.
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the 'attr' method's parameters.
*/
{
fill: "#333",
stroke: "none"
},
titleStyle: /**
* A value that indicates the style of the legend title. The text for the title is set in the text
* attribute of the legend.
* @remarks
* Note: Any style options set in the fallback textStyle option are used for any
* style options that are not set explicitly (or set by default) in this option.
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the 'attr' method's parameters.
*/
{
"font-weight": "bold",
fill: "#000",
stroke: "none"
},
compass: /**
* A value that indicates the compass position of the legend.
* @remarks
* Valid Values: "north", "south", "east", "west"
*/
"east",
orientation: /**
* A value that indicates the orientation of the legend.
* @remarks
* Vertical orientation generally works better with an east or west compass setting for the
* legend, while horizontal is more useful with a north or south compass setting and a small
* number of series in the seriesList.
* Valid Values:
* "horizontal" Displays series labels and colors in a row.
* "vertical" Displays series labels and colors in a column.
*/
"vertical",
visible: /**
* A value that indicates whether to show the legend. Set this value to false to hide the legend.
*/
true
};
/**
* A value that contains all of the information to create the X and Y axes of the chart
*/
this.axis = {
x: /**
* An object containing all of the information to create the X axis of the chart.
*/
{
alignment: /**
* Sets the alignment of the X axis title text.
* @remarks
* Options are 'center', 'near', 'far'.
*/
"center",
style: /**
* A value that indicates the style of the X axis.
* @remarks
* The style is defined in Raphael here is the documentation:http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
stroke: "#999999",
"stroke-width": 0.5
},
visible: /**
* A value that indicates the visibility of the X axis.
*/
true,
textVisible: /**
* A value that indicates the visibility of the X axis text.
*/
true,
text: /**
* Sets the text to use for the X axis title.
*/
"",
textStyle: /**
* A value that indicates the style of text of the X axis.
* @remarks
* Note: Any style options set in the fallback textStyle option are used for
* any style options that are not set explicitly (or set by default) in this option.
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
fill: "#888",
"font-size": 15,
"font-weight": "bold"
},
labels: /**
* A value that provides information for the labels.
*/
{
style: /**
* A value that indicates the style of major text of the X axis.
* @remarks
* Note: Any style options set in the fallback textStyle option are used for any style
* options that are not set explicitly (or set by default) in this option.
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
fill: "#333",
"font-size": 11
},
textAlign: /**
* A value that indicates the alignment of major text of the X axis.
* @remarks
* Options are 'near', 'center' and 'far'.
*/
"near",
width: /**
* A value that indicates the width of major text of the X axis.
* @remarks
* If the value is null, then the width will be calculated automatically.
*/
null
},
compass: /**
* A value that indicates where to draw the X axis using the four points of a compass.
* @remarks
* "north" Draws the axis along the top edge of the chart.
* "south" Draws the axis along the bottom edge of the chart.
* "east" Draws the axis along the right edge of the chart.
* "west" Draws the axis along the left edge of the chart.
*/
"south",
autoMin: /**
* A value that indicates whether to calculate the axis minimum value automatically.
* @remarks
* If you set this value to false, in order to show major tick marks on the axis, you must
* specify a value for the min option.
*/
true,
autoMax: /**
* A value that indicates whether to calculate the axis maximum value automatically.
* @remarks
* If you set this value to false, in order to show major tick marks on the axis, you must specify a
* value for the max option.
*/
true,
min: /**
* A value that indicates the minimum value of the axis.
@type {?number}
*/
null,
max: /**
* A value that indicates the maximum value of the axis.
* @type {?number}
*/
null,
origin: /**
* A value that indicates the origin value of the X axis.
* @type {?number}
*/
null,
autoMajor: /**
* A value that indicates whether to calculate the major tick mark values automatically.
* @remarks
* If you set this value to false, in order to show major tick marks on the axis, you must
* specify a value for the unitMajor option.
*/
true,
autoMinor: /**
* A value that indicates whether to calculate the minor tick mark values automatically
* @remarks
* If you set this value to false, in order to show minor tick marks on the axis, you must
* specify a value for the unitMinor option.
*/
true,
unitMajor: /**
* A value that indicates the units between major tick marks.
* @type {?number}
*/
null,
unitMinor: /**
* A value that indicates the units between minor tick marks.
* @type {?number}
*/
null,
gridMajor: /**
* A value that provides information for the major grid line.
*/
{
visible: /**
* A value that indicates the visibility of the major grid line.
*/
false,
style: /**
* A value that indicates the style of the major grid line
* @remarks
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
stroke: "#CACACA",
"stroke-dasharray": "- "
}
},
gridMinor: /**
* A value that provides information for the minor grid line.
*/
{
visible: /**
* A value that indicates the visibility of the minor grid line.
*/
false,
style: /**
* A value that indicates the style of the minor grid line.
* @remarks
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
stroke: "#CACACA",
"stroke-dasharray": "- "
}
},
tickMajor: /**
* Creates an object with all of the settings to use in drawing tick marks that appear next to the numeric
* labels for major values along the X axis.
*/
{
position: /**
* A value that indicates the position of the major tick mark in relation to the axis.
* @remarks
* Valid Values: none, inside, outside, cross
*/
"none",
style: /**
* A value that indicates the style of major tick mark
* @remarks
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
fill: "black"
},
factor: /**
* A value that indicates an integral factor for major tick mark length.
*/
1
},
tickMinor: /**
* A value that provides information for the minor tick.
*/
{
position: /**
* A value that indicates the type of minor tick mark.
* @remarks
* Valid Values: none, inside, outside, cross
*/
"none",
style: /**
* A value that indicates the style of minor tick mark
* @remarks
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
fill: "black"
},
factor: /**
* A value that indicates an integral factor for minor tick mark length.
*/
1
},
annoMethod: /**
* The annoMethod option indicates how to label values along the axis.
* @remarks
* Valid Values:
* "values" Uses numeric seriesList data values to annotate the axis.
* "valueLabels" Uses the array of string values that you provide in the valueLabels option to
* annotate the axis.
*/
"values",
annoFormatString: /**
* The annoFormatString option uses Standard Numeric Format Strings to provide formatting for numeric
* values in axis labels.
*/
"",
valueLabels: /**
* The valueLabels option shows a collection of valueLabels for the X axis.
* @remarks
* If the annoMethod is "values", this option will lost effect, If the annoMethod is "valueLabels",
* the axis's label will set to this option's value.
*/
[]
},
y: // todo.
// autoOrigin: true,
// origin: null,
// tickLabel: "nextToAxis",
/**
* An object containing all of the information to create the Y axis of the chart.
*/
{
alignment: /**
* A value that indicates the alignment of the Y axis text.
* @remarks
* Options are 'center', 'near', 'far'.
*/
"center",
style: /**
* A value that indicates the style of the Y axis.
* @remarks
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
stroke: "#999999",
"stroke-width": 0.5
},
visible: /**
* A value that indicates the visibility of the Y axis.
*/
false,
textVisible: /**
* A value that indicates the visibility of the Y axis text.
*/
true,
text: /**
* Sets the text to use for the Y axis title.
*/
"",
textStyle: /**
* A value that indicates the style of text of the Y axis.
* @remarks
* Note: Any style options set in the fallback textStyle option are used for any style options that are not
* set explicitly (or set by default) in this option.
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
fill: "#888",
"font-size": 15,
"font-weight": "bold"
},
labels: /**
* A value that provides information for the labels.
*/
{
style: /**
* A value that indicates the style of major text of the Y axis.
* @remarks
* Note: Any style options set in the fallback textStyle option are used for any style options
* that are not set explicitly (or set by default) in this option.
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
fill: "#333",
"font-size": 11
},
textAlign: /**
* A value that indicates the alignment of major text of the Y axis.
* @remarks
* Options are 'near', 'center' and 'far'.
*/
"center",
width: /**
* A value that indicates the width major text of the Y axis.
* @remarks
* If the value is null, then the width will be calculated automatically.
* @type {?number}
*/
null
},
compass: /**
* A value that indicates the compass position of the Y axis.
* @remarks
* Options are 'north', 'south', 'east' and 'west'.
*/
"west",
autoMin: /**
* A value that indicates whether the axis minimum value is calculated automatically.
*/
true,
autoMax: /**
* A value that indicates whether the axis maximum value is calculated automatically.
*/
true,
min: /**
* A value that indicates the minimum value of the axis.
* @type {?number}
*/
null,
max: /**
* A value that indicates the maximum value of the axis.
* @type {?number}
*/
null,
origin: /**
* A value that indicates the origin value of the Y axis.
* @type {?number}
*/
null,
autoMajor: /**
* A value that indicates whether the major tick mark values are calculated automatically.
*/
true,
autoMinor: /**
* A value that indicates whether the minor tick mark values are calculated automatically.
*/
true,
unitMajor: /**
* A value that indicates the units between major tick marks.
* @type {?number}
*/
null,
unitMinor: /**
* A value that indicates the units between minor tick marks.
* @type {?number}
*/
null,
gridMajor: /**
* A value that provides information for the major grid line.
*/
{
visible: /**
* A value that indicates the visibility of the major grid line.
*/
true,
style: /**
* A value that indicates the style of the major grid line.
* @remarks
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
stroke: "#999999",
"stroke-width": 0.5,
"stroke-dasharray": "none"
}
},
gridMinor: /**
* A value that provides information for the minor grid line.
*/
{
visible: /**
* A value that indicates the visibility of the minor grid line.
*/
false,
style: /**
* A value that indicates the style of the minor grid line.
* @remarks
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
stroke: "#CACACA",
"stroke-dasharray": "- "
}
},
tickMajor: /**
* A value that provides information for the major tick.
*/
{
position: /**
* A value that indicates the type of major tick mark.
* @remarks
* Options are 'none', 'inside', 'outside' and 'cross'.
*/
"none",
style: /**
* A value that indicates the style of major tick mark.
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
fill: "black"
},
factor: /**
* A value that indicates an integral factor for major tick mark length.
*/
1
},
tickMinor: /**
* A value that provides information for the minor tick.
*/
{
position: /**
* A value that indicates the type of minor tick mark.
* @remarks
* Options are 'none', 'inside', 'outside' and 'cross'.
*/
"none",
style: /**
* A value that indicates the style of minor tick mark.
* @remarks
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
fill: "black"
},
factor: /**
* A value that indicates an integral factor for minor tick mark length.
*/
1
},
annoMethod: /**
* A value that indicates the method of annotation.
* @remarks
* Options are 'values', 'valueLabels'. If the value is “values”, when paint axis,
* the axis’s label will set to the data value of the series. If the value is “valueLabels”, when paint
* the axis, The axis’s label will set to a value which is set in axis’s valueLabels option.
*/
"values",
annoFormatString: /**
* The annoFormatString option uses Standard Numeric Format Strings to provide formatting for numeric
* values in axis labels.
*/
"",
valueLabels: /**
* The valueLabels option shows a collection of valueLabels for the X axis.
* @remarks
* If the annoMethod is "values", this option will lost effect, If the annoMethod is "valueLabels",
* the axis's label will set to this option's value.
*/
[]
}
};// todo.
// autoOrigin: true,
// origin: null,
// tickLabel: "nextToAxis",
/**
* Creates an object to use as the tooltip, or hint, when the mouse is over a chart element.
* @remarks
* By default, it displays the value of the seriesList label and Y data for the chart
*/
this.hint = {
enable: /**
* A value that indicates whether to show the tooltip.
* @remarks
* Set this value to false to hide hints even when the mouse is over a chart element.
*/
true,
content: /**
* A value that appears in the content part of the tooltip or a function which is
* used to get a value for the tooltip shown.
* @remarks
* If you do not set the content here, the hint displays content in the following order:
* The hint option's title attribute
* The seriesList option's label attribute, which shows "undefined" if you do not provide a label value
* The seriesList option's data y attribute
* You can format the numeric Y data in this attribute using a function
*/
null,
contentStyle: /**
* A value that indicates the style of content text.
* @remarks
* Note: Any style options set in the fallback textStyle option are used for any style
* options that are not set explicitly (or set by default) in this option.
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the 'attr' method's parameters.
*/
{
fill: "#d1d1d1",
"font-size": 16
},
title: /**
* A text value (or a function returning a text value) to display in the hint on a line
* above the content.
*/
null,
titleStyle: /**
* A value that indicates the style to use for the hint title text.
* @remarks
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* he style is the 'attr' method's parameters.
*/
{
fill: "#d1d1d1",
"font-size": 16
},
style: /**
* A value that indicates the fill color or gradient and outline thickness and color
* (stroke) of the rectangle used to display the hint.
* @remarks
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the 'attr' method's parameters.
*/
{
fill: "#000000",
"stroke-width": 2
},
animated: /**
* A value that indicates the effect to use when showing or hiding the hint when showAnimated
* or hideAnimated is not specified.
* @remarks
* The only animation style included is "fade." If you want a different one, you can create a custom animation
*/
"fade",
showAnimated: /**
* A value that indicates the animation effect to use when the hint appears after you mouse into the chart element.
* @remarks
* This allows you to use a different effect when you mouse out of a bar than when you mouse in. (See also
* hideAnimated.) If you set this value to null, the animated property supplies the animation effect to use.
* The only animation style included is "fade." If you want a different one, you can create a custom animation
*/
"fade",
hideAnimated: /**
* A value that indicates the animation effect to use when the hint goes away after you mouse out of the chart element.
* @remarks
* This allows you to use a different effect when you mouse into a chart elemrnt than when you mouse out.
* (See also showAnimated.) If you set this value to null, the animated property supplies the animation
* effect to use. The only animation style included is "fade." If you want a different one, you can create
* a custom animation
*/
"fade",
duration: /**
* A value that indicates the number of milliseconds it takes to show or hide the hint when you mouse over
* or mouse out of a bar with the showDuration or hideDuration attribute set to null.
*/
120,
showDuration: /**
* A value that indicates the number of milliseconds it takes for the indicated animation effect to completely
* show the tooltip.
* @remarks
* This allows you to use a different number of milliseconds when you mouse out of a bar than when you mouse in.
*/
120,
hideDuration: /**
* A value that indicates the number of milliseconds it takes for the indicated animation effect to completely
* hide the tooltip.
* @remarks
* This allows you to use a different number of milliseconds when you mouse into a bar than when you mouse out.
*/
120,
easing: /**
* A value that indicates the easing animation used to show or hide the hint when you mouse over or mouse out
* of a bar with the showEasing or hideEasing attribute set to null.
* @remarks
* The easing is defined in Raphael, the documentation is:http://raphaeljs.com/reference.html#Raphael.easing_formulas
*/
"",
showEasing: /**
* A value that indicates the easing effect to use when the hint appears after you mouse into the chart element.
* @remarks
* This allows you to use a different effect when you mouse out of a bar than when you mouse in. (See also
* hideEasing.) If you set this value to null, the easing property supplies the easing effect to use.
*/
"",
hideEasing: /**
* A value that indicates the easing effect to use when the hint goes away after you mouse out of the chart element.
* @remarks
* This allows you to use a different effect when you mouse into a bar than when you mouse out. (See also
* showEasing.) If you set this value to null, the easing property supplies the easing effect to use.
*/
"",
showDelay: /**
* A value that indicates the number of milliseconds to wait before showing the hint after the mouse moves
* into the chart element
* @remarks
* This allows you to use a different number of milliseconds when you mouse out of a bar than when you mouse in.
*/
0,
hideDelay: /**
* A value that indicates the number of milliseconds to wait before hiding the hint after the mouse leaves
* the chart element
* @remarks
* This allows you to use a different number of milliseconds when you mouse into a bar than when you mouse out.
*/
150,
compass: /**
* A value that indicates the compass position of the callout (the small triangle that points from the main
* hint box to the bar it describes) in relation to the hint box.
* @remarks
* Valid Values: west, east, south, southeast, southwest, northeast and northwest
*/
"north",
offsetX: /**
* A value that indicates the horizontal distance in pixels from the mouse pointer to the callout triangle
* of the hint.
* @remarks
* The position of the callout triangle depends on the compass setting of the hint callout.
*/
0,
offsetY: /**
* A value that indicates the vertical distance in pixels from the mouse pointer to the callout triangle
* of the hint.
* @remarks
* The position of the callout triangle depends on the compass setting of the hint callout.
*/
0,
showCallout: /**
* Determines whether to show the callout element, the small triangle that points from the main hint box
* to the bar it describes.
* @remarks
* To change the appearance of the callout, see these other hint attributes: calloutFilled,calloutFilledStyle,
* and compass.
*/
true,
calloutFilled: /**
* Determines whether to fill the callout (the small triangle that points from the main hint box to the bar
* it describes).
* @remarks
* If you set it to true, the callout triangle uses the colors you specify in the calloutFilledStyle
* attribute. Otherwise, it takes on the colors of the style attribute of the hint.
*/
false,
calloutFilledStyle: /**
* A value that indicates the style to use in rendering the callout (the small triangle that points from the
* main hint box to the bar it describes).
* @remarks
* In order for this attribute of the callout to take effect, you must also set the calloutFilled attribute
* to true. Otherwise, it takes on the colors of the style attribute of the hint.
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
fill: "#000"
}
};
/**
* Sets up an object that can display an indicator line running horizontally/vertically through the center
* of each chart element in the chart when the user clicks the chart element.
*/
this.indicator = {
visible: /**
* A value that indicates whether to show indicator lines when the user clicks a chart element in the chart.
*/
false,
style: /**
* A value that contains the fill color and outline color (stroke) of the indicator lines.
* @remarks
* Note that when you set the stroke color of the indicator line, it extends this color to the outline
* of the #hint:hint for the duration of the click.
*/
{
stroke: "#000000"
}
};
/**
* A value that indicates whether to show default chart labels.
*/
this.showChartLabels = true;
/**
* Sets all of the style options of the chart labels that show the value of each chart element.
* @remarks
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
this.chartLabelStyle = {
};
/**
* Sets the numeric format of the chart labels that show the value of each chart element. You can use Standard
* Numeric Format Strings.
*/
this.chartLabelFormatString = "";
/**
* Sets a value indicating whether you can set the font-family of the text using a class instead of options.
* @remarks
* Note: This applies only to the font-family in the current version.
*/
this.disableDefaultTextStyle = false;
/**
* A value that indicates whether to show a shadow around the edge of the chart.
*/
this.shadow = true;
/**
* Sets the array to use as a source for data that you can bind to the axes in your seriesList.
* @remarks
* Use the data option, and bind values to your X and Y axes. For more information please see the datasource demo:
* http://wijmo.com/demo/explore/?widget=BarChartsample=Array%20as%20datasource.
*/
this.dataSource = null;
/**
* Bind a field to each series's data x array
*/
this.data = null;
/**
* This event fires before the series changes. This event can be cancelled. "return false;" to cancel the event.
* @event
* @dataKey {array} oldSeriesList The old series list before changes.
* @dataKey {array} newSeriesList The new series list that will replace the old one.
*/
this.beforeSeriesChange = null;
/**
* This event fires when the series changes.
* @event
* @dataKey {object} data An object that contains new series values.
*/
this.seriesChanged = null;
/**
* This event fires before the canvas is painted. This event can be cancelled. "return false;" to cancel the event.
* @event
*/
this.beforePaint = null;
/**
* This event fires after the canvas is painted.
* @event
*/
this.painted = null;
}
return wijchartcore_options;
})();
wijchartcore.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijchartcore_options());
})(wijmo.chart || (wijmo.chart = {}));
var chart = wijmo.chart;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../wijchart/jquery.wijmo.wijchartcore.ts"/>
/*globals jQuery, Globalize*/
/*
* Depends:
* raphael.js
* globalize.js
* jquery.ui.widget.js
* jquery.wijmo.wijchartcore.js
*
*/
(function (chart) {
/**
* @widget
*/
var wijbarchart = (function (_super) {
__extends(wijbarchart, _super);
function wijbarchart() {
_super.apply(this, arguments);
}
wijbarchart.prototype._create = function () {
var self = this, o = self.options, defFill = self._getDefFill(), compass;
// if (o.horizontal) {
// $.extend(true, o.axis, {
// x: {
// compass: "west"
// },
// y: {
// compass: "south"
// }
// });
// }
if(o.horizontal) {
compass = o.axis.y.compass || "south";
o.axis.y.compass = o.axis.x.compass || "west";
o.axis.x.compass = compass;
}
$.extend(true, {
compass: "east"
}, o.hint);
self._handleChartStyles();
defFill = null;
_super.prototype._create.call(this);
self.chartElement.addClass(o.wijCSS.barChart);
};
wijbarchart.prototype._setOption = function (key, value) {
if(key === "horizontal") {
$.extend(true, this.options.axis, {
x: {
compass: value ? "west" : "south"
},
y: {
compass: value ? "south" : "west"
}
});
}
_super.prototype._setOption.call(this, key, value);
};
wijbarchart.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this, o = self.options, element = self.chartElement, fields = element.data("fields"), aniBarsAttr = fields && fields.bars;
element.removeClass(o.wijCSS.barChart);
_super.prototype.destroy.call(this);
if(aniBarsAttr && aniBarsAttr.length) {
$.each(aniBarsAttr, function (idx, barAttr) {
barAttr = null;
});
}
element.data("fields", null);
};
wijbarchart.prototype._clearChartElement = function () {
var self = this, o = self.options, fields = self.chartElement.data("fields");
_super.prototype._clearChartElement.call(this);
self.element.removeData("plotInfos");
if(!o.seriesTransition.enabled) {
if(fields && fields.aniBarsAttr) {
fields.aniBarsAttr = null;
}
}
};
wijbarchart.prototype._isBarChart = function () {
return true;
};
wijbarchart.prototype.getBar = /**
* This method returns the bar, which has a set of Raphaël objects (rects) that represent bars for the
* series data, from the specified index.
* @param {number} index The zero-based index of the bar to return.
* @returns {Raphael element} Bar object.
*/
function (index) {
var element = this.chartElement, fields = element.data("fields");
return fields.chartElements.bars[index];
};
wijbarchart.prototype._paintTooltip = /** end of public methods */
function () {
var self = this, element = self.chartElement, fields = element.data("fields");
_super.prototype._paintTooltip.call(this);
if(self.tooltip) {
if(fields && fields.trackers && fields.trackers.length) {
self.tooltip.setTargets(fields.trackers);
self.tooltip.setOptions({
relatedElement: fields.trackers[0]
});
}
}
};
wijbarchart.prototype._getTooltipText = function (fmt, target) {
var tar = $(target.node), dataObj, obj;
//value = dataObj.data,
if(tar.data("owner")) {
tar = tar.data("owner");
}
dataObj = tar.data("wijchartDataObj");
obj = {
data: dataObj,
value: dataObj.value,
label: dataObj.label,
total: dataObj.total,
target: target,
fmt: fmt,
x: dataObj.x,
y: dataObj.y
};
return $.proxy(fmt, obj)();
};
wijbarchart.prototype._preHandleSeriesData = function () {
_super.prototype._preHandleSeriesData.call(this);
var self = this, o = self.options, seriesList = o.seriesList;
$.each(seriesList, function (i, n) {
var data = n.data;
if(data.y) {
$.each(data.y, function (j, y) {
try {
if(!self._isDate(y)) {
data.y[j] = parseFloat(y);
}
} catch (e) {
data.y[j] = 1;
}
});
}
});
};
wijbarchart.prototype._paintPlotArea = function () {
var self = this, o = self.options;
this.barchartRender = new BarChartRender(this.chartElement, {
canvas: self.canvas,
bounds: self.canvasBounds,
tooltip: self.tooltip,
widgetName: self.widgetName,
horizontal: o.horizontal,
stacked: o.stacked,
axis: o.axis,
seriesList: o.seriesList,
seriesStyles: o.seriesStyles,
seriesHoverStyles: o.seriesHoverStyles,
seriesTransition: o.seriesTransition,
showChartLabels: o.showChartLabels,
textStyle: o.textStyle,
chartLabelStyle: o.chartLabelStyle,
chartLabelFormatString: o.chartLabelFormatString,
shadow: o.shadow,
disabled: o.disabled,
clusterOverlap: o.clusterOverlap,
clusterWidth: o.clusterWidth,
clusterSpacing: o.clusterSpacing,
is100Percent: o.is100Percent,
clusterRadius: o.clusterRadius,
animation: o.animation,
culture: self._getCulture(),
isYTime: self.axisInfo.y[0].isTime,
isXTime: self.axisInfo.x.isTime,
mouseDown: $.proxy(self._mouseDown, self),
mouseUp: $.proxy(self._mouseUp, self),
mouseOver: $.proxy(self._mouseOver, self),
mouseOut: $.proxy(self._mouseOut, self),
mouseMove: $.proxy(self._mouseMove, self),
click: $.proxy(self._click, self),
wijCSS: o.wijCSS,
widget: this
});
this.barchartRender.render();
};
wijbarchart.prototype._showSerieEles = function (seriesEle) {
var stacked = this.options.stacked, seriesIndex = -1;
$.each(seriesEle, function (i, bar) {
if(bar && bar.bar) {
bar.bar.show();
if(bar.bar.shadow) {
bar.bar.shadow.show();
}
if(bar.bar.tracker) {
bar.bar.tracker.show();
}
if($(bar.bar.node).data("wijchartDataObj")) {
$(bar.bar.node).data("wijchartDataObj").visible = true;
}
}
if(bar && bar.dcl) {
bar.dcl.show();
}
if(bar && bar.animatedBar && !bar.animatedBar.removed) {
bar.animatedBar.show();
}
if(bar.sIndex) {
seriesIndex = bar.sIndex;
}
});
//handle stacked
if(stacked && this.stackedSeriesObjs) {
this._handleStackedVisible(seriesEle.length);
}
};
wijbarchart.prototype._hideSerieEles = function (seriesEle) {
var stacked = this.options.stacked, seriesIndex = -1, totalLength = seriesEle.length;
$.each(seriesEle, function (i, bar) {
if(bar && bar.bar) {
bar.bar.hide();
if(bar.bar.shadow) {
bar.bar.shadow.hide();
}
if(bar.bar.tracker) {
bar.bar.tracker.hide();
}
if($(bar.bar.node).data("wijchartDataObj")) {
$(bar.bar.node).data("wijchartDataObj").visible = false;
}
}
if(bar && bar.dcl) {
bar.dcl.hide();
}
if(bar && bar.animatedBar && !bar.animatedBar.removed) {
bar.animatedBar.hide();
}
if(bar.sIndex) {
seriesIndex = bar.sIndex;
}
});
//handle stacked
if(stacked && this.stackedSeriesObjs) {
this._handleStackedVisible(seriesEle.length);
}
};
wijbarchart.prototype._handleStackedVisible = function (sCount) {
var _this = this;
function getVisible(ele) {
return $(ele.bar.node).data("wijchartDataObj").visible !== false;
}
function adjustBarH(ele, x, width) {
if(ele) {
if(ele.bar) {
ele.bar.attr("x", x);
ele.bar.attr("width", width);
}
if(ele.bar.shadow) {
ele.bar.shadow.attr("x", x);
ele.bar.shadow.attr("width", width);
}
if(ele.bar.tracker) {
ele.bar.tracker.attr("x", x);
ele.bar.tracker.attr("width", width);
}
}
}
function adjustBarV(ele, y, height) {
if(ele) {
if(ele.bar) {
ele.bar.attr("y", y);
ele.bar.attr("height", height);
}
if(ele.bar.shadow) {
ele.bar.shadow.attr("y", y);
ele.bar.shadow.attr("height", height);
}
if(ele.bar.tracker) {
ele.bar.tracker.attr("y", y);
ele.bar.tracker.attr("height", height);
}
}
}
function resetBarH(ele) {
if(ele) {
var x = ele.rect.x, width = ele.rect.width;
if(ele.bar) {
ele.bar.attr("x", x);
ele.bar.attr("width", width);
}
if(ele.bar.shadow) {
ele.bar.shadow.attr("x", x);
ele.bar.shadow.attr("width", width);
}
if(ele.bar.tracker) {
ele.bar.tracker.attr("x", x);
ele.bar.tracker.attr("width", width);
}
}
}
function resetBarV(ele) {
if(ele) {
var y = ele.rect.y, height = ele.rect.height;
if(ele.bar) {
ele.bar.attr("y", y);
ele.bar.attr("height", height);
}
if(ele.bar.shadow) {
ele.bar.shadow.attr("y", y);
ele.bar.shadow.attr("height", height);
}
if(ele.bar.tracker) {
ele.bar.tracker.attr("y", y);
ele.bar.tracker.attr("height", height);
}
}
}
if(this.stackedSeriesObjs) {
$.each(this.stackedSeriesObjs, function (i, ele) {
if(_this.options.horizontal) {
resetBarH(ele);
} else {
resetBarV(ele);
}
});
var eleVisibles = [], stackCount = this.element.data("fields").seriesEles.length;
;
for(var i = 0; i < stackCount; i++) {
eleVisibles.push(getVisible(this.stackedSeriesObjs[i + "0"]));
}
var adjusts = [], start = -1, end = -1, lastVisibleIndex = -1;
for(var i = eleVisibles.length - 1; i >= 0; i--) {
if(eleVisibles[i]) {
if(lastVisibleIndex - i > 1) {
adjusts.push({
start: lastVisibleIndex,
end: i + 1
});
}
lastVisibleIndex = i;
}
}
if(lastVisibleIndex > 0) {
adjusts.push({
start: lastVisibleIndex,
end: 0
});
}
$.each(adjusts, function (i, adjust) {
var sIndex = adjust.start, eIndex = adjust.end, sEl, eEl, nx, ny, nw, wh;
for(var i = 0; i < sCount; i++) {
sEl = _this.stackedSeriesObjs[sIndex + "" + i];
eEl = _this.stackedSeriesObjs[eIndex + "" + i];
if(_this.options.horizontal) {
nx = eEl.rect.x;
nw = sEl.rect.width + sEl.rect.x - eEl.rect.x;
adjustBarH(sEl, nx, nw);
} else {
nx = sEl.rect.y;
nw = eEl.rect.height + eEl.rect.y - sEl.rect.y;
adjustBarV(sEl, nx, nw);
}
}
});
}
};
wijbarchart.prototype._indicatorLineShowing = function (objs) {
_super.prototype._indicatorLineShowing.call(this, objs);
$.each(objs, function (i, obj) {
if(obj.bar) {
obj.bar.attr(obj.hoverStyle);
}
});
};
wijbarchart.prototype._removeIndicatorStyles = function (objs) {
$.each(objs, function (i, obj) {
if(obj.bar) {
obj.bar.attr(obj.style);
}
});
};
wijbarchart.prototype._supportStacked = function () {
return true;
};
wijbarchart.prototype._calculateParameters = function (axisInfo, options) {
_super.prototype._calculateParameters.call(this, axisInfo, options);
// check for bar chart and x axis expansion
if(axisInfo.id === "x") {
var minor = options.unitMinor, adj = //autoMin = options.autoMin,
//autoMax = options.autoMax,
this._getBarAdjustment(axisInfo);
if(adj === 0) {
adj = minor;
} else {
if(minor < adj && minor !== 0) {
adj = Math.floor(adj / minor) * minor;
}
}
/*if (autoMin) {
axisInfo.min -= adj;
}
if (autoMax) {
axisInfo.max += adj;
}*/
axisInfo.min -= adj;
axisInfo.max += adj;
this._calculateMajorMinor(options, axisInfo);
}
};
wijbarchart.prototype._getBarAdjustment = function (axisInfo) {
var len = 0, o = this.options, max = axisInfo.max, min = axisInfo.min, seriesList = o.seriesList, i = 0, xLen = 0;
for(i = 0; i < seriesList.length && seriesList[i].data.x; i++) {
xLen = seriesList[i].data.x.length;
if(len < xLen) {
len = xLen;
}
}
if(len > 1) {
return (max - min) / len * o.clusterWidth * 0.0125;
} else if(len === 1) {
if(min === 0.0 && max === 1.0) {
min = -1.0;
axisInfo.min = min;
}
return (max - min) * 0.0125;
} else {
return 0;
}
};
return wijbarchart;
})(chart.wijchartcore);
chart.wijbarchart = wijbarchart;
var wijbarchart_options = (function () {
function wijbarchart_options() {
/**
* Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijbarchart')";
/**
* @ignore
*/
this.wijCSS = {
barChart: "wijmo-wijbarchart",
barLabel: "wijbarchart-label",
barElement: "wijbarchart",
barTracker: "bartracker"
};
/**
* A value that determines whether the bar chart renders horizontally or vertically.
* @remarks
* If set to false, the numeric Y axis renders to the left, and the X axis labels render below the bars.
* @example
* // set the bar as column chart.
$("#wijbarchart").wijbarchart({
* horizontal: false,
* seriesList: [{
* legendEntry: false,
* data: {
* x: ['Ford', 'GM', 'Chrysler', 'Toyota', 'Nissan', 'Honda'],
* y: [.05, .04, .21, .27, .1, .24]
* }
* }]
* });
*/
this.horizontal = true;
/**
* Sets a value that determines whether to stack bars in the chart to show how each value in a series
* contributes to the total.
* @remarks
* If you want each bar to fill up 100 percet of the chart area, you can also set the is100Percent option to true.
* See Clustering Data for more information on the concept of using the same X values with multiple Y series.
* @example
* // set the chart to stacked bar chart.
* $("#wijbarchart").wijbarchart({
* stacked: true,
* seriesList: [{
* label: "US",
* data: { x: ['PS3', 'XBOX360', 'Wii'], y: [12.35, 21.50, 30.56] }
* }, {
* label: "Japan",
* data: { x: ['PS3', 'XBOX360', 'Wii'], y: [4.58, 1.23, 9.67] }
* }, {
* label: "Other",
* data: { x: ['PS3', 'XBOX360', 'Wii'], y: [31.59, 37.14, 65.32] }
* }]
* });
*/
this.stacked = false;
/**
* Sets a value that determines whether to present stacked bars as a total value of 100 percent, illustrating
* how each value contributes to the total.
* @remarks
* See Clustering Data for more information on the concept of using the same X values with multiple Y series.
* Note: This value has no effect if you do not set the stacked option to true.
* @example
* // This code results in bars with data for three countries stacked to fill 100% of the chart area, with each
* // series in a different color representing its percentage of the total.
* $("#wijbarchart").wijbarchart({
* stacked: true,
* is100Percent: true,
* seriesList: [{
* label: "US",
* legendEntry: true,
* data: { x: ['PS3', 'XBOX360', 'Wii'], y: [12.35, 21.50, 30.56] }
* }, {
* label: "Japan",
* legendEntry: true,
* data: { x: ['PS3', 'XBOX360', 'Wii'], y: [4.58, 1.23, 9.67] }
* }, {
* label: "Other",
* legendEntry: true,
* data: { x: ['PS3', 'XBOX360', 'Wii'], y: [31.59, 37.14, 65.32] }
* }],
* });
*/
this.is100Percent = false;
/**
* Sets the amount of each bar to render over the edge of the next bar in the same cluster,as a percentage of
* the bar width.
* @remarks
* Note: A cluster occurs when you have two or more series in your seriesList that have the same x data,
* but have different y data and different labels
*/
this.clusterOverlap = 0;
/**
* Sets the percentage of each cluster's allocated plot area that the bars in each cluster occupy.
* @remarks
* By default, the bars occupy 85% of the cluster's plot area, leaving a small gap between clusters. A setting
* of 100% removes the gap, or you can make the gap more dramatic with a setting of 50%.
* This setting may affect your clusterSpacing option setting.
*/
this.clusterWidth = 85;
/**
* Sets the number of pixels by which to round the corner-radius for the bars in the chart.
* @remarks
* The amount of rounding this produces depends on the size of the bar.For example, with a clusterRadius
* of 3, a small bar might look like a ball on the end, while a very large bar might only show a slight
* rounding of the corners.
*/
this.clusterRadius = 0;
/**
* Sets the amount of space in pixels between the bars in each cluster.
* @remarks
* This space may also be affected by the clusterOverlap and clusterWidth option settings.
*/
this.clusterSpacing = 0;
/**
* The animation option determines whether and how the animation is shown.
* @remarks
* It defines the animation effect and controls other aspects of the widget's animation, such as
* duration and easing. Set this option to false in order to disable the animation effect.
*/
this.animation = {
enabled: /**
* A value that determines whether to show animation. Set this option to false in order to disable easing.
*/
true,
duration: /**
* The duration option defines the length of the animation effect in milliseconds.
*/
400,
easing: /**
* Sets the type of animation easing effect that users experience when the wijbarchart series loads on the page
* @remarks
* For example, the wijbarchart series can bounce several times as it loads.
* The easing is defined in Raphael, the documentation is: http://raphaeljs.com/reference.html#Raphael.easing_formulas
*/
">"
};
/**
* Creates the animation object to use when the seriesList data changes.
* @remarks
* This allows you to visually show changes in data for the same series.
* Note: This animation does not appear when you first load or reload the page--it only occurs when data changes.
* @example
* // This code creates a chart with random data that regenerates when you click the button created in the
* second code snippet below
* $(document).ready(function () {
* $("#wijbarchart").wijbarchart({
* seriesList: [createRandomSeriesList("2013")],
* seriesTransition: {
* duration: 800,
* easing: "easeOutBounce"
* }
* });
* } );
* function reload() {
* $("#wijbarchart").wijbarchart("option", "seriesList", [createRandomSeriesList("2013")]);
* }
* function createRandomSeriesList(label) {
* var data = [],
* randomDataValuesCount = 12,
* labels = ["January", "February", "March", "April", "May", "June",
* "July", "August", "September", "October", "November", "December"],
* idx;
* for (idx = 0; idx < randomDataValuesCount; idx++) {
* data.push(Math.round(Math.random() * 100));
* }
* return {
* label: label,
* legendEntry: false,
* data: { x: labels, y: data }
* };
* }
*/
this.seriesTransition = {
enabled: /**
* A value that determines whether to show animation in redrawing bars when the seriesList data changes.
* Set this option to false to disable this animation.
*/
true,
duration: /**
* A value that indicates how long to display the series transition animation in milliseconds.
*/
400,
easing: /**
* Sets the type of animation easing effect to use in redrawing bars when the seriesList data changes.
* @remarks
* The easing is defined in Raphael, the documentation is:http://raphaeljs.com/reference.html#Raphael.easing_formulas
*/
">"
};
/**
* This event fires when the user clicks a mouse button.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IBarChartEventArgs} data Information about an event
*/
this.mouseDown = null;
/**
* Fires when the user releases a mouse button while the pointer is over the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IBarChartEventArgs} data Information about an event
*/
this.mouseUp = null;
/**
* Fires when the user first places the pointer over the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IBarChartEventArgs} data Information about an event
*/
this.mouseOver = null;
/**
* Fires when the user moves the pointer off of the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IBarChartEventArgs} data Information about an event
*/
this.mouseOut = null;
/**
* Fires when the user moves the mouse pointer while it is over a chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IBarChartEventArgs} data Information about an event
*/
this.mouseMove = null;
/**
* Fires when the user clicks the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IBarChartEventArgs} data Information about an event
*/
this.click = null;
}
return wijbarchart_options;
})();
wijbarchart.prototype.options = $.extend(true, {
}, chart.wijchartcore.prototype.options, new wijbarchart_options());
wijbarchart.prototype.widgetEventPrefix = "wijbarchart";
//$.widget("wijmo.wijbarchart", WijBarChart.prototype);
$.wijmo.registerWidget("wijbarchart", wijbarchart.prototype);
var XSpec = (function () {
function XSpec(nx) {
this.x = nx;
this.paSpec = [];
}
XSpec.prototype.stackValues = function () {
var self = this, len = self.paSpec.length, ps0;
if(len > 1) {
ps0 = self.paSpec[0];
$.each(self.paSpec, function (idx, ps) {
if(idx === 0) {
return true;
}
ps.y += ps0.y;
ps0 = ps;
});
}
};
return XSpec;
})();
// render the bar chart.
/** @ignore */
var BarChartRender = (function () {
function BarChartRender(element, options) {
this.options = options;
this.element = element;
this._init();
}
BarChartRender.prototype._init = function () {
var o = this.options, inverted = o.horizontal, xaxis = o.axis.x, bounds = o.bounds;
this.startLocation = {
x: bounds.startX,
y: bounds.startY
};
this.width = bounds.endX - this.startLocation.x;
this.height = bounds.endY - this.startLocation.y;
this.nSeries = o.seriesList.length , this.seriesList = $.arrayClone(o.seriesList);
this.seriesStyles = [].concat(o.seriesStyles.slice(0, this.nSeries));
this.seriesHoverStyles = [].concat(o.seriesHoverStyles.slice(0, this.nSeries));
this.xscale = chart.ChartUtil.getScaling(inverted, xaxis.max, xaxis.min, inverted ? this.height : this.width);
this.xlate = chart.ChartUtil.getTranslation(inverted, this.startLocation, xaxis.max, xaxis.min, this.xscale);
this.fields = this.element.data("fields") || {
};
this.chartElements = this.fields.chartElements || {
};
this.aniBarsAttr = this.fields.aniBarsAttr;
this.canvas = o.canvas;
};
BarChartRender.prototype._paintShadow = function (element, offset, stroke) {
if(this.options.shadow) {
chart.ChartUtil.paintShadow(element, offset, stroke);
}
};
BarChartRender.prototype.getMinDX = function (x) {
var minDx = Number.MAX_VALUE, len = x.length, idx, dx;
for(idx = 1; idx < len; idx++) {
dx = x[idx].x - x[idx - 1].x;
if(dx < minDx && dx > 0) {
minDx = dx;
}
}
if(minDx === Number.MAX_VALUE) {
return 2;
}
return minDx;
};
BarChartRender.prototype.stackValues = function (x) {
$.each(x, function (idx, xSpec) {
xSpec.stackValues();
});
return x;
};
BarChartRender.prototype.barPointList = function (seriesList) {
var x = [], getXSortedPoints = chart.ChartUtil.getXSortedPoints;
function addSeriesData(idx, series) {
var points = getXSortedPoints(series), nSeries = series.length, xs = null, lim = 0, j = 0, jlim = 0, first_point = true, xprev = 0, dupl = false;
if(points) {
lim = points.length;
}
if(x) {
jlim = x.length;
}
if(points === undefined) {
return;
}
$.each(points, function (p, point) {
if(first_point) {
first_point = false;
xprev = point.x;
} else {
if(xprev === point.x) {
dupl = true;
} else {
dupl = false;
}
xprev = point.x;
}
while(j < jlim && x[j].x < point.x) {
j++;
}
if(j < jlim) {
// use or insert before the existing item
if(x[j].x !== point.x) {
xs = new XSpec(point.x);
x.splice(j, 0, xs);
jlim = x.length;
} else {
xs = x[j];
}
} else {
// add a new item
xs = new XSpec(point.x);
x.push(xs);
jlim = x.length;
}
xs.paSpec.push({
y: point.y,
sIdx: idx,
pIdx: p,
dupl: dupl
});
});
}
$.each(seriesList, function (idx, series) {
addSeriesData(idx, series);
});
return x;
};
BarChartRender.prototype.adjustToLimits = function (val, min, max) {
if(val < min) {
return min;
}
if(val > max) {
return max;
}
return val;
};
BarChartRender.prototype.transformPoints = function (inverted, xscale, yscale, xlate, ylate, points) {
$.each(points, function (idx, point) {
var x = point.x, y = point.y, temp = 0;
point.x = xscale * x + xlate;
point.y = yscale * y + ylate;
if(inverted) {
temp = point.x;
point.x = point.y;
point.y = temp;
}
});
return points;
};
BarChartRender.prototype.paintDefaultChartLabel = function (rf, y, isTime, seriesTextStyle) {
var options = this.options, inverted = options.horizontal, canvas = options.canvas, wijCSS = options.wijCSS, culture = options.culture, textStyle = $.extend(true, {
}, options.textStyle, options.chartLabelStyle), pos = inverted ? {
x: rf.x + rf.width,
y: rf.y + rf.height / 2
} : {
x: rf.x + rf.width / 2,
y: rf.y
}, chartLabelFormatString = options.chartLabelFormatString, dclBox, defaultChartLabel, widget = this.options.widget, text = y;
if(seriesTextStyle) {
textStyle = $.extend(true, textStyle, seriesTextStyle);
}
/*if (isTime) {
text = $.wijchart.fromOADate(y);
} else {
text = $.wijchart.round(y, 2);
}*/
if(isTime) {
text = $.fromOADate(y);
}
if(chartLabelFormatString && chartLabelFormatString.length) {
//text = $.format(text, o.chartLabelFormatString);
text = Globalize.format(text, options.chartLabelFormatString, culture);
} else if(!isTime) {
text = $.round(text, 2);
}
defaultChartLabel = widget._text.call(widget, pos.x, pos.y, text).attr(textStyle);
$.wijraphael.addClass($(defaultChartLabel.node), wijCSS.barLabel);
dclBox = defaultChartLabel.getBBox();
if(inverted) {
defaultChartLabel.attr({
x: pos.x + dclBox.width / 2
});
} else {
defaultChartLabel.attr({
y: pos.y - dclBox.height / 2
});
}
return defaultChartLabel;
};
BarChartRender.prototype.paintBar = function (rp, y, height, xAxisInfo, yAxisInfo, seriesStyle, animated, shadowOffset, startLocation, clusterOverlap, preY, lastY, isYTime, seriesTextStyle, yaxis) {
var o = this.options, stacked = o.stacked, inverted = o.horizontal, is100Percent = o.is100Percent, xmin = xAxisInfo.min, xmax = xAxisInfo.max, ymin = yAxisInfo.min, ymax = yAxisInfo.max, xscale = xAxisInfo.scale, xlate = xAxisInfo.late, yscale = yAxisInfo.scale, ylate = yAxisInfo.late, hold, x, inPlotArea, rf, defaultChartLabel = null, r, style = seriesStyle, strokeWidth = seriesStyle["stroke-width"], stroke = seriesStyle.stroke, bar, barWidth, barHeight, animatedBar, start = -1;
if(yaxis.origin !== null) {
start = yscale * yaxis.origin + ylate;
}
if(stacked) {
if(is100Percent) {
if(lastY > 0) {
rp.height = y / lastY;
}
if(preY || preY === 0) {
rp.y = preY / lastY;
rp.height -= rp.y;
}
} else {
rp.height = y;
if(preY || preY === 0) {
rp.height -= preY;
rp.y = preY;
}
}
} else {
if(preY || preY === 0) {
// 1 bar over less overlap and 1 pixel
rp.x += rp.width * (1 - clusterOverlap);
rp.height = y;
}
}
x = [
{
x: rp.x,
y: rp.y
},
{
x: rp.x + rp.width,
y: rp.y + rp.height
}
];
inPlotArea = ((xmin <= x[0].x && x[0].x <= xmax) || (xmin <= x[1].x && x[1].x <= xmax)) && ((ymin <= x[0].y && x[0].y <= ymax) || (ymin <= x[1].y && x[1].y <= ymax));
x[0].x = this.adjustToLimits(x[0].x, xmin, xmax);
x[0].y = this.adjustToLimits(x[0].y, ymin, ymax);
x[1].x = this.adjustToLimits(x[1].x, xmin, xmax);
x[1].y = this.adjustToLimits(x[1].y, ymin, ymax);
x = this.transformPoints(inverted, xscale, yscale, xlate, ylate, x);
if(x[0].x > x[1].x) {
hold = x[0].x;
x[0].x = x[1].x;
x[1].x = hold;
}
if(x[0].y > x[1].y) {
hold = x[0].y;
x[0].y = x[1].y;
x[1].y = hold;
}
rf = {
x: x[0].x,
y: x[0].y,
width: x[1].x - x[0].x,
height: x[1].y - x[0].y
};
if(inPlotArea && !stacked) {
if(rf.width === 0) {
rf.width = 1;
}
if(rf.height === 0) {
rf.height = 1;
rf.y -= 1;
}
}
if(o.showChartLabels) {
defaultChartLabel = this.paintDefaultChartLabel(rf, y, isYTime, seriesTextStyle);
}
r = seriesStyle.r ? seriesStyle.r : o.clusterRadius;
if(r) {
style = $.extend(true, {
}, seriesStyle, {
r: 0
});
}
if(stroke !== "none" && strokeWidth) {
strokeWidth = parseInt(strokeWidth, 10);
}
if(!strokeWidth || isNaN(strokeWidth)) {
strokeWidth = 0;
}
barWidth = rf.width;
barHeight = rf.height;
if(strokeWidth > 1) {
strokeWidth--;
barWidth = rf.width - strokeWidth;
barHeight = rf.height - strokeWidth / 2;
rf.x += strokeWidth / 2;
}
if(barWidth < 0) {
barWidth = 0;
}
if(barHeight < 0) {
barHeight = 0;
}
if(animated) {
if(start === -1) {
if(inverted) {
start = startLocation.x + strokeWidth / 2;
} else {
start = startLocation.y + height - strokeWidth / 2;
}
}
if(r) {
if(inverted) {
if(y > yaxis.origin) {
bar = this.canvas.roundRect(rf.x, rf.y, barWidth, barHeight, 0, 0, r, r).hide();
} else {
bar = this.canvas.roundRect(rf.x, rf.y, barWidth, barHeight, r, r, 0, 0).hide();
}
animatedBar = this.canvas.rect(start, rf.y, rf.width, rf.height);
} else {
if(y > yaxis.origin) {
bar = this.canvas.roundRect(rf.x, rf.y, barWidth, barHeight, r, 0, 0, r).hide();
} else {
bar = this.canvas.roundRect(rf.x, rf.y, barWidth, barHeight, 0, r, r, 0).hide();
}
animatedBar = this.canvas.rect(rf.x, start, rf.width, rf.height);
}
this._paintShadow(animatedBar, shadowOffset);
animatedBar.wijAttr(style);
animatedBar.bar = bar;
} else {
if(inverted) {
bar = this.canvas.rect(start, rf.y, rf.width, barHeight);
} else {
bar = this.canvas.rect(rf.x, start, barWidth, rf.height);
}
animatedBar = bar;
}
if(defaultChartLabel) {
defaultChartLabel.attr({
opacity: 0
});
animatedBar.chartLabel = defaultChartLabel;
}
animatedBar.left = rf.x;
animatedBar.top = rf.y;
animatedBar.width = barWidth;
animatedBar.height = barHeight;
animatedBar.r = r;
} else {
if(r) {
if(inverted) {
if(y > yaxis.origin) {
bar = this.canvas.roundRect(rf.x, rf.y, barWidth, barHeight, 0, 0, r, r);
} else {
bar = this.canvas.roundRect(rf.x, rf.y, barWidth, barHeight, r, r, 0, 0);
}
} else {
if(y > yaxis.origin) {
bar = this.canvas.roundRect(rf.x, rf.y, barWidth, barHeight, r, 0, 0, r);
} else {
bar = this.canvas.roundRect(rf.x, rf.y, barWidth, barHeight, 0, r, r, 0);
}
}
} else {
bar = this.canvas.rect(rf.x, rf.y, barWidth, barHeight);
}
}
this._paintShadow(bar, shadowOffset);
if(animated && r) {
if(bar.shadow) {
bar.shadow.hide();
}
}
bar.wijAttr(seriesStyle);
return {
rect: rf,
dcl: defaultChartLabel,
animatedBar: animatedBar,
bar: bar
};
};
BarChartRender.prototype.paintClusters = function (seriesList, seriesStyles, seriesHoverStyles, xAxisInfo, yAxisInfo, width, height, startLocation, isYTime, isXTime) {
var self = this, o = self.options, clusterOverlap = o.clusterOverlap / 100, clusterWidth = o.clusterWidth / 100, shadowOffset = 1, clusterSpacing = o.clusterSpacing + shadowOffset, nSeries = seriesList.length, canvas = o.canvas, stacked = o.stacked, inverted = o.horizontal, yaxis = o.axis.y, widget = o.widget, wijCSS = o.wijCSS, animated = o.animation && o.animation.enabled, bpl, bw, pointX, chartLabels = [], bars = [], animatedBars = [], rects = [], sList = //isYTime = yAxisInfo.isTime,
[], seriesEles = [], trackers = canvas.set(), tooltipObj, strokeWidth = 0;
if(isYTime || isXTime) {
$.each(seriesList, function (i, s) {
var se = $.extend(true, {
}, s);
if(se.data && se.data.y && se.data.y.length && isYTime) {
$.each(se.data.y, function (idx, data) {
se.data.y[idx] = $.toOADate(data);
});
}
if(se.data && se.data.x && se.data.x.length && isXTime) {
$.each(se.data.x, function (idx, data) {
se.data.x[idx] = $.toOADate(data);
});
}
sList.push(se);
});
bpl = self.barPointList(sList);
} else {
bpl = self.barPointList(seriesList);
}
if(stacked) {
bpl = self.stackValues(bpl);
}
bw = self.getMinDX(bpl) * clusterWidth;
// fixed an issue that if the stroke-width is not 0, if set the clusterSpacing to small,
// some bars are shows too close.
$.each(seriesStyles, function (i, st) {
if(st["stroke-width"] && !isNaN(st["stroke-width"])) {
if(strokeWidth !== 0) {
strokeWidth = Math.min(parseFloat(st["stroke-width"]), strokeWidth);
} else {
strokeWidth = parseFloat(st["stroke-width"]);
}
}
});
// adjust the bar width (bw) to account for overlap
if(nSeries > 1 && !stacked) {
clusterOverlap -= (bpl.length * (nSeries - 1) * (clusterSpacing + strokeWidth * 2)) / (inverted ? height : width);
bw /= (nSeries * (1 - clusterOverlap) + clusterOverlap);
}
$.each(bpl, function (bplIdx, xs) {
var ps = xs.paSpec, ns = ps.length, sx, rp, bar, barInfo;
if(stacked) {
sx = bw;
} else {
sx = (bw * (ns * (1 - clusterOverlap) + clusterOverlap));
}
// calculate the first series rectangle
rp = {
x: xs.x - sx / 2,
y: 0,
width: bw,
height: ps[0].y
};
$.each(ps, function (psIndex, points) {
// if the array data.x's length is more than the data.y's,
// the rp.height is undefined. it will cause wrong.
if(rp.height === undefined) {
return true;
}
var sIdx = points.sIdx, pIdx = points.pIdx, seriesStyle = seriesStyles[sIdx], series = seriesList[sIdx], tracker, yAxisIndex = series.yAxis || 0, axisY = yaxis[yAxisIndex] || yaxis, axisInfoY = yAxisInfo[yAxisIndex] || yAxisInfo;
if(!rects[sIdx]) {
rects[sIdx] = [];
}
if(!seriesEles[sIdx]) {
seriesEles[sIdx] = [];
}
self.yscale = chart.ChartUtil.getScaling(!inverted, axisY.max, axisY.min, inverted ? width : height);
self.ylate = chart.ChartUtil.getTranslation(!inverted, startLocation, axisY.max, axisY.min, self.yscale);
axisInfoY.late = self.ylate;
axisInfoY.scale = self.yscale;
barInfo = self.paintBar(rp, points.y, height, xAxisInfo, axisInfoY, seriesStyle, animated, shadowOffset, startLocation, clusterOverlap, psIndex > 0 ? ps[psIndex - 1].y : null, ps[ps.length - 1].y, isYTime, series.textStyle, axisY);
bar = barInfo.bar;
tracker = bar.clone().attr(// In IE, if the tracker has an stroke width,
// the bar will show an black border.
{
opacity: 0.01,
fill: "white",
"stroke-width": 0,
"fill-opacity": 0.01
});
if(series.visible === false) {
bar.hide();
if(barInfo.dcl) {
barInfo.dcl.hide();
}
tracker.hide();
if(bar.shadow) {
bar.shadow.hide();
}
}
$.wijraphael.addClass($(bar.node), wijCSS.canvasObject + " " + wijCSS.barElement);
tooltipObj = $.extend(false, {
index: pIdx,
bar: bar,
type: "bar",
style: seriesStyle,
hoverStyle: seriesHoverStyles[sIdx],
x: series.data.x[pIdx],
y: series.data.y[pIdx],
visible: true
}, series);
$(bar.node).data("wijchartDataObj", tooltipObj);
// cache the bar position to show indicator line.
//if()
widget.dataPoints = widget.dataPoints || {
};
widget.pointXs = widget.pointXs || [];
if(o.horizontal) {
pointX = $.round(barInfo.rect.y + barInfo.rect.height / 2, 2);
} else {
pointX = $.round(barInfo.rect.x + barInfo.rect.width / 2, 2);
}
if(!widget.dataPoints[pointX.toString()]) {
widget.dataPoints[pointX.toString()] = [];
widget.pointXs.push(pointX);
}
widget.dataPoints[pointX.toString()].push(tooltipObj);
$(tracker.node).data("owner", $(bar.node));
$.wijraphael.addClass($(tracker.node), wijCSS.barElement + " " + wijCSS.barTracker);
barInfo.bar.tracker = tracker;
trackers.push(tracker);
bars.push(bar);
if(barInfo.animatedBar) {
animatedBars.push(barInfo.animatedBar);
}
if(barInfo.dcl) {
chartLabels.push(barInfo.dcl);
}
rects[sIdx][pIdx] = barInfo.rect;
seriesEles[sIdx][pIdx] = barInfo;
bar = null;
tracker = null;
});
});
//set default chart label to front.
$.each(chartLabels, function (sIdx, chartLabel) {
chartLabel.toFront();
});
trackers.toFront();
return {
bars: bars,
animatedBars: animatedBars,
rects: rects,
chartLabels: chartLabels,
seriesEles: seriesEles,
trackers: trackers
};
};
BarChartRender.prototype.processStackedElement = function (seriesEles) {
var eles = {
};
$.each(seriesEles, function (i, seriesEle) {
$.each(seriesEle, function (j, ele) {
ele.sIndex = i;
ele.stackIndex = j;
eles[i + "" + j] = ele;
});
});
this.options.widget.stackedSeriesObjs = eles;
};
BarChartRender.prototype.playAnimation = function (animatedBars) {
var self = this, o = self.options, animation = o.animation, animated = animation && animation.enabled, inverted = o.horizontal, seriesTransition = o.seriesTransition, duration, easing, barsAttr = [], diffAttr, chartLabelStyle = o.chartLabelStyle;
if(animated) {
duration = animation.duration || 2000;
easing = animation.easing || "linear";
$.each(animatedBars, function (idx, animatedBar) {
var params;
if(inverted) {
animatedBar.wijAttr({
width: 0
});
params = {
width: animatedBar.width,
x: animatedBar.left
};
} else {
animatedBar.wijAttr({
height: 0
});
params = {
height: animatedBar.height,
y: animatedBar.top
};
}
if(self.aniBarsAttr && seriesTransition.enabled) {
if(self.aniBarsAttr.length > idx) {
diffAttr = chart.ChartUtil.getDiffAttrs(self.aniBarsAttr[idx], animatedBar.attr());
if(inverted) {
diffAttr.x = self.aniBarsAttr[idx].x;
diffAttr.width = self.aniBarsAttr[idx].width;
} else {
diffAttr.y = self.aniBarsAttr[idx].y;
diffAttr.height = self.aniBarsAttr[idx].height;
}
if(diffAttr.path) {
delete diffAttr.path;
}
animatedBar.attr(diffAttr);
duration = seriesTransition.duration;
easing = seriesTransition.easing;
}
}
barsAttr.push($.extend(true, {
}, animatedBar.attr(), params));
if(animatedBar.tracker) {
animatedBar.tracker.hide();
}
//return;
animatedBar.stop().wijAnimate(params, duration, easing, function () {
var b = this, r = b.r, bar = b;
if(b.chartLabel) {
// fixed an issue that if the chart label's opacity is not 1,
// this code will change the opacity.
if(chartLabelStyle && chartLabelStyle.opacity) {
b.chartLabel.wijAnimate({
opacity: chartLabelStyle.opacity
}, 250);
} else {
b.chartLabel.wijAnimate({
opacity: 1
}, 250);
}
}
if(b.tracker) {
b.tracker.show();
b.tracker.attr({
width: b.width,
height: b.height,
x: b.attr("x"),
y: b.attr("y")
});
}
if(r) {
bar = b.bar;
bar.show();
if(bar.shadow) {
bar.shadow.show();
}
if(b.shadow) {
b.shadow.wijRemove();
b.shadow = null;
}
b.wijRemove();
//bar.animatedBar = null;
b = null;
}
});
});
self.aniBarsAttr = barsAttr;
}
};
BarChartRender.prototype.bindLiveEvents = function () {
var o = this.options, wijCSS = o.wijCSS, widgetName = o.widgetName, disabled = o.disabled, mouseDown = o.mouseDown, mouseUp = o.mouseUp, mouseOver = o.mouseOver, mouseOut = o.mouseOut, mouseMove = o.mouseMove, click = o.click, element = this.element, isFunction = $.isFunction;
// if (hintEnable && !tooltip) {
// hint = $.extend(true, {}, options.hint);
// hint.offsetY = hint.offsetY || -2;
// title = hint.title;
// content = hint.content;
// if ($.isFunction(title)) {
// hint.title = function () {
// return getTooltipText(title, this.target);
// };
// }
// if ($.isFunction(content)) {
// hint.content = function () {
// return getTooltipText(content, this.target);
// };
// }
// hint.beforeShowing = function () {
// if (this.target) {
// this.options.style.stroke =
// this.target.attrs.stroke ||
// this.target.attrs.fill;
// }
// };
// tooltip = canvas.tooltip(bars, hint);
// }
$("." + wijCSS.barElement, element[0]).on("mousedown." + widgetName, function (e) {
if(disabled) {
return;
}
if(isFunction(mouseDown)) {
var target = $(e.target), dataObj;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
mouseDown.call(element, e, dataObj);
dataObj = null;
}
}).on("mouseup." + widgetName, function (e) {
if(disabled) {
return;
}
if(isFunction(mouseUp)) {
var target = $(e.target), dataObj;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
mouseUp.call(element, e, dataObj);
dataObj = null;
}
}).on("mouseover." + widgetName, function (e) {
if(disabled) {
return;
}
if(isFunction(mouseOver)) {
var target = $(e.target), dataObj, bar;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
bar = dataObj.bar;
if(!dataObj.hoverStyle) {
if(bar) {
bar.wijAttr({
opacity: "0.8"
});
}
} else {
dataObj.initTransform = bar.matrix.toTransformString();
//bar.transform("");
bar.wijAttr(dataObj.hoverStyle);
}
mouseOver.call(element, e, dataObj);
dataObj = null;
}
}).on("mouseout." + widgetName, function (e) {
if(disabled) {
return;
}
var target = $(e.target), dataObj, bar;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
bar = dataObj.bar;
if(!dataObj.hoverStyle) {
if(bar) {
bar.wijAttr({
opacity: "1"
});
}
} else {
// when set the seriesStyle init the transform of the element.
bar.transform("");
if(bar.shadow) {
bar.shadow.transform("");
}
bar.wijAttr(dataObj.style);
}
if(isFunction(mouseOut)) {
mouseOut.call(element, e, dataObj);
}
dataObj = null;
//if (tooltip) {
// tooltip.hide();
//}
}).on("mousemove." + widgetName, function (e) {
if(disabled) {
return;
}
var target = $(e.target), dataObj, bar;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
bar = dataObj.bar;
if(isFunction(mouseMove)) {
mouseMove.call(element, e, dataObj);
}
dataObj = null;
//end of code for adding hover state effect.
}).on("click." + widgetName, function (e) {
if(disabled) {
return;
}
if(isFunction(click)) {
var target = $(e.target), dataObj;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
click.call(element, e, dataObj);
}
});
};
BarChartRender.prototype.unbindLiveEvents = function () {
var o = this.options, widgetName = o.widgetName, wijCSS = o.wijCSS, element = this.element;
// TO DO
$("." + wijCSS.barElement, element[0]).off(widgetName).off(// for jQuery 1.7.1
"." + widgetName);
};
BarChartRender.prototype.render = function () {
var o = this.options, inverted = o.horizontal, stacked = o.stacked, seriesList = this.seriesList, seriesStyles = this.seriesStyles, seriesHoverStyles = this.seriesHoverStyles, xaxis = o.axis.x, yaxis = o.axis.y, isYTime = o.isYTime, isXTime = o.isXTime, clusterInfos;
this.unbindLiveEvents();
if(inverted && !stacked) {
seriesList.reverse();
seriesStyles.reverse();
seriesHoverStyles.reverse();
}
if(this.nSeries === 0) {
return;
}
clusterInfos = this.paintClusters(seriesList, seriesStyles, seriesHoverStyles, {
min: xaxis.min,
max: xaxis.max,
late: this.xlate,
scale: this.xscale
}, yaxis, this.width, this.height, this.startLocation, isYTime, isXTime);
this.element.data("plotInfos", {
xscale: this.xscale,
xlate: this.xlate,
yscale: this.yscale,
ylate: this.ylate,
rects: clusterInfos.rects
});
this.playAnimation(clusterInfos.animatedBars);
//bars = clusterInfos.bars;
this.chartElements.bars = clusterInfos.bars;
this.chartElements.animatedBars = clusterInfos.animatedBars;
this.chartElements.chartLabels = clusterInfos.chartLabels;
this.fields.seriesEles = clusterInfos.seriesEles;
this.fields.trackers = clusterInfos.trackers;
//fields.chartElements = chartElements;
if(!this.fields.chartElements) {
this.fields.chartElements = {
};
}
if(inverted && !stacked) {
this.fields.seriesEles.reverse();
}
if(stacked) {
this.processStackedElement(this.fields.seriesEles);
}
$.extend(true, this.fields.chartElements, this.chartElements);
this.fields.aniBarsAttr = this.aniBarsAttr;
this.element.data("fields", this.fields);
this.bindLiveEvents();
};
return BarChartRender;
})();
chart.BarChartRender = BarChartRender;
})(wijmo.chart || (wijmo.chart = {}));
var chart = wijmo.chart;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../wijchart/jquery.wijmo.wijchartcore.ts"/>
/*globals $, Raphael, jQuery, document, window, Globalize*/
/*
* Depends:
* jquery.js
* jquery.ui.widget.js
* raphael.js
* globalize.js
* jquery.wijmo.raphael.js
* jquery.wijmo.wijchartcore.js
*
*/
(function (chart) {
/**
* @widget
*/
var wijlinechart = (function (_super) {
__extends(wijlinechart, _super);
function wijlinechart() {
_super.apply(this, arguments);
}
wijlinechart.prototype._create = function () {
var o = this.options;
this._handleChartStyles();
_super.prototype._create.call(this);
this.chartElement.addClass(o.wijCSS.lineChart);
if(o.type === "area") {
this.chartElement.addClass(o.wijCSS.areaChart);
}
};
wijlinechart.prototype.destroy = /** Remove the functionality completely.
*This will return the element back to its pre-init state.
*/
function () {
var o = this.options;
this.chartElement.removeClass(o.wijCSS.lineChart);
if(o.type === "area") {
this.chartElement.removeClass(o.wijCSS.areaChart);
}
_super.prototype.destroy.call(this);
if(this.aniPathsAttr && this.aniPathsAttr.length) {
$.each(this.aniPathsAttr, function (idx, pathAttr) {
pathAttr = null;
});
this.aniPathsAttr = null;
}
};
wijlinechart.prototype.getLinePath = /** Returns reference to raphael's path object for the line data with given index.
* @param {number} lineIndex The index of the series data for which to return lines.
* @returns {Raphael Element} Reference to raphael element object.
* @example
* //Get the first line.
* $("#linechart").wijlinechart("getLinePath", 0);
*/
function (lineIndex) {
var fields = this.chartElement.data("fields"), chartEles, und;
if(fields && fields.chartElements) {
chartEles = fields.chartElements;
if(chartEles.paths && chartEles.paths.length) {
return chartEles.paths[lineIndex];
}
}
return und;
};
wijlinechart.prototype.getLineMarkers = /** Returns reference to set of the raphael's objects
* what represents markers for the line data with given index.
* @param {number} lineIndex The index of the series data for which to return markers.
* @returns {Raphael Element} Reference to raphael element object.
* @example
* //Get the markers of the first line.
* $("#linechart").wijlinechart("getLineMarkers", 0);
*/
function (lineIndex) {
var o = this.options, fields = this.chartElement.data("fields"), chartEles, und;
if(o.seriesList && o.seriesList[lineIndex].markers && o.seriesList[lineIndex].markers.visible) {
if(fields && fields.chartElements) {
chartEles = fields.chartElements;
if(chartEles.markersSet && chartEles.markersSet.length) {
return chartEles.markersSet[lineIndex];
}
}
}
return und;
};
wijlinechart.prototype._showSerieEles = function (seriesEle) {
var o = this.options, obj;
if(seriesEle.markers) {
$.each(seriesEle.markers, function (i, marker) {
var dataObj = $(marker.node).data("wijchartDataObj");
if(dataObj && dataObj.lineSeries && dataObj.lineSeries.markers) {
if(!dataObj.lineSeries.markers.visible) {
return true;
}
}
marker.show();
});
}
if(seriesEle.dcl) {
$.each(seriesEle.dcl, function (i, dcl) {
if(o.showChartLabels) {
dcl.show();
}
});
}
if(seriesEle.path) {
obj = $(seriesEle.path.node).data("wijchartDataObj");
if(obj.visible) {
seriesEle.path.show();
if(seriesEle.path.shadow) {
seriesEle.path.shadow.show();
}
if(seriesEle.path.area) {
seriesEle.path.area.show();
}
if(seriesEle.path.tracker) {
seriesEle.path.tracker.show();
}
}
// mark the mark is not visible
if($(seriesEle.path.node).data("wijchartDataObj") && $(seriesEle.path.node).data("wijchartDataObj").virtualMarkers) {
$.each($(seriesEle.path.node).data("wijchartDataObj").virtualMarkers, function (i, markerObj) {
markerObj.visible = true;
});
}
}
};
wijlinechart.prototype._hideSerieEles = function (seriesEle) {
if(seriesEle.markers) {
$.each(seriesEle.markers, function (i, marker) {
marker.hide();
});
}
if(seriesEle.dcl) {
$.each(seriesEle.dcl, function (i, dcl) {
dcl.hide();
});
}
if(seriesEle.path) {
seriesEle.path.hide();
if(seriesEle.path.shadow) {
seriesEle.path.shadow.hide();
}
if(seriesEle.path.area) {
seriesEle.path.area.hide();
}
if(seriesEle.path.tracker) {
seriesEle.path.tracker.hide();
}
if($(seriesEle.path.node).data("wijchartDataObj") && $(seriesEle.path.node).data("wijchartDataObj").virtualMarkers) {
$.each($(seriesEle.path.node).data("wijchartDataObj").virtualMarkers, function (i, markerObj) {
markerObj.visible = false;
});
}
}
};
wijlinechart.prototype._supportStacked = function () {
return true;
};
wijlinechart.prototype._indicatorLineShowing = // when showing the indicator line, hover the line marker.
function (objs) {
_super.prototype._indicatorLineShowing.call(this, objs);
$.each(objs, function (i, obj) {
if(obj.marker) {
obj.marker.attr(obj.markerHoverStyle);
}
});
};
wijlinechart.prototype._removeIndicatorStyles = function (objs) {
$.each(objs, function (i, obj) {
if(obj.marker) {
obj.marker.attr(obj.markerStyle);
obj.marker.transform("s1");
}
});
};
wijlinechart.prototype._mouseDownInsidePlotArea = function (e, mousePos) {
_super.prototype._mouseDownInsidePlotArea.call(this, e, mousePos);
this._clearHoverState(true);
};
wijlinechart.prototype._mouseDown = function (e, args) {
_super.prototype._mouseDown.call(this, e, args);
};
wijlinechart.prototype._mouseUp = function (e, args) {
_super.prototype._mouseUp.call(this, e, args);
};
wijlinechart.prototype._mouseOver = function (e, lineSeries) {
if(!lineSeries || !(lineSeries.type === "line" || lineSeries.type === "marker")) {
return;
}
if(this.indicatorLine) {
return;
}
_super.prototype._mouseOver.call(this, e, lineSeries);
if(lineSeries.type === "marker") {
lineSeries = lineSeries.lineSeries;
}
if(lineSeries.path.removed) {
return;
}
if(this.hoverLine !== lineSeries || this.hoverLine === null) {
this.isNewLine = true;
if(this.hoverLine) {
if(!this.hoverLine.path.removed) {
// fixed the issue jQuery 1.9.
// the options will set on the prototype,
// so the seriesStyles will effect by other chart.
// if the chart type is not area, remove the style's fill.
if(this.options.type === "line" && this.hoverLine.lineStyle.fill) {
delete this.hoverLine.lineStyle.fill;
}
this.hoverLine.path.wijAttr(this.hoverLine.lineStyle);
if(this.hoverPoint && !this.hoverPoint.isSymbol) {
this.hoverPoint.marker.wijAttr(this.hoverPoint.markerStyle);
this.hoverPoint.marker.transform("s1");
}
}
}
if(lineSeries.lineHoverStyle) {
lineSeries.path.wijAttr(lineSeries.lineHoverStyle);
}
this.hoverLine = lineSeries;
this.hoverPoint = null;
this.hoverVirtualPoint = null;
}
};
wijlinechart.prototype._mouseOut = function (e, args) {
_super.prototype._mouseOut.call(this, e, args);
};
wijlinechart.prototype._mouseMove = function (e, args) {
_super.prototype._mouseMove.call(this, e, args);
};
wijlinechart.prototype._click = function (e, args) {
_super.prototype._click.call(this, e, args);
};
wijlinechart.prototype._mouseMoveInsidePlotArea = function (e, mousePos) {
var _this = this;
var tooltip = this.tooltip, hint = this.options.hint, markers, virtualMarkers, idx = 0, p, point, valueX, valueY, s = null, dataObj = null, op = null, title = hint.title, content = hint.content, isTitleFunc = $.isFunction(title), isContentFunc = $.isFunction(content), distance = 0;
if(tooltip) {
op = tooltip.getOptions();
}
if(this.hoverLine && !this.indicatorLine) {
if(this.isNewLine) {
if(hint.enable && tooltip) {
tooltip.hide();
}
this.isNewLine = false;
}
markers = this.hoverLine.lineMarkers;
virtualMarkers = this.hoverLine.virtualMarkers;
idx = -1;
p = {
x: 0,
y: 0
};
if(markers && markers.length) {
$.each(markers, function (i, marker) {
if(marker.removed) {
return true;
}
var box = marker.wijGetBBox(), pos = box.x + box.width / 2, dis = Math.abs(pos - mousePos.left);
if(i === 0 || dis < distance) {
distance = dis;
idx = i;
p = {
x: pos,
y: box.y + box.height / 2
};
}
});
if(this.hoverPoint && this.hoverPoint.index === idx) {
return;
}
if(idx > -1) {
if(markers[idx].removed) {
return;
}
point = $(markers[idx].node).data("wijchartDataObj");
if(point) {
if(this.hoverPoint && !this.hoverPoint.isSymbol) {
if(!this.hoverPoint.removed) {
this.hoverPoint.marker.wijAttr(this.hoverPoint.markerStyle);
this.hoverPoint.marker.transform("s1");
}
}
if(!point.isSymbol) {
if(!point.marker.removed) {
point.marker.wijAttr(point.markerHoverStyle);
}
}
}
this.hoverPoint = point;
this.hoverVirtualPoint = virtualMarkers[idx];
}
} else {
$.each(virtualMarkers, function (i, marker) {
var dis = Math.abs(marker.x - mousePos.left);
if(i === 0 || dis < distance) {
distance = dis;
idx = i;
p = {
x: marker.x,
y: marker.y
};
}
});
if(this.hoverVirtualPoint && this.hoverVirtualPoint.index === idx) {
return;
}
if(idx > -1) {
this.hoverPoint = null;
this.hoverVirtualPoint = virtualMarkers[idx];
}
}
if(tooltip) {
dataObj = this.hoverVirtualPoint;
valueX = dataObj.valX;
valueY = dataObj.valY;
if(isTitleFunc || isContentFunc) {
if(isTitleFunc) {
op.title = function () {
var obj = {
pointIndex: idx,
lineIndex: _this.hoverLine.index,
x: valueX,
y: valueY,
label: _this.hoverLine.label,
data: dataObj,
fmt: title
}, fmt = $.proxy(obj.fmt, obj), tit = fmt();
return tit;
};
}
if(isContentFunc) {
op.content = function () {
var obj = {
pointIndex: idx,
lineIndex: _this.hoverLine.index,
x: valueX,
y: valueY,
label: _this.hoverLine.label,
data: dataObj,
fmt: content
}, fmt = $.proxy(obj.fmt, obj), con = fmt();
return con;
};
}
}
s = $.extend({
stroke: this.hoverLine.path.attr("stroke")
}, hint.style);
op.style.stroke = s.stroke;
tooltip.showAt(p);
}
}
_super.prototype._mouseMoveInsidePlotArea.call(this, e, mousePos);
};
wijlinechart.prototype._mouseMoveOutsidePlotArea = function (e, mousePos) {
this._clearHoverState(false);
_super.prototype._mouseMoveOutsidePlotArea.call(this, e, mousePos);
};
wijlinechart.prototype._clearHoverState = function (keepTooltip) {
var tooltip = this.tooltip, hint = this.options.hint;
if(hint.enable && tooltip && !keepTooltip) {
tooltip.hide();
}
if(this.hoverLine) {
if(!this.hoverLine.path.removed) {
// fixed the issue jQuery 1.9.
// the options will set on the prototype,
// so the seriesStyles will effect by other chart.
// if the chart type is not area, remove the style's fill.
if(this.options.type === "line" && this.hoverLine.lineStyle.fill) {
delete this.hoverLine.lineStyle.fill;
}
this.hoverLine.path.wijAttr(this.hoverLine.lineStyle);
if(this.hoverPoint && !this.hoverPoint.isSymbol) {
this.hoverPoint.marker.wijAttr(this.hoverPoint.markerStyle);
this.hoverPoint.marker.transform("s1");
}
}
}
this.hoverLine = null;
this.hoverPoint = null;
this.hoverVirtualPoint = null;
};
wijlinechart.prototype._paintLegendIcon = function (x, y, width, height, style, legendIndex, seriesIndex, legendCss, series, leg) {
var self = this, o = this.options, icon = self.canvas.path(Raphael.format("M{0},{1}L{2},{3}", x, y + height / 2, x + width, y + height / 2)), dot;
$(icon.node).data("legendIndex", legendIndex).data("index", seriesIndex);
self.legendIcons.push(icon);
if(style) {
icon.attr($.extend(true, {
}, style, {
"stroke-width": o.legend.size.height
}));
}
$.wijraphael.addClass($(icon.node), legendCss);
var markerStyle = series.markerStyle;
markerStyle = $.extend({
fill: style.stroke,
stroke: style.stroke,
opacity: 1
}, markerStyle);
if(style["stroke-dasharray"]) {
icon.attr({
"stroke-width": //if stroke-width is bigger than 1,
//it doesn't look good.
1,
"stroke-dasharray": style["stroke-dasharray"]
});
}
if(series.markers && series.markers.visible) {
var type = series.markers.type;
if(!type) {
type = "circle";
}
dot = this.canvas.paintMarker(type, x + width / 2, y + height / 2, 3);
$.wijraphael.addClass($(dot.node), Raphael.format("{0} {1} {2}", o.wijCSS.legend, o.wijCSS.legendDot, o.wijCSS.canvasObject));
dot.attr(markerStyle);
$(dot.node).data("index", seriesIndex).data("legendIndex", legendIndex);
this.legendDots.push(dot);
}
return icon;
};
wijlinechart.prototype._paintLegend = function () {
var o = this.options, i = 0, ii = 0, idx = 0, legendIcon = null, chartsSeries = o.seriesList, chartsSeriesStyles = o.seriesStyles, chartSeries = null, chartSeriesStyle = null, box = null, x = 0, y = 0, markerStyle = null, type = null, dot = null;
$.extend(true, o, {
legend: {
size: {
width: 30,
height: 3
}
}
});
_super.prototype._paintLegend.call(this);
//if (o.legend.visible) {
// //set fill attr to legendIcons
// if (this.legends.length && this.legendIcons.length) {
// $.each(this.legendIcons, (i, icon) => {
// var b = icon.getBBox(),
// canvas = this.canvas,
// newIcon;
// newIcon = canvas.path(Raphael.format("M{0},{1}L{2},{3}",
// b.x, b.y + b.height / 2, b.x + b.width,
// b.y + b.height / 2)).attr($.extend(true, {}, icon.attr(), {
// stroke: icon.attr("stroke"),
// "stroke-width": o.legend.size.height
// }));
// $(newIcon.node)
// .data("legendIndex", $(icon.node).data("legendIndex"))
// .data("index", $(icon.node).data("index"));
// $.wijraphael.addClass($(newIcon.node), Raphael.format("{0} {1}",
// o.wijCSS.legend, o.wijCSS.legendIcon));
// icon.remove();
// icon = null;
// this.legendIcons[i] = newIcon;
// });
// }
// //add marker to legendIcons
// if (!o.legend.reversed) {
// for (i = 0, ii = chartsSeries.length; i < ii; i++) {
// chartSeries = chartsSeries[i];
// chartSeriesStyle = chartsSeriesStyles[i];
// if (chartSeries.legendEntry &&
// chartSeries.display !== "exclude") {
// if (chartSeries.markers && chartSeries.markers.visible) {
// legendIcon = this.legendIcons[idx];
// if (chartSeriesStyle["stroke-dasharray"]) {
// legendIcon.attr({
// //if stroke-width is bigger than 1,
// //it doesn't look good.
// "stroke-width": 1,
// "stroke-dasharray":
// chartSeriesStyle["stroke-dasharray"]
// });
// }
// box = legendIcon.wijGetBBox();
// x = box.x + box.width / 2;
// y = box.y + box.height / 2;
// markerStyle = chartSeries.markerStyle;
// markerStyle = $.extend({
// fill: chartSeriesStyle.stroke,
// stroke: chartSeriesStyle.stroke,
// opacity: 1
// }, markerStyle);
// type = chartSeries.markers.type;
// if (!type) {
// type = "circle";
// }
// dot = this.canvas.paintMarker(type, x, y, 3);
// $.wijraphael.addClass($(dot.node),
// Raphael.format("{0} {1} {2}",
// o.wijCSS.legend, o.wijCSS.legendDot,
// o.wijCSS.canvasObject));
// dot.attr(markerStyle);
// $(dot.node).data("index", i)
// .data("legendIndex", idx);
// this.legendDots.push(dot);
// }
// idx++;
// }
// }
// } else {
// for (i = chartsSeries.length - 1; i >= 0; i--) {
// chartSeries = chartsSeries[i];
// chartSeriesStyle = chartsSeriesStyles[i];
// if (chartSeries.legendEntry &&
// chartSeries.display !== "exclude") {
// if (chartSeries.markers && chartSeries.markers.visible) {
// legendIcon = this.legendIcons[idx];
// if (chartSeriesStyle["stroke-dasharray"]) {
// legendIcon.attr({
// //if stroke-width is bigger than 1,
// //it doesn't look good.
// "stroke-width": 1,
// "stroke-dasharray":
// chartSeriesStyle["stroke-dasharray"]
// });
// }
// box = legendIcon.wijGetBBox();
// x = box.x + box.width / 2;
// y = box.y + box.height / 2;
// markerStyle = chartSeries.markerStyle;
// markerStyle = $.extend({
// fill: chartSeriesStyle.stroke,
// stroke: chartSeriesStyle.stroke,
// opacity: 1
// }, markerStyle);
// type = chartSeries.markers.type;
// if (!type) {
// type = "circle";
// }
// dot = this.canvas.paintMarker(type, x, y, 3);
// $.wijraphael.addClass($(dot.node),
// Raphael.format("{0} {1} {2}",
// o.wijCSS.legend, o.wijCSS.legendDot,
// o.wijCSS.canvasObject));
// dot.attr(markerStyle);
// $(dot.node).data("index", i)
// .data("legendIndex", idx);
// this.legendDots.push(dot);
// }
// idx++;
// }
// }
// }
//}
};
wijlinechart.prototype._paintPlotArea = function () {
var o = this.options, opt;
if(!this.aniPathsAttr) {
this.aniPathsAttr = [];
}
this.linechartRender = new LineChartRender(this.chartElement, {
bounds: this.canvasBounds,
widgetName: this.widgetName,
canvas: this.canvas,
tooltip: this.tooltip,
wijCSS: o.wijCSS,
stacked: o.stacked,
hole: o.hole,
type: o.type,
axis: o.axis,
animation: o.animation,
seriesTransition: o.seriesTransition,
seriesList: o.seriesList,
seriesStyles: o.seriesStyles,
seriesHoverStyles: o.seriesHoverStyles,
showChartLabels: o.showChartLabels,
chartLabelStyle: o.chartLabelStyle,
chartLabelFormatString: o.chartLabelFormatString,
isXTime: this.axisInfo.x.isTime,
isYTime: this.axisInfo.y.isTime || this.axisInfo.y[0].isTime,
disabled: o.disabled,
culture: this._getCulture(),
hint: o.hint,
aniPathsAttr: this.aniPathsAttr,
chartLabelEles: this.chartLabelEles,
mouseDown: $.proxy(this._mouseDown, this),
mouseUp: $.proxy(this._mouseUp, this),
mouseOver: $.proxy(this._mouseOver, this),
mouseOut: $.proxy(this._mouseOut, this),
mouseMove: $.proxy(this._mouseMove, this),
click: $.proxy(this._click, this),
widget: this,
extremeValue: {
txx: this.extremeValue.txx,
txn: this.extremeValue.txn,
tyx: this.extremeValue.y[0].tyx,
tyn: this.extremeValue.y[0].tyn
}
});
this.linechartRender.render();
};
return wijlinechart;
})(chart.wijchartcore);
chart.wijlinechart = wijlinechart;
var wijlinechart_options = (function () {
function wijlinechart_options() {
/**
* Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijlinechart')";
/**
* All CSS classes used in widgets.
* @ignore
*/
this.wijCSS = {
lineChart: "wijmo-wijlinechart",
areaChart: "wijmo-wijareachart",
lineLabel: "wijlinechart-label",
lineElement: "wijlinechart",
areaElement: "wijlinechart-area",
lineTracker: "linetracker",
canvasMarker: "wijchart-canvas-marker"
};
/** A value that determines whether to show a stacked chart.*/
this.stacked = false;
/** Gets or sets the data hole value.
* @type {number}
* @remarks Data holes are used as placeholders for data points
* that indicate data is normally present but not in this case.
*/
this.hole = null;
/** An option that indicates the type of chart to be displayed.
* @remarks Options are 'line' and 'area'.
*/
this.type = "line";
/** The animation option defines the animation effect and controls other aspects of the widget's animation,
* such as duration and easing.
*/
this.animation = {
enabled: /** A value that determines whether to show the animation.
* Set this option to false in order to disable easing.
*/
true,
direction: /** A value that determines the effect for the animation.
* @remarks Options are 'horizontal' and 'vertical'.
*/
"horizontal",
duration: /** A value that indicates the duration for the animation.*/
2000,
easing: /** Sets the type of animation easing effect that users experience
* when the wijlinechart series is loaded to the page.
* For example, a user can have the wijlinechart series bounce several times as it loads.
* @remarks Values available for the animation easing effect include the following:
* easeInCubic ¨C Cubic easing in. Begins at zero velocity and then accelerates.
* easeOutCubic ¨C Cubic easing in and out. Begins at full velocity and then decelerates to zero.
* easeInOutCubic ¨C Begins at zero velocity, accelerates until halfway, and then decelerates to zero velocity again.
* easeInBack ¨C Begins slowly and then accelerates.
* easeOutBack ¨C Begins quickly and then decelerates.
* easeOutElastic ¨C Begins at full velocity and then decelerates to zero.
* easeOutBounce ¨C Begins quickly and then decelerates. The number of bounces is related to the duration, longer durations produce more bounces.
*/
"easeInCubic"
};
/** The seriesTransition option is used to animate series in the chart when just their values change.
* This is helpful for visually showing changes in data for the same series.
*/
this.seriesTransition = {
enabled: /** A value that determines whether to show animation when reload.*/
true,
duration: /** A value that indicates the duration for the series transition.*/
2000,
easing: /** A value that indicates the easing for the series transition.*/
"easeInCubic"
};
/** This event fires when the user clicks a mouse button.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijLineChartEventArgs} args The data with this event.
*/
this.mouseDown = null;
/** This event fires when the user releases a mouse button while the pointer is over the chart element.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijLineChartEventArgs} args The data with this event.
*/
this.mouseUp = null;
/** This event fires when the user first places the pointer over the chart element.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijLineChartEventArgs} args The data with this event.
*/
this.mouseOver = null;
/** This event fires when the user moves the pointer off of the chart element.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijLineChartEventArgs} args The data with this event.
*/
this.mouseOut = null;
/** This event fires when the user moves the mouse pointer while it is over a chart element.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijLineChartEventArgs} args The data with this event.
*/
this.mouseMove = null;
/** This event fires when the user clicks the chart element.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijLineChartEventArgs} args The data with this event.
*/
this.click = null;
}
return wijlinechart_options;
})();
;
wijlinechart.prototype.options = $.extend(true, {
}, chart.wijchartcore.prototype.options, new wijlinechart_options());
$.wijmo.registerWidget("wijlinechart", wijlinechart.prototype);
;
/** @ignore*/
var LineChartRender = (function () {
function LineChartRender(element, options) {
this.options = options;
this.element = element;
}
LineChartRender.prototype.render = function () {
var element = this.element, options = this.options, wijCSS = options.wijCSS, cBounds = options.bounds, widgetName = options.widgetName, canvas = options.canvas, ani = options.animation, seTrans = options.seriesTransition, hint = options.hint, tooltip = options.tooltip, mouseDown = options.mouseDown, mouseUp = options.mouseUp, mouseOver = options.mouseOver, mouseOut = options.mouseOut, mouseMove = options.mouseMove, click = options.click, markersSet = [], symbols = [], linesStyle = [], paths = [], shadowPaths = [], disabled = options.disabled, animationSet = canvas.set(), fieldsAniPathAttr = options.aniPathsAttr, aniPathsAttr = [], chartEles, fields = element.data("fields") || {
}, seriesEles = [], culture = options.culture, widget = options.widget, exVal = options.extremeValue, clipRect = {
enable: false,
left: -10,
top: -10,
right: 10,
bottom: 10
};
this.widget = widget;
this.renderLineChart(options, aniPathsAttr, fieldsAniPathAttr, paths, shadowPaths, markersSet, animationSet, symbols, linesStyle, seriesEles, culture);
//fix #35743, #30015
if(!options.axis.x.autoMax && options.axis.x.max < exVal.txx) {
clipRect.enable = true;
clipRect.right = 0;
}
if(!options.axis.x.autoMin && options.axis.x.min > exVal.txn) {
clipRect.enable = true;
clipRect.left = 0;
}
if(!options.axis.y.autoMax && options.axis.y.max < exVal.tyx) {
clipRect.enable = true;
clipRect.top = 0;
}
if(!options.axis.y.autoMin && options.axis.y.min > exVal.tyn) {
clipRect.enable = true;
clipRect.bottom = 0;
}
if(ani.enabled || seTrans.enabled) {
this.playAnimation(ani, seTrans, animationSet, cBounds, paths, fieldsAniPathAttr, clipRect);
} else if(clipRect.enable) {
this.setClipRect(clipRect, animationSet, cBounds);
}
fieldsAniPathAttr.length = 0;
$.each(aniPathsAttr, function (idx, aniPathAttr) {
fieldsAniPathAttr.push(aniPathAttr);
});
this.unbindLiveEvents(element, widgetName, wijCSS);
this.bindLiveEvents(element, canvas, cBounds, widgetName, mouseDown, mouseUp, mouseOver, mouseOut, mouseMove, click, disabled, hint, linesStyle, tooltip, wijCSS);
chartEles = {
paths: paths,
shadowPaths: shadowPaths,
markersSet: markersSet,
animationSet: animationSet,
symbols: symbols
};
if(!fields.chartElements) {
fields.chartElements = {
};
}
fields.seriesEles = seriesEles;
$.extend(true, fields.chartElements, chartEles);
element.data("fields", fields);
};
LineChartRender.prototype.setClipRect = function (clipRect, animationSet, cBounds) {
var width = cBounds.endX - cBounds.startX - clipRect.left + clipRect.right, height = cBounds.endY - cBounds.startY - clipRect.top + clipRect.bottom;
animationSet.wijAttr("clip-rect", Raphael.format("{0} {1} {2} {3}", (cBounds.startX + clipRect.left), (cBounds.startY + clipRect.top), width, height));
};
LineChartRender.prototype.playAnimation = function (ani, seTrans, animationSet, cBounds, paths, fieldsAniPathAttr, clipRect) {
var _this = this;
var duration = ani.duration, easing = ani.easing;
if(ani.direction === "horizontal") {
if(fieldsAniPathAttr && fieldsAniPathAttr.length && seTrans.enabled) {
duration = seTrans.duration;
easing = seTrans.easing;
}
this.playHAnimation(duration, easing, animationSet, cBounds, paths, clipRect);
} else {
if(clipRect.enable) {
this.setClipRect(clipRect, animationSet, cBounds);
}
$.each(paths, function (idx, path) {
if(typeof path === "undefined" || path === null) {
return true;
}
if(fieldsAniPathAttr && fieldsAniPathAttr.length > idx && seTrans.enabled) {
duration = seTrans.duration;
easing = seTrans.easing;
_this.playVAnimation(path, fieldsAniPathAttr, idx, duration, easing);
} else {
if(path.straight) {
_this.playVStraightAnimation(path, duration, easing);
}
}
});
}
};
LineChartRender.prototype.playVAnimation = function (path, fieldsAniPathAttr, idx, duration, easing) {
var aniPathAttr, diffAttr;
if(path.shadow) {
path.shadow.hide();
}
if(path.tracker) {
path.tracker.hide();
}
aniPathAttr = fieldsAniPathAttr[idx];
if(aniPathAttr && aniPathAttr.path) {
diffAttr = chart.ChartUtil.getDiffAttrs(aniPathAttr.path, path.attr());
}
if(!$.isEmptyObject(diffAttr)) {
path.attr(aniPathAttr.path);
path.wijAnimate(diffAttr, duration, easing, function () {
if(path.shadow && path.visible !== false) {
path.shadow.show();
}
if(path.tracker) {
path.tracker.show();
}
});
}
$.each(path.markers, function (i, marker) {
var diffMarkerAttr = chart.ChartUtil.getDiffAttrs(aniPathAttr.markers[i], marker.attr());
if(!$.isEmptyObject(diffMarkerAttr)) {
marker.attr(aniPathAttr.markers[i]);
marker.wijAnimate(diffMarkerAttr, duration, easing);
}
});
if(path.labels) {
$.each(path.labels, function (i, label) {
var diffLabelAttr = chart.ChartUtil.getDiffAttrs(aniPathAttr.labels[i], label.attr()), labelAttr = aniPathAttr.labels[i];
if(labelAttr && labelAttr.text) {
delete labelAttr.text;
}
if(!$.isEmptyObject(diffLabelAttr)) {
label.attr(labelAttr);
label.wijAnimate(diffLabelAttr, duration, easing);
}
});
}
if(path.area) {
diffAttr = chart.ChartUtil.getDiffAttrs(aniPathAttr.area, path.area.attr());
if(!$.isEmptyObject(diffAttr)) {
path.area.attr(aniPathAttr.area);
path.area.wijAnimate(diffAttr, duration, easing);
}
}
};
LineChartRender.prototype.playVStraightAnimation = function (path, duration, easing) {
var aniPathAttr, diffPath, area;
if(path.shadow) {
path.shadow.hide();
}
if(path.tracker) {
path.tracker.hide();
}
aniPathAttr = path.straight;
diffPath = path.attr().path;
path.attr({
path: aniPathAttr
});
path.wijAnimate({
path: diffPath
}, duration, easing, function () {
if(path.shadow && path.visible !== false) {
path.shadow.show();
}
if(path.tracker) {
path.tracker.show();
}
});
$.each(path.markers, function (i, marker) {
if(marker.straight) {
var cy = marker.attr().cy;
marker.attr({
cy: marker.straight
});
marker.wijAnimate({
cy: cy
}, duration, easing);
}
});
if(path.area) {
area = path.area;
aniPathAttr = area.straight;
diffPath = area.attr().path;
area.attr({
path: aniPathAttr
});
area.wijAnimate({
path: diffPath
}, duration, easing);
}
};
LineChartRender.prototype.playHAnimation = function (duration, easing, animationSet, cBounds, paths, clipRect) {
$.each(paths, function (idx, path) {
if(path.tracker) {
path.tracker.hide();
}
});
var clipRectEnable = clipRect.enable, width = cBounds.endX - cBounds.startX - clipRect.left + clipRect.right, height = cBounds.endY - cBounds.startY - clipRect.top + clipRect.bottom;
animationSet.wijAttr("clip-rect", Raphael.format("{0} {1} 0 {2}", (cBounds.startX + clipRect.left), (cBounds.startY + clipRect.top), height));
animationSet.wijAnimate({
"clip-rect": Raphael.format("{0} {1} {2} {3}", (cBounds.startX + clipRect.left), (cBounds.startY + clipRect.top), width, height)
}, duration, easing, function () {
if(this.tracker) {
this.tracker.show();
}
if(Raphael.vml && !clipRectEnable) {
//delete clip-rect's div in vml
var attrs = null, clipRect = //group = null,
null, node = this.node;
if(node && node.clipRect) {
attrs = this.attrs;
delete attrs["clip-rect"];
node.clipRect = null;
clipRect = $(node).parent();
clipRect.before(node);
clipRect.remove();
this.attr(attrs);
//Add comments to fix tfs issue 19385
if(attrs.src && attrs.src.length) {
this.attr({
"src": attrs.src
});
}
//end comments.
}
}
});
};
LineChartRender.prototype.renderLineChart = function (options, aniPathsAttr, fieldsAniPathAttr, paths, shadowPaths, markersSet, animationSet, symbols, linesStyle, seriesEles, culture) {
var _this = this;
var wijCSS = options.wijCSS, cBounds = options.bounds, canvas = options.canvas, stacked = options.stacked, hole = options.hole, type = options.type, axis = options.axis, ani = options.animation, seTrans = options.seriesTransition, needAnimated = false, linesSeries = options.seriesList, linesSeriesStyles = options.seriesStyles, linesHoverStyles = options.seriesHoverStyles, showChartLabels = options.showChartLabels, chartLabelStyle = options.chartLabelStyle, chartLabelFormatString = options.chartLabelFormatString, isXTime = options.isXTime, isYTime = options.isYTime, chartLabelEles = options.chartLabelEles, defaultChartLabels, firstYPoint, lastYPoint, fitType, valuesX, valuesY, lastValuesY = [], lastPathAttr = [], valX, pathArr, markers, paintSymbol, valsY;
$.each(linesSeries, function (k, lineSeries) {
var aniMarkersAttr = [], aniLabelsAttr = [], initAniPath = [], lineData, lineStyle, lineHoverStyle, lineMarkerStyle, lineMarkerHoverStyle, lineSeriesStyle, virtualMarkers = [];
if(lineSeries.display === "exclude") {
return true;
}
lineSeriesStyle = linesSeriesStyles[k];
//set default value of line series
lineSeries = $.extend(true, {
display: "show",
fitType: "line",
markers: {
visible: false,
type: "circle"
},
visible: true
}, lineSeries);
lineData = lineSeries.data;
lineStyle = $.extend({
stroke: "black",
opacity: 1,
fill: "none",
"stroke-linejoin": "round",
"stroke-linecap": "round"
}, lineSeriesStyle);
lineMarkerStyle = lineSeries.markerStyle;
lineMarkerStyle = $.extend({
fill: lineStyle.stroke,
stroke: lineStyle.stroke,
opacity: //Add comments by RyanWu@20110706.
//I can't add transform: "s1" here, because if so,
//The marker will be disapperaed after animation played
//in browsers which support vml(ie6/7/8). I don't know
//why. So I use the transform("s1") method to recover the
//original state of the marker after mouse out.
//transform: "s1",
//end by RyanWu@20110706.
1,
width: 3
}, lineMarkerStyle);
lineHoverStyle = linesHoverStyles[k];
lineMarkerHoverStyle = $.extend(true, {
}, lineHoverStyle, {
transform: "s1.5",
"stroke-width": 1
}, linesSeries.markerHoverStyle);
valuesX = [].concat(lineData.x);
valuesY = [].concat(lineData.y);
// Lines and markers:
markers = canvas.set();
pathArr = [];
fitType = lineSeries.fitType;
paintSymbol = false;
if(lineSeries.markers.symbol && lineSeries.markers.symbol.length) {
paintSymbol = true;
}
defaultChartLabels = canvas.set();
if(!fieldsAniPathAttr || fieldsAniPathAttr.length <= k || (ani.enabled && !seTrans.enabled)) {
needAnimated = true;
}
if(needAnimated) {
if(valuesY.length > 0) {
firstYPoint = chart.ChartUtil.getFirstValidListValue(valuesY);
if(isYTime) {
firstYPoint = $.toOADate(firstYPoint);
}
lastYPoint = chart.ChartUtil.getLastValidListValue(valuesY);
if(isYTime) {
lastYPoint = $.toOADate(lastYPoint);
}
}
}
valsY = _this.processYValues(valuesY, lineSeries.display, hole, stacked, lastValuesY);
$.each(valuesY, function (j, valY) {
valX = valuesX[j];
if(isXTime) {
valX = $.toOADate(valX);
}
valY = valuesY[j];
if(valsY[j].isHole) {
if(lineSeries.display === "excludeHole") {
return true;
}
if(!valsY[j].isValue) {
return true;
}
}
if(isYTime) {
valY = $.toOADate(valY);
}
if(valX === undefined) {
return false;
}
pathArr = _this.renderPoint(cBounds, canvas, initAniPath, pathArr, markers, aniMarkersAttr, animationSet, defaultChartLabels, aniLabelsAttr, chartLabelEles, chartLabelFormatString, needAnimated, firstYPoint, lastYPoint, valX, valY, lineData.y[j], axis, fitType, isXTime, isYTime, j, lineMarkerStyle, lineMarkerHoverStyle, lineSeries, paintSymbol, showChartLabels, symbols, valuesX, valuesY, valsY, lineSeries.display, stacked, virtualMarkers, culture, wijCSS);
});
_this.renderPath(canvas, cBounds, lineSeries, paths, shadowPaths, linesStyle, lineHoverStyle, lineMarkerStyle, lineMarkerHoverStyle, markers, markersSet, animationSet, pathArr, aniPathsAttr, initAniPath, lineStyle, chartLabelStyle, aniMarkersAttr, aniLabelsAttr, defaultChartLabels, k, type, lastPathAttr, stacked, virtualMarkers, wijCSS);
seriesEles.push({
markers: markers,
path: paths[paths.length - 1],
shadowPath: shadowPaths[shadowPaths.length - 1],
dcl: defaultChartLabels
});
});
//fix #35792
$.each($.merge([], paths).reverse(), function (idx, path) {
path.toFront();
if(path.area) {
path.area.toFront();
}
});
//end #35792
$.each(paths, function (idx, path) {
if(path.tracker) {
path.tracker.toFront();
}
});
//markers should always be in front of trackers.
$.each(paths, function (idx, path) {
if(path.markers) {
path.markers.toFront();
}
});
};
LineChartRender.prototype.renderPath = function (canvas, bounds, lineSeries, paths, shadowPaths, linesStyle, lineHoverStyle, lineMarkerStyle, lineMarkerHoverStyle, markers, markersSet, animationSet, pathArr, aniPathsAttr, initAniPath, lineStyle, chartLabelStyle, aniMarkersAttr, aniLabelsAttr, defaultChartLabels, pathIdx, type, lastPathAttr, stacked, virtualMarkers, wijCSS) {
var path, fill, fillOpacity, opacity, area, startX, endX, tracker, trackerWidth, labelStyle, prevPathArr, prevPath, currentPathArr, idx, noFillStyle;
path = canvas.path(pathArr.join(" "));
path.straight = initAniPath.join(" ");
//shadow
chart.ChartUtil.paintShadow(path, 1, "#cccccc");
if(pathIdx === 0) {
lastPathAttr.length = 0;
if(pathArr.length > 1) {
startX = pathArr[1];
endX = pathArr[pathArr.length - 2];
} else {
startX = bounds.startX;
endX = bounds.endX;
}
$.merge(lastPathAttr, [
"L",
startX,
bounds.endY,
"L",
endX,
bounds.endY
]);
}
tracker = canvas.path(pathArr.join(" "));
path.tracker = tracker;
if(lineStyle["stroke-width"]) {
trackerWidth = 10 + parseFloat(lineStyle["stroke-width"]);
} else {
trackerWidth = 10;
}
tracker.attr({
"stroke-width": trackerWidth,
stroke: "#C0C0C0",
opacity: 0.01
});
$.wijraphael.addClass($(tracker.node), Raphael.format("{0} {1} {2}", wijCSS.canvasObject, wijCSS.lineElement, wijCSS.lineTracker));
$(tracker.node).data("owner", $(path.node));
if(type === "area") {
if(lineStyle.fill && lineStyle.fill !== "none") {
fill = lineStyle.fill;
delete lineStyle.fill;
} else {
fill = lineStyle.stroke;
}
fillOpacity = 0.5;
opacity = 1;
if(lineStyle["fill-opacity"] && lineStyle["fill-opacity"] !== "none") {
fillOpacity = lineStyle["fill-opacity"];
}
if(lineStyle["opacity"] && lineStyle["opacity"] !== "none") {
opacity = lineStyle["opacity"];
}
path.wijAttr(lineStyle);
if(pathArr.length > 1) {
startX = pathArr[1];
} else {
startX = bounds.startX;
}
if(stacked) {
//fix #35792
/*
if (pathIdx > 0) {
prevPathArr = Raphael.parsePathString(
paths[pathIdx - 1].attr("path"));
if (prevPathArr && prevPathArr.length > 0) {
for (idx = prevPathArr.length - 1; idx >= 0; idx--) {
prevPath = prevPathArr[idx];
if (prevPath.length === 3) {
pathArr.push("L");
pathArr.push(prevPath[1]);
pathArr.push(prevPath[2]);
}
}
pathArr.push("Z");
}
}
else {
*/
pathArr.push("V");
pathArr.push(bounds.endY);
pathArr.push("H");
pathArr.push(startX);
pathArr.push("Z");
//}
//end
} else {
currentPathArr = Raphael.parsePathString(path.attr("path"));
if(currentPathArr && currentPathArr.length > 0) {
pathArr = [];
$.each(currentPathArr, function (i, currentPath) {
$.each(currentPath, function (j, val) {
pathArr.push(val);
});
if(currentPath[0] === "M") {
startX = currentPath[1];
}
if(i < currentPathArr.length - 1 && currentPathArr[i + 1][0] === "M") {
pathArr.push("V");
pathArr.push(bounds.endY);
pathArr.push("H");
pathArr.push(startX);
pathArr.push("Z");
}
if(i === currentPathArr.length - 1) {
pathArr.push("V");
pathArr.push(bounds.endY);
pathArr.push("H");
pathArr.push(startX);
pathArr.push("Z");
}
});
}
}
area = canvas.path(pathArr.join(" "));
$.wijraphael.addClass($(area.node), wijCSS.areaElement);
area.wijAttr({
fill: fill,
opacity: opacity,
"fill-opacity": fillOpacity,
stroke: "none"
});
initAniPath.push("V");
initAniPath.push(bounds.endY);
initAniPath.push("H");
initAniPath.push(startX);
initAniPath.push("Z");
area.straight = initAniPath.join(" ");
//area.toBack();
path.area = area;
animationSet.push(area);
aniPathsAttr.push({
path: $.extend(true, {
}, path.attr()),
area: $.extend(true, {
}, area.attr()),
markers: aniMarkersAttr,
labels: aniLabelsAttr
});
} else {
//remove fill attribute when painting line.
//path.wijAttr(lineStyle);
noFillStyle = $.extend(true, {
}, lineStyle);
if(noFillStyle.fill) {
delete noFillStyle.fill;
}
path.wijAttr(noFillStyle);
//end comments.
aniPathsAttr.push({
path: $.extend(true, {
}, path.attr()),
markers: aniMarkersAttr,
labels: aniLabelsAttr
});
}
path.markers = markers;
paths.push(path);
if(path.shadow) {
shadowPaths[pathIdx] = path.shadow;
}
animationSet.push(path);
linesStyle[pathIdx] = {
lineStyle: lineStyle,
lineHoverStyle: lineHoverStyle,
markerStyle: lineMarkerStyle,
markerHoverStyle: lineMarkerHoverStyle
};
if(!lineSeries.markers.visible || lineSeries.display === "hide") {
markers.hide();
}
if(!lineSeries.visible || lineSeries.display === "hide") {
path.hide();
if(path.shadow) {
path.shadow.hide();
}
if(path.area) {
path.area.hide();
}
path.visible = false;
}
if(lineSeries.markers.style) {
markers.attr(lineSeries.markers.style);
}
markers.toFront();
if(defaultChartLabels.length) {
labelStyle = $.extend(true, {
}, chartLabelStyle);
if(lineSeries.textStyle) {
labelStyle = $.extend(true, labelStyle, lineSeries.textStyle);
}
defaultChartLabels.attr(labelStyle);
defaultChartLabels.toFront();
path.labels = defaultChartLabels;
}
markersSet[pathIdx] = markers;
lineSeries.index = pathIdx;
lineSeries.type = "line";
lineSeries.path = path;
lineSeries.lineMarkers = markers;
lineSeries.lineStyle = lineStyle;
lineSeries.lineHoverStyle = lineHoverStyle;
lineSeries.virtualMarkers = virtualMarkers;
$.wijraphael.addClass($(path.node), Raphael.format("{0} {1}", wijCSS.canvasObject, wijCSS.lineElement));
$(path.node).data("wijchartDataObj", lineSeries);
};
LineChartRender.prototype.renderPoint = function (cBounds, canvas, initAniPath, pathArr, markers, aniMarkersAttr, animationSet, defaultChartLabels, aniLabelsAttr, chartLabelEles, chartLabelFormatString, needAnimated, firstYPoint, lastYPoint, valX, valY, dataY, axis, fitType, isXTime, isYTime, pointIdx, lineMarkerStyle, lineMarkerHoverStyle, lineSeries, paintSymbol, showChartLabels, symbols, valuesX, valuesY, valsY, display, stacked, virtualMarkers, culture, wijCSS) {
var width = cBounds.endX - cBounds.startX, height = cBounds.endY - cBounds.startY, minX = axis.x.min, minY = axis.y.min, maxX = axis.x.max, maxY = axis.y.max, kx = width / (maxX - minX), ky = height / (maxY - minY), marker, dot, val, X = 0, Y, initAniY, markerData, defaultChartLabel, markerVisible = lineSeries.markers.visible, widget = this.widget, pointX;
if(isNaN(valX) || typeof valX === "string") {
val = pointIdx;
} else {
val = valX;
}
X = cBounds.startX + (val - minX) * kx;
Y = cBounds.endY - (valY - minY) * ky;
valsY[pointIdx].x = X;
valsY[pointIdx].y = Y;
if(needAnimated) {
initAniY = firstYPoint + (lastYPoint - firstYPoint) / (maxX - minX) * (val - minX);
initAniY = cBounds.endY - (initAniY - minY) * ky;
initAniPath.push(valsY[pointIdx].idx ? "L" : "M");
initAniPath.push(X);
initAniPath.push(initAniY);
}
if(!valsY[pointIdx].isHole) {
pathArr = this.getPathArrByFitType(pathArr, fitType, pointIdx, valuesY.length, cBounds, valuesX, valuesY, X, Y, isXTime, isYTime, valX, valY, kx, ky, minX, minY, valsY, display, stacked);
} else {
return pathArr;
}
if(showChartLabels) {
defaultChartLabel = this.renderChartLabel(canvas, isYTime, valY, chartLabelFormatString, X, Y, culture, wijCSS);
chartLabelEles.push(defaultChartLabel);
defaultChartLabels.push(defaultChartLabel);
aniLabelsAttr.push($.extend(true, {
}, defaultChartLabel.attr()));
}
if(markerVisible) {
marker = this.renderMarker(canvas, symbols, paintSymbol, lineSeries.markers, pointIdx, X, Y, lineMarkerStyle, wijCSS);
dot = marker.dot;
if(needAnimated) {
dot.straight = initAniY;
}
}
markerData = {
};
markerData.valX = valuesX[pointIdx];
markerData.valY = dataY;
markerData.index = pointIdx;
markerData.type = "marker";
markerData.lineSeries = lineSeries;
markerData.x = X;
markerData.y = Y;
markerData.markerStyle = lineMarkerStyle;
markerData.markerHoverStyle = lineMarkerHoverStyle;
markerData.visible = true;
if(markerVisible) {
markerData.marker = dot;
markerData.isSymbol = marker.isSymbol;
$(dot.node).data("wijchartDataObj", markerData);
markers.push(dot);
aniMarkersAttr.push($.extend(true, {
}, dot.attr()));
animationSet.push(dot);
}
// cache the bar position to show indicator line.
widget.dataPoints = widget.dataPoints || {
};
widget.pointXs = widget.pointXs || [];
pointX = $.round(X, 2);
if(!widget.dataPoints[pointX.toString()]) {
widget.dataPoints[pointX.toString()] = [];
widget.pointXs.push(pointX);
}
widget.dataPoints[pointX.toString()].push(markerData);
virtualMarkers.push(markerData);
return pathArr;
};
LineChartRender.prototype.processYValues = function (values, display, hole, stacked, lastValues) {
var vals = [], idx = 0, firstYIdx = 0;
$.each(values, function (i, value) {
if(!idx) {
firstYIdx = i;
}
var val = {
isHole: false,
isValue: true,
idx: idx,
firstYIdx: firstYIdx,
x: 0,
y: 0
};
idx++;
if(chart.ChartUtil.isHolefunction(value, hole)) {
if(stacked) {
values[i] = 0;
} else {
val.isHole = true;
if(display === "excludeHole") {
idx--;
val.idx = 0;
} else {
idx = 0;
val.idx = 0;
}
if(!chart.ChartUtil.isHolefunction(hole, undefined) && value === hole) {
val.isValue = true;
} else {
val.isValue = false;
}
}
}
vals.push(val);
if(stacked && i < lastValues.length) {
values[i] += lastValues[i];
}
});
lastValues.length = 0;
$.merge(lastValues, values);
return vals;
};
LineChartRender.prototype.renderMarker = function (canvas, symbols, paintSymbol, markers, markerIdx, X, Y, lineMarkerStyle, wijCSS) {
var symbs, dot = null, isSymbol = false, markerType, markerWidth;
if(paintSymbol) {
symbs = markers.symbol;
$.each(symbs, function (idx, symbol) {
if(symbol.index === markerIdx) {
dot = canvas.image(symbol.url, X - symbol.width / 2, Y - symbol.height / 2, symbol.width, symbol.height);
symbols.push(dot);
isSymbol = true;
return false;
}
});
}
if(dot === null) {
markerType = markers.type;
markerWidth = lineMarkerStyle.width;
dot = canvas.paintMarker(markerType, X, Y, markerWidth);
if(markers.visible) {
dot.attr(lineMarkerStyle);
}
}
$.wijraphael.addClass($(dot.node), Raphael.format("{0} {1} {2}", wijCSS.canvasObject, wijCSS.lineElement, wijCSS.canvasMarker));
return {
dot: dot,
isSymbol: isSymbol
};
};
LineChartRender.prototype.renderChartLabel = function (canvas, isYTime, valY, chartLabelFormatString, X, Y, culture, wijCSS) {
var labelText, defaultChartLabel, dclBox, widget = this.options.widget;
//Add comments by RyanWu@20110707.
//For supporting date time value on y axi.
//labelText = valY;
labelText = isYTime ? $.fromOADate(valY) : valY;
//end by RyanWu@20110707.
if(chartLabelFormatString && chartLabelFormatString.length) {
labelText = Globalize.format(labelText, chartLabelFormatString, culture);
}
defaultChartLabel = widget._text.call(widget, X, Y, labelText);
$.wijraphael.addClass($(defaultChartLabel.node), wijCSS.lineLabel);
dclBox = defaultChartLabel.wijGetBBox();
defaultChartLabel.transform(Raphael.format("...T{0},{1}", 0, -dclBox.height));
return defaultChartLabel;
};
LineChartRender.prototype.getAnchors = function (p1x, p1y, p2x, p2y, p3x, p3y) {
var l1 = (p2x - p1x) / 2, l2 = (p3x - p2x) / 2, a = Math.atan((p2x - p1x) / Math.abs(p2y - p1y)), b = Math.atan((p3x - p2x) / Math.abs(p2y - p3y)), alpha = 0, dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0;
a = p1y < p2y ? Math.PI - a : a;
b = p3y < p2y ? Math.PI - b : b;
alpha = Math.PI / 2 - ((a + b) % (Math.PI * 2)) / 2;
dx1 = l1 * Math.sin(alpha + a);
dy1 = l1 * Math.cos(alpha + a);
dx2 = l2 * Math.sin(alpha + b);
dy2 = l2 * Math.cos(alpha + b);
return {
x1: p2x - dx1,
y1: p2y + dy1,
x2: p2x + dx2,
y2: p2y + dy2
};
};
LineChartRender.prototype.getPathArrByFitType = function (pathArr, fitType, idx, len, cBounds, valuesX, valuesY, X, Y, isXTime, isYTime, valX, valY, kx, ky, minX, minY, valsY, display, stacked) {
var valY2 = null, Y0 = 0, Y2 = 0, X0 = 0, X2 = 0, valX2 = null, a = null, valueY = valsY[idx], isNextPointHole = false, index = valueY.idx, i, prevIdx = idx - 1, nextIdx = idx + 1;
if(display === "excludeHole" && !stacked) {
if(idx > 0 && idx < len - 1) {
nextIdx = -1;
prevIdx = -1;
for(i = idx + 1; i < len; i++) {
isNextPointHole = true;
if(valsY[i].isHole) {
continue;
}
nextIdx = i;
isNextPointHole = false;
break;
}
for(i = idx - 1; i >= 0; i--) {
if(valsY[i].isHole) {
continue;
}
prevIdx = i;
break;
}
if(prevIdx > -1) {
X0 = valsY[prevIdx].x;
Y0 = valsY[prevIdx].y;
}
}
} else {
if(idx < len - 1) {
isNextPointHole = valsY[nextIdx].isHole;
}
if(idx > 0 && idx < len - 1) {
X0 = valsY[prevIdx].x;
Y0 = valsY[prevIdx].y;
}
}
if(stacked) {
fitType = "line";
}
if(fitType === "line") {
pathArr = pathArr.concat([
index ? "L" : "M",
X,
Y
]);
} else if(fitType === "spline") {
if(!index) {
if(idx === len - 1) {
pathArr = pathArr.concat([
"M",
X,
Y
]);
} else if(isNextPointHole) {
pathArr = pathArr.concat([
"M",
X,
Y
]);
} else {
pathArr = pathArr.concat([
"M",
X,
Y,
"C",
X,
Y
]);
}
} else if(index && idx < len - 1 && !isNextPointHole) {
valY2 = valuesY[nextIdx];
if(isYTime) {
valY2 = $.toOADate(valY2);
}
Y2 = cBounds.endY - (valY2 - minY) * ky;
if(isNaN(valX) || typeof valX === "string") {
X2 = cBounds.startX + (nextIdx - minX) * kx;
} else {
valX2 = valuesX[nextIdx];
if(isXTime) {
valX2 = $.toOADate(valX2);
}
X2 = cBounds.startX + (valX2 - minX) * kx;
}
a = this.getAnchors(X0, Y0, X, Y, X2, Y2);
pathArr = pathArr.concat([
a.x1,
a.y1,
X,
Y,
a.x2,
a.y2
]);
} else {
pathArr = pathArr.concat([
X,
Y,
X,
Y
]);
}
} else if(fitType === "bezier") {
if(!index) {
pathArr = pathArr.concat([
"M",
X,
Y
]);
} else if((idx < len - 1 && valsY[idx + 1].isHole && index % 2 === 1) || (idx === len - 1 && index % 2 === 1)) {
pathArr = pathArr.concat([
"Q",
X,
Y,
X,
Y
]);
} else {
if(index % 2 === 0) {
pathArr = pathArr.concat([
X,
Y
]);
} else {
pathArr = pathArr.concat([
"Q",
X,
Y
]);
}
}
}
return pathArr;
};
LineChartRender.prototype.bindLiveEvents = function (element, canvas, cBounds, widgetName, mouseDown, mouseUp, mouseOver, mouseOut, mouseMove, click, disabled, hint, linesStyle, tooltip, wijCSS) {
var touchEventPre = "", proxyObj = {
element: element,
mousedown: function (e) {
if(disabled) {
return;
}
var tar = $(e.target), data, lineSeries = null;
if(tar.data("owner")) {
tar = tar.data("owner");
}
data = tar.data("wijchartDataObj");
if(tar.hasClass(wijCSS.canvasMarker)) {
lineSeries = data.lineSeries;
if(!lineSeries.markers.visible) {
mouseDown.call(element, e, lineSeries);
} else {
mouseDown.call(element, e, data);
}
} else {
mouseDown.call(element, e, data);
}
},
mouseup: function (e) {
if(disabled) {
return;
}
var tar = $(e.target), data, lineSeries = null;
if(tar.data("owner")) {
tar = tar.data("owner");
}
data = tar.data("wijchartDataObj");
if(tar.hasClass(wijCSS.canvasMarker)) {
lineSeries = data.lineSeries;
if(!lineSeries.markers.visible) {
mouseUp.call(element, e, lineSeries);
} else {
mouseUp.call(element, e, data);
}
} else {
mouseUp.call(element, e, data);
}
},
mouseover: function (e) {
if(disabled) {
return;
}
var tar = $(e.target), data, lineSeries = null;
if(tar.data("owner")) {
tar = tar.data("owner");
}
data = tar.data("wijchartDataObj");
if(tar.hasClass(wijCSS.canvasMarker)) {
lineSeries = data.lineSeries;
if(!lineSeries.markers.visible) {
mouseOver.call(element, e, lineSeries);
} else {
mouseOver.call(element, e, data);
}
} else {
mouseOver.call(element, e, data);
}
},
mouseout: function (e) {
if(disabled) {
return;
}
var tar = $(e.target), data, lineSeries = null;
if(tar.data("owner")) {
tar = tar.data("owner");
}
data = tar.data("wijchartDataObj");
if(tar.hasClass(wijCSS.canvasMarker)) {
lineSeries = data.lineSeries;
if(!lineSeries.markers.visible) {
mouseOut.call(element, e, lineSeries);
} else {
mouseOut.call(element, e, data);
}
} else {
mouseOut.call(element, e, data);
}
},
mousemove: function (e) {
if(disabled) {
return;
}
var tar = $(e.target), data, lineSeries = null;
if(tar.data("owner")) {
tar = tar.data("owner");
}
data = tar.data("wijchartDataObj");
if(tar.hasClass(wijCSS.canvasMarker)) {
lineSeries = data.lineSeries;
if(!lineSeries.markers.visible) {
mouseMove.call(element, e, lineSeries);
} else {
mouseMove.call(element, e, data);
}
} else {
mouseMove.call(element, e, data);
}
},
click: function (e) {
if(disabled) {
return;
}
var tar = $(e.target), data, lineSeries = null;
if(tar.data("owner")) {
tar = tar.data("owner");
}
data = tar.data("wijchartDataObj");
if(tar.hasClass(wijCSS.canvasMarker)) {
lineSeries = data.lineSeries;
if(!lineSeries.markers.visible) {
click.call(element, e, lineSeries);
} else {
click.call(element, e, data);
}
} else {
click.call(element, e, data);
}
}
};
if($.support.isTouchEnabled && $.support.isTouchEnabled()) {
touchEventPre = "wij";
}
element.on(touchEventPre + "mousedown." + widgetName, "." + wijCSS.lineElement, $.proxy(proxyObj.mousedown, proxyObj)).on(touchEventPre + "mouseup." + widgetName, "." + wijCSS.lineElement, $.proxy(proxyObj.mouseup, proxyObj)).on(touchEventPre + "mouseover." + widgetName, "." + wijCSS.lineElement, $.proxy(proxyObj.mouseover, proxyObj)).on(touchEventPre + "mouseout." + widgetName, "." + wijCSS.lineElement, $.proxy(proxyObj.mouseout, proxyObj)).on(touchEventPre + "mousemove." + widgetName, "." + wijCSS.lineElement, $.proxy(proxyObj.mousemove, proxyObj)).on(touchEventPre + "click." + widgetName, "." + wijCSS.lineElement, $.proxy(proxyObj.click, proxyObj));
};
LineChartRender.prototype.unbindLiveEvents = function (element, widgetName, wijCSS) {
element.off("." + widgetName, "." + wijCSS.lineElement);
};
return LineChartRender;
})();
chart.LineChartRender = LineChartRender;
})(wijmo.chart || (wijmo.chart = {}));
var chart = wijmo.chart;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../wijchart/jquery.wijmo.wijchartcore.ts"/>
/*globals Raphael,jQuery, window, Globalize*/
/*
* Depends:
* jquery.js
* raphael.js
* globalize.js
* jquery.ui.widget.js
* jquery.wijmo.raphael.js
* jquery.wijmo.wijchartcore.js
*
*/
(function (chart) {
/**
* @widget
*/
var wijpiechart = (function (_super) {
__extends(wijpiechart, _super);
function wijpiechart() {
_super.apply(this, arguments);
}
wijpiechart.prototype._create = function () {
this._handleChartStyles();
_super.prototype._create.call(this);
this.chartElement.addClass(this.options.wijCSS.pieChart);
};
wijpiechart.prototype.destroy = /** Removes the functionality completely.
* This will return the element back to its pre-init state.
*/
function () {
var wijCSS = this.options.wijCSS, element = this.chartElement, fields = element.data("fields"), aniSectors = fields && fields.sectors, aniLabels = fields && fields.labels;
element.removeClass(wijCSS.pieChart);
_super.prototype.destroy.call(this);
if(aniSectors && aniSectors.length) {
$.each(aniSectors, function (idx, sector) {
sector = null;
});
}
if(aniLabels && aniLabels.length) {
$.each(aniLabels, function (idx, label) {
label = null;
});
}
element.data("fields", null);
};
wijpiechart.prototype._isPieChart = function () {
return true;
};
wijpiechart.prototype.getSector = /** Returns the sector of the pie chart with the given index.
* @param {number} index The index of the sector.
* @returns {Raphael Element} Reference to raphael element object.
*/
function (index) {
var fields = this.chartElement.data("fields");
if(fields && fields.chartElements) {
return fields.chartElements.sectors[index];
}
return null;
};
wijpiechart.prototype._bindData = //add binding for pie chart
function () {
var o = this.options, ds = o.dataSource, data = o.data, seriesList = [], dataLabel, dataValue, dataOffset;
if(ds && data) {
dataLabel = data.label;
dataValue = data.value;
dataOffset = data.offset;
if(dataLabel && dataLabel.bind) {
dataLabel = this._getBindData(ds, dataLabel.bind);
}
if(dataValue && dataValue.bind) {
dataValue = this._getBindData(ds, dataValue.bind);
}
if(dataOffset && dataOffset.bind) {
dataOffset = this._getBindData(ds, dataOffset.bind);
}
if(dataLabel && $.isArray(dataLabel) && dataLabel.length && dataValue && $.isArray(dataValue) && dataValue.length) {
$.each(dataValue, function (idx, val) {
var label, offset = 0;
if(idx >= 0 && idx < dataLabel.length) {
label = dataLabel[idx];
}
if(dataOffset && $.isArray(dataValue) && dataOffset.length && idx >= 0 && idx < dataOffset.length) {
offset = typeof dataOffset[idx] === 'undefined' ? 0 : dataOffset[idx];
}
seriesList.push({
data: val,
label: label,
offset: offset,
legendEntry: true
});
});
o.seriesList = seriesList;
}
}
};
wijpiechart.prototype._hanldSharedXData = //Override chartcore's _hanldSharedXData, there's no x/y axis in piechart.
function () {
};
wijpiechart.prototype._getSeriesFromTR = function (theaders, sList, seriesList) {
var label = null, th = null, tds = null, data = null, series = null;
if(sList.length) {
sList.each(function () {
th = $("th", $(this));
label = $.trim(th.text());
tds = $("td", $(this));
if(tds.length) {
data = parseFloat($.trim($(tds[0]).text()));
}
series = {
label: label,
legendEntry: true,
data: data
};
seriesList.push(series);
});
}
};
wijpiechart.prototype._showSerieEles = function (seriesEle) {
var showLabels = this.options.showChartLabels;
if(seriesEle.sector) {
seriesEle.sector.show();
if(seriesEle.sector.shadow) {
seriesEle.sector.shadow.show();
}
if(seriesEle.sector.tracker) {
seriesEle.sector.tracker.show();
}
}
if(seriesEle.label && showLabels) {
seriesEle.label.show();
if(seriesEle.label.connector) {
seriesEle.label.connector.show();
}
$(seriesEle.label.node).data("legendHide", false);
}
};
wijpiechart.prototype._hideSerieEles = function (seriesEle) {
if(seriesEle.sector) {
seriesEle.sector.hide();
if(seriesEle.sector.shadow) {
seriesEle.sector.shadow.hide();
}
if(seriesEle.sector.tracker) {
seriesEle.sector.tracker.hide();
}
}
if(seriesEle.label) {
seriesEle.label.hide();
if(seriesEle.label.connector) {
seriesEle.label.connector.hide();
}
$(seriesEle.label.node).data("legendHide", true);
}
};
wijpiechart.prototype._hasAxes = function () {
return false;
};
wijpiechart.prototype._mouseMoveInsidePlotArea = function (e, mousePos) {
_super.prototype._mouseMoveInsidePlotArea.call(this, e, mousePos);
if(this.isTapAndHold) {
var previousAngle = this.previousAngle, rotation = 0, rotationStr = "", element = this.chartElement, dataObj = this.tapTarget ? this.tapTarget.data("wijchartDataObj") : {
}, pieId = dataObj.pieID || "", sectors = element.data("fields").chartElements["sectors" + pieId], cb = this.canvasBounds, pieCX = (cb.startX + cb.endX) / 2, pieCY = (cb.startY + cb.endY) / 2, angle = Raphael.angle(mousePos.left, mousePos.top, pieCX, pieCY);
if(previousAngle) {
rotation = Math.round(angle - previousAngle);
if(Math.abs(angle - previousAngle) > 180) {
if(angle > previousAngle) {
rotation = rotation - 360;
} else {
rotation = rotation + 360;
}
}
if(rotation) {
rotationStr = Raphael.format("...r{0},{1},{2}", rotation, pieCX, pieCY);
$.each(sectors, function (idx, sector) {
sector.transform(rotationStr);
});
if(this.tooltip) {
this._setTouchTooltip(null);
}
}
}
this.previousAngle = angle;
}
};
wijpiechart.prototype._mouseMoveOutsidePlotArea = function (e, mousePos) {
_super.prototype._mouseMoveOutsidePlotArea.call(this, e, mousePos);
if(this.isTapAndHold) {
this._rotateToSectorCenter(null);
}
};
wijpiechart.prototype._rotateToSectorCenter = function (specifiedSector) {
var _this = this;
var animation = this.options.animation, element = this.chartElement, dataObj = this.tapTarget ? this.tapTarget.data("wijchartDataObj") : {
}, pieId = dataObj.pieID || "", sectors = element.data("fields").chartElements["sectors" + pieId], labels = element.data("fields").chartElements["labels" + pieId], cb = this.canvasBounds, pieCX = (cb.startX + cb.endX) / 2, pieCY = (cb.startY + cb.endY) / 2, animate, touchSector, angle, self = this;
this._hideSectorElements(sectors, labels);
if(this.tooltip) {
touchSector = this._getTouchttSector(specifiedSector);
}
//add targetCenterAngle >=0.01 to prevent the precision issue.
if(this.touchttSector && this.touchttSector === touchSector && Math.abs(this.targetCenterAngle) >= 0.01) {
if(this.targetCenterAngle > 180) {
angle = this.targetCenterAngle - 360;
} else if(this.targetCenterAngle < -180) {
angle = this.targetCenterAngle + 360;
} else {
angle = this.targetCenterAngle;
}
animate = Raphael.animation({
transform: Raphael.format("...r{0},{1},{2}", angle, pieCX, pieCY)
}, animation.duration, animation.easing, function () {
self._rotateCallback(this, labels);
});
$.each(sectors, function (idx, sector) {
sector.animate(animate);
});
} else {
$.each(sectors, function (idx, sector) {
_this._rotateCallback(sector, labels);
});
}
this.previousAngle = null;
this.isTapAndHold = false;
this.tapTarget = null;
};
wijpiechart.prototype._rotateCallback = function (sector, labels) {
var cb = this.canvasBounds, pieCX = (cb.startX + cb.endX) / 2, pieCY = (cb.startY + cb.endY) / 2, idx = sector.index, rotation = 0, transforms = sector.attr("transform"), label;
$.each(transforms, function (idx, transform) {
if(transform[0] !== "r") {
return true;
}
if(transform.length >= 4) {
rotation += transform[1];
}
});
if(pieCX > 0) {
rotation = rotation % 360;
sector.attr("transform", Raphael.format("r{0},{1},{2}", rotation, pieCX, pieCY));
}
if(sector.tracker) {
sector.tracker.attr("transform", Raphael.format("r{0},{1},{2}", rotation, pieCX, pieCY));
sector.tracker.show();
}
if(sector.shadow) {
sector.shadow.attr("transform", Raphael.format("r{0},{1},{2}", rotation, pieCX, pieCY));
sector.shadow.show();
}
if(labels && labels.length && labels.length > idx) {
label = labels[idx];
label.attr("transform", Raphael.format("r{0},{1},{2}r{3}", rotation, pieCX, pieCY, 0 - rotation));
if($(label.node).data("legendHide")) {
return;
}
label.show();
}
};
wijpiechart.prototype._getTouchttSector = function (specifiedSector) {
var _this = this;
var element = this.chartElement, dataObj = this.tapTarget ? this.tapTarget.data("wijchartDataObj") : {
}, pieId = dataObj.pieID || "", sectors = element.data("fields").chartElements["sectors" + pieId], ttOpts = this.tooltip.getOptions(), ttCompass = ttOpts.compass, targetAngle = 90, targetSector;
switch(ttCompass) {
case "east":
targetAngle = 0;
break;
case "south":
targetAngle = 270;
break;
case "west":
targetAngle = 180;
break;
case "north":
default:
targetAngle = 90;
}
$.each(sectors, function (idx, sector) {
var transforms = sector.attr("transform"), rotation = 0, angle = sector.angles;
$.each(transforms, function (idx, transform) {
if(transform[0] !== "r") {
return true;
}
if(transform.length >= 4) {
rotation += transform[1];
}
});
rotation = rotation % 360;
if(rotation < 0) {
rotation = 360 + rotation;
}
rotation = (targetAngle + rotation) % 360;
if(specifiedSector) {
if(sector === specifiedSector) {
_this.targetCenterAngle = (angle.start + angle.end) / 2 - rotation;
targetSector = specifiedSector;
return false;
}
} else {
if(angle.start <= rotation && angle.end >= rotation) {
_this.targetCenterAngle = (angle.start + angle.end) / 2 - rotation;
targetSector = sector;
return false;
}
}
});
return targetSector;
};
wijpiechart.prototype._setTouchTooltip = function (specifiedSector) {
var ttOpts = this.tooltip.getOptions(), ttCompass = ttOpts.compass, sector = this._getTouchttSector(specifiedSector), hint = this.options.hint, title = hint.title, content = hint.content, isTitleFunc = $.isFunction(title), isContentFunc = $.isFunction(content), dataObj, obj;
if(!sector || (this.touchttSector && this.touchttSector === sector)) {
return;
}
dataObj = $(sector.node).data("wijchartDataObj");
obj = {
data: dataObj,
value: dataObj.value,
label: dataObj.label,
total: dataObj.total,
y: dataObj.value
};
if(isTitleFunc || isContentFunc) {
if(isTitleFunc) {
ttOpts.title = function () {
obj.fmt = title;
var fmt = $.proxy(obj.fmt, obj), tit = fmt();
return tit;
};
}
if(isContentFunc) {
ttOpts.content = function () {
obj.fmt = content;
var fmt = $.proxy(obj.fmt, obj), con = fmt();
return con;
};
}
}
this._showTouchTooltip(ttCompass);
this.touchttSector = sector;
};
wijpiechart.prototype._showTouchTooltip = function (compass) {
var element = this.chartElement, cb = this.canvasBounds, point = {
x: 0,
y: 0
};
switch(compass) {
case "east":
point = {
x: element.width(),
y: (cb.startY + cb.endY) / 2
};
break;
case "south":
point = {
x: (cb.startX + cb.endX) / 2,
y: element.height()
};
break;
case "west":
point = {
x: 0,
y: (cb.startY + cb.endY) / 2
};
break;
case "north":
default:
point = {
x: (cb.startX + cb.endX) / 2,
y: 0
};
}
this.tooltip.showAt(point);
};
wijpiechart.prototype._mouseDown = function (e, args) {
var target = $(e.target), element = this.chartElement, pieId, sectors, labels;
_super.prototype._mouseDown.call(this, e, args);
if($.support.isTouchEnabled && $.support.isTouchEnabled()) {
this.isTapAndHold = true;
if(target.data("owner")) {
target = target.data("owner");
}
this.tapTarget = target;
pieId = args.pieID || "";
sectors = element.data("fields").chartElements["sectors" + pieId];
labels = element.data("fields").chartElements["labels" + pieId];
this._hideSectorElements(sectors, labels);
}
};
wijpiechart.prototype._hideSectorElements = function (sectors, labels) {
$.each(sectors, function (idx, sector) {
sector.stop();
if(sector.tracker) {
sector.tracker.hide();
}
if(sector.shadow) {
sector.shadow.hide();
}
if(labels && labels.length) {
var label = labels[idx];
label.hide();
}
});
};
wijpiechart.prototype._mouseUp = function (e, args) {
_super.prototype._mouseUp.call(this, e, args);
if($.support.isTouchEnabled && $.support.isTouchEnabled() && this.isTapAndHold) {
this._rotateToSectorCenter(null);
}
};
wijpiechart.prototype._mouseOver = function (e, args) {
_super.prototype._mouseOver.call(this, e, args);
};
wijpiechart.prototype._mouseOut = function (e, args) {
_super.prototype._mouseOut.call(this, e, args);
};
wijpiechart.prototype._mouseMove = function (e, args) {
_super.prototype._mouseMove.call(this, e, args);
};
wijpiechart.prototype._click = function (e, args) {
var element = this.chartElement, pieId, sectors, sector;
_super.prototype._click.call(this, e, args);
if($.support.isTouchEnabled && $.support.isTouchEnabled() && this.tooltip) {
pieId = args.pieID || "";
sectors = element.data("fields").chartElements["sectors" + pieId];
if(sectors.length && sectors.length > args.index) {
sector = sectors[args.index];
this._setTouchTooltip(sector);
this._rotateToSectorCenter(sector);
}
}
};
wijpiechart.prototype._paintTooltip = function () {
var wijCSS = this.options.wijCSS, element = this.chartElement, fields = element.data("fields");
_super.prototype._paintTooltip.call(this);
if(this.tooltip && fields) {
if($.support.isTouchEnabled && $.support.isTouchEnabled()) {
this.tooltip.setOptions({
closeBehavior: "none",
mouseTrailing: false,
animated: null,
showAnimated: null,
windowCollisionDetection: "fit"
});
this._setTouchTooltip(null);
this._rotateToSectorCenter(null);
} else {
if(fields.trackers && fields.trackers.length) {
this.tooltip.setSelector($("." + wijCSS.canvasObject, element[0]));
this.tooltip.setOptions({
relatedElement: fields.trackers[0]
});
}
}
}
};
wijpiechart.prototype._paintPlotArea = function () {
var o = this.options, canvasBounds = this.canvasBounds, width = canvasBounds.endX - canvasBounds.startX, height = canvasBounds.endY - canvasBounds.startY, r = o.radius;
if(!r) {
r = Math.min(width, height) / 2;
} else {
if(width < 2 * r) {
r = width / 2;
}
if(height < 2 * r) {
r = height / 2;
}
}
//remove to fix a resize issue.
//o.radius = r;
canvasBounds.startX += width / 2 - r;
canvasBounds.endX = canvasBounds.startX + 2 * r;
canvasBounds.startY += height / 2 - r;
canvasBounds.endY = canvasBounds.startY + 2 * r;
if(this.chartElement.data("fields")) {
this.chartElement.data("fields").seriesEles = null;
}
this.piechartRender = new PieChartRender(this.chartElement, {
canvas: this.canvas,
tooltip: this.tooltip,
bounds: canvasBounds,
wijCSS: o.wijCSS,
radius: r,
startAngle: o.startAngle,
widgetName: this.widgetName,
innerRadius: o.innerRadius,
seriesList: o.seriesList,
seriesStyles: o.seriesStyles,
seriesHoverStyles: o.seriesHoverStyles,
seriesTransition: o.seriesTransition,
showChartLabels: o.showChartLabels,
disabled: o.disabled,
textStyle: o.textStyle,
chartLabelStyle: o.chartLabelStyle,
chartLabelFormatString: o.chartLabelFormatString,
chartLabelFormatter: o.chartLabelFormatter,
labels: o.labels,
shadow: o.shadow,
animation: o.animation,
culture: this._getCulture(),
mouseDown: $.proxy(this._mouseDown, this),
mouseUp: $.proxy(this._mouseUp, this),
mouseOver: $.proxy(this._mouseOver, this),
mouseOut: $.proxy(this._mouseOut, this),
mouseMove: $.proxy(this._mouseMove, this),
click: $.proxy(this._click, this),
widget: this
});
this.piechartRender.render();
};
wijpiechart.prototype._getTooltipText = function (fmt, target) {
var tar = $(target.node), dataObj, obj;
if(tar.data("owner")) {
tar = tar.data("owner");
}
dataObj = tar.data("wijchartDataObj");
obj = {
data: dataObj,
value: dataObj.value,
label: dataObj.label,
total: dataObj.total,
target: target,
y: dataObj.value,
fmt: fmt
};
return $.proxy(fmt, obj)();
};
return wijpiechart;
})(chart.wijchartcore);
chart.wijpiechart = wijpiechart;
/** end of private methods */
var wijpiechart_options = (function () {
function wijpiechart_options() {
/**
* Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijpiechart')";
/**
* All CSS classes used in widgets.
* @ignore
*/
this.wijCSS = {
pieChart: "wijmo-wijpiechart",
pieLabel: "wijpiechart-label",
pieElement: "wijpiechart",
pieTracker: "pietracker"
};
/** Sets the number of degrees of angle from which to begin painting wedges in the pie.
* To see an example of this property in action, check out the following link,
* http://jsbin.com/ewofiv/1
*/
this.startAngle = 0;
/** A value that indicates the radius used for a pie chart.
* @type {number}
* @remarks If the value is null, then the radius will be calculated
* by the width/height value of the pie chart.
*/
this.radius = null;
/** A value that indicates the inner radius used for doughnut charts.*/
this.innerRadius = 0;
/** A value that indicates a function which is used to get a value
* for the chart label shown.
* @type {function}
*/
this.chartLabelFormatter = null;
/** A value that indicates the chart label elements of chart.*/
this.labels = {
style: /** A value that indicates the style of the chart labels.*/
{
},
formatString: /** A value that indicates the format string of the chart labels.*/
"",
formatter: /** A value that indicates the formatter of the chart labels.
* @type {function}
*/
null,
connectorStyle: /** A value that indicates the style of the chart labels' connector.*/
{
},
position: /** A value that indicates the style of the chart labels.
* @remarks Options are 'inside', 'outside'.
*/
"inside",
offset: /** A value that indicates the offset of the chart labels.*/
10
};
/** The animation option defines the animation effect and controls other aspects of the widget's animation,
* such as duration and easing.
*/
this.animation = {
enabled: /** A value that determines whether to show animation.*/
true,
duration: /** A value that indicates the duration for the animation. */
400,
easing: /** Sets the type of animation easing effect that users experience when the wijpiechart series
* is reloaded after they have changed the data for the seriesList option.
* @remarks Values available for the animation easing effect include the following:
* easeInCubic ¨C Cubic easing in. Begins at zero velocity and then accelerates.
* easeOutCubic ¨C Cubic easing in and out. Begins at full velocity and then decelerates to zero.
* easeInOutCubic ¨C Begins at zero velocity, accelerates until halfway, and then decelerates to zero velocity again.
* easeInBack ¨C Begins slowly and then accelerates.
* easeOutBack ¨C Begins quickly and then decelerates.
* easeOutElastic ¨C Begins at full velocity and then decelerates to zero.
* easeOutBounce ¨C Begins quickly and then decelerates. The number of bounces is related to the duration, longer durations produce more bounces.
*/
"easeInCubic",
offset: /** A value that indicates the offset for an explode animation.*/
10
};
/** A value that indicates whether to show animation
* and the duration for the animation when reload data.
*/
this.seriesTransition = {
enabled: /** A value that determines whether to show animation when reload.*/
true,
duration: /** A value that indicates the duration for the series transition.*/
1000,
easing: /** A value that indicates the easing for the series transition. */
"bounce"
};
/** An array collection that contains the data to be charted.
* @remarks The following is the sample data for seriesList option,
* [{
* label: "Q1",
* legendEntry: true,
* data: 12,
* offset: 0
* }, {
* label: "Q2",
* legendEntry: true,
* data: 21,
* offset: 0
* }, {
* label: "Q3",
* legendEntry: true,
* data: 9,
* offset: 0
* }, {
* label: "Q4",
* legendEntry: true,
* data: 29,
* offset: 10
* }]
*/
this.seriesList = [];
/** Fires when the user clicks a mouse button.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijPieChartEventArgs} args The data with this event.
*/
this.mouseDown = null;
/** Fires when the user releases a mouse button
* while the pointer is over the chart element.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijPieChartEventArgs} args The data with this event.
*/
this.mouseUp = null;
/** Fires when the user first places the pointer over the chart element.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijPieChartEventArgs} args The data with this event.
*/
this.mouseOver = null;
/** Fires when the user moves the pointer off of the chart element.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijPieChartEventArgs} args The data with this event.
*/
this.mouseOut = null;
/** Fires when the user moves the mouse pointer
* while it is over a chart element.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijPieChartEventArgs} args The data with this event.
*/
this.mouseMove = null;
/** Fires when the user clicks the chart element.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijPieChartEventArgs} args The data with this event.
*/
this.click = null;
}
return wijpiechart_options;
})();
;
wijpiechart.prototype.options = $.extend(true, {
}, chart.wijchartcore.prototype.options, new wijpiechart_options());
$.wijmo.registerWidget("wijpiechart", wijpiechart.prototype);
;
//render pie chart.
/** @ignore*/
var PieChartRender = (function () {
function PieChartRender(element, options) {
this.options = options;
this.element = element;
}
PieChartRender.prototype.render = function () {
var ele = this.element, o = this.options, paintShadow = function (element, offset, stroke) {
if(o.shadow) {
chart.ChartUtil.paintShadow(element, offset, stroke);
}
}, getDiffAttrs = chart.ChartUtil.getDiffAttrs, canvas = o.canvas, getPositionByAngle = $.wijraphael.getPositionByAngle, seriesList = o.seriesList, seriesStyles = o.seriesStyles, seriesHoverStyles = o.seriesHoverStyles, stylesLength = seriesStyles.length, textStyle = o.textStyle, labelsOpts = o.labels || {
style: {
},
formatString: "",
formatter: null,
connectorStyle: {
},
position: "inside",
offset: 10
}, chartLabelStyle = $.extend(true, {
}, textStyle, o.chartLabelStyle, labelsOpts.style), chartLabelFormatString = labelsOpts.formatString || o.chartLabelFormatString, chartLabelFormatter = labelsOpts.formatter || o.chartLabelFormatter, culture = o.culture, bounds = o.bounds, startX = bounds.startX, startY = bounds.startY, radius = o.radius, showChartLabels = o.showChartLabels, animation = o.animation, seriesTransition = o.seriesTransition, innerRadius = o.innerRadius, fields = ele.data("fields") || {
}, chartElements = fields.chartElements || {
}, aniSectorAttrs = fields.aniSectorAttrs, aniLabelAttrs = fields.aniLabelAttrs, total = 0, angle = o.startAngle || 0, wijCSS = o.wijCSS, pieID, path, attr, sectorAttrs = [], labelAttrs = [], sectors = [], labels = [], tooltipTars = [], seriesEles = [], trackers = canvas.set(), widget = this.options.widget;
canvas.customAttributes.segment = function (x, y, a1, a2, outerR, innerR) {
var path = null, offset = 0.01;
if(a2 - a1 > 360 - offset) {
a2 -= offset;
} else if(a2 - a1 < offset) {
a2 += offset;
}
if(innerR) {
path = chart.ChartUtil.donut(x, y, outerR, innerR, a1, a2);
} else {
path = chart.ChartUtil.sector(x, y, outerR, a1, a2);
}
return {
"path": path
};
};
$.each(seriesList, function (idx, series) {
if(series && typeof (series.data) === "number") {
total += series.data;
}
});
$.each(seriesList, function (idx, series) {
var seriesStyle = $.extend({
opacity: 1,
stroke: "gray",
"stroke-width": 1
}, seriesStyles[idx % stylesLength]), anglePlus = 360 * series.data / total, cx = startX + radius, cy = startY + radius, center, sector, label, pos, textStyle, borderPos, tracker, chartLabel, formatter, labelPosition = labelsOpts.position, labelConnectorStyle = labelsOpts.connectorStyle, labelOffset = labelsOpts.offset, calculatedAngle, labelBounds, labelConnector, animate = false;
pieID = series.pieID;
series = $.extend(true, {
offset: 0
}, series);
if(series.offset) {
center = getPositionByAngle(cx, cy, series.offset, angle + anglePlus / 2);
cx = center.x;
cy = center.y;
}
path = [
cx,
cy,
angle,
angle + anglePlus,
radius,
innerRadius
];
if(aniSectorAttrs && seriesTransition.enabled) {
seriesStyle["segment"] = path;
if(idx < aniSectorAttrs.length) {
attr = aniSectorAttrs[idx];
} else {
attr = $.extend(true, {
}, seriesStyle);
attr.segment = [
cx,
cy,
0,
360,
radius,
innerRadius
];
}
sector = canvas.path().attr(attr);
seriesStyle = getDiffAttrs(attr, seriesStyle);
if(!sector.removed) {
sector.wijAnimate(seriesStyle, seriesTransition.duration, seriesTransition.easing, function () {
paintShadow(sector, 1, "#cccccc");
if(tracker && !tracker.removed && !sector.removed) {
tracker.attr({
"path": sector.attr("path")
});
}
delete seriesStyle["segment"];
});
}
} else {
sector = canvas.path().attr({
segment: path
});
paintShadow(sector, 1, "#ccccc");
sector.wijAttr(seriesStyle);
}
sector.angles = {
start: angle,
end: angle + anglePlus
};
sector.index = idx;
sector.getOffset = function (offset) {
var pos = getPositionByAngle(cx, cy, offset, (sector.angles.start + sector.angles.end) / 2);
return {
x: pos.x - cx,
y: pos.y - cy
};
};
sector.center = {
x: cx,
y: cy
};
sector.radius = radius;
if(innerRadius) {
sector.innerRadius = innerRadius;
}
tracker = sector.clone();
// in vml, if the tracker has a stroke, the boder is black.
if(Raphael.vml) {
tracker.attr({
opacity: 0.01,
fill: "white",
"stroke-width": 0,
"fill-opacity": 0.01
});
} else {
tracker.attr({
opacity: 0.01,
fill: "white",
"fill-opacity": 0.01
});
}
$.wijraphael.addClass($(tracker.node), Raphael.format("{0} {1} {2} wijchart-tracker" + idx, wijCSS.canvasObject, wijCSS.pieElement, wijCSS.pieTracker));
$(tracker.node).data("owner", $(sector.node));
sector.tracker = tracker;
trackers.push(tracker);
// add class "wijmo-wijpiechart-series-n" to fix bug 18590
$.wijraphael.addClass($(sector.node), Raphael.format("{0} {1} wijmo-wijpiechart-series-" + idx, wijCSS.canvasObject, wijCSS.pieElement));
//addClass($(sector.node), "wijchart-canvas-object wijpiechart");
//end comments
$(sector.node).data("wijchartDataObj", series);
if(showChartLabels) {
if(labelPosition === "outside") {
borderPos = getPositionByAngle(cx, cy, radius, angle + anglePlus / 2);
pos = getPositionByAngle(cx, cy, radius + labelOffset, angle + anglePlus / 2);
} else {
pos = getPositionByAngle(cx, cy, series.offset + radius * 2 / 3, angle + anglePlus / 2);
}
textStyle = $.extend(true, {
}, textStyle, chartLabelStyle);
if(series.textStyle) {
textStyle = $.extend(true, textStyle, series.textStyle);
}
chartLabel = series.label;
if(chartLabelFormatString && chartLabelFormatString.length > 0) {
chartLabel = Globalize.format(chartLabel, chartLabelFormatString, culture);
}
if(chartLabelFormatter && $.isFunction(chartLabelFormatter)) {
formatter = {
index: idx,
value: series.data,
y: series.data,
total: total,
chartLabel: chartLabel,
chartLabelFormatter: chartLabelFormatter
};
chartLabel = $.proxy(chartLabelFormatter, formatter)();
}
if(aniLabelAttrs && seriesTransition.enabled) {
if(idx < aniLabelAttrs.length) {
animate = true;
attr = aniLabelAttrs[idx];
attr.text = chartLabel;
label = widget._text.call(widget, 0, 0, "").attr(attr);
textStyle = getDiffAttrs(attr, textStyle);
textStyle.x = pos.x;
textStyle.y = pos.y;
label.wijAnimate(textStyle, seriesTransition.duration, seriesTransition.easing, function () {
if(labelConnector) {
labelConnector.show();
}
});
} else {
label = widget._text.call(widget, pos.x, pos.y, chartLabel).attr(textStyle);
}
} else {
label = widget._text.call(widget, pos.x, pos.y, chartLabel).attr(textStyle);
}
if(labelPosition === "outside") {
calculatedAngle = (angle + anglePlus / 2) % 360;
labelBounds = label.wijGetBBox();
if(calculatedAngle >= 90 && calculatedAngle <= 270) {
label.transform(Raphael.format("T{0},{1}", -labelBounds.width / 2, 0));
} else {
label.transform(Raphael.format("T{0},{1}", labelBounds.width / 2, 0));
}
//connector
labelConnector = canvas.path(Raphael.format("M{0} {1}L{2} {3}", borderPos.x, borderPos.y, pos.x, pos.y)).attr(labelConnectorStyle);
if(animate) {
labelConnector.hide();
}
label.connector = labelConnector;
}
$.wijraphael.addClass($(label.node), Raphael.format("{0} {1} {2}", wijCSS.canvasObject, wijCSS.pieElement, wijCSS.pieLabel));
$(label.node).data("wijchartDataObj", series);
tooltipTars.push(label);
labels.push(label);
labelAttrs[idx] = label.attr();
}
seriesEles.push({
label: labels[idx],
sector: sector
});
if(series.visible === false) {
sector.hide();
if(labels[idx]) {
labels[idx].hide();
}
if(labelConnector) {
labelConnector.hide();
}
if(sector.shadow) {
sector.shadow.hide();
}
tracker.hide();
}
sectorAttrs[idx] = sector.attr();
sectors.push(sector);
tooltipTars.push(sector);
series.style = seriesStyle;
series.hoverStyle = seriesHoverStyles[idx];
series.index = idx;
series.value = series.data;
series.y = series.data;
series.total = total;
series.type = "pie";
angle += anglePlus;
});
//ensuring labels are rendered on top of pie slices.
if(labels && labels.length) {
$.each(labels, function (idx, label) {
label.toFront();
});
}
//end comments.
chartElements.sectors = sectors;
if(pieID) {
chartElements["sectors" + pieID] = sectors;
chartElements["labels" + pieID] = labels;
}
chartElements.labels = labels;
if(!fields.chartElements) {
fields.chartElements = {
};
}
trackers.toFront();
$.extend(true, fields.chartElements, chartElements);
fields.aniSectorAttrs = sectorAttrs;
fields.aniLabelAttrs = labelAttrs;
fields.seriesEles = seriesEles;
fields.trackers = trackers;
ele.data("fields", fields);
this.unbindLiveEvents();
this.bindLiveEvents();
};
PieChartRender.prototype.bindLiveEvents = function () {
var o = this.options, ele = this.element, tooltip = o.tooltip, offset = {
x: 0,
y: 0
}, touchEventPre = "", isFunction = $.isFunction, disabled = o.disabled, animation = o.animation;
if($.support.isTouchEnabled && $.support.isTouchEnabled()) {
touchEventPre = "wij";
}
if(tooltip) {
tooltip.setTargets(this.tooltipTars);
}
ele.on(touchEventPre + "mousedown." + o.widgetName, "." + o.wijCSS.pieElement, function (e) {
if(disabled) {
return;
}
var mouseDown = o.mouseDown, target = $(e.target), dataObj;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
if(!dataObj) {
return;
}
if(isFunction(mouseDown)) {
mouseDown.call(ele, e, dataObj);
}
}).on(touchEventPre + "mouseup." + o.widgetName, "." + o.wijCSS.pieElement, function (e) {
if(disabled) {
return;
}
var mouseUp = o.mouseUp, target = $(e.target), dataObj;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
if(!dataObj) {
return;
}
if(isFunction(mouseUp)) {
mouseUp.call(ele, e, dataObj);
}
}).on(touchEventPre + "mouseover." + o.widgetName, "." + o.wijCSS.pieElement, function (e) {
if(disabled) {
return;
}
var mouseOver = o.mouseOver, target = $(e.target), animated = animation && animation.enabled, dataObj, id, index, sector, showAnimationTimer, hideAnimationTimer, explodeAnimationShowing;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
if(!dataObj) {
return;
}
id = dataObj.pieID || "";
index = dataObj.index;
sector = ele.data("fields").chartElements["sectors" + id][index];
showAnimationTimer = sector.showAnimationTimer;
hideAnimationTimer = sector.hideAnimationTimer;
explodeAnimationShowing = sector.explodeAnimationShowing;
if(isFunction(mouseOver)) {
mouseOver.call(ele, e, dataObj);
}
if($.support.isTouchEnabled && $.support.isTouchEnabled()) {
return;
}
if(sector.removed) {
return;
}
sector.wijAttr(dataObj.hoverStyle);
if(animated) {
if(hideAnimationTimer) {
window.clearTimeout(hideAnimationTimer);
hideAnimationTimer = null;
sector.hideAnimationTimer = hideAnimationTimer;
}
if(showAnimationTimer) {
window.clearTimeout(showAnimationTimer);
showAnimationTimer = null;
sector.showAnimationTimer = null;
}
if(explodeAnimationShowing) {
return;
}
showAnimationTimer = window.setTimeout(function () {
var duration = animation.duration, easing = animation.easing;
if(sector.removed) {
return;
}
offset = sector.getOffset(animation.offset || 10);
sector.offset = offset;
if(sector.shadow && !sector.shadow.removed) {
sector.shadow.hide();
}
sector.wijAnimate({
transform: Raphael.format("t{0},{1}", offset.x, offset.y)
}, duration, easing);
if(sector.tracker && !sector.tracker.removed) {
sector.tracker.wijAnimate({
transform: Raphael.format("t{0},{1}", offset.x, offset.y)
}, duration, easing);
}
explodeAnimationShowing = true;
sector.explodeAnimationShowing = explodeAnimationShowing;
}, 150);
sector.showAnimationTimer = showAnimationTimer;
}
}).on(touchEventPre + "mouseout." + o.widgetName, "." + o.wijCSS.pieElement, function (e) {
if(disabled) {
return;
}
var mouseOut = o.mouseOut, target = $(e.target), animated = animation && animation.enabled, dataObj, id, index, sector, showAnimationTimer, hideAnimationTimer, explodeAnimationShowing;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
if(!dataObj) {
return;
}
id = dataObj.pieID || "";
index = dataObj.index;
sector = ele.data("fields").chartElements["sectors" + id][index];
showAnimationTimer = sector.showAnimationTimer;
hideAnimationTimer = sector.hideAnimationTimer;
explodeAnimationShowing = sector.explodeAnimationShowing;
if(isFunction(mouseOut)) {
mouseOut.call(ele, e, dataObj);
}
if($.support.isTouchEnabled && $.support.isTouchEnabled()) {
return;
}
if(sector.removed) {
return;
}
if(dataObj.style.segment) {
delete dataObj.style.segment;
}
sector.wijAttr(dataObj.style);
if(animated) {
if(hideAnimationTimer) {
window.clearTimeout(hideAnimationTimer);
hideAnimationTimer = null;
sector.hideAnimationTimer = hideAnimationTimer;
}
if(showAnimationTimer) {
window.clearTimeout(showAnimationTimer);
showAnimationTimer = null;
sector.showAnimationTimer = showAnimationTimer;
}
if(!explodeAnimationShowing) {
return;
}
hideAnimationTimer = window.setTimeout(function () {
var duration = animation.duration, easing = animation.easing;
offset = sector.offset;
if(sector.shadow && !sector.shadow.removed) {
sector.shadow.show();
}
if(!sector.removed) {
sector.wijAnimate({
transform: "t0,0"
}, duration, easing);
}
if(sector.tracker && !sector.tracker.removed) {
sector.tracker.wijAnimate({
transform: "t0,0"
}, duration, easing);
}
if(sector.shadow && !sector.shadow.removed) {
sector.shadow.wijAnimate({
transform: "t0,0"
}, duration, easing);
}
offset = {
x: 0,
y: 0
};
explodeAnimationShowing = false;
sector.explodeAnimationShowing = explodeAnimationShowing;
}, 150);
sector.hideAnimationTimer = hideAnimationTimer;
}
}).on(touchEventPre + "mousemove." + o.widgetName, "." + o.wijCSS.pieElement, function (e) {
if(disabled) {
return;
}
var mouseMove = o.mouseMove, target = $(e.target), dataObj;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
if(!dataObj) {
return;
}
if(isFunction(mouseMove)) {
mouseMove.call(ele, e, dataObj);
}
}).on(touchEventPre + "click." + o.widgetName, "." + o.wijCSS.pieElement, function (e) {
if(disabled) {
return;
}
var click = o.click, target = $(e.target), dataObj;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
if(!dataObj) {
return;
}
if(isFunction(click)) {
click.call(ele, e, dataObj);
}
});
};
PieChartRender.prototype.unbindLiveEvents = function () {
var ele = this.element, o = this.options;
ele.off("." + o.widgetName, "." + o.wijCSS.pieElement);
};
return PieChartRender;
})();
chart.PieChartRender = PieChartRender;
})(wijmo.chart || (wijmo.chart = {}));
var chart = wijmo.chart;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/// <reference path="../wijtextbox/jquery.wijmo.wijtextbox.ts" />
/*globals jQuery, window, XMLHttpRequest*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
(function (tree) {
"use strict";
var $ = jQuery, widgetName = "wijtree";
/** @widget */
var wijtree = (function (_super) {
__extends(wijtree, _super);
function wijtree() {
_super.apply(this, arguments);
}
wijtree.prototype._create = function () {
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
this._initState();
this._createTree();
this._attachEvent();
this._attachNodeEvent();
};
wijtree.prototype._setOption = function (key, value) {
var self = this, isResetHitArea = false, o = self.options, check, node;
switch(key) {
case "allowDrag":
self._setAllowDrag(value);
break;
case "allowDrop":
self._setAllowDrop(value);
break;
case "showCheckBoxes":
self._setCheckBoxes(value);
break;
case "showExpandCollapse":
if(self.options.showExpandCollapse !== value) {
isResetHitArea = true;
}
break;
case "disabled":
//if (value) {
// self.widgetDom.addClass(o.wijCSS.stateDisabled);
//} else {
// self.widgetDom.removeClass(o.wijCSS.stateDisabled);
//}
check = self.element.find(":wijmo-wijtreecheck");
if(check.length) {
check.wijtreecheck("option", "disabled", value);
}
self._setAllowDrag(!value);
break;
default:
break;
}
$.Widget.prototype._setOption.apply(self, arguments)//use Widget disable
;
if(key === "nodes") {
self._createChildNodes();
}
if(isResetHitArea === true) {
self._setHitArea(value);
}
};
wijtree.prototype._initState = function () {
//declare the properties of tree
var self = this, o = self.options;
self._selectedNodes = [];
self._checkedNodes = [];
if(!o.nodes) {
o.nodes = [];
}
self._enabled = true;
self._insertPosition = "unKnown"//end,after,before
;
self.nodeWidgetName = "wijtreenode";
};
wijtree.prototype._createTree = function () {
//create by dom
var self = this, o = self.options, nodes = [], treeClass = [
"wijmo-wijtree",
o.wijCSS.widget,
o.wijCSS.content,
o.wijCSS.helperClearFix,
o.wijCSS.cornerAll
].join(' ');
if(self.element.is("ul")) {
self.$nodes = self.element;
self.element.wrap("<div></div>");
self.widgetDom = self.element.parent();
} else if(self.element.is("div")) {
self.widgetDom = self.element;
self.$nodes = self.widgetDom.children("ul:eq(0)");
}
if(self.$nodes.length) {
self.widgetDom.addClass(treeClass).attr({
role: "tree",
"aria-multiselectable": true
});
self.$nodes.addClass("wijmo-wijtree-list " + o.wijCSS.helperReset);
if(o.showExpandCollapse === false) {
self.$nodes.addClass("wijmo-wijtree-allexpanded");
}
self._createChildNodes();
self.widgetDom.append($("<div>").css("clear", "both"));
}
if(o.disabled) {
self.disable();
}
};
wijtree.prototype._createChildNodes = function () {
var self = this, options = {
nIndex: undefined
}, nodes = [], ns = self.$nodes, data = self.options.nodes, lis = ns.children("li");
if(data.length) {
ns.empty();
$.each(data, function (i, n) {
var $li = self._generateMarkup(n);
ns.append($li);
options.nIndex = i;
self._createNodeWidget($li, options);
nodes.push(self._getNodeWidget($li));
});
} else {
lis.each(function (idx, ele) {
var $li = $(ele), w;
self._createNodeWidget($li, options);
w = self._getNodeWidget($li);
nodes.push(w);
data.push(w.options);
});
}
self._hasChildren = nodes.length > 0;
self._setField("nodes", nodes);
self.nodes = nodes;
};
wijtree.prototype._generateMarkup = function (item) {
var li, a, u = item.navigateUrl || "";
if(!$.isPlainObject(item)) {
return;
}
li = $("<li></li>");
a = $("<a>").attr("src", (typeof u === "string" && u) ? u : "#");
a.appendTo(li);
if(typeof item.text === "string" && item.text) {
$("<span>").html(item.text).appendTo(a);
}
return li;
};
wijtree.prototype._createNodeWidget = function ($li, options) {
var self = this, nodeWidgetName = self.nodeWidgetName;
if($.fn[nodeWidgetName]) {
$li.data("owner", this);
if(!!options && $.isPlainObject(options)) {
$.extend(options, {
treeClass: this.widgetFullName
});
$li[nodeWidgetName](options);
} else {
$li[nodeWidgetName]({
treeClass: this.widgetFullName
});
}
}
return $li;
};
wijtree.prototype._attachEvent = /*tree event*/
function () {
var self = this;
self.element.bind($.browser.msie ? "focusin." : "focus." + self.widgetName, $.proxy(self._onFocus, self)).bind("mouseover." + this.widgetName, $.proxy(self._onMouseOver, self));
if(self.options.allowDrop) {
self._attachDroppable();
}
};
wijtree.prototype._attachDroppable = function () {
var self = this, o = self.options, options = {
accept: "li",
scope: "tree",
drop: undefined
}, setTriState = function (node) {
if(o.showCheckBoxes && o.allowTriState && !node.element.is(":" + self.widgetFullName) && node._getField("nodes").length > 0) {
node._getField("nodes")[0]._setParentCheckState();
}
}, droppable = o.droppable;
$.extend(options, droppable);
options.drop = function (event, ui) {
var d = ui.draggable, dragNode = self._getNodeWidget(d), dropNode, position, oldOwner, parent, brothers, idx, oldPosition, newPosition = -1;
if(self._trigger("nodeBeforeDropped", event, ui) === false || !dragNode || o.disabled) {
self._isDragging = false;
return;
}
dropNode = dragNode._dropTarget;
position = dragNode._insertPosition;
if(dropNode && position !== "unKnown") {
oldOwner = d.data("owner");
if(oldOwner) {
oldPosition = d.index();
}
if(position === "end") {
newPosition = dropNode._getField("nodes").length;
parent = dropNode;
} else if(position === "before" || position === "after") {
parent = dropNode._getField("owner");
brothers = parent._getField("nodes");
idx = $.inArray(dropNode, brothers);
if(idx !== -1) {
newPosition = position === "before" ? idx : idx + 1;
}
}
if(droppable && $.isFunction(droppable.drop)) {
ui.oldParent = oldOwner.element;
ui.newParent = parent.element;
ui.oldIndex = oldPosition;
ui.newIndex = newPosition;
droppable.drop.call(self.element, event, ui);
} else {
if(oldOwner) {
oldOwner.remove(d);
}
if(newPosition !== -1) {
// re-calculate position (when old parent== new parent)
if(position === "before" || position === "after") {
if(idx != $.inArray(dropNode, brothers)) {
newPosition--;
}
}
// Handling when the drop tree has no child-nodes
if(self.$nodes.children("li").length) {
parent.add(d, newPosition);
} else {
self.add(d, newPosition);
}
}
}
/*reset old tree*/
$("a:eq(0)", d).blur();
dragNode._tree._isDragging = false;
if(dragNode.options.selected) {
dragNode._setSelected(false);
}
/*set tree*/
setTriState(oldOwner);
setTriState(parent);
$.extend(ui, {
sourceParent: oldOwner ? oldOwner.element : null,
sIndex: oldPosition,
targetParent: parent.element,
tIndex: newPosition,
widget: dragNode
});
self._trigger("nodeDropped", event, ui);
}
};
if($.fn.droppable) {
self.widgetDom.droppable(options);
}
};
wijtree.prototype._attachNodeEvent = function () {
this.element.bind("click." + this.widgetName, $.proxy(this._onClick, this)).bind("mouseout." + this.widgetName, $.proxy(this._onMouseOut, this)).bind("keydown." + this.widgetName, $.proxy(this._onKeyDown, this));
};
wijtree.prototype._onClick = function (event) {
this._callEvent(event, '_onClick');
if($.browser.webkit) {
this.widgetDom.focus();
}
};
wijtree.prototype._onFocus = function (event) {
this._callEvent(event, '_onFocus');
};
wijtree.prototype._onKeyDown = function (event) {
this._callEvent(event, '_onKeyDown');
};
wijtree.prototype._onMouseOut = function (event) {
this._callEvent(event, '_onMouseOut');
};
wijtree.prototype._onMouseOver = function (event) {
this._callEvent(event, '_onMouseOver');
};
wijtree.prototype._callEvent = function (event, type) {
var el = event.target, node;
if(el) {
node = this._getNodeWidgetByDom(el);
if(node === null) {
return;
}
node[type](event);
}
};
wijtree.prototype._nodeSelector = function () {
return ":wijmo-wijtreenode";
};
wijtree.prototype.getSelectedNodes = /*public methods*/
/**
* The getSelectedNodes method gets the selected nodes.
* @example $("selector").wijtree("getSelectedNodes");
* @returns {array}
*/
function () {
return this._selectedNodes;
};
wijtree.prototype.getCheckedNodes = /**
* The getCheckedNodes method gets the nodes which are checked.
* @example $("selector").wijtree("getCheckedNodes");
* @returns {array}
*/
function () {
var self = this, checkedNodes = [], nodeWidgetName = self.nodeWidgetName;
$(self._nodeSelector(), self.element).each(function (idx, ele) {
if($(ele)[nodeWidgetName]("option", "checked") && $(ele)[nodeWidgetName]("option", "checkState") !== "indeterminate") {
checkedNodes.push($(ele));
}
});
return checkedNodes;
};
wijtree.prototype.destroy = /**
* The destroy method will remove the rating functionality completely and will return the element to its pre-init state.
* @example $("selector").wijtree("destroy");
*/
function () {
var self = this, $nodes = self.$nodes, o = self.options, c = [
"wijmo-wijtree",
o.wijCSS.widget,
o.wijCSS.content,
o.wijCSS.helperClearFix,
o.wijCSS.cornerAll
].join(' ');
;
self.widgetDom.removeClass(c).removeAttr("role").removeAttr("aria-multiselectable");
if(self.widgetDom.data("uiDroppable")) {
self.widgetDom.droppable("destroy");
}
self.widgetDom.children("div[style]:last").remove();
$nodes.removeData("nodes").removeClass("wijmo-wijtree-list " + o.wijCSS.helperReset);
$nodes.children("li").each(function (idx, ele) {
var nodeWidget = self._getNodeWidget($(ele));
if(nodeWidget) {
nodeWidget.destroy();
}
});
$.wijmo.wijtree.prototype.options.nodes = null;
$.Widget.prototype.destroy.apply(this);
};
wijtree.prototype.add = /**
* The add method adds a node to the tree widget.
* @example $("#tree").wijtree("add", "node 1", 1);
* @param {string|object} node
* 1.markup html.such as "<li><a>node</a></li>" as a node.
* 2.wijtreenode widget.
* 3.object options according to the options of wijtreenode.
* 4.node's text.
* @param {number} position The position to insert at.
*/
function (node, position) {
var nodeWidget = null, o = {
}, $node, nodes, self = this, i, originalLength, itemDom = "<li><a href='{0}'>{1}</a></li>", cnodes;
if(typeof node === "string") {
$node = $(itemDom.replace(/\{0\}/, "#").replace(/\{1\}/, node));
self._createNodeWidget($node, o);
nodeWidget = $node.data($node.data("widgetName"));
} else if(node.jquery) {
if(!node.data("widgetName")) {
self._createNodeWidget(node, o);
}
nodeWidget = node.data(node.data("widgetName"));
} else if(node.nodeType) {
$node = $(node);
self._createNodeWidget($node, o);
nodeWidget = $node.data($node.data("widgetName"));
} else if($.isPlainObject(node)) {
$node = $(itemDom.replace(/\{0\}/, node.url ? node.url : "#").replace(/\{1\}/, node.text))//node
;
self._createNodeWidget($node, node);
nodeWidget = $node.data($node.data("widgetName"));
}
if(nodeWidget === null) {
return;
}
nodes = self._getField("nodes");
if(!position || position > nodes.length) {
if(position !== 0) {
position = nodes.length;
}
}
cnodes = nodeWidget._getField("nodes");
nodeWidget._tree = self;
for(i = 0; i < cnodes.length; i++) {
cnodes[i]._tree = self;
}
nodeWidget._setField("owner", this);
originalLength = nodes.length;
if(originalLength > 0 && originalLength !== position) {
if(nodeWidget.element.get(0) !== nodes[position].element.get(0)) {
nodeWidget.element.insertBefore(nodes[position].element);
}
} else {
self.$nodes.append(nodeWidget.element);
}
self._changeCollection(position, nodeWidget);
nodeWidget._initNodeClass();
//self._refreshNodesClass();
};
wijtree.prototype.remove = /**
* The remove method removes the indicated node from the wijtree element.
* @example $("#tree").wijtree("remove", 1);
* @param {number|object} node
* which node to be removed
* 1.wijtreenode element.
* 2.the zero-based index of which node you determined to remove.
*/
function (node) {
var idx = -1, nodeWidget, nodes;
if(node && node.jquery) {
idx = node.index();
} else if(typeof node === "number") {
idx = node;
}
nodes = this._getField("nodes");
if(idx < 0 || idx >= nodes.length) {
return;
}
nodeWidget = nodes[idx];
nodeWidget.element.detach();
this._changeCollection(idx);
//this._refreshNodesClass();
};
wijtree.prototype._changeCollection = function (idx, nodeWidget) {
var nodes = this._getField("nodes"), ons = this.options.nodes;
if(nodeWidget) {
nodes.splice(idx, 0, nodeWidget);
ons.splice(idx, 0, nodeWidget.options);
} else {
nodes.splice(idx, 1);
ons.splice(idx, 1);
}
};
wijtree.prototype.getNodes = /**
* The getNodes method gets an array that contains the root nodes of the current tree.
* @example $("#tree").wijtree("getNodes");
* @return {Array}
*/
function () {
return this.nodes;
};
wijtree.prototype.findNodeByText = /**
* The findNodeByText method finds a node by the specified node text.
* @example $("#tree").wijtree("findNodeByText", "node 1");
* @param {string} txt The text of which node you want to find.
* @return {wijtreenode}
*/
function (txt) {
var nodes = $(".wijmo-wijtree-node a>span", this.$nodes).filter(function () {
return $(this).text() === txt;
});
if(nodes.length) {
return this._getNodeWidgetByDom(nodes.get(0));
}
return null;
};
wijtree.prototype._setAllowDrag = function (value) {
var self = this, $allNodes, nodeSelector = self._nodeSelector(), nodeWidgetName = "wijmoWijtreenode";
if(!$.fn.draggable) {
return;
}
if(value) {
$allNodes = self.element.find(nodeSelector);
$allNodes.each(function () {
var w = $(this).data(nodeWidgetName);
if(!$(this).data("uiDraggable") && !w.$navigateUrl.data("events") || !w.$navigateUrl.data("events").mousedown) {
w.$navigateUrl.one("mousedown", w, w._onMouseDown);
}
});
} else {
$allNodes = self.element.find(nodeSelector + ":ui-draggable");
$allNodes.draggable("destroy");
}
};
wijtree.prototype._setAllowDrop = function (value) {
if(!$.fn.droppable) {
return;
}
if(value) {
if(!this.widgetDom.data("uiDroppable")) {
this._attachDroppable();
}
} else if(this.widgetDom.droppable) {
this.widgetDom.droppable("destroy");
}
};
wijtree.prototype._setCheckBoxes = function (value) {
var self = this;
self.$nodes.children("li").each(function (idx, ele) {
var nodeWidget = self._getNodeWidget($(ele));
if(nodeWidget !== null) {
nodeWidget._setCheckBoxes(value);
}
});
};
wijtree.prototype._setHitArea = function (value) {
var self = this;
self.$nodes[value ? "addClass" : "removeClass"]("wijmo-wijtree-allexpanded");
self.$nodes.children("li").each(function (idx, ele) {
var nodeWidget = self._getNodeWidget($(ele));
if(nodeWidget !== null) {
nodeWidget._setHitArea(value);
}
});
};
wijtree.prototype._getNodeWidget = /*region methods(private)*/
function ($node) {
if($node.is(this._nodeSelector())) {
var widget = $node.data($node.data("widgetName"));
return widget;
}
return null;
};
wijtree.prototype._getNodeWidgetByDom = function (el) {
var node = this._getNodeByDom(el);
return this._getNodeWidget(node);
};
wijtree.prototype._getNodeByDom = function (el) {
//Arg :Dom Element
return $(el).closest(this._nodeSelector());
};
wijtree.prototype._refreshNodesClass = function () {
var nodes = this._getField("nodes"), i;
for(i = 0; i < nodes.length; i++) {
nodes[i]._initNodeClass();
}
};
wijtree.prototype._getField = function (key) {
return this.element.data(key);
};
wijtree.prototype._setField = function (key, value) {
return this.element.data(key, value);
};
return wijtree;
})(wijmo.wijmoWidget);
tree.wijtree = wijtree;
/** @ignore */
var wijtreenode = (function (_super) {
__extends(wijtreenode, _super);
function wijtreenode() {
_super.apply(this, arguments);
}
wijtreenode.prototype._setOption = function (key, value) {
var self = this, check, i;
switch(key) {
case "accessKey":
if(self.$navigateUrl !== null) {
self.$navigateUrl.attr("accesskey", value);
}
break;
case "checked":
self._checkState = value ? "checked" : "unChecked";
self._setChecked(value);
break;
case "collapsedIconClass":
case "expandedIconClass":
case "itemIconClass":
self.options[key] = value;
self._initNodeImg();
break;
case "expanded":
self._setExpanded(value);
break;
case "selected":
self._setSelected(value);
break;
case "text":
self._setText(value);
break;
case "toolTip":
self._setToolTip(value);
break;
case "navigateUrl":
self._setNavigateUrlHref(value);
break;
case "disabled":
if(self._isClosestDisabled() && value === true) {
return;
}
check = self.element.find(":wijmo-wijtreecheck");
if(check.length) {
check.wijtreecheck("option", "disabled", value);
}
break;
default:
break;
}
if(key === "nodes") {
self.options.nodes.length = 0;
$.each(value, function (i, n) {
self.options.nodes.push(n);
});
self.options.nodes.concat();
self._hasChildren = self._getChildren();
self._createChildNodes(self.element);
self._initNodeClass();
} else {
$.Widget.prototype._setOption.apply(self, arguments);
}
};
wijtreenode.prototype._initState = function () {
// declare the properity of node
this._tree = null;
this._dropTarget = null;
this._checkState = "unChecked"//Checked, UnChecked, Indeterminate
;
this._value = this._text = this._navigateUrl = "";
this._insertPosition = "unKnown"//end,after,before
;
this._hasNodes = false//for ajax load
;
};
wijtreenode.prototype._create = function () {
var self = this, o = self.options;
self._initState();
self._createTreeNode();
self._initNode();
self.element.data("widgetName", "wijmoWijtreenode");
if(o.selected) {
self._tree._selectedNodes.push(self);
}
if(o.checked) {
self._checkState = "checked";
if(self.$checkBox) {
if(o.checkState === "indeterminate") {
self.$checkBox.wijtreecheck("option", "checkState", "triState");
} else {
self.$checkBox.wijtreecheck("option", "checkState", "check");
}
}
}
};
wijtreenode.prototype._createTreeNode = function () {
var $li = this.element, ownerNodes, childOpts, self = this, ownerOpts, o = self.options, nodes = [];
this.$navigateUrl = $li.children("a");
if(self._tree === null) {
self._tree = self._getTree();
}
if(!isNaN(o.nIndex)) {
ownerOpts = self._getOwner().options , childOpts = ownerOpts.nodes[o.nIndex];
if(childOpts && !childOpts.nodes) {
childOpts.nodes = [];
}
$.extend(o, childOpts);
ownerOpts.nodes[o.nIndex] = o;
} else if(!o.nodes) {
o.nodes = [];
}
self.$nodeBody = null;
self.$checkBox = null;
self.$hitArea = null;
self.$nodes = null;
self.$nodeImage = $("<span>");
self.$nodeBody = $("<div>").attr({
role: "treeitem",
"aria-expanded": false,
"aria-checked": false,
"aria-selected": false
});
if(self._tree.options.showCheckBoxes === true) {
self.$checkBox = $("<div>");
}
if(self.$navigateUrl.length === 0) {
self.$navigateUrl = $li.children("div");
self.$navigateUrl.addClass("wijmo-wijtree-template");
self._isTemplate = true;
}
if(self.$navigateUrl.length === 0) {
self.$navigateUrl = $("<a>");
self.$navigateUrl.attr("href", "#");
}
if(!self._isTemplate) {
self.$text = self.$navigateUrl.find("span:eq(0)");
if(self.$text.length === 0) {
self.$navigateUrl.wrapInner("<span></span>");
self.$text = self.$navigateUrl.find("span:eq(0)");
}
}
self._hasChildren = self._getChildren();
self.$inner = $("<span></span>").addClass(o.wijCSS.helperClearFix + " wijmo-wijtree-inner " + o.wijCSS.cornerAll);
self._createChildNodes($li);
self.$inner.append(self.$nodeImage);
if(self.$checkBox !== null) {
self.$inner.append(self.$checkBox);
self.$checkBox.wijtreecheck();
}
self.$inner.append(self.$navigateUrl);
self.$nodeBody.append(self.$inner);
$li.prepend(self.$nodeBody);
};
wijtreenode.prototype._createChildNodes = function ($li) {
var self = this, nodes = [], o = self.options;
if(self._hasChildren) {
$li.addClass("wijmo-wijtree-parent");
self.$nodeBody.addClass("wijmo-wijtree-node wijmo-wijtree-header " + o.wijCSS.stateDefault);
self.$hitArea = $("<span>");
self.$inner.prepend(self.$hitArea);
self.$nodes = $li.find("ul:eq(0)");
nodes = self._createChildNode();
self.$nodes.addClass("wijmo-wijtree-list " + o.wijCSS.helperReset + " wijmo-wijtree-child");
} else {
$li.addClass("wijmo-wijtree-item");
self.$nodeBody.addClass("wijmo-wijtree-node " + o.wijCSS.stateDefault);
}
self._setField("nodes", nodes);
};
wijtreenode.prototype._createChildNode = function () {
var self = this, o = self.options, nodes = [], opts = {
nIndex: undefined,
treeClass: undefined,
cfli: undefined,
nodes: undefined
};
if(o.nodes && o.nodes.length) {
if(self.$nodes && self.$nodes.length) {
self.$nodes.empty();
} else {
self.$nodes = $("<ul>").appendTo(self.element);
}
$.each(o.nodes, function (i, n) {
var $li = self._generateMarkup(n), nodeWidget;
self.$nodes.append($li);
$li.data("owner", self);
opts.nIndex = i;
opts.treeClass = o.treeClass;
$li.wijtreenode(opts);
nodeWidget = self._getNodeWidget($li);
nodeWidget._index = i;
nodes.push(nodeWidget);
});
} else {
if(!o.nodes) {
o.nodes = [];
}
self.$nodes.children("li").each(function (i, n) {
var $li = $(n), nodeWidget;
$li.data("owner", self);
opts.cfli = true;
opts.nIndex = i;
opts.treeClass = o.treeClass;
opts.nodes = [];
$li.wijtreenode(opts)//the arg must be jquerify
;
nodeWidget = self._getNodeWidget($li);
nodeWidget._index = i;
nodes.push(nodeWidget);
});
}
return nodes;
};
wijtreenode.prototype._generateMarkup = function (item) {
var li, a, u = item.navigateUrl || "";
if(!$.isPlainObject(item)) {
return;
}
li = $("<li></li>");
a = $("<a>").attr("src", (typeof u === "string" && u) ? u : "#");
a.appendTo(li);
if(typeof item.text === "string" && item.text) {
$("<span>").html(item.text).appendTo(a);
}
return li;
};
wijtreenode.prototype._initNode = function () {
//init node(children,class, tree)
var self = this, o = self.options;
if(!self._initialized) {
self._initialized = true;
self._initNavigateUrl();
if(!self._isTemplate && self.$text) {
self._text = self.$text.html();
o.text = self.$text.html();
}
self._hasChildren = self._getChildren();
self._initNodesUL();
self._initNodeClass();
self._initNodeImg();
self._initCheckBox();
self.$navigateUrl.one("mousedown", self, self._onMouseDown);
}
};
wijtreenode.prototype._initNodeClass = function () {
var self = this, o = self.options, style, nodeClass = "wijmo-wijtree-item", hitClass = o.wijCSS.icon + " " + (o.expanded ? o.wijCSS.iconArrowRightDown : o.wijCSS.iconArrowRight);
if(self._tree.options.showExpandCollapse) {
if(self._hasChildren || !!o.hasChildren) {
if(self.$hitArea !== null) {
self.$hitArea.removeClass([
o.wijCSS.icon,
o.wijCSS.iconArrowRightDown,
o.wijCSS.iconArrowRight
].join(' ')).addClass(hitClass);
} else {
self.$hitArea = $("<span>").addClass(hitClass).prependTo(self.$inner);
self.element.removeClass(nodeClass).addClass("wijmo-wijtree-parent");
}
if(self._hasChildren) {
//self.$nodes[o.expanded ? "show" : "hide"]();
// the performance "display:none" is must better then show,
// hide, fixed bug on adding lots of child nodes.
style = o.expanded ? "" : "none";
self.$nodes.css({
display: style
});
}
} else if(self.$hitArea) {
self.$hitArea.remove();
self.$hitArea = null;
self.element.removeClass("wijmo-wijtree-parent").addClass(nodeClass);
}
}
if(!self._hasChildren && self.$nodes) {
self.$nodes.css({
display: "none"
});
}
if(o.selected && self.$inner) {
self.$inner.addClass(o.wijCSS.stateActive);
}
};
wijtreenode.prototype._initCheckBox = function () {
var self = this, o = self.options;
if(self.$checkBox && o.checkState) {
switch(o.checkState) {
case "checked":
self.$checkBox.wijtreecheck("option", "checkState", "check");
break;
case "indeterminate":
self.$checkBox.wijtreecheck("option", "checkState", "triState");
break;
case "unChecked":
self.$checkBox.wijtreecheck("option", "checkState", "unCheck");
break;
default:
self.$checkBox.wijtreecheck("option", "checkState", "unCheck");
break;
}
}
};
wijtreenode.prototype._initNodesUL = function () {
var self = this;
if(self._tree.options.showExpandCollapse) {
if(self._hasChildren) {
self.$nodes[self._expanded ? 'show' : 'hide']();
}
}
};
wijtreenode.prototype._initNavigateUrl = function () {
var self = this, href = self.$navigateUrl.attr("href");
self.$navigateUrl.bind("blur." + self.widgetName, self, self._onBlur);
if(!this._isTemplate) {
self._navigateUrl = !!href ? href : "";
self._setNavigateUrlHref(href);
}
};
wijtreenode.prototype._applyIconClass = function (el, o) {
if(el.attr("expandediconclass")) {
o.expandedIconClass = el.attr("expandediconclass");
el.removeAttr("expandediconclass");
}
if(el.attr("collapsediconclass")) {
o.collapsedIconClass = el.attr("collapsediconclass");
el.removeAttr("collapsediconclass");
}
if(el.attr("itemiconclass")) {
o.itemIconClass = el.attr("itemiconclass");
el.removeAttr("itemiconclass");
}
};
wijtreenode.prototype._initNodeImg = function () {
//ui-icon instead of image
var self = this, o = self.options, el = self.element;
if(self.$nodeImage === null || !self.$nodeImage.length) {
self.$nodeImage = $("<span>");
}
/* initial html has icon attribute for asp.net mvc*/
self._applyIconClass(el, o);
/* end */
if(o.collapsedIconClass !== "" && o.expandedIconClass !== "") {
self.$nodeImage.removeClass().addClass(o.wijCSS.icon).addClass(o.expanded ? o.expandedIconClass : o.collapsedIconClass);
if(!self._tree.options.showExpandCollapse) {
self.$nodeImage.addClass(o.expandedIconClass);
}
self.$nodeImage.insertBefore(self.$checkBox);
} else if(o.itemIconClass !== "") {
self.$nodeImage.removeClass().addClass(o.wijCSS.icon);
self.$nodeImage.addClass(o.itemIconClass);
self.$nodeImage.insertBefore(self.$checkBox);
}
};
wijtreenode.prototype._setNavigateUrlHref = function (href) {
if(this.$navigateUrl) {
if(href === "" || typeof href === "undefined") {
href = "#";
}
this.$navigateUrl.attr("href", href);
}
};
wijtreenode.prototype._editNode = function () {
//edit node
this._tree._editMode = true;
this.$navigateUrl.hide();
if(!this.$editArea) {
this.$editArea = $("<input type=\"text\">").wijtextbox();
}
this.$editArea.val(this.$text.html());
this.$editArea.insertBefore(this.$navigateUrl);
this.$editArea.bind("blur", this, this._editionComplete);
this.$editArea.focus();
};
wijtreenode.prototype._editionComplete = function (event) {
var self = event.data, text;
self._tree._editMode = false;
if(self.$editArea) {
text = self.$editArea.val();
self.$editArea.remove();
}
self.$navigateUrl.show();
self.$editArea = null;
self._changeText(text);
};
wijtreenode.prototype._changeText = function (text) {
var self = this, o = self.options;
if(self.$text !== null && text !== "") {
self.$text.text(text);
o.text = text;
self._tree._trigger("nodeTextChanged", null, self);
}
};
wijtreenode.prototype._expandCollapseItem = /*behavior Methods*/
function () {
//access
var self = this, o = self.options;
if(!self._tree.options.disabled && !self._isClosestDisabled()) {
if(self._hasChildren || o.hasChildren) {
self._setExpanded(!o.expanded);
}
}
};
wijtreenode.prototype._expandNode = function (expand) {
var self = this, treeOption = self._tree.options, trigger = expand ? "nodeExpanding" : "nodeCollapsing";
if(self._tree._trigger(trigger, null, {
node: this,
params: this.options.params
}) === false) {
return;
}
self.$nodeBody.attr("aria-expanded", expand);
self._expanded = expand;
self.options.expanded = expand;
if(!treeOption.disabled && !self._isClosestDisabled()) {
if(expand) {
if(treeOption.expandDelay > 0) {
if(typeof self._expandTimer !== "undefined") {
self._expandTimer = window.clearTimeout(self._expandTimer);
}
self._expandTimer = window.setTimeout(function () {
self._expandNodeVisually();
}, treeOption.expandDelay);
} else {
self._expandNodeVisually();
}
} else {
if(treeOption.collapseDelay > 0) {
self._collapseTimer = window.clearTimeout(self._collapseTimer);
self._collapseTimer = window.setTimeout(function () {
self._collapseNodeVisually();
}, treeOption.collapseDelay);
} else {
self._collapseNodeVisually();
}
}
}
};
wijtreenode.prototype._expandNodeVisually = function () {
var self = this, nodes, o = self.options;
if(self._tree.options.autoCollapse) {
//autoCollapse
nodes = self.element.siblings(":" + this.widgetFullName);
$.each(nodes, function (i) {
var widget = self._getNodeWidget(nodes[i]);
if(widget.options.expanded) {
widget._setExpanded(false);
}
});
}
if(o.collapsedIconClass !== "" && o.expandedIconClass !== "") {
self.$nodeImage.removeClass(o.collapsedIconClass).addClass(o.expandedIconClass);
}
self._internalSetNodeClass(true);
self._show();
};
wijtreenode.prototype._collapseNodeVisually = function () {
var self = this;
if(self.options.collapsedIconClass !== "" && self.options.expandedIconClass !== "") {
self.$nodeImage.removeClass(self.options.expandedIconClass).addClass(self.options.collapsedIconClass);
}
self._internalSetNodeClass(false);
self._hide();
};
wijtreenode.prototype._internalSetNodeClass = function (expanded) {
var css = this.options.wijCSS, iconCss = [
css.icon,
css.iconArrowRightDown,
css.iconArrowRight
].join(' ');
this.$hitArea && this.$hitArea.removeClass(iconCss).addClass(css.icon + " " + (expanded ? css.iconArrowRightDown : css.iconArrowRight));
};
wijtreenode.prototype._show = function () {
this._animation(true);
};
wijtreenode.prototype._hide = function () {
this._animation(false);
};
wijtreenode.prototype._animation = function (show) {
var self = this, el = self.$nodes, animate = show ? "expandAnimation" : "collapseAnimation", event = show ? "nodeExpanded" : "nodeCollapsed", effect, animation = self._tree.options[animate];
if(el) {
if(animation) {
effect = animation.animated || animation.effect;
if($.effects && !!effect) {
el[show ? "show" : "hide"](effect, {
easing: animation.easing
}, animation.duration, function () {
self._tree._trigger(event, null, self);
});
} else {
el[show ? "show" : "hide"](animation.duration, function () {
self._tree._trigger(event, null, self);
});
}
} else {
el[show ? "show" : "hide"]();
self._tree._trigger(event, null, self);
}
}
};
wijtreenode.prototype._getBounds = function ($el) {
//get top,left,height,width of element
var h = $el.height(), w = $el.width(), t = $el.offset().top, l = $el.offset().left;
return {
h: h,
w: w,
t: t,
l: l
};
};
wijtreenode.prototype._isMouseInsideRect = function (p, b) {
//whether mouse is over a element
if(p.x < b.l || p.x >= b.l + b.w) {
return false;
}
if(p.y <= b.t + 1 || p.y >= b.t + b.h) {
/*fix 1px on the mouse out the element
(e.g. 31<30.98 now 31<30.98+1 maybe
pageY/PageX are int but left/top are float)*/
return false;
}
return true;
};
wijtreenode.prototype._getNodeByMouseOn = function (p) {
$("li").each(function () {
var b = this._getBounds($(this));
if($.ui.isOver(p.y, p.x, b.t, b.l, b.h, b.w)) {
return $(this);
}
});
return null;
};
wijtreenode.prototype._drowTemplate = function (p, temp, targetEl) {
var position = "unKnown", body = targetEl.is(".wijmo-wijtree-node") ? targetEl : targetEl.children(".wijmo-wijtree-node"), n = this._getBounds(body);
temp.width(body.width());
if(p.y > n.t && p.y < n.t + n.h / 2) {
temp.offset({
left: n.l,
top: n.t
});
position = "before";
} else if(p.y > n.t + n.h / 2 && p.y < n.t + n.h) {
temp.offset({
left: n.l,
top: n.t + n.h
});
position = "after";
}
return position;
};
wijtreenode.prototype._beginDrag = function (e) {
//set draggable
var self = this, $item = self.element, dragVisual, to = self._tree.options, draggable = to.draggable, options = {
cursor: "point",
cursorAt: {
top: 15,
left: -25
},
helper: function () {
return $("<div>" + self.$navigateUrl.html() + "</div>").addClass(to.wijCSS.header + " " + to.wijCSS.cornerAll);
},
distance: $.browser.msie ? 1 : 10,
handle: self.$navigateUrl,
scope: "tree",
stop: undefined,
start: undefined,
drag: undefined
}, temp = $("<div>").addClass("wijmo-wijtree-insertion " + to.wijCSS.stateDefault);
if(typeof to.dropVisual === "string") {
dragVisual = $(to.dropVisual);
temp = dragVisual.length ? dragVisual : temp;
} else if($.isFunction(to.dropVisual)) {
dragVisual = $(to.dropVisual.call());
temp = dragVisual.length ? dragVisual : temp;
}
temp.hide();
$.extend(options, draggable);
options.start = function (event, ui) {
self._tree._isDragging = true;
self._tree.widgetDom.prepend(temp);
self._tree._trigger("nodeDragStarted", event, self);
if(draggable && $.isFunction(draggable.start)) {
draggable.start.call(self.element, event, ui);
} else {
$item.hide();
}
};
options.drag = function (event, ui) {
var t = event.srcElement || event.originalEvent.target, targetEl = $(t), dropNode, p = {
x: event.pageX,
y: event.pageY
};
if(temp) {
temp.hide();
}
if(targetEl) {
dropNode = self._getNodeWidget(targetEl);
if(dropNode && !dropNode._tree.options.disabled) {
if(targetEl.closest(".wijmo-wijtree-inner", self.element).length) {
self._insertPosition = "end"//end,after,before
;
} else {
temp.show();
self._insertPosition = self._drowTemplate(p, temp, dropNode.element);
}
if(dropNode != self) {
self._dropTarget = dropNode;
}
} else if(targetEl.is(":" + self.options.treeClass)) {
self._dropTarget = targetEl.data(self.options.treeClass);
self._insertPosition = "end";
}
}
self._tree._trigger("nodeDragging", event, self);
if(draggable && $.isFunction(draggable.drag)) {
draggable.drag.call(self.element, event, ui);
}
};
options.stop = function (event, ui) {
temp.remove();
self._dropTarget = null;
self._insertPosition = "unKnown";
self._tree._isDragging = false;
if(draggable && $.isFunction(draggable.stop)) {
draggable.stop.call(self.element, event, ui);
} else {
$item.show();
self._resetDrag();
}
};
if($.fn.draggable) {
$item.draggable(options).trigger(e);
if($.browser.mozilla) {
self._setFocused(true);
}
}
};
wijtreenode.prototype._resetDrag = function () {
var self = this, nodes, i;
if(!self._tree.options.allowDrag && self.element.data("uiDraggable")) {
self.element.draggable("destroy");
}
nodes = self._getField("nodes");
for(i = 0; i < nodes.length; i++) {
nodes[i]._resetDrag();
}
};
wijtreenode.prototype._checkClick = function () {
//check , uncheck, indeterminate
var self = this, o = self.options;
if(!self._tree.options.disabled && !self._isClosestDisabled()) {
if(o.checked && self._checkState === "indeterminate") {
self._checkState = "checked";
self._checkItem();
} else {
self._checkState = o.checked ? "unChecked" : "checked";
self._setChecked(!o.checked);
}
self._tree._trigger("nodeCheckChanged", null, self);
}
};
wijtreenode.prototype._checkItem = function () {
//access
var self = this, autoCheck = false, tree = self._tree;
if(tree === null || !tree.options.showCheckBoxes) {
return;
}
if(tree.options.autoCheckNodes && self._checkState !== "indeterminate") {
autoCheck = true;
self._changeCheckState(self.options.checked);
}
if(tree.options.allowTriState) {
self._setParentCheckState();
}
self[self.options.checked ? "_checkNode" : "_unCheckNode"](autoCheck);
};
wijtreenode.prototype._checkNode = function (autoCheck) {
//todo: add to tree._checkedNodes
var self = this, o = self.options, nodes = this._getField("nodes"), i;
if(self._checkState === "checked") {
self.$checkBox.wijtreecheck("option", "checkState", "check");
o.checkState = "checked";
} else if(self._checkState === "indeterminate") {
//todo: tristate Style
self.$checkBox.wijtreecheck("option", "checkState", "triState");
o.checkState = "indeterminate";
}
if(autoCheck) {
for(i = 0; i < nodes.length; i++) {
nodes[i]._checkNode(true);
}
}
};
wijtreenode.prototype._unCheckNode = function (autoCheck) {
//todo: remove to tree._checkedNodes
var nodes = this._getField("nodes"), o = this.options, i;
this.$checkBox.wijtreecheck("option", "checkState", "unCheck");
o.checkState = "unChecked";
if(autoCheck) {
for(i = 0; i < nodes.length; i++) {
nodes[i]._unCheckNode(true);
}
}
};
wijtreenode.prototype._changeCheckState = function (checked) {
var nodes = this._getField("nodes");
$.each(nodes, function (i, node) {
node.options.checked = checked;
node.$nodeBody.attr("aria-checked", checked);
node._checkState = checked ? "checked" : "unChecked";
node._changeCheckState(checked);
});
};
wijtreenode.prototype._setParentCheckState = function () {
//set parent check state
var owner = this._getOwner(), nodes, allChecked = true, hasChildrenChecked = false, triState = false, i, self = this;
if(owner.element.is(":" + self.options.treeClass)) {
return;
}
nodes = owner._getField("nodes");
for(i = 0; i < nodes.length; i++) {
if(nodes[i]._checkState === "indeterminate") {
triState = true;
}
if(nodes[i].options.checked) {
hasChildrenChecked = true;
} else {
allChecked = false;
}
if(!allChecked && hasChildrenChecked) {
break;
}
}
if(triState) {
owner._checkState = "indeterminate";
owner._setChecked(true);
} else {
if(hasChildrenChecked) {
if(allChecked) {
owner._checkState = "checked";
owner._checkNode(false);
} else {
owner._checkState = "indeterminate";
}
owner._setChecked(true);
} else {
owner._checkState = "unChecked";
owner._setChecked(false);
owner._unCheckNode(false);
}
}
owner._setParentCheckState();
};
wijtreenode.prototype._onKeyDown = /*Events*/
function (event) {
var el = $(event.target), self = this;
if(el.closest(".wijmo-wijtree-inner", self.element).length > 0) {
self._keyAction(event);
}
};
wijtreenode.prototype._onClick = function (event) {
var el = $(event.target), self = this;
if(el.closest(".wijmo-checkbox", self.element).length > 0) {
self._checkClick();
event.preventDefault();
event.stopPropagation();
} else if(self.$hitArea && self.$hitArea[0] === el[0]) {
self._expandCollapseItem();
event.preventDefault();
event.stopPropagation();
} else if(el.closest(".wijmo-wijtree-inner", self.element).length > 0) {
self._click(event);
}
};
wijtreenode.prototype._onMouseDown = function (event) {
var el = $(event.target), node = event.data;
if(!node._tree.options.disabled && node._tree.options.allowDrag) {
//prepare for drag
if(el.closest(".wijmo-wijtree-node", node.element).length > 0) {
node._beginDrag(event);
}
}
};
wijtreenode.prototype._onMouseOver = function (event) {
var el = $(event.target), self = this, rel = $(event.relatedTarget);
if(el.closest(".wijmo-wijtree-inner", self.element).length > 0 && (this._tree._overNode !== self || rel.is(':' + this.widgetFullName))) {
self._mouseOver(event);
this._tree._overNode = self;
}
self._mouseOverHitArea(event);
};
wijtreenode.prototype._onMouseOut = function (event) {
var el = $(event.target), self = this, rel = $(event.relatedTarget), node = this._getNodeWidget(rel);
if(el.closest(".wijmo-wijtree-inner", self.element).length > 0 && (this._tree._overNode !== node || rel.is(':' + this.widgetFullName) || rel.is('.wijmo-wijtree-list') || rel.is('.ui-effects-wrapper'))) {
self._mouseOut(event);
if(!node) {
this._tree._overNode = null;
}
}
self._mouseOutHitArea(event);
};
wijtreenode.prototype._onFocus = function (event) {
var el = $(event.target), self = this, css = self.options.wijCSS;
if(el.closest(".wijmo-wijtree-inner", self.element).length > 0 && !self._tree.options.disabled && !self._isClosestDisabled() && !(el.hasClass(css.iconArrowRightDown) || el.hasClass(css.iconArrowRight)) && !el.closest(".wijmo-checkbox", self.element).length) {
if(self._tree._focusNode) {
self._tree._focusNode.$navigateUrl.blur();
}
self._focused = true;
self._tree._focusNode = this;
self.$inner.addClass(css.stateFocus);
self._tree._trigger("nodeFocus", event, self)// < = NEW LINE
;
}
};
wijtreenode.prototype._onBlur = function (event) {
var el = $(event.target), self = event.data, css = self.options.wijCSS;
if(!self._tree.options.disabled && !self._isClosestDisabled()) {
self._focused = false;
if(el.closest(".wijmo-wijtree-inner", self.element).length > 0) {
self.$inner.removeClass(css.stateFocus);
}
self._tree._trigger("nodeBlur", event, self);
}
};
wijtreenode.prototype._click = function (event) {
var self = this, o = self.options, tree = self._tree, url = self.$navigateUrl.attr("href");
if(!tree.options.disabled && !self._isClosestDisabled()) {
if(!/^[#,\s]*$/.test(url)) {
if($.browser.msie && /^7\.[\d]*/.test($.browser.version)) {
if(url.indexOf(window.location.href) < 0) {
return;
}
} else {
return;
}
}
self._isClick = true;
tree._ctrlKey = event.ctrlKey;
if(o.selected && tree._ctrlKey) {
self._setSelected(false);
} else if(o.selected && !self._tree._editMode && tree.options.allowEdit && !self._isTemplate) {
self._editNode();
} else {
self._setSelected(!o.selected);
}
if(!self._isTemplate) {
event.preventDefault();
event.stopPropagation();
}
} else {
self._setNavigateUrlHref("");
}
};
wijtreenode.prototype._selectNode = function (select, event) {
var self = this, o = self.options, ctrlKey, idx;
if(!self._tree.options.disabled && !self._isClosestDisabled() && !self._tree._isDragging) {
ctrlKey = self._tree._ctrlKey;
if(ctrlKey) {
idx = $.inArray(self, self._tree._selectedNodes);
if(idx !== -1 && !select) {
self._tree._selectedNodes.splice(idx, 1);
self.$inner.removeClass(o.wijCSS.stateActive);
}
} else {
$.each(self._tree._selectedNodes, function (i, n) {
n.$inner.removeClass(o.wijCSS.stateActive);
n.options.selected = false;
n.$nodeBody.attr("aria-selected", false);
});
self._tree._selectedNodes = [];
}
if(select) {
idx = $.inArray(self, self._tree._selectedNodes);
if(idx === -1) {
this._tree._selectedNodes.push(self);
}
self.$inner.addClass(o.wijCSS.stateActive);
} else {
self.$inner.removeClass(o.wijCSS.stateActive);
}
if(self._isClick) {
self._tree._trigger("nodeClick", event, self);
}
self._isClick = false;
self._tree._ctrlKey = false;
self._tree._trigger("selectedNodeChanged", event, self);
}
};
wijtreenode.prototype.getKeyCodeEnum = /** @ignore*/
function () {
if($.ui && $.ui.keyCode) {
return $.ui.keyCode;
}
if($.mobile && $.mobile.keyCode) {
return $.mobile.keyCode;
}
throw "keyCode object is not found";
};
wijtreenode.prototype._keyAction = function (e) {
var el = e.target, self = this, isEdit = false, keyCode = self.getKeyCodeEnum();
if(self._tree.options.disabled || self._isClosestDisabled()) {
return;
}
if(el) {
if(self._tree._editMode && e.keyCode !== keyCode.ENTER) {
return;
}
switch(e.keyCode) {
case keyCode.UP:
self._moveUp();
break;
case keyCode.DOWN:
self._moveDown();
break;
case keyCode.RIGHT:
if(self._tree.options.showExpandCollapse) {
self._moveRight();
}
break;
case keyCode.LEFT:
if(self._tree.options.showExpandCollapse) {
self._moveLeft();
}
break;
case 83:
//key s
if(!self._tree._editMode && self._tree.options.allowSorting) {
self.sortNodes();
}
break;
case 113:
//key f2
if(self._tree.options.allowEdit) {
self._editNode();
}
break;
case 109:
//key -
if(self._tree.options.showExpandCollapse && this._expanded) {
self._setExpanded(false);
}
break;
case 107:
//key +
if(self._tree.options.showExpandCollapse && !this._expanded) {
self._setExpanded(true);
}
break;
case keyCode.ENTER:
if(self._tree._editMode) {
e.data = self;
self._editionComplete(e);
self._setFocused(true);
isEdit = true;
e.preventDefault();
}
break;
case keyCode.SPACE:
//check
if(self._tree.options.showCheckBoxes) {
self._checkState = self.options.checked ? "unChecked" : "checked";
self._setChecked(!self.options.checked);
}
break;
}
self._customKeyDown(e.keyCode, isEdit);
if(!self._isTemplate && e.keyCode !== keyCode.ENTER) {
e.preventDefault();
e.stopPropagation();
}
}
};
wijtreenode.prototype._customKeyDown = function (keyCode, isEdit) {
};
wijtreenode.prototype._prevNode = function (node) {
var el = node.element;
if(el.prev().length > 0) {
return el.prev().data(el.data("widgetName"));
}
};
wijtreenode.prototype._nextNode = function (node) {
var el = node.element;
if(el.next().length > 0) {
return el.next().data(el.data("widgetName"));
}
};
wijtreenode.prototype._getNextExpandedNode = function (node) {
var nextNode = node, nextNodes = node._getField("nodes"), newNode;
if(node._expanded && nextNodes.length > 0) {
newNode = nextNodes[nextNodes.length - 1];
if(newNode !== null) {
nextNode = this._getNextExpandedNode(newNode);
}
}
return nextNode;
};
wijtreenode.prototype._getNextNode = function (owner) {
var nextNode = null, self = this;
if(owner.element.is(":" + self.options.treeClass)) {
return null;
}
nextNode = self._nextNode(owner);
if(nextNode) {
return nextNode;
}
return self._getNextNode(owner._getOwner());
};
wijtreenode.prototype._moveUp = function () {
var level = this._getCurrentLevel(), prevNode = this._prevNode(this);
if(!prevNode) {
if(level > 0) {
this._getOwner()._setFocused(true);
}
} else {
this._getNextExpandedNode(prevNode)._setFocused(true);
}
};
wijtreenode.prototype._moveDown = function () {
//sometimes blur
var nodes = this._getField("nodes"), nextNode, owner, pNextNode;
if(this._expanded && nodes.length > 0) {
nodes[0]._setFocused(true);
} else {
nextNode = this._nextNode(this);
if(nextNode) {
nextNode._setFocused(true);
} else {
owner = this._getOwner();
pNextNode = this._getNextNode(owner);
if(pNextNode) {
pNextNode._setFocused(true);
}
}
}
};
wijtreenode.prototype._moveLeft = function () {
var nextNode = this._getOwner();
if(this._expanded) {
this._setExpanded(false);
} else if(nextNode !== null && !nextNode.element.is(":" + this.options.treeClass)) {
nextNode._setFocused(true);
}
};
wijtreenode.prototype._moveRight = function () {
if(this._hasChildren) {
if(!this._expanded) {
this._setExpanded(true);
} else {
var nextNode = this._getField("nodes")[0];
if(nextNode !== null) {
nextNode._setFocused(true);
}
}
}
};
wijtreenode.prototype._mouseOver = function (event) {
var self = this, tree = self._tree;
if(!tree.options.disabled && !self._isClosestDisabled() && !tree._editMode) {
self._mouseOverNode();
if(!tree._isDragging) {
tree._trigger("nodeMouseOver", event, self);
}
}
};
wijtreenode.prototype._mouseOut = function (event) {
var self = this, tree = self._tree;
if(!tree.options.disabled && !self._isClosestDisabled() && !tree._editMode) {
self._mouseOutNode();
if(!tree._isDragging) {
tree._trigger("nodeMouseOut", event, self);
}
}
};
wijtreenode.prototype._mouseOverNode = function () {
if(this.$inner !== null && !this._isOverNode) {
this.$inner.addClass(this.options.wijCSS.stateHover);
this._isOverNode = true;
}
};
wijtreenode.prototype._mouseOutNode = function () {
if(this.$inner !== null && this._isOverNode) {
this.$inner.removeClass(this.options.wijCSS.stateHover);
this._isOverNode = false;
}
};
wijtreenode.prototype._mouseOverHitArea = function (event) {
var bound, p, self = this, tree = self._tree;
if(!tree.options.disabled && !self._isClosestDisabled()) {
if(tree.options.expandCollapseHoverUsed) {
if(self._hasChildren && !self._isOverHitArea) {
bound = self._getBounds(self.element);
p = {
x: event.pageX,
y: event.pageY
};
if(self._isMouseInsideRect(p, bound)) {
self._isOverHitArea = true;
self._setExpanded(true);
}
}
}
}
};
wijtreenode.prototype._mouseOutHitArea = function (event) {
var p = {
x: event.pageX,
y: event.pageY
}, bound, self = this, tree = self._tree;
if(!tree.options.disabled && !self._isClosestDisabled()) {
if(tree.options.expandCollapseHoverUsed) {
if(self._hasChildren && !!self._isOverHitArea) {
bound = self._getBounds(self.element);
if(!self._isMouseInsideRect(p, bound)) {
self._isOverHitArea = false;
self._setExpanded(false);
}
} else if(self._getOwner().element.is(":" + self.widgetFullName)) {
bound = self._getBounds(self._getOwner().element);
if(!self._isMouseInsideRect(p, bound)) {
self._getOwner()._isOverHitArea = false;
self._getOwner()._setExpanded(false);
}
}
}
}
};
wijtreenode.prototype.destroy = /*public methods*/
/**
* Destroy the node widget.
*/
function () {
var self = this, $nodes, o = self.options;
if(self.element.data("uiDraggable")) {
self.element.draggable("destroy");
}
if(self.$hitArea) {
self.$hitArea.remove();
}
if(self.$checkBox) {
self.$checkBox.remove();
}
if(self.$nodeImage) {
self.$nodeImage.remove();
}
self.$navigateUrl.unwrap().unwrap().removeClass(o.wijCSS.stateDefault + " " + o.wijCSS.stateActive).unbind("mousedown").unbind("blur");
$nodes = this.element.find("ul:first").show();
$nodes.removeClass();
$nodes.children("li").each(function () {
var nodeWidget = self._getNodeWidget($(this));
nodeWidget.destroy();
});
self.element.removeData("nodes").removeData("owner").removeData("widgetName").removeClass();
$.Widget.prototype.destroy.apply(this);
};
wijtreenode.prototype.add = /**
* The add method adds a node to the node.
* @example $("#treenode1").wijtreenode("add", "node 1", 1);
* @param {string|object} node
* 1.markup html.such as "<li><a>node</a></li>" as a node.
* 2.wijtreenode element.
* 3.object options according to the options of wijtreenode.
* 4. node's text.
* @param {number} position The position to insert at.
*/
function (node, position) {
var nodeWidget = null, $node, nodes, self = this, cnodes, i, itemDom = "<li><a href='{0}'>{1}</a></li>", originalLength;
if(typeof node === "string") {
$node = $(itemDom.replace(/\{0\}/, "#").replace(/\{1\}/, node));
self._createNodeWidget($node);
nodeWidget = $node.data($node.data("widgetName"));
} else if(node.jquery) {
if(!node.data("widgetName")) {
self._createNodeWidget(node);
}
nodeWidget = node.data(node.data("widgetName"));
} else if(node.nodeType) {
$node = $(node);
self._createNodeWidget($node);
nodeWidget = $node.data($node.data("widgetName"));
} else if($.isPlainObject(node)) {
$node = $(itemDom.replace(/\{0\}/, node.url ? node.url : "#").replace(/\{1\}/, node.text))//node
;
self._createNodeWidget($node, node);
nodeWidget = $node.data($node.data("widgetName"));
}
if(nodeWidget === null) {
return;
}
nodes = self._getField("nodes");
if(!position || position > nodes.length) {
if(position !== 0) {
position = nodes.length;
}
}
if($.mobile) {
nodeWidget.element.find("a").addClass("ui-link");
}
cnodes = nodeWidget._getField("nodes");
nodeWidget._tree = self._tree;
for(i = 0; i < cnodes.length; i++) {
cnodes[i]._tree = self._tree;
}
nodeWidget._setField("owner", self);
originalLength = nodes.length;
if(!self.$nodes) {
self.$nodes = $("<ul></ul>").addClass("wijmo-wijtree-list " + self.options.wijCSS.helperReset + " wijmo-wijtree-child");
self.element.append(self.$nodes);
}
if(originalLength > 0 && originalLength !== position) {
if(nodeWidget.element.get(0) !== nodes[position].element.get(0)) {
nodeWidget.element.insertBefore(nodes[position].element);
}
} else {
self.$nodes.append(nodeWidget.element);
}
self._changeCollection(position, nodeWidget);
self._collectionChanged();
nodeWidget._initNodeClass();
};
wijtreenode.prototype.remove = /**
* The remove method removes the indicated node from this node.
* @example $("#tree").wijtree("remove", 1);
* @param {string|object} node
* which node to be removed
* 1.wijtreenode element.
* 2.the zero-based index of which node you determined to remove.
*/
function (node) {
var idx = -1, nodeWidget, self = this, nodes = this._getField("nodes");
if(node.jquery) {
idx = node.index();
} else if(typeof node === "number") {
idx = node;
}
if(idx < 0 || idx >= nodes.length) {
return;
}
nodeWidget = nodes[idx];
nodeWidget.element.detach();
self._changeCollection(idx);
self._collectionChanged();
};
wijtreenode.prototype.getNodes = /**
* The getNodes method gets an array that contains the root nodes of the current tree node.
* @example $("#tree").wijtree("getNodes");
* @return {Array}
*/
function () {
return this._getField("nodes");
};
wijtreenode.prototype._changeCollection = function (idx, nodeWidget) {
var nodes = this._getField("nodes"), ons = this.options.nodes;
if(nodeWidget) {
nodes.splice(idx, 0, nodeWidget);
ons.splice(idx, 0, nodeWidget.options);
} else {
nodes.splice(idx, 1);
ons.splice(idx, 1);
}
};
wijtreenode.prototype.sortNodes = /**
* Sorts the child nodes of the node.
*/
function () {
var nodes = this._getField("nodes");
this._sort();
$.each(nodes, function (i, childNode) {
childNode._index = i;
childNode._insertBefore(i);
});
this._refreshNodesClass();
};
wijtreenode.prototype.check = /**
* Checks or unchecks the node.
* @param {boolean} value Check or uncheck the node.
*/
function (value) {
this._setOption("checked", value);
};
wijtreenode.prototype.select = /**
* Selects or unselects the node.
* @param {boolean} value select or unselect the node.
*/
function (value) {
this._setOption("selected", value);
};
wijtreenode.prototype.getOwner = /**
* Get owner which contains the node.
*/
function () {
var owner = this._getOwner();
if(owner && owner.element.is("li")) {
return owner;
}
return null;
};
wijtreenode.prototype.expand = /**
* Expands the node.
*/
function () {
this._setOption("expanded", true);
};
wijtreenode.prototype.collapse = /**
* Collapses the node.
*/
function () {
this._setOption("expanded", false);
};
wijtreenode.prototype._insertBefore = /*region prvite Methods*/
function (i) {
var $lis = this.element.parent().children("li");
if(this.element.index() !== i) {
this.element.insertBefore($lis.eq(i));
}
};
wijtreenode.prototype._sort = function () {
var nodes = this._getField("nodes");
if(this._isSorted) {
if(!this._isDecsSort) {
nodes.sort(this._compare2NodeTextAcs);
this._isDecsSort = true;
} else {
nodes.sort(this._compare2NodeTextDesc);
this._isDecsSort = false;
}
} else {
nodes.sort(this._compare2NodeTextAcs);
this._isSorted = true;
this._isDecsSort = true;
}
};
wijtreenode.prototype._compare2NodeTextAcs = function (a, b) {
if(a !== null && b !== null) {
return a._text.localeCompare(b._text);
}
};
wijtreenode.prototype._compare2NodeTextDesc = function (a, b) {
if(a !== null && b !== null) {
return -1 * a._text.localeCompare(b._text);
}
};
wijtreenode.prototype._collectionChanged = function () {
this._hasChildren = this._getChildren();
this._initNodeClass();
//this._refreshNodesClass();
};
wijtreenode.prototype._refreshNodesClass = function () {
var nodes = this._getField("nodes"), i;
for(i = 0; i < nodes.length; i++) {
nodes[i]._initNodeClass();
}
};
wijtreenode.prototype._setChecked = function (value) {
var self = this;
if(self.options.checked === value && self._checkState !== "indeterminate") {
return;
}
self.options.checked = value;
self.$nodeBody.attr("aria-checked", value);
this._checkItem();
};
wijtreenode.prototype._isClosestDisabled = function () {
var self = this;
if(self.element.closest(".wijmo-wijtree-disabled," + ".wijmo-wijtreenode-disabled", self._tree.element).length) {
return true;
}
return false;
};
wijtreenode.prototype._setExpanded = function (value) {
var self = this, o = self.options;
if(self._expanded === value) {
return;
}
if(self._hasChildren || o.hasChildren) {
self._expandNode(value);
}
};
wijtreenode.prototype._setFocused = function (value) {
if(value) {
this.$navigateUrl.focus();
//if ($.browser.msie || $.browser.webkit) {
this._setFocusNode();
//}
} else {
this.$navigateUrl.blur();
}
};
wijtreenode.prototype._setFocusNode = function () {
if(this._tree._focusNode && $.browser.webkit) {
this._tree._focusNode.$navigateUrl.blur();
}
this._focused = true;
this._tree._focusNode = this;
this.$inner.addClass(this.options.wijCSS.stateFocus);
this._tree._trigger("nodeFocus", null, this);
};
wijtreenode.prototype._setToolTip = function (value) {
if(value.length) {
this.element.attr("title", value);
} else {
this.element.removeAttr("title");
}
};
wijtreenode.prototype._setText = function (value) {
if(this._text !== value && value.length) {
this._text = value;
this._changeText(value);
}
};
wijtreenode.prototype._setSelected = function (value) {
var self = this, o = self.options;
if(o.selected !== value) {
o.selected = value;
self.$nodeBody.attr("aria-selected", value);
self._selectNode(value);
self._setFocused(value);
}
};
wijtreenode.prototype._setCheckBoxes = function (value) {
var self = this;
if(self.$checkBox) {
self.$checkBox[value ? 'show' : 'hide']();
} else if(value) {
self.$checkBox = $("<div>");
self.$checkBox.insertBefore(self.$navigateUrl);
self.$checkBox.wijtreecheck();
}
if(self.$nodes) {
self.$nodes.children("li").each(function (idx, data) {
var nodeWidget = self._getNodeWidget($(data));
if(nodeWidget !== null) {
nodeWidget._setCheckBoxes(value);
}
});
}
};
wijtreenode.prototype._setHitArea = function (value) {
var self = this;
if(self._hasChildren)//todo: initnode class
{
if(value) {
self._initNodeClass();
if(self.$hitArea) {
self.$hitArea.show();
}
} else {
self._expanded = true;
self.options.expanded = true;
self.$nodeBody.attr("aria-expanded", true);
if(self.$nodes) {
self.$nodes.show();
}
self._initNodeClass();
if(self.$hitArea) {
self.$hitArea.hide();
}
}
}
if(self.$nodes) {
self.$nodes.children("li").each(function (idx, data) {
var nodeWidget = self._getNodeWidget($(data));
if(nodeWidget !== null) {
nodeWidget._setHitArea(value);
}
});
}
};
wijtreenode.prototype._getOwner = function () {
return this._getField("owner");
};
wijtreenode.prototype._getTree = function () {
var owner = this._getOwner();
if(owner) {
if(owner.element.is(":" + this.options.treeClass)) {
return owner;
} else {
return owner._getTree();
}
}
return null;
};
wijtreenode.prototype._getInitElement = function () {
var li = $("<li>"), self = this, ul = $("<ul>"), nodes = self._getField("nodes");
li.append(self.$navigateUrl.clone());
if(nodes.length) {
li.append(ul);
$.each(nodes, function (i, n) {
var c = n._getInitElement();
ul.append(c);
});
}
return li;
};
wijtreenode.prototype._getChildren = function () {
return (this.element.find(">ul:first>li").length > 0 && this.element.children("ul:first")) || !!(this.options.nodes && this.options.nodes.length);
};
wijtreenode.prototype._getNodeWidget = function (el) {
var node = this._getNodeByDom(el), widget;
if(node.length > 0) {
widget = node.data(node.data("widgetName"));
return widget;
}
return null;
};
wijtreenode.prototype._createNodeWidget = function ($li, options) {
if($.fn.wijtreenode) {
$li.data("owner", this);
if(!!options && $.isPlainObject(options)) {
$.extend(options, {
treeClass: this.options.treeClass
});
$li.wijtreenode(options);
} else {
$li.wijtreenode({
treeClass: this.options.treeClass
});
}
}
return $li;
};
wijtreenode.prototype._getNodeByDom = function (el) {
//Arg :Dom Element
return $(el).closest(":" + this.widgetFullName);
};
wijtreenode.prototype._getCurrentLevel = function () {
return this.element.parentsUntil(":" + this.options.treeClass).length - 1;
};
wijtreenode.prototype._getField = function (key) {
return this.element.data(key);
};
wijtreenode.prototype._setField = function (key, value) {
return this.element.data(key, value);
};
return wijtreenode;
})(wijmo.wijmoWidget);
tree.wijtreenode = wijtreenode;
var checkClass = "", triStateClass = "";
/** @ignore */
var wijtreecheck = (function (_super) {
__extends(wijtreecheck, _super);
function wijtreecheck() {
_super.apply(this, arguments);
}
wijtreecheck.prototype._initCSS = function (o) {
var css = o.wijCSS;
checkClass = css.icon + ' ' + css.iconCheck;
triStateClass = css.icon + ' ' + css.iconStop;
};
wijtreecheck.prototype._create = function () {
var self = this, o = this.options, css = o.wijCSS;
self._initCSS(o);
if(self.element.is("div")) {
self.element.addClass("wijmo-checkbox " + css.widget).attr("role", "checkbox");
self.$icon = $("<span>");
self.$icon.addClass("wijmo-checkbox-icon");
if(o.checkState === "check") {
self.$icon.addClass(checkClass);
} else if(o.checkState === "triState") {
self.$icon.addClass(triStateClass);
}
self.$body = $('<div></div>').addClass([
"wijmo-checkbox-box",
css.widget,
css.cornerAll,
css.stateDefault
].join(' ')).css({
position: "relative"
}).append(self.$icon);
self.element.append(self.$body);
self.element.bind("mouseover.wijtreecheck", function () {
if(!self.options.disabled) {
self.$body.addClass(css.stateHover);
}
}).bind("mouseout.wijtreecheck", function () {
if(!self.options.disabled) {
self.$body.removeClass(css.stateHover).not(css.stateFocus).addClass(css.stateDefault);
}
});
}
};
wijtreecheck.prototype._setOption = function (key, value) {
var self = this, css = self.options.wijCSS;
if(key === "checkState") {
if(value === "unCheck") {
self.$body.removeClass(css.stateActive);
self.$icon.removeClass(checkClass + " " + triStateClass + " " + css.stateActive);
} else if(value === "check") {
self.$body.addClass(css.stateActive);
self.$icon.removeClass(triStateClass).addClass(checkClass);
} else if(value === "triState") {
self.$body.addClass(css.stateActive);
self.$icon.removeClass(checkClass).addClass(triStateClass);
}
}
$.Widget.prototype._setOption.apply(self, arguments);
};
wijtreecheck.prototype.destory = /** The destroy method will remove the rating functionality completely and will return the element to its pre-init state. */
function () {
this.element.children().remove();
this.element.removeClass("wijmo-checkbox " + this.options.wijCSS.widget);
$.Widget.prototype.destroy.apply(this);
};
return wijtreecheck;
})(wijmo.wijmoWidget);
tree.wijtreecheck = wijtreecheck;
wijtreecheck.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, {
wijMobileCSS: {
header: "ui-header ui-bar-a",
content: "ui-body-c",
stateHover: "ui-btn-down-b",
stateActive: "ui-btn-down-b"
},
checkState: "unCheck"
});
var wijtreenode_options = (function () {
function wijtreenode_options() {
/** wijMobileCSS
* @ignore
*/
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body-c",
stateDefault: "ui-btn-up-c",
stateHover: "ui-btn-down-c",
stateActive: "ui-btn-down-b"
};
/** @ignore */
this.treeClass = "wijmo-wijtree";
/** Selector option for auto self initialization.
* This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijtreenode')";
/** @ignore */
this.accessKey = "";
/** The checked option checks the tree node checkbox when it is set to true. It will uncheck the tree node checkbox when set to false.
* @example $(".selector").wijtreenode("checked",true).
*/
this.checked = false;
/** The collapsedIconClass option sets the collapsed node icon (based on ui-icon) for the specified nodes.
* @example
* $(".selector").wijtreenode("collapsedIconClass","ui-icon-file").
*/
this.collapsedIconClass = "";
/** The expanded option will expand the tree node if set to "true." It will collapse the tree node if set to "false.".
* @example $(".selector").wijtreenode("expanded",true).
*/
this.expanded = false;
/** The expandedIconClass option sets the expanded node icon (based on ui-icon) for the specified nodes.
* @example $(".selector").wijtreenode("expandedIconClass","iconClass").
*/
this.expandedIconClass = "";
/** The itemIconClass option sets the node icon (based on ui-icon). It will be displayed on both expanded and collapsed nodes when the expandedIconClass and collapsedIconClass options are not specified.
* @example $(".selector").wijtreenode("itemIconClass","iconClass").
*/
this.itemIconClass = "";
/** The navigateUrl option sets the node's navigate url link.
* @example $(".selector").wijtreenode("navigateUrl","http://google.com").
*/
this.navigateUrl = "";
/** The selected option selects the specified node when set to true, otherwise it unselects the node.
* @example $(".selector").wijtreenode("selected",true).
*/
this.selected = false;
/** This option sets the node's text.
* @example $(".selector").wijtreenode("text","Hello World!").
*/
this.text = "";
/** The toolTip option sets the node's tooltip.
* @example $(".selector").wijtreenode("toolTip","Node 1 toolTip").
*/
this.toolTip = "";
/** The hasChildren option determines whether the specified node has child nodes. It's always used when you're custom adding child nodes, such as in an async load.
* @example $(".selector").wijtreenode("hasChildren",true).
*/
this.hasChildren = false;
/** The params option sets the parameter needed to pass when the user is custom loading child nodes.
* @example $(".selector").wijtreenode("ajaxParams",{}).
*/
this.params = {
};
/** Determines the child nodes of this nodes.
*/
this.nodes = null;
}
return wijtreenode_options;
})();
var wijtree_options = (function () {
function wijtree_options() {
/**
* wijMobileCSS
* @ignore
*/
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body-c",
stateDefault: "ui-btn-up-c",
stateHover: "ui-btn-down-b",
stateActive: "ui-btn-down-c"
};
/** When the allowDrag option is set to true, the tree nodes can be dragged.
*/
this.allowDrag = false;
/** When allowDrop is set to true, one tree node can be dropped within another tree node.
*/
this.allowDrop = false;
/** The allowEdit option allows a user to edit the tree nodes at run time.
*/
this.allowEdit = false;
/** The allowSorting option allows the tree nodes to be sorted at run time when the user presses the "s" key.
*/
this.allowSorting = true;
/** The allowTriState option allows the tree nodes to exhibit triState behavior. This lets the node checkboxes be checked, unchecked, or indeterminate. This option must be used with the showCheckBoxes option.
*/
this.allowTriState = true;
/** The autoCheckNodes option allows the sub-nodes to be checked when the parent nodes are checked. To use this option, showCheckboxes must be set to "true."
*/
this.autoCheckNodes = true;
/** If this option is set to true,
* the expanded node will be collapsed if another node is expanded.
*/
this.autoCollapse = false;
/** If set to true, the select, click,
* and check operations are disabled too.
*/
this.disabled = false;
/** The expandCollapseHoverUsed option allows the tree to expand or collapse when the mouse hovers over the expand/collapse button.
*/
this.expandCollapseHoverUsed = false;
/** The showCheckBoxes option allows the node Check Box to be shown on the tree nodes.
*/
this.showCheckBoxes = false;
/** The showExpandCollapse option determines if the tree is displayed in an expanded or collapsed state. If set to "false," then the wijtree widget will be displayed in the expanded state.
*/
this.showExpandCollapse = true;
/** The expandAnimation option determines the animation effect, easing, and duration for showing child nodes when the parent node is expanded.
* @type {object}
*/
this.expandAnimation = {
effect: "blind",
easing: "linear",
duration: 200
};
/** The expandDelay option controls the length of time in milliseconds to delay before the node is expanded.
*/
this.expandDelay = 0;
/** The collapseAnimation option determines the animation effect, easing, and duration for hiding child nodes when the parent node is collapsed.
*/
this.collapseAnimation = {
effect: "blind",
easing: "linear",
duration: 200
};
/** This option controls the length of time in milliseconds to delay before the node collapses.
*/
this.collapseDelay = 0;
/** Customize the jquery-ui-draggable plugin of wijtree.
*/
this.draggable = null;
/** Customize the jquery-ui-droppable plugin of wijtree.
*/
this.droppable = null;
/*
* Customizes the helper element to be used to display the position that
* the node will be inserted to.
* If a function is specified, it must return a DOMElement.
* @type {String|Function}
*/
this.dropVisual = null;
/** Set the child nodes object array as the datasource of wijtree.
* @type {Array}
* @example
* // Supply a function as an option.
* $(".selector").wijtree("option","nodes",
* [{ text:"node1", navigateUrl:"#" }]);
*/
this.nodes = null;
/** The nodeBlur event fired when the node loses focus.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.nodeBlur = null;
/** The nodeFocus event fired when the node is focused.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.nodeFocus = null;
/** The nodeClick event fires when a tree node is clicked.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.nodeClick = null;
/** The nodeCheckChanged event fires when a node is checked.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.nodeCheckChanged = null;
/** The nodeCollapsed event fires when a tree node is collapsed.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.nodeCollapsed = null;
/** The nodeExpanded event handler.
* A function called when a node is expanded.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.nodeExpanded = null;
/** The nodeDragging event handler.A function called
* when the node is moved during a drag-and-drop operation.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.nodeDragging = null;
/** The nodeDragStarted event fires when a user starts to drag a node.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.nodeDragStarted = null;
/** The nodeBeforeDropped event handler is called before a draggable node is dropped in another position. If the event handler returns false, the drop action will be prevented.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.nodeBeforeDropped = null;
/** The nodeDropped event is called when an acceptable draggable node is dropped over to another position.
* @event
* @dataKey {jQuery} sourceParent The source parent of current draggable node before it be dragged, a jQuery object.
* @dataKey {number} sIndex The Index of dragged node in source parent.
* @dataKey {jQuery} targetParent The target parent of current draggable node after it be dropped, a jQuery object.
* @dataKey {number} tIndex The Index of dragged node in target parent.
* @dataKey {jQuery} draggable The current draggable node.
* @dataKey {object} offset The current absolute position of the draggable helper.
* @dataKey {object} position The current position of the draggable helper.
*/
this.nodeDropped = null;
/** The nodeMouseOver event fires when a user places the mouse pointer over a node.
* @event
* @param {object} event jQuery.Event object.
* @param {object} data The node widget that relates to this event.
*/
this.nodeMouseOver = null;
/** The nodeMouseOut event fires when the user moves the mouse pointer off of a node.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.nodeMouseOut = null;
/** The nodeTextChanged event fires when the text of a node changes.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.nodeTextChanged = null;
/** The selectedNodeChanged event fires when the selected node changes.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.selectedNodeChanged = null;
/** The nodeExpanding event fires before a tree node is expanded.
* This event can be canceled, if return false
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.nodeExpanding = null;
/** The nodeCollapsing event fires before a node collapses.
* This event can be canceled, if return false
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.nodeCollapsing = null;
}
return wijtree_options;
})();
wijtreenode.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijtreenode_options());
wijtree.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijtree_options());
$.wijmo.registerWidget("wijtree", wijtree.prototype);
$.wijmo.registerWidget("wijtreenode", wijtreenode.prototype);
$.wijmo.registerWidget("wijtreecheck", wijtreecheck.prototype);
})(wijmo.tree || (wijmo.tree = {}));
var tree = wijmo.tree;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/*globals jQuery, window, XMLHttpRequest,SWFUpload,swfobject*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
var wijmo;
(function (wijmo) {
(function (upload) {
"use strict";
var $ = jQuery, widgetName = "wijupload";
var uploadClass = "wijmo-wijupload", uploadFileRowClass = "wijmo-wijupload-fileRow", isUploadFileRow = "." + uploadFileRowClass, uploadFilesListClass = "wijmo-wijupload-filesList", uploadCommandRowClass = "wijmo-wijupload-commandRow", uploadUploadAllClass = "wijmo-wijupload-uploadAll", uploadCancelAllClass = "wijmo-wijupload-cancelAll", uploadButtonContainer = "wijmo-wijupload-buttonContainer", uploadUploadClass = "wijmo-wijupload-upload", isUploadUpload = "." + uploadUploadClass, uploadCancelClass = "wijmo-wijupload-cancel", isUploadCancel = "." + uploadCancelClass, uploadFileClass = "wijmo-wijupload-file", uploadProgressClass = "wijmo-wijupload-progress", uploadLoadingClass = "wijmo-wijupload-loading", uiContentClass = "ui-widget-content", uiCornerClass = "ui-corner-all", uiHighlight = "ui-state-highlight", wijuploadXhr, wijuploadFrm, _getFileName = function (fileName) {
// Trim path on IE.
if(fileName.indexOf("\\") > -1) {
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
}
return fileName;
}, _getFileNameByInput = function (fileInput) {
var files = fileInput.files, name = "";
if(files) {
$.each(files, function (i, n) {
name += _getFileName(n.name) + "; ";
});
if(name.length) {
name = name.substring(0, name.lastIndexOf(";"));
}
} else {
name = _getFileName(fileInput.value);
}
return name;
}, _getFileSize = function (file) {
var files = file.files, size = 0;
if(files && files.length > 0) {
$.each(files, function (i, n) {
if(n.size) {
size += n.size;
}
});
}
return size;
};
wijuploadXhr = function (uploaderId, fileRow, action) {
var uploader, inputFile = $("input", fileRow), _cancel = function (xhr) {
if(xhr) {
xhr.abort();
xhr = null;
}
}, _destroy = function (xhr) {
if(xhr) {
xhr = null;
}
}, Uploader = function () {
var self = this, files = inputFile.get(0).files, xhrs = [], idx = 0, uploadedSize = 0, createXHR = function (name, action) {
var xhttpr = new XMLHttpRequest();
xhttpr.open("POST", action, true);
xhttpr.setRequestHeader("Wijmo-RequestType", "XMLHttpRequest");
xhttpr.setRequestHeader("Cache-Control", "no-cache");
xhttpr.setRequestHeader("Wijmo-FileName", name);
xhttpr.setRequestHeader("Content-Type", "application/octet-stream");
xhttpr.upload.onprogress = function (e) {
if(e.lengthComputable) {
var obj;
if($.isFunction(self.onProgress)) {
obj = {
supportProgress: true,
loaded: uploadedSize + e.loaded,
total: _getFileSize(inputFile[0]),
fileName: _getFileName(self.currentFile.name),
fileNameList: _getFileNameByInput(inputFile[0]).split("; ")
};
self.onProgress(obj);
}
}
};
xhttpr.onreadystatechange = function (e) {
if(this.readyState === 4) {
var response = this.responseText, obj;
uploadedSize += files[idx].size;
idx++;
if(files.length > idx) {
_doAjax(files[idx]);
} else if($.isFunction(self.onComplete)) {
obj = {
e: e,
response: response,
supportProgress: true
};
self.onComplete(obj);
}
}
};
xhrs.push(xhttpr);
return xhttpr;
}, _doAjax = function (file) {
var name = _getFileName(file.name), xhr = createXHR(name, action);
self.handleRequest(xhr, file);
self.currentFile = file;
xhr.send(file);
};
self.fileRow = fileRow;
self.inputFile = inputFile;
self.upload = function () {
_doAjax(files[idx]);
};
self.cancel = function () {
$.each(xhrs, function (i, xhr) {
_cancel(xhr);
});
if($.isFunction(self.onCancel)) {
self.onCancel();
}
};
self.destroy = function () {
$.each(xhrs, function (i, xhr) {
_destroy(xhr);
});
};
self.updateAction = function (act) {
action = act;
};
self.handleRequest = null;
self.onCancel = null;
self.onComplete = null;
self.onProgress = null;
};
uploader = new Uploader();
return uploader;
};
wijuploadFrm = function (uploaderId, fileRow, action) {
var uploader, inputFile = $("input", fileRow), inputFileId = inputFile.attr("id"), formId = "wijUploadForm_" + uploaderId, form = $("#" + formId), iframeId = "wijUploadIfm_" + inputFileId, isFirstLoad = true, iframe = $("<iframe id=\"" + iframeId + "\" name=\"" + iframeId + "\">"), _upload = // ifm = $("<iframe src=\"javascript:false;\" id=\"" +
// id + "\" name=\"" + id + "\">");
//"javascript".concat(":false;")
//src="javascript:false;" removes ie6 prompt on https
function (ifm, iptFile) {
form.empty();
form.attr("target", ifm.attr("name"));
if(iptFile) {
iptFile.parent().append(iptFile.clone());
form.append(iptFile);
}
form.submit();
}, _cancel = function (ifm) {
// to cancel request set src to something else
// we use src="javascript:false;" because it doesn't
// trigger ie6 prompt on https
ifm.attr("src", "javascript".concat(":false;"));
}, _destroy = function (ifm, removeForm) {
if(removeForm && form) {
form.remove();
form = null;
}
if(ifm) {
ifm.remove();
ifm = null;
}
}, Uploader;
if(form.length === 0) {
form = $("<form method=\"post\" enctype=\"multipart/form-data\"></form>");
form.attr("action", action).attr("id", formId).attr("name", formId).appendTo("body");
}
iframe.css("position", "absolute").css("top", "-1000px").css("left", "-1000px");
iframe.appendTo("body");
Uploader = function () {
var self = this;
self.fileRow = fileRow;
self.iframe = iframe;
self.inputFile = inputFile;
self.upload = function () {
var obj;
_upload(iframe, inputFile);
if($.isFunction(self.onProgress)) {
obj = {
supportProgress: false,
loaded: 1,
total: 1
};
self.onProgress(obj);
}
};
self.doPost = function () {
_upload(iframe);
};
self.cancel = function () {
_cancel(iframe);
if($.isFunction(self.onCancel)) {
self.onCancel();
}
};
self.updateAction = function (act) {
action = act;
form.attr("action", act);
};
self.destroy = function (removeForm) {
_destroy(iframe, removeForm);
};
self.onCancel = null;
self.onComplete = null;
self.onProgress = null;
iframe.bind("load", function (e) {
if(!$.browser.safari) {
if(isFirstLoad && !self.autoSubmit) {
isFirstLoad = false;
return;
}
}
if(iframe.attr("src") === "javascript".concat(":false;")) {
return;
}
var target = e.target, response, doc, obj;
try {
doc = target.contentDocument ? target.contentDocument : window.frames[0].document;
//if (doc.readyState && doc.readyState !== "complete") {
// return;
//}
if(doc.XMLDocument) {
response = doc.XMLDocument;
} else if(doc.body) {
response = doc.body.innerHTML;
} else {
response = doc;
}
if($.isFunction(self.onComplete)) {
obj = {
e: e,
response: response,
supportProgress: false
};
self.onComplete(obj);
}
} catch (ex) {
response = "";
}finally {
//iframe.unbind("load");
}
});
};
uploader = new Uploader();
return uploader;
};
/** @widget */
var wijupload = (function (_super) {
__extends(wijupload, _super);
function wijupload() {
_super.apply(this, arguments);
}
wijupload.prototype._swfAppendAddtionalData = function (swfupload) {
swfupload.queueData = {
files: {
},
filesSelected: // The files in the queue
0,
filesQueued: // The number of files selected in the last select operation
0,
filesReplaced: // The number of files added to the queue in the last select operation
0,
filesCancelled: // The number of files replaced in the last select operation
0,
filesErrored: // The number of files that were cancelled instead of replaced
0,
uploadsSuccessful: // The number of files that caused error in the last select operation
0,
uploadsErrored: // The number of files that were successfully uploaded
0,
averageSpeed: // The number of files that returned errors during upload
0,
queueLength: // The average speed of the uploads in KB
0,
queueSize: // The number of files in the queue
0,
uploadSize: // The size in bytes of the entire queue
0,
queueBytesUploaded: // The size in bytes of the upload queue
0,
uploadQueue: // The size in bytes that have been uploaded for the current upload queue
[],
errorMsg: // The files currently to be uploaded
''
};
//Some files were not added to the queue:
swfupload.widget = this;
};
wijupload.prototype._swfGetHandlers = function () {
var widget = this, el = widget.element;
return {
onSelect: function (file) {
var swfupload = this;
var queuedFile = {
};
if(widget._trigger("change", null, file) === false) {
return false;
}
widget._createFileRow(file);
this.queueData.queueSize += file.size;
this.queueData.files[file.id] = file;
},
onSelectError: function (file, errorCode) {
if(errorCode == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
alert("File size exceeds the limitation!");
} else if(errorCode == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
alert("Too many files!");
}
},
onDialogOpen: function () {
//prepare
this.queueData.filesReplaced = 0;
this.queueData.filesCancelled = 0;
},
onDialogClose: function (filesSelected, filesQueued, queueLength) {
// start upload
var settings = this.settings;
// Update the queue information
this.queueData.filesErrored = filesSelected - filesQueued;
this.queueData.filesSelected = filesSelected;
this.queueData.filesQueued = filesQueued - this.queueData.filesCancelled;
this.queueData.queueLength = queueLength;
widget.isStartUpload = false;
// Call the user-defined event handler
if(widget.options.autoSubmit) {
widget.uploadAll = true;
widget._swfUploadFile();
}
if(settings.onDialogClose) {
settings.onDialogClose.call(this, this.queueData);
}
},
onUploadStart: function (file) {
this.bytesLoaded = 0;
if(this.queueData.uploadQueue.length == 0) {
this.queueData.uploadSize = file.size;
}
if(!widget.isStartUpload && widget.uploadAll) {
if(widget._trigger("totalUpload", null, null) === false) {
this.cancelUpload();
return false;
}
widget.isStartUpload = true;
}
if(widget._trigger("upload", null, file) === false) {
this.cancelUpload(file.id);
return false;
}
},
onUploadProgress: function (file, fileBytesLoaded, fileTotalBytes) {
var fileRow = $("#" + file.id, el), loaded, total, percentage = Math.round(fileBytesLoaded / fileTotalBytes * 100), progressSpan = $("." + uploadProgressClass, fileRow), data = {
sender: file.name,
loaded: fileBytesLoaded,
total: fileTotalBytes
}, queue = this.queueData;
progressSpan.html(percentage + "%");
widget._trigger("progress", null, data);
loaded = queue.queueBytesUploaded + fileBytesLoaded;
total = queue.queueSize;
widget._updateSwfProgress(loaded, total);
widget._trigger("totalProgress", null, {
loaded: loaded,
total: total
});
},
onUploadError: function (file, errorCode, errorMsg) {
// Load the swfupload settings
var settings = this.settings, fileRow = $("#" + file.id, el), progressSpan = $("." + uploadProgressClass, fileRow);
// Set the error string
var errorString = 'Error';
switch(errorCode) {
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
errorString = 'HTTP Error (' + errorMsg + ')';
break;
case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
errorString = 'Missing Upload URL';
break;
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
errorString = 'IO Error';
break;
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
errorString = 'Security Error';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
alert('The upload limit has been reached (' + errorMsg + ').');
errorString = 'Exceeds Upload Limit';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
errorString = 'Failed';
break;
case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
break;
case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
errorString = 'Validation Error';
break;
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
errorString = 'Cancelled';
this.queueData.queueSize -= file.size;
this.queueData.queueLength -= 1;
if(file.status == SWFUpload.FILE_STATUS.IN_PROGRESS || $.inArray(file.id, this.queueData.uploadQueue) >= 0) {
this.queueData.uploadSize -= file.size;
}
// Trigger the onCancel event
if(settings.onCancel) {
settings.onCancel.call(this, file);
}
delete this.queueData.files[file.id];
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
errorString = 'Stopped';
break;
}
progressSpan.text(errorString);
var stats = this.getStats();
this.queueData.uploadsErrored = stats.upload_errors;
},
onUploadSuccess: function (file, data, response) {
var stats = this.getStats();
this.queueData.uploadsSuccessful = stats.successful_uploads;
this.queueData.queueBytesUploaded += file.size;
this.queueData.response = response;
var fileRow = $("#" + file.id, el), self = this;
self.queueData.queueLength -= 1;
fileRow.fadeOut(1500, function () {
fileRow.remove();
if(widget.options.showUploadedFiles) {
widget._createUploadedFiles(file.name);
}
if(!self.queueData.queueLength) {
widget.commandRow.hide();
}
});
widget._trigger("complete", null, {
response: response
});
},
onUploadComplete: function (file, data, response) {
var self = this;
if(!self.queueData.queueLength && widget.uploadAll) {
widget._cleanSwfProgress();
widget._trigger("totalComplete", null, self.queueData);
}
if(widget.uploadAll) {
widget._swfUploadFile();
}
}
};
};
wijupload.prototype._cleanSwfProgress = function () {
};
wijupload.prototype._updateSwfProgress = function (loaded, total) {
};
wijupload.prototype._initSwfUploadOptions = function (w, h) {
var self = this, el = self.element, settings, handlers = self._swfGetHandlers(), o = self.options, swfOptions = self.options.swfUploadOptions, id = el.attr("id"), inputId = id + "_SWFUpload";
$("<input type='file' id='" + inputId + "'>").appendTo(el);
//uploadify
settings = $.extend({
id: inputId,
swf: 'SWFUpload.swf',
auto: // Options
false,
buttonClass: '',
buttonCursor: 'hand',
buttonImage: null,
checkExisting: // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the button
false,
debug: // The path to a server-side script that checks for existing files on the server
false,
fileObjName: // Turn on swfUpload debugging mode
'Filedata',
fileSizeLimit: // The name of the file object to use in your server-side script
o.maximumFileSize ? o.maximumFileSize : 0,
fileTypeDesc: // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit)
'All Files',
fileTypeExts: // The description for file types in the browse dialog
o.accept ? o.accept : '*.*',
height: // Allowed extensions in the browse dialog (server-side validation should also be used)
h,
itemTemplate: // The height of the browse button
false,
method: // The template for the file item in the queue
'post',
multi: // The method to use when sending files to the server-side upload script
o.multiple,
formData: // Allow multiple file selection in the browse dialog
{
},
preventCaching: // An object with additional data to send to the server-side upload script with every file upload
true,
progressData: // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters)
'percentage',
queueID: // ('percentage' or 'speed') Data to show in the queue item during a file upload
false,
queueSizeLimit: // The ID of the DOM object to use as a file queue (without the #)
o.maximumFiles ? o.maximumFiles : 999,
removeCompleted: // The maximum number of files that can be in the queue at one time
true,
removeTimeout: // Remove queue items from the queue when they are done uploading
3,
requeueErrors: // The delay in seconds before removing a queue item if removeCompleted is set to true
false,
successTimeout: // Keep errored files in the queue and keep trying to upload them
30,
uploadLimit: // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading
0,
width: // The maximum number of files you can upload
w,
uploader: // The width of the browse button
o.action,
overrideEvents: // Events
[]
}, // (Array) A list of default event handlers to skip
swfOptions);
return {
assume_success_timeout: settings.successTimeout,
button_placeholder_id: settings.id,
button_width: settings.width,
button_height: settings.height,
button_text: null,
button_text_style: null,
button_text_top_padding: 0,
button_text_left_padding: 0,
button_action: (o.multiple ? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE),
button_disabled: false,
button_cursor: (settings.buttonCursor == 'arrow' ? SWFUpload.CURSOR.ARROW : SWFUpload.CURSOR.HAND),
button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
debug: settings.debug,
requeue_on_error: settings.requeueErrors,
file_post_name: settings.fileObjName,
file_size_limit: settings.fileSizeLimit,
file_types: settings.fileTypeExts,
file_types_description: settings.fileTypeDesc,
file_queue_limit: settings.queueSizeLimit,
file_upload_limit: settings.uploadLimit,
flash_url: settings.swf,
prevent_swf_caching: settings.preventCaching,
post_params: settings.formData,
upload_url: settings.uploader,
use_query_string: (settings.method == 'get'),
file_dialog_complete_handler: // Event Handlers
handlers.onDialogClose,
file_dialog_start_handler: handlers.onDialogOpen,
file_queued_handler: handlers.onSelect,
file_queue_error_handler: handlers.onSelectError,
swfupload_loaded_handler: settings.onSWFReady,
upload_complete_handler: handlers.onUploadComplete,
upload_error_handler: handlers.onUploadError,
upload_progress_handler: handlers.onUploadProgress,
upload_start_handler: handlers.onUploadStart,
upload_success_handler: handlers.onUploadSuccess
};
};
wijupload.prototype._createSWFUpload = function () {
var self = this, el = self.element, btn = self.addBtn, swfOptions, settings = self.options.swfUploadOptions, swfupload, w = btn.width(), h = btn.height();
var playerVersion = swfobject.getFlashPlayerVersion();
var flashInstalled = (playerVersion.major >= 9);
if(flashInstalled) {
swfOptions = self._initSwfUploadOptions(w, h);
swfupload = new SWFUpload(swfOptions);
// Add the SWFUpload object to the elements data object
self.swfupload = swfupload;
$('#' + swfupload.movieName).css({
'position': 'absolute',
'z-index': 100,
'top': 0,
'left': 0,
'width': w,
'height': h
});
self._swfAppendAddtionalData(swfupload);
} else {
alert("Please install flash player.");
if(settings && settings.onFallback) {
settings.onFallback.call();
}
}
};
wijupload.prototype._create = function () {
var self = this, o = self.options, id = new Date().getTime(), useXhr = self.supportXhr();
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
self.filesLen = 0;
self.totalUploadFiles = 0;
self.useXhr = useXhr;
self.id = id;
self._createContainers();
self._createUploadButton();
if((o.enableSWFUploadOnIE && $.browser.msie) || o.enableSWFUpload) {
self._createSWFUpload();
} else {
self._createFileInput();
}
self._bindEvents();
//Add for support disabled option at 2011/7/8
if(o.disabled) {
self.disable();
}
//end for disabled option
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
self._applyInputPosition();
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
}, "wijupload");
}
};
wijupload.prototype._setOption = function (key, value) {
var self = this;
$.Widget.prototype._setOption.apply(this, arguments);
//Add for support disabled option at 2011/7/8
if(key === "disabled") {
self._handleDisabledOption(value, self.upload);
} else //end for disabled option
if(key === "accept") {
if(self.input) {
self.input.attr("accept", value);
}
}
};
wijupload.prototype._handleDisabledOption = function (disabled, ele) {
var self = this;
if(disabled) {
if(!self.disabledDiv) {
self.disabledDiv = self._createDisabledDiv(ele);
}
self.disabledDiv.appendTo("body");
} else {
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
}
};
wijupload.prototype._createDisabledDiv = function (outerEle) {
var self = this, div, ele = //Change your outerelement here
outerEle ? outerEle : self.upload, eleOffset = ele.offset(), disabledWidth = ele.outerWidth(), disabledHeight = ele.outerHeight();
div = $("<div></div>").addClass("ui-disabled").css({
"z-index": "99999",
position: "absolute",
width: disabledWidth,
height: disabledHeight,
left: eleOffset.left,
top: eleOffset.top
});
if($.browser.msie) {
div.css("background-color", "white");
if(parseInt($.browser.version) >= 9) {
div.css("opacity", "0.1");
}
}
return div;
};
wijupload.prototype.destroy = /**
* Removes the wijupload functionality completely.This will return the element back to its pre - init state.
* @example $(" selector ").wijupload("destroy");
*/
function () {
var self = this;
self.upload.removeClass(uploadClass);
self.upload.undelegate(self.widgetName).undelegate("." + self.widgetName);
self.input.remove();
self.addBtn.remove();
self.filesList.remove();
self.commandRow.remove();
if(self.isCreateByInput === true) {
self.element.css({
display: ""
}).unwrap();
}
if(self.uploaders) {
$.each(self.uploaders, function (idx, uploader) {
if(uploader.destroy) {
uploader.destroy(true);
}
uploader = null;
});
self.uploaders = null;
}
//Add for support disabled option at 2011/7/8
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
//end for disabled option
};
wijupload.prototype.widget = /**
* Returns the.wijmo - wijupload element.
* @example $(" selector ").wijupload("widget");
*/
function () {
return this.upload;
};
wijupload.prototype.supportXhr = /** @ignore */
function () {
var useXhr = false;
if(typeof (new XMLHttpRequest().upload) === "undefined") {
useXhr = false;
} else {
useXhr = true;
}
return useXhr;
};
wijupload.prototype._createContainers = function () {
var self = this, filesList, commandRow, el = self.element;
if(el.is(":input") && el.attr("type") === "file") {
self.isCreateByInput = true;
self.maxDisplay = (el.attr("multiple") || self.options.multiple) ? 0 : 1;
self.upload = el.css({
display: "none"
}).wrap("<div>").parent();
} else if(self.element.is("div")) {
self.maxDisplay = self.options.multiple ? 0 : 1;
self.upload = el;
} else {
throw 'The initial markup must be "DIV", "INPUT[type=file]"';
}
self.upload.addClass(uploadClass);
filesList = $("<ul>").addClass(uploadFilesListClass).appendTo(self.upload);
commandRow = $("<div>").addClass(uploadCommandRowClass).appendTo(self.upload);
self.filesList = filesList;
commandRow.hide();
self.commandRow = commandRow;
self._createCommandRow(commandRow);
};
wijupload.prototype._createCommandRow = function (commandRow) {
var self = this, uploadAllBtn = $("<a>").attr("href", "#").text("uploadAll").addClass(uploadUploadAllClass).button({
icons: {
primary: "ui-icon-circle-arrow-n"
},
label: self._getLocalization("uploadAll", "Upload All")
}), cancelAllBtn = $("<a>").attr("href", "#").text("cancelAll").addClass(uploadCancelAllClass).button({
icons: {
primary: "ui-icon-cancel"
},
label: self._getLocalization("cancelAll", "Cancel All")
});
commandRow.append(uploadAllBtn).append(cancelAllBtn);
};
wijupload.prototype._getLocalization = function (key, defaultVal) {
var lo = this.options.localization;
return (lo && lo[key]) || defaultVal;
};
wijupload.prototype._createUploadButton = function () {
var self = this, addBtn = $("<a>").attr("href", "#").button({
label: self._getLocalization("uploadFiles", "Upload files")
});
addBtn.mousemove(function (e) {
var disabled = addBtn.data("uiButton").options.disabled;
if(self.input) {
var pageX = e.pageX, pageY = e.pageY;
if(!disabled) {
self.input.offset({
left: pageX + 10 - self.input.width(),
top: pageY + 10 - self.input.height()
});
}
}
});
self.addBtn = addBtn;
self.upload.prepend(addBtn);
};
wijupload.prototype._applyInputPosition = function () {
var self = this, addBtn = self.addBtn, addBtnOffset = addBtn.offset(), fileInput = self.cuurentInput;
fileInput.offset({
left: addBtnOffset.left + addBtn.width() - fileInput.width(),
top: addBtnOffset.top
}).height(addBtn.height());
};
wijupload.prototype._createFileInput = function () {
var self = this, addBtn = self.addBtn, addBtnOffset = addBtn.offset(), accept = self.element.attr("accept") || self.options.accept, id = "wijUpload_" + self.id + "_input" + self.filesLen, fileInput = $("<input>").attr("type", "file").prependTo(self.upload), maxFiles = self.options.maximumFiles || self.maxDisplay;
if(maxFiles !== 1 && self.maxDisplay === 0) {
fileInput.attr("multiple", "multiple");
}
if(accept) {
fileInput.attr("accept", accept);
}
self.cuurentInput = fileInput;
self.filesLen++;
fileInput.attr("id", id).attr("name", id).css("position", "absolute").offset({
left: addBtnOffset.left + addBtn.width() - fileInput.width(),
top: addBtnOffset.top
}).css("z-index", "9999").css("opacity", 0).height(addBtn.height()).css("cursor", "pointer");
self.input = fileInput;
fileInput.bind("change", function (e) {
var fileRow, uploadBtn;
if(self._trigger("change", e, $(this)) === false) {
return false;
}
self._createFileInput();
fileRow = self._createFileRow($(this));
self._setAddBtnState();
if(self.options.autoSubmit) {
uploadBtn = $(isUploadUpload, fileRow);
if(uploadBtn) {
uploadBtn.click();
}
}
fileInput.unbind("change");
});
self.uploadAll = false;
};
wijupload.prototype._createUploadedFiles = function (name) {
};
wijupload.prototype._setAddBtnState = function () {
var self = this, maxFiles = self.options.maximumFiles || self.maxDisplay, addBtn = self.addBtn, files;
if(!maxFiles) {
return;
}
if(!addBtn) {
return;
}
if(!self.maskDiv) {
self.maskDiv = $("<div></div>").css("position", "absolute").css(//.css("background-color", "red")
"z-index", "9999").width(addBtn.outerWidth()).height(addBtn.outerHeight()).appendTo(self.upload).offset(addBtn.offset());
}
files = $("li", self.filesList);
if(files.length >= maxFiles) {
addBtn.button({
disabled: true
});
self.maskDiv.show();
if(self.input) {
self.input.css("left", "-1000px");
}
} else {
addBtn.button({
disabled: false
});
self.maskDiv.hide();
}
};
wijupload.prototype._createFileRow = function (uploadFile) {
var self = this, o = self.options, fileRow = $("<li>"), fileName = '', file, progress, fileRows, buttonContainer = $("<span>").addClass(uploadButtonContainer), uploadBtn = $("<a>").attr("href", "#").text("upload").addClass(uploadUploadClass).button({
text: false,
icons: {
primary: "ui-icon-circle-arrow-n"
},
label: self._getLocalization("upload", "upload")
}), cancelBtn = $("<a>").attr("href", "#").text("cancel").addClass(uploadCancelClass).button({
text: false,
icons: {
primary: "ui-icon-cancel"
},
label: self._getLocalization("cancel", "cancel")
});
fileRow.addClass(uploadFileRowClass).addClass(uiContentClass).addClass(uiCornerClass);
if((o.enableSWFUploadOnIE && $.browser.msie) || o.enableSWFUpload) {
fileName = uploadFile.name;
fileRow.attr("id", uploadFile.id).data("file", uploadFile);
} else {
fileRow.append(uploadFile);
uploadFile.hide();
fileName = _getFileNameByInput(uploadFile[0]);
}
file = $("<span>" + fileName + "</span>").addClass(uploadFileClass).addClass(uiHighlight).addClass(uiCornerClass);
fileRow.append(file);
fileRow.append(buttonContainer);
progress = $("<span />").addClass(uploadProgressClass);
buttonContainer.append(progress);
buttonContainer.append(uploadBtn).append(cancelBtn);
fileRow.appendTo(self.filesList);
fileRows = $(isUploadFileRow, self.upload);
if(fileRows.length) {
self.commandRow.show();
if((!o.enableSWFUploadOnIE || !$.browser.msie) && !o.enableSWFUpload) {
self._createUploader(fileRow);
}
self._resetProgressAll();
}
return fileRow;
};
wijupload.prototype._createUploader = function (fileRow) {
var self = this, inputFile = $("input", fileRow), action = self.options.action, hr = self.options.handleRequest, uploader;
if(self.useXhr) {
uploader = wijuploadXhr(self.id, fileRow, action);
uploader.handleRequest = function (xhr, file) {
if($.isFunction(hr)) {
hr.call(self, xhr, file);
}
};
} else {
uploader = wijuploadFrm(self.id, fileRow, action);
}
uploader.onCancel = function () {
var t = this;
self._trigger("cancel", null, t.inputFile);
//self.totalUploadFiles--;
if(self.totalUploadFiles === 0 && self.uploadAll) {
self._trigger("totalComplete");
}
};
if(self._wijUpload()) {
uploader.onProgress = function (obj) {
var progressSpan = $("." + uploadProgressClass, this.fileRow), data = {
sender: obj.fileName,
loaded: obj.loaded,
total: obj.total,
fileNameList: undefined
}, id = this.inputFile.attr("id");
if(obj.supportProgress) {
progressSpan.html(Math.round(1000 * obj.loaded / obj.total) / 10 + "%");
if(obj.fileNameList) {
data.fileNameList = obj.fileNameList;
}
self._trigger("progress", null, data);
self._progressTotal(id, obj.loaded);
} else {
progressSpan.addClass(uploadLoadingClass);
}
};
uploader.onComplete = function (obj) {
var t = this, id = t.inputFile.attr("id"), uploader = self.uploaders[id], fileSize = //fileName = _getFileName(t.inputFile.val()),
_getFileSize(t.inputFile[0]), progressSpan = $("." + uploadProgressClass, t.fileRow);
//xhr = obj.e.currentTarget;
// if (xhr.status != 200) {
// throw xhr;
// }
self._trigger("complete", obj.e, t.inputFile);
progressSpan.removeClass(uploadLoadingClass);
progressSpan.html("100%");
self._removeFileRow(t.fileRow, uploader, true);
self._progressTotal(id, fileSize);
self.totalUploadFiles--;
if(self.totalUploadFiles === 0 && (self.uploadAll || self.options.autoSubmit)) {
self._trigger("totalComplete", obj.e, obj);
}
};
}
if(typeof (self.uploaders) === "undefined") {
self.uploaders = {
};
}
self.uploaders[inputFile.attr("id")] = uploader;
};
wijupload.prototype._progressTotal = function (fileName, loadedSize) {
var self = this, progressAll = self.progressAll, loaded, total;
if(!self.uploadAll) {
return;
}
if(progressAll && progressAll.loadedSize) {
progressAll.loadedSize[fileName] = loadedSize;
loaded = self._getLoadedSize(progressAll.loadedSize);
total = progressAll.totalSize;
}
self._trigger("totalProgress", null, {
loaded: loaded,
total: total
});
};
wijupload.prototype._getLoadedSize = function (loadedSize) {
var loaded = 0;
$.each(loadedSize, function (key, value) {
loaded += value;
});
return loaded;
};
wijupload.prototype._getTotalSize = function () {
var self = this, total = 0;
if(self.uploaders) {
$.each(self.uploaders, function (key, uploader) {
total += _getFileSize(uploader.inputFile[0]);
});
}
return total;
};
wijupload.prototype._resetProgressAll = function () {
this.progressAll = {
totalSize: 0,
loadedSize: {
}
};
};
wijupload.prototype._wijUpload = function () {
//return this.widgetName === "wijupload";
return true;
};
wijupload.prototype._wijcancel = function (fileInput) {
};
wijupload.prototype._upload = function (fileRow, isUpload) {
};
wijupload.prototype._swfUploadFile = function (fileName) {
this.swfupload.startUpload(fileName);
};
wijupload.prototype._bindEvents = function () {
var self = this, o = self.options, progressAll = self.progressAll;
self.upload.delegate(isUploadCancel, "click." + self.widgetName, function (e) {
var cancelBtn = $(this), fileRow = cancelBtn.parents(isUploadFileRow), fileInput, uploader;
if((o.enableSWFUploadOnIE && $.browser.msie) || o.enableSWFUpload) {
var file = fileRow.data("file");
//self.swfupload.queueData.queueSize -= file.size;
//self.swfupload.queueData.queueLength -= 1;
self.swfupload.cancelUpload(file.id);
fileRow.fadeOut(1500, function () {
fileRow.remove();
if(self.swfupload.queueData.queueLength == 0) {
self.commandRow.hide();
}
});
} else {
fileInput = $("input", fileRow[0]);
uploader = self.uploaders[fileInput.attr("id")];
self._wijcancel(fileInput);
if(self._wijUpload() && uploader) {
uploader.cancel();
}
if(progressAll) {
progressAll.totalSize -= _getFileSize(fileInput[0]);
if(progressAll.loadedSize[fileInput.val()]) {
delete progressAll.loadedSize[fileInput.val()];
}
}
self._removeFileRow(fileRow, uploader, false);
}
});
self.upload.delegate(isUploadUpload, "click." + self.widgetName, function (e) {
var uploadBtn = $(this), fileRow = uploadBtn.parents(isUploadFileRow), fileInput, uploader;
if((o.enableSWFUploadOnIE && $.browser.msie) || o.enableSWFUpload) {
var file = fileRow.data("file");
self.uploadAll = false;
if(self._wijUpload()) {
self._swfUploadFile(file.id);
} else {
self._upload(file.id, true);
}
} else {
fileInput = $("input", fileRow[0]);
uploader = self.uploaders[fileInput.attr("id")];
if(self._trigger("upload", e, fileInput) === false) {
return false;
}
if(self.options.autoSubmit) {
//when autoSubmit set to "true", will trigger "totalUpload" immediately.
//self.uploadAll = true; //fixed bug 23877
uploader.autoSubmit = true;
if(self._trigger("totalUpload", e, null) === false) {
return false;
}
}
self.totalUploadFiles++;
self._upload(fileRow);
if(uploader && self._wijUpload()) {
uploader.upload();
}
}
e.preventDefault();
});
self.upload.delegate("." + uploadUploadAllClass, "click." + self.widgetName, function (e) {
if((o.enableSWFUploadOnIE && $.browser.msie) || o.enableSWFUpload) {
self.uploadAll = true;
if(self._wijUpload()) {
self._swfUploadFile();
} else {
self._upload(true, true);
}
} else {
self.uploadAll = true;
if(!self.progressAll) {
self._resetProgressAll();
}
if(self._trigger("totalUpload", e, null) === false) {
return false;
}
self.progressAll.totalSize = self._getTotalSize();
self._wijuploadAll($(isUploadUpload, self.filesList[0]));
if(self._wijUpload()) {
$(isUploadUpload, self.filesList[0]).each(function (idx, uploadBtn) {
$(uploadBtn).click();
return idx;
});
}
}
});
self.upload.delegate("." + uploadCancelAllClass, "click." + self.widgetName, function (e) {
if((o.enableSWFUploadOnIE && $.browser.msie) || o.enableSWFUpload) {
$.each(self.swfupload.queueData.files, function (key, v) {
self.swfupload.cancelUpload(key);
});
$(isUploadFileRow, self.element).fadeOut(1500, function () {
$(this).remove();
self.commandRow.hide();
});
} else {
self._resetProgressAll();
$(isUploadCancel, self.filesList[0]).each(function (idx, cancelBtn) {
$(cancelBtn).click();
});
}
});
};
wijupload.prototype._wijuploadAll = function (uploadBtns) {
};
wijupload.prototype._wijFileRowRemoved = function (fileRow, fileInput, isComplete) {
this._setAddBtnState();
};
wijupload.prototype._removeFileRow = function (fileRow, uploader, isComplete) {
var self = this, inputFileId, files;
if(uploader) {
inputFileId = uploader.inputFile.attr("id");
}
fileRow.fadeOut(1500, function () {
fileRow.remove();
self._wijFileRowRemoved(fileRow, uploader.inputFile, isComplete);
if(self.uploaders[inputFileId]) {
delete self.uploaders[inputFileId];
}
files = $(isUploadFileRow, self.upload);
if(files.length) {
self.commandRow.show();
if(uploader && uploader.destroy) {
uploader.destroy();
}
} else {
self.commandRow.hide();
self.totalUploadFiles = 0;
self._resetProgressAll();
if(uploader && uploader.destroy) {
uploader.destroy(true);
}
}
});
};
wijupload.prototype._getFileName = // Used by C1Upload.
function (fileName) {
return _getFileName(fileName);
};
wijupload.prototype._getFileNameByInput = function (fileInput) {
return _getFileNameByInput(fileInput);
};
wijupload.prototype._getFileSize = function (fileInput) {
return _getFileSize(fileInput);
};
return wijupload;
})(wijmo.wijmoWidget);
upload.wijupload = wijupload;
var wijupload_options = (function () {
function wijupload_options() {
/** Specifies the URL path of the server-side handler that handles the post request, validates file size and type, renames files, and saves the file to the server disk.
* @example
* For php:
* $(".selector").wijupload("option", "action", "../upload.php")
* For asp.net:
* $(".selector").wijupload("option", "action", "../handlers/uploadHandler.ashx")
*/
this.action = "";
/** The value indicates whether to upload the file as soon as it is selected in the "Choose File to Upload" dialog box.
*/
this.autoSubmit = false;
/** Fires when user selects a file. This event can be cancelled.
* "return false;" to cancel the event.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data An object that contains the input file.
*/
this.change = null;
/** Fires before the file is uploaded. This event can be cancelled.
* "return false;" to cancel the event.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data An object that contains the input file.
*/
this.upload = null;
/** Fires when the uploadAll button is clicked. This event can be cancelled.
* "return false;" to cancel the event.
* @event
*/
this.totalUpload = null;
/** Fires when a file is uploading.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data An object that contains the file info, loadedSize and totalSize.
*/
this.progress = null;
/** Fires when the uploadAll button is clicked and file upload is complete.
* @event
* @dataKey {number} loadedSize The size of loaded files.
* @dataKey {number} totalSize The size of total files.
*/
this.totalProgress = null;
/** Fires when file upload is complete.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data An object that contains the file info.
*/
this.complete = null;
/** Fires when the uploadAll button is clicked and file upload is complete.
* @event
*/
this.totalComplete = null;
/** Specifies the maximum number of files that can be uploaded.
*/
this.maximumFiles = 0;
/** Determines whether multiple selection is supported.
*/
this.multiple = true;
/** Specifies the accept attribute of upload. This is an attribute of the file input.
* @remarks
* It is a filter that allows the "Choose File to Upload" dialog box to show the file list with the specified type.
* Possible values:
* audio/* - All sound files are accepted.
* video/* - All video files are accepted.
* image/* - All image files are accepted.
* MIME_type - A valid MIME type with no parameters.
* @example
* $(".selector").wijupload("accept", "image/*")
*/
this.accept = "";
/** upload with SWFupload.swf,
* this option is used for multiple-select in IE.
*/
this.enableSWFUploadOnIE = false;
/** upload with SWFupload.swf in all browsers.
*/
this.enableSWFUpload = false;
/** @ignore
* For web control
*/
this.swfUploadOptions = {
};
/** @ignore
* For web control
*/
this.localization = {
};
/** @ignore
* For web control
*/
this.handleRequest = null;
}
return wijupload_options;
})();
var mainClass = "wijmo-wijupload", classPrefix = mainClass + "-";
wijupload.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijupload_options());
$.wijmo.registerWidget("wijupload", wijupload.prototype);
})(wijmo.upload || (wijmo.upload = {}));
var upload = wijmo.upload;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/// <reference path="../wijsuperpanel/jquery.wijmo.wijsuperpanel.ts" />
/*
* Depends:
* jquery-1.4.2.js
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.position.js
* jquery.effects.core.js
* jquery.cookie.js
* jquery.wijmo.wijsuperpanel.js
* jquery.wijmo.wijutil.js
*
*/
(function (wizard) {
"use strict";
var $ = jQuery;
/** @widget*/
var wijwizard = (function (_super) {
__extends(wijwizard, _super);
function wijwizard() {
_super.apply(this, arguments);
}
wijwizard.prototype._create = function () {
var _this = this;
if(this.element.is(":hidden") && this.element.wijAddVisibilityObserver) {
this.element.wijAddVisibilityObserver(function () {
if(_this.element.wijRemoveVisibilityObserver) {
_this.element.wijRemoveVisibilityObserver();
}
_this._pageLize(true);
}, "wijwizard");
//return;
}
this._pageLize(true);
};
wijwizard.prototype._init = function () {
var o = this.options, dis = o.disabled;
if(o.disabledState) {
this.disable();
o.disabled = dis;
} else {
if(o.autoPlay) {
this.play();
}
}
};
wijwizard.prototype._setOption = function (key, value) {
_super.prototype._setOption.call(this, key, value);
switch(key) {
case 'activeIndex':
this.show(value);
break;
case 'navButtons':
case 'backBtnText':
case 'nextBtnText':
this._createButtons();
break;
case 'autoPlay':
if(value === true) {
this.play();
} else {
this.stop();
}
default:
this._pageLize(false);
break;
}
};
wijwizard.prototype.destroy = /** Removes the wijwizard functionality completely.
* This returns the element back to its pre-init state.
*/
function () {
var o = this.options;
this.abort();
this.stop();
this._removeScroller();
this._removeButtons();
this.element.unbind('.wijwizard').removeClass(o.wijCSS.wijwizard).removeClass(o.wijCSS.widget).removeClass(o.wijCSS.helperClearFix).removeData('wijwizard');
if(this.list) {
this.list.removeClass(o.wijCSS.widget).removeClass(o.wijCSS.helperReset).removeClass(o.wijCSS.wijwizardSteps).removeClass(o.wijCSS.helperClearFix).removeAttr('role');
}
if(this.lis) {
this.lis.removeClass(o.wijCSS.header).removeClass(o.wijCSS.cornerAll).removeClass(o.wijCSS.priorityPrimary).removeClass(o.wijCSS.prioritySecondary).removeAttr('role');
$.each(this.lis, function () {
if($.data(this, 'destroy.wijwizard')) {
$(this).remove();
} else {
$(this).removeAttr('aria-selected');
}
});
}
$.each(this.panels, function () {
var $this = $(this).unbind('.wijwizard');
$.each([
'load',
'cache'
], function (i, prefix) {
$this.removeData(prefix + '.wijwizard');
});
if($.data(this, 'destroy.wijwizard')) {
$this.remove();
} else {
$this.removeClass(o.wijCSS.stateDefault).removeClass(o.wijCSS.wijwizardActived).removeClass(o.wijCSS.stateActive).removeClass(o.wijCSS.stateHover).removeClass(o.wijCSS.stateFocus).removeClass(o.wijCSS.stateDisabled).removeClass(o.wijCSS.wijwizardPanel).removeClass(o.wijCSS.content).removeClass(o.wijCSS.wijwizardHide).css({
position: '',
left: '',
top: ''
}).removeAttr('aria-hidden');
}
});
this.container.replaceWith(this.container.contents());
if(o.cookie) {
this._cookie(null, o.cookie);
}
return this;
};
wijwizard.prototype._pageLize = function (init) {
var o = this.options, fragmentId = /^#.+/;
// Safari 2 reports '#' for an empty hash;
//Fix a bug that when no title and has ul li element in its content
this.list = this.element.children('ol,ul').eq(0);
if(this.list && this.list.length === 0) {
this.list = this.element.find("." + o.wijCSS.wijwizardSteps).eq(0);
if(this.list && this.list.length === 0) {
this.list = null;
}
}
if(this.list) {
this.lis = $('li', this.list);
}
if(init) {
this.panels = $('> div', this.element);
$.each(this.panels, function (i, p) {
var url = $(p).attr('src');
// inline
if(url && !fragmentId.test(url)) {
// mutable data
$.data(p, 'load.wijwizard', url.replace(/#.*$/, ''));
}
});
this.element.addClass(o.wijCSS.wijwizard).addClass(o.wijCSS.widget).addClass(o.wijCSS.helperClearFix);
if(this.list) {
this.list.addClass(o.wijCSS.widget).addClass(o.wijCSS.helperReset).addClass(o.wijCSS.wijwizardSteps).addClass(o.wijCSS.helperClearFix).attr("role", "tablist");
this.lis.addClass(o.wijCSS.header).addClass(o.wijCSS.cornerAll).attr("role", "tab");
}
this.container = $('<div/>');
this.container.addClass(o.wijCSS.wijwizardContent).addClass(o.wijCSS.widget).addClass(o.wijCSS.content).addClass(o.wijCSS.cornerAll);
this.container.append(this.panels);
this.container.appendTo(this.element);
this.panels.addClass(o.wijCSS.wijwizardPanel).addClass(o.wijCSS.content).attr("role", "tabpanel");
// Active a panel
// use "activeIndex" option or try to retrieve:
// 1. from cookie
// 2. from actived class attribute on panel
if(o.activeIndex === undefined) {
if(typeof o.activeIndex !== 'number' && o.cookie) {
o.activeIndex = parseInt(this._cookie(undefined, undefined), 10);
}
if(typeof o.activeIndex !== 'number' && this.panels.filter('.' + o.wijCSS.wijwizardActived).length) {
o.activeIndex = this.panels.index(this.panels.filter('.' + o.wijCSS.wijwizardActived));
}
o.activeIndex = o.activeIndex || (this.panels.length ? 0 : -1);
} else if(o.activeIndex === null) {
// usage of null is deprecated, TODO remove in next release
o.activeIndex = -1;
}
// sanity check - default to first page...
o.activeIndex = ((o.activeIndex >= 0 && this.panels[o.activeIndex]) || o.activeIndex < 0) ? o.activeIndex : 0;
this.panels.addClass(o.wijCSS.wijwizardHide).attr('aria-hidden', true);
if(o.activeIndex >= 0 && this.panels.length) {
// check for length avoids error when initializing empty pages
this.panels.eq(o.activeIndex).removeClass(o.wijCSS.wijwizardHide).addClass(o.wijCSS.wijwizardActived).attr('aria-hidden', false);
this.load(o.activeIndex);
}
this._createButtons();
} else {
this.panels = $('> div', this.container);
o.activeIndex = this.panels.index(this.panels.filter('.' + o.wijCSS.wijwizardActived));
}
this._refreshStep();
this._initScroller();
// set or update cookie after init and add/remove respectively
if(o.cookie) {
this._cookie(o.activeIndex, o.cookie);
}
// reset cache if switching from cached to not cached
if(o.cache === false) {
this.panels.removeData('cache.wijwizard');
}
if(o.showOption === undefined || o.showOption === null) {
o.showOption = {
};
}
this._normalizeBlindOption(o.showOption);
if(o.hideOption === undefined || o.hideOption === null) {
o.hideOption = {
};
}
this._normalizeBlindOption(o.hideOption);
// remove all handlers
this.panels.unbind('.wijwizard');
};
wijwizard.prototype._removeButtons = function () {
if(this.buttons) {
this.buttons.remove();
this.buttons = undefined;
}
};
wijwizard.prototype._createButtons = function () {
var _this = this;
var self = this, o = this.options, bt, addState, removeState, backBtnText = o.backBtnText, nextBtnText = o.nextBtnText;
this._removeButtons();
if(o.navButtons === 'none') {
return;
}
if(!this.buttons) {
bt = o.navButtons;
if(bt === 'auto') {
bt = this.list ? 'common' : 'edge';
}
this.buttons = $('<div/>');
this.buttons.addClass(o.wijCSS.wijwizardButtons);
addState = function (state, el) {
if(o.disabled) {
return;
}
if(el.is(':not(.' + o.wijCSS.stateDisabled + ')')) {
el.addClass(state);
}
};
removeState = function (state, el) {
if(o.disabled) {
return;
}
el.removeClass(state);
};
if(bt === 'common') {
this.backBtn = $("<a href='#'><span class='" + o.wijCSS.buttonText + "'>" + backBtnText + "</span></a>").addClass(o.wijCSS.widget).addClass(o.wijCSS.stateDefault).addClass(o.wijCSS.cornerAll).addClass(o.wijCSS.button).addClass(o.wijCSS.buttonTextOnly).appendTo(this.buttons).bind({
'click': function () {
_this.back();
return false;
},
'mouseover': function () {
addState(o.wijCSS.stateHover, $(this));
},
'mouseout': function () {
removeState(o.wijCSS.stateHover, $(this));
},
'mousedown': function () {
addState(o.wijCSS.stateActive, $(this));
},
'mouseup': function () {
removeState(o.wijCSS.stateActive, $(this));
}
}).attr("role", "button");
this.nextBtn = $("<a href='#'><span class='" + o.wijCSS.buttonText + "'>" + nextBtnText + "</span></a>").addClass(o.wijCSS.widget).addClass(o.wijCSS.stateDefault).addClass(o.wijCSS.cornerAll).addClass(o.wijCSS.button).addClass(o.wijCSS.buttonTextOnly).appendTo(this.buttons).bind({
'click': function () {
self.next();
return false;
},
'mouseover': function () {
addState(o.wijCSS.stateHover, $(this));
},
'mouseout': function () {
removeState(o.wijCSS.stateHover, $(this));
},
'mousedown': function () {
addState(o.wijCSS.stateActive, $(this));
},
'mouseup': function () {
removeState(o.wijCSS.stateActive, $(this));
}
}).attr("role", "button");
} else {
this.backBtn = $("<a href='#'/>").addClass(o.wijCSS.wijwizardPrev).addClass(o.wijCSS.stateDefault).addClass(o.wijCSS.cornerRight).append("<span class='" + o.wijCSS.icon + " " + o.wijCSS.iconArrowLeft + "'></span>").appendTo(this.buttons).bind({
'click': function () {
self.back();
return false;
},
'mouseover': function () {
addState(o.wijCSS.stateHover, $(this));
},
'mouseout': function () {
removeState(o.wijCSS.stateHover, $(this));
},
'mousedown': function () {
addState(o.wijCSS.stateActive, $(this));
},
'mouseup': function () {
removeState(o.wijCSS.stateActive, $(this));
}
}).attr("role", "button");
this.nextBtn = $("<a href='#'/>").addClass(o.wijCSS.wijwizardNext).addClass(o.wijCSS.stateDefault).addClass(o.wijCSS.cornerLeft).append("<span class='" + o.wijCSS.icon + " " + o.wijCSS.iconArrowRight + "'></span>").appendTo(this.buttons).bind({
'click': function () {
self.next();
return false;
},
'mouseover': function () {
addState(o.wijCSS.stateHover, $(this));
},
'mouseout': function () {
removeState(o.wijCSS.stateHover, $(this));
},
'mousedown': function () {
addState(o.wijCSS.stateActive, $(this));
},
'mouseup': function () {
removeState(o.wijCSS.stateActive, $(this));
}
}).attr("role", "button");
}
this.buttons.appendTo(this.element);
}
};
wijwizard.prototype._refreshStep = function () {
var o = this.options;
if(this.lis) {
this.lis.removeClass(o.wijCSS.priorityPrimary).addClass(o.wijCSS.prioritySecondary).attr('aria-selected', false);
if(o.activeIndex >= 0 && o.activeIndex <= this.lis.length - 1) {
if(this.lis) {
this.lis.eq(o.activeIndex).removeClass(o.wijCSS.prioritySecondary).addClass(o.wijCSS.priorityPrimary).attr('aria-selected', true);
}
if(this.scrollWrap) {
this.scrollWrap.wijsuperpanel('scrollChildIntoView', this.lis.eq(o.activeIndex));
}
}
}
if(this.buttons && !o.loop) {
this.backBtn[o.activeIndex <= 0 ? 'addClass' : 'removeClass'](o.wijCSS.stateDisabled).attr('aria-disabled', o.activeIndex === 0);
this.nextBtn[o.activeIndex >= this.panels.length - 1 ? 'addClass' : 'removeClass'](o.wijCSS.stateDisabled).attr('aria-disabled', (o.activeIndex >= this.panels.length - 1));
}
};
wijwizard.prototype._initScroller = function () {
if(!this.lis) {
return;
}
var width = 0;
$.each(this.lis, function () {
width += $(this).outerWidth(true);
});
if(this.element.innerWidth() < width) {
if(this.scrollWrap === undefined) {
this.list.wrap("<div class='scrollWrap'></div>");
this.scrollWrap = this.list.parent();
if($.effects && $.effects.save) {
$.effects.save(this.list, [
'width',
'height',
'overflow'
]);
} else if($.save) {
$.save(this.list, [
'width',
'height',
'overflow'
]);
}
}
this.list.width(width + 8);
this.scrollWrap.height(this.list.outerHeight(true));
this.scrollWrap.wijsuperpanel({
allowResize: false,
hScroller: {
scrollBarVisibility: 'hidden'
},
vScroller: {
scrollBarVisibility: 'hidden'
}
});
} else {
this._removeScroller();
}
};
wijwizard.prototype._removeScroller = function () {
if(this.scrollWrap) {
this.scrollWrap.wijsuperpanel('destroy').replaceWith(this.scrollWrap.contents());
this.scrollWrap = undefined;
if($.effects && $.effects.restore) {
$.effects.restore(this.list, [
'width',
'height',
'overflow'
]);
} else if($.restore) {
$.restore(this.list, [
'width',
'height',
'overflow'
]);
}
}
};
wijwizard.prototype._cookie = function (index, c) {
var cookie = this.cookie || (this.cookie = this.options.cookie.name);
return $.cookie.apply(null, [
cookie
].concat($.makeArray(arguments)));
};
wijwizard.prototype._normalizeBlindOption = function (o) {
if(o.blind === undefined) {
o.blind = false;
}
if(o.fade === undefined) {
o.fade = false;
}
if(o.duration === undefined) {
o.duration = 200;
}
if(typeof o.duration === 'string') {
try {
o.duration = parseInt(o.duration, 10);
} catch (e) {
o.duration = 200;
}
}
};
wijwizard.prototype._ui = function (panel) {
return {
panel: panel,
index: this.panels.index(panel)
};
};
wijwizard.prototype._removeSpinner = function () {
// restore all former loading wijwizard labels
this.element.removeClass(this.options.wijCSS.tabsLoading);
var spinner = this.element.data('spinner.wijwizard');
if(spinner) {
this.element.removeData('spinner.wijwizard');
spinner.remove();
}
};
wijwizard.prototype._showPanel = function (p) {
var _this = this;
var o = this.options, $show = $(p), props;
$show.addClass(o.wijCSS.wijwizardActived);
if((o.showOption.blind || o.showOption.fade) && o.showOption.duration > 0) {
props = {
duration: o.showOption.duration
};
if(o.showOption.blind) {
props.height = 'toggle';
}
if(o.showOption.fade) {
props.opacity = 'toggle';
}
$show.hide().removeClass(o.wijCSS.wijwizardHide).animate(// avoid flicker that way
props, o.showOption.duration || 'normal', "linear", function () {
_this._resetStyle($show);
if($show.wijTriggerVisibility) {
$show.wijTriggerVisibility();
}
_this._trigger('show', null, _this._ui($show[0]));
_this._removeSpinner();
$show.attr('aria-hidden', false);
_this._trigger('activeIndexChanged', null, _this._ui($show[0]));
});
} else {
$show.removeClass(o.wijCSS.wijwizardHide).attr('aria-hidden', false);
if($show.wijTriggerVisibility) {
$show.wijTriggerVisibility();
}
this._trigger('show', null, this._ui($show[0]));
this._removeSpinner();
this._trigger('activeIndexChanged', null, this._ui($show[0]));
}
};
wijwizard.prototype._hidePanel = function (p) {
var _this = this;
var self = this, o = this.options, $hide = $(p), props;
$hide.removeClass(o.wijCSS.wijwizardActived);
if((o.hideOption.blind || o.hideOption.fade) && o.hideOption.duration > 0) {
props = {
duration: o.hideOption.duration
};
if(o.hideOption.blind) {
props.height = 'toggle';
}
if(o.hideOption.fade) {
props.opacity = 'toggle';
}
$hide.animate(props, o.hideOption.duration || 'normal', "linear", function () {
$hide.addClass(o.wijCSS.wijwizardHide).attr('aria-hidden', true);
_this._resetStyle($hide);
_this.element.dequeue("wijwizard");
});
} else {
$hide.addClass(o.wijCSS.wijwizardHide).attr('aria-hidden', true);
this.element.dequeue("wijwizard");
}
};
wijwizard.prototype._resetStyle = // Reset certain styles left over from animation
// and prevent IE's ClearType bug...
function ($el) {
$el.css({
display: ''
});
if(!$.support.opacity) {
$el[0].style.removeAttribute('filter');
}
};
wijwizard.prototype.add = /** The add method adds a new panel.
* @param {number} index Zero-based position where to insert the new panel.
* @param {string} title The step title.
* @param {string} desc The step description.
* @example
* // Add a new panel to be the second step.
* // It's title is "New Panel", description is "New Panel Description".
* $("#wizard").wijwizard("add", 1, "New Panel", "New Panel Description");
*/
function (index, title, desc) {
if(index === undefined) {
index = this.panels.length// append by default
;
}
if(title === undefined) {
title = "Step " + index;
}
var self = this, o = this.options, $panel = $(o.panelTemplate || self._defaults.panelTemplate).data('destroy.wijwizard', true), $li;
$panel.addClass(o.wijCSS.wijwizardPanel).addClass(o.wijCSS.content).addClass(o.wijCSS.cornerAll).addClass(o.wijCSS.wijwizardHide).attr('aria-hidden', true);
if(index >= this.panels.length) {
if(this.panels.length > 0) {
$panel.insertAfter(this.panels[this.panels.length - 1]);
} else {
$panel.appendTo(this.container);
}
} else {
$panel.insertBefore(this.panels[index]);
}
if(this.list && this.lis) {
$li = $((o.stepHeaderTemplate || self._defaults.stepHeaderTemplate).replace(/#\{title\}/g, title).replace(/#\{desc\}/g, desc));
$li.addClass(o.wijCSS.header).addClass(o.wijCSS.cornerAll).addClass(o.wijCSS.prioritySecondary).data('destroy.wijwizard', true);
if(index >= this.lis.length) {
$li.appendTo(this.list);
} else {
$li.insertBefore(this.lis[index]);
}
}
this._pageLize(false);
if(this.panels.length === 1) {
// after pagelize
o.activeIndex = 0;
$li.addClass(o.wijCSS.priorityPrimary);
$panel.removeClass(o.wijCSS.wijwizardHide).addClass(o.wijCSS.wijwizardActived).attr('aria-hidden', false);
this.element.queue("wijwizard", function () {
self._trigger('show', null, self._ui(self.panels[0]));
});
this._refreshStep();
this.load(0);
}
// callback
this._trigger('add', null, this._ui(this.panels[index]));
return this;
};
wijwizard.prototype.remove = /** The remove method removes a panel.
* @param {number} index The zero-based index of the panel to be removed.
* @example
* // Remove the second step.
* $("#wizard").wijwizard("remove", 1);
*/
function (index) {
var o = this.options, $panel = //$li = this.lis.eq(index).remove(),
this.panels.eq(index).remove();
this.lis.eq(index).remove();
if(index < o.activeIndex) {
o.activeIndex--;
}
this._pageLize(false);
//Ajust the active panel index in some case
if($panel.hasClass(o.wijCSS.wijwizardActived) && this.panels.length >= 1) {
this.show(index + (index < this.panels.length ? 0 : -1));
}
// callback
this._trigger('remove', null, this._ui($panel[0]));
return this;
};
wijwizard.prototype.show = /** The show method selects an active panel and displays the panel at a specified position.
* @param {number} index The zero-based index of the panel to be actived.
* @example
* // Show the second step.
* $("#wizard").wijwizard("show", 1);
*/
function (index) {
var _this = this;
if(index < 0 || index >= this.panels.length) {
return this;
}
// previous animation is still processing
if(this.element.queue("wijwizard").length > 0) {
return this;
}
var o = this.options, args = {
nextIndex: 0,
nextPanel: null
}, $hide, $show;
$.extend(args, this._ui(this.panels[o.activeIndex]));
args.nextIndex = index;
args.nextPanel = this.panels[index];
if(this._trigger('validating', null, args) === false) {
return this;
}
$hide = this.panels.filter(':not(.' + o.wijCSS.wijwizardHide + ')');
$show = this.panels.eq(index);
o.activeIndex = index;
this.abort();
if(o.cookie) {
this._cookie(o.activeIndex, o.cookie);
}
this._refreshStep();
// show new panel
if($show.length) {
if($hide.length) {
this.element.queue("wijwizard", function () {
_this._hidePanel($hide);
});
}
this.element.queue("wijwizard", function () {
_this._showPanel($show);
});
this.load(index);
} else {
throw 'jQuery UI wijwizard: Mismatching fragment identifier.';
}
return this;
};
wijwizard.prototype.next = /** The next method moves to the next panel. */
function () {
var o = this.options, index = o.activeIndex + 1;
if(o.disabled) {
return false;
}
if(o.loop) {
index = index % this.panels.length;
}
if(index < this.panels.length) {
this.show(index);
return true;
}
return false;
};
wijwizard.prototype.back = /** The back method moves to the previous panel. */
function () {
var o = this.options, index = o.activeIndex - 1;
if(o.disabled) {
return false;
}
if(o.loop) {
index = index < 0 ? this.panels.length - 1 : index;
}
if(index >= 0) {
this.show(index);
return true;
}
return false;
};
wijwizard.prototype.load = /** The load method reload the content of an Ajax panel programmatically.
* @param {number} index The zero-based index of the panel to be loaded.
* @example
* // Reload the content of second step.
* $("#wizard").wijwizard("load", 1);
*/
function (index) {
var self = this, o = self.options, p = self.panels.eq(index)[0], url = $.data(p, 'load.wijwizard'), spinner;
self.abort();
// not remote or from cache
if(!url || self.element.queue("wijwizard").length !== 0 && $.data(p, 'cache.wijwizard')) {
self.element.dequeue("wijwizard");
return;
}
// load remote from here on
this.element.addClass(o.wijCSS.tabsLoading);
if(o.spinner) {
spinner = this.element.data('spinner.wijwizard');
if(!spinner) {
spinner = $('<div/>');
spinner.addClass(o.wijCSS.wijwizardSpinner);
spinner.html(o.spinner || self._defaults.spinner);
spinner.appendTo(document.body);
this.element.data('spinner.wijwizard', spinner);
spinner.wijpopup({
showEffect: 'blind',
hideEffect: 'blind'
});
}
spinner.wijpopup('show', {
of: this.element,
my: 'center center',
at: 'center center'
});
}
this.xhr = $.ajax($.extend({
}, o.ajaxOptions, {
url: url,
dataType: 'html',
success: function (r, s) {
$(p).html(r);
if(o.cache) {
// if loaded once do not load them again
$.data(p, 'cache.wijwizard', true);
}
// callbacks
self._trigger('load', null, self._ui(self.panels[index]));
try {
if(o.ajaxOptions && o.ajaxOptions.success) {
o.ajaxOptions.success(r, s);
}
} catch (e1) {
}
},
error: function (xhr, s, e) {
// callbacks
self._trigger('load', null, self._ui(self.panels[index]));
try {
// Passing index avoid a race condition when this method is
// called after the user has selected another panel.
if(o.ajaxOptions && o.ajaxOptions.error) {
o.ajaxOptions.error(xhr, s, index, p);
}
} catch (e2) {
}
}
}));
// last, so that load event is fired before show...
self.element.dequeue("wijwizard");
return self;
};
wijwizard.prototype.abort = /** The abort method terminates all running panel ajax requests and animations. */
function () {
this.element.queue([]);
this.panels.stop(false, true);
// "wijwizard" queue must not contain more than two elements,
// which are the callbacks for hide and show
this.element.queue("wijwizard", this.element.queue("wijwizard").splice(-2, 2));
// terminate pending requests from other wijwizard
if(this.xhr) {
this.xhr.abort();
delete this.xhr;
}
// take care of spinners
this._removeSpinner();
return this;
};
wijwizard.prototype.url = /** The url method changes the url from which an Ajax (remote) panel will be loaded.
* @param {number} index The zero-based index of the panel of which its URL is to be updated.
* @param {string} url A URL the content of the panel is loaded from.
* @example
* // Change the url content of second step.
* $("#wizard").wijwizard("url", 1, "http://wijmo.com/newurl.html");
*/
function (index, url) {
this.panels.eq(index).removeData('cache.wijwizard').data('load.wijwizard', url);
return this;
};
wijwizard.prototype.count = /**
* The count method retrieves the number panels.
* @returns {number} the pabels's length
*/
function () {
return this.panels.length;
};
wijwizard.prototype.stop = /** The stop method stops displaying the panels in order automatically. */
function () {
var id = this.element.data('intId.wijwizard');
if(id) {
window.clearInterval(id);
this.element.removeData('intId.wijwizard');
}
};
wijwizard.prototype.play = /** The play method begins displaying the panels in order automatically. */
function () {
var _this = this;
var o = this.options, id, len = this.panels.length;
if(!this.element.data('intId.wijwizard')) {
id = window.setInterval(function () {
var index = o.activeIndex + 1;
if(index >= len) {
if(o.loop) {
index = 0;
} else {
_this.stop();
return;
}
}
_this.show(index);
}, o.delay);
this.element.data('intId.wijwizard', id);
}
};
return wijwizard;
})(wijmo.wijmoWidget);
wizard.wijwizard = wijwizard;
wijwizard.prototype._defaults = {
stepHeaderTemplate: '<li><h1>#{title}</h1>#{desc}</li>',
panelTemplate: '<div></div>',
spinner: '<em>Loading…</em>'
};
var wijwizard_options = (function () {
function wijwizard_options() {
/** All CSS classes used in widgets.
* @ignore
*/
this.wijCSS = {
wijwizard: "wijmo-wijwizard",
wijwizardButtons: "wijmo-wijwizard-buttons",
wijwizardPrev: "wijmo-wijwizard-prev",
wijwizardNext: "wijmo-wijwizard-next",
wijwizardSteps: "wijmo-wijwizard-steps",
wijwizardContent: "wijmo-wijwizard-content",
wijwizardPanel: "wijmo-wijwizard-panel",
wijwizardActived: "wijmo-wijwizard-actived",
wijwizardHide: "wijmo-wijwizard-hide",
wijwizardSpinner: "wijmo-wijwizard-spinner"
};
/** @ignore*/
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body-c",
stateDefault: "ui-btn-up-a",
stateHover: "ui-btn-down-a",
stateActive: "ui-btn-down-a"
};
/** The navButtons option defines the type of navigation buttons used with the wijwizard.
* @remarks The possible values are 'auto', 'common', 'edge' and 'none'.
*/
this.navButtons = 'auto';
/** The autoPlay option allows the panels to automatically display in order. */
this.autoPlay = false;
/** The delay option determines the time span between displaying panels in autoplay mode. */
this.delay = 3000;
/** The loop option allows the wijwizard to begin again from the first panel
* when reaching the last panel in autoPlay mode. */
this.loop = false;
/** The hideOption option defines the animation effects
* when hiding the panel content.
* @example
* //Set hide animation to blind and duration to 500.
* $(".selector").wijwizard({
* hideOption: {fade: false, blind: true, duration: 500}
* });
*/
this.hideOption = {
fade: true
};
/** The showOption option defines the animation effects
* when showing the panel content.
* @example
* //Set show animation to blind and duration to 500.
* $(".selector").wijwizard({
* showOption: {fade: false, blind: true, duration: 500}
* });
*/
this.showOption = {
fade: true,
duration: 400
};
/** A value that indicates additional Ajax options to consider when
* loading panel content (see $.ajax).
* @type {object}
* @remarks Please see following link for more details,
* http://api.jquery.com/jQuery.ajax/ .
*
*/
this.ajaxOptions = null;
/** An option that determines whether to cache emote wijwizard content.
* @remarks Cached content is being lazy loaded,
* for example only and only once for the panel is displayed.
* Note that to prevent the actual Ajax requests from being cached by the browser,
* you need to provide an extra cache: false flag to ajaxOptions.
*/
this.cache = false;
/** The cookie option is a value that stores the latest active index in a cookie.
* The cookie is then used to determine the initially active index
* if the activeIndex option is not defined.
* @remarks This option requires a cookie plugin.
* The object needs to have key/value pairs
* of the form the cookie plugin expects as options.
* @type {object}
* @example
* $(".selector").wijwizard({cookie:{expires: 7, path: '/', domain: 'jquery.com';, secure: true }})
*/
this.cookie = null;
/** The stepHeaderTemplate option creates an HTML template
* for the step header when a new panel is added with the
* add method or when creating a panel for a remote panel on the fly.
*/
this.stepHeaderTemplate = '';
/** The panelTemplate option is an HTML template from which a new panel is created.
* The new panel is created by adding a panel with the add method or when creating
* a panel from a remote panel on the fly.
*/
this.panelTemplate = '';
/** The HTML content of this string is shown in a panel
* while remote content is loading.
* Pass the option in empty string to deactivate that behavior. */
this.spinner = '';
/** The backBtnText option defines the text for the wizard back button. */
this.backBtnText = 'back';
/** The nextBtnText option defines the text for the wijwizard next button. */
this.nextBtnText = 'next';
/** The add event handler is a function called when a panel is added.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijWizardEventArgs} args The data with this event.
*/
this.add = null;
/** The remove event handler is a function called when a panel is removed.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijWizardEventArgs} args The data with this event.
*/
this.remove = null;
/** The activeIndexChanged event handler is a function called when the activeIndex is changed.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijWizardEventArgs} args The data with this event.
*/
this.activeIndexChanged = null;
/** The show event handler is a function called when a panel is shown.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijWizardEventArgs} args The data with this event.
*/
this.show = null;
/** The load event handler is a function called after the content of a remote panel has been loaded.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijWizardEventArgs} args The data with this event.
*/
this.load = null;
/** The validating event handler is a function called before moving to next panel.
* This event is Cancellable.
* @event
* @param {Object} e The jQuery.Event object.
* @param {IWijWizardValidatingEventArgs} args The data with this event.
*/
this.validating = null;
}
return wijwizard_options;
})();
;
wijwizard.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijwizard_options());
$.wijmo.registerWidget("wijwizard", wijwizard.prototype);
;
;
})(wijmo.wizard || (wijmo.wizard = {}));
var wizard = wijmo.wizard;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../external/declarations/globalize.d.ts"/>
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/// <reference path="../wijtabs/jquery.wijmo.wijtabs.ts" />
/*globals jQuery,window,document*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.wijmo.wijtooltip.js
*/
(function (ribbon) {
"use strict";
var $ = jQuery, widgetName = "wijribbon";
var css_ribbon = "wijmo-wijribbon", css_ribbon_disabled = css_ribbon + "-disabled", css_ribbon_bigbutton = css_ribbon + "-bigbutton", css_ribbon_panel = css_ribbon + "-panel", css_ribbon_groups = css_ribbon + "-groups", css_ribbon_group = css_ribbon + "-group", css_ribbon_groupcontent = css_ribbon_group + "-content", css_ribbon_grouplabel = css_ribbon_group + "-label", css_ribbon_dropdown = css_ribbon + "-dropdown", css_ribbon_dropdowngroup = css_ribbon + "-dropdowngroup", css_ribbon_abbrev = css_ribbon + "-abbrev", css_ribbon_abbrevgroup = css_ribbon_abbrev + "group", css_ribbon_text = css_ribbon + "-text", css_ribbon_icon = css_ribbon + "-icon", css_ribbon_abbrevicon = css_ribbon + "-abbrevicon";
/** @widget */
var wijribbon = (function (_super) {
__extends(wijribbon, _super);
function wijribbon() {
_super.apply(this, arguments);
}
wijribbon.prototype._create = function () {
var self = this;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
self._ribbonify();
//update for visibility change
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
self.updateRibbonSize();
if(self.options.disabled) {
self._setDisabled(true);
}
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
}, "wijribbon");
}
if(self.options.disabled) {
self._setDisabled(true);
}
};
wijribbon.prototype._setOption = function (key, value) {
$.wijmo.widget.prototype._setOption.apply(this, arguments);
if(key === "disabled") {
this._setDisabled(value);
}
};
wijribbon.prototype._setDisabled = function (value) {
var self = this, element = self.element, eleOffset = element.offset(), offsetTop = eleOffset.top, offsetLeft = eleOffset.left, offsetParent = $("body"), wijCSS = this.options.wijCSS, disabledModal = self.disabledModal;
if(element.data("wijmoWijtabs")) {
element.wijtabs("option", "disabled", value);
}
if(element.closest(".wijmo-wijeditor").length !== 0) {
offsetTop = 0;
offsetLeft = 0;
offsetParent = element.parent();
}
if(value) {
if(!disabledModal) {
disabledModal = $("<div></div>").addClass(wijCSS.stateDisabled + " " + css_ribbon_disabled).css({
top: offsetTop,
left: offsetLeft,
"background-color": //"z-index": "10000",
//for ie can't disabled, so add background-color attribute
"lightgray",
"position": "absolute"
}).appendTo(offsetParent).bind("click mousedown mouseup mouseover mouseout " + "focus keydown keypress", function (e) {
e.stopPropagation();
e.preventDefault();
return false;
});
self.disabledModal = disabledModal;
}
self.disabledModal.width(element.width()).height(element.outerHeight()).show();
} else {
if(self.disabledModal) {
self.disabledModal.hide();
}
}
};
wijribbon.prototype._ribbonify = function () {
var self = this, wijCSS = this.options.wijCSS;
self.buttons = {
};
self.listUis = {
};
self._getButtonSets();
self._createButtons();
self._createGroup();
self._createSplit();
self._createDropdwon();
self._hideShowedList();
self._createTab();
$("." + wijCSS.helperReset + ":not(." + css_ribbon_groups + ", ." + wijCSS.tabsNav + ")", self.element).hover(function () {
$(this).addClass(wijCSS.stateHover);
}, function () {
$(this).removeClass(wijCSS.stateHover);
});
//update for adding active class at 2011-11-17
$(".ui-button", self.element).bind("mouseenter", function () {
$("." + wijCSS.buttonText, this).addClass(wijCSS.stateHover);
}).bind("mouseleave", function () {
$("." + wijCSS.buttonText, this).removeClass(wijCSS.stateHover);
});
$("button.ui-button", self.element).bind("mousedown", function () {
self._addActiveClassToButtonText(this);
}).bind("mouseup", function () {
self._addActiveClassToButtonText(this);
});
//update for 36511 issue for jquery ui 1.10: button interface changed
/**
$("label.ui-button", self.element).bind("click", function () {
self._addActiveClassToLabelButtonText(this);
});*/
};
wijribbon.prototype._addActiveClassToButtonText = function (button) {
var wijCSS = this.options.wijCSS;
if(button) {
if($(button).hasClass(wijCSS.stateActive)) {
$("." + wijCSS.buttonText, button).addClass(wijCSS.stateActive);
} else {
$("." + wijCSS.buttonText, button).removeClass(wijCSS.stateActive);
}
}
};
wijribbon.prototype._addActiveClassToLabelButtonText = function (button) {
var self = this, oriEle, oriEleID, eleGroup;
if(button) {
oriEleID = $(button).attr("for");
oriEle = $("#" + oriEleID, self.element);
if(oriEle.is(":checkbox")) {
self._addActiveClassToButtonText(button);
} else if((oriEle.is(":radio"))) {
eleGroup = self.element.find("[name='" + oriEle.attr("name") + "']");
$.each(eleGroup, function () {
self._updateGroupElementTextState(this);
});
}
}
};
wijribbon.prototype._updateGroupElementTextState = function (button) {
var radioLabelEle, wijCSS = this.options.wijCSS;
if(!button) {
return;
}
radioLabelEle = $("[for='" + $(button).attr("id") + "']", $(button).parent());
if(radioLabelEle) {
if(radioLabelEle.hasClass(wijCSS.stateActive)) {
radioLabelEle.children("." + wijCSS.buttonText).addClass(wijCSS.stateActive);
} else {
radioLabelEle.children("." + wijCSS.buttonText).removeClass(wijCSS.stateActive);
}
}
};
wijribbon.prototype._getButtonSets = function () {
var self = this, span;
self.groups = [];
self.splits = [];
self.dropdowns = [];
$("span>button, span>:checkbox, span>:radio, div>button, div>:checkbox," + " div>:radio", self.element).each(function (i, btn) {
span = $(btn).parent();
if($(">ul", span).length === 0) {
self.groups.push(span);
} else {
if($(">button", span).length === 2) {
self.splits.push(span);
} else if($(">button", span).length === 1) {
self.dropdowns.push(span);
}
}
return this;
});
self.groups = self._unique(self.groups);
self.splits = self._unique(self.splits);
};
wijribbon.prototype._unique = function (group) {
var array = $.makeArray($.map(group, function (n) {
return n.get(0);
}));
return $.map($.unique(array), function (n) {
return $(n);
});
};
wijribbon.prototype._createButtons = function () {
var self = this, element = self.element;
$(":checkbox", element).each(function () {
self._createButton($(this), "checkbox");
//update for 36511 issue for jquery ui 1.10: button interface changed
$(this).bind("change", function () {
self._addActiveClassToLabelButtonText($(this).button("widget")[0]);
});
return this;
});
$(":radio", element).each(function () {
self._createButton($(this), "radio");
$(this).bind("change", function () {
self._addActiveClassToLabelButtonText($(this).button("widget")[0]);
});
return this;
});
$("button", element).each(function () {
self._createButton($(this), "button");
return this;
});
};
wijribbon.prototype._createButton = function (button, type) {
var self = this, wijCSS = this.options.wijCSS, options = self._buildButtonOption(button, type), name = button.data("commandName"), labelEle;
button.button(options);
if(!options.text) {
if(type === "button") {
button.children("." + wijCSS.buttonText).text(name);
} else {
labelEle = $("[for='" + button.attr("id") + "']", button.parent());
if(labelEle) {
labelEle.children("." + wijCSS.buttonText).text(name);
}
}
}
self._triggerEvent(button);
};
wijribbon.prototype._createGroup = function () {
$.each(this.groups, function (i, group) {
group.buttonset();
});
};
wijribbon.prototype._createSplit = function () {
var self = this, wijCSS = this.options.wijCSS;
$.each(self.splits, function (i, split) {
var list = split.children("ul"), content = split.children("button:eq(0)"), splitName = content.data("commandName"), triggerEle = split.children("button:eq(1)"), splitObj;
list.children("li").addClass(wijCSS.cornerAll);
split.addClass(css_ribbon + "-" + splitName);
triggerEle.button({
icons: {
primary: wijCSS.iconArrowDown
},
text: false
}).data("list", list).unbind("click").bind(//update for preventing submit by wuhao at 2011/8/2
"click", function (e) {
e.stopPropagation();
e.preventDefault();
}).bind(//end at 2011/8/2
"mouseup", function (e) {
list = $(this).data("list");
if(list.is(":visible")) {
self.showList.hide().css("z-index", "");
self.showList = null;
} else {
list.show().position({
my: 'left top',
at: 'left bottom',
of: split
}).css("z-index", 9999);
self.showList = list;
}
e.stopPropagation();
e.preventDefault();
});
triggerEle.children("." + wijCSS.buttonText).text("foo");
split.after(list);
list.css("position", "absolute").addClass(wijCSS.helperReset + " " + wijCSS.helperClearFix + " " + wijCSS.cornerAll + " " + css_ribbon_dropdown).hide();
split.buttonset();
splitObj = {
ui: content,
defaultValue: content.button("option", "label"),
buttons: [],
type: "split",
trigger: triggerEle,
list: list
};
$("button, :checkbox, :radio", list).bind("click", function (e) {
//var uiButton = $(this);
//content.button("option", "label",
///uiButton.button("option", "label"));
//content.data("commandName", uiButton.data("commandName"));
list.hide().css("z-index", "");
self.showList = null;
e.preventDefault();
});
list.find(">li>button,>li>:radio,>li>:checkbox").each(function (i, button) {
var commandName = $(button).data("commandName");
if(commandName !== "" && self.buttons[commandName]) {
self.buttons[commandName].parent = content;
self.buttons[commandName].type = "split";
}
splitObj.buttons.push($(button));
});
if(splitName !== "") {
self.listUis[splitName] = splitObj;
}
});
};
wijribbon.prototype._createDropdwon = function () {
var self = this, wijCSS = this.options.wijCSS;
self.dropdownLabels = {
};
$.each(self.dropdowns, function (i, dropdown) {
var list = dropdown.children("ul"), button = dropdown.children("button:eq(0)"), dropdownName = button.data("commandName"), dropdownObj;
list.children("li").addClass(wijCSS.cornerAll);
dropdown.addClass(css_ribbon + "-" + dropdownName);
button.button({
icons: {
secondary: wijCSS.iconArrowDown
}
}).unbind("click").bind(//update by wuhao 2011/8/1 for preventing submit
"click", function (e) {
e.stopPropagation();
e.preventDefault();
}).bind(//end for preventing submit
"mouseup", function (e) {
if(list.is(":visible")) {
self.showList.hide().css("z-index", "");
self.showList = null;
} else {
if(self.showList) {
self.showList.hide();
self.showList = null;
}
list.show().position({
my: 'left top',
at: 'left bottom',
of: button
}).css("z-index", 9999);
self.showList = list;
self.isShow = true;
}
e.stopPropagation();
e.preventDefault();
});
dropdownObj = {
ui: button,
defaultValue: button.button("option", "label"),
buttons: [],
type: "dropdown",
list: list
};
$("button, :checkbox, :radio", list).bind("click", function (e) {
var name = $(this).data("commandName"), label, width = button.children("." + wijCSS.buttonText).width();
if(!self.dropdownLabels[name]) {
self.dropdownLabels[name] = self._getDropdownLabelSubstr($(this).button("option", "label"), button.children("." + wijCSS.buttonText), width);
}
label = self.dropdownLabels[name];
button.button("option", "label", label);
button.attr("title", $(this).button("option", "label"));
list.hide().css("z-index", "");
self.showList = null;
e.preventDefault();
});
//dropdown.after(list);
list.css("position", "absolute").addClass(wijCSS.helperReset + " " + wijCSS.helperClearFix + " " + wijCSS.cornerAll + " " + css_ribbon_dropdown).hide();
dropdown.buttonset();
list.find(">li>button,>li>:radio,>li>:checkbox").each(function (i, btn) {
var commandName = $(btn).data("commandName");
if(commandName !== "" && self.buttons[commandName]) {
self.buttons[commandName].parent = button;
self.buttons[commandName].type = "dropdown";
}
dropdownObj.buttons.push($(btn));
});
// cache a hash to save the dropdown.
if(dropdownName !== "") {
self.listUis[dropdownName] = dropdownObj;
}
});
};
wijribbon.prototype._createTab = function () {
var self = this, wijCSS = this.options.wijCSS, element = self.element;
element.addClass(css_ribbon);
self.tabEle = element;
if($(">ul", element).length > 0) {
element.wijtabs();
self._createRibbonGroups();
return true;
} else {
element.addClass(css_ribbon + "-simple").addClass(wijCSS.stateDefault).addClass(wijCSS.helperClearFix);
}
return false;
};
wijribbon.prototype.updateRibbonSize = /** @ignore */
function () {
var self = this, groupDropDown, wijCSS = this.options.wijCSS, abbrevgroupContainer;
self.tabEle.children("div").each(function (i, tabPage) {
var $tabPage = $(tabPage), isTabVisible = $tabPage.is(":visible"), groups = $tabPage.find(">ul>li"), groupInfos = [], pageWidth;
pageWidth = $tabPage.width();
// if($tabPage.css("display") === "none"){
// pageWidth = self.tabEle.width();
// }
//Note: add by wh at 2011/10/30
if(!isTabVisible) {
$tabPage.removeClass(wijCSS.wijtabsHide);
pageWidth = $tabPage.width();
}
groups.each(function (j, li) {
var group = $(li), lblDiv = group.find(">div:last"), text = //text = $.trim(lblDiv.text());
lblDiv.attr("displayname") ? lblDiv.attr("displayname") : $.trim(lblDiv.text());
//update by wh for refresh 2012/1/9
//recover the ribbon to orign
groupDropDown = group.children("." + css_ribbon_dropdowngroup);
abbrevgroupContainer = group.children("." + css_ribbon_abbrevgroup);
if(groupDropDown) {
group.addClass(css_ribbon + "-" + text.toLowerCase()).prepend(groupDropDown.children());
groupDropDown.remove();
if(abbrevgroupContainer) {
abbrevgroupContainer.remove();
}
}
//end
groupInfos.push({
width: group.outerWidth(true),
text: text
});
return this;
});
self._adjustRibbonGroupIfNeeded(groups, groupInfos, pageWidth);
//Note: add by wh at 2011/10/30
if(!isTabVisible) {
$tabPage.addClass(wijCSS.wijtabsHide);
}
return this;
});
if(self.options.disabled) {
self._setDisabled(true);
}
};
wijribbon.prototype._createRibbonGroups = function () {
var self = this, wijCSS = this.options.wijCSS;
self.tabEle.children("div").each(function (i, tabPage) {
var $tabPage = $(tabPage), isTabVisible = $tabPage.is(":visible"), groups = $tabPage.find(">ul>li"), groupInfos = [], pageWidth;
//update for fixed issue 21292 by wh at 2012/5/8
if($tabPage.data("destroy.tabs")) {
$tabPage.remove();
return;
}
//end
if(!isTabVisible) {
$tabPage.removeClass(wijCSS.wijtabsHide);
}
pageWidth = $tabPage.width();
$tabPage.addClass(css_ribbon_panel);
$tabPage.find(">ul").addClass(wijCSS.helperReset + " " + wijCSS.helperClearFix + " " + wijCSS.content + " " + wijCSS.cornerAll + " " + css_ribbon_groups);
groups.each(function (j, li) {
var group = $(li), lblDiv = group.find(">div:last"), css = wijCSS.stateDefault + " " + css_ribbon_group, text = //text = $.trim(lblDiv.text());
lblDiv.attr("displayname") ? lblDiv.attr("displayname") : $.trim(lblDiv.text());
if(lblDiv) {
css += " " + css_ribbon + "-" + text.toLowerCase();
}
group.addClass(css);
lblDiv.addClass(css_ribbon_grouplabel).bind("click", function () {
return false;
});
group.wrapInner("<div class = '" + css_ribbon_groupcontent + "'></div>");
group.children().bind("mouseover", function () {
$(this).addClass(wijCSS.stateHover);
}).bind("mouseout", function () {
$(this).removeClass(wijCSS.stateHover);
});
lblDiv.appendTo(group);
groupInfos.push({
width: group.outerWidth(true),
text: text
});
return this;
});
self._originalGroupInfo = groupInfos;
self._adjustRibbonGroupIfNeeded(groups, groupInfos, pageWidth);
if(!isTabVisible) {
$tabPage.addClass(wijCSS.wijtabsHide);
}
return this;
});
};
wijribbon.prototype._adjustRibbonGroupIfNeeded = function (groups, groupInfos, pageWidth) {
var self = this, i = groups.length - 1, j = 0, iWidth = 0, jWidth = 0, groupDropDown, abbrevgroupContainer, gi;
for(; i >= 0; i--) {
jWidth = 0;
for(j = 0; j < i; j++) {
jWidth += groupInfos[j].width;
}
if(jWidth + iWidth + groupInfos[i].width <= pageWidth) {
//remove the dropdowngroup and add dropdowngroup's children to group
groupDropDown = $(groups[i]).children("." + css_ribbon_dropdowngroup);
abbrevgroupContainer = $(groups[i]).children("." + css_ribbon_abbrevgroup);
if(groupDropDown) {
$(groups[i]).addClass(css_ribbon + "-" + groupInfos[i].text.toLowerCase()).prepend(groupDropDown.children());
groupDropDown.remove();
if(abbrevgroupContainer) {
abbrevgroupContainer.remove();
}
//continue;
}
} else {
gi = groupInfos[i];
iWidth += self._createDropDownRibbonGroup(gi.text, groups[i]);
}
}
};
wijribbon.prototype._createDropDownRibbonGroup = function (text, group) {
var self = this, grpClass = css_ribbon + "-" + text.toLowerCase(), wijCSS = this.options.wijCSS, $group = $(group).removeClass(grpClass), displayText = $group.find(">div:last").text() || text, $abbrevgrp;
$group.wrapInner("<div class='" + css_ribbon_dropdowngroup + " " + css_ribbon_group + "'></div>").children().hide().addClass(grpClass).bind("mouseup." + self.widget, function (e) {
if(self.showDrpDwnGroup !== null) {
self.showDrpDwnGroup.hide().css("z-index", "");
self.showDrpDwnGroup = null;
}
});
$abbrevgrp = $("<div class='" + css_ribbon_abbrevgroup + "'>" + "<span class='" + css_ribbon_abbrev + text.toLowerCase() + " " + css_ribbon_icon + " " + css_ribbon_abbrevicon + "'></span>" + "<span class='" + css_ribbon_text + "'>" + displayText + "</span>" + "<span class='" + wijCSS.icon + " " + wijCSS.iconArrowDown + " " + css_ribbon_icon + "'></span></div>").appendTo($group).unbind(self.widget).bind("mouseover." + self.widget, function (e) {
$(this).addClass(wijCSS.stateHover);
}).bind("mouseout." + self.widget, function (e) {
$(this).removeClass(wijCSS.stateHover);
}).bind("click." + self.widget, function (e) {
var $drpGroup = $(this).siblings("." + css_ribbon_dropdowngroup);
if($drpGroup.is(":visible")) {
$drpGroup.hide().css("z-index", "");
self.showDrpDwnGroup = null;
} else {
if(self.showDrpDwnGroup) {
self.showDrpDwnGroup.hide().css("z-index", "");
}
$drpGroup.show().position({
my: "left top",
at: "left bottom",
of: this
}).css("z-index", "10000");
self.showDrpDwnGroup = $drpGroup;
e.stopPropagation();
}
});
return $group.outerWidth(true);
};
wijribbon.prototype._hideShowedList = function () {
var self = this;
$(document).bind("mouseup", function (e) {
var target = e.target;
if(self.showList) {
//Note: click the font, dropdown is open
//then click the design view(document), there is a error
//update by wh at 2011/9/14
//if (!$.contains(self.showList.get(0), target)) {
if($(target).is(document) || !$.contains(self.showList.get(0), target)) {
//end by wh
self.showList.hide().css("z-index", "");
self.showList = null;
}
}
if(self.showDrpDwnGroup) {
//Note: click the font, dropdown is open
//then click the design view(document), there is a error
//update by wh at 2011/9/14
//if (!$.contains(self.showDrpDwnGroup.get(0), target)) {
if($(target).is(document) || !$.contains(self.showDrpDwnGroup.get(0), target)) {
//end by wh
self.showDrpDwnGroup.hide().css("z-index", "");
self.showDrpDwnGroup = null;
}
}
});
};
wijribbon.prototype._buildButtonOption = function (node, type) {
var text = true, self = this, nodeClass = node.attr("class"), spans, iconClass, iconEle, imagePosition, label, labelEle, name;
// only icon
if(nodeClass && nodeClass !== "" && nodeClass !== css_ribbon_bigbutton) {
iconClass = nodeClass.split(" ")[0];
node.removeClass(iconClass);
label = $.trim(node.text());
if(label === "") {
text = false;
}
} else {
if(type === "checkbox" || type === "radio") {
if($.trim(node.attr("id")) === "") {
return;
}
labelEle = $("[for='" + node.attr("id") + "']", node.parent());
if(!labelEle.is("label")) {
return;
}
nodeClass = labelEle.attr("class");
if(nodeClass && nodeClass !== "" && nodeClass !== css_ribbon_bigbutton) {
iconClass = nodeClass.split(" ")[0];
labelEle.removeClass(iconClass);
label = $.trim(labelEle.text());
if(label === "") {
text = false;
}
} else {
//TODO only text
spans = labelEle.children("span,div");
}
} else if(type === "button") {
spans = node.children("span,div");
}
if(spans) {
if(spans.length === 1) {
//only image
if(spans.eq(0).attr("class") !== "") {
iconEle = spans.eq(0);
iconClass = iconEle.attr("class");
text = false;
}
// to do only text
} else if(spans.length === 2) {
if(spans.eq(0).attr("class")) {
iconEle = spans.eq(0);
iconClass = iconEle.attr("class");
if(iconEle.is("span")) {
imagePosition = "left";
} else if(iconEle.is("div")) {
imagePosition = "top";
}
label = spans.eq(1).text();
}
// TODO: Text before image.
// TODO: Text above image.
} else {
if(type === "button" && $.trim(node.text()) !== "") {
label = $.trim(node.text());
}
}
}
}
if(type === "button") {
node.empty();
name = $.trim(node.attr("name"));
if(name !== "") {
node.removeAttr("name");
}
} else {
name = $.trim(labelEle.attr("name"));
if(name !== "") {
labelEle.removeAttr("name");
}
}
if(name !== "") {
node.data("commandName", name);
self.buttons[name] = {
button: node
};
}
return {
label: label,
icons: {
primary: iconClass
},
position: imagePosition,
text: text
};
};
wijribbon.prototype._triggerEvent = function (button) {
var self = this;
button.bind("click", function (e) {
if(self.options.disabled) {
e.preventDefault();
e.stopPropagation();
return;
}
var commandName = button.data("commandName"), buttonObj = self.buttons[commandName], obj = {
name: undefined,
commandName: undefined
};
if(buttonObj && buttonObj.parent) {
obj.name = buttonObj.parent.data("commandName");
}
obj.commandName = commandName;
self._trigger("click", e, obj);
// if is button to prevent submit form
if(button.is("button")) {
e.preventDefault();
e.stopPropagation();
}
});
};
wijribbon.prototype._getDropdownLabelSubstr = function (text, label, width) {
var self = this, length = text.length, start = 0, end = length, mid = Math.floor((start + end) / 2), newLabel = $("<span></span>"), str = text.substr(0, mid), midWidth;
newLabel.appendTo(label.parent());
midWidth = self._calculateWidth(str, newLabel);
while(midWidth !== width && end > start) {
str = text.substr(0, mid + 1);
midWidth = self._calculateWidth(str, newLabel);
if(midWidth > width) {
end = mid - 1;
} else if(midWidth < width) {
start = mid + 1;
}
mid = Math.floor((start + end) / 2);
}
newLabel.remove();
return str;
};
wijribbon.prototype._calculateWidth = function (str, span) {
span.text(str);
return span.width();
};
wijribbon.prototype.hideDropdown = /** @ignore */
function (name) {
var self = this, dropdown = self.listUis[name];
if(dropdown && dropdown.list) {
dropdown.list.hide();
}
};
wijribbon.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
if(this.disabledModal) {
this.disabledModal.remove();
}
$.Widget.prototype.destroy.call(this);
};
wijribbon.prototype.getDropdownList = /** @ignore */
function (name) {
var self = this, dropdown = self.listUis[name], retrunObj = {
};
if(dropdown) {
$.each(dropdown.buttons, function (i, button) {
retrunObj[button.data("commandName")] = button.button("option", "label");
});
}
return retrunObj;
};
wijribbon.prototype.setButtonDisabled = /** The method sets the chosen button as enabled or disabled according to the command name.
* @param {string} commandName The name of the command.
* @param {boolean} disabled The disabled state of the button, true or false.
*/
function (commandName, disabled) {
var buttonObj = this.buttons[commandName], wijCSS = this.options.wijCSS, isButtonEle = false, button, splitUi;
if(buttonObj && buttonObj.button) {
button = buttonObj.button;
isButtonEle = button.is("button");
button.button("option", "disabled", disabled);
if(isButtonEle) {
// when the keypress, the button text will be happen change
// For "Save" to "save"
if(commandName !== "save") {
button.children("." + wijCSS.buttonText).text(commandName);
}
} else {
$("[for='" + button.attr("id") + "']", button.parent()).children("." + wijCSS.buttonText).text(commandName);
}
splitUi = this.listUis[commandName];
if(splitUi && splitUi.type === "split") {
splitUi.trigger.button("option", "disabled", disabled);
splitUi.trigger.children("." + wijCSS.buttonText).text(commandName);
}
}
};
wijribbon.prototype.setButtonsDisabled = /** The method sets the ribbon buttons as enabled or disabled according to the command name.
* @param {object} commands An object that contains commands infos that need to change state,
* key is command name, value is button disabled state, true or false.
*/
function (commands) {
var self = this;
$.each(commands, function (key, value) {
self.setButtonDisabled(key, value);
});
};
wijribbon.prototype.setButtonsChecked = /** The method sets sets the buttons as checked or not checked.
* @param {object} commands An object that contains commands infos that need to change state,
* key is command name, value is button checked state, true or false.
*/
function (commands) {
var self = this;
$.each(commands, function (key, value) {
if($.isPlainObject(value)) {
self.setButtonChecked(key, value.checked, value.name);
} else {
self.setButtonChecked(key, value, null);
}
});
};
wijribbon.prototype.setButtonChecked = /** Sets a ribbon button as checked or not checked.
* @param {string} commandName The command name of the button.
* @param {boolean} checked The checked state of the button.
* @param {string} name The parent name of the button.
*/
function (commandName, checked, name) {
var self = this, radios, buttonObj = self.buttons[commandName], wijCSS = this.options.wijCSS, buttonEle, listUi, label;
if(buttonObj && buttonObj.button) {
buttonEle = buttonObj.button;
if(buttonEle.is("button")) {
if(checked) {
buttonEle.addClass(wijCSS.stateActive);
} else {
buttonEle.removeClass(wijCSS.stateActive);
}
} else {
buttonEle.prop("checked", checked);
buttonEle.button("refresh");
}
if(buttonObj.parent) {
if(buttonObj.type === "dropdown") {
// checked
if(checked) {
if(!self.dropdownLabels[commandName]) {
self.dropdownLabels[commandName] = self._getDropdownLabelSubstr(buttonEle.button("option", "label"), buttonObj.parent.children("." + wijCSS.buttonText), buttonObj.parent.children("." + wijCSS.buttonText).width());
}
label = self.dropdownLabels[commandName];
buttonObj.parent.button("option", "label", label);
buttonObj.parent.attr("title", buttonEle.button("option", "label"));
//add for adding active class at 2011/11/16
//TODO: dropdown hasn't unchecked behavior,
//so when will remove
//the active class
//buttonObj.parent.children("." + css_button_text)
//.addClass(css_state_active);
//update for fixing issue 20268 by wh at 2011/3/7
//radios = $(":radio", buttonObj.parent
// .closest("ul"));
radios = $(":radio", buttonObj.button.closest("ul"));
//end for issue 20268
if(radios) {
$.each(radios, function () {
self._updateGroupElementTextState(this);
});
}
//end for active class
}
// dropdown hasn't unchecked behavior.
// else {
// // unchecked
// if (!name) {
// name = buttonObj.parent.data("commandName");
// }
// listUi = self.listUis[name];
// if (listUi) {
// listUi.ui.button("option", "label", listUi.defaultValue);
// }
// }
//TODO the list button is icon.
}
//TODO split
} else {
self._addActiveClassToButtonText(buttonEle.button("widget"));
}
} else if(name) {
// handle dropdown
listUi = self.listUis[name];
if(listUi) {
listUi.ui.button("option", "label", listUi.defaultValue);
if(listUi.buttons) {
$.each(listUi.buttons, function (i, btn) {
btn.prop("checked", false);
btn.button("refresh");
//add for adding active class at 2011/11/16
self._addActiveClassToButtonText(btn.button("widget"));
//end for adding active class
});
}
}
}
};
return wijribbon;
})(wijmo.wijmoWidget);
ribbon.wijribbon = wijribbon;
var wijribbon_options = (function () {
function wijribbon_options() {
/** Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijribbon')";
/** All CSS classes used in widgets.
* @ignore
*/
this.wijCSS = {
wijtabsHide: "wijmo-wijtabs-hide"
};
/** The wijRibbonClick event is a function that is called
* when the ribbon command button is clicked.
* @event
* @dataKey {string} commandName the command name of the button.
* @dataKey {string} name the parent name of the button which means if the drop down item is clicked,
* then the name specifies the command name of the drop down button.
*/
this.click = null;
}
return wijribbon_options;
})();
;
wijribbon.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijribbon_options());
$.wijmo.registerWidget("wijribbon", wijribbon.prototype);
})(wijmo.ribbon || (wijmo.ribbon = {}));
var ribbon = wijmo.ribbon;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/// <reference path="../wijsplitter/jquery.wijmo.wijsplitter.ts" />
/// <reference path="../wijdialog/jquery.wijmo.wijdialog.ts" />
/// <reference path="../external/declarations/globalize.d.ts" />
/*globals jQuery,window,document*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.wijmo.wijtooltip.js
*/
(function (editor) {
"use strict";
var $ = jQuery, widgetName = "wijeditor";
var wijAlert = alert, wijWindow = window, wijDoc = document, wijParseInt = parseInt, oriWidth, oriHeight, $oriParent, uniqueIds = [], isFontSizeCustomized = //fullScreen = false,
null, wordwrap = true, tblBorderShowing = true, undoSteps = 0, undoBuffers = [], rangeSelection = null, inspectElement = null, setButtonDisabled = //id_prefix ="",
"setButtonDisabled", setButtonsDisabled = "setButtonsDisabled", setButtonChecked = "setButtonChecked", setButtonsChecked = "setButtonsChecked", cmd_form = "form", cmd_imagebutton = "imagebutton", cmd_textarea = "textarea", cmd_button = "button", cmd_textbox = "textbox", cmd_listbox = "list", cmd_password = "passwordfield", cmd_dropdownlist = "dropdownlist", cmd_hiddenfield = "hiddenfield", cmd_radio = "radio", cmd_checkbox = "checkbox", cmd_insertcolumn = "insertcol", cmd_insertrow = "insertrow", cmd_insertcell = "insertcell", cmd_splitcell = "splitcell", cmd_mergecell = "mergecell", cmd_removecolumn = "deletecol", cmd_removerow = "deleterow", cmd_removecell = "deletecell", cmd_alignleft = "justifyleft", cmd_aligncenter = "justifycenter", cmd_alignright = "justifyright", cmd_alignfull = "justifyfull", cmd_borders = "borders", cmd_numberedlist = "insertorderedlist", cmd_bulletedlist = "insertunorderedlist", cmd_outdent = "outdent", cmd_indent = "indent", cmd_backcolor = "backcolor", cmd_fontcolor = "fontcolor", cmd_bold = "bold", cmd_italic = "italic", cmd_strike = "strikethrough", cmd_underline = "underline", cmd_subscript = "subscript", cmd_superscript = "superscript", cmd_template = "template", cmd_removeformat = "removeformat", cmd_insertbreak = "insertbreak", cmd_insertparagraph = "insertparagraph", cmd_insertprintbreak = "insertprintpagebreak", cmd_inserthr = "inserthorizontalrule", cmd_table = "tablebutton", cmd_inserttable = "inserttable", cmd_edittable = "edittable", cmd_designview = "wysiwyg", cmd_splitview = "split", cmd_sourceview = "code", cmd_wordwrap = "wordwrap", cmd_fullscreen = "fullscreen", cmd_undo = "undo", cmd_redo = "redo", cmd_preview = "preview", cmd_cleanup = "cleanup", cmd_cut = "cut", cmd_copy = "copy", cmd_paste = "paste", cmd_selectall = "selectall", cmd_media = "media", cmd_specialchar = "specialchar", cmd_date = "datetime", cmd_find = "find", cmd_inspect = "inspect", cmd_save = "save", cmd_spelling = "spelling", cmd_imagebrowser = "imagebrowser", cmd_link = "link", cmd_verysmall = "xx-small", cmd_smaller = "x-small", cmd_small = "small", cmd_medium = "medium", cmd_large = "large", cmd_larger = "x-large", cmd_verylarge = "xx-large", cmd_fontname = "fontname", cmd_fontsize = "fontsize", cmd_blockquote = "blockquote", cmd_insertcode = "insertcode", css_ribbon = "wijmo-wijribbon", css_ribbon_bigbutton = css_ribbon + "-bigbutton", css_ribbon_dropdownbutton = css_ribbon + "-dropdownbutton", css_ribbon_splitbutton = css_ribbon + "-splitbutton", css_ribbon_list = css_ribbon + "-list", css_ribbon_save = css_ribbon + "-save", css_ribbon_save16 = css_ribbon + "-save16", css_ribbon_undo = css_ribbon + "-undo", css_ribbon_redo = css_ribbon + "-redo", css_ribbon_preview = css_ribbon + "-preview", css_ribbon_cleanup = css_ribbon + "-cleanup", css_ribbon_cut = css_ribbon + "-cut", css_ribbon_copy = css_ribbon + "-copy", css_ribbon_paste = css_ribbon + "-paste", css_ribbon_selectall = css_ribbon + "-selectall", css_ribbon_bgcolor = css_ribbon + "-bgcolor", css_ribbon_color = css_ribbon + "-color", css_ribbon_bold = css_ribbon + "-bold", css_ribbon_italic = css_ribbon + "-italic", css_ribbon_underline = css_ribbon + "-underline", css_ribbon_strike = css_ribbon + "-strike", css_ribbon_sub = css_ribbon + "-sub", css_ribbon_sup = css_ribbon + "-sup", css_ribbon_template = css_ribbon + "-template", css_ribbon_removeformat = css_ribbon + "-removeformat", css_ribbon_justifyleft = css_ribbon + "-justifyleft", css_ribbon_justifycenter = css_ribbon + "-justifycenter", css_ribbon_justifyright = css_ribbon + "-justifyright", css_ribbon_justifyfull = css_ribbon + "-justifyfull", css_ribbon_borders = css_ribbon + "-borders", css_ribbon_orderlist = css_ribbon + "-orderlist", css_ribbon_unorderlist = css_ribbon + "-unorderlist", css_ribbon_outdent = css_ribbon + "-outdent", css_ribbon_indent = css_ribbon + "-indent", css_ribbon_inspect = css_ribbon + "-inspect", css_ribbon_find = css_ribbon + "-find", css_ribbon_table = css_ribbon + "-table", css_ribbon_inserttable = css_ribbon + "-inserttable", css_ribbon_edittable = css_ribbon + "-edittable", css_ribbon_insertcol = css_ribbon + "-insertcol", css_ribbon_insertrow = css_ribbon + "-insertrow", css_ribbon_insertcell = css_ribbon + "-insertcell", css_ribbon_splitcell = css_ribbon + "-splitcell", css_ribbon_mergecell = css_ribbon + "-mergecell", css_ribbon_deletecol = css_ribbon + "-deletecol", css_ribbon_deleterow = css_ribbon + "-deleterow", css_ribbon_deletecell = css_ribbon + "-deletecell", css_ribbon_insertbreak = css_ribbon + "-insertbreak", css_ribbon_insertparagraph = css_ribbon + "-insertparagraph", css_ribbon_insertprintpagebreak = css_ribbon + "-insertprintpagebreak", css_ribbon_inserthr = css_ribbon + "-inserthr", css_ribbon_form = css_ribbon + "-form", css_ribbon_textarea = css_ribbon + "-textarea", css_ribbon_textbox = css_ribbon + "-textbox", css_ribbon_password = css_ribbon + "-password", css_ribbon_hiddenfield = css_ribbon + "-hiddenfield", css_ribbon_imagebutton = css_ribbon + "-imagebutton", css_ribbon_button = css_ribbon + "-button", css_ribbon_listbox = css_ribbon + "-listbox", css_ribbon_dropdownlist = css_ribbon + "-dropdownlist", css_ribbon_radio = css_ribbon + "-radio", css_ribbon_checkbox = css_ribbon + "-checkbox", css_ribbon_link = css_ribbon + "-link", css_ribbon_link16 = css_ribbon + "-link16", css_ribbon_imagebrowser = css_ribbon + "-imagebrowser", css_ribbon_media = css_ribbon + "-media", css_ribbon_specialchar = css_ribbon + "-specialchar", css_ribbon_datetime = css_ribbon + "-datetime", css_ribbon_blockquote = css_ribbon + "-blockquote", css_ribbon_insertcode = css_ribbon + "-insertcode", css_ribbon_modes = css_ribbon + "-modes", css_ribbon_designview = css_ribbon + "-designview", css_ribbon_sourceview = css_ribbon + "-sourceview", css_ribbon_splitview = css_ribbon + "-splitview", css_ribbon_wordwrap = css_ribbon + "-wordwrap", css_ribbon_fullscreen = css_ribbon + "-fullscreen", css_editor = "wijmo-wijeditor", css_editor_container = css_editor + "-container", css_editor_header = css_editor + "-header", css_editor_content = css_editor + "-content", css_editor_footer = css_editor + "-footer", css_editor_pathselector = css_editor + "-pathselector", css_editor_fullscreen = css_editor + "-fullscreen", css_dlg = css_editor + "-dialog", css_dlg_hr = css_dlg + "-hr", css_dlg_buttons = css_dlg + "-buttons", css_dlg_button = css_dlg + "-button", css_dlg_text = css_dlg + "-text", css_imgdlg = css_editor + "-imagedlg", css_imgdlg_content = css_imgdlg + "-content", css_imgdlg_fields = css_imgdlg + "-fields", css_imgdlg_field = css_imgdlg + "-imagefield", css_imgdlg_list = css_imgdlg + "-imagelist", css_imgdlg_preview = css_imgdlg + "-preview", css_imgdlg_url = css_imgdlg + "-imagesrc", css_imgdlg_alt = css_imgdlg + "-imagealt", css_imgdlg_width = css_imgdlg + "-imagewidth", css_imgdlg_height = css_imgdlg + "-imageheight", css_imgdlg_css = css_imgdlg + "-css", css_imgdlg_hideimglist = css_imgdlg + "-hideimagelist", css_tpldlg = css_editor + "-templatedlg", css_tpl_labels = css_tpldlg + "-toplabels", css_tpl_tllabel = css_tpldlg + "-topleftlabel", css_tpl_trlabel = css_tpldlg + "-toprightlabel", css_tpl_content = css_tpldlg + "-content", css_tpl_list = css_tpldlg + "-templatelist", css_tpl_preview = css_tpldlg + "-preview", css_tpl_tplinfo = css_tpldlg + "-templateinfo", css_tpl_nameinfo = css_tpldlg + "-nameinfo", css_tpl_desinfo = css_tpldlg + "-descriptioninfo", css_tpl_fields = css_tpldlg + "-fields", css_tpl_namefield = css_tpldlg + "-name", css_tpl_desfield = css_tpldlg + "-description", css_tpl_buttons = css_tpldlg + "-buttons", css_tpl_delete = css_tpldlg + "-delete", css_tpl_save = css_tpldlg + "-save", css_linkdlg = css_editor + "-linkdlg", css_linkdlg_address = css_linkdlg + "-address", css_linkdlg_linktype = css_linkdlg + "-linktype", css_linkdlg_anchor = css_linkdlg + "-anchor", css_linkdlg_text = css_linkdlg + "-text", css_linkdlg_target = css_linkdlg + "-target", css_linkdlg_css = css_linkdlg + "-css", css_linkdlg_url = css_linkdlg + "-src", css_linkdlg_width = css_linkdlg + "-width", css_linkdlg_height = css_linkdlg + "-height", css_linkdlg_imagecontainer = css_linkdlg + "-imagecontainer", css_linkdlg_linkicontype = css_linkdlg + "-linkicontype", css_codedlg = css_editor + "-codedlg", css_codedlg_source = css_codedlg + "-source", css_codedlg_sourcelabel = css_codedlg + "-sourcelabel", css_taginsdlg = css_editor + "-taginsdlg", css_taginsdlg_caption = css_taginsdlg + "-caption", css_taginsdlg_taglabel = css_taginsdlg + "-taglabel", css_taginsdlg_tagtext = css_taginsdlg + "-tagtext", css_taginsdlg_filterempty = css_taginsdlg + "-filterempty", css_taginsdlg_attribs = css_taginsdlg + "-attribs", css_taginsdlg_attriblist = css_taginsdlg + "-attriblist", css_taginsdlg_innerhtml = css_taginsdlg + "-innerhtml", css_taginsdlg_css = css_taginsdlg + "-css", css_colordlg = css_editor + "-colordlg", css_colordlg_picker = css_colordlg + "-picker", css_colordlg_color = css_colordlg + "-color", css_tabledlg = css_editor + "-tabledlg", css_tabledlg_rows = css_tabledlg + "-rows", css_tabledlg_columns = css_tabledlg + "-columns", css_tabledlg_width = css_tabledlg + "-width", css_tabledlg_height = css_tabledlg + "-height", css_tabledlg_border = css_tabledlg + "-border", css_tabledlg_cellpadding = css_tabledlg + "-cellpadding", css_tabledlg_cellspacing = css_tabledlg + "-cellspacing", css_tabledlg_csstext = css_tabledlg + "-csstext", css_tabledlg_bgcolor = css_tabledlg + "-bgcolor", css_previewdlg = css_editor + "-previewdlg", css_previewdlg_caption = css_previewdlg + "-caption", css_previewdlg_navigator = css_previewdlg + "-navigator", css_previewdlg_prev = css_previewdlg + "-prev", css_previewdlg_next = css_previewdlg + "-next", css_previewdlg_printall = css_previewdlg + "-printall", css_previewdlg_printone = css_previewdlg + "-printone", css_previewdlg_ok = css_previewdlg + "-ok", css_previewdlg_printdocument = css_previewdlg + "-printdocument", css_previewdlg_previewiframe = css_previewdlg + "-previewiframe", css_cleanupdlg = css_editor + "-cleanupdlg", css_cleanupdlg_caption = css_cleanupdlg + "-caption", css_cleanupdlg_document = css_cleanupdlg + "-document", css_cleanupdlg_actions = css_cleanupdlg + "-actions", css_finddlg = css_editor + "-finddlg", css_finddlg_find = css_finddlg + "-find", css_finddlg_replace = css_finddlg + "-replace", css_mediadlg = css_editor + "-mediadlg", css_mediadlg_type = css_mediadlg + "-type", css_mediadlg_url = css_mediadlg + "-src", css_mediadlg_width = css_mediadlg + "-width", css_mediadlg_height = css_mediadlg + "-height", css_specialchardlg = css_editor + "-specialchardlg", css_specialchardlg_chars = css_specialchardlg + "-chars", css_specialchardlg_preview = css_specialchardlg + "-preview", css_specialchardlg_content = css_specialchardlg + "-content", css_specialchardlg_list = css_specialchardlg + "-list", css_specialchardlg_label = css_specialchardlg + "_label", css_specialchardlg_punctuation = css_specialchardlg + "-punctuation", css_specialchardlg_symbols = css_specialchardlg + "-symbols", css_specialchardlg_diacritics = css_specialchardlg + "-diacritics", css_formatspan = "wijmo-formatspan", selector_dlg_ok = "." + css_dlg_buttons + " input:first", selector_dlg_cancel = "." + css_dlg_buttons + " input:last", selector_input_ok = "." + css_dlg_buttons + " input[value='OK']", selector_input_cancel = "." + css_dlg_buttons + " input[engValue='Cancel']", imageTypeButton = [
"Bold",
"Italic",
"UnderLine",
"StrikeThrough",
"SubScript",
"SuperScript",
"JustifyLeft",
"JustifyCenter",
"JustifyRight",
"JustifyFull",
"Border",
"NumberedList",
"BulletedList",
"Outdent",
"Indent"
], defaultSimpleModeCommands = [
"Bold",
"Italic",
"Link",
"BlockQuote",
"StrikeThrough",
"InsertDate",
"InsertImage",
"NumberedList",
"BulletedList",
"InsertCode"
], defaultBBCodeModeCommands = [
"Bold",
"Italic",
"StrikeThrough",
"UnderLine",
"ForeColor",
"FontSize",
"Link",
"InsertImage",
"NumberedList",
"BulletedList",
"BlockQuote"
], buttonInfoAsCommand = {
Form: {
name: "form",
tip: 'Form',
css: css_ribbon_form
},
Image: {
name: "imagebutton",
tip: 'Image Button',
css: css_ribbon_imagebutton
},
TextArea: {
name: "textarea",
tip: 'TextArea',
css: css_ribbon_textarea
},
Button: {
name: "button",
tip: 'Button',
css: css_ribbon_button
},
TextBox: {
name: "textbox",
tip: 'TextBox',
css: css_ribbon_textbox
},
List: {
name: "list",
tip: 'ListBox',
css: css_ribbon_listbox
},
PasswordField: {
name: "passwordfield",
tip: 'Password Field',
css: css_ribbon_password
},
DropDownList: {
name: "dropdownlist",
tip: 'DropDownList',
css: css_ribbon_dropdownlist
},
HiddenField: {
name: "hiddenfield",
tip: 'Hidden Field',
css: css_ribbon_hiddenfield
},
Radio: {
name: "radio",
tip: 'RadioButton',
css: css_ribbon_radio
},
CheckBox: {
name: "checkbox",
tip: 'CheckBox',
css: css_ribbon_checkbox
},
InsertColumn: {
name: "insertcol",
tip: 'Insert Column',
css: css_ribbon_insertcol
},
InsertRow: {
name: "insertrow",
tip: 'Insert Row',
css: css_ribbon_insertrow
},
InsertCell: {
name: "insertcell",
tip: 'Insert Cell',
css: css_ribbon_insertcell
},
SplitCell: {
name: "splitcell",
tip: 'Split Cell',
css: css_ribbon_splitcell
},
MergeCell: {
name: "mergecell",
tip: 'Merge Cell',
css: css_ribbon_mergecell
},
DeleteColumn: {
name: "deletecol",
tip: 'Delete Column',
css: css_ribbon_deletecol
},
DeleteRow: {
name: "deleterow",
tip: 'Delete Row',
css: css_ribbon_deleterow
},
DeleteCell: {
name: "deletecell",
tip: 'Delete Cell',
css: css_ribbon_deletecell
},
JustifyLeft: {
name: "justifyleft",
tip: 'Justify Left',
css: css_ribbon_justifyleft,
grpname: 'alignment'
},
JustifyCenter: {
name: "justifycenter",
tip: 'Justify Center',
css: css_ribbon_justifycenter,
grpname: 'alignment'
},
JustifyRight: {
name: "justifyright",
tip: 'Justify Right',
css: css_ribbon_justifyright,
grpname: 'alignment'
},
JustifyFull: {
name: "justifyfull",
tip: 'Justify Full',
css: css_ribbon_justifyfull,
grpname: 'alignment'
},
Border: {
name: "borders",
tip: 'Border',
css: css_ribbon_borders
},
NumberedList: {
name: "insertorderedlist",
tip: 'Numbered List',
css: css_ribbon_orderlist,
grpname: 'list'
},
BulletedList: {
name: "insertunorderedlist",
tip: 'Bulleted List',
css: css_ribbon_unorderlist,
grpname: 'list'
},
Outdent: {
name: "outdent",
tip: 'Outdent',
css: css_ribbon_outdent,
grpname: 'block'
},
Indent: {
name: "indent",
tip: 'Indent',
css: css_ribbon_indent,
grpname: 'block'
},
BackColor: {
name: "backcolor",
tip: 'Background Color',
css: css_ribbon_bgcolor
},
ForeColor: {
name: "fontcolor",
tip: 'Font Color',
css: css_ribbon_color
},
Bold: {
name: "bold",
tip: 'Bold',
css: css_ribbon_bold
},
Italic: {
name: "italic",
tip: 'Italic',
css: css_ribbon_italic
},
StrikeThrough: {
name: "strikethrough",
tip: 'Strikethrough',
css: css_ribbon_strike
},
UnderLine: {
name: "underline",
tip: 'Underline',
css: css_ribbon_underline
},
SubScript: {
name: "subscript",
tip: 'Subscript',
css: css_ribbon_sub
},
SuperScript: {
name: "superscript",
tip: 'Superscript',
css: css_ribbon_sup
},
Template: {
name: "template",
tip: 'Template',
css: css_ribbon_template
},
RemoveFormat: {
name: "removeformat",
tip: 'RemoveFormat',
css: css_ribbon_removeformat
},
InsertBreak: {
name: "insertbreak",
tip: 'Insert Break',
css: css_ribbon_insertbreak
},
InsertParagraph: {
name: "insertparagraph",
tip: 'Insert Paragraph',
css: css_ribbon_insertparagraph
},
InsertPrint: {
name: "insertprintpagebreak",
tip: 'Insert Print Page Break',
css: css_ribbon_insertprintpagebreak
},
InsertHR: {
name: "inserthorizontalrule",
tip: 'Insert Horizontal Line',
css: css_ribbon_inserthr
},
Table: {
name: "tablebutton",
tip: 'Table',
css: css_ribbon_table
},
InsertTable: {
name: "inserttable",
tip: 'Insert Table',
css: css_ribbon_inserttable
},
EditTable: {
name: "edittable",
tip: 'Edit Table',
css: css_ribbon_edittable
},
Wysiwyg: {
name: "wysiwyg",
tip: 'Design View',
css: css_ribbon_designview,
grpname: 'modes'
},
Split: {
name: "split",
tip: 'Split View',
css: css_ribbon_splitview,
grpname: 'modes'
},
Code: {
name: "code",
tip: 'Source View',
css: css_ribbon_sourceview,
grpname: 'modes'
},
Wordwrap: {
name: "wordwrap",
tip: 'Wordwrap',
css: css_ribbon_wordwrap
},
FullScreen: {
name: "fullscreen",
tip: 'Fullscreen',
css: css_ribbon_fullscreen
},
Undo: {
name: "undo",
tip: 'Undo',
css: css_ribbon_undo
},
Redo: {
name: "redo",
tip: 'Redo',
css: css_ribbon_redo
},
Preview: {
name: "preview",
tip: 'Preview',
css: css_ribbon_preview
},
Cleanup: {
name: "cleanup",
tip: 'Clean up',
css: css_ribbon_cleanup
},
Cut: {
name: "cut",
tip: 'Cut',
css: css_ribbon_cut
},
Copy: {
name: "copy",
tip: 'Copy',
css: css_ribbon_copy
},
Paste: {
name: "paste",
tip: 'Paste',
css: css_ribbon_paste
},
SelectAll: {
name: "selectall",
tip: 'Select All',
css: css_ribbon_selectall
},
Media: {
name: "media",
tip: 'Media',
css: css_ribbon_media
},
InsertSpecialChar: {
name: "specialchar",
tip: 'Insert Special Character',
css: css_ribbon_specialchar
},
InsertDate: {
name: "datetime",
tip: 'Insert Date Time',
css: css_ribbon_datetime
},
Find: {
name: "find",
tip: 'Find And Replace',
css: css_ribbon_find,
text: 'Find'
},
Inspect: {
name: "inspect",
tip: 'Tag Inspect',
css: css_ribbon_inspect,
text: 'Inspect'
},
Save: {
name: "save",
tip: 'Save',
css: css_ribbon_save,
text: 'Save'
},
Spelling: {
name: "spelling",
tip: 'Form',
css: ''
},
InsertImage: {
name: "imagebrowser",
tip: 'Image Browser',
css: css_ribbon_imagebrowser
},
Link: {
name: "link",
tip: 'Link',
css: css_ribbon_link,
text: 'Link'
},
FontName: //xx-small: {tip: 'Form', css: css_ribbon_form},
//x-small: {tip: 'Form', css: css_ribbon_form},
//small: { tip: 'Form', css: css_ribbon_form },
//medium: { tip: 'Form', css: css_ribbon_form },
//large: { tip: 'Form', css: css_ribbon_form },
//x-large: {tip: 'Form', css: css_ribbon_form},
//xx-large: {tip: 'Form', css: css_ribbon_form},
{
name: "fontname",
tip: 'Font Name',
css: css_ribbon_dropdownbutton
},
FontSize: {
name: "fontsize",
tip: 'Font Size',
css: css_ribbon_dropdownbutton
},
BlockQuote: {
name: "blockquote",
tip: 'Block Quote',
css: css_ribbon_blockquote
},
InsertCode: {
name: "insertcode",
tip: 'Insert Code',
css: css_ribbon_insertcode
}
}, StringBuilder = function () {
var self = this, strs = [];
self.append = function (str) {
strs.push(str);
};
self.toString = function () {
return strs.join("");
};
self.dispose = function () {
strs = null;
};
}, TextElement = function (text) {
this.text = text;
this.render = function () {
return this.text;
};
}, HtmlElement = function (tagName, innerText, attributes) {
var self = this, halfTags = {
br: true,
img: true,
hr: true,
input: true
};
self.tagName = tagName || "div";
self.attributes = attributes || {
};
self.innerText = innerText || "";
self.children = [];
if($.isPlainObject(innerText)) {
self.innerText = "";
self.attributes = innerText;
}
self._isShortTag = false;
if(halfTags[self.tagName] === true) {
self._isShortTag = true;
}
self.render = function () {
var sb = new StringBuilder(), html = "";
sb.append(self._renderBeginTag(self.tagName, self.attributes));
if(self.innerText !== "") {
sb.append(self.innerText);
}
if(self.children.length > 0) {
$.each(self.children, function (index, ele) {
sb.append(ele.render());
});
}
sb.append(self._renderEndTag(self.tagName));
html = sb.toString();
sb.dispose();
return html;
};
self.add = function (ele) {
this.children.push(ele);
};
self._renderBeginTag = function (tagName, attributes) {
var sb = new StringBuilder(), strRet = "";
sb.append("<");
sb.append(tagName);
$.each(attributes, function (key, value) {
sb.append(" ");
sb.append(key);
sb.append("=");
sb.append("\"");
sb.append(value ? value.toString() : "");
sb.append("\"");
});
if(this._isShortTag) {
sb.append(" ");
} else {
sb.append(">");
}
strRet = sb.toString();
sb.dispose();
return strRet;
};
self._renderEndTag = function (tagName) {
var sb = new StringBuilder(), strRet = "";
if(this._isShortTag) {
sb.append("/>");
} else {
sb.append("</");
sb.append(tagName);
sb.append(">");
}
strRet = sb.toString();
sb.dispose();
return strRet;
};
};
/** @widget */
var wijeditor = (function (_super) {
__extends(wijeditor, _super);
function wijeditor() {
_super.apply(this, arguments);
}
wijeditor.prototype.wijeditor = /**
* @constructor
* @ignore
*/
function () {
this._curPageIdx = 0;
this.tRange = null;
this.txtFoundInIE = false;
this.txtFoundInNoneIE = false;
};
wijeditor.prototype._create = function () {
var self = this;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
//update for fixing bug 18157 at 2011/11/5 by wh
if(self.element.is("input")) {
return;
}
//end for 18157
//if place two editors, it will be mess in ui and function
self.id_prefix = "wijeditor-" + self.element.attr("id") + "-";
self.$ribbon = undefined;
self.$modes = undefined;
self._editorify();
self._initElements();
wijWindow.setTimeout(function () {
if(self.options.disabled) {
self._handleDisabledOption(true, self.editor);
}
}, 40);
//add for fixing issue 20372 by wh at 2012/3/9
self._continueSavingInputTextForUndo = false;
//enf for 20372
//update for visibility change
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function (e) {
if($.contains(self.editor[0], e.target)) {
return;
}
self.refresh();
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
}, "wijeditor");
}
};
wijeditor.prototype._contextMenuWidgetName = function () {
return "wijmenu";
};
wijeditor.prototype._createBigButton = function (tip, css, name, text) {
var self = this, button = self._createElement("button", {
title: tip,
name: name,
"class": css_ribbon_bigbutton
});
button.add(self._createDiv(css));
button.add(self._createSpan("", text));
return button;
};
wijeditor.prototype._createTextButton = function (tip, name, text) {
return this._createElement("button", text, {
title: tip,
name: name
});
};
wijeditor.prototype._createButton = function (tip, css, name, text) {
var self = this, button;
if(!text) {
return self._createElement("button", {
title: tip,
name: name,
"class": css
});
}
button = self._createElement("button", {
title: tip,
name: name
});
button.add(self._createSpan(css));
button.add(self._createSpan("", text));
return button;
};
wijeditor.prototype._createTextRadioButton = function (tip, idPre, name, grpName, text) {
var self = this, buttons = [];
buttons.push(self._createElement("input", {
id: idPre + name,
type: "radio",
name: grpName
}));
buttons.push(self._createElement("label", text, {
"for": idPre + name,
title: tip,
name: name
}));
return buttons;
};
wijeditor.prototype._createImageRadioButton = function (tip, idPre, css, name, grpName) {
var self = this, buttons = [];
buttons.push(self._createElement("input", {
id: idPre + name,
type: "radio",
name: grpName
}));
buttons.push(self._createElement("label", {
"for": idPre + name,
title: tip,
name: name,
"class": css
}));
return buttons;
};
wijeditor.prototype._createImageCheckButton = function (tip, idPre, css, name) {
var self = this, buttons = [];
buttons.push(self._createElement("input", {
id: idPre + name,
type: "checkbox"
}));
buttons.push(self._createElement("label", {
"for": idPre + name,
title: tip,
name: name,
"class": css
}));
return buttons;
};
wijeditor.prototype._createRibbonList = function () {
return this._createSpan(css_ribbon_list);
};
wijeditor.prototype._createDropdownButton = function (tip, name, text, items, idPrefix) {
var self = this, divBtn = self._createElement("div", {
title: tip,
"class": css_ribbon_dropdownbutton
}), ulDrpList = self._createElement("ul");
divBtn.add(self._createTextButton(tip, name, text));
divBtn.add(ulDrpList);
$.each(items, function (idx, item) {
var liDrpBtn = self._createElement("li"), btns = self._createTextRadioButton(item.tip, idPrefix, item.name, name, item.text);
$.each(btns, function (i, btn) {
liDrpBtn.add(btn);
});
ulDrpList.add(liDrpBtn);
});
return divBtn;
};
wijeditor.prototype._createSplitButton = function (tip, css, name, text, items) {
var self = this, divBtn = self._createElement("div", {
title: tip,
"class": css_ribbon_splitbutton
}), ulDrpList = self._createElement("ul");
divBtn.add(self._createBigButton(tip, css, name, text));
divBtn.add(self._createElement("button", {
"class": css_ribbon_bigbutton
}));
divBtn.add(ulDrpList);
$.each(items, function (idx, item) {
var liDrpBtn = self._createElement("li");
liDrpBtn.add(self._createButton(item.tip, item.css, item.name, item.text));
ulDrpList.add(liDrpBtn);
});
return divBtn;
};
wijeditor.prototype._createButtonByCommand = //get special button
function (cmd) {
var self = this, button, buttoninfo = buttonInfoAsCommand[cmd], cmdName;
if(!buttoninfo) {
return;
}
cmdName = buttoninfo.name;
switch(cmdName) {
case cmd_blockquote:
case cmd_form:
case cmd_imagebutton:
case cmd_textarea:
case cmd_button:
case cmd_textbox:
case cmd_listbox:
case cmd_password:
case cmd_dropdownlist:
case cmd_hiddenfield:
case cmd_radio:
case cmd_checkbox:
case cmd_insertcolumn:
case cmd_insertrow:
case cmd_insertcell:
case cmd_splitcell:
case cmd_mergecell:
case cmd_removecolumn:
case cmd_removerow:
case cmd_removecell:
case cmd_removeformat:
case cmd_insertbreak:
case cmd_insertparagraph:
case cmd_insertprintbreak:
case cmd_fullscreen:
case cmd_undo:
case cmd_redo:
case cmd_cut:
case cmd_copy:
case cmd_paste:
case cmd_date:
case cmd_wordwrap:
case cmd_backcolor:
case cmd_fontcolor:
case cmd_preview:
case cmd_cleanup:
case cmd_media:
case cmd_specialchar:
case cmd_template:
case cmd_imagebrowser:
case cmd_insertcode:
case cmd_inserthr:
case cmd_selectall:
button = self._createButton(buttoninfo.tip, buttoninfo.css, cmdName);
break;
case cmd_find:
case cmd_inspect:
button = self._createButton(buttoninfo.tip, buttoninfo.css, cmdName, buttoninfo.text);
break;
case cmd_borders:
case cmd_subscript:
case cmd_superscript:
case cmd_bold:
case cmd_italic:
case cmd_underline:
case cmd_strike:
button = self._createImageCheckButton(buttoninfo.tip, self.id_prefix, buttoninfo.css, cmdName);
break;
case cmd_designview:
case cmd_splitview:
case cmd_sourceview:
case cmd_alignleft:
case cmd_aligncenter:
case cmd_alignright:
case cmd_alignfull:
case cmd_outdent:
case cmd_indent:
case cmd_numberedlist:
case cmd_bulletedlist:
button = self._createImageRadioButton(buttoninfo.tip, self.id_prefix, buttoninfo.css, cmdName, buttoninfo.grpname);
break;
case cmd_table:
button = self._createSplitButton("Table", css_ribbon_table, cmd_table, "Table", [
{
tip: "Insert Table",
css: css_ribbon_inserttable,
name: cmd_inserttable,
text: "Insert"
},
{
tip: "Edit Table",
css: css_ribbon_edittable,
name: cmd_edittable,
text: "Edit"
}
]);
break;
case cmd_save:
if(self.options.mode === "ribbon") {
button = self._createBigButton(buttoninfo.tip, buttoninfo.css, cmdName, buttoninfo.text);
} else {
button = self._createButton(buttoninfo.tip, css_ribbon_save16, cmdName);
}
break;
case cmd_link:
if(self.options.mode === "ribbon") {
button = self._createBigButton(buttoninfo.tip, buttoninfo.css, cmdName, buttoninfo.text);
} else {
button = self._createButton(buttoninfo.tip, css_ribbon_link16, cmdName);
}
break;
case cmd_fontname:
button = self._createDropdownButton("Font Name", cmd_fontname, "Font Name", [
{
tip: "Arial",
name: "fn1",
text: "Arial"
},
{
tip: "Courier New",
name: "fn2",
text: "Courier New"
},
{
tip: "Garamond",
name: "fn3",
text: "Garamond"
},
{
tip: "Tahoma",
name: "fn4",
text: "Tahoma"
},
{
tip: "Times New Roman",
name: "fn5",
text: "Times New Roman"
},
{
tip: "Verdana",
name: "fn6",
text: "Verdana"
},
{
tip: "Wingdings",
name: "fn7",
text: "Wingdings"
}
], self.id_prefix);
break;
case cmd_fontsize:
button = self._createDropdownButton("Font Size", cmd_fontsize, "Font Size", [
{
tip: "VerySmall",
name: "xx-small",
text: "VerySmall"
},
{
tip: "Smaller",
name: "x-small",
text: "Smaller"
},
{
tip: "Small",
name: "small",
text: "Small"
},
{
tip: "Medium",
name: "medium",
text: "Medium"
},
{
tip: "Large",
name: "large",
text: "Large"
},
{
tip: "Larger",
name: "x-large",
text: "Larger"
},
{
tip: "VeryLarge",
name: "xx-large",
text: "VeryLarge"
}
], self.id_prefix);
break;
case cmd_spelling:
break;
}
return button;
};
wijeditor.prototype._createActionGroup = //end of special button
function () {
var self = this, rbActionGrp = self._createElement("li"), rbList = self._createRibbonList();
//save button
rbActionGrp.add(self._createButtonByCommand("Save"));
//undo/redo list
rbActionGrp.add(rbList);
rbList.add(self._createButtonByCommand("Undo"));
rbList.add(self._createButtonByCommand("Redo"));
//preview/clean up list
rbList = self._createRibbonList();
rbActionGrp.add(rbList);
rbList.add(self._createButtonByCommand("Preview"));
rbList.add(self._createButtonByCommand("Cleanup"));
//cut/copy/paste list
rbList = self._createRibbonList();
rbActionGrp.add(rbList);
rbList.add(self._createButtonByCommand("Cut"));
rbList.add(self._createButtonByCommand("Copy"));
rbList.add(self._createButtonByCommand("Paste"));
rbList.add(self._createButtonByCommand("SelectAll"));
//action name
rbActionGrp.add(self._createElement("div", "Actions"));
return rbActionGrp;
};
wijeditor.prototype._createFontGroup = function () {
var self = this, rbFontGrp = self._createElement("li"), rbList = self._createRibbonList();
//font name.
rbFontGrp.add(self._createButtonByCommand("FontName"));
//font size.
rbFontGrp.add(self._createButtonByCommand("FontSize"));
//bgcolor/fontcolor list
rbFontGrp.add(rbList);
rbList.add(self._createButtonByCommand("BackColor"));
rbList.add(self._createButtonByCommand("ForeColor"));
//bold/italic/underline/strike/sub/sup list
rbList = self._createRibbonList();
rbFontGrp.add(rbList);
$.each(self._createButtonByCommand("Bold"), function (idx, btn) {
rbList.add(btn);
});
$.each(self._createButtonByCommand("Italic"), function (idx, btn) {
rbList.add(btn);
});
$.each(self._createButtonByCommand("UnderLine"), function (idx, btn) {
rbList.add(btn);
});
$.each(self._createButtonByCommand("StrikeThrough"), function (idx, btn) {
rbList.add(btn);
});
$.each(self._createButtonByCommand("SubScript"), function (idx, btn) {
rbList.add(btn);
});
$.each(self._createButtonByCommand("SuperScript"), function (idx, btn) {
rbList.add(btn);
});
//template list
rbList = self._createRibbonList();
rbFontGrp.add(rbList);
rbList.add(self._createButtonByCommand("Template"));
//remove format list
rbList = self._createRibbonList();
rbFontGrp.add(rbList);
rbList.add(self._createButtonByCommand("RemoveFormat"));
//action name
rbFontGrp.add(self._createElement("div", "Font"));
return rbFontGrp;
};
wijeditor.prototype._createParaGroup = function () {
var self = this, rbParaGrp = self._createElement("li"), rbList = self._createRibbonList();
//justifyleft/justifycenter/justifyright/justifyfull list
rbParaGrp.add(rbList);
$.each(self._createButtonByCommand("JustifyLeft"), function (idx, btn) {
rbList.add(btn);
});
$.each(self._createButtonByCommand("JustifyCenter"), function (idx, btn) {
rbList.add(btn);
});
$.each(self._createButtonByCommand("JustifyRight"), function (idx, btn) {
rbList.add(btn);
});
$.each(self._createButtonByCommand("JustifyFull"), function (idx, btn) {
rbList.add(btn);
});
//borders list
rbList = self._createRibbonList();
rbParaGrp.add(rbList);
$.each(self._createButtonByCommand("Border"), function (idx, btn) {
rbList.add(btn);
});
//numberedlist/bulletedlist list
rbList = self._createRibbonList();
rbParaGrp.add(rbList);
$.each(self._createButtonByCommand("NumberedList"), function (idx, btn) {
rbList.add(btn);
});
$.each(self._createButtonByCommand("BulletedList"), function (idx, btn) {
rbList.add(btn);
});
//outdent/indent list
rbList = self._createRibbonList();
rbParaGrp.add(rbList);
$.each(self._createButtonByCommand("Outdent"), function (idx, btn) {
rbList.add(btn);
});
$.each(self._createButtonByCommand("Indent"), function (idx, btn) {
rbList.add(btn);
});
//action name
rbParaGrp.add(self._createElement("div", "Paragraph"));
return rbParaGrp;
};
wijeditor.prototype._createReviewGroup = function () {
var self = this, rbReviewGrp = self._createElement("li");
//inspect/find
rbReviewGrp.add(self._createButtonByCommand("Inspect"));
rbReviewGrp.add(self._createButtonByCommand("Find"));
//action name
rbReviewGrp.add(self._createElement("div", "Review"));
return rbReviewGrp;
};
wijeditor.prototype._createTablesGroup = function () {
var self = this, rbTablesGrp = self._createElement("li"), rbList = self._createRibbonList();
//table button
rbTablesGrp.add(self._createButtonByCommand("Table"));
//insertcol/insertrow/insertcell list
rbTablesGrp.add(rbList);
rbList.add(self._createButtonByCommand("InsertColumn"));
rbList.add(self._createButtonByCommand("InsertRow"));
rbList.add(self._createButtonByCommand("InsertCell"));
//splitcell/mergecell/insertcell list
rbList = self._createRibbonList();
rbTablesGrp.add(rbList);
rbList.add(self._createButtonByCommand("SplitCell"));
rbList.add(self._createButtonByCommand("MergeCell"));
//deletecol/deleterow/deletecell list
rbList = self._createRibbonList();
rbTablesGrp.add(rbList);
rbList.add(self._createButtonByCommand("DeleteColumn"));
rbList.add(self._createButtonByCommand("DeleteRow"));
rbList.add(self._createButtonByCommand("DeleteCell"));
//action name
rbTablesGrp.add(self._createElement("div", "Tables"));
return rbTablesGrp;
};
wijeditor.prototype._createBreaksGroup = function () {
var self = this, rbBreaksGrp = self._createElement("li");
//insertbreak/insertparagraph/insertprintpagebreak/inserthr
rbBreaksGrp.add(self._createButtonByCommand("InsertBreak"));
rbBreaksGrp.add(self._createButtonByCommand("InsertParagraph"));
rbBreaksGrp.add(self._createButtonByCommand("InsertPrint"));
rbBreaksGrp.add(self._createButtonByCommand("InsertHR"));
//action name
rbBreaksGrp.add(self._createElement("div", "Breaks"));
return rbBreaksGrp;
};
wijeditor.prototype._createFormsGroup = function () {
var self = this, rbFormsGrp = self._createElement("li"), rbList = self._createRibbonList();
//form list
rbFormsGrp.add(rbList);
rbList.add(self._createButtonByCommand("Form"));
//textarea/textbox/password/hidden field list
rbList = self._createRibbonList();
rbFormsGrp.add(rbList);
rbList.add(self._createButtonByCommand("TextArea"));
rbList.add(self._createButtonByCommand("TextBox"));
rbList.add(self._createButtonByCommand("PasswordField"));
rbList.add(self._createButtonByCommand("HiddenField"));
//image button/button list
rbList = self._createRibbonList();
rbFormsGrp.add(rbList);
rbList.add(self._createButtonByCommand("Image"));
rbList.add(self._createButtonByCommand("Button"));
//listbox/dropdownlist/radio/checkbox list
rbList = self._createRibbonList();
rbFormsGrp.add(rbList);
rbList.add(self._createButtonByCommand("List"));
rbList.add(self._createButtonByCommand("DropDownList"));
rbList.add(self._createButtonByCommand("Radio"));
rbList.add(self._createButtonByCommand("CheckBox"));
//action name
rbFormsGrp.add(self._createElement("div", "Forms"));
return rbFormsGrp;
};
wijeditor.prototype._createSpecialGroup = function () {
var self = this, rbSpecialGrp = self._createElement("li");
//link button
rbSpecialGrp.add(self._createButtonByCommand("Link"));
//imagebrowser/media/specialchar/datetime list
rbSpecialGrp.add(self._createButtonByCommand("InsertImage"));
rbSpecialGrp.add(self._createButtonByCommand("Media"));
rbSpecialGrp.add(self._createButtonByCommand("InsertSpecialChar"));
rbSpecialGrp.add(self._createButtonByCommand("InsertDate"));
//action name
rbSpecialGrp.add(self._createElement("div", "Special"));
return rbSpecialGrp;
};
wijeditor.prototype._getDefaultRibbonMarkup = function () {
var self = this, rb = self._createElement("div"), rbTabs = self._createElement("ul"), rbFmtTab = self._createElement("li"), rbIstTab = self._createElement("li"), rbFmtPnl = self._createElement("div", {
id: self.id_prefix + "format"
}), rbIstPnl = self._createElement("div", {
id: self.id_prefix + "insert"
}), rbFmtGrps = self._createElement("ul"), rbIstGrps = self._createElement("ul");
//ribbon tab.
rb.add(rbTabs);
rb.add(rbFmtPnl);
rb.add(rbIstPnl);
rbTabs.add(rbFmtTab);
rbTabs.add(rbIstTab);
rbFmtTab.add(self._createElement("a", "Format", {
href: "#" + self.id_prefix + "format"
}));
rbIstTab.add(self._createElement("a", "Insert", {
href: "#" + self.id_prefix + "insert"
}));
//format groups
rbFmtPnl.add(rbFmtGrps);
//action group.
rbFmtGrps.add(self._createActionGroup());
//font group.
rbFmtGrps.add(self._createFontGroup());
//para group.
rbFmtGrps.add(self._createParaGroup());
//review group.
rbFmtGrps.add(self._createReviewGroup());
//insert groups
rbIstPnl.add(rbIstGrps);
//tables group.
rbIstGrps.add(self._createTablesGroup());
//breaks group.
rbIstGrps.add(self._createBreaksGroup());
//forms group.
rbIstGrps.add(self._createFormsGroup());
//special group.
rbIstGrps.add(self._createSpecialGroup());
return rb.render();
};
wijeditor.prototype._getRibbonModesMarkup = function () {
var self = this, rb = self._createDiv(css_ribbon_modes), rbList = self._createRibbonList(), editorFooter = self.element.find(".wijeditor-footer"), wysiwyg, split, code, wordwrap, fullscreen;
//added for localization
if(editorFooter.length > 0) {
wysiwyg = $(editorFooter.find("." + css_ribbon_designview));
if(wysiwyg.length > 0) {
buttonInfoAsCommand.Wysiwyg.tip = wysiwyg.attr("title") || buttonInfoAsCommand.Wysiwyg.tip;
}
split = $(editorFooter.find("." + css_ribbon_splitview));
if(split.length > 0) {
buttonInfoAsCommand.Split.tip = split.attr("title") || buttonInfoAsCommand.Split.tip;
}
code = $(editorFooter.find("." + css_ribbon_sourceview));
if(code.length > 0) {
buttonInfoAsCommand.Code.tip = code.attr("title") || buttonInfoAsCommand.Code.tip;
}
wordwrap = $(editorFooter.find("." + css_ribbon_wordwrap));
if(wysiwyg.length > 0) {
buttonInfoAsCommand.Wordwrap.tip = wordwrap.attr("title") || buttonInfoAsCommand.Wordwrap.tip;
}
fullscreen = $(editorFooter.find("." + css_ribbon_fullscreen));
if(wysiwyg.length > 0) {
buttonInfoAsCommand.FullScreen.tip = fullscreen.attr("title") || buttonInfoAsCommand.FullScreen.tip;
}
editorFooter.remove();
}
rb.add(rbList);
$.each(self._createButtonByCommand("Wysiwyg"), function (idx, btn) {
rbList.add(btn);
});
$.each(self._createButtonByCommand("Code"), function (idx, btn) {
rbList.add(btn);
});
$.each(self._createButtonByCommand("Split"), function (idx, btn) {
rbList.add(btn);
});
rb.add(self._createButtonByCommand("Wordwrap"));
rb.add(self._createButtonByCommand("FullScreen"));
return rb.render();
};
wijeditor.prototype._getSimpleToolBar = function (simpleModeCommands) {
var self = this, button, rb = self._createDiv("");
$.each(simpleModeCommands, function (idx, cmd) {
button = self._createButtonByCommand(cmd);
if(button) {
if($.inArray(cmd, imageTypeButton) !== -1) {
$.each(button, function (idx, btn) {
rb.add(btn);
});
} else {
rb.add(button);
}
}
});
return rb.render();
};
wijeditor.prototype._editorify = function () {
var self = this, element = self.element, width = element.width(), height = element.height(), o = self.options, mode = o.mode, container, content, filterCustomSimpleModeCommands, ribbons, footer, $content, text;
self._oriStyle = element.attr("style");
self._oriContent = element.html();
self._oriEleWidth = width;
self._oriEleHeight = height;
if(element.is("textarea")) {
if(mode === "ribbon") {
self.$ribbon = $(self._getDefaultRibbonMarkup());
} else if(mode === "bbcode") {
self.$ribbon = $(self._getSimpleToolBar(defaultBBCodeModeCommands));
} else {
if(o.simpleModeCommands && o.simpleModeCommands.length !== 0) {
//Note: filter table command
filterCustomSimpleModeCommands = $.grep(o.simpleModeCommands, function (n, i) {
return n !== "Table";
}, undefined);
self.$ribbon = $(self._getSimpleToolBar(filterCustomSimpleModeCommands));
} else {
self.$ribbon = $(self._getSimpleToolBar(defaultSimpleModeCommands));
}
}
if(o.text) {
element.val(o.text);
}
self.sourceView = element;
self.editor = element.wrap("<div></div>").parent();
self.editor.width(width).height(height);
} else {
self.editor = element;
self.$ribbon = element.children(":eq(0)");
$content = element.children(":eq(1)");
if($content.is("textarea")) {
if(o.text) {
$content.val(o.text);
}
self.sourceView = $content;
} else {
if(o.text) {
text = o.text;
} else {
text = $content.html();
}
$content.remove();
self.sourceView = $("<textarea></textarea>").val(text);
}
}
container = $("<div class='" + css_editor_container + "'></div>");
self.dialog = $("<div class ='" + css_editor + "'></div>");
self.subDialog = $("<div class ='" + css_editor + "'></div>");
self.editor.addClass(css_editor).addClass(self.options.wijCSS.widget).append(container).append(self.dialog).append(self.subDialog);
//fixed bug for customContextMenu
self._createMenuMarkUp(self, o);
//head
//ribbon
self.$ribbon.wrap("<a href='javascript:void(null)'></a>").parent().appendTo("<div class='" + css_editor_header + " ui-widget-header ui-helper-clearfix ui-corner-top'></div>").parent().appendTo(container);
//content
content = $("<div class='" + css_editor_content + "'></div>").appendTo(container);
self.designView = $("<iframe frameborder='0'></iframe>");
self.designView.wrap("<div></div>").parent().appendTo(content);
self.sourceView.wrap("<div></div>").parent().appendTo(content);
ribbons = [
self.$ribbon
];
self.$modes = $(self._getRibbonModesMarkup());
//footer
if(o.showFooter) {
footer = $("<div class='" + css_editor_footer + " " + "ui-widget ui-widget-content ui-state-default'></div>");
container.append(footer);
footer.append("<div class='" + css_editor_pathselector + "'></div>");
self.$modes.appendTo(footer);
ribbons.push(self.$modes);
}
$.each(ribbons, function (idx, ribbon) {
ribbon.wijribbon({
click: function (e, data) {
self._ribbonCommand(data.commandName, data.name);
self._trigger('commandButtonClick', e, data);
}
});
});
};
wijeditor.prototype._createMenuMarkUp = //fixed bug for customContextMenu
function (self, o) {
if(o.customContextMenu && !$.browser.webkit) {
self.contextMenu = $("<ul>" + "<li _c1buttoncmd='cut'><a>" + this.localizeString("contextMenuCut", "Cut") + "</a></li>" + "<li _c1buttoncmd='copy'><a>" + this.localizeString("contextMenuCopy", "Copy") + "</a></li>" + "<li _c1buttoncmd='paste'><a>" + this.localizeString("contextMenuPaste", "Paste") + "</a></li></ul>");
$("<a href='#'></a>").append(self.contextMenu).appendTo(self.editor);
}
};
wijeditor.prototype._handleDisabledOption = function (disabled, ele) {
var self = this;
if(disabled) {
if(!self.disabledDiv) {
self.disabledDiv = self._createDisabledDiv(ele);
}
//self.disabledDiv.appendTo("body");
$("body").focus();
self.disabledDiv.appendTo(self.editor);
} else {
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
}
};
wijeditor.prototype._createDisabledDiv = function (outerEle) {
var self = this, ele = //Change your outerelement here
outerEle ? outerEle : self.element, disabledWidth = //eleOffset = ele.offset(),
ele.outerWidth(), disabledHeight = ele.outerHeight();
return $("<div></div>").addClass("ui-state-disabled").css({
"z-index": "99999",
position: //position: "absolute",
"relative",
"background-color": "lightgray",
width: disabledWidth,
height: disabledHeight,
left: //left: eleOffset.left,
//top: eleOffset.top
0,
top: -disabledHeight
});
};
wijeditor.prototype._initElements = function () {
var self = this, o = self.options, contentHeight = self.element.height() - self._getHeader().outerHeight(true) - self._getFooter().outerHeight(true), buttonStates = {
};
self._getContent().height(contentHeight).wijsplitter({
showExpander: false,
orientation: "horizontal",
panel1: {
scrollBars: "none",
collapsed: false
},
panel2: {
scrollBars: "none",
collapsed: true
}
});
self.sourceView.css("width", "").css("height", "");
self._addHandlerToDesignView();
//for adding default font style to editor by wh at 2012/1/18
self._addDefaultFontStyleToDesignView();
//end for adding
self._createWijMenu();
//update for bbcode hiding the path by wh at 2011/9/26
//if (!o.showPathSelector) {
if(!o.showPathSelector || self.options.mode === "bbcode") {
//end for hiding path
self._getPathSelector().hide();
}
self._ribbonCommand(o.editorMode);
//update for supporting fullscreenmode by wuhao at 2011/8/2
if(o.fullScreenMode) {
//fullScreen = self.options.fullScreenMode;
self._setFullScreen(o.fullScreenMode);
}
//end for fullscreenmode
buttonStates[cmd_redo] = true;
buttonStates[cmd_undo] = true;
self.$ribbon.wijribbon(setButtonsDisabled, buttonStates);
self._handleWinDocumentKeyDown()//update for 32998 at 2013-2-19
;
};
wijeditor.prototype._handleWinDocumentKeyDown = function () {
var self = this;
$(document).keydown(function (e) {
if(self.options.disabled) {
return;
}
switch(e.keyCode) {
case 27:
self._escActionAssociated();
break;
}
});
};
wijeditor.prototype._setOption = function (key, value) {
var self = this, o = self.options, oldMode = o.mode, ribbonParent = self.$ribbon.parent(), oldCustomContextMenu = o.customContextMenu;
$.Widget.prototype._setOption.apply(self, arguments);
if(key === "fullScreenMode") {
o.fullScreenMode = value;
self._setFullScreen(value);
} else if(key === "showPathSelector") {
o.showPathSelector = value;
if(value) {
self._getPathSelector().show();
} else {
self._getPathSelector().hide();
}
} else if(key === "editorMode") {
o.editorMode = value;
self._ribbonCommand(value);
} else if(key === "fullScreenContainerSelector") {
o.fullScreenContainerSelector = value;
if(self.options.fullScreenMode) {
self._setFullScreen(true);
}
} else if(key === "disabled") {
self._handleDisabledOption(value, self.editor);
} else if(key === "showFooter") {
if(value) {
if(!($("." + css_editor_footer).is(":visible"))) {
$("." + css_editor_footer).show();
}
} else {
if(($("." + css_editor_footer).is(":visible"))) {
$("." + css_editor_footer).hide();
}
}
} else if(key === "commandButtonClick") {
o.commandButtonClick = value;
} else if(key === "text") {
o.text = value;
self.setText(value);
} else if(key === "customContextMenu") {
//fixed bug for customContextMenu
if(oldCustomContextMenu === value) {
return;
}
if(value) {
if(!self.contextMenu) {
self._createMenuMarkUp(self, o);
}
self._createWijMenu();
} else {
self.contextMenu[self._contextMenuWidgetName()]("destroy").remove();
self.contextMenu = undefined;
}
} else if(key === "mode" && value !== oldMode) {
self.$ribbon.wijribbon("destroy");
self.$ribbon.remove();
if(value === "ribbon") {
self.$ribbon = $(self._getDefaultRibbonMarkup());
} else if(value === "bbcode") {
self.$ribbon = $(self._getSimpleToolBar(defaultBBCodeModeCommands));
} else {
self.$ribbon = $(self._getSimpleToolBar(defaultSimpleModeCommands));
}
ribbonParent.append(self.$ribbon);
self.$ribbon.wijribbon({
click: function (e, data) {
self._ribbonCommand(data.commandName, data.name);
self._trigger('commandButtonClick', e, data);
}
});
self._ribbonCommand(o.editorMode);
}
};
wijeditor.prototype._getHeader = function () {
return $("." + css_editor_header, this.editor);
};
wijeditor.prototype._getContent = function () {
return $("." + css_editor_content, this.editor);
};
wijeditor.prototype._getFooter = function () {
return $("." + css_editor_footer, this.editor);
};
wijeditor.prototype._getPathSelector = function () {
return $("." + css_editor_pathselector, this.editor);
};
wijeditor.prototype._getModes = function () {
return $("." + css_ribbon_modes, this.editor);
};
wijeditor.prototype._getDesignView = function () {
return this.designView;
};
wijeditor.prototype._getDesignViewWindow = function () {
var $designView = this.designView;
if($designView && $designView.length > 0) {
return $designView[0].contentWindow;
}
return null;
};
wijeditor.prototype._getDesignViewDocument = function () {
var win = this._getDesignViewWindow();
if(win) {
return win.document;
}
return null;
};
wijeditor.prototype._getDesignViewText = function () {
var doc = this._getDesignViewDocument();
if(doc && doc.body && doc.body.innerHTML) {
return doc.body.innerHTML;
}
return "";
};
wijeditor.prototype._setDesignViewText = function (text) {
var self = this, doc = this._getDesignViewDocument();
if(this.options.mode === "bbcode") {
//Note: maybe need to trim the text.
text = self._convertBBCodeToHtml(text);
}
if(doc && doc.body) {
doc.body.innerHTML = text;
}
self.options.text = text;
};
wijeditor.prototype._getDialog = function () {
return this.dialog;
};
wijeditor.prototype._getSubDialog = function () {
return this.subDialog;
};
wijeditor.prototype._initContentDocument = function () {
var self = this, text = self.sourceView.val(), doc = self._getDesignViewDocument();
if(self.options.mode === "bbcode") {
//Note: trim leading/trailing whitespace
//because when get the innerhtml from body, there
//are some whitespace on leading/trailing
text = self._convertBBCodeToHtml($.trim(text));
}
doc.open();
doc.write("<html style=\"width:100%;height:100%;" + (self.options.enabled ? "cursor:text;" : "") + "\"><head><title></title><style id=\"__wijStyle\" " + " type=\"text/css\" >table,td,tr{border: 1px #acacac dashed;}" + "</style></head><body>" + text + "</body></html>");
doc.close();
//update for 24254 issue
if(!tblBorderShowing) {
$('#__wijStyle', doc).prop("disabled", !tblBorderShowing);
}
if(self.element.attr("accesskey")) {
$(doc.body).attr("accesskey", self.element.attr("accesskey"));
self.element.removeAttr("accesskey");
}
undoBuffers = [];
undoBuffers.push(text);
undoSteps = 0;
};
wijeditor.prototype._addHandlerToDesignView = function () {
var self = this, win = self._getDesignViewWindow(), doc = win.document;
self._initContentDocument();
self._loadDesignView();
};
wijeditor.prototype._loadDesignView = function () {
var self = this, win = self._getDesignViewWindow(), doc = win.document;
if($.browser.mozilla) {
setTimeout(self._setDesignModeForFF, 1000, self);
} else {
self._setContentEditable(doc, true);
}
if($.browser.msie) {
self._setContentSpellCheck(doc, false);
}
self.sourceView.bind('blur.' + self.widgetName, function (e) {
self._onSourceViewBlur();
});
//add for any change happens, the text would be saved by wh at 2011/12/07
self.sourceView.bind('keyup.' + self.widgetName, function (e) {
self._onSourceViewBlur();
});
//end for change happens
//note: in safari and chrome, the source view is show null
//update by wh at 2011/9/19
//if ($.browser.msie) {
if(!$.browser.mozilla) {
//end by wh
$(win).blur(function (e) {
self._onDesignViewBlur(e);
});
} else {
$(doc).bind('blur.' + self.widgetName, function (e) {
self._onDesignViewBlur(e);
});
}
$(doc).bind('mouseup.' + self.widgetName, function (e) {
self._onDesignViewMouseUp(e);
}).bind('keydown.' + self.widgetName, function (e) {
self._onDesignViewKeyDown(e);
}).bind('keyup.' + self.widgetName, function (e) {
self._onDesignViewKeyUp(e);
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(e);
//end for change happens
});
};
wijeditor.prototype._addDefaultFontStyleToDesignView = function () {
var self = this, o = self.options, doc = self._getDesignViewDocument(), defaultFontName = o.defaultFontName, defaultFontSize = o.defaultFontSize, defaultFontStyleString = "<style type=\"text/css\"> body {";
if((defaultFontName === "" || defaultFontName === null) && (defaultFontSize === "" || defaultFontSize === null)) {
return;
}
if(defaultFontName !== "" && defaultFontName !== null) {
defaultFontStyleString += "font-family: " + defaultFontName + ";";
}
if(o.defaultFontSize !== "" && o.defaultFontSize !== null) {
defaultFontStyleString += " font-size: " + defaultFontSize + ";";
}
defaultFontStyleString += "}</style>";
//update for fix issue 19693 by wh at 2012/2/3
//$(defaultFontStyleString).appendTo(doc.head);
window.setTimeout(function () {
$(defaultFontStyleString).appendTo($("head", doc));
}, 200);
//end for issue 19693
//init the button state
self._setFontStyleButtonState(defaultFontName, cmd_fontname);
self._setFontStyleButtonState(defaultFontSize, cmd_fontsize);
};
wijeditor.prototype._setFontStyleButtonState = function (defaultValue, cmd) {
var defaultKey = "";
if(!defaultValue || defaultValue === null) {
return;
}
$.each(this.$ribbon.wijribbon("getDropdownList", cmd), function (key, value) {
if(value.toUpperCase() === defaultValue.toUpperCase()) {
defaultKey = key;
return false;
}
});
this.$ribbon.wijribbon(setButtonChecked, defaultKey, true, cmd);
};
wijeditor.prototype._setDesignModeForFF = function (self) {
var dvDoc = self._getDesignViewDocument();
if(dvDoc) {
dvDoc.designMode = "on";
}
};
wijeditor.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this;
self.element.html(self._oriContent);
self.element.removeAttr("tabindex");
if(self._oriStyle === undefined) {
self.element.removeAttr("style");
} else {
self.element.attr("style", self._oriStyle);
}
//self.editor.replaceWith(self.element);
self.element.insertBefore(self.editor);
self.element.unbind('.' + self.widgetName);
self.editor.remove();
$.Widget.prototype.destroy.call(self);
};
wijeditor.prototype.showEditorDialog = /** @ignore */
function (dialogCmd) {
switch(dialogCmd) {
case cmd_inserttable:
case cmd_template:
case cmd_imagebrowser:
case cmd_inspect:
case cmd_find:
case cmd_specialchar:
case cmd_media:
case cmd_cleanup:
case cmd_link:
case cmd_backcolor:
case cmd_fontcolor:
case cmd_insertcode:
this._ribbonCommand(dialogCmd);
break;
default:
wijAlert("Cannot find the dialog with command name '" + dialogCmd + "'!");
break;
}
};
wijeditor.prototype.executeEditorAction = /** @ignore */
function (command, parentCmd) {
this._ribbonCommand(command, parentCmd);
};
wijeditor.prototype._isFontSizeCustomized = function () {
if(isFontSizeCustomized !== null) {
return isFontSizeCustomized;
}
var fontSizes = this.$ribbon.wijribbon("getDropdownList", cmd_fontsize), fss = [
cmd_verysmall,
cmd_smaller,
cmd_small,
cmd_medium,
cmd_large,
cmd_larger,
cmd_verylarge
];
isFontSizeCustomized = false;
$.each(fontSizes, function (key, value) {
if($.inArray(key, fss) === -1) {
isFontSizeCustomized = true;
return false;
}
});
return isFontSizeCustomized;
};
wijeditor.prototype._fontSizeCommand = function (cmd) {
var self = this, doc = self._getDesignViewDocument(), docSelection, arg = //docSelection = self._getDesignViewWindow().getSelection(),
4, fontSize = "font-size", $spans = [];
if(self._getDesignViewWindow().getSelection) {
docSelection = self._getDesignViewWindow().getSelection();
}
switch(cmd) {
case cmd_verysmall:
arg = 1;
break;
case cmd_smaller:
arg = 2;
break;
case cmd_small:
arg = 3;
break;
case cmd_medium:
arg = 4;
break;
case cmd_large:
arg = 5;
break;
case cmd_larger:
arg = 6;
break;
case cmd_verylarge:
arg = 7;
break;
}
//Add comments by RyanWu@20110915.
//For implementing the font-size
//support px/pt etc other than only small/x-small/x-large/large...
//doc.execCommand("FontSize", false, arg);
if(!self._isFontSizeCustomized()) {
if($.browser.msie && wijParseInt($.browser.version) >= 9) {
if(docSelection && docSelection.rangeCount > 0) {
doc.execCommand("FontSize", false, arg);
}
} else {
doc.execCommand("FontSize", false, arg);
}
} else if($.browser.msie) {
self._formatFontSpan(doc, fontSize, cmd);
} else {
//Here we set fontsize to 4(temp value) because we just use
//execCommand to separate the html correctly
//and we will set the correct fontsize value to the replaced span.
doc.execCommand("FontSize", false, arg);
$.each($("font[size]", doc), function (idx, fs) {
$spans.push(self._replaceFontWithSpan($(fs), "size", fontSize, cmd));
});
self._setSelection($spans);
}
//end by RyanwWu@20110915.
if(self.options.mode === "bbcode" && !($.browser.msie)) {
self._convertFontStyleToStandTag();
}
self._addtoUndoBuffer();
};
wijeditor.prototype._fontNameCommand = function (cmd) {
var self = this, doc = self._getDesignViewDocument(), docSelection, fontNames = //docSelection = self._getDesignViewWindow().getSelection(),
self.$ribbon.wijribbon("getDropdownList", cmd_fontname), fontName;
if(self._getDesignViewWindow().getSelection) {
docSelection = self._getDesignViewWindow().getSelection();
}
$.each(fontNames, function (key, value) {
if(cmd === key) {
fontName = value;
return false;
}
});
//Add comments by RyanWu@20110915.
//For implementing the font-size
//support px/pt etc other than only small/smaller/larger/large...
//doc.execCommand("FontName", false, fontName);
if($.browser.msie && wijParseInt($.browser.version) >= 9) {
if(docSelection && docSelection.rangeCount > 0) {
doc.execCommand("FontName", false, fontName);
}
} else {
doc.execCommand("FontName", false, fontName);
}
if(self._isFontSizeCustomized() && $.browser.msie) {
self._formatFontSpan(doc, "font-family", fontName);
}
//end by RyanwWu@20110915.
self._addtoUndoBuffer();
};
wijeditor.prototype._formatFontSpan = //Add comments by RyanWu@20110922.
//For implementing the font-size
//support px/pt etc other than only small/smaller/larger/large...
function (doc, cssName, cssValue) {
var self = this, tempValue = cssValue, styleAttrName = "fontFamily", $spans = [];
if(cssName !== "font-family") {
tempValue = "c1-temp";
styleAttrName = "fontSize";
}
doc.execCommand("FontName", false, tempValue);
$.each($("font[face='" + tempValue + "']", doc), function (i, fn) {
var $span = self._replaceFontWithSpan($(fn), "face", cssName, cssValue), $children, idx;
$spans.push($span);
//1. remove all font-family style of the child spans.
//<span style="font-family:B">blah<span style="font-family:A">
//</span></span>,
//need remove the span whose font-family is A
$children = $("span." + css_formatspan, $span);
for(idx = $children.length - 1; idx >= 0; idx--) {
self._removeSpecifiedStyleSpan($($children[idx]), styleAttrName, cssName);
}
//2. remove duplicated spans.
//<span style="font-family:A">
//<span style="font-family:B">blah</span></span>
$.each($span, function (idx, span) {
$.each($(span).parents("span." + css_formatspan), function (i, parent) {
var $parent = $(parent);
if($parent.children().length > 1) {
return false;
}
if($parent.text() === $(span).text()) {
self._removeSpecifiedStyleSpan($parent, styleAttrName, cssName);
}
});
});
});
self._setSelection($spans);
};
wijeditor.prototype._setSelection = function ($nodes, start, length) {
var win = this._getDesignViewWindow(), doc = win.document, range, startNode, endNode, selection, len = 0;
try {
if($.browser.msie) {
// range.moveStart("character", -text.length);
// range.moveEnd("character", -text.length);
// range.collapse(true);
// range.moveStart("character", start);
// range.moveEnd("character", length);
//range.moveStart("textedit", -1);
// range.moveStart("textedit", -1);
// range.collapse(true);
// range.moveStart("character", start);
// range.moveEnd("character", length);
range = doc.selection.createRange();
if($nodes) {
$.each($nodes, function (idx, $node) {
len += $node.text().length;
});
range.moveToElementText($nodes[0][0]);
range.collapse(true);
range.moveEnd("character", len);
} else {
range.moveStart("textedit", -1);
range.collapse(true);
range.moveStart("character", start);
range.moveEnd("character", length);
}
range.select();
} else {
selection = win.getSelection();
range = doc.createRange();
startNode = $nodes[0][0];
endNode = $nodes[$nodes.length - 1][0];
range.setStart(startNode, 0);
range.setEnd(endNode, endNode.childNodes.length);
selection.removeAllRanges();
selection.addRange(range);
}
} catch (e) {
}
};
wijeditor.prototype._replaceFontWithSpan = function ($fn, attrName, cssName, cssValue) {
$fn.wrap("<span class = '" + css_formatspan + "' style='" + cssName + ":" + cssValue + "'></span>");
var $span = $fn.parent();
$fn.removeAttr(attrName);
if(/<font\s*>/ig.test($span.html())) {
//$fn.replaceWith($fn.html());
$span.html($fn.html());
$fn.remove();
}
return $span;
};
wijeditor.prototype._removeSpecifiedStyleSpan = function ($span, styleAttrName, cssAttrName) {
var style, shouldRemove = true;
if($span[0].style[styleAttrName] !== "") {
$span.css(cssAttrName, "");
}
style = $span.attr("style");
if(style) {
$.each(style.split(';'), function (i, attr) {
var styleAttr = $.trim(attr).toLowerCase();
if(styleAttr !== "" && styleAttr.indexOf(cssAttrName) !== -1) {
shouldRemove = false;
return false;
}
});
}
if(shouldRemove) {
$span.replaceWith($span.html());
}
};
wijeditor.prototype._removeFormat = function () {
var self = this, doc = self._getDesignViewDocument(), buttonStates = {
};
doc.execCommand(cmd_removeformat, false, null);
if(self._isFontSizeCustomized() && $.browser.msie) {
self._removeFormatForIE(doc);
}
self._addtoUndoBuffer();
buttonStates[cmd_bold] = false;
buttonStates[cmd_italic] = false;
buttonStates[cmd_strike] = false;
buttonStates[cmd_underline] = false;
buttonStates[cmd_subscript] = false;
buttonStates[cmd_superscript] = false;
buttonStates[cmd_numberedlist] = false;
buttonStates[cmd_bulletedlist] = false;
buttonStates[cmd_alignleft] = false;
buttonStates[cmd_aligncenter] = false;
buttonStates[cmd_alignright] = false;
buttonStates[cmd_alignfull] = false;
self.$ribbon.wijribbon(setButtonsChecked, buttonStates);
};
wijeditor.prototype._removeFormatForIE = function (doc) {
var range = doc.selection.createRange(), htmlText = range.htmlText, text = range.text, start = 0, $parent = $(range.parentElement()), $body = $(doc.body), preHtml = "", sufHtml = "", specialStr = "__c1temp", specialCss = "c1-temp", tempSpan = "<span class='" + specialCss + "'>" + specialStr + "</span>", $tempSpan, $tempSibling, $spans, $span, idx, items;
//1. <span style="font-size:20pt">A[B</span>C]D
//2. <span style="font-size:20pt">A[B</span>CD<span style="font-size:30pt">EF]G</span>
//3. <span style="font-size:20pt">A[BC]D</span>
//4. <span style="font-family:arial"><span style="font-size:20pt">A[B</span>CD<span style="font-size:30pt">EF]G</span></span>
$parent.addClass("c1-app-parent");
range.pasteHTML(tempSpan);
start = $body.text().indexOf(specialStr);
$tempSpan = $("span." + specialCss, doc);
$tempSibling = $tempSpan;
$tempSpan.parentsUntil("body").each(function (index) {
if($(this).is(".c1-app-parent")) {
return false;
}
$tempSibling = $(this);
});
$tempSpan.html(htmlText);
$spans = $("span." + css_formatspan, $tempSpan);
for(idx = $spans.length - 1; idx >= 0; idx--) {
$span = $($spans[idx]);
$span.replaceWith($span.html());
}
if(!$tempSibling.is("." + specialCss)) {
$tempSibling.after($tempSpan);
}
$.each($tempSibling.parents("span." + css_formatspan), function (index, p) {
preHtml += "</span>";
sufHtml = "<span class='" + css_formatspan + "' style = '" + $(p).attr("style") + "'>" + sufHtml;
});
htmlText = $tempSpan.html();
$tempSpan.replaceWith(specialStr);
items = $body.html().split(specialStr);
$body.html(items[0] + preHtml + htmlText + sufHtml + items[1]);
$spans = $("span." + css_formatspan, doc);
for(idx = $spans.length - 1; idx >= 0; idx--) {
$span = $($spans[idx]);
if($span.text() === "") {
$span.replaceWith($span.html());
}
}
$(".c1-app-parent", doc).removeClass("c1-app-parent");
this._setSelection(null, start, text.length);
};
wijeditor.prototype._toggleFullScreen = //end by RyanwWu@20110922.
function () {
var self = this, o = self.options;
o.fullScreenMode = !o.fullScreenMode;
self._setFullScreen(o.fullScreenMode);
};
wijeditor.prototype._setFullScreen = function (fullScreenMode) {
var self = this, borderWidth = 1, header = self._getHeader(), footer = self._getFooter(), content = self._getContent(), cSelector = self.options.fullScreenContainerSelector, $container = $(cSelector), oriHtml = self._getDesignViewText(), width, height, contentHeight;
if(fullScreenMode) {
if($container.length === 0) {
$container = $(wijWindow);
cSelector = "body";
//note:add the block for preventing the scrollbar appear
self._oriDocOverFlow = $(document.documentElement).css("overflow");
$(document.documentElement).css({
overflow: "hidden"
});
//end for block
//note: if the content exclude the editor, the window still
//has the scroll, need to do some adjustment.
if(!$.browser.mozilla) {
window.scrollTo(0, 0);
}
$(wijWindow).bind("resize.wijeditor", function () {
self._fullscreenOnWindowResize();
});
}
width = $container.width();
height = $container.height() - 2 * borderWidth;
oriWidth = self.editor.width();
oriHeight = self.editor.height();
if(!$oriParent) {
$oriParent = self.editor.parent();
}
if(!self._replacedDiv) {
self._replacedDiv = $("<div />");
}
self.editor.after(self._replacedDiv);
$(cSelector).append(self.editor);
//Note: think of body and fullScreenContainerSelector
//update by wuhao 2011/8/6
// self.editor.css({
// width: width,
// height: height,
// position: "absolute",
// left: 0,
// top: 0
// });
self.editor.css({
width: width,
height: height,
position: ""
}).addClass(css_editor_fullscreen);
//end by wuhao
/*
self.sourceView.css({
width: width,
height: height
});*/
self.$ribbon.wijribbon("updateRibbonSize");
} else {
//if ($oriParent) {
// $oriParent.append(self.editor);
//}
self._replacedDiv.after(self.editor).remove();
self.editor.css({
width: oriWidth,
height: oriHeight,
position: "static"
}).removeClass(css_editor_fullscreen);
/*
self.sourceView.css({
width: oriWidth,
height: oriHeight
});*/
if(!self.options.fullScreenContainerSelector) {
$(document.documentElement).css({
overflow: self._oriDocOverFlow
});
}
$(wijWindow).unbind("resize.wijeditor");
self.$ribbon.wijribbon("updateRibbonSize");
}
contentHeight = self.editor.height() - header.outerHeight(true) - footer.outerHeight(true);
content.height(contentHeight).wijsplitter("refresh");
self._addHandlerToDesignView();
//for adding default font style to editor by wh at 2012/1/18
self._addDefaultFontStyleToDesignView();
//end for adding
//update: contextmenu don't show when fullscreen mode
//update by wh at 2011/10/10
self._createWijMenu();
//end for contextmenu
//update for fixing bug 20695
if($.browser.msie) {
window.setTimeout(function () {
if(self.options.mode === "bbcode") {
oriHtml = self._convertHtmlToBBCode($.trim(oriHtml));
}
self._setDesignViewText(oriHtml);
//for case 20731 fixing at 2012/4/23
if(wijParseInt($.browser.version) >= 9) {
self.sourceView.val(oriHtml);
}
}, 40);
}
};
wijeditor.prototype._createWijMenu = //fixed bug for customContextMenu
function () {
var self = this, doc = self._getDesignViewDocument();
if(self.contextMenu) {
self.contextMenu[self._contextMenuWidgetName()]({
orientation: 'vertical',
trigger: self.designView,
triggerEvent: 'rtclick',
showing: function (e, sublist) {
//update for fixing issue 20382 by wh at 2012/3/12
if($.browser.msie) {
rangeSelection = doc.selection.createRange();
}
//end for 20382 issue.
//sublist.element.show();
var offset = self.designView.offset(), contentWindowScrollLeft = $(($(self.designView)[0]).contentWindow).scrollLeft(), contentWindowScrollTop = $(($(self.designView)[0]).contentWindow).scrollTop(), menuOffsetLeft = offset.left + 2 - contentWindowScrollLeft, menuOffsetTop = offset.top - contentWindowScrollTop;
sublist.options.position = {
my: 'left+' + menuOffsetLeft + ' ' + 'top+' + menuOffsetTop,
at: 'right top',
of: e,
collision: //offset: (menuOffsetLeft) + " " + (menuOffsetTop),
'none none'
};
//sublist.element.hide();
},
animation: {
animated: "fade"
},
select: function (e, item) {
//update for fixing 20488 by wh at 2012/3/14
self._setIESelection();
//end for 20488 issue.
self._contextMenuItemClick(e, item);
//fixed a bug: the hover state remain after select
self.contextMenu[self._contextMenuWidgetName()]("deactivate");
}
});
}
};
wijeditor.prototype._fullscreenOnWindowResize = function () {
var self = this, header = self._getHeader(), footer = self._getFooter(), content = self._getContent(), contentHeight, fWidth = $(window).width(), fHeight = $(window).height();
self.editor.css({
width: fWidth,
height: fHeight
});
contentHeight = self.editor.height() - header.height() - footer.height();
content.height(contentHeight).wijsplitter("refresh");
//TODO
//$ribbon.wijribbon("updateRibbonSize");
};
wijeditor.prototype._saveText = //update for fixing issue 18777 by wuhao at 2011/12/15
function (arg) {
};
wijeditor.prototype._doSpellCheck = //end for fixing issue
function () {
};
wijeditor.prototype._ribbonCommand = function (cmd, parentCmd) {
var self = this, doc = self._getDesignViewDocument(), content = self._getContent(), elementName, selectedHtml, range;
if(parentCmd === cmd_fontname) {
self._fontNameCommand(cmd);
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(null);
//end for change happens
return;
}
if(parentCmd === cmd_fontsize) {
self._fontSizeCommand(cmd);
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(null);
//end for change happens
return;
}
//for case: 35318 issue 2013/3/28
if(!self.editor.hasClass("ui-helper-hidden-accessible")) {
self._setIEFocus();
}
switch(cmd) {
case cmd_blockquote:
if($.browser.msie) {
// we first change the block into <ADDRESS> tags,
// using the FormatBlock functionality of the execCommand
doc.execCommand("FormatBlock", false, "<ADDRESS>");
range = doc.selection.createRange();
range = $(range.parentElement()).closest("address");
if(range.length) {
// then sneakily we use regex's to replace
// <ADDRESS> tags with <BLOCKQUOTE> tags
range.replaceWith("<blockquote>" + range.html() + "</blockquote>");
// then we tidy any extra <BLOCKQUOTES>
//that have been unhelpfully added.
doc.body.innerHTML = doc.body.innerHTML.replace(/<BLOCKQUOTE>\s*?<BLOCKQUOTE>/gi, "<BLOCKQUOTE>");
doc.body.innerHTML = doc.body.innerHTML.replace(/<\/BLOCKQUOTE>\s*?<\/BLOCKQUOTE>/gi, "<\/BLOCKQUOTE>");
doc.body.innerHTML = doc.body.innerHTML.replace(/<BLOCKQUOTE>\s*?<\/BLOCKQUOTE>/gi, "");
}
} else {
doc.execCommand("FormatBlock", false, "<BLOCKQUOTE>");
}
self._addtoUndoBuffer();
self._setFocusNotIE();
break;
case cmd_form:
elementName = self._generateUniqueName('form');
self.insertHTML('<form id="' + elementName + '" name="' + elementName + '" method="post">' + elementName + '</form>');
self._setFocusNotIE();
break;
case cmd_imagebutton:
elementName = self._generateUniqueName('image');
self.insertHTML('<input id="' + elementName + '" name="' + elementName + '" type="image"' + ' value="' + elementName + '"/>');
self._setFocusNotIE();
break;
case cmd_textarea:
elementName = self._generateUniqueName('textarea');
self.insertHTML('<textarea id="' + elementName + '" name="' + elementName + '" rows="4" cols="48"></textarea>');
self._setFocusNotIE();
break;
case cmd_button:
elementName = self._generateUniqueName('button');
self.insertHTML('<input id="' + elementName + '" name="' + elementName + '" type="button"' + ' value="' + elementName + '"/>');
self._setFocusNotIE();
break;
case cmd_textbox:
elementName = self._generateUniqueName('textbox');
self.insertHTML('<input id="' + elementName + '" name="' + elementName + '" type="text"' + ' value="' + elementName + '"/>');
self._setFocusNotIE();
break;
case cmd_listbox:
elementName = self._generateUniqueName('list');
self.insertHTML('<select id="' + elementName + '" name="' + elementName + '" style="width: 120px" size="8"></select>');
self._setFocusNotIE();
break;
case cmd_password:
elementName = self._generateUniqueName('password');
self.insertHTML('<input id="' + elementName + '" name="' + elementName + '" type="password" value="' + elementName + '"/>');
self._setFocusNotIE();
break;
case cmd_dropdownlist:
elementName = self._generateUniqueName('dropdown');
self.insertHTML('<select id="' + elementName + '" name="' + elementName + '"></select>');
self._setFocusNotIE();
break;
case cmd_hiddenfield:
elementName = self._generateUniqueName('hidden');
self.insertHTML('<input id="' + elementName + '" name="' + elementName + '" type="hidden" value="' + elementName + '" />');
self._setFocusNotIE();
break;
case cmd_radio:
elementName = self._generateUniqueName('radiobox');
self.insertHTML('<input id="' + elementName + '" name="' + elementName + '" type="radio"' + ' value="' + elementName + '">' + '<label for="' + elementName + '">' + elementName + '</label></input>');
self._setFocusNotIE();
break;
case cmd_checkbox:
elementName = self._generateUniqueName('checkbox');
self.insertHTML('<input id="' + elementName + '" name="' + elementName + '" type="checkbox"' + ' value="' + elementName + '">' + '<label for="' + elementName + '">' + elementName + '</label></input>');
self._setFocusNotIE();
break;
case cmd_insertcolumn:
case cmd_insertrow:
case cmd_insertcell:
case cmd_splitcell:
case cmd_mergecell:
case cmd_removecolumn:
case cmd_removerow:
case cmd_removecell:
self._tableAction(cmd);
break;
case cmd_borders:
self._toggleTableBorders();
break;
case cmd_subscript:
try {
if(doc.queryCommandState(cmd_superscript)) {
doc.execCommand(cmd_superscript, false, null);
self.$ribbon.wijribbon(setButtonChecked, cmd_superscript, false);
}
} catch (e) {
}
doc.execCommand(cmd_subscript, false, null);
self._addtoUndoBuffer();
self._setFocusNotIE();
break;
case cmd_superscript:
try {
if(doc.queryCommandState(cmd_subscript)) {
doc.execCommand(cmd_subscript, false, null);
self.$ribbon.wijribbon(setButtonChecked, cmd_subscript, false);
}
} catch (e1) {
}
doc.execCommand(cmd_superscript, false, null);
self._addtoUndoBuffer();
self._setFocusNotIE();
break;
case cmd_removeformat:
//doc.execCommand(cmd_removeformat, false, null);
self._removeFormat();
self._setFocusNotIE();
break;
case cmd_insertbreak:
self.insertHTML("<br/>");
self._setFocusNotIE();
break;
case cmd_insertparagraph:
selectedHtml = self._getSelectedContent();
if(!selectedHtml || selectedHtml === "") {
selectedHtml = " ";
}
self.insertHTML('<p>' + selectedHtml + '</p>');
self._setFocusNotIE();
break;
case cmd_insertprintbreak:
self.insertHTML('<div title="Print Page Break" ' + 'style="font-size:1px;page-break-before:always;' + 'vertical-align:middle;height:1px;' + 'background-color:#c0c0c0"> </div>');
self._setFocusNotIE();
break;
case cmd_fullscreen:
self._toggleFullScreen();
break;
case cmd_undo:
self._undoAction();
self._setFocusNotIE();
break;
case cmd_redo:
self._redoAction();
self._setFocusNotIE();
break;
case cmd_cut:
self._execCut();
self._setFocusNotIE();
break;
case cmd_copy:
self._execCopy();
break;
case cmd_paste:
self._execPaste();
break;
case cmd_date:
self.insertDateAndTime();
self._setFocusNotIE();
break;
case cmd_designview:
if(self.$modes.data("wijmoWijribbon")) {
self.$modes.wijribbon(setButtonDisabled, cmd_wordwrap, true).wijribbon(setButtonChecked, cmd_designview, true);
}
self.$ribbon.wijribbon("option", "disabled", false);
//TODO:maybe need to add the code block
//update for bbcode
//if (self.options.mode === "bbcode") {
//self._onSourceViewBlur();
//}
//end for update
content.wijsplitter("option", "panel2", {
collapsed: true
});
break;
case cmd_splitview:
if(self.$modes.data("wijmoWijribbon")) {
self.$modes.wijribbon(setButtonDisabled, cmd_wordwrap, true).wijribbon(setButtonChecked, cmd_splitview, true);
}
self.$ribbon.wijribbon("option", "disabled", false);
content.wijsplitter("option", {
panel1: {
collapsed: false
},
panel2: {
collapsed: false
}
});
break;
case cmd_sourceview:
if(self.$modes.data("wijmoWijribbon")) {
self.$modes.wijribbon(setButtonDisabled, cmd_wordwrap, false).wijribbon(setButtonChecked, cmd_sourceview, true);
}
self.$ribbon.wijribbon("option", "disabled", true);
//TODO:maybe need to add the code block
//update for bbcode
//if (self.options.mode === "bbcode") {
//self._onDesignViewBlur();
//}
//end for update
content.wijsplitter("option", "panel1", {
collapsed: true
});
if($.browser.msie) {
self.sourceView.focus();
}
break;
case cmd_wordwrap:
if(content.wijsplitter("option", "panel1").collapsed) {
self._toggleWordWrap();
}
break;
case cmd_backcolor:
//update for fixing issue 20382 by wh at 2012/3/9
/*
if ($.browser.msie) {
rangeSelection = doc.selection.createRange();
}*/
self._saveSelectionForIE();
//end for 20382 issue
self._createDialog(this.localizeString("backColorDialogTitle", "Set BackColor"), self._getDialogRes_BackColor(), self.initBackColorDialog);
break;
case cmd_fontcolor:
//update for fixing issue 20382 by wh at 2012/3/9
/*
if ($.browser.msie) {
rangeSelection = doc.selection.createRange();
}*/
self._saveSelectionForIE();
//end for 20382 issue
self._createDialog(this.localizeString("foreColorDialogTitle", "Set ForeColor"), self._getDialogRes_ForeColor(), self.initForeColorDialog);
break;
case cmd_inserttable:
//update for fixing issue 20382 by wh at 2012/3/9
/*
if ($.browser.msie) {
rangeSelection = doc.selection.createRange();
}*/
self._saveSelectionForIE();
//end for 20382 issue
self._createDialog(this.localizeString("insertTableDialogTitle", "Insert Table"), self._getDialogRes_Table(), self.initInsertTableDialog);
break;
case cmd_edittable:
if(self._getEditableTable()) {
self._createDialog(this.localizeString("editTableDialogTitle", "Edit Table"), self._getDialogRes_Table(), self.initEditTableDialog);
}
break;
case cmd_preview:
self._createDialog(this.localizeString("previewDialogPreview", "Preview"), self._getDialogRes_Preview(), self.initPreviewDialog);
break;
case cmd_cleanup:
self._createDialog(this.localizeString("cleanUpDialogTitle", "Clean up source HTML document"), self._getDialogRes_CleanUp(), self.initCleanUpDialog);
break;
case cmd_media:
//update for fixing issue 20382 by wh at 2012/3/9
/*
if ($.browser.msie) {
rangeSelection = doc.selection.createRange();
}*/
self._saveSelectionForIE();
//end for 20382 issue
self._createDialog(this.localizeString("mediaDialogTitle", "Insert media"), self._getDialogRes_Media(), self.initMediaDialog);
break;
case cmd_specialchar:
//update for fixing issue 20382 by wh at 2012/3/9
/*
if ($.browser.msie) {
rangeSelection = doc.selection.createRange();
}*/
self._saveSelectionForIE();
//end for 20382 issue
self._createDialog(this.localizeString("specialCharacterDialogTitle", "Insert special character"), self._getDialogRes_SpecialCharacter(), self.initSpecialCharacterDialog);
break;
case cmd_find:
self._createDialog(this.localizeString("findAndReplaceTitle", "Find and replace"), self._getDialogRes_FindAndReplace(), self.initFindDialog);
break;
case cmd_inspect:
inspectElement = self._getSelectedElement();
self._createDialog(this.localizeString("tagInspectorDialogTitle", "Tag Inspector"), self._getDialogRes_TagInspector(), self.initTagInspectorDialog);
break;
case cmd_template:
//update for fixing issue 20382 by wh at 2012/3/9
/*
if ($.browser.msie) {
rangeSelection = doc.selection.createRange();
}*/
self._saveSelectionForIE();
//end for 20382 issue
self._createDialog(this.localizeString("templateDialogApplyTemplate", "Apply Template"), self._getDialogRes_Template(), self.initTemplateDialog);
break;
case cmd_imagebrowser:
//update for fixing issue 20382 by wh at 2012/3/9
/*
if ($.browser.msie) {
rangeSelection = doc.selection.createRange();
}*/
self._saveSelectionForIE();
//end for 20382 issue
self._createDialog(this.localizeString("imageEditorDialogImageBrowser", "Image Browser"), self._getDialogRes_ImageBrowser(), self.initImageBrowserDialog);
break;
case cmd_link:
//update for fixing issue 20382 by wh at 2012/3/9
/*
if ($.browser.msie) {
rangeSelection = doc.selection.createRange();
}*/
self._saveSelectionForIE();
//end for 20382 issue
self._createDialog(this.localizeString("hyperLinkDialogInserthyperLink", "Insert hyperLink"), self._getDialogRes_Link(), self.initHyperLinkDialog);
break;
case cmd_insertcode:
//update for fixing issue 20382 by wh at 2012/3/9
/*
if ($.browser.msie) {
rangeSelection = doc.selection.createRange();
}*/
self._saveSelectionForIE();
//end for 20382 issue
self._createDialog("Insert Code", self._getDialogRes_Code(), self.initInsertCodeDialog);
break;
case cmd_alignleft:
case cmd_aligncenter:
case cmd_alignright:
case cmd_alignfull:
case cmd_outdent:
case cmd_indent:
case cmd_bold:
case cmd_italic:
case cmd_underline:
case cmd_numberedlist:
case cmd_bulletedlist:
case cmd_strike:
case cmd_inserthr:
case cmd_selectall:
doc.execCommand(cmd, false, null);
if(self.options.mode === "bbcode" && !($.browser.msie)) {
//convert style="font-weight: bold;
//font-style: italic; text-decoration: underline;"
//same as ie
self._convertStyleToStandTag();
}
self._addtoUndoBuffer();
self._setFocusNotIE();
break;
case cmd_save:
//update for fixing issue 18777 by wuhao at 2011/12/15
self._saveText();
//end for fixing issue
break;
case cmd_spelling:
self._doSpellCheck();
break;
}
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(null);
//end for change happens
};
wijeditor.prototype._saveSelectionForIE = function () {
var cWin = this._getDesignViewWindow(), selection;
if($.browser.msie) {
selection = cWin.document.selection;
rangeSelection = selection.createRange();
}
};
wijeditor.prototype._createDialog = //added by Ryanwu@20110512.
function (title, content, callback) {
var self = this, dialogOpts, $dlg = self.dialog;
$dlg.html("").undelegate(self.widgetName).undelegate("." + self.widgetName).append(content);
//add for fixing issue 20444 by wh at 2012/3/13
if(self.subDialog) {
self.subDialog.html("").undelegate(self.widgetName).undelegate("." + self.widgetName);
}
dialogOpts = {
width: "auto",
height: "auto",
modal: true,
title: title,
position: "center",
resizable: false,
captionButtons: {
pin: {
visible: false
},
refresh: {
visible: false
},
toggle: {
visible: false
},
minimize: {
visible: false
},
maximize: {
visible: false
}
}
};
//end for 20444 issue
if(!$dlg.data("wijmoWijdialog")) {
if($.browser.msie && wijParseInt($.browser.version) === 6) {
window.setTimeout(function () {
$dlg.wijdialog(dialogOpts);
}, 0);
} else {
$dlg.wijdialog(dialogOpts);
}
} else {
$dlg.wijdialog("reset");
$dlg.wijdialog("option", {
width: "auto",
height: "auto",
title: title
});
}
self._adjustDialogLayoutForIE7();
if(callback) {
callback.call(self);
}
$dlg.wijdialog("open");
};
wijeditor.prototype._adjustDialogLayoutForIE7 = function () {
var $dlg = this.dialog;
if($.browser.msie && /^7\.[0-9]+/.test($.browser.version)) {
$dlg.wijdialog('option', 'width', $dlg.parent().width());
}
};
wijeditor.prototype._contextMenuItemClick = function (e, item, sender) {
var self = this, cmd = item.item.element.attr("_c1buttoncmd");
switch(cmd) {
case cmd_cut:
self._execCut();
break;
case cmd_copy:
self._execCopy();
break;
case cmd_paste:
self.focus();
self._execPaste();
break;
}
};
wijeditor.prototype._execCut = function () {
var self = this, doc = self._getDesignViewDocument();
if($.browser.safari) {
wijAlert(this.localizeString("errorMessageCutError", "This function is not supported in current browser. Plesse use (Ctrl + X)."));
} else if($.browser.msie) {
//add the block for fixing bug 18146 at 2011/11/3 by wh
doc.execCommand("Cut", false, null);
self._addtoUndoBuffer();
//end for 18146
} else {
self._execCopy();
self._deleteSelectionContent();
self._addtoUndoBuffer();
}
};
wijeditor.prototype._execCopy = function () {
var self = this, doc = self._getDesignViewDocument();
if($.browser.safari) {
wijAlert(this.localizeString("errorMessageCopyError", "This function is not supported in current browser. Plesse use (Ctrl + C)."));
} else if($.browser.msie) {
//add the block for fixing bug 18146 at 2011/11/3 by wh
doc.execCommand("Copy", false, null);
self._addtoUndoBuffer();
//end for 18146
} else {
self._copyToClipboard(self._getSelectedContent());
}
};
wijeditor.prototype._execPaste = function () {
var self = this, copiedText, doc = self._getDesignViewDocument();
if($.browser.safari) {
wijAlert(this.localizeString("errorMessagePasteError", "This function is not supported in current browser. Plesse use (Ctrl + V)."));
} else if($.browser.msie) {
//add the block for fixing bug 18146 at 2011/11/3 by wh
doc.execCommand("Paste", false, null);
self._addtoUndoBuffer();
//end for 18146
} else {
try {
copiedText = self._copyFromClipboard();
if(copiedText && copiedText !== '') {
self.insertHTML(copiedText);
}
} catch (e1) {
}
}
};
wijeditor.prototype._getFontSizeCollection = function () {
return {
'10px': cmd_verysmall,
'13px': cmd_smaller,
'16px': cmd_small,
'18px': cmd_medium,
'24px': cmd_large,
'32px': cmd_larger,
'48px': cmd_verylarge,
1: cmd_verysmall,
2: cmd_smaller,
3: cmd_small,
4: cmd_medium,
5: cmd_large,
6: cmd_larger,
7: cmd_verylarge
};
};
wijeditor.prototype._updateButtonStates = function (e) {
var self = this, doc = self._getDesignViewDocument(), rawValue, cmd, buttonStates = {
}, stateButtons = [
cmd_bold,
cmd_italic,
cmd_strike,
cmd_underline,
cmd_subscript,
cmd_superscript,
cmd_numberedlist,
cmd_bulletedlist,
cmd_alignleft,
cmd_aligncenter,
cmd_alignright,
cmd_alignfull
], $fontSizeSpans, target = e.target, $target = $(target);
$.each(stateButtons, function (idx, btnKey) {
buttonStates[btnKey] = doc.queryCommandState(btnKey);
});
self.$ribbon.wijribbon(setButtonsChecked, buttonStates);
rawValue = self._queryCommandValue(cmd_fontname) || "";
$.each(self.$ribbon.wijribbon("getDropdownList", cmd_fontname), function (key, value) {
if(value.toUpperCase() === rawValue.toUpperCase()) {
cmd = key;
return false;
}
});
self.$ribbon.wijribbon(setButtonChecked, cmd, true, cmd_fontname);
//Add comments by RyanWu@20110923.
//For implementing the font size customization.
if(self._isFontSizeCustomized()) {
if($target.is("span")) {
cmd = target.style.fontSize;
} else {
cmd = "";
}
if(cmd === "") {
$fontSizeSpans = $target.parents("span." + css_formatspan);
$.each($fontSizeSpans, function (idx, fontSizeSpan) {
cmd = fontSizeSpan.style.fontSize;
if(cmd && cmd !== "") {
return false;
}
});
}
if(cmd === "") {
cmd = $target.css("font-size");
}
} else {
rawValue = self._queryCommandValue(cmd_fontsize) || "";
if(rawValue === "") {
rawValue = $target.css("font-size");
}
$.each(self._getFontSizeCollection(), function (key, value) {
if(key.toString() === rawValue.toString()) {
cmd = value;
return false;
}
});
}
//end by RyanWu@20110923.
self.$ribbon.wijribbon(setButtonChecked, cmd, true, cmd_fontsize);
};
wijeditor.prototype._queryCommandValue = function (commandName) {
var doc = this._getDesignViewDocument();
try {
if(!doc.queryCommandEnabled(commandName)) {
return null;
}
} catch (e1) {
return null;
}
try {
return doc.queryCommandValue(commandName);
} catch (e2) {
}
return null;
};
wijeditor.prototype._escActionAssociated = function () {
var self = this, win = self._getDesignViewWindow();
if(win.document.selection !== undefined) {
win.document.selection.empty();
}
if(win.getSelection !== undefined) {
win.getSelection().removeAllRanges();
}
self._hideAllDropdownsMenus();
};
wijeditor.prototype._hideAllDropdownsMenus = function () {
var self = this;
if(self.contextMenu) {
self.contextMenu[self._contextMenuWidgetName()]("hideAllMenus");
}
self.$ribbon.wijribbon("hideDropdown", cmd_fontname).wijribbon("hideDropdown", cmd_fontsize).wijribbon("hideDropdown", cmd_table);
};
wijeditor.prototype._onDesignViewKeyDown = function (e) {
var self = this, ch;
self._setSaveBtnEnabled();
try {
if(e.ctrlKey) {
ch = String.fromCharCode(e.keyCode).toLowerCase();
// switch (ch) {
// case 'x':
// case 'v':
// self._addtoUndoBuffer();
// break;
// }
} else {
switch(e.keyCode) {
case 27:
self._escActionAssociated();
break;
case 13:
case 46:
self._addtoUndoBuffer();
//update for fixing issue 20372 by wh at 2012/3/9
self._continueSavingInputTextForUndo = false;
//end for 20372 issue
break;
default:
//update for fixing issue 20372 by wh at 2012/3/9
self._continueSavingInputTextForUndo = true;
//end for 20372 issue
break;
}
}
} catch (e1) {
}
};
wijeditor.prototype._onDesignViewKeyUp = function (e) {
var self = this, ch;
if(e.keyCode === 37 || e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 40 || e.keyCode === 33 || e.keyCode === 34 || e.keyCode === 35 || e.keyCode === 36) {
if($.browser.msie && $.browser.version === "6.0") {
if(self._keyTimeoutHandlerIE6) {
clearTimeout(self._keyTimeoutHandlerIE6);
self._keyTimeoutHandlerIE6 = null;
}
self._keyTimeoutHandlerIE6 = window.setTimeout(function () {
self._updateButtonStates(e);
}, 300);
} else {
self._updateButtonStates(e);
}
}
if(e.ctrlKey) {
ch = String.fromCharCode(e.keyCode).toLowerCase();
switch(ch) {
case 'y':
self._redoAction();
e.preventDefault();
e.stopPropagation();
break;
case 'z':
self._undoAction();
e.preventDefault();
e.stopPropagation();
break;
case 'x':
case 'v':
self._addtoUndoBuffer();
//update for fixing issue 20372 by wh at 2012/3/9
self._continueSavingInputTextForUndo = false;
//end for 20372 issue
break;
}
}
};
wijeditor.prototype._onDesignViewMouseUp = function (e) {
var self = this, $link;
if(e.button === 2) {
return;
}
self._updateButtonStates(e);
self._refreshPathSelector();
//Note: recover the code by wuhao at 2011/9/14, when dropdown is open
//click the design view, the dropdown don't close
self._hideAllDropdownsMenus();
$(document).mouseup();
if($.browser.msie) {
$link = $(e.target).closest("a");
if(e.ctrlKey && $link.length > 0) {
try {
$link.focus();
wijWindow.open($link[0].href, '_blank');
} catch (e1) {
}
}
}
};
wijeditor.prototype._onDesignViewBlur = function (e) {
var self = this, o = self.options, sourceView;
sourceView = self._getDesignViewText();
//update for fixing issue 20372 by wh at 2012/3/9
self._onTextChange(e);
//end for 20372 issue
if(o.mode === "bbcode") {
//Note: trim leading/trailing whitespace
//because when get the innerhtml from body, there
//are some whitespace on leading/trailing
sourceView = self._convertHtmlToBBCode($.trim(sourceView));
}
self.sourceView.val(sourceView);
o.text = sourceView;
};
wijeditor.prototype._onTextChange = function (e) {
var self = this;
if(self._continueSavingInputTextForUndo) {
self._addtoUndoBuffer();
self._continueSavingInputTextForUndo = false;
}
self._trigger('textChanged', e, {
text: self.options.text
});
};
wijeditor.prototype._onSourceViewBlur = function () {
var self = this, designViewText;
designViewText = self.sourceView.val();
self._setDesignViewText(designViewText);
self.options.text = designViewText;
};
wijeditor.prototype._convertBBCodeToHtml = //bbcode implement
function (data) {
if(!data) {
return "";
}
// Convert < and > to their HTML entities.
data = data.replace(/</g, '<');
data = data.replace(/>/g, '>');
//note: can't asure there is no problem.
//data = data.replace(/ /g, ' ');
// Convert line breaks to <br>.
data = data.replace(/(?:\r\n|\n|\r)/g, '<br>');
//[email]
data = data.replace(/\[EMAIL\]([\s\S]*?)\[\/EMAIL\]/gim, '<a href="mailto:$1">$1</a>');
data = data.replace(/\[EMAIL\=([^\]]+)]([\s\S]*?)\[\/EMAIL\]/gim, '<a href="mailto:$1">$2</a>');
// [url]
data = data.replace(/\[URL\]([\s\S]*?)\[\/URL\]/gim, '<a href="$1">$1</a>');
data = data.replace(/\[URL\=([^\]]+)]([\s\S]*?)\[\/URL\]/gim, '<a href="$1">$2</a>');
// [b]
data = data.replace(/\[B\]/gim, '<b>');
data = data.replace(/\[\/B\]/gim, '</b>');
// [i]
data = data.replace(/\[I\]/gim, '<i>');
data = data.replace(/\[\/I\]/gim, '</i>');
// [s]
data = data.replace(/\[S\]/gim, '<strike>');
data = data.replace(/\[\/S\]/gim, '</strike>');
// [u]
data = data.replace(/\[U\]/gim, '<u>');
data = data.replace(/\[\/U\]/gim, '</u>');
// [IMG] [^<>]*
data = data.replace(/\[IMG height=(.*?) width=(.*?)](.+?)\[\/IMG\]/gim, '<img height="$1" width = "$2" src="$3"/>');
//[BLOCK]
data = data.replace(/\[BLOCK\]/gim, '<blockquote>');
data = data.replace(/\[\/BLOCK\]/gim, '</blockquote>');
// Ordered List [OL]
data = data.replace(/\[LIST\=1\]\[\*\]([\s\S]*?)\[\/LIST\]/gim, '<ol><li>$1</li></ol>');
// Unordered List [UL]
data = data.replace(/\[LIST\]\[\*\]([\s\S]*?)\[\/LIST\]/gim, '<ul><li>$1</li></ul>');
//LI
data = data.replace(/\[\*\]/gim, '</li><li>');
// [SIZE]
// data = data.replace(/\[size=([^\]]*?)\]/gi,
// "<span style=\"font-size: $1;\">");
// data = data.replace(/\[\/size\]/gim, '</span>');
data = data.replace(/\[size=([^\]]*?)\]/gi, "<font size=\"$1\">");
data = data.replace(/\[\/size\]/gim, '</font>');
// [COLOR]
data = data.replace(/\[color=([^\]]*?)\]/gi, "<font color=\"$1\">");
data = data.replace(/\[\/color\]/gim, '</font>');
return data;
};
wijeditor.prototype._replaceComplexHtml = function (data) {
var imgs, fonts, replaceHtml, i, root = $("<div/>").html(data);
//img
imgs = $("img", root);
$.each(imgs, function () {
replaceHtml = '[IMG height=' + $(this).height() + ' width=' + $(this).width() + ']' + $(this).attr("src").toString() + '[/IMG]';
$(this).replaceWith(replaceHtml);
});
//font
fonts = $("font", root);
for(i = fonts.length - 1; i >= 0; i--) {
if($(fonts[i]).attr("color") && $($(fonts[i])).attr("size")) {
replaceHtml = '[Color=' + $($(fonts[i])).attr("color") + ']' + '[Size=' + $($(fonts[i])).attr("size") + ']' + $($(fonts[i])).html() + '[/Size][/Color]';
} else if($($(fonts[i])).attr("color") && !$($(fonts[i])).attr("size")) {
replaceHtml = '[Color=' + $($(fonts[i])).attr("color") + '] ' + $($(fonts[i])).html() + '[/Color]';
} else if($($(fonts[i])).attr("size") && !$($(fonts[i])).attr("color")) {
replaceHtml = '[Size=' + $($(fonts[i])).attr("size") + ']' + $($(fonts[i])).html() + '[/Size]';
}
$($(fonts[i])).replaceWith(replaceHtml);
}
return root.html();
};
wijeditor.prototype._convertHtmlToBBCode = function (data) {
var self = this;
if(data === "") {
return;
}
data = self._replaceComplexHtml(data);
// Convert <br> to line breaks.
data = data.replace(/<br(?=[ \/>]).*?>/gim, '\r\n');
// [URL]
data = data.replace(/<a .*?href=(["'])(.+?)\1.*?>(.+?)<\/a>/gi, '[URL=$2]$3[/URL]');
// [Email]
data = data.replace(/<a .*?href=(["'])mailto:(.+?)\1.*?>(.+?)<\/a>/gi, '[EMAIL=$2]$3[/EMAIL]');
// [B]
data = data.replace(/<(?:b|strong)>/gim, '[B]');
data = data.replace(/<\/(?:b|strong)>/gim, '[/B]');
// [I]
data = data.replace(/<(?:i|em)>/gim, '[I]');
data = data.replace(/<\/(?:i|em)>/gim, '[/I]');
// [strike]
data = data.replace(/<(?:strike|s)>/gim, '[S]');
data = data.replace(/<\/(?:strike|s)>/gim, '[/S]');
// [U]
data = data.replace(/<u>/gim, '[U]');
data = data.replace(/<\/u>/gim, '[/U]');
// [IMG]
//data = data.replace(/<img\s{1}.*?src\s{0,1}=\s{0,1}["'](.+?)["'].*/gim,
// '[IMG="$1"][/IMG]');
//data = data.replace(/<img\s{1}([^>]*)src\s{0,1}=\s{0,1}["'](.+?)["']([^>]*)>/gim,
// '[IMG $1$3]$2[/IMG]');
// [BLOCK]
data = data.replace(/<blockquote.*?\>/gim, '[BLOCK]');
data = data.replace(/\s{0,}<\/blockquote>/gim, '[/BLOCK]');
// Ordered List [OL]
data = data.replace(/(?:\r\n|\r|\n){0,1}<(?:ol)>[\s]*/gim, '[LIST=1]');
data = data.replace(/<\/(?:ol)>/gim, '[/LIST]');
// Unordered List [UL]
//\r\n<ul> must convert to ul
data = data.replace(/(?:\r\n|\r|\n){0,1}\<(?:ul)>[\s]*/gim, '[LIST]');
data = data.replace(/<\/(?:ul)>/gim, '[/LIST]');
// [LI]
data = data.replace(/\s{0,}<li\s{0,1}.*?>([\s\S]*?)\n{0,}\s{0,}<\/li>/gim, '[*]$1');
//space convert
data = data.replace(/ /gi, " ");
// Remove remaining tags.
data = data.replace(/(<[^>]+>)/gm, '');
return data;
};
wijeditor.prototype._convertFontStyleToStandTag = function () {
var self = this, doc = self._getDesignViewDocument(), $designviewBody = $(doc.body), currentNode, bbcodeMark, colorTag = $("[style*='color: ']", $designviewBody);
if(colorTag.length !== 0) {
currentNode = colorTag;
bbcodeMark = "<font color='" + self._getWebColorFromRgb(colorTag.css("color")) + "'></font>";
}
if(currentNode) {
$.each(currentNode, function (i) {
//there is no attribute in span,
//like <span style="color:#123">xxx</b>
//must replace span with new tag
//like <b>XXX</b>
if($(this).is("span")) {
$(this).replaceWith($(bbcodeMark).html($(this).html()));
} else if($(this).is("font") && $(this).attr("size")) {
//note: there are other attribute in span
//like <span style="font-size:15px, color=#123">XXX</b>
// so insert new tag in span content
//like <span style="font-size:15px><b>XXX</b></span>
//maybe there is no need here
//$(this).css("color", undefined)
//$(this).removeAttr("style")
// .html($(bbcodeMark).html($(this).html()));
$(this).removeAttr("style").html($(bbcodeMark).html());
}
});
}
};
wijeditor.prototype._convertStyleToStandTag = function () {
var self = this, doc = self._getDesignViewDocument(), $designviewBody = $(doc.body), currentNode, bbcodeMark, currentAttr, boldTag = $("[style*='font-weight: bold;']", $designviewBody), italicTag = $("[style*='font-style: italic;']", $designviewBody), strikeTag = $("[style*='text-decoration: line-through;']", $designviewBody), underlineTag = $("[style*='text-decoration: underline;']", $designviewBody);
if(boldTag.length !== 0) {
currentNode = boldTag;
bbcodeMark = "<b></b>";
currentAttr = "font-weight";
} else if(italicTag.length !== 0) {
currentNode = italicTag;
bbcodeMark = "<i></i>";
currentAttr = "font-style";
} else if(strikeTag.length !== 0) {
currentNode = strikeTag;
bbcodeMark = "<strike></strikes>";
currentAttr = "text-decoration";
} else if(underlineTag.length !== 0) {
currentNode = underlineTag;
bbcodeMark = "<u></u>";
currentAttr = "text-decoration";
}
if(currentNode) {
$.each(currentNode, function (i) {
//there is no attribute in span,
//like <span style="color:#123">xxx</b>
//must replace span with new tag
//like <b>XXX</b>
if($(this).is("span") && this.style.fontSize === "") {
$(this).replaceWith($(bbcodeMark).html($(this).html()));
} else {
//note: there are other attribute in span
//like <span style="font-size:15px, color=#123">XXX</b>
// so insert new tag in span content
//like <span style="font-size:15px><b>XXX</b></span>
//maybe there is no need here
//$(this).css(currentAttr, null)
//$(this).removeAttr("style")
// .html($(bbcodeMark).html($(this).html()));
$(this).removeAttr("style").html($(bbcodeMark).html());
}
});
}
};
wijeditor.prototype._getWebColorFromRgb = function (rgbColor) {
var self = this, rgbColorItems;
if(rgbColor.indexOf('rgb(') === 0) {
rgbColorItems = rgbColor.substring(4, rgbColor.length - 1).split(',');
rgbColor = self._convertToWebColor(wijParseInt(rgbColorItems[0]), wijParseInt(rgbColorItems[1]), wijParseInt(rgbColorItems[2]));
}
return rgbColor;
};
wijeditor.prototype._updateList = //end bbcode
//common for dialogs.
function (list, $select) {
var name;
$("option", $select).remove();
for(name in list) {
if(list[name]) {
$select.append("<option>" + name + "</option>");
}
}
};
wijeditor.prototype._triggerEvent = function (evName, arg) {
var self = this, ev = self.options[evName];
if(ev && typeof (ev) === "function") {
return ev.call(self, arg);
}
return ev;
};
wijeditor.prototype._closeDialog = function () {
this.dialog.wijdialog("close");
};
wijeditor.prototype._onTemplateList = //end of common dialogs.
//begin to handle the template dialog.
function (arg) {
return this._triggerEvent("templateList", arg);
};
wijeditor.prototype.updateTemplateList = /** @ignore */
function (templateList, select) {
var self = this, $select = select || $("select", self.dialog);
self._updateList(templateList, $select);
self._templateList = templateList;
};
wijeditor.prototype.initTemplateDialog = /** @ignore */
function () {
var self = this, $dlg = self.dialog, tplList = $("select", $dlg), templateList = self._onTemplateList();
$dlg.delegate("select", "change." + self.widgetName, function () {
self.templateListOnChanged();
}).delegate("." + css_tpl_delete, "click." + self.widgetName, function () {
self.deleteTemplate();
}).delegate("." + css_tpl_save, "click." + self.widgetName, function () {
self.saveTemplate();
}).delegate(selector_dlg_ok, "click." + self.widgetName, function () {
self.applyTemplate();
}).delegate(selector_dlg_cancel, "click." + self.widgetName, function () {
self._closeDialog();
});
if(!templateList) {
templateList = self._templateList;
if(!templateList) {
return;
}
}
self.updateTemplateList(templateList, tplList);
};
wijeditor.prototype.templateListOnChanged = /** @ignore */
function () {
var self = this, $dlg = self.dialog, selectedTpl = $("select", $dlg).val(), preview = $('iframe', $dlg), templateList = self._templateList, template;
if(!templateList) {
return;
}
template = templateList[selectedTpl];
if(template.src) {
preview.attr("src", template.src + '?d=' + new Date().getMilliseconds().toString());
}
if(template.text && preview.length > 0) {
(preview[0]).contentWindow.document.write(template.text);
}
if(selectedTpl) {
$("." + css_tpl_nameinfo, $dlg).html(selectedTpl);
$("." + css_tpl_namefield, $dlg).val(selectedTpl);
}
if(template.desc) {
$("." + css_tpl_desinfo, $dlg).html(template.desc);
$("." + css_tpl_desfield, $dlg).val(template.desc);
}
};
wijeditor.prototype._onSaveTemplate = function (arg) {
this._triggerEvent("saveTemplate", arg);
};
wijeditor.prototype.saveTemplate = /** @ignore */
function () {
var self = this, $dlg = self.dialog, name = $("." + css_tpl_namefield, $dlg).val(), desc = $("." + css_tpl_desfield, $dlg).val(), templateList = self._templateList, text = this._getDesignViewText();
if($.trim(name) === '') {
wijAlert(this.localizeString("errorMessageTemplateNameError", "Please input a template name!"));
return;
}
if(!templateList) {
self._templateList = [];
templateList = self._templateList;
}
if(!templateList[name]) {
$("select", $dlg).append("<option>" + name + "</option>");
}
templateList[name] = {
desc: desc,
text: text
};
self._onSaveTemplate({
name: name,
desc: desc,
text: text
});
};
wijeditor.prototype._onDeleteTemplate = function (arg) {
this._triggerEvent("deleteTemplate", arg);
};
wijeditor.prototype.deleteTemplate = /** @ignore */
function () {
var self = this, $dlg = self.dialog, tplList = $("select", $dlg), selectedTpl = tplList.val(), templateList = self._templateList;
if($.trim(selectedTpl) === '') {
wijAlert(this.localizeString("errorMessageTemplateFileError", "Please select a template file."));
return;
}
$("option:selected", tplList).remove();
$('iframe', $dlg).attr("src", "about:blank");
$("." + css_tpl_nameinfo, $dlg).empty();
$("." + css_tpl_namefield, $dlg).val("");
$("." + css_tpl_desinfo, $dlg).empty();
$("." + css_tpl_desfield, $dlg).val("");
delete templateList[selectedTpl];
self._onDeleteTemplate(selectedTpl);
};
wijeditor.prototype.applyTemplate = /** @ignore */
function () {
var self = this, $dlg = self.dialog, tplList = $("select", $dlg), selectedTpl = tplList.val(), preview = $('iframe', $dlg)[0], name = $("." + css_tpl_namefield, $dlg).val(), html = (preview).contentWindow.document.body.innerHTML;
if($.trim(name) === '' || $.trim(selectedTpl) === '') {
wijAlert(this.localizeString("errorMessageValidTemplateFileError", "Please select a valid template file."));
return;
}
self._setDesignViewText(html);
self._addtoUndoBuffer();
self._setSaveBtnEnabled();
self._closeDialog();
};
wijeditor.prototype._onImageList = //begin to handle the image dialog.
function () {
var self = this, imageList = self.options.imageList;
if(imageList && typeof (imageList) === "function") {
return imageList.call(self);
}
return imageList;
};
wijeditor.prototype.updateImageList = /** @ignore */
function (imgList, select) {
var self = this, $dlg = self.dialog, $select = select || $("select", $dlg), $imgfields = $("." + css_imgdlg_field, $dlg);
self._updateList(imgList, $select);
self._imgList = imgList;
if(!imgList) {
$imgfields.addClass(css_imgdlg_hideimglist);
return;
}
$imgfields.removeClass(css_imgdlg_hideimglist);
};
wijeditor.prototype.initImageBrowserDialog = /** @ignore */
function () {
var self = this, $dlg = self.dialog, imgList = self._onImageList();
$("img", $dlg).hide();
$dlg.delegate("select", "change." + self.widgetName, function () {
//self.imageListOnChanged(this);
self.imageListOnChanged();
}).delegate(//update for ie don't fire the change event
//.delegate("." + css_imgdlg_url + " input", "change." + self.widgetName,
//function () {
// self.imageUrlChanged(this);
// })
selector_dlg_ok, "click." + self.widgetName, function (e) {
self.submitInsertImageDialog();
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(e);
//end for change happens
}).delegate(selector_dlg_cancel, "click." + self.widgetName, function () {
self._closeDialog();
});
//update for ie don't fire the change event
$("." + css_imgdlg_url + " input", $dlg).bind("change." + self.widgetName, function () {
self.imageUrlChanged(this);
});
if(!imgList) {
imgList = self._imgList;
if(!imgList) {
$("." + css_imgdlg_field, $dlg).addClass(css_imgdlg_hideimglist);
return;
}
}
self.updateImageList(imgList, $("select", $dlg));
};
wijeditor.prototype.imageUrlChanged = /** @ignore */
function (element) {
var self = this, $dlg = self.dialog;
$('img', this.dialog).attr("src", $(element).val() + "?" + new Date().getTime()).show().bind("load", function () {
$("." + css_imgdlg_width + " input", $dlg).val($('img', $dlg).width().toString());
$("." + css_imgdlg_height + " input", $dlg).val($('img', $dlg).height().toString());
});
};
wijeditor.prototype.imageListOnChanged = /** @ignore */
function () {
var self = this, $dlg = self.dialog, selectedImg = $('select', $dlg).val(), imgList = self._imgList, img;
if(!imgList) {
return;
}
img = imgList[selectedImg];
$('img', $dlg).prop("src", img).show();
$("." + css_imgdlg_url + " input", $dlg).prop("value", img);
wijWindow.setTimeout(function () {
$("." + css_imgdlg_width + " input", $dlg).val($('img', $dlg).width().toString());
$("." + css_imgdlg_height + " input", $dlg).val($('img', $dlg).height().toString());
}, 200);
};
wijeditor.prototype.submitInsertImageDialog = /** @ignore */
function () {
var self = this, imageHtml, $dlg = self.dialog, imgUrl = $("." + css_imgdlg_url + " input", $dlg).val(), alt = $("." + css_imgdlg_alt + " input", $dlg).val(), width = $("." + css_imgdlg_width + " input", $dlg).val(), height = $("." + css_imgdlg_height + " input", $dlg).val(), css = $("." + css_imgdlg_css + " input", $dlg).val();
if($.trim(imgUrl) === "") {
wijAlert(this.localizeString("errorMessageSelectImageError", "Please select a image."));
return;
}
if(!self._isNumeric(width)) {
wijAlert(this.localizeString("errorMessageImageWidthError", "Please input a number for 'Image width' textbox."));
return;
}
if(!self._isNumeric(height)) {
wijAlert(this.localizeString("errorMessageImageHeightError", "Please input a number for 'Image height' textbox."));
return;
}
self.focus();
if($.browser.msie) {
//for 35039 issue
imageHtml = '<img src="' + imgUrl + '" alt="' + alt + '" style="width:' + width + 'px;height:' + height + 'px';
if(self.options.mode !== "bbcode" && css !== null && css !== undefined && css.length > 0) {
imageHtml += ';' + css;
}
} else {
imageHtml = '<img src="' + imgUrl + '" alt="' + alt + '" width="' + width + '" height="' + height;
if(self.options.mode !== "bbcode") {
imageHtml += '" style="' + css;
}
}
imageHtml += '"/>';
self.insertHTML(imageHtml);
self._closeDialog();
};
wijeditor.prototype.initHyperLinkDialog = //begin to handle the link dialog.
/** @ignore */
function () {
var self = this, $dlg = self.dialog, address = self.getLinkHrefField(), $imageContainer = $("." + css_linkdlg_imagecontainer, $dlg), iconTypeIsImg, linkInnerHtml, $img, $address = $("." + css_linkdlg_address + " input", $dlg);
$dlg.delegate(selector_dlg_ok, "click." + self.widgetName, function (e) {
self.submitHyperLinkDialog();
//add for any change happens,
//the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(e);
//end for change happens
}).delegate(selector_dlg_cancel, "click." + self.widgetName, function () {
self._closeDialog();
}).delegate("." + css_linkdlg_anchor, "change." + self.widgetName, function () {
self.anchorListOnChanged(this);
}).delegate("." + css_linkdlg_linktype + ">div", "click." + self.widgetName, function () {
self.radioListOnChanged();
}).delegate("." + css_linkdlg_linkicontype + ">div", "click." + self.widgetName, function () {
self.linkIconTypeOnChanged();
}).delegate("." + css_linkdlg_url + " input", "change." + self.widgetName, function () {
self.tempImg = $('<img src="' + $("." + css_linkdlg_url + " input", $dlg).val() + '">').appendTo("body");
wijWindow.setTimeout(function () {
$("." + css_linkdlg_width + " input", $dlg).val(self.tempImg.width().toString());
$("." + css_linkdlg_height + " input", $dlg).val(self.tempImg.height().toString());
self.tempImg.remove();
self.tempImg = undefined;
}, 200);
});
try {
$address.val(address);
linkInnerHtml = self._getLinkInnerHTML();
} catch (e) {
}
$img = $(linkInnerHtml);
if(linkInnerHtml && linkInnerHtml.substring(0, 3) === '<img') {
iconTypeIsImg = true;
} else {
iconTypeIsImg = false;
}
if(!iconTypeIsImg) {
$("." + css_linkdlg_text + " input", $dlg).show();
$imageContainer.hide();
$("." + css_linkdlg_text + " input", $dlg).val(linkInnerHtml);
} else {
$imageContainer.show();
$("." + css_linkdlg_text + " input", $dlg).hide();
$("." + css_linkdlg_url + " input", $dlg).val($img.attr("src"));
$("." + css_linkdlg_width + " input", $dlg).val($img.attr("width"));
$("." + css_linkdlg_height + " input", $dlg).val($img.attr("heigth"));
}
$("." + css_linkdlg_css + " input", $dlg).val(self._getLinkCssField());
$("." + css_linkdlg_target + " select", $dlg).val(self._getLinkTarget());
$("#radAnchor", $dlg).attr("checked", "checked");
$("#radLinkTypeIsText", $dlg).attr("checked", "checked");
if(address.length > 6) {
if(address.substring(0, 4) === 'http') {
$("#radUrl", $dlg).attr("checked", "checked");
} else if(address.substring(0, 6) === 'mailto') {
$("#radMail", $dlg).attr("checked", "checked");
} else {
if(address.substring(0, 1) === '#') {
$("#radAnchor", $dlg).attr("checked", "checked");
} else {
$("#radFile", $dlg).attr("checked", "checked");
}
}
}
$img = undefined;
};
wijeditor.prototype._getLinkInnerHTML = function () {
var self = this, inspElem;
self.focus();
inspElem = self._getInspectElement();
try {
if(inspElem && inspElem.tagName === 'A') {
return inspElem.innerHTML || '';
}
} catch (error) {
}// return self.getSelectionHTMLContent() || '';
return '';
};
wijeditor.prototype.getLinkHrefField = /** @ignore */
function () {
var self = this, inspElem;
self.focus();
inspElem = self._getInspectElement();
try {
if(inspElem && inspElem.tagName === 'A') {
return self.fixAbsoluteUrlsIfNeeded(inspElem.href || '');
}
} catch (error) {
}
return '';
};
wijeditor.prototype._getLinkTarget = function () {
var self = this, inspElem;
self.focus();
inspElem = self._getInspectElement();
try {
if(inspElem && inspElem.tagName === 'A') {
return inspElem.target || '';
}
} catch (error) {
}
return '';
};
wijeditor.prototype._getLinkCssField = function () {
var self = this, inspElem;
self.focus();
inspElem = self._getInspectElement();
try {
if(inspElem && inspElem.tagName === 'A') {
return inspElem.style.cssText || '';
}
} catch (error) {
}
return '';
};
wijeditor.prototype.submitHyperLinkDialog = /** @ignore */
function () {
var self = this, $dlg = self.dialog, $radMail = $("#radMail", $dlg), $address = $("." + css_linkdlg_address + " input", $dlg), $text = $("." + css_linkdlg_text + " input", $dlg), $css = $("." + css_linkdlg_css + " input", $dlg), $target = $("." + css_linkdlg_target + " select", $dlg), address = $address.val(), text = $text.val(), target = $target.val(), $radImage = $("#radLinkTypeIsImage", $dlg), imageChecked = $radImage.prop("checked"), imageUrl = $("." + css_linkdlg_url + " input", $dlg).val(), imageWidth = $("." + css_linkdlg_width + " input", $dlg).val(), imageHeight = $("." + css_linkdlg_height + " input", $dlg).val(), css = $css.val();
if(address === '') {
wijAlert(this.localizeString("errorMessageAddressError", "Please input address!"));
return;
}
if(text === '' && !imageChecked) {
wijAlert(this.localizeString("errorMessageDisplayTextError", "Please input display text!"));
return;
}
if(imageUrl === '' && imageChecked) {
wijAlert(this.localizeString("errorMessageHyperLinkImageUrlError", "Please input image url!"));
return;
}
if(!self._isNumeric(imageWidth) && imageChecked) {
wijAlert(this.localizeString("errorMessageHyperLinkImageWidthError", "Please input correct image width!"));
return;
}
if(!self._isNumeric(imageHeight) && imageChecked) {
wijAlert(this.localizeString("errorMessageHyperLinkImageHeightError", "Please input correct image height!"));
return;
}
if($radMail.attr("checked") && !self._isEmail(address)) {
wijAlert(this.localizeString("errorMessageHyperLinkEmail", "Please input correct email!"));
return;
}
if(imageChecked) {
text = '<img src="' + imageUrl + '" width="' + imageWidth + '" height="' + imageHeight;
text += '"/>';
}
self._editLink(text, address, css, target);
self._closeDialog();
};
wijeditor.prototype._editLink = function (text, href, css, target) {
var self = this, inspElem, html = '';
self.focus();
inspElem = self._getInspectElement();
try {
if(inspElem && inspElem.tagName === 'A') {
inspElem.innerHTML = text;
inspElem.href = href;
inspElem.target = target;
if(css !== inspElem.style.cssText) {
inspElem.style.cssText = css;
}
self._addtoUndoBuffer();
self._setSaveBtnEnabled();
return;
}
} catch (error) {
}
html = '<a href="' + href + '" target="' + target + '"';
if(css !== '') {
html += ' style="' + css + '"';
}
html += '>' + text + '</a>';
self._setIESelection();
self.insertHTML(html);
};
wijeditor.prototype.anchorListOnChanged = /** @ignore */
function (list) {
var self = this, $dlg = self.dialog, val = $(list).val();
if(val !== '') {
$("." + css_linkdlg_address + " input", $dlg).val(val);
$("#radAnchor", $dlg).attr("checked", "checked");
}
};
wijeditor.prototype.radioListOnChanged = /** @ignore */
function () {
var self = this, $dlg = self.dialog, $anchor = $("." + css_linkdlg_anchor, $dlg), $address = $("." + css_linkdlg_address + " input", $dlg);
$address.val("");
if($("#radUrl", $dlg).is(":checked")) {
$anchor.hide();
} else if($("#radAnchor", $dlg).is(":checked")) {
$anchor.show();
} else if($("#radMail", $dlg).is(":checked")) {
$anchor.hide();
$address.val('mailto:');
} else if($("#radFile", $dlg).is(":checked")) {
$anchor.hide();
}
};
wijeditor.prototype.linkIconTypeOnChanged = /** @ignore */
function () {
var self = this, $dlg = self.dialog, $imageContainer = $("." + css_linkdlg_imagecontainer, $dlg), $text = $("." + css_linkdlg_text, $dlg);
if($("#radLinkTypeIsText", $dlg).is(":checked")) {
$text.show();
$imageContainer.hide();
} else if($("#radLinkTypeIsImage", $dlg).is(":checked")) {
$text.hide();
$imageContainer.show();
}
};
wijeditor.prototype._getDialogRes_Code = //end of link dialog.
//beging to handle the insert code dialog
function () {
var self = this, dialog = self._createDiv(css_linkdlg);
dialog.add(self._createElement("div", "Enter source code", {
"class": css_codedlg_sourcelabel
}));
dialog.add(self._createElement("textarea", "", {
"class": css_codedlg_source
}));
dialog.add(self._createSeparator());
dialog.add(self._createOKCancelButtons());
return dialog.render();
};
wijeditor.prototype.initInsertCodeDialog = /** @ignore */
function () {
var self = this, $dlg = self.dialog;
$dlg.delegate(selector_dlg_ok, "click." + self.widgetName, function (e) {
self.submitCodeDialog();
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(e);
//end for change happens
}).delegate(selector_dlg_cancel, "click." + self.widgetName, function () {
self._closeDialog();
});
};
wijeditor.prototype.submitCodeDialog = /** @ignore */
function () {
var self = this, $dlg = self.dialog, $source = $("." + css_codedlg_source, $dlg), html = $source.val();
if(html === '') {
return;
}
html = html.replace(/</g, '<');
html = html.replace(/>/g, '>');
html = '<pre>' + html + '</pre>';
self._setIESelection();
self.insertHTML(html);
self._closeDialog();
};
wijeditor.prototype.initTagInspectorDialog = //end of insert code dialog
//begin to handle the tagInspector dialog.
/** @ignore */
function () {
var self = this, $dlg = self.dialog, $innerHTML = $("." + css_taginsdlg_innerhtml);
$dlg.delegate(selector_dlg_ok, "click." + self.widgetName, function (e) {
self.submitTagInspectorDialog();
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(e);
//end for change happens
}).delegate(selector_dlg_cancel, "click." + self.widgetName, function () {
self._closeDialog();
}).delegate("#displayNoEmpty", "click." + self.widgetName, function () {
self.tagInspectorDialogSwitchAttList(this);
});
self._laySelectedElementAttributes($("." + css_taginsdlg_attriblist, $dlg), $("." + css_taginsdlg_tagtext, $dlg));
$("." + css_taginsdlg_css + " input", $dlg).val(self._getSelectedElementStyle());
if(self._selectedElementCanHaveChildren()) {
$innerHTML.show();
$("textarea", $innerHTML).val(self._getSelectedElementInnerHTML());
} else {
$innerHTML.hide();
}
};
wijeditor.prototype.submitTagInspectorDialog = /** @ignore */
function () {
var self = this, $dlg = self.dialog, el = self._getInspectElement(), $attriblist = $("." + css_taginsdlg_attriblist, $dlg), cssText = $("." + css_taginsdlg_css + " input").val(), innerHTML = $("." + css_taginsdlg_innerhtml + " textarea").val();
try {
$.each($("input:checkbox", $attriblist), function (idx, chk) {
var attrName, attrValue, $chk = $(chk);
if($chk.is(":checked")) {
attrName = $chk.siblings("span").text();
attrName = attrName.substring(0, attrName.length - 1);
attrValue = $chk.siblings("input:text").val();
$(el).attr(attrName, attrValue);
}
});
if($.trim(cssText) !== '') {
el.style.cssText = cssText;
}
if(self._selectedElementCanHaveChildren()) {
$(el).html(innerHTML);
}
} catch (error) {
}
self._closeDialog();
self._addtoUndoBuffer();
self._setSaveBtnEnabled();
};
wijeditor.prototype.tagInspectorDialogSwitchAttList = /** @ignore */
function (element) {
var $attriblis = $("." + css_taginsdlg_attriblist, this.dialog), showAll = !element.checked;
$.each($("input:text", $attriblis), function (idx, text) {
if($(text).val() === "") {
$(text).parent("li")[showAll ? "show" : "hide"]();
}
});
};
wijeditor.prototype._laySelectedElementAttributes = function ($attriblist, $tag) {
var self = this, el = self._getInspectElement(), dic, tag, attrs, localSaveString = this.localizeString("tagInspectorDialogSave", "Save"), html = "";
if(!el) {
return;
}
$tag.html(el.tagName);
dic = self._getDictionaryDeclare();
tag = el.tagName.toLowerCase();
attrs = dic[tag];
switch(tag) {
case 'ul':
case 'u':
case 'textarea':
case 'tbody':
case 'tr':
case 'th':
case 'td':
case 'table':
case 'select':
case 'strong':
case 'span':
case 'p':
case 'option':
case 'ol':
case 'li':
case 'label':
case 'input':
case 'img':
case 'i':
case 'hr':
case 'form':
case 'font':
case 'em':
case 'div':
case 'code':
case 'button':
case 'body':
case 'b':
case 'a':
html += "<ul class='ui-helper-reset'>";
$.each(attrs, function (idx, attr) {
var val = el.getAttribute(attr) || "";
html += "<li><span class='" + css_dlg_text + "'>";
html += attr + ":</span>";
html += "<input type='text' value='" + val + "'/>";
html += "<input type='checkbox' id='save" + idx + "'/>";
html += "<label for='save" + idx + "'>" + localSaveString + "</label></li>";
});
break;
}
$attriblist.html(html);
};
wijeditor.prototype._getSelectedElementStyle = function () {
var inspElem = this._getInspectElement();
if(inspElem && inspElem.style) {
return inspElem.style.cssText || '';
} else {
return '';
}
};
wijeditor.prototype._getSelectedElementInnerHTML = function () {
var inspElem = this._getInspectElement();
if(inspElem) {
return inspElem.innerHTML;
} else {
return '';
}
};
wijeditor.prototype._selectedElementCanHaveChildren = function () {
return !$(this._getInspectElement()).is("input,hr,br,img");
};
wijeditor.prototype.initBackColorDialog = //end of tag inspector dialog.
//begin to handle the color dialog.
/** @ignore */
function () {
this._initColorDialog("BackColor");
};
wijeditor.prototype.initForeColorDialog = /** @ignore */
function () {
this._initColorDialog("ForeColor");
};
wijeditor.prototype._initColorDialog = function (colorCommand) {
var self = this, $dlg = self.dialog, doc = self._getDesignViewDocument(), color = doc.queryCommandValue(colorCommand), iColor, items, sColor;
$dlg.delegate(selector_dlg_ok, "click." + self.widgetName, function (e) {
self.submitColorDialog(colorCommand);
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(e);
//end for change happens
}).delegate(selector_dlg_cancel, "click." + self.widgetName, function () {
self._closeDialog();
});
if(color) {
sColor = color.toString();
//update for case 27846 issue
if($.browser.mozilla && sColor === "transparent") {
sColor = "#ffffff";
}
if($.browser.msie) {
iColor = wijParseInt(sColor);
sColor = 'rgb(' + (iColor & 255) + ', ' + ((iColor & 65280) >> 8) + ', ' + ((iColor & 16711680) >> 16) + ')';
}
if(sColor.indexOf('rgb(') === 0) {
items = sColor.substring(4, sColor.length - 1).split(',');
sColor = self._convertToWebColor(wijParseInt(items[0]), wijParseInt(items[1]), wijParseInt(items[2]));
} else if(sColor.indexOf('rgba(') === 0) {
items = sColor.substring(5, sColor.length - 1).split(',');
sColor = self._convertToWebColor(wijParseInt(items[0]), wijParseInt(items[1]), wijParseInt(items[2]));
}
$("." + css_colordlg_color + " input", $dlg).attr("value", sColor);
}
$("." + css_colordlg_picker, $dlg).wijeditorcolorcanvas("." + css_colordlg_color + " input", sColor);
};
wijeditor.prototype.submitColorDialog = /** @ignore */
function (colorCommand) {
var self = this, $color = $("." + css_colordlg_color + " input", self.dialog);
self.setColor(colorCommand, $color.val());
self._closeDialog();
};
wijeditor.prototype.setColor = /** @ignore */
function (cmdID, color) {
var self = this, doc = self._getDesignViewDocument(), win = self._getDesignViewWindow(), selection;
self._setIESelection();
if($.browser.mozilla && cmdID === 'BackColor') {
selection = win.getSelection();
self.insertHTML('<span style="background-color:' + color + ';">' + selection + '</span>');
} else {
doc.execCommand(cmdID, false, color);
if(self.options.mode === "bbcode" && !($.browser.msie)) {
self._convertFontStyleToStandTag();
}
}
self._addtoUndoBuffer();
self._setSaveBtnEnabled();
};
wijeditor.prototype.initInsertTableDialog = //end of color dialog.
//begin to handle the table dialog.
////begin to handle the insert table dialog.
/** @ignore */
function () {
var self = this, $dlg = self.dialog;
$dlg.delegate(selector_dlg_ok, "click." + self.widgetName, function (e) {
self.submitInsertTableDialog();
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(e);
//end for change happens
}).delegate(//update for fixing issue 20275 issue by wh at 2012/3/12
//note: jquery upgrade the first and last have some problems
//.delegate(selector_dlg_cancel, "click." + self.widgetName, function () {
selector_input_cancel, "click." + self.widgetName, function () {
//end for 20275 issue
self._closeDialog();
}).delegate("." + css_tabledlg_bgcolor + " input:button", "click." + self.widgetName, function () {
self.showTableColorDialog(this);
});
};
wijeditor.prototype.submitInsertTableDialog = /** @ignore */
function () {
var self = this, attribs = self._getValuesFromTableDialog();
if(!attribs) {
return;
}
self._insertTable(attribs);
self._closeDialog();
};
wijeditor.prototype._insertTable = function (attribs) {
var self = this, html = '', i, j;
if(!attribs) {
return false;
}
self.focus();
html += '<table width="' + attribs.width + '" height="' + attribs.height + '" cellspacing="' + attribs.cspacing + '" cellpadding="' + attribs.cpadding + '" border="' + attribs.border + '" bgcolor="' + attribs.bgcolor + '" style="' + attribs.css + '">';
for(i = 0; i < attribs.rows; i++) {
html += '<tr>';
for(j = 0; j < attribs.cols; j++) {
html += '<td>Cell ' + (i + 1) + '-' + (j + 1) + '</td>';
}
html += '</tr>';
}
html += '</table>';
if($.browser.mozilla || ($.browser.msie && wijParseInt($.browser.version) >= 9)) {
html += '<br />';
}
self.insertHTML(html);
};
wijeditor.prototype.initEditTableDialog = ////end of the insert table dialog.
////begin to handle the edit table dialog.
/** @ignore */
function () {
var self = this, $dlg = self.dialog, el = self._getInspectElement(), rows, columns;
$dlg.delegate(selector_dlg_ok, "click." + self.widgetName, function (e) {
self.submitEditTableDialog();
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(e);
//end for change happens
}).delegate(//update for fixing 20275 issue by wh at 2012/3/12
//.delegate(selector_dlg_cancel, "click." + self.widgetName, function () {
selector_input_cancel, "click." + self.widgetName, function () {
self._closeDialog();
}).delegate(//end for 20275 issue
"." + css_tabledlg_bgcolor + " input:button", "click." + self.widgetName, function () {
self.showTableColorDialog(this);
});
if(!el) {
return;
}
try {
rows = el.rows;
if(rows.length > 0) {
columns = rows[0].cells.length;
} else {
columns = 0;
}
rows = rows.length;
} catch (e) {
}
$("." + css_tabledlg_rows + " input", $dlg).val(rows);
$("." + css_tabledlg_columns + " input", $dlg).val(columns);
$("." + css_tabledlg_width + " input", $dlg).val(el.getAttribute("width"));
$("." + css_tabledlg_height + " input", $dlg).val(el.getAttribute("height"));
$("." + css_tabledlg_border + " input", $dlg).val(el.getAttribute("border"));
$("." + css_tabledlg_cellpadding + " input", $dlg).val(el.getAttribute("cellPadding"));
$("." + css_tabledlg_cellspacing + " input", $dlg).val(el.getAttribute("cellSpacing"));
$("." + css_tabledlg_bgcolor + " input", $dlg).val(el.getAttribute("bgcolor") || "#ffffff");
$("." + css_tabledlg_csstext + " input", $dlg).val(el.style.cssText);
};
wijeditor.prototype.submitEditTableDialog = /** @ignore */
function () {
var self = this, el = self._getInspectElement(), $el = $(el), attribs = self._getValuesFromTableDialog(), rows = attribs && wijParseInt(attribs.rows), cols = attribs && wijParseInt(attribs.cols), newRow, newCell;
if(!attribs) {
return;
}
if(el) {
$el.attr("width", attribs.width);
$el.attr("height", attribs.height);
$el.attr("bgcolor", attribs.bgcolor);
$el.attr("border", attribs.border);
$el.attr("cellSpacing", attribs.cspacing);
$el.attr("cellPadding", attribs.cpadding);
el.style.cssText = attribs.css;
if(!rows || isNaN(rows)) {
return;
}
if(!cols || isNaN(cols)) {
return;
}
while(el.rows.length > rows) {
el.deleteRow(0);
}
while(el.rows.length < rows) {
newRow = el.insertRow(0);
while(newRow.cells.length < cols) {
newCell = newRow.insertCell(0);
newCell.innerHTML = ' ';
}
}
$.each(el.rows, function (idx, row) {
while(row.cells.length > cols) {
row.deleteCell(0);
}
while(row.cells.length < cols) {
newCell = row.insertCell(0);
newCell.innerHTML = ' ';
}
});
}
self._closeDialog();
};
wijeditor.prototype._getValuesFromTableDialog = ////end of the edit table dialog.
function () {
var self = this, $dlg = self.dialog, rows = $("." + css_tabledlg_rows + " input", $dlg).val(), cols = $("." + css_tabledlg_columns + " input", $dlg).val(), width = $("." + css_tabledlg_width + " input", $dlg).val(), height = $("." + css_tabledlg_height + " input", $dlg).val(), border = $("." + css_tabledlg_border + " input", $dlg).val(), cpadding = $("." + css_tabledlg_cellpadding + " input", $dlg).val(), cspacing = $("." + css_tabledlg_cellspacing + " input", $dlg).val(), css = $("." + css_tabledlg_csstext + " input", $dlg).val(), bgcolor = $("." + css_tabledlg_bgcolor + " input", $dlg).val();
if(!self._isNumeric(rows)) {
wijAlert(this.localizeString("errorMessageRowsError", "Please input a number for 'Rows' textbox."));
return false;
}
if(!self._isNumeric(cols)) {
wijAlert(this.localizeString("errorMessageColumnsError", "Please input a number for 'Columns' textbox."));
return false;
}
if(!self._isNumeric(width)) {
wijAlert(this.localizeString("errorMessageTableWidthError", "Please input a number for 'Table Width ' textbox."));
return false;
}
if(!self._isNumeric(height)) {
wijAlert(this.localizeString("errorMessageTableHeightError", "Please input a number for 'Table Height' textbox."));
return false;
}
if(!self._isNumeric(border)) {
wijAlert(this.localizeString("tableDialogBorderError", "Please input a number for 'Border thickness' textbox."));
return false;
}
if(!self._isNumeric(cpadding)) {
wijAlert(this.localizeString("tableDialogCellPaddingError", "Please input a number for 'Cell Padding' textbox."));
return false;
}
if(!self._isNumeric(cspacing)) {
wijAlert(this.localizeString("tableDialogCellSpacingError", "Please input a number for 'Cell Spacing' textbox."));
return false;
}
return {
rows: rows,
cols: cols,
width: wijParseInt(width),
height: wijParseInt(height),
border: border,
cpadding: cpadding,
cspacing: cspacing,
css: css,
bgcolor: bgcolor
};
};
wijeditor.prototype.showTableColorDialog = /** @ignore */
function (el) {
var self = this, dialogOpts, $subDlg = self.subDialog, bgcolor = $(el).prev().val(), content = self._getDialogRes_Color();
dialogOpts = {
width: "auto",
height: "auto",
modal: true,
title: "Set Background Color",
position: "center",
resizable: false,
captionButtons: {
pin: {
visible: false
},
refresh: {
visible: false
},
toggle: {
visible: false
},
minimize: {
visible: false
},
maximize: {
visible: false
}
}
};
$subDlg.empty().append(content);
if($.browser.msie && wijParseInt($.browser.version) === 6) {
window.setTimeout(function () {
$subDlg.wijdialog(dialogOpts);
}, 0);
} else {
$subDlg.wijdialog(dialogOpts);
}
//update for fixing issue 20275 by wh at 2012/3/12
//$subDlg.delegate(selector_dlg_ok,, "click." + self.widgetName, function () {
$subDlg.delegate(selector_input_ok, "click." + self.widgetName, function () {
self.submitTableColorDialog();
}).delegate(//.delegate(selector_dlg_cancel, "click." + self.widgetName, function () {
selector_input_cancel, "click." + self.widgetName, function () {
self.closeSubDialog();
});
//end for 20275 issue
if(bgcolor !== "") {
$("." + css_colordlg_color + " input", $subDlg).val(bgcolor);
}
$("." + css_colordlg_picker, $subDlg).wijeditorcolorcanvas("." + css_colordlg_color + " input", bgcolor);
$subDlg.wijdialog("open");
};
wijeditor.prototype.submitTableColorDialog = /** @ignore */
function () {
var self = this, $subDlg = self.subDialog, $dlg = self.dialog, color = $("." + css_colordlg_color + " input", $subDlg).val();
$("." + css_tabledlg_bgcolor + " input:text", $dlg).val(color);
self.closeSubDialog();
};
wijeditor.prototype.closeSubDialog = /** @ignore */
function () {
this.subDialog.wijdialog("close");
};
wijeditor.prototype._getEditableTable = function () {
var self = this, table, editableTable, $editableTable;
editableTable = self._getSelectedElement();
if(!editableTable) {
wijAlert(this.localizeString("errorMessageSelectTableError", "Please select a table!"));
return false;
}
$editableTable = $(editableTable);
if($editableTable.is("td,tr,tbody,th")) {
editableTable = $editableTable.parents("table:first")[0];
} else if(!$editableTable.is("table")) {
table = $editableTable.find("table:only-child");
if($.browser.msie && table.length) {
editableTable = table[0];
} else {
wijAlert(this.localizeString("errorMessageSelectTableError", "Please select a table!"));
return false;
}
}
inspectElement = editableTable;
return true;
};
wijeditor.prototype.initPreviewDialog = //end of table dialog.
//begin to handle the preview dialog.
/** @ignore */
function () {
var self = this, $dlg = self.dialog;
self._setPreviewContent(0);
$dlg.delegate("#rad640_480", "click." + self.widgetName, function () {
self._setPreviewDialogSize(640, 480);
}).delegate("#rad800_600", "click." + self.widgetName, function () {
self._setPreviewDialogSize(800, 600);
}).delegate("#rad1024_768", "click." + self.widgetName, function () {
self._setPreviewDialogSize(1024, 768);
}).delegate("#chkSplit", "click." + self.widgetName, function () {
self._splitPreviewPages(this.checked);
}).delegate("." + css_previewdlg_printall, "click." + self.widgetName, function () {
self._printPreviewPage(true);
}).delegate("." + css_previewdlg_printone, "click." + self.widgetName, function () {
self._printPreviewPage(false);
}).delegate("." + css_previewdlg_ok, "click." + self.widgetName, function () {
self._closeDialog();
}).delegate("." + css_previewdlg_prev, "click." + self.widgetName, function () {
self._navigatePreviewPage(false);
}).delegate("." + css_previewdlg_next, "click." + self.widgetName, function () {
self._navigatePreviewPage(true);
});
};
wijeditor.prototype._setPreviewContent = function (pageIndex) {
var self = this, $dlg = self.dialog, $iframe = $("iframe", $dlg), $pager = $("." + css_previewdlg_navigator + " span", $dlg), doc = ($iframe[0]).contentWindow.document;
doc.open();
if(pageIndex === -1) {
doc.write(self._getPreviewAllPageContent());
$pager.html('1 / 1');
} else {
doc.write(self._getPreviewPageContent(pageIndex));
$pager.html((pageIndex + 1) + ' / ' + self._getPreviewPageCount());
}
doc.close();
};
wijeditor.prototype._setPreviewDialogSize = function (width, height) {
var self = this, $dlg = self.dialog, $iframe = $("iframe", $dlg), offsetW = $dlg.wijdialog("option", "width"), offsetH = $dlg.wijdialog("option", "height");
if(offsetW === "auto") {
offsetW = $dlg.parent(".wijmo-wijdialog").width() - $iframe.width();
} else {
offsetW = offsetW - $iframe.width();
}
if(offsetH === "auto") {
offsetH = $dlg.parent(".wijmo-wijdialog").height() - $iframe.height();
} else {
offsetH = offsetH - $iframe.height();
}
$iframe.css("width", width).css("height", height);
$dlg.wijdialog("option", {
width: width + offsetW,
height: height + offsetH
});
};
wijeditor.prototype._getPreviewPageCount = function () {
return this._getPreviewPages().length;
};
wijeditor.prototype._getPreviewPageContent = function (pageIndex) {
var contents = this._getPreviewPages();
if(contents.length > pageIndex) {
return contents[pageIndex];
}
return null;
};
wijeditor.prototype._getPreviewAllPageContent = function () {
return this._getDesignViewText();
};
wijeditor.prototype._getPreviewPages = function () {
var contents = this._getPreviewAllPageContent(), regexp = new RegExp('<(DIV|div)[^>]*(page-break-before|' + 'PAGE-BREAK-BEFORE)[ ]*:[ ]*always[^>]*>(.*?)<\\/(DIV|div)>', 'g'), tempContents = contents.replace(regexp, '!-~U^n#i@q,P|.a=g~e+br!');
return tempContents.split('!-~U^n#i@q,P|.a=g~e+br!');
};
wijeditor.prototype._splitPreviewPages = //_curPageIdx: 0,
function (isSplit) {
var self = this, $dlg = self.dialog, $pdoc = $("." + css_previewdlg_printdocument, $dlg), $pnav = $("." + css_previewdlg_navigator, $dlg);
if(isSplit) {
self._setPreviewContent(0);
$pnav.show();
$pdoc.hide();
} else {
self._setPreviewContent(-1);
$pnav.hide();
$pdoc.show();
}
self._curPageIdx = 0;
};
wijeditor.prototype._navigatePreviewPage = function (isNext) {
var self = this, $chkSplit = $("#chkSplit", self.dialog), curIdx = self._curPageIdx, pageCount = self._getPreviewPageCount();
if($chkSplit.is(":checked")) {
if(isNext) {
curIdx++;
if(curIdx < pageCount) {
self._setPreviewContent(curIdx);
} else {
curIdx = pageCount - 1;
}
} else {
curIdx--;
if(curIdx >= 0) {
self._setPreviewContent(curIdx);
} else {
curIdx = 0;
}
}
self._curPageIdx = curIdx;
}
};
wijeditor.prototype._printPreviewPage = function (isAll) {
var self = this, $dlg = self.dialog, $chkSplit = $("#chkSplit", $dlg), win = ($("iframe", $dlg)[0]).contentWindow;
if(isAll) {
$chkSplit.removeAttr("checked");
self._setPreviewContent(-1);
}
win.focus();
win.print();
};
wijeditor.prototype.initCleanUpDialog = //end of preview dialog.
//begin to handle the cleanup dialog.
/** @ignore */
function () {
var self = this, $dlg = self.dialog;
$("textarea", $dlg).val(self.sourceView.val());
$dlg.delegate(selector_dlg_ok, "click." + self.widgetName, function (e) {
self.submitCleanUpDialog();
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(e);
//end for change happens
}).delegate(selector_dlg_cancel, "click." + self.widgetName, function () {
self._closeDialog();
});
};
wijeditor.prototype.submitCleanUpDialog = /** @ignore */
function () {
var self = this, $dlg = self.dialog, $sourceView = self.sourceView, source = $sourceView.val(), reg;
if($("#replaceSpans", $dlg).is(":checked")) {
reg = new RegExp('<\\/?SPAN[^>]*>', 'g');
source = source.replace(reg, '');
}
if($("#replaceClass", $dlg).is(":checked")) {
reg = new RegExp('<(\\w[^>]*) class=([^ |>]*)([^>]*)', 'g');
source = source.replace(reg, '<$1$3');
}
if($("#replaceStyle", $dlg).is(":checked")) {
reg = new RegExp('<(\\w[^>]*) style=\"([^\"]*)\"([^>]*)', 'g');
source = source.replace(reg, '<$1$3');
reg = new RegExp('<(\\w[^>]*) lang=([^ |>]*)([^>]*)', 'g');
source = source.replace(reg, '<$1$3');
reg = new RegExp('<\\\\?\\?xml[^>]*>', 'g');
source = source.replace(reg, '');
reg = new RegExp('<\\/?\\w+:[^>]*>', 'g');
source = source.replace(reg, '');
}
if($("#replaceNbsp", $dlg).is(":checked")) {
reg = new RegExp(' ', 'g');
source = source.replace(reg, ' ');
}
if($("#transformPtoDiv", $dlg).is(":checked")) {
reg = new RegExp('(<P)([^>]*>.*?)(<\\/P>)', 'g');
source = source.replace(reg, '<div$2</div>');
}
$sourceView.val(source);
self._setDesignViewText(source);
self._addtoUndoBuffer();
self._closeDialog();
};
wijeditor.prototype.initFindDialog = //end of cleanup dialog.
//begin to handle the find/replace dialog.
/** @ignore */
function () {
var self = this, $dlg = self.dialog;
//update for fixing issue 20316 by wh at 2012/3/14
if(self.tRange) {
self.tRange = null;
}
//end for 20316 issue.
$dlg.delegate(selector_dlg_ok, "click." + self.widgetName, function () {
self.submitFindAction();
}).delegate(selector_dlg_cancel, "click." + self.widgetName, function (e) {
self.submitReplaceAction();
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(e);
//end for change happens
});
};
wijeditor.prototype.submitFindAction = /** @ignore */
function () {
var self = this, text = $("textarea:first", self.dialog).val();
if($.trim(text) === '') {
return;
}
self._findAndReplaceString(text);
};
wijeditor.prototype.submitReplaceAction = /** @ignore */
function () {
var self = this, $dlg = self.dialog, fText = $("textarea:first", $dlg).val(), rText = $("textarea:last", $dlg).val();
if($.trim(fText) === '') {
return;
}
if($.trim(rText) === '') {
wijAlert(this.localizeString("errorMessageReplaceStringError", "please input replace string!"));
return;
}
self._findAndReplaceString(fText, rText);
};
wijeditor.prototype._findAndReplaceString = //tRange: null;
//txtFoundInIE: false;
//txtFoundInNoneIE: false;
function (fText, rText) {
var self = this, contentWindow = self._getDesignViewWindow(), strFound = 0, strReplaced = false, needReplace = rText && rText !== fText;
if(!rText) {
rText = fText;
}
if($.browser.msie) {
if(self.tRange) {
if(self.txtFoundInIE && needReplace) {
strFound = self.tRange.findText(fText);
if(strFound) {
self.tRange.pasteHTML(rText);
self.tRange.collapse(false);
strReplaced = true;
self.txtFoundInIE = false;
}
} else {
self.tRange.collapse(false);
strFound = self.tRange.findText(fText);
if(strFound) {
self.tRange.select();
}
}
}
if(!strReplaced && (!self.tRange || !strFound)) {
self.tRange = contentWindow.document.body.createTextRange();
strFound = self.tRange.findText(fText);
if(strFound) {
self.tRange.select();
if(needReplace) {
self.tRange.pasteHTML(rText);
strReplaced = true;
}
}
}
} else {
if(self.txtFoundInNoneIE && needReplace) {
self._replaceSelectionForNoneIE(rText);
strReplaced = true;
self.txtFoundInNoneIE = false;
} else {
strFound = contentWindow.find(fText);
if(!strFound) {
strFound = contentWindow.find(fText, 0, 1);
while(contentWindow.find(fText, 0, 1)) {
continue;
}
}
}
self.txtFoundInNoneIE = self.txtFoundInNoneIE || strFound;
if(self.txtFoundInNoneIE && needReplace) {
self._replaceSelectionForNoneIE(rText);
strReplaced = true;
self.txtFoundInNoneIE = false;
}
}
if(!strFound && !strReplaced) {
wijAlert('"' + fText + '"' + this.localizeString("errorMessageFindTextError", " String Not Found!"));
self.tRange = null;
self.txtFoundInNoneIE = false;
self.txtFoundInIE = false;
} else {
self.txtFoundInIE = true;
}
};
wijeditor.prototype._replaceSelectionForNoneIE = function (html) {
var doc = this._getDesignViewDocument();
//randomStr = 'insert_html_' + Math.round(Math.random() * 100000000);
//regex = new RegExp('<[^<]*' + randomStr + '[^>]*>');
/** update for case 30008
doc.execCommand('insertimage', false, randomStr);
doc.body.innerHTML = doc.body.innerHTML.replace(regex, html);
*/
doc.execCommand('inserthtml', false, html);
};
wijeditor.prototype.initMediaDialog = //end of find/replace dialog.
//begin to handle the media dialog.
/** @ignore */
function () {
var self = this, $dlg = self.dialog;
$dlg.delegate(selector_dlg_ok, "click." + self.widgetName, function (e) {
self.submitMediaDialog();
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(e);
//end for change happens
}).delegate(selector_dlg_cancel, "click." + self.widgetName, function () {
self._closeDialog();
});
};
wijeditor.prototype.submitMediaDialog = /** @ignore */
function () {
var self = this, $dlg = self.dialog, type = $("select", $dlg).val(), url = $("." + css_mediadlg_url + " input", $dlg).val(), width = $("." + css_mediadlg_width + " input", $dlg).val(), height = $("." + css_mediadlg_height + " input", $dlg).val();
if(url === '') {
wijAlert(this.localizeString("errorMessageUrlEmptyError", "URL is empty!"));
return;
}
if(!self._isUrl(url)) {
wijAlert(this.localizeString("errorMessageUrlCorrectError", "please input correct URL!"));
return;
}
if(!self._isNumeric(width)) {
wijAlert(this.localizeString("errorMessageMediaWidthError", "please input width of the media!"));
return;
}
if(!self._isNumeric(height)) {
wijAlert(this.localizeString("errorMessageMediaHeightError", "please input height of the media!"));
return;
}
self._insertMedia(type, url, width, height);
self._closeDialog();
};
wijeditor.prototype._insertMedia = function (type, url, width, height) {
var self = this, html = '';
self._setIESelection();
switch(type) {
case 'video':
html += '<embed src="' + url + '" width="' + width + '" ' + 'height="' + height + '" ' + 'type=audio/x-pn-realaudio-plugin console="Clip1" ' + 'controls="IMAGEWINDOW,ControlPanel,StatusBar" ' + 'autostart="true"></embed>';
break;
case 'flash':
html += '<object classid="' + 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ' + 'codebase="http://download.macromedia.com/pub/' + 'shockwave/cabs/flash/swflash.cab#version=6,0,29,0" ' + 'width="' + width + '" height="' + height + '">';
html += '<param name="movie" value="' + url + '">';
html += '<param name="quality" value="high">';
html += '<embed src="' + url + '" quality="high" ' + 'pluginspage="http://www.macromedia.com/go/getflashplayer" ' + 'type="application/x-shockwave-flash" ' + 'width="' + width + '" height="' + height + '"></embed>';
html += '</object>';
break;
case 'applet':
html += '<applet code="' + url + '" width="' + width + '" ' + 'height="' + height + '"></applet>';
break;
case 'other':
html += '<embed src="' + url + '" width="' + width + '" ' + 'height="' + height + '"></embed>';
break;
}
self.insertHTML(html);
};
wijeditor.prototype.initSpecialCharacterDialog = //end of media dialog.
//begin to handle the special char dialog.
/** @ignore */
function () {
var self = this, $dlg = self.dialog, $preview = $("." + css_specialchardlg_content + " span", $dlg);
$dlg.delegate("label", "click." + self.widgetName, function (e) {
self.submitSpecialCharacterDialog(this);
//add for any change happens, the text would be saved by wh at 2011/12/07
self._onDesignViewBlur(e);
//end for change happens
}).delegate(selector_dlg_ok, "click." + self.widgetName, function () {
self._closeDialog();
}).delegate("label", "mouseover." + self.widgetName, function () {
$preview.html($(this).html());
}).delegate("label", "mouseout." + self.widgetName, function () {
$preview.empty();
});
};
wijeditor.prototype.submitSpecialCharacterDialog = /** @ignore */
function (element) {
var self = this;
self._setIESelection();
self.insertHTML($(element).html());
self._closeDialog();
};
wijeditor.prototype._setSaveBtnEnabled = //end of special dialog.
// selectElement: function (pElement) {
// var designView = this._getDesignView().get(0);
// //
// this._C1WEB__SelectElement(designView.contentWindow, pElement);
// this.refreshPathSelector();
// },
//begin to handle the ribbon commands.
function () {
this.$ribbon.wijribbon(setButtonDisabled, cmd_save, false);
};
wijeditor.prototype._undoAction = //undo/redo action.
function () {
var body = this._getDesignViewDocument().body, buttonStates = {
};
undoSteps--;
if(undoSteps <= 0) {
undoSteps = 0;
}
body.innerHTML = undoBuffers[undoSteps];
if(!undoSteps) {
buttonStates[cmd_undo] = true;
buttonStates[cmd_redo] = false;
this.$ribbon.wijribbon(setButtonsDisabled, buttonStates);
} else {
this.$ribbon.wijribbon(setButtonDisabled, cmd_redo, false);
}
};
wijeditor.prototype._redoAction = function () {
var body = this._getDesignViewDocument().body, len = undoBuffers.length, buttonStates = {
};
undoSteps++;
if(undoSteps >= len - 1) {
undoSteps = len - 1;
}
body.innerHTML = undoBuffers[undoSteps];
if(undoSteps === len - 1) {
buttonStates[cmd_undo] = false;
buttonStates[cmd_redo] = true;
this.$ribbon.wijribbon(setButtonsDisabled, buttonStates);
} else {
this.$ribbon.wijribbon(setButtonDisabled, cmd_undo, false);
}
};
wijeditor.prototype._addtoUndoBuffer = function () {
var len = undoBuffers.length - 1 - undoSteps, idx;
for(idx = 0; idx < len; idx++) {
undoBuffers.pop();
}
undoSteps++;
undoBuffers.push(this._getDesignViewText());
this.$ribbon.wijribbon(setButtonDisabled, cmd_undo, false);
};
wijeditor.prototype._deleteSelectionContent = //end of undo/redo action.
//delete action for cut.
function () {
var cWin = this._getDesignViewWindow(), selection, i, range, rangeCount = "rangeCount";
if($.browser.msie) {
selection = cWin.document.selection;
if(selection.type.toLowerCase() !== 'none') {
selection.clear();
}
} else {
selection = cWin.getSelection();
for(i = 0; i < selection[rangeCount]; i++) {
range = selection.getRangeAt(i);
range.deleteContents();
}
}
};
wijeditor.prototype._refreshPathSelector = //end of delete action for cut.
//path selector action.
function () {
var self = this, inspEl = self._getParentElement(self._getDesignViewWindow()), inspElName, $pathSelector = self._getPathSelector(), $parents = $(inspEl).parents(), len = $parents.length, css = "wijmo-wijeditor-label ui-state-default ui-corner-all", idx;
if(!inspEl) {
return;
}
inspElName = inspEl.tagName ? inspEl.tagName.toLowerCase() : "";
$pathSelector.empty();
for(idx = len - 1; idx >= 0; idx--) {
$pathSelector.append("<label class='" + css + "'><" + $parents[idx].tagName.toLowerCase() + "></label>");
}
$pathSelector.append("<label class='" + css + " wijmo-wijeditor-selectlabel ui-state-highlight ui-corner-all'><" + inspElName + "></label>");
};
wijeditor.prototype._toggleTableBorders = //end of path selector action.
//table borders action.
function () {
var doc = this._getDesignViewDocument(), $bStyle = $('#__wijStyle', doc);
tblBorderShowing = !tblBorderShowing;
if($.browser.safari) {
if(tblBorderShowing) {
$bStyle.html('table,td,tr{border: 1px #acacac dashed;}');
} else {
$bStyle.empty();
}
} else {
$bStyle.prop("disabled", !tblBorderShowing);
}
};
wijeditor.prototype._tableAction = //end of table borders action.
//table action.
function (type) {
var self = this, inspEl = self._getParentElement(self._getDesignViewWindow()), $td = $(inspEl).closest("td"), $tr, $table, td, tr, table, rowIdx, cellIdx, cellCount, rowCount, newRow, idx = 0;
self._setSaveBtnEnabled();
if($td.length === 0 && type !== cmd_mergecell) {
return false;
} else if(type !== cmd_mergecell) {
$tr = $td.parent();
$table = $tr.closest("table");
td = $td[0];
tr = $tr[0];
table = $table[0];
rowIdx = tr.rowIndex;
cellIdx = td.cellIndex;
}
try {
switch(type) {
case cmd_insertrow:
cellCount = tr.cells.length;
newRow = table.insertRow(rowIdx);
for(idx = 0; idx < cellCount; idx++) {
self._insertCell(newRow, idx);
}
break;
case cmd_removerow:
table.deleteRow(rowIdx);
break;
case cmd_insertcolumn:
rowCount = table.rows.length;
for(idx = 0; idx < rowCount; idx++) {
self._insertCell(table.rows[idx], cellIdx);
}
break;
case cmd_removecolumn:
self._removeColumn(table, cellIdx);
break;
case cmd_insertcell:
self._insertCell(tr, cellIdx + 1);
break;
case cmd_removecell:
cellCount = tr.cells.length;
if(cellCount === 1) {
table.deleteRow(rowIdx);
} else {
tr.deleteCell(cellIdx);
}
break;
case cmd_splitcell:
self._splitCell(table, tr, rowIdx, cellIdx);
break;
case cmd_mergecell:
self._mergeCell(self._getSelectedCells(inspEl));
break;
}
//
this._addtoUndoBuffer();
} catch (e) {
wijAlert(e.message);
return false;
}
return true;
};
wijeditor.prototype._removeColumn = function (table, curCellIndex) {
var rowCount = table.rows.length, idx = 0, tr, cells, cellCount, cellIdx, colSpan;
while(idx < rowCount) {
tr = table.rows[idx];
cells = tr.cells;
cellCount = cells.length;
cellIdx = (curCellIndex > cellCount - 1) ? cellCount - 1 : curCellIndex;
colSpan = cells[cellIdx].colSpan;
if(colSpan > 1 && cellCount > 1) {
if(cellIdx + 1 < cellCount) {
(cells[cellIdx + 1]).colSpan += colSpan - 1;
} else {
(cells[cellIdx - 1]).colSpan += colSpan + 1;
}
}
if(cellCount === 1) {
table.deleteRow(idx);
rowCount = table.rows.length;
} else {
tr.deleteCell(cellIdx);
idx++;
}
}
};
wijeditor.prototype._splitCell = function (table, tr, rowIndex, cellIndex) {
var rowCount = table.rows.length, idx = 0, colSpan = 0, tempRow, tempColSpan, i, maxCellIdx, tempRowCount;
while(idx <= cellIndex) {
if(tr.cells[idx].colSpan > 1) {
colSpan += tr.cells[idx].colSpan - 1;
}
idx++;
}
this._insertCell(tr, cellIndex + 1);
for(i = 0; i < rowCount; i++) {
tempRow = table.rows[i];
if(i !== rowIndex) {
maxCellIdx = cellIndex;
idx = 0;
tempColSpan = 0;
while(idx <= maxCellIdx) {
if(tempRow.cells[idx].colSpan > 1) {
tempColSpan += tempRow.cells[idx].colSpan - 1;
maxCellIdx -= tempColSpan;
}
idx++;
}
tempRowCount = cellIndex + colSpan - tempColSpan;
if(tempRowCount < 0) {
tempRowCount = 0;
}
tempRow.cells[tempRowCount].colSpan++;
}
}
};
wijeditor.prototype._mergeCell = function (cells) {
var len = cells.length, tr, sIdx, eIdx, idx;
if(len < 2 || cells[0].parentNode !== cells[len - 1].parentNode) {
return false;
}
tr = cells[0].parentNode;
sIdx = cells[0].cellIndex;
eIdx = sIdx + len;
for(idx = sIdx + 1; idx < eIdx; idx++) {
tr.cells[sIdx].innerHTML += tr.cells[sIdx + 1].innerHTML;
tr.cells[sIdx].colSpan++;
tr.deleteCell(sIdx + 1);
}
};
wijeditor.prototype._getSelectedCells = function (inspEl) {
var win = this._getDesignViewWindow(), doc = win.document, cells = [], range, parent, selection, idx, rangeCount, sContainer, nodeName, offset;
if($.browser.msie) {
range = doc.selection.createRange();
parent = $(inspEl).closest("tr")[0];
if(parent) {
$.each(parent.cells, function (idx, cell) {
var cellRange = doc.selection.createRange(), cep = "compareEndPoints";
cellRange.moveToElementText(cell);
if(range.inRange(cellRange) || (range[cep]('StartToStart', cellRange) >= 0 && range[cep]('StartToEnd', cellRange) <= 0) || (range[cep]('EndToStart', cellRange) >= 0 && range[cep]('EndToEnd', cellRange) <= 0)) {
cells.push(cell);
}
});
}
} else if($.browser.mozilla) {
selection = win.getSelection();
rangeCount = selection.rangeCount;
for(idx = 0; idx < rangeCount; idx++) {
range = selection.getRangeAt(idx);
sContainer = range.startContainer;
nodeName = sContainer.nodeName.toLowerCase();
if(nodeName === 'td' || nodeName === 'th') {
cells.push(sContainer);
} else if(nodeName === 'tr') {
offset = range.startOffset;
cells.push(sContainer.cells[offset]);
}
}
} else {
selection = win.getSelection();
parent = $(inspEl).closest("tr")[0];
if(parent) {
rangeCount = parent.cells.length;
for(idx = 0; idx < rangeCount; idx++) {
cells.push(parent.cells[idx]);
}
}
}
return cells;
};
wijeditor.prototype.insertDateAndTime = //end of table action.
//insert date time.
/** @ignore */
function () {
var curDate = new Date();
if(this.options.culture && this.options.culture !== "") {
this.insertHTML(Globalize.format(curDate, "dddd ", Globalize.findClosestCulture(this.options.culture)) + Globalize.format(curDate, "F", Globalize.findClosestCulture(this.options.culture)));
} else {
this.insertHTML(curDate.toDateString() + ' ' + curDate.toTimeString());
}
};
wijeditor.prototype._toggleWordWrap = //end of insert date time.
//wordwrap action.
function () {
var self = this, $sourceView = self.sourceView, wrap = "wrap", value;
wordwrap = !wordwrap;
value = wordwrap ? 'soft' : 'off';
$sourceView.attr(wrap, value);
$sourceView[0].focus();
if($.browser.mozilla) {
$sourceView.hide();
wijWindow.setTimeout(function () {
$sourceView.show();
}, 40);
}
};
wijeditor.prototype.insertHTML = //end of wordwrap action.
//insert html text to the document.
/** @ignore */
function (htmlText) {
var self = this, doc = self._getDesignViewDocument(), range;
try {
if($.browser.msie) {
range = doc.selection.createRange();
range.pasteHTML(htmlText);
range.collapse(false);
range.select();
} else {
doc.execCommand('insertHTML', false, htmlText);
}
} catch (e) {
}
self._addtoUndoBuffer();
self._setSaveBtnEnabled();
};
wijeditor.prototype._getSelectedContent = //end of insert html text to the document.
//get selected content.
function () {
var win = this._getDesignViewWindow(), doc = win.document, selectedContent = "", cloneContents = "cloneContents", range, contents, helperDiv;
if(!doc.selection) {
range = win.getSelection().getRangeAt(0);
if(range) {
if(range[cloneContents]) {
contents = range[cloneContents]();
helperDiv = document.createElement('div');
helperDiv.appendChild(contents);
selectedContent = helperDiv.innerHTML;
helperDiv = null;
}
}
} else {
range = doc.selection.createRange();
return range.htmlText;
}
return selectedContent || "";
};
wijeditor.prototype._setIESelection = //end of get selected content.
//focus related methods in ie.
function () {
if($.browser.msie && rangeSelection) {
rangeSelection.select();
}
};
wijeditor.prototype._setIEFocus = function () {
var doc = this._getDesignViewDocument();
if($.browser.msie) {
try {
doc.body.focus();
} catch (ee) {
}
}
};
wijeditor.prototype.focus = /** @ignore */
function () {
var win = this._getDesignViewWindow(), doc = win.document;
if($.browser.msie) {
if(!rangeSelection) {
//In IE10 Compatibility view, when call the focus too quickly, the iframe document is not loaded,
// the body will be null. So use the onreadystatechange to delay the focus.
if(doc.body) {
doc.body.focus();
} else {
doc.onreadystatechange = function () {
if(doc.readyState === "complete") {
doc.body.focus();
}
};
}
} else {
rangeSelection.select();
}
} else {
win.focus();
}
};
wijeditor.prototype._setFocusNotIE = //end of focus related methods in ie.
function () {
var win = this._getDesignViewWindow();
if(!$.browser.msie) {
win.focus();
}
};
wijeditor.prototype._getInspectElement = //gets inspect element.
function () {
return inspectElement || this._getSelectedElement();
};
wijeditor.prototype._getSelectedElement = function () {
return this._getParentElement(this._getDesignViewWindow());
};
wijeditor.prototype._createElement = //end of gets inspect element.
function (tagName, innerText, attribs) {
return new HtmlElement(tagName, innerText, attribs);
};
wijeditor.prototype._createDiv = function (className, title) {
return this._createElement("div", {
"class": className
});
};
wijeditor.prototype._createSpan = function (className, text) {
var self = this;
if(!text) {
return self._createElement("span", {
"class": className
});
}
if(className.length === 0) {
return self._createElement("span", text);
}
return this._createElement("span", text, {
"class": className
});
};
wijeditor.prototype._createTextBox = function (className, text) {
var attrs = {
"class": className,
"type": "text",
"value": undefined
};
if(text) {
attrs.value = text;
}
return this._createElement("input", attrs);
};
wijeditor.prototype._createLabel = function (text, labelfor) {
if(labelfor) {
return new HtmlElement("label", text, {
"for": labelfor
});
}
return new HtmlElement("label", text);
};
wijeditor.prototype._createRadio = function (id, name, value) {
var attrs = {
name: name,
id: id,
value: value,
type: "radio"
};
return this._createElement("input", attrs);
};
wijeditor.prototype._createCheckbox = function (id) {
var attrs = {
"type": "checkbox",
id: id
};
return this._createElement("input", "", attrs);
};
wijeditor.prototype._createSelect = function (classname, options) {
var self = this, attrs = {
"class": classname
}, select = self._createElement("select", attrs);
if(classname === "") {
select = self._createElement("select");
}
$.each(options, function (i, o) {
if($.isPlainObject(o) && o.selected) {
select.add(self._createElement("option", o.text, {
selected: "selected"
}));
} else {
select.add(self._createElement("option", o));
}
});
return select;
};
wijeditor.prototype._createInputButton = function (className, text) {
var attrs = {
"class": className,
"type": "button",
"value": undefined
};
if(text) {
attrs.value = text;
}
return this._createElement("input", attrs);
};
wijeditor.prototype._createTextField = function (label, className, text, defaultValue) {
var self = this, ele = self._createDiv(className), attrs = {
type: "text",
value: ""
};
if(defaultValue) {
attrs.value = defaultValue;
}
ele.add(self._createSpan(css_dlg_text, label));
ele.add(self._createElement("input", attrs));
if(text) {
ele.add(new TextElement(text));
}
return ele;
};
wijeditor.prototype._createSeparator = function () {
var self = this, hrdiv = self._createDiv(css_dlg_hr);
hrdiv.add(self._createElement("hr"));
return hrdiv;
};
wijeditor.prototype._createOKCancelButtons = function () {
var self = this, buttons = self._createDiv(css_dlg_buttons);
buttons.add(self._createElement("input", {
type: "button",
"class": css_dlg_button,
value: this.localizeString("dialogOK", "OK")
}));
buttons.add(self._createElement("input", {
type: "button",
"class": css_dlg_button,
engValue: "Cancel",
value: this.localizeString("dialogCancel", "Cancel")
}));
return buttons;
};
wijeditor.prototype._getDialogRes_Template = function () {
var self = this, dialog = self._createDiv(css_tpldlg), topLabels = self._createDiv(css_tpl_labels), content = self._createDiv(css_tpl_content), tpllist = self._createDiv(css_tpl_list), preview = self._createDiv(css_tpl_preview), tplinfo = self._createDiv(css_tpl_tplinfo), namefield = self._createElement("div", this.localizeString("templateDialogName", "Name :")), desfield = self._createElement("div", this.localizeString("templateDialogDescription", "Description :")), fields = self._createDiv(css_tpl_fields), tplButtons = self._createDiv(css_tpl_buttons);
topLabels.add(self._createElement("div", this.localizeString("templateDialogSelectTemplate", "Select Template:"), {
"class": css_tpl_tllabel
}));
topLabels.add(self._createElement("div", this.localizeString("templateDialogTemplatePreview", "Template Preview:"), {
"class": css_tpl_trlabel
}));
dialog.add(topLabels);
tpllist.add(self._createElement("select", {
size: 8
}));
preview.add(self._createElement("iframe", {
frameborder: 0
}));
content.add(tpllist);
content.add(preview);
dialog.add(content);
namefield.add(self._createSpan(css_tpl_nameinfo));
desfield.add(self._createSpan(css_tpl_desinfo));
tplinfo.add(namefield);
tplinfo.add(desfield);
dialog.add(tplinfo);
fields.add(self._createSpan(css_dlg_text, this.localizeString("templateDialogName", "Name :")));
fields.add(self._createTextBox(css_tpl_namefield));
fields.add(self._createSpan(css_dlg_text, this.localizeString("templateDialogDescription", "Description :")));
fields.add(self._createTextBox(css_tpl_desfield));
dialog.add(fields);
tplButtons.add(self._createInputButton(css_dlg_button + " " + css_tpl_delete, this.localizeString("templateDialogDeleteSelected", "Delete selected")));
tplButtons.add(self._createInputButton(css_dlg_button + " " + css_tpl_save, this.localizeString("templateDialogSaveCurrentPage", "Save current page as template")));
dialog.add(tplButtons);
dialog.add(self._createSeparator());
dialog.add(self._createOKCancelButtons());
return dialog.render();
};
wijeditor.prototype._getDialogRes_ImageBrowser = function () {
var self = this, dialog = self._createDiv(css_imgdlg), content = self._createDiv(css_imgdlg_content), fields = self._createDiv(css_imgdlg_fields), imgField = self._createDiv(css_imgdlg_field), imglist = self._createDiv(css_imgdlg_list), imgpreview = self._createDiv(css_imgdlg_preview);
fields.add(self._createTextField(this.localizeString("imageEditorDialogImageSrc", "Image Src:"), css_imgdlg_url));
fields.add(self._createTextField(this.localizeString("imageEditorDialogImageAltText", "Image alt text:"), css_imgdlg_alt));
fields.add(self._createTextField(this.localizeString("imageEditorDialogImageWidth", "Image width:"), css_imgdlg_width, this.localizeString("dialogPixel", "px")));
fields.add(self._createTextField(this.localizeString("imageEditorDialogImageHeight", "Image height:"), css_imgdlg_height, this.localizeString("dialogPixel", "px")));
fields.add(self._createTextField(this.localizeString("imageEditorDialogCssText", "Css text:"), css_imgdlg_css));
content.add(fields);
imgField.add(imglist);
imglist.add(self._createElement("select", {
size: 8
}));
imgField.add(imgpreview);
imgpreview.add(self._createElement("img", {
src: "",
alt: ""
}));
content.add(imgField);
content.add(self._createSeparator());
content.add(self._createOKCancelButtons());
dialog.add(content);
return dialog.render();
};
wijeditor.prototype._getDialogRes_Link = function () {
var self = this, dialog = self._createDiv(css_linkdlg), address = self._createTextField(this.localizeString("hyperLinkDialogAddress", "Address :"), css_linkdlg_address), linktype = self._createDiv(css_linkdlg_linktype + " ui-helper-clearfix"), linktypecontainer = self._createElement("div"), imageContainer = self._createDiv(css_linkdlg_imagecontainer), linkIconTypeOuterContainer = self._createDiv(css_linkdlg_linkicontype), linkIconTypeContainer = self._createElement("div"), radioArr = [
{
id: "radUrl",
value: "url",
text: this.localizeString("hyperLinkDialogUrl", "url")
},
{
id: "radAnchor",
value: "anchor",
checked: true,
text: this.localizeString("hyperLinkDialogAnchor", "anchor")
},
{
id: "radMail",
value: "email",
text: this.localizeString("hyperLinkDialogEmail", "email")
}
], linkIconType = [
{
id: "radLinkTypeIsText",
value: "text",
checked: true,
text: this.localizeString("hyperLinkDialogText", "text")
},
{
id: "radLinkTypeIsImage",
value: "image",
text: this.localizeString("hyperLinkDialogImage", "image")
}
], linkTypeOptions = [], text = self._createTextField(this.localizeString("hyperLinkDialogTextToDisplay", "Text to display :"), css_linkdlg_text), inconTypeSpan = self._createSpan(css_dlg_text, this.localizeString("hyperLinkDialogIconType", "Icon Type :")), target = self._createDiv(css_linkdlg_target), targetSpan = self._createSpan(css_dlg_text, this.localizeString("hyperLinkDialogTarget", "Target :")), targetOption = [
{
text: "_blank",
selected: true
},
"_parent",
"_self",
"_top"
], targetSelect = self._createSelect(css_linkdlg_target, targetOption), css = self._createTextField(this.localizeString("hyperLinkDialogCss", "Css :"), css_linkdlg_css), idx;
imageContainer.add(self._createTextField(this.localizeString("imageEditorDialogImageSrc", "Image Src:"), css_linkdlg_url));
imageContainer.add(self._createTextField(this.localizeString("imageEditorDialogImageWidth", "Image width:"), css_linkdlg_width, this.localizeString("dialogPixel", "px")));
imageContainer.add(self._createTextField(this.localizeString("imageEditorDialogImageHeight", "Image height:"), css_linkdlg_height, this.localizeString("dialogPixel", "px")));
dialog.add(address);
dialog.add(linktype);
linktype.add(linktypecontainer);
linkIconTypeOuterContainer.add(linkIconTypeContainer);
linkIconTypeContainer.add(inconTypeSpan);
$.each(radioArr, function (idx, radio) {
linktypecontainer.add(self._createRadio(radio.id, "radioList", radio.value));
linktypecontainer.add(self._createLabel(radio.text, radio.id));
});
$.each(linkIconType, function (idx, radio) {
linkIconTypeContainer.add(self._createRadio(radio.id, "linkIconRadioList", radio.value));
linkIconTypeContainer.add(self._createLabel(radio.text, radio.id));
});
for(idx = 1; idx < 8; idx++) {
linkTypeOptions.push("#anchor" + idx.toString());
}
linktype.add(self._createSelect(css_linkdlg_anchor, linkTypeOptions));
dialog.add(self._createSeparator());
dialog.add(linkIconTypeOuterContainer);
dialog.add(text);
dialog.add(imageContainer);
dialog.add(target);
target.add(targetSpan);
target.add(targetSelect);
dialog.add(css);
dialog.add(self._createSeparator());
dialog.add(self._createOKCancelButtons());
return dialog.render();
};
wijeditor.prototype._getDialogRes_TagInspector = function () {
var self = this, taginsdlg = self._createDiv(css_taginsdlg), caption = self._createDiv(css_taginsdlg_caption), filterempty = self._createDiv(css_taginsdlg_filterempty), attribs = self._createDiv(css_taginsdlg_attribs), innerhtml = self._createDiv(css_taginsdlg_innerhtml);
taginsdlg.add(caption);
caption.add(self._createSpan(css_taginsdlg_taglabel, this.localizeString("tagInspectorDialogSelectedTag", "Selected tag :")));
caption.add(self._createSpan(css_taginsdlg_tagtext, ""));
taginsdlg.add(filterempty);
filterempty.add(self._createCheckbox("displayNoEmpty"));
filterempty.add(self._createLabel(this.localizeString("tagInspectorDialogDisplayNotEmptyAttributes", "Display not empty attributes only"), "displayNoEmpty"));
taginsdlg.add(attribs);
attribs.add(self._createSpan(css_dlg_text, this.localizeString("tagInspectorDialogAttributes", "Attributes:")));
attribs.add(self._createDiv(css_taginsdlg_attriblist));
taginsdlg.add(innerhtml);
innerhtml.add(self._createSpan(css_dlg_text, this.localizeString("tagInspectorDialogInnerHTML", "Inner HTML:")));
innerhtml.add(self._createElement("textarea"));
taginsdlg.add(self._createTextField(this.localizeString("tagInspectorDialogCSSText", "Css Text:"), css_taginsdlg_css));
taginsdlg.add(self._createSeparator());
taginsdlg.add(self._createOKCancelButtons());
return taginsdlg.render();
};
wijeditor.prototype._getDialogRes_Color = function () {
return this._getDialogRes_CommonColor("#FFFFFF");
};
wijeditor.prototype._getDialogRes_ForeColor = function () {
return this._getDialogRes_CommonColor("#000000");
};
wijeditor.prototype._getDialogRes_BackColor = function () {
return this._getDialogRes_CommonColor("#FFFFFF");
};
wijeditor.prototype._getDialogRes_CommonColor = function (initColor) {
var self = this, colordlg = self._createDiv(css_colordlg), color = self._createDiv(css_colordlg_color);
colordlg.add(self._createDiv(css_colordlg_picker));
colordlg.add(color);
color.add(self._createSpan(css_dlg_text, this.localizeString("backColorDialogSelectedColor", "Selected Color:")));
color.add(self._createElement("input", {
type: "text",
value: initColor
}));
colordlg.add(self._createSeparator());
colordlg.add(self._createOKCancelButtons());
return colordlg.render();
};
wijeditor.prototype._getDialogRes_Table = function () {
var self = this, tbldlg = self._createDiv(css_tabledlg), bgcolor = self._createDiv(css_tabledlg_bgcolor);
tbldlg.add(self._createTextField(this.localizeString("tableDialogRows", "Rows :"), css_tabledlg_rows, "", 3));
tbldlg.add(self._createTextField(this.localizeString("tableDialogColumns", "Columns :"), css_tabledlg_columns, "", 3));
tbldlg.add(self._createTextField(this.localizeString("tableDialogTableWidth", "Table Width :"), css_tabledlg_width, this.localizeString("tableDialogPixels", "pixels"), 200));
tbldlg.add(self._createTextField(this.localizeString("tableDialogTableHeight", "Table Height :"), css_tabledlg_height, this.localizeString("tableDialogPixels", "pixels"), 200));
tbldlg.add(self._createTextField(this.localizeString("tableDialogBorder", "Border thickness:"), css_tabledlg_border));
tbldlg.add(self._createTextField(this.localizeString("tableDialogCellPadding", "Cell Padding :"), css_tabledlg_cellpadding));
tbldlg.add(self._createTextField(this.localizeString("tableDialogCellSpacing", "Cell Spacing :"), css_tabledlg_cellspacing));
tbldlg.add(self._createTextField(this.localizeString("tableDialogCssText", "Css Text :"), css_tabledlg_csstext));
tbldlg.add(bgcolor);
bgcolor.add(self._createSpan(css_dlg_text, this.localizeString("tableDialogBackgroundColor", "Background Color:")));
bgcolor.add(self._createElement("input", {
type: "text"
}));
bgcolor.add(self._createElement("input", {
type: "button",
value: "..."
}));
tbldlg.add(self._createSeparator());
tbldlg.add(self._createOKCancelButtons());
return tbldlg.render();
};
wijeditor.prototype._getDialogRes_Preview = function () {
var self = this, previewdlg = self._createDiv(css_previewdlg), caption = self._createDiv(css_previewdlg_caption), buttons = self._createDiv(css_dlg_buttons), navigate = self._createDiv(css_previewdlg_navigator), previewFrame = self._createDiv(css_previewdlg_previewiframe);
previewdlg.add(caption);
caption.add(self._createSpan(css_dlg_text, this.localizeString("previewDialogPreviewSize", "Preview Size:")));
caption.add(self._createElement("input", {
id: "rad640_480",
name: "preview",
type: "radio",
checked: "checked"
}));
caption.add(self._createLabel("640x480", "rad640_480"));
caption.add(self._createElement("input", {
id: "rad800_600",
name: "preview",
type: "radio"
}));
caption.add(self._createLabel("800x600", "rad800_600"));
caption.add(self._createElement("input", {
id: "rad1024_768",
name: "preview",
type: "radio"
}));
caption.add(self._createLabel("1024x768", "rad1024_768"));
caption.add(self._createElement("input", {
id: "chkSplit",
type: "checkbox",
checked: "checked"
}));
caption.add(self._createLabel(this.localizeString("previewDialogSplit", "Split pages"), "chkSplit"));
previewdlg.add(self._createSeparator());
previewdlg.add(buttons);
buttons.add(self._createInputButton(css_dlg_button + " " + css_previewdlg_printall, this.localizeString("previewDialogPrintAll", "Print All")));
buttons.add(self._createInputButton(css_dlg_button + " " + css_previewdlg_printone, this.localizeString("previewDialogPrintPage", "Print Page")));
buttons.add(self._createInputButton(css_dlg_button + " " + css_previewdlg_ok, this.localizeString("dialogOK", "OK")));
previewdlg.add(self._createSeparator());
previewdlg.add(navigate);
navigate.add(self._createElement("a", this.localizeString("previewDialogPrevPage", "Prev page"), {
"class": css_previewdlg_prev,
href: "#"
}));
navigate.add(self._createElement("span", "1 / 1"));
navigate.add(self._createElement("a", this.localizeString("previewDialogNextPage", "Next page"), {
"class": css_previewdlg_next,
href: "#"
}));
previewdlg.add(self._createDiv(css_previewdlg_printdocument));
previewdlg.add(previewFrame);
previewFrame.add(self._createElement("iframe", {
src: "about:blank"
}));
return previewdlg.render();
};
wijeditor.prototype._getDialogRes_CleanUp = function () {
var self = this, cleanupdlg = self._createDiv(css_cleanupdlg), caption = self._createDiv(css_cleanupdlg_caption), doc = self._createDiv(css_cleanupdlg_document), actions = self._createDiv(css_cleanupdlg_actions), actionsArr = [
{
id: "replaceSpans",
label: this.localizeString("cleanUpDialogStripSpanTag", "Strip SPAN tag")
},
{
id: "replaceClass",
label: this.localizeString("cleanUpDialogStripClass", "Strip CLASS tag")
},
{
id: "replaceStyle",
label: this.localizeString("cleanUpDialogStripStyle", "Strip STYLE attribute")
},
{
id: "replaceNbsp",
label: this.localizeString("cleanUpDialogReplaceSymbol", "Replace &nbsp; symbol")
},
{
id: "transformPtoDiv",
label: this.localizeString("cleanUpDialogTransformParagraphToDIV", "Transform Paragraph to DIV")
}
];
cleanupdlg.add(caption);
caption.add(self._createSpan(css_dlg_text, this.localizeString("cleanUpDialogDocumentSource", "Document source :")));
cleanupdlg.add(doc);
doc.add(self._createElement("textarea", {
readonly: "readonly"
}));
cleanupdlg.add(actions);
$.each(actionsArr, function (i, act) {
actions.add(self._createCheckbox(act.id));
actions.add(self._createLabel(act.label, act.id));
});
cleanupdlg.add(self._createSeparator());
cleanupdlg.add(self._createOKCancelButtons());
return cleanupdlg.render();
};
wijeditor.prototype._getDialogRes_FindAndReplace = function () {
var self = this, finddlg = self._createDiv(css_finddlg), find = self._createDiv(css_finddlg_find), replace = self._createDiv(css_finddlg_replace), buttons = self._createDiv(css_dlg_buttons);
finddlg.add(find);
find.add(self._createSpan(css_dlg_text, this.localizeString("findAndReplaceFind", "Find:")));
find.add(self._createElement("textarea", "text"));
finddlg.add(replace);
replace.add(self._createSpan(css_dlg_text, this.localizeString("findAndReplaceReplace", "Replace:")));
replace.add(self._createElement("textarea"));
finddlg.add(self._createSeparator());
finddlg.add(buttons);
buttons.add(self._createInputButton(css_dlg_button, this.localizeString("findAndReplaceFindButton", "Find")));
buttons.add(self._createInputButton(css_dlg_button, this.localizeString("findAndReplaceReplaceButton", "Replace")));
return finddlg.render();
};
wijeditor.prototype._getDialogRes_Media = function () {
var self = this, meddlg = self._createDiv(css_mediadlg), type = self._createDiv(css_mediadlg_type);
meddlg.add(type);
type.add(self._createSpan(css_dlg_text, this.localizeString("mediaDialogMediaType", "Media Type :")));
type.add(self._createSelect("", [
"flash",
"video",
"applet",
"other"
]));
meddlg.add(self._createTextField(this.localizeString("mediaDialogMediaUrl", "Media Url :"), css_mediadlg_url));
meddlg.add(self._createTextField(this.localizeString("mediaDialogWidth", "Width :"), css_mediadlg_width, this.localizeString("dialogPixel", "px"), 200));
meddlg.add(self._createTextField(this.localizeString("mediaDialogHeight", "Height :"), css_mediadlg_height, this.localizeString("dialogPixel", "px"), 200));
meddlg.add(self._createSeparator());
meddlg.add(self._createOKCancelButtons());
return meddlg.render();
};
wijeditor.prototype._getDialogRes_SpecialCharacter = function () {
var self = this, chardlg = self._createDiv(css_specialchardlg), chars = self._createDiv(css_specialchardlg_chars), preview = self._createDiv(css_specialchardlg_preview), content = self._createDiv(css_specialchardlg_content), list = self._createDiv(css_specialchardlg_list), punctuationLabel = self._createDiv(css_specialchardlg_label, "Punctuation"), punctuation = self._createDiv(css_specialchardlg_punctuation), punctuationArr = [
"–",
"—",
"¡",
"¿",
""",
"«",
"»",
" "
], symbolsLabel = self._createDiv(css_specialchardlg_label, "Symbols"), symbols = self._createDiv(css_specialchardlg_symbols), symbolsArr = [
"&",
"¢",
"©",
"÷",
">",
"<",
"µ",
"•",
"¶",
"±",
"€",
"£",
"®",
"§",
"¥"
], diacriticsLabel = self._createDiv(css_specialchardlg_label, "Diacritics"), diacritics = self._createDiv(css_specialchardlg_diacritics), diacriticsArr = [
"á",
"Á",
"à",
"À",
"â",
"Â",
"å",
"Å",
"ã",
"Ã",
"ä",
"Ä",
"æ",
"Æ",
"ç",
"Ç",
"é",
"É",
"è",
"È",
"ê",
"Ê",
"ë",
"Ë",
"í",
"Í",
"ì",
"Ì",
"î",
"Î",
"ï",
"Ï",
"ñ",
"Ñ",
"ó",
"Ó",
"ò",
"Ò",
"ô",
"Ô",
"ø",
"Ø",
"õ",
"Õ",
"ö",
"Ö",
"ú",
"Ú",
"ù",
"Ù",
"û",
"Û",
"ü",
"Ü",
"ß",
"ÿ",
"‘",
"’"
], buttons = self._createDiv(css_dlg_buttons);
chardlg.add(chars);
chars.add(preview);
preview.add(content);
content.add(new HtmlElement("span"));
chars.add(list);
list.add(punctuationLabel);
punctuationLabel.add(punctuation);
$.each(punctuationArr, function (i, n) {
punctuation.add(self._createLabel(n));
});
list.add(symbolsLabel);
symbolsLabel.add(symbols);
$.each(symbolsArr, function (i, n) {
symbols.add(self._createLabel(n));
});
list.add(diacriticsLabel);
diacriticsLabel.add(diacritics);
$.each(diacriticsArr, function (i, n) {
diacritics.add(self._createLabel(n));
});
chardlg.add(self._createSeparator());
buttons.add(self._createInputButton(css_dlg_button, "Cancel"));
chardlg.add(buttons);
return chardlg.render();
};
wijeditor.prototype._copyFromClipboard = function () {
var clip, trans, str, strLength;
//str = {},
//strLength = {};
if(wijWindow.clipboardData) {
return wijWindow.clipboardData.getData('Text');
} else if($.browser.mozilla) {
try {
if(netscape.security.PrivilegeManager.enablePrivilege) {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}
} catch (ex) {
}
clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(Components.interfaces.nsIClipboard);
if(!clip) {
return false;
}
trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if(!trans) {
return false;
}
trans.addDataFlavor("text/unicode");
clip.getData(trans, clip.kGlobalClipboard);
trans.getTransferData("text/unicode", str, strLength);
if(str) {
str = str.value.QueryInterface(Components.interfaces.nsISupportsString);
}
if(str) {
return str.data.substring(0, strLength.value / 2);
}
return "";
}
};
wijeditor.prototype._copyToClipboard = function (copyText) {
var clip, trans, clipid, str = {
}, len = {
};
if(wijWindow.clipboardData && copyText) {
wijWindow.clipboardData.setData("Text", copyText);
} else if($.browser.mozilla) {
try {
if(netscape.security.PrivilegeManager.enablePrivilege) {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
}
clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
if(!clip) {
return;
}
trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
if(!trans) {
return;
}
trans.addDataFlavor('text/unicode');
//str = {}; // new Object();
len = {
}// new Object();
;
str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
str.data = copyText;
trans.setTransferData("text/unicode", str, copyText.length * 2);
clipid = Components.interfaces.nsIClipboard;
if(!clip) {
return false;
}
clip.setData(trans, null, clipid.kGlobalClipboard);
} catch (e) {
str = "Copy text to Clipboard \n";
str += "If you are using firefox please do the following :\n ";
str += "1. Write in your url box : 'about:config'\n";
str += "2. Change signed.applets.codebase_principal_support = true\n";
wijAlert(this.localizeString("errorMessageCopyToClipboardError", str));
}
}
};
wijeditor.prototype.fixAbsoluteUrlsIfNeeded = /** @ignore */
function (html) {
var self = this, sBaseDocUrl = wijDoc.URL, sBaseUrl = wijDoc.URL, sRootBaseUrl = wijDoc.URL, baseUrlFound = false, len = sBaseUrl.length, ret = html, ch, ch2, s1, r, s2, s3, i, pos;
for(i = len - 1; i > 0; i--) {
ch = sBaseUrl.charAt(i);
ch2 = sBaseUrl.charAt(i - 1);
if(ch === '/' || ch === '\\') {
if(ch === ch2) {
break;
}
sRootBaseUrl = sBaseUrl.substring(0, i) + ch;
if(!baseUrlFound) {
sBaseUrl = sRootBaseUrl;
baseUrlFound = true;
}
}
}
s1 = self._prepareLiteralRegexText(sBaseDocUrl + '?');
r = new RegExp(s1, 'g');
ret = ret.replace(r, '?');
s2 = self._prepareLiteralRegexText(sBaseUrl);
r = new RegExp(s2, 'g');
ret = ret.replace(r, '');
s3 = self._prepareLiteralRegexText(sRootBaseUrl);
r = new RegExp(s3, 'g');
ret = ret.replace(r, '/');
pos = ret.indexOf('#');
if(pos > -1) {
ret = ret.substr(pos);
}
return ret;
};
wijeditor.prototype._insertCell = function (row, idx) {
var newCell = row.insertCell(idx);
newCell.innerHTML = ' ';
return newCell;
};
wijeditor.prototype._getDictionaryDeclare = function () {
var attrs = {
};
attrs.a = [
'accesskey',
'charset',
'class',
'coords',
'dir',
'href',
'hreflang',
'id',
'lang',
'name',
'rel',
'rev',
'shape',
'tabindex',
'target',
'title'
];
attrs.b = [
'class',
'dir',
'id',
'lang',
'title'
];
attrs.body = [
'alink',
'background',
'bgColor',
'bgproperties',
'bottommargin',
'class',
'dir',
'id',
'lang',
'leftmargin',
'link',
'marginheight',
'marginwidth',
'rightmargin',
'text',
'title',
'topmargin',
'vlink'
];
attrs.button = [
'accesskey',
'class',
'dir',
'disabled',
'id',
'lang',
'name',
'tabindex',
'title',
'type',
'value'
];
attrs.code = [
'class',
'dir',
'id',
'lang',
'title'
];
attrs.div = [
'align',
'class',
'dir',
'id',
'lang',
'title'
];
attrs.em = [
'class',
'dir',
'id',
'lang',
'title'
];
attrs.font = [
'class',
'color',
'dir',
'face',
'id',
'lang',
'pointsize',
'size',
'title'
];
attrs.form = [
'action',
'class',
'dir',
'enctype',
'id',
'lang',
'method',
'name',
'runat',
'target',
'title'
];
attrs.hr = [
'align',
'class',
'color',
'id',
'noshade',
'size',
'title',
'width'
];
attrs.i = [
'class',
'dir',
'id',
'lang',
'title'
];
attrs.img = [
'align',
'alt',
'border',
'class',
'controls',
'dir',
'dynsrc',
'height',
'hspace',
'id',
'ismap',
'lang',
'longdesc',
'loop',
'lowsrc',
'name',
'src',
'start',
'title',
'usemap',
'vspace',
'width'
];
attrs.input = [
'accept',
'accesskey',
'align',
'alt',
'border',
'checked',
'class',
'dir',
'disabled',
'height',
'hspace',
'id',
'lang',
'maxlength',
'name',
'readonly',
'size',
'src',
'tabindex',
'title',
'type',
'usemap',
'value',
'vspace',
'width'
];
attrs.label = [
'accesskey',
'class',
'dir',
'for',
'id',
'lang',
'title'
];
attrs.li = [
'class',
'dir',
'id',
'lang',
'title',
'type',
'value'
];
attrs.ol = [
'class',
'compact',
'dir',
'id',
'lang',
'start',
'title',
'type'
];
attrs.option = [
'class',
'dir',
'disabled',
'id',
'label',
'lang',
'selected',
'title',
'value'
];
attrs.p = [
'align',
'class',
'dir',
'id',
'lang',
'title'
];
attrs.span = [
'class',
'dir',
'id',
'lang',
'title'
];
attrs.strong = [
'class',
'dir',
'id',
'lang',
'title'
];
attrs.select = [
'accesskey',
'class',
'dir',
'disabled',
'id',
'lang',
'multiple',
'name',
'size',
'tabindex',
'title'
];
attrs.table = [
'align',
'background',
'bgColor',
'border',
'bordercolor',
'bordercolordark',
'bordercolorlight',
'cellpadding',
'cellspacing',
'class',
'cols',
'datapagesize',
'dir',
'frame',
'height',
'hspace',
'id',
'lang',
'rules',
'summary',
'title',
'vspace',
'width'
];
attrs.td = [
'abbr',
'align',
'axis',
'background',
'bgColor',
'bordercolor',
'bordercolordark',
'bordercolorlight',
'class',
'colspan',
'dir',
'headers',
'height',
'id',
'lang',
'nowrap',
'rowspan',
'scope',
'title',
'valign',
'width'
];
attrs.th = [
'abbr',
'align',
'axis',
'background',
'bgColor',
'bordercolor',
'bordercolordark',
'bordercolorlight',
'class',
'colspan',
'dir',
'headers',
'height',
'id',
'lang',
'nowrap',
'rowspan',
'scope',
'title',
'valign',
'width'
];
attrs.tr = [
'align',
'bgColor',
'bordercolor',
'bordercolordark',
'bordercolorlight',
'class',
'dir',
'height',
'id',
'lang',
'nowrap',
'title',
'valign'
];
attrs.tbody = [
'align',
'bgColor',
'class',
'dir',
'id',
'lang',
'title',
'valign'
];
attrs.textarea = [
'accesskey',
'class',
'cols',
'dir',
'disabled',
'id',
'label',
'lang',
'name',
'readonly',
'rows',
'tabindex',
'title',
'wrap'
];
attrs.u = [
'class',
'id',
'xml:lang'
];
attrs.ul = [
'class',
'compact',
'dir',
'id',
'lang',
'title',
'type'
];
return attrs;
};
wijeditor.prototype._getParentElement = function (contentWin) {
var self = this, range = self._getRange(contentWin), selection, startContainer, endContainer, startOffset, endOffset;
if(!range) {
return null;
}
if(range.commonAncestorContainer) {
selection = contentWin.getSelection();
startContainer = range.startContainer || selection.baseNode;
endContainer = range.endContainer || selection.extentNode;
startOffset = range.startOffset;
if(startOffset === null) {
startOffset = selection.baseOffset;
}
endOffset = range.endOffset;
if(endOffset === null) {
endOffset = selection.extentOffset;
}
if(startContainer === endContainer && (endOffset - startOffset) === 1) {
return selection.anchorNode.childNodes[selection.anchorOffset];
}
if(!range.commonAncestorContainer.tagName) {
if(contentWin.document === range.commonAncestorContainer && selection.baseNode) {
return selection.baseNode.parentNode;
}
return range.commonAncestorContainer.parentNode;
}
return range.commonAncestorContainer;
}
if(range.length) {
return range.item(0);
}
if(range.parentElement) {
return range.parentElement();
}
return null;
};
wijeditor.prototype._getRange = function (contentWin) {
var selection, range;
if(contentWin.document.selection && !wijWindow.opera) {
return contentWin.document.selection.createRange();
}
if(contentWin.getSelection) {
selection = contentWin.getSelection();
if(!selection || selection.rangeCount < 1) {
return null;
}
if(selection.getRangeAt) {
range = selection.getRangeAt(0);
} else {
range = contentWin.document.createRange();
}
return range;
}
};
wijeditor.prototype._generateUniqueName = function (prefix) {
var idx = uniqueIds[prefix];
if(!idx) {
idx = 0;
}
uniqueIds[prefix] = ++idx;
return prefix + idx;
};
wijeditor.prototype._setContentEditable = function (doc, isEditable) {
var designMode = "designMode", contentEditable = "contentEditable";
try {
if(doc.body[contentEditable]) {
doc.body[contentEditable] = isEditable.toString();
}
if(doc[designMode]) {
if(!isEditable && doc[designMode] !== 'off') {
doc[designMode] = 'off';
} else if(isEditable && doc[designMode] !== 'on') {
//update for ie9 can't select the content after scroll
if(!($.browser.msie && wijParseInt($.browser.version) >= 9)) {
doc[designMode] = 'on';
}
}
}
if(isEditable && !$.browser.msie) {
doc.execCommand('useCSS', false, true);
}
} catch (e) {
}
};
wijeditor.prototype._setContentSpellCheck = function (doc, isSpellCheck) {
var spellcheck = "spellcheck";
try {
if(doc.body[spellcheck] !== undefined) {
doc.body[spellcheck] = isSpellCheck;
}
} catch (e) {
}
};
wijeditor.prototype._formatString = function (str, len) {
var strLen = str.length, i;
for(i = 0; i < len - strLen; i++) {
str = '0' + str;
}
return str;
};
wijeditor.prototype._convertToWebColor = function (r, g, b) {
var self = this, hr, hg, hb, result;
if(isNaN(r) || 255 - r < 0) {
r = 0;
}
if(isNaN(g) || 255 - g < 0) {
g = 0;
}
if(isNaN(b) || 255 - b < 0) {
b = 0;
}
hr = self._formatString(wijParseInt(r).toString(16), 2);
hg = self._formatString(wijParseInt(g).toString(16), 2);
hb = self._formatString(wijParseInt(b).toString(16), 2);
result = '#' + hr + hg + hb;
return result;
};
wijeditor.prototype._prepareLiteralRegexText = function (s1) {
var ret = s1;
ret = ret.replace('\\', '\\\\');
ret = ret.replace('.', '\\.');
ret = ret.replace('?', '\\?');
return ret;
};
wijeditor.prototype._isNumeric = function (str) {
return new RegExp('^\\d+$').test(str);
};
wijeditor.prototype._isEmail = function (str) {
return new RegExp('mailto:(\\S)+[@]{1}(\\S)+[.]{1}(\\w)+').test(str);
};
wijeditor.prototype._isUrl = function (str) {
return new RegExp('[a-zA-z]+://[^s]+').test(str);
};
wijeditor.prototype.refresh = /** Adjust the editor layout.*/
function () {
var self = this, element = self.element, header = self._getHeader(), footer = self._getFooter(), width = self._oriEleWidth, height = self._oriEleHeight, content = self._getContent(), contentHeight;
self.editor.width(width).height(height);
this.$ribbon.wijribbon("updateRibbonSize");
contentHeight = self.editor.height() - header.outerHeight(true) - footer.outerHeight(true);
content.height(contentHeight).wijsplitter("refresh");
};
wijeditor.prototype.getText = /** Gets the text displayed in the editor.*/
function () {
var self = this;
return self._getDesignViewText();
};
wijeditor.prototype.setText = /** Sets the text to display in the editor.
* @remarks
* You can use the example code in a click function linked to a button,
* and replace any existing text in the editor with your text.
* @param {string} text The text to show in the editor.
*/
function (text) {
var self = this;
if(text) {
self._setDesignViewText(text);
self.sourceView.val(text);
}
};
wijeditor.prototype.localizeString = /** @ignore */
function (key, defaultValue) {
var o = this.options;
if(o.localization && o.localization[key]) {
return o.localization[key];
}
return defaultValue;
};
return wijeditor;
})(wijmo.wijmoWidget);
editor.wijeditor = wijeditor;
//end of public method
var wijeditor_options = (function () {
function wijeditor_options() {
/** Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijeditor')";
/** Set to the selector that returns the container to fill when the user
* selects full screen mode.By default, it fills the client's area on the web page.
* @remarks
* Once set , you can refer to this string in the ID attribute of the container,
* for example < div id = "container" > < / div >.
*/
this.fullScreenContainerSelector = "";
/** Set the type of editor to show initially.
* @remarks
* It has three options: wysiwyg/code/split.
* wysiwyg -- A visual designer with toolbar buttons that allow you to format text.
* code -- A code view of the text that allows you to edit the HTML formatting.
* split -- A horizontally split editor with the visual designer in the top pane
* and the code view in the bottom.In this mode, the user can resize the panes by
* dragging the horizontal bar separating them up or down.
*/
this.editorMode = "wysiwyg";
/** Set this option to true to show the editor in full screen mode when the page is first opened.
* @remarks
* The editor fills the client area of the page(or the container specified in the fullScreenContainerSelector option).
* Note that this only sets the initial mode.The user can still toggle fullScreenMode off
* using the button at the bottom right of the editor.
*/
this.fullScreenMode = false;
/** Select whether to show the path selector in the left side of the footer.
* @remarks
* When you click in the content of the design view, the path selector shows HTML tags
* indicating where you are in the source view.If you set showFooter to false, this option is ignored.
*/
this.showPathSelector = true;
/** Specify which toolbar to render. Ribbon and simple modes allow you to customize the toolbar.
* @remarks
* For more information on customizing the toolbar,
* see editor samples "Customize" and "Customize Simple."
* ribbon -- Includes the most commonly used tool buttons.
* simple -- Includes fewer buttons, is much smaller, and takes up less space.
* bbcode -- Includes buttons used with Bulletin Board Code,
* a markup language used to format posts in message boards.
*/
this.mode = "ribbon";
/** Occurs when the command button is clicked.
* @event
* @dataKey {string} commandName The command name of the button.
* @dataKey {string} name The parent name of the button which means
* if the drop down item is clicked, then the name specifies the command name of the drop down button.
*/
this.commandButtonClick = null;
/** Specify an array of commands to display in customizing the simple toolbar.
* @remarks
* Note that you must specify every command that you want to display,
* as these commands are used in place of the default commands.Therefore,
* the sample code shown below would only render two commands in the toolbar.
* The simple mode commands displayed by default are:
* "BlockQuote", "Bold", "BulletedList", "InsertCode", "InsertDate", "InsertImage",
* "Italic", "Link", "NumberedList", "NumberedList"
* Note: The buildin simple commands support the following commands:
* "Form","Image","TextArea","Button","TextBox","List","DropDownList",
* "HiddenField","Radio","CheckBox","JustifyLeft,"JustifyCenter",
* "JustifyRight","JustifyFull","Border","NumberedList","BulletedList",
* "Outdent","Indent","BackColor","ForeColor","Bold","Italic","UnderLine",
* "SubScript","SuperScript","Template","RemoveFormat","InsertBreak",
* "InsertParagraph","InsertPrint","InsertHR","Undo","Redo","Preview","Cleanup",
* "Cut","Copy","Paste","SelectAll","Media","InsertSpecialChar","InsertDate","Find",
* "Inspect","InsertImage","Link","FontName","FontSize","BlockQuote","InsertCode"
* The default simple mode commands are:
* ["Bold", "Italic", "Link", "BlockQuote",
* "StrikeThrough", "InsertDate", "InsertImage",
* "NumberedList", "BulletedList", "InsertCode"]
* @example
* $("#wijeditor").wijeditor({
* mode: "simple",
* simpleModeCommands: ["Bold","Undo"]
* });
*/
this.simpleModeCommands = null;
/** Specify whether to show the footer at the bottom of the editor,
* where users can toggle full screen mode, word wrap, and view mode.
* @remarks
* When you are in design view, the footer also displays the path selector,
* HTML tags showing your location in source view.
*/
this.showFooter = true;
/** Determines whether the custom context menu is shown.
* @remarks
* Instead of the standard context menu items shown by the browser,
* the custom context menu has only three commands:
* Cut, Copy, and Paste.Note that the context menu is invalid in Safari.
*/
this.customContextMenu = true;
/** Set the text that appears in the editor.
* @type {string}
* @remarks
* Note that this overrides any text that you add in tags
* inside the textarea object that displays the widget.
* You can use HTML(or BBCode markup if you set the mode to bbcode) inside the string.
*/
this.text = null;
/** Occurs when the text changed.
* @event
* @dataKey {String} text The text of the editor.
*/
this.textChanged = null;
/** Use the localization option in order to localize text which not depends on culture.
* @ignore
*/
this.localization = null;
}
return wijeditor_options;
})();
;
wijeditor.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijeditor_options());
$.wijmo.registerWidget("wijeditor", wijeditor.prototype);
//wijDoc = document,
//wijParseInt = parseInt,
//css_editor = "wijmo-wijeditor",
var css_editor_colorcanvas = css_editor + "-colorcanvas", css_editor_color = css_editor + "-color", css_editor_wheel = css_editor + "-wheel", css_editor_overlay = css_editor + "-overlay", css_editor_marker = css_editor + "-marker";
/** @ignore */
$.fn.wijeditorcolorcanvas = function (callback, initColor) {
//$.wijeditorcolorcanvas(this, callback, initColor);
var container = this.get(0);
return container.wijeditorcolorcanvas || (container.wijeditorcolorcanvas = new _wijeditorcolorcanvas(container, callback, initColor));
return this;
};
/** @ignore */
var _wijeditorcolorcanvas = (function () {
function _wijeditorcolorcanvas(container, callback, initColor) {
// Store editorcolorcanvas object
var fb = this, markup = "", e, alphaImageLoader;
alphaImageLoader = "progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(enabled=true, sizingMethod=crop, ";
markup += "<div class='" + css_editor_colorcanvas + "'>";
markup += "<div class='" + css_editor_color + "'></div>";
markup += "<div class='" + css_editor_wheel + "'></div>";
markup += "<div class='" + css_editor_overlay + "'></div>";
markup += "<div class='h-marker " + css_editor_marker + "'></div>";
markup += "<div class='sl-marker " + css_editor_marker + "'></div></div>";
$(container).html(markup);
e = $("." + css_editor_colorcanvas, container);
fb.wheel = $("." + css_editor_wheel, container).get(0);
// Dimensions
fb.radius = 84;
fb.square = 100;
fb.width = 194;
// Fix background PNGs in IE6
if($.browser.msie && parseInt($.browser.version, 10) < 7) {
$('*', e).each(function () {
var imgEl = this, bgImg = imgEl.currentStyle.backgroundImage;
if(bgImg !== 'none') {
bgImg = bgImg.substring(5, bgImg.length - 2);
$(imgEl).css({
'backgroundImage': 'none',
'filter': alphaImageLoader + "src='" + bgImg + "')"
});
}
return this;
});
}
/**
* Link to the given element(s) or callback.
*/
fb.linkTo = function (callback) {
// Unbind previous nodes
if(typeof fb.callback === 'object') {
$(fb.callback).unbind('keyup', fb.updateValue);
}
// Reset color
fb.color = null;
// Bind callback or elements
if(typeof callback === 'function') {
fb.callback = callback;
} else if(typeof callback === 'object' || typeof callback === 'string') {
fb.callback = $(callback);
fb.callback.bind('keyup', fb.updateValue);
if(fb.callback.get(0).value) {
fb.setColor(fb.callback.get(0).value);
}
}
return this;
};
fb.updateValue = function (event) {
var self = this;
if(self.value && self.value !== fb.color) {
fb.setColor(self.value);
}
};
/**
* Change color with HTML syntax #123456
*/
fb.setColor = function (color) {
var unpack = fb.unpack(color);
if(fb.color !== color && unpack) {
fb.color = color;
fb.rgb = unpack;
fb.hsl = fb.RGBToHSL(fb.rgb);
fb.updateDisplay();
}
return this;
};
/**
* Change color with HSL triplet [0..1, 0..1, 0..1]
*/
fb.setHSL = function (hsl) {
fb.hsl = hsl;
fb.rgb = fb.HSLToRGB(hsl);
fb.color = fb.pack(fb.rgb);
fb.updateDisplay();
return this;
};
/**
* Retrieve the coordinates of the given event relative to the center
* of the widget.
*/
fb.widgetCoords = function (event) {
var x, y, el, reference, pos;
el = event.target || event.srcElement;
reference = fb.wheel;
// Use absolute coordinates
pos = fb.absolutePosition(reference);
x = (event.pageX || 0 * (event.clientX + $('html').get(0).scrollLeft)) - pos.x;
y = (event.pageY || 0 * (event.clientY + $('html').get(0).scrollTop)) - pos.y;
// Subtract distance to middle
return {
x: x - fb.width / 2,
y: y - fb.width / 2
};
};
/**
* Mousedown handler
*/
fb.mousedown = function (event) {
// Capture mouse
if(!wijDoc.dragging) {
$(wijDoc).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup);
wijDoc.dragging = true;
}
// Check which area is being dragged
var pos = fb.widgetCoords(event);
//document.title = pos.x + "|" + pos.y;
fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square;
// Process
fb.mousemove(event);
return false;
};
/**
* Mousemove handler
*/
fb.mousemove = function (event) {
// Get coordinates relative to color picker center
var pos = fb.widgetCoords(event), hue, sat, lum;
// Set new HSL parameters
if(fb.circleDrag) {
hue = Math.atan2(pos.x, -pos.y) / 6.28;
if(hue < 0) {
hue += 1;
}
fb.setHSL([
hue,
fb.hsl[1],
fb.hsl[2]
]);
} else {
sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + 0.5));
lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + 0.5));
fb.setHSL([
fb.hsl[0],
sat,
lum
]);
}
return false;
};
/**
* Mouseup handler
*/
fb.mouseup = function () {
// Uncapture mouse
$(wijDoc).unbind('mousemove', fb.mousemove).unbind('mouseup', fb.mouseup);
wijDoc.dragging = false;
};
/**
* Update the markers and styles
*/
fb.updateDisplay = function () {
// Markers
var angle = fb.hsl[0] * 6.28, inputEl;
$('.h-marker', e).css({
left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px',
top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px'
});
$('.sl-marker', e).css({
left: Math.round(fb.square * (0.5 - fb.hsl[1]) + fb.width / 2) + 'px',
top: Math.round(fb.square * (0.5 - fb.hsl[2]) + fb.width / 2) + 'px'
});
// Saturation/Luminance gradient
$("." + css_editor_color, e).css('backgroundColor', fb.pack(fb.HSLToRGB([
fb.hsl[0],
1,
0.5
])));
// Linked elements or callback
if(typeof fb.callback === 'object') {
// Set background/foreground color
$(fb.callback).css({
backgroundColor: fb.color,
color: fb.hsl[2] > 0.5 ? '#000' : '#fff'
});
// Change linked value
$(fb.callback).each(function () {
inputEl = this;
if(inputEl.value && inputEl.value !== fb.color) {
inputEl.value = fb.color;
}
return this;
});
} else if(typeof fb.callback === 'function') {
fb.callback.call(fb, fb.color);
}
};
/**
* Get absolute position of element
*/
fb.absolutePosition = function (el) {
var r = {
x: el.offsetLeft,
y: el.offsetTop
}, tmp;
// Resolve relative to offsetParent
if(el.offsetParent) {
tmp = fb.absolutePosition(el.offsetParent);
r.x += tmp.x;
r.y += tmp.y;
}
return r;
};
/* Various color utility functions */
fb.pack = function (rgb) {
var r = Math.round(rgb[0] * 255), g, b;
g = Math.round(rgb[1] * 255);
b = Math.round(rgb[2] * 255);
return '#' + (r < 16 ? '0' : '') + r.toString(16) + (g < 16 ? '0' : '') + g.toString(16) + (b < 16 ? '0' : '') + b.toString(16);
};
fb.unpack = function (color) {
if(color.length === 7) {
return [
wijParseInt('0x' + color.substring(1, 3)) / 255,
wijParseInt('0x' + color.substring(3, 5)) / 255,
wijParseInt('0x' + color.substring(5, 7)) / 255
];
} else if(color.length === 4) {
return [
wijParseInt('0x' + color.substring(1, 2)) / 15,
wijParseInt('0x' + color.substring(2, 3)) / 15,
wijParseInt('0x' + color.substring(3, 4)) / 15
];
}
};
fb.HSLToRGB = function (hsl) {
var m1, m2, h, s, l, self = this;
//r, g, b,
h = hsl[0];
s = hsl[1];
l = hsl[2];
m2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s;
m1 = l * 2 - m2;
return [
self.hueToRGB(m1, m2, h + 0.33333),
self.hueToRGB(m1, m2, h),
self.hueToRGB(m1, m2, h - 0.33333)
];
};
fb.hueToRGB = function (m1, m2, h) {
h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h);
if(h * 6 < 1) {
return m1 + (m2 - m1) * h * 6;
}
if(h * 2 < 1) {
return m2;
}
if(h * 3 < 2) {
return m1 + (m2 - m1) * (0.66666 - h) * 6;
}
return m1;
};
fb.RGBToHSL = function (rgb) {
var min, max, delta, h, s, l, r, g, b;
r = rgb[0];
g = rgb[1];
b = rgb[2];
min = Math.min(r, Math.min(g, b));
max = Math.max(r, Math.max(g, b));
delta = max - min;
l = (min + max) / 2;
s = 0;
if(l > 0 && l < 1) {
s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
}
h = 0;
if(delta > 0) {
if(max === r && max !== g) {
h += (g - b) / delta;
}
if(max === g && max !== b) {
h += (2 + (b - r) / delta);
}
if(max === b && max !== r) {
h += (4 + (r - g) / delta);
}
h /= 6;
}
return [
h,
s,
l
];
};
// Install mousedown handler (the others are set on the document on-demand)
$('*', e).mousedown(fb.mousedown);
// Init color
fb.setColor(initColor || '#000000');
// Set linked elements/callback
if(callback) {
fb.linkTo(callback);
}
}
return _wijeditorcolorcanvas;
})();
editor._wijeditorcolorcanvas = _wijeditorcolorcanvas;
})(wijmo.editor || (wijmo.editor = {}));
var editor = wijmo.editor;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts"/>
/*globals jQuery, window*/
/*
* Depends:
* jquery.js
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.wijmo.widget.js
* jquery.wijmo.util.js
*/
(function (rating) {
var _this = this;
"use strict";
var $ = jQuery;
/** @widget */
var wijrating = (function (_super) {
__extends(wijrating, _super);
function wijrating() {
_super.apply(this, arguments);
}
wijrating.prototype._setOption = function (key, value) {
var o = this.options, resetButton = $("." + o.wijCSS.wijratingResetButton, this.ratingElement[0]), starContainer = $("." + o.wijCSS.wijratingStarContainer, this.ratingElement[0]), stars = $("." + o.wijCSS.wijratingNormalStar, this.ratingElement[0]);
if($.isPlainObject(o[key])) {
switch(key) {
case "resetButton":
if(typeof (value.disabled) !== 'undefined') {
if(value.disabled !== o[key].disabled) {
if(value.disabled) {
resetButton.hide();
//add aria support.
resetButton.attr("aria-hidden", true);
} else {
if(!o.disabled) {
resetButton.show();
//add aria support.
resetButton.attr("aria-hidden", false);
}
}
}
}
if(typeof (value.hint) !== 'undefined') {
if(value.hint !== o[key].hint) {
if(value.hint === null) {
resetButton.attr("title", "");
} else {
resetButton.attr("title", value.hint);
}
}
}
if(value.position && value.position.length) {
if(value.position !== o[key].position) {
if(value.position === "rightOrBottom") {
resetButton.parent().append(resetButton);
} else {
resetButton.parent().prepend(resetButton);
}
}
}
if(typeof (value.customizedClass) !== 'undefined') {
if(value.customizedClass !== o[key].customizedClass) {
if(o[key].customizedClass.length) {
resetButton.removeClass(o[key].customizedClass);
}
if(value.customizedClass.length) {
resetButton.addClass(value.customizedClass);
}
}
}
break;
case "hint":
if(typeof (value.disabled) !== 'undefined') {
if(value.disabled !== o[key].disabled) {
if(value.disabled) {
stars.removeAttr("title");
} else {
this._resetHint(o.hint.content);
}
}
}
if(typeof (value.content) !== 'undefined') {
if(value.content !== o[key].content) {
if(!o[key].disabled) {
this._resetHint(value.content);
}
}
}
break;
case "icons":
if(typeof (value.iconsClass) !== 'undefined') {
if(o[key].iconsClass && o[key].iconsClass.length) {
this._removeCustomizedIconsClass(o[key].iconsClass);
}
this._addCustomizedIconsClass(value.iconsClass, o.split);
}
if(typeof (value.hoverIconsClass) !== 'undefined') {
if(o[key].hoverIconsClass && o[key].hoverIconsClass.length) {
this._removeCustomizedIconsClass(o[key].hoverIconsClass);
}
}
if(typeof (value.ratedIconsClass) !== 'undefined') {
if(o[key].ratedIconsClass && o[key].ratedIconsClass.length) {
this._removeCustomizedIconsClass(o[key].ratedIconsClass);
}
this._resetValue(o.value, o.ratingMode, value.ratedIconsClass);
}
break;
default:
break;
}
$.extend(true, o[key], value);
} else {
if(value === o[key]) {
return;
}
switch(key) {
case "disabled":
if(value) {
this._unbindLiveEvents();
resetButton.hide();
//add aria support.
resetButton.attr("aria-hidden", true);
} else {
this._bindLiveEvents();
if(!o.resetButton.disabled) {
resetButton.show();
//add aria support.
resetButton.attr("aria-hidden", false);
}
}
break;
case "count":
this._createStars(o.split, value, starContainer);
break;
case "split":
this._createStars(value, o.count, starContainer);
break;
case "totalValue":
this._resetTotalValue(value);
break;
case "orientation":
if(value === "vertical") {
this.ratingElement.addClass(o.wijCSS.wijvRating);
} else {
this.ratingElement.removeClass(o.wijCSS.wijvRating);
}
if(o.split > 1) {
o[key] = value;
this._createStars(o.split, o.count, starContainer);
}
break;
case "direction":
o[key] = value;
this._createStars(o.split, o.count, starContainer);
break;
case "ratingMode":
this._resetValue(o.value, value, o.icons.ratedIconsClass);
break;
case "value":
if(o.min && value < o.min) {
return;
}
if(o.max && value > o.max) {
return;
}
this._resetValue(value, o.ratingMode, o.icons.ratedIconsClass);
break;
case "iconWidth":
o[key] = value;
this._createStars(o.split, o.count, starContainer);
break;
case "iconHeight":
o[key] = value;
this._createStars(o.split, o.count, starContainer);
break;
default:
break;
}
_super.prototype._setOption.call(this, key, value);
}
};
wijrating.prototype._create = function () {
var o = this.options, ratingElement;
if(this.element.is("select")) {
this._parseSelect();
this.element.hide();
ratingElement = $("<div></div>");
this.element.after(ratingElement);
} else if(this.element.is("div")) {
if(this.element.children("input[type='radio']").length > 0) {
this._parseRadio();
this.element.hide();
ratingElement = $("<div></div>");
this.element.after(ratingElement);
} else {
ratingElement = this.element;
}
} else {
return;
}
this.ratingElement = ratingElement;
this._createRating();
if(!o.disabled) {
this._bindLiveEvents();
}
_super.prototype._create.call(this);
};
wijrating.prototype.destroy = /** The destroy() method will remove the rating functionality completely
* and will return the element to its pre-init state.
*/
function () {
var o = this.options;
this._unbindLiveEvents();
if(this.element !== this.ratingElement) {
this.ratingElement.remove();
this.element.show();
} else {
this.element.removeClass(o.wijCSS.widget).removeClass(o.wijCSS.wijrating).removeClass(o.wijCSS.wijvRating).empty();
}
_super.prototype.destroy.call(this);
};
wijrating.prototype._unbindLiveEvents = function () {
var o = this.options;
this.ratingElement.off(".wijrating", "." + o.wijCSS.wijratingNormalStar).off(".wijrating", "." + o.wijCSS.wijratingResetButton);
};
wijrating.prototype._bindLiveEvents = function () {
var self = this, o = self.options, isStar = "." + o.wijCSS.wijratingNormalStar, isRestButton = "." + o.wijCSS.wijratingResetButton, args, starProxyObj = {
element: self.ratingElement,
mouseover: function (e) {
var tar = $(e.target), allStars = $(isStar, self.ratingElement[0]);
if(tar.is(isStar)) {
allStars.removeClass(o.wijCSS.wijratingHoverStar);
tar.addClass(o.wijCSS.wijratingHoverStar);
if(o.ratingMode === "continuous") {
if(o.direction === "reversed") {
tar.parent().nextAll().children().addClass(o.wijCSS.wijratingHoverStar);
} else {
tar.parent().prevAll().children().addClass(o.wijCSS.wijratingHoverStar);
}
}
self._addCustomizedHoverIconsClass(o.icons.hoverIconsClass, o.split, tar);
args = {
value: parseFloat(tar.html()),
target: tar
};
self._trigger("hover", e, args);
}
},
mouseout: function (e) {
var tar = $(e.target), allStars = $(isStar, self.ratingElement[0]);
if(tar.is(isStar)) {
allStars.removeClass(o.wijCSS.wijratingHoverStar);
self._removeCustomizedIconsClass(o.icons.hoverIconsClass);
}
},
click: function (e) {
var tar = $(e.target), val = parseFloat(tar.html()), allStars = $(isStar, self.ratingElement[0]), animation = {
duration: 500,
easing: null,
delay: 250,
animated: null
}, animations = $.wijmo.wijrating.animations, animated;
$.extend(true, animation, o.animation);
animated = animation.animated;
if(!tar.is(isStar)) {
return;
}
if(o.max && val > o.max) {
return;
}
if(o.min && val < o.min) {
return;
}
args = {
oldValue: o.value,
newValue: val,
target: tar
};
if(self._trigger("rating", e, args) === false) {
return false;
}
o.value = val;
self._resetValue(val, o.ratingMode, o.icons.ratedIconsClass);
allStars.removeClass(o.wijCSS.wijratingHoverStar);
self._removeCustomizedIconsClass(o.icons.hoverIconsClass);
args = {
value: val,
target: tar
};
if(animated) {
if(animations && animations[animated]) {
animations[animated](o, allStars, function () {
self._trigger("rated", e, args);
});
} else if($.effects && ($.effects[animated] || ($.effects.effect && $.effects.effect[animated]))) {
//individual effects in jqueryui 1.9 are now defined on
// $.effects.effect rather than directly on $.effects.
self._playJqueryAnimation(animation, allStars, function () {
//remove filter style to fix jquery animation
//bug in ie8.
if($.browser.msie && parseInt($.browser.version) < 9) {
allStars.css("filter", "");
}
self._trigger("rated", e, args);
});
} else {
self._trigger("rated", e, args);
}
} else {
self._trigger("rated", e, args);
}
}
}, resetButtonProxy = {
element: self.ratingElement,
mouseover: function (e) {
var tar = $(e.target);
tar = tar.closest("." + o.wijCSS.wijratingResetButton);
tar.addClass(o.wijCSS.wijratingHoverResetButton).addClass(o.wijCSS.stateHover);
if(o.resetButton.customizedHoverClass && o.resetButton.customizedHoverClass.length) {
tar.addClass(o.resetButton.customizedHoverClass);
}
},
mouseout: function (e) {
var tar = $(e.target);
tar = tar.closest("." + o.wijCSS.wijratingResetButton);
tar.removeClass(o.wijCSS.wijratingHoverResetButton).removeClass(o.wijCSS.stateHover);
if(o.resetButton.customizedHoverClass && o.resetButton.customizedHoverClass.length) {
tar.removeClass(o.resetButton.customizedHoverClass);
}
},
click: function (e) {
var tar = $(e.target);
self._setOption("value", 0);
args = {
target: tar
};
self._trigger("reset", e, args);
}
};
this.ratingElement.on("mouseover.wijrating", isStar, $.proxy(starProxyObj.mouseover, starProxyObj)).on("mouseout.wijrating", isStar, $.proxy(starProxyObj.mouseout, starProxyObj)).on("click.wijrating", isStar, $.proxy(starProxyObj.click, starProxyObj)).on("mouseover.wijrating", isRestButton, $.proxy(resetButtonProxy.mouseover, resetButtonProxy)).on("mouseout.wijrating", isRestButton, $.proxy(resetButtonProxy.mouseout, resetButtonProxy)).on("click.wijrating", isRestButton, $.proxy(resetButtonProxy.click, resetButtonProxy));
};
wijrating.prototype._createRating = function () {
var element = this.ratingElement, o = this.options, resetButton, resetIcon, starContainer;
element.addClass(o.wijCSS.wijrating).addClass(o.wijCSS.widget);
if(o.orientation === "vertical") {
element.addClass(o.wijCSS.wijvRating);
}
//add reset button.
resetButton = $("<div></div>").addClass(o.wijCSS.wijratingResetButton).addClass(o.wijCSS.cornerAll).addClass(o.wijCSS.stateDefault);
if(o.resetButton.customizedClass && o.resetButton.customizedClass.length) {
resetButton.addClass(o.resetButton.customizedClass);
}
resetButton.appendTo(element);
//add aria support.
resetButton.attr("role", "button").attr("aria-label", "reset").attr("aria-hidden", false);
if(o.resetButton.hint && o.resetButton.hint.length) {
resetButton.attr("title", o.resetButton.hint);
}
if(o.resetButton.disabled || o.disabled) {
resetButton.hide();
//add aria support
resetButton.attr("aria-hidden", true);
}
resetIcon = $("<span></span>");
resetIcon.addClass(o.wijCSS.icon).addClass(o.wijCSS.iconClose);
resetButton.append(resetIcon);
//add star container.
starContainer = $("<div></div>");
//add aria support.
starContainer.attr("role", "radiogroup").addClass(o.wijCSS.wijratingStarContainer);
if(o.resetButton.position === "leftOrTop") {
starContainer.appendTo(element);
} else {
starContainer.prependTo(element);
}
// create stars.
this._createStars(o.split, o.count, starContainer);
};
wijrating.prototype._createStars = function (split, starCount, starContainer) {
var o = this.options, hint = o.hint, content, star, val, idx = 0, splitIdx = 0, starWidth = Math.ceil(o.iconWidth / split), starHeight = Math.ceil(o.iconHeight / split), ratedIconsClass = o.icons.ratedIconsClass, customizedIconIdx, customizedIconClass, isCustomizedClass = ratedIconsClass && ratedIconsClass.length;
starContainer.empty();
for(idx; idx < starCount * split; idx++ , splitIdx++) {
val = Math.round((idx + 1) * o.totalValue * 100 / starCount / split) / 100;
if(splitIdx === split) {
splitIdx = 0;
}
star = $("<div></div>");
//add aria support.
star.attr("role", "radio").attr("aria-checked", false);
if(o.orientation === "vertical") {
star.width(o.iconWidth).height(starHeight);
} else {
star.width(starWidth).height(o.iconHeight);
}
star.addClass(o.wijCSS.wijratingStar);
content = $("<div>" + val + "</div>");
content.addClass(o.wijCSS.wijratingNormalStar).width(o.iconWidth).height(o.iconHeight);
//add aria support.
star.attr("aria-label", val);
if(splitIdx > 0 && o.direction === "normal") {
if(o.orientation === "vertical") {
content.css({
"margin-top": "-" + splitIdx * starHeight + "px"
});
} else {
content.css({
"margin-left": "-" + splitIdx * starWidth + "px"
});
}
} else if(splitIdx < split - 1 && o.direction === "reversed") {
if(o.orientation === "vertical") {
content.css({
"margin-top": "-" + (split - 1 - splitIdx) * starHeight + "px"
});
} else {
content.css({
"margin-left": "-" + (split - 1 - splitIdx) * starWidth + "px"
});
}
}
if(!hint.disabled) {
if(hint.content && hint.content.length) {
if(idx <= hint.content.length) {
content.attr("title", hint.content[idx]);
//add aria support.
star.attr("aria-label", hint.content[idx]);
}
} else {
content.attr("title", val);
}
}
if(isCustomizedClass) {
if(typeof (ratedIconsClass) === "string") {
customizedIconClass = ratedIconsClass;
} else if($.isArray(ratedIconsClass)) {
customizedIconIdx = Math.floor(idx / split);
if(ratedIconsClass.length > customizedIconIdx) {
customizedIconClass = ratedIconsClass[customizedIconIdx];
}
}
}
if(val === o.value) {
content.addClass(o.wijCSS.wijratingRatedStar);
if(isCustomizedClass) {
content.addClass(customizedIconClass);
}
//add aria support.
star.attr("aria-checked", true);
} else if(val < o.value && o.ratingMode === "continuous") {
content.addClass(o.wijCSS.wijratingRatedStar);
if(isCustomizedClass) {
content.addClass(customizedIconClass);
}
}
content.appendTo(star);
if(o.direction === "reversed") {
star.prependTo(starContainer);
} else {
star.appendTo(starContainer);
}
}
//add customized class
this._addCustomizedIconsClass(o.icons.iconsClass, split);
};
wijrating.prototype._resetValue = function (value, ratingMode, ratedIconsClass) {
var o = this.options, stars = $("." + o.wijCSS.wijratingNormalStar, this.ratingElement[0]), rMode = ratingMode || o.ratingMode, isCustomizedClass = ratedIconsClass && ratedIconsClass.length, customizedIconIdx = 0, customizedIconClass;
$.each(stars, function (idx, ele) {
var content = $(ele), val = parseFloat(content.html());
content.removeClass(o.wijCSS.wijratingRatedStar);
//add aria support.
content.parent().attr("aria-checked", false);
if(isCustomizedClass) {
if(typeof (ratedIconsClass) === "string") {
content.removeClass(ratedIconsClass);
customizedIconClass = ratedIconsClass;
} else if($.isArray(ratedIconsClass)) {
$.each(ratedIconsClass, function (i, cl) {
content.removeClass(cl);
});
if(o.direction === "reversed") {
customizedIconIdx = Math.floor((stars.length - 1 - idx) / o.split);
} else {
customizedIconIdx = Math.floor(idx / o.split);
}
if(ratedIconsClass.length > customizedIconIdx) {
customizedIconClass = ratedIconsClass[customizedIconIdx];
}
}
}
if(val === value) {
content.addClass(o.wijCSS.wijratingRatedStar);
if(isCustomizedClass) {
content.addClass(customizedIconClass);
}
//add aria support.
content.parent().attr("aria-checked", true);
} else if(rMode === "continuous") {
if(val < value) {
content.addClass(o.wijCSS.wijratingRatedStar);
if(isCustomizedClass) {
content.addClass(customizedIconClass);
}
}
}
});
};
wijrating.prototype._resetTotalValue = function (value) {
var o = this.options, content = o.hint, stars = $("." + o.wijCSS.wijratingNormalStar, this.ratingElement[0]), starsLen = stars.length;
$.each(stars, function (idx, star) {
var jStar = $(star), newVal = Math.round((idx + 1) * value * 100 / starsLen) / 100, val = parseFloat(jStar.html());
//set new value.
if(val === o.value) {
o.value = newVal;
}
jStar.html(newVal.toString());
if(content && content.length && content.length >= idx && content[idx] && content[idx].length) {
jStar.attr("title", content[idx]);
} else {
jStar.attr("title", newVal);
}
});
};
wijrating.prototype._resetHint = function (content) {
var o = this.options, stars = $("." + o.wijCSS.wijratingNormalStar, this.ratingElement[0]);
$.each(stars, function (idx, star) {
var jStar = $(star), val = parseFloat(jStar.html());
if(content && content.length && content.length >= idx && content[idx] && content[idx].length) {
jStar.attr("title", content[idx]);
} else {
jStar.attr("title", val);
}
});
};
wijrating.prototype._clearIntentTimer = function () {
if(this.intentTimers && this.intentTimers.length) {
$.each(this.intentTimers, function (i, timer) {
if(timer) {
window.clearTimeout(timer);
timer = null;
}
});
}
this.intentTimers = [];
};
wijrating.prototype._playJqueryAnimation = function (animation, allStars, animationComplete) {
var _this = this;
var self = this, o = self.options, animationOption = {
easing: animation.easing
}, animated = animation.animated;
self._clearIntentTimer();
$.each(allStars, function (i, star) {
var hideDelay = Math.floor(i / o.split) * animation.delay, intentHideTimer;
intentHideTimer = window.setTimeout(function () {
$(star).hide(animated, animationOption, animation.duration, function () {
if(i !== allStars.length - 1) {
return;
}
$.each(allStars, function (idx, showStar) {
var showDelay = Math.floor(idx / o.split) * animation.delay, intentShowTimer;
intentShowTimer = window.setTimeout(function () {
$(showStar).show(animated, animationOption, animation.duration, function () {
if(idx === allStars.length - 1) {
if(animationComplete && $.isFunction(animationComplete)) {
animationComplete.call(_this);
}
}
});
}, showDelay);
self.intentTimers.push(intentShowTimer);
});
});
}, hideDelay);
self.intentTimers.push(intentHideTimer);
});
};
wijrating.prototype._addCustomizedIconsClass = function (iconsClass, split) {
var self = this, o = self.options, stars, idx = 0, iconsIdx = 0;
if(iconsClass && iconsClass.length) {
stars = $("." + o.wijCSS.wijratingNormalStar, self.ratingElement[0]);
$.each(stars, function (i, star) {
if(idx === split) {
idx = 0;
iconsIdx++;
}
if(typeof (iconsClass) === "string") {
$(star).addClass(iconsClass);
} else if($.isArray(iconsClass)) {
var len = iconsClass.length;
if(iconsIdx < len) {
if(self.options.direction === "reversed") {
$(star).addClass(iconsClass[len - iconsIdx - 1]);
} else {
$(star).addClass(iconsClass[iconsIdx]);
}
}
}
idx++;
});
}
};
wijrating.prototype._addCustomizedHoverIconsClass = function (hoverIconsClass, split, target) {
var o = this.options, direction = o.direction, ratingMode = o.ratingMode, allStars = $("." + o.wijCSS.wijratingNormalStar, this.ratingElement[0]), tarIdx = allStars.index(target), iconIdx = 0, idx;
if(hoverIconsClass && hoverIconsClass.length) {
if(typeof (hoverIconsClass) === "string") {
target.addClass(hoverIconsClass);
if(ratingMode !== "single") {
if(direction === "reversed") {
target.parent().nextAll().children().addClass(hoverIconsClass);
} else {
target.parent().prevAll().children().addClass(hoverIconsClass);
}
}
} else if($.isArray(hoverIconsClass)) {
if(ratingMode === "single") {
if(direction === "reversed") {
idx = allStars.length - 1 - tarIdx;
} else {
idx = tarIdx;
}
iconIdx = Math.floor(idx / split);
if(hoverIconsClass.length > iconIdx) {
target.addClass(hoverIconsClass[iconIdx]);
}
} else {
if(direction === "reversed") {
for(idx = allStars.length - 1; idx >= tarIdx; idx--) {
iconIdx = Math.floor((allStars.length - 1 - idx) / split);
if(hoverIconsClass.length > iconIdx) {
$(allStars[idx]).addClass(hoverIconsClass[iconIdx]);
}
}
} else {
for(idx = 0; idx <= tarIdx; idx++) {
iconIdx = Math.floor(idx / split);
if(hoverIconsClass.length > iconIdx) {
$(allStars[idx]).addClass(hoverIconsClass[iconIdx]);
}
}
}
}
}
}
};
wijrating.prototype._removeCustomizedIconsClass = function (iconsClass) {
var o = this.options, allStars = $("." + o.wijCSS.wijratingNormalStar, this.ratingElement[0]);
if(iconsClass && iconsClass.length) {
if(typeof (iconsClass) === "string") {
allStars.removeClass(iconsClass);
} else if($.isArray(iconsClass)) {
$.each(iconsClass, function (idx, iconClass) {
allStars.removeClass(iconClass);
});
}
}
};
wijrating.prototype._parseSelect = function () {
var o = this.options, hintValues = [], opts = $("option", this.element);
if(opts.length) {
o.count = opts.length;
o.totalValue = opts.length;
$.each(opts, function (idx, opt) {
var jOpt = $(opt);
hintValues.push(jOpt.html());
if(jOpt.is(":selected")) {
o.value = idx + 1;
}
});
o.hint.content = hintValues;
}
};
wijrating.prototype._parseRadio = function () {
var self = this, o = self.options, hintValues = [], radios = $("input[type='radio']", self.element);
if(radios.length) {
o.count = radios.length;
o.totalValue = radios.length;
$.each(radios, function (idx, radio) {
var jRadio = $(radio), radioId = jRadio.attr("id"), jLabel;
if(radioId && radioId.length > 0) {
jLabel = $("label[for='" + radioId + "']", self.element);
if(jLabel.length) {
hintValues.push(jLabel.html());
} else {
hintValues.push("");
}
} else {
hintValues.push("");
}
if(jRadio.is(":checked")) {
o.value = idx + 1;
}
});
o.hint.content = hintValues;
}
};
return wijrating;
})(wijmo.wijmoWidget);
rating.wijrating = wijrating;
var wijrating_options = (function () {
function wijrating_options() {
/** @ignore*/
this.wijCSS = {
wijrating: "wijmo-wijrating",
wijratingStarContainer: "wijmo-wijrating-starcontainer",
wijratingResetButton: "wijmo-wijrating-reset",
wijratingHoverResetButton: "wijmo-wijrating-resethover",
wijratingStar: "wijmo-wijrating-star",
wijratingNormalStar: "wijmo-wijrating-normal",
wijratingHoverStar: "wijmo-wijrating-hover",
wijratingRatedStar: "wijmo-wijrating-rated",
wijvRating: "wijmo-wijrating-vertical"
};
/** @ignore*/
this.wijMobileCSS = {
iconClose: "ui-icon-delete"
};
/** A value that determines whether or not to disable the rating widget. */
this.disabled = false;
/** A value that determines the number of stars to display. */
this.count = 5;
/** An option that determines the number of sections into which each star will be split. */
this.split = 1;
/** An option that determines the total value of the rating widget.
* @remarks For example, in a rating widget with 5 stars the count is 5. A split of 2 means that each star is split into two parts.
* If the totalValue of the stars is 100, then each part of the split star has a value of 10 and each whole star has a value of 20.
* The step can be represented by this equation: 100/(5 * 2) = 10 and the value of one star can be represented by this equation: 10*(1 * 2) = 20.
*/
this.totalValue = 5;
/** An option that determines the rated value of the rating widget. */
this.value = 0;
/** An option that defines the minimum value that can be rated using the rating widget.
* @type {number}
*/
this.min = null;
/** An option that defines the maximum value that can be rated using the rating widget.
* @type {number}
*/
this.max = null;
/** The resetButton option determines the properties of the widget's reset button.
* @remarks The reset button is used to reset the rated value to 0.
* If the rating widget is disabled, the reset button will be hidden.
*/
this.resetButton = {
disabled: /** An option that determines whether to show the reset button. */
false,
hint: /** An option that controls the text shown when hovering over the button. */
"cancel this rating!",
position: /** The position sub-property defines the resetButton's position in relation to the rating widget.
* @remarks Options are "leftOrTop", "rightOrBottom".
*/
"leftOrTop",
customizedClass: /** The value that controls the customized class added to the reset button. */
"",
customizedHoverClass: /** An option that controls the customized class added to the reset button when a user hovers over it. */
""
};
/** A value that controls the hint information shown when hovering over the rating star. */
this.hint = {
disabled: /** An option that determines whether or not to show the hint. */
false,
content: /** An option that determines the values that will be shown when a star is hovered over.
* @type {array}
* @remarks If the content is null and disabled is false, then the hint will
* show the value of each star.
*/
null
};
/** The orientation option determines the orientation of the rating widget.
* @remarks Options are "horizontal" and "vertical".
*/
this.orientation = "horizontal";
/** The direction option determines the direction in which items are rated.
* @remarks Options are "normal" and "reversed". The "normal" represents rating
* from left to right or top to bottom.
*/
this.direction = "normal";
/** The ratingMode option determines how the widget performs the rating function.
* The widget can rate things continuously or singly.
* @remarks Options are "continuous" and "single". The "single" option represents
* that only one star can be rated, while "continuous" represents that
* all the stars from first to the rated one will be rated.
*/
this.ratingMode = "continuous";
/** A value that indicates the settings for customized rating icons. */
this.icons = {
iconsClass: /** A string or an array value that indicates the urls of icons.
* @type {string|array}
* @remarks If the value is a string, then all the star will apply the iconsClass.
* If the value is an array, then each star will apply the related
* iconsClass value by index.
*/
null,
hoverIconsClass: /** A string or an array value indicates the urls of hover icons.
* @type {string|array}
* @remarks If the value is a string, then all the star will apply the iconsClass when hovered over.
* If the value is an array, then each star will apply the
* related iconsClass value by index when hovered over.
*/
null,
ratedIconsClass: /** A string or an array value indicates the urls of rated icons.
* @type {string|array}
* @remarks If the value is a string, then all the rated star will apply the iconsClass.
* If the value is an array, then each rated star will apply the related
* iconsClass value by index.
*/
null
};
/** An option that determines the width of the icon. All icons should have the same width. */
this.iconWidth = 16;
/** An option that determines the height of the icon. All icons should have the same height. */
this.iconHeight = 16;
/** An option that controls aspects of the widget's animation,
* such as the animation effect and easing.
* @type {object}
* @remarks animation.animated defines the animation effect for the rating widget.
* animation.duration defines the length of the animation effect in milliseconds.
* animation.easing defines the easing effect of an animation.
* animation.delay defines the length of the delay in milliseconds.
*/
this.animation = null;
/** The rating event fires before widget rating.
* You can use this event if you'd like to track the rated values.
* You can cancel this event by returning false.
* @event
* @dataKey {number} oldValue The previously rated value.
* @dataKey {number} newValue The new value that is to be rated.
* @dataKey target The rated object.
*/
this.rating = null;
/** The rated event fires after the widget is rated.
* @event
* @dataKey {number} value The rated value.
* @dataKey target The rated object.
*/
this.rated = null;
/** The reset event fires when the reset button is clicked.
* @event
*/
this.reset = null;
/** The hover event fires when a user hovers over a rating icon.
* You can use this event to trigger something, such as an alert,
* when a user hovers over one of the rating icons.
* @event
* @dataKey {number} value The value of hovered object.
* @dataKey target The hovered object.
*/
this.hover = null;
}
return wijrating_options;
})();
wijrating.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijrating_options());
$.wijmo.registerWidget("wijrating", wijrating.prototype);
//prevent jqm's default behavior for <select> markup.
if($.mobile) {
$.mobile.selectmenu.prototype.options.initSelector = $.mobile.selectmenu.prototype.options.initSelector + ":not( :jqmData(role='wijrating') )";
}
$.extend($.wijmo.wijrating, {
animations: {
scroll: function (options, stars, animationComplete) {
var o = options, aniCmp = animationComplete, duration = 250, delay = 500, easing = "linear", starDelay = 250, starsArr = jQuery.makeArray(stars);
starsArr.reverse();
$.each(starsArr, function (i, star) {
var hideDelay = Math.floor(i / o.split) * starDelay, showAnimate = {
width: 0
}, intentHideTimer, delayTimer;
intentHideTimer = window.setTimeout(function () {
$(star).animate(showAnimate, duration, easing, function () {
window.clearTimeout(intentHideTimer);
if(i !== stars.length - 1) {
return;
}
delayTimer = window.setTimeout(function () {
$.each(stars, function (idx, showStar) {
var showDelay = Math.floor(idx / o.split) * starDelay, hideAnimate = {
width: o.iconWidth
}, intentShowTimer;
intentShowTimer = window.setTimeout(function () {
var _this = this;
$(showStar).animate(hideAnimate, duration, easing, function () {
window.clearTimeout(intentShowTimer);
if(idx === stars.length - 1) {
if(aniCmp && $.isFunction(aniCmp)) {
aniCmp.call(_this);
}
}
});
}, showDelay);
});
window.clearTimeout(delayTimer);
}, delay);
});
}, hideDelay);
});
if(animationComplete && $.isFunction(animationComplete)) {
animationComplete.call(_this);
}
}
}
});
;
;
})(wijmo.rating || (wijmo.rating = {}));
var rating = wijmo.rating;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../wijchart/jquery.wijmo.wijchartcore.ts"/>
/// <reference path="../external/declarations/globalize.d.ts"/>
/*globals $, Raphael, jQuery, document, window, navigator*/
/*
* Depends:
* jquery.js
* raphael.js
* jquery.wijmo.raphael.js
* globalize.min.js
* jquery.ui.widget.js
* jquery.wijmo.wijchartcore.js
*
*/
(function (chart) {
/**
* @widget
*/
var wijscatterchart = (function (_super) {
__extends(wijscatterchart, _super);
function wijscatterchart() {
_super.apply(this, arguments);
}
wijscatterchart.prototype._create = function () {
var self = this;
self._handleChartStyles();
_super.prototype._create.call(this);
self.chartElement.addClass(self.options.wijCSS.scatter);
};
wijscatterchart.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state
*/
function () {
var self = this;
self.chartElement.removeClass(self.options.wijCSS.scatter);
_super.prototype.destroy.call(this);
};
wijscatterchart.prototype.getScatter = /** Returns the scatter element with the given series index and scatter index.
* @param {number} seriesIndex The index of the series
* @param {number} scatterIndex The index of the scatter element
* @returns {Raphael Element} if scatterIndex is not specified, return a list of scatters of specified seriesIndex,
* else return the specified scatter element
*/
function (seriesIndex, scatterIndex) {
var self = this, fields = self.chartElement.data("fields"), und, len, scatters, scatter;
if(fields && fields.chartElements) {
scatters = fields.chartElements.scatters;
if(scatters && scatters.length) {
len = scatters.length;
if(seriesIndex < 0 || seriesIndex >= len) {
return und;
}
scatter = scatters[seriesIndex];
if(typeof scatterIndex === "undefined") {
return scatter;
}
len = scatter.length;
if(scatter && len) {
if(scatterIndex < 0 || scatterIndex >= len) {
return und;
}
return scatter[scatterIndex];
}
}
return und;
}
};
wijscatterchart.prototype._paintLegendIcon = function (x, y, width, height, style, legendIndex, seriesIndex, legendCss, series, leg) {
var self = this, r = Math.min(width, height), markerStyle, type = series.markerType, icon;
markerStyle = series.markerStyle;
markerStyle = $.extend({
fill: style.stroke,
stroke: style.stroke,
opacity: 1
}, markerStyle);
if(!type) {
type = "circle";
}
icon = self.canvas.paintMarker(type, x + width / 2, y + height / 2, 3);
$(icon.node).data("legendIndex", legendIndex).data("index", seriesIndex);
self.legendIcons.push(icon);
icon.attr(markerStyle);
$.wijraphael.addClass($(icon.node), legendCss);
if(series.visible === false) {
$(leg.node).data("dotOpacity", icon.attr("opacity") || 1);
icon.attr("opacity", 0.3);
}
return icon;
};
wijscatterchart.prototype._paintLegend = function () {
var self = this, o = self.options, chartsSeries = [].concat(o.seriesList), chartsSeriesStyle = o.seriesStyles, idx = 0;
$.extend(true, o, {
legend: {
size: {
width: 20,
height: 10
}
}
});
_super.prototype._paintLegend.call(this);
//if (o.legend.visible) {
// //hide legendIcons
// if (self.legends.length && self.legendIcons.length) {
// $.each(self.legendIcons, function (idx, icon) {
// icon.hide();
// });
// }
// //add marker to legendIcons
// if (o.legend.reversed) {
// chartsSeries.reverse();
// }
// $.each(chartsSeries, function (i, chartSeries) {
// var type = chartSeries.markerType,
// legendIcon,
// box,
// x,
// y,
// seriesStyle = o.legend.reversed ?
// chartsSeriesStyle[chartsSeries.length - 1 - i] :
// chartsSeriesStyle[i],
// style:any = $.extend(true, {}, seriesStyle),
// leg = o.legend.textWidth ?
// self.legends[idx][0] : self.legends[idx],
// dot;
// if (style.stroke && !style.fill) {
// style.fill = style.stroke;
// }
// if (chartSeries.legendEntry &&
// chartSeries.display !== "exclude") {
// if ((chartSeries.data.x === undefined &&
// chartSeries.data.xy === undefined) ||
// chartSeries.data.y === undefined &&
// chartSeries.data.xy === undefined
// ) {
// return true;
// }
// legendIcon = self.legendIcons[idx];
// box = legendIcon.wijGetBBox();
// x = box.x + box.width / 2;
// y = box.y + box.height / 2;
// if (!type) {
// type = "circle";
// }
// dot = self.canvas.paintMarker(type, x, y, 3);
// $.wijraphael.addClass($(dot.node),
// o.wijCSS.legendDot + " " + o.wijCSS.canvasObject + " " + o.wijCSS.legend);
// dot.attr(style);
// self.legendDots.push(dot);
// $(dot.node).data("legendIndex",
// $(leg.node).data("legendIndex"))
// .data("index", $(leg.node).data("index"));
// self.legendEles.push(dot);
// if (chartSeries.visible === false) {
// $(leg.node).data("dotOpacity",
// dot.attr("opacity") || 1);
// dot.attr("opacity", 0.3);
// }
// idx++;
// }
// });
//}
};
wijscatterchart.prototype._showSerieEles = function (seriesEle) {
$.each(seriesEle, function (i, dot) {
dot.show();
if(dot.label) {
dot.label.show();
}
if($(dot.element).data("wijchartDataObj")) {
$(dot.element).data("wijchartDataObj").visible = true;
}
});
};
wijscatterchart.prototype._hideSerieEles = function (seriesEle) {
$.each(seriesEle, function (i, dot) {
dot.hide();
if(dot.label) {
dot.label.hide();
}
if($(dot.element).data("wijchartDataObj")) {
$(dot.element).data("wijchartDataObj").visible = false;
}
});
};
wijscatterchart.prototype._indicatorLineShowing = function (objs) {
_super.prototype._indicatorLineShowing.call(this, objs);
$.each(objs, function (i, obj) {
if(obj.dot) {
obj.dot.attr(obj.hoverStyle);
obj.dot.scale(1.5, 1.5);
}
});
};
wijscatterchart.prototype._removeIndicatorStyles = function (objs) {
$.each(objs, function (i, obj) {
if(obj.dot) {
obj.dot.attr(obj.style);
obj.dot.scale(1, 1);
}
});
};
wijscatterchart.prototype._paintTooltip = function () {
var self = this, element = self.chartElement, fields = element.data("fields");
_super.prototype._paintTooltip.call(this);
if(self.tooltip) {
if(fields && fields.chartElements && fields.chartElements.tooltipTars) {
self.tooltip.setTargets(fields.chartElements.tooltipTars);
self.tooltip.setOptions({
mouseTrailing: false
});
}
}
};
wijscatterchart.prototype._getTooltipText = function (fmt, target) {
var dataObj = $(target).data("wijchartDataObj"), obj = {
data: dataObj,
label: dataObj.label,
x: dataObj.x,
y: dataObj.y,
type: dataObj.markerType,
target: target,
fmt: fmt
};
return $.proxy(fmt, obj)();
};
wijscatterchart.prototype._onBeforeTooltipShowing = function (tooltip) {
var self = this, o = tooltip.options, hintStyle = self.options.hint.style, target = tooltip.target, obj, dotStyle;
if(target) {
if($.browser.msie && parseInt($.browser.version) < 9) {
obj = $(target).data().wijchartDataObj;
dotStyle = obj.style;
o.style.stroke = hintStyle.stroke || dotStyle.stroke || dotStyle.fill || "#ffffff";
} else {
o.style.stroke = hintStyle.stroke || target.getAttribute("stroke") || target.getAttribute("fill") || "#ffffff";
}
target.attrs = {
stroke: o.style.stroke
};
}
_super.prototype._onBeforeTooltipShowing.call(this, tooltip);
};
wijscatterchart.prototype._clearChartElement = function () {
var self = this, fields = self.chartElement.data("fields");
if(self.headerEles.length) {
$.each(self.headerEles, function (idx, headerEle) {
headerEle.wijRemove();
headerEle = null;
});
self.headerEles = [];
}
if(self.footerEles.length) {
$.each(self.footerEles, function (idx, footerEle) {
footerEle.wijRemove();
footerEle = null;
});
self.footerEles = [];
}
if(self.legendEles.length) {
$.each(self.legendEles, function (idx, legendEle) {
legendEle.wijRemove();
legendEle = null;
});
self.legendEles = [];
}
if(self.legends.length) {
$.each(self.legends, function (idx, legend) {
legend.wijRemove();
legend = null;
});
self.legends = [];
}
if(self.legendIcons.length) {
$.each(self.legendIcons, function (idx, legendIcon) {
legendIcon.wijRemove();
legendIcon = null;
});
self.legendIcons = [];
}
if(self.legendDots.length) {
$.each(self.legendDots, function (idx, legendDot) {
legendDot = null;
});
self.legendDots = [];
}
if(self.axisEles.length) {
$.each(self.axisEles, function (idx, axisEle) {
axisEle.wijRemove();
axisEle = null;
});
self.axisEles = [];
}
if(self.chartLabelEles.length) {
$.each(self.chartLabelEles, function (idx, chartLabelEle) {
chartLabelEle.wijRemove();
chartLabelEle = null;
});
self.chartLabelEles = [];
}
if(fields && fields.chartElements) {
$.each(fields.chartElements, function (key, eles) {
if(eles.length) {
$.each(eles, function (i, ele) {
if(ele[0] !== null) {
if(ele.remove) {
ele.remove();
}
eles[i] = null;
}
});
}
fields.chartElements[key] = null;
});
fields.chartElements = {
};
$(fields.clipRect.element).stop().remove();
fields.render.destroy();
fields.clipRect.destroy();
}
self.dataPoints = null;
self.pointXs = null;
self.canvas.clear();
self.innerState = {
};
};
wijscatterchart.prototype._paintPlotArea = function () {
var self = this, o = self.options, scatterRender;
scatterRender = new ScatterChartRender(this.chartElement, {
bounds: self.canvasBounds,
widgetName: self.widgetName,
canvas: self.canvas,
tooltip: self.tooltip,
axis: o.axis,
animation: o.animation,
seriesTransition: o.seriesTransition,
seriesList: o.seriesList,
seriesStyles: o.seriesStyles,
seriesHoverStyles: o.seriesHoverStyles,
hint: o.hint,
disabled: o.disabled,
isXTime: //plotInfo: plotInfo,
self.axisInfo.x.isTime,
isYTime: self.axisInfo.y[0].isTime,
zoomOnHover: o.zoomOnHover,
mouseDown: $.proxy(self._mouseDown, self),
mouseUp: $.proxy(self._mouseUp, self),
mouseOver: $.proxy(self._mouseOver, self),
mouseOut: $.proxy(self._mouseOut, self),
mouseMove: $.proxy(self._mouseMove, self),
click: $.proxy(self._click, self),
showChartLabels: o.showChartLabels,
chartLabelStyle: o.chartLabelStyle,
chartLabelFormatString: o.chartLabelFormatString,
culture: self._getCulture(),
wijCSS: o.wijCSS,
widget: this
});
scatterRender.render();
};
return wijscatterchart;
})(chart.wijchartcore);
chart.wijscatterchart = wijscatterchart;
wijscatterchart.prototype.widgetEventPrefix = "wijscatterchart";
var wijscatterchart_options = (function () {
function wijscatterchart_options() {
/**
* Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijscatterchart')";
/**
* @ignore
*/
this.wijCSS = {
scatter: "wijmo-wijscatterchart",
scatterElement: "wijscatterchart"
};
/**
* An option that controls aspects of the widget's animation, such as duration and easing.
*/
this.animation = {
enabled: /**
* A value that determines whether to show animation.
*/
true,
duration: /**
* A value that indicates the duration for the animation.
*/
2000,
easing: /**
* Sets the type of animation easing effect that users experience when the wijscatterchart series is loaded to the page.
* @remarks
* For example, a user can have the wijscatterchart series bounce several times as it loads.
* The easing is defined in Raphael, the documentation is: http://raphaeljs.com/reference.html#Raphael.easing_formulas
*/
">"
};
/**
* A value that indicates whether to show default chart labels.
*/
this.showChartLabels = false;
/**
* The seriesTransition option is used to animate series in the chart when just their values change.
* @remarks
* This is helpful for visually showing changes in data for the same series.
*/
this.seriesTransition = {
enabled: /**
* A value that determines whether to show animation when reloading data.
*/
true,
duration: /**
* A value that indicates the duration for the series transition.
*/
2000,
easing: /**
* A value that indicates the easing for the series transition.
* @remarks
* The easing is defined in Raphael, the documentation is: http://raphaeljs.com/reference.html#Raphael.easing_formulas
*/
">"
};
/**
* A value that indicates whether to zoom in on the marker on hover.
*/
this.zoomOnHover = true;
/**
* Occurs when the user clicks a mouse button.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IScatterChartEventArgs} data Information about an event
*/
this.mouseDown = null;
/**
* Fires when the user releases a mouse button while the pointer is over the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IScatterChartEventArgs} data Information about an event
*/
this.mouseUp = null;
/**
* Fires when the user first places the pointer over the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IScatterChartEventArgs} data Information about an event
*/
this.mouseOver = null;
/**
* Fires when the user moves the pointer off of the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IScatterChartEventArgs} data Information about an event
*/
this.mouseOut = null;
/**
* Fires when the user moves the mouse pointer while it is over a chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IScatterChartEventArgs} data Information about an event
*/
this.mouseMove = null;
/**
* Fires when the user clicks the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IScatterChartEventArgs} data Information about an event
*/
this.click = null;
}
return wijscatterchart_options;
})();
wijscatterchart.prototype.options = $.extend(true, {
}, chart.wijchartcore.prototype.options, new wijscatterchart_options());
$.wijmo.registerWidget("wijscatterchart", wijscatterchart.prototype);
/** @ignore */
var ScatterChartRender = (function () {
function ScatterChartRender(element, options) {
this.scatters = [];
this.chartLabels = [];
this.tooltipTars = [];
this.seriesEles = [];
this.element = element;
this.options = options;
this._init();
}
ScatterChartRender.prototype._init = function () {
var element = this.element, o = this.options, bounds = o.bounds, minX = o.axis.x.min, minY = o.axis.y.min, maxX = o.axis.x.max, maxY = o.axis.y.max;
this.width = bounds.endX - bounds.startX;
this.height = bounds.endY - bounds.startY;
this.plotInfo = {
minX: minX,
minY: minY,
maxX: maxX,
maxY: maxY,
width: this.width,
height: this.height,
kx: this.width / (maxX - minX),
ky: this.height / (maxY - minY)
};
this.fields = element.data("fields") || {
};
if(element.find("svg").length > 0) {
this.chartRender = chart.render.createRender(element.find("svg").get(0), element.width(), element.height());
} else {
this.chartRender = chart.render.createRender(element.children(":first").addClass("vmlcontainer").get(0), element.width(), element.height());
}
this.clipRect = this.chartRender.clipRect(0, 0, 0, element.height());
this.g = this.chartRender.g();
this.g.clip(this.clipRect);
this.g.add();
this.fields.render = this.chartRender;
this.fields.clipRect = this.clipRect;
};
ScatterChartRender.prototype.bindLiveEvents = function () {
var isFunction = $.isFunction, o = this.options, wijCSS = o.wijCSS, element = this.element, widgetName = o.widgetName, mouseDown = o.mouseDown, mouseUp = o.mouseUp, mouseOver = o.mouseOver, mouseOut = o.mouseOut, mouseMove = o.mouseMove, click = o.click, zoomOnHover = o.zoomOnHover, seriesHoverStyles = o.seriesHoverStyles, seriesStyles = o.seriesStyles, disabled = o.disabled;
$("." + wijCSS.scatterElement, element[0]).on("mousedown." + widgetName, function (e) {
if(disabled) {
return;
}
if(isFunction(mouseDown)) {
var dataObj = $(e.target).data("wijchartDataObj");
if(!dataObj) {
dataObj = $(e.target.parentNode).data("wijchartDataObj");
}
mouseDown.call(element, e, dataObj);
}
}).on("mouseup." + widgetName, function (e) {
if(disabled) {
return;
}
if(isFunction(mouseUp)) {
var dataObj = $(e.target).data("wijchartDataObj");
if(!dataObj) {
dataObj = $(e.target.parentNode).data("wijchartDataObj");
}
mouseUp.call(element, e, dataObj);
}
}).on("mouseover." + widgetName, function (e) {
if(disabled) {
return;
}
var dataObj = $(e.target).data("wijchartDataObj"), seriesIndex, style, dot;
if(!dataObj) {
dataObj = $(e.target.parentNode).data("wijchartDataObj");
}
dot = dataObj.dot;
if(zoomOnHover) {
seriesIndex = dataObj.seriesIndex;
if(dot.attr) {
// style = $.extend(true, dot.attr(),
// seriesHoverStyles[seriesIndex]);
style = $.extend(true, {
}, seriesHoverStyles[seriesIndex]);
dot.attr(style);
}
if(document.createElementNS) {
dot.scale(1.5, 1.5);
} else {
dot.attr("stroke-width", 5);
}
}
if(isFunction(mouseOver)) {
mouseOver.call(element, e, dataObj);
}
}).on("mouseout." + widgetName, function (e) {
if(disabled) {
return;
}
var dataObj = $(e.target).data("wijchartDataObj"), seriesIndex, dot;
if(!dataObj) {
dataObj = $(e.target.parentNode).data("wijchartDataObj");
}
dot = dataObj.dot;
if(zoomOnHover) {
seriesIndex = dataObj.seriesIndex;
if(dot.attr) {
dot.attr($.extend(true, {
}, seriesStyles[seriesIndex]));
}
}
if(document.createElementNS) {
dot.scale(1, 1);
}
if(isFunction(mouseOut)) {
mouseOut.call(element, e, dataObj);
}
}).on("mousemove." + widgetName, function (e) {
if(disabled) {
return;
}
if(isFunction(mouseMove)) {
var dataObj = $(e.target).data("wijchartDataObj");
if(!dataObj) {
dataObj = $(e.target.parentNode).data("wijchartDataObj");
}
mouseMove.call(element, e, dataObj);
}
}).on("click." + widgetName, function (e) {
if(disabled) {
return;
}
if(isFunction(click)) {
var dataObj = $(e.target).data("wijchartDataObj");
if(!dataObj) {
dataObj = $(e.target.parentNode).data("wijchartDataObj");
}
click.call(element, e, dataObj);
}
});
};
ScatterChartRender.prototype.unbindLiveEvents = function () {
var o = this.options, widgetName = o.widgetName, wijCSS = o.wijCSS;
$("." + wijCSS.scatterElement, this.element).off(widgetName).off(// for jQuery 1.7.1
"." + widgetName);
};
ScatterChartRender.prototype.paintDefaultChartLabel = function (x, y, val) {
var o = this.options, textStyle = $.extend(true, {
}, o.textStyle, o.chartLabelStyle), text, chartLabelFormatString = o.chartLabelFormatString, dcl;
if(o.isYTime) {
text = Globalize.format(val, "f", o.culture);
} else {
text = $.round(val, 2);
}
if(chartLabelFormatString && chartLabelFormatString.length) {
text = Globalize.format(text, chartLabelFormatString, o.culture);
}
dcl = this.chartRender.text(x, y, text);
return dcl;
};
ScatterChartRender.prototype.paintScatters = function () {
var self = this, o = self.options, seriesList = o.seriesList, seriesStyles = o.seriesStyles, seriesHoverStyles = o.seriesHoverStyles, isXTime = o.isXTime, isYTime = o.isYTime, bounds = o.bounds, plotInfo = this.plotInfo, wijCSS = o.wijCSS, showChartLabels = o.showChartLabels, labelStyle = o.chartLabelStyle, widget = o.widget;
$.each(seriesList, function (i, series) {
var data = series.data, type, markerWidth = series.markerWidth || 5, style = seriesStyles[i], hoverStyle = seriesHoverStyles[i], valuesX = data.x, valuesY = data.y, scatter = [], seriesEle = [], pointX;
series = $.extend(true, {
visible: true,
markerType: "circle"
}, series);
type = series.markerType;
if(series.display === "exclude") {
return true;
}
if(!style.fill && style.stroke) {
style.fill = style.stroke;
}
if(valuesX === undefined) {
return true;
}
$.each(valuesY, function (j, valY) {
var valX = valuesX[j], X = 0, Y = 0, val, dot, chartLabel, dotData = {
};
if(isXTime) {
valX = $.toOADate(valX);
}
if(isYTime) {
valY = $.toOADate(valY);
}
if(typeof (valX) === "undefined") {
return false;
}
if(isNaN(valX) || typeof valX === "string") {
val = j;
} else {
val = valX;
}
X = bounds.startX + (val - plotInfo.minX) * plotInfo.kx;
Y = bounds.endY - (valY - plotInfo.minY) * plotInfo.ky;
if(style.opacity) {
style["fill-opacity"] = style.opacity;
style["stroke-opacity"] = style.opacity;
delete (style.opacity);
}
if(type === "cross" && style["stroke-width"] !== undefined && style["stroke-width"] === 0) {
style["stroke-width"] = 1;
}
//handle gradient fill.
//fill = style.fill;
//fill = fill.replace(/[\(\)\s,\xb0#]/g, "_");
dot = self.chartRender.symbol(type, X, Y, markerWidth);
dot.attr(style);
dot.add(self.g);
dot.attr({
"class": wijCSS.canvasObject + " " + wijCSS.scatterElement
});
dotData = $.extend(false, {
dot: dot,
x: valuesX[j],
y: valuesY[j],
seriesIndex: i,
index: j,
markerType: type,
type: "scatter",
style: style,
hoverStyle: hoverStyle,
visible: true
}, series);
// paint label
if(showChartLabels) {
chartLabel = self.paintDefaultChartLabel(X, Y - 6, valuesY[j]);
chartLabel.add(self.g);
//self.chartRender.text(X, Y - 6, valuesY[j]).add(self.g);
labelStyle = $.extend({
"font-size": "10px",
fill: "#888",
"font-family": "Arial"
}, labelStyle);
chartLabel.attr(labelStyle);
dot.label = chartLabel;
self.chartLabels.push(chartLabel);
}
// cache the bar position to show indicator line.
widget.dataPoints = widget.dataPoints || {
};
widget.pointXs = widget.pointXs || [];
pointX = $.round(X, 2);
if(!widget.dataPoints[pointX.toString()]) {
widget.dataPoints[pointX.toString()] = [];
widget.pointXs.push(pointX);
}
widget.dataPoints[pointX.toString()].push(dotData);
$(dot.element).data("wijchartDataObj", dotData);
scatter.push(dot);
self.tooltipTars.push($.extend({
}, dot, {
node: dot.element
}));
seriesEle.push(dot);
if(series.visible === false) {
dot.hide();
}
});
self.scatters.push(scatter);
self.seriesEles.push(seriesEle);
});
};
ScatterChartRender.prototype.playAnimation = function () {
var self = this, o = self.options, ani = o.animation, element = self.element, bgColor = element.css("background-color");
if(ani.enabled) {
if(bgColor === "transparent") {
bgColor = "white";
}
if(self.clipRect.getCSS) {
$(self.clipRect.members[0].element).animate({
width: element.width()
}, {
duration: ani.duration,
step: function (val) {
self.clipRect.width = val;
var clipcss = self.clipRect.getCSS();
$(this).css(clipcss);
}
});
} else {
$(self.clipRect.element).animate({
width: element.width()
}, {
duration: ani.duration,
step: function (val) {
self.clipRect.attr("width", val);
}
});
}
} else {
if(self.clipRect.getCSS) {
$(self.clipRect.members[0].element).css({
width: element.width()
});
self.clipRect.width = element.width();
$(self.clipRect.members[0].element).css(self.clipRect.getCSS());
} else {
$(self.clipRect.element).css({
width: element.width()
});
self.clipRect.attr("width", element.width());
}
}
};
ScatterChartRender.prototype.render = function () {
this.paintScatters();
this.playAnimation();
this.unbindLiveEvents();
this.bindLiveEvents();
this.chartEles = {
animationSet: this.animationSet,
tooltipTars: this.tooltipTars,
scatters: this.scatters,
labels: this.chartLabels
};
if(!this.fields.chartElements) {
this.fields.chartElements = {
};
}
this.fields.seriesEles = this.seriesEles;
$.extend(true, this.fields.chartElements, this.chartEles);
this.element.data("fields", this.fields);
};
return ScatterChartRender;
})();
chart.ScatterChartRender = ScatterChartRender;
})(wijmo.chart || (wijmo.chart = {}));
var chart = wijmo.chart;
})(wijmo || (wijmo = {}));
var wijmo;
(function (wijmo) {
(function (chart) {
/** @ignore */
(function (render) {
var doc = document, each = $.each, isIE = $.browser.msie, docMode8 = doc.documentMode === 8, SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg')["createSVGRect"], _counter = 0, DIV = 'div', ABSOLUTE = 'absolute', HIDDEN = 'hidden', PREFIX = 'scatterchart-', VISIBLE = 'visible', VISIBILITY = "visibility", PX = 'px', NONE = 'none', M = 'M', L = 'L', regRadialGradient = /^r(?:\(([^,]+?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*([^\)]+?)\))?/, regLinearGradient = /^(\d{1,3})\-(?:((?:[a-zA-Z]+)|(?:\#[0-9a-fA-F]{6})|(?:\#[0-9a-fA-F]{3}))\-)(?:(?:((?:(?:[a-zA-Z]+)|(?:\#[0-9a-fA-F]{6})|(?:\#[0-9a-fA-F]{3}))(?:\:\d{1,3})?)\-)?)*((?:[a-zA-Z]+)|(?:\#[0-9a-fA-F]{6})|(?:\#[0-9a-fA-F]{3}))$/;
function isString(s) {
return typeof s === 'string';
}
function isNumber(n) {
return typeof n === 'number';
}
function defined(obj) {
return obj !== undefined && obj !== null;
}
function attr(elem, prop, value) {
var setAttr = 'setAttribute', ret;
if(isString(prop)) {
if(defined(value)) {
elem[setAttr](prop, value);
} else if(elem && elem.getAttribute) {
ret = elem.getAttribute(prop);
}
} else if(defined(prop) && $.isPlainObject(prop)) {
$.each(prop, function (key, val) {
elem[setAttr](key, val);
});
}
return ret;
}
function css(el, styles) {
if(isIE) {
if(styles && styles.opacity !== undefined) {
styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
}
}
$.extend(el.style, styles);
}
function createElement(tag, attribs, styles) {
var el = doc.createElement(tag);
if(attribs) {
$.extend(el, attribs);
}
if(styles) {
css(el, styles);
}
return el;
}
function destroyObjectProperties(obj) {
$.each(obj, function (key, node) {
if(obj[key] && obj[key].destroy) {
obj[key].destroy();
}
delete obj[key];
});
}
var ChartElement = (function () {
function ChartElement() { }
ChartElement.prototype.attr = function (hash, val) {
};
ChartElement.prototype.scale = function (x, y) {
};
ChartElement.prototype.symbolAttr = function (hash) {
};
ChartElement.prototype.clip = function (clipRect) {
};
ChartElement.prototype.crisp = function (strokeWidth, x, y, width, height) {
};
ChartElement.prototype.css = function (styles) {
};
ChartElement.prototype.getBBox = function () {
};
ChartElement.prototype.show = function () {
};
ChartElement.prototype.hide = function () {
};
ChartElement.prototype.add = function (parent) {
};
ChartElement.prototype.destroy = function () {
};
ChartElement.prototype.empty = function () {
};
ChartElement.prototype.remove = function () {
};
return ChartElement;
})();
render.ChartElement = ChartElement;
var ChartRender = (function () {
function ChartRender(container, width, height) {
}
ChartRender.prototype.destroy = function () {
};
ChartRender.prototype.createElement = function (nodeName) {
};
ChartRender.prototype.path = function (path) {
return this._element;
};
ChartRender.prototype.circle = function (x, y, r) {
return this._element;
};
ChartRender.prototype.rect = function (x, y, width, height, r, strokeWidth) {
return this._element;
};
ChartRender.prototype.setSize = function (width, height) {
};
ChartRender.prototype.g = function (name) {
return this._element;
};
ChartRender.prototype.text = function (x, y, text) {
return this._element;
};
ChartRender.prototype.symbol = function (_symbol, x, y, radius, options) {
return this._element;
};
ChartRender.prototype.clipRect = function (x, y, width, height) {
return this._element;
};
return ChartRender;
})();
render.ChartRender = ChartRender;
var SVGElement = (function (_super) {
__extends(SVGElement, _super);
function SVGElement() {
_super.apply(this, arguments);
}
SVGElement.prototype.init = function (renderer, nodeName) {
this.element = doc.createElementNS(SVG_NS, nodeName);
this.renderer = renderer;
};
SVGElement.prototype.attr = function (hash, val) {
var key, value, element = this.element, renderer = this.renderer, nodeName = element.nodeName, skipAttr, ret = this;
if(hash === undefined) {
return;
}
if(isString(hash) && defined(val)) {
key = hash;
hash = {
};
hash[key] = val;
}
if(isString(hash)) {
key = hash;
if(nodeName === 'circle') {
key = {
x: 'cx',
y: 'cy'
}[key] || key;
}
ret = attr(element, key) || this[key] || 0;
if(key !== 'd' && key !== VISIBILITY) {
ret = parseFloat(ret);
}
} else if(hash) {
$.each(hash, function (key, v) {
skipAttr = false;
value = hash[key];
if(key === 'd') {
if(value && value.join) {
value = value.join(' ');
}
if(/(NaN| {2}|^$)/.test(value)) {
value = 'M 0 0';
}
this.d = value;
// apply gradients
} else if(key === 'fill') {
value = renderer._color(value, element, key);
} else if(nodeName === 'circle' && (key === 'x' || key === 'y')) {
key = {
x: 'cx',
y: 'cy'
}[key] || key;
}
if(jQuery.browser.safari && key === 'stroke-width' && value === 0) {
value = 0.000001;
}
if(!skipAttr) {
attr(element, key, value);
}
// Fixed an issue that in composite chart, when show the tooltip, the chart will throw javascript exception
// save the attribute to attrs
element.attrs = element.attrs || {
};
element.attrs[key] = value;
});
}
return ret;
};
SVGElement.prototype.scale = function (x, y) {
var self = this, bbox = self.getBBox(), cx = -(bbox.x + bbox.width / 2) / 2, cy = -(bbox.y + bbox.height / 2) / 2;
if(x === 1) {
cx = 0;
}
if(y === 1) {
cy = 0;
}
self.attr("transform", "matrix(" + x + ",0,0, " + y + "," + cx + "," + cy + ")");
};
SVGElement.prototype.symbolAttr = function (hash) {
var self = this;
each([
'x',
'y',
'r',
'start',
'end',
'width',
'height',
'innerR'
], function (i, key) {
if(hash[key]) {
self[key] = hash[key];
} else {
self[key] = self[key];
}
});
self.attr({
d: self.renderer.symbols[self.symbolName](Math.round(self.x * 2) / 2, Math.round(self.y * 2) / 2, self.r, {
start: self.start,
end: self.end,
width: self.width,
height: self.height,
innerR: self.innerR
})
});
};
SVGElement.prototype.clip = function (clipRect) {
return this.attr('clip-path', 'url(' + this.renderer.url + '#' + clipRect.id + ')');
};
SVGElement.prototype.crisp = function (strokeWidth, x, y, width, height) {
var self = this, key, attr = {
}, values = {
}, normalizer;
strokeWidth = strokeWidth || self.strokeWidth || 0;
normalizer = strokeWidth % 2 / 2;
values.x = Math.floor(x || self.x || 0) + normalizer;
values.y = Math.floor(y || self.y || 0) + normalizer;
values.width = Math.floor((width || self.width || 0) - 2 * normalizer);
values.height = Math.floor((height || self.height || 0) - 2 * normalizer);
values.strokeWidth = strokeWidth;
for(key in values) {
if(self[key] !== values[key]) {
// only set attribute if changed
self[key] = attr[key] = values[key];
}
}
return attr;
};
SVGElement.prototype.css = function (styles) {
var self = this, elem = self.element, textWidth = styles && styles.width && elem.nodeName === 'text', serializedCss = '', hyphenate = function (a, b) {
return '-' + b.toLowerCase();
};
if(styles && styles.color) {
styles.fill = styles.color;
}
styles = $.extend(self.styles, styles);
self.styles = styles;
if(isIE && !hasSVG) {
if(textWidth) {
delete styles.width;
}
css(self.element, styles);
} else {
$.each(styles, function (i, n) {
serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
});
self.attr({
style: serializedCss
});
}
return self;
};
SVGElement.prototype.getBBox = function () {
var bBox, width, height, rotation = this.rotation, rad = rotation * Math.PI * 2 / 360;
try {
bBox = $.extend({
}, this.element.getBBox());
} catch (e) {
bBox = {
width: 0,
height: 0
};
}
width = bBox.width;
height = bBox.height;
if(rotation) {
bBox.width = Math.abs(height * Math.sin(rad)) + Math.abs(width * Math.cos(rad));
bBox.height = Math.abs(height * Math.cos(rad)) + Math.abs(width * Math.sin(rad));
}
return bBox;
};
SVGElement.prototype.show = function () {
return this.attr({
visibility: VISIBLE
});
};
SVGElement.prototype.hide = function () {
return this.attr({
visibility: HIDDEN
});
};
SVGElement.prototype.add = function (parent) {
var self = this, renderer = self.renderer, parentWrapper = parent || renderer, parentNode = parentWrapper.element || renderer.box, childNodes = parentNode.childNodes, element = self.element, zIndex = attr(element, 'zIndex'), otherElement, otherZIndex, i;
if(parent && self.htmlNode) {
if(!parent.htmlNode) {
parent.htmlNode = [];
}
parent.htmlNode.push(self);
}
if(zIndex) {
parentWrapper.handleZ = true;
zIndex = parseInt(zIndex, 10);
}
if(parentWrapper.handleZ) {
for(i = 0; i < childNodes.length; i++) {
otherElement = childNodes[i];
otherZIndex = attr(otherElement, 'zIndex');
if(otherElement !== element && (parseInt(otherZIndex, 10) > zIndex || (!defined(zIndex) && defined(otherZIndex)))) {
parentNode.insertBefore(element, otherElement);
return self;
}
}
}
parentNode.appendChild(element);
self.added = true;
return self;
};
SVGElement.prototype._safeRemoveChild = function (element) {
var parentNode = element.parentNode;
if(parentNode) {
parentNode.removeChild(element);
}
};
SVGElement.prototype.destroy = function () {
var wrapper = this, element = wrapper.element || {
}, shadows = wrapper.shadows, box = wrapper.box, i;
// remove events
element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = null;
if(wrapper.clipPath) {
wrapper.clipPath = wrapper.clipPath.destroy();
}
// Destroy stops in case this is a gradient object
if(wrapper.stops) {
for(i = 0; i < wrapper.stops.length; i++) {
wrapper.stops[i] = wrapper.stops[i].destroy();
}
wrapper.stops = null;
}
// remove element
wrapper._safeRemoveChild(element);
// destroy shadows
if(shadows) {
each(shadows, function (shadow) {
wrapper._safeRemoveChild(shadow);
});
}
// destroy label box
if(box) {
box.destroy();
}
$.each(wrapper, function (key, obj) {
delete wrapper[key];
});
return null;
};
SVGElement.prototype.empty = function () {
var element = this.element, childNodes = element.childNodes, i = childNodes.length;
while(i--) {
element.removeChild(childNodes[i]);
$(childNodes[i]).remove();
}
};
SVGElement.prototype.remove = function () {
var ele = this.element, parentNode = ele.parentNode;
parentNode.removeChild(ele);
$(ele).remove();
};
return SVGElement;
})(ChartElement);
var SVGRender = (function (_super) {
__extends(SVGRender, _super);
function SVGRender(container, width, height) {
_super.call(this, container, width, height);
this.gradientCache = {
};
this.init(container, width, height);
}
SVGRender.prototype.init = function (container, width, height) {
var self = this, loc = doc.location, boxWrapper;
this.symbols = SVGRender._symbols;
this.Element = SVGElement;
if($(container).is("svg")) {
self.box = container;
boxWrapper = new self.Element();
boxWrapper.element = container;
boxWrapper.render = self;
self.defs = $("defs", container).get(0);
self.gradients = {
};
} else {
boxWrapper = self.createElement('svg').attr({
xmlns: SVG_NS,
version: '1.1'
});
container.appendChild(boxWrapper.element);
self.box = boxWrapper.element;
self.boxWrapper = boxWrapper;
self.defs = this.createElement('defs').add();
self.gradients = {
};
self.setSize(width, height);
}
self.url = isIE ? '' : loc.href.replace(/#.*?$/, '');
};
SVGRender.prototype.destroy = function () {
var self = this;
self.box = null;
destroyObjectProperties(self.gradients || {
});
self.gradients = null;
return null;
};
SVGRender.prototype.createElement = function (nodeName) {
var wrapper = new this.Element();
wrapper.init(this, nodeName);
return wrapper;
};
SVGRender.prototype.path = function (path) {
var ret = this.createElement('path');
ret.attr({
d: path,
fill: NONE
});
return ret;
};
SVGRender.prototype.circle = function (x, y, r) {
var attr = $.isPlainObject(x) ? x : {
x: x,
y: y,
r: r
}, ret = this.createElement('circle');
ret.attr(attr);
return ret;
};
SVGRender.prototype.rect = function (x, y, width, height, r, strokeWidth) {
if($.isPlainObject(x)) {
y = x.y;
width = x.width;
height = x.height;
r = x.r;
strokeWidth = x.strokeWidth;
x = x.x;
}
var wrapper = this.createElement('rect');
wrapper.attr({
rx: r,
ry: r,
fill: NONE
});
wrapper.attr(wrapper.crisp(strokeWidth, x, y, Math.max(width, 0), Math.max(height, 0)));
return wrapper;
};
SVGRender.prototype.setSize = function (width, height) {
var self = this;
self.width = width;
self.height = height;
self.boxWrapper.attr({
width: width,
height: height
});
};
SVGRender.prototype.g = function (name) {
var elem = this.createElement('g');
if(defined(name)) {
elem.attr({
'class': PREFIX + name
});
}
return elem;
};
SVGRender.prototype.text = function (x, y, text) {
if($.isPlainObject(x)) {
y = x.y;
text = x.text;
x = x.x;
}
var wrapper = this.createElement('text');
wrapper.attr({
x: x,
y: y,
"text-anchor": "middle"
});
wrapper.element.textContent = text;
return wrapper;
};
SVGRender.prototype.symbol = function (symbol, x, y, radius, options) {
var obj, self = this, symbolFn = self.symbols[symbol], path = symbolFn && symbolFn(Math.round(x), Math.round(y), radius, options);
if(path) {
obj = self.path(path);
$.extend(obj, {
symbolName: symbol,
x: x,
y: y,
r: radius
});
if(options) {
$.extend(obj, options);
}
} else {
obj = self.circle(x, y, radius);
}
return obj;
};
SVGRender._symbols = {
'box': function (x, y, radius) {
var len = 0.707 * radius;
return [
M,
x - len,
y - len,
L,
x + len,
y - len,
x + len,
y + len,
x - len,
y + len,
'Z'
];
},
'tri': function (x, y, radius) {
return [
M,
x,
y - 1.33 * radius,
L,
x + radius,
y + 0.67 * radius,
x - radius,
y + 0.67 * radius,
'Z'
];
},
'invertedTri': function (x, y, radius) {
return [
M,
x,
y + 1.33 * radius,
L,
x - radius,
y - 0.67 * radius,
x + radius,
y - 0.67 * radius,
'Z'
];
},
'diamond': function (x, y, radius) {
return [
M,
x,
y - radius,
L,
x + radius,
y,
x,
y + radius,
x - radius,
y,
'Z'
];
},
'cross': function (x, y, radius) {
var offset = 0.707 * radius;
return [
M,
x - offset,
y - offset,
L,
x + offset,
y + offset,
M,
x - offset,
y + offset,
L,
x + offset,
y - offset
];
},
'arc': function (x, y, radius, options) {
var start = options.start, end = options.end - 0.000001, innerRadius = options.innerR, cosStart = Math.cos(start), sinStart = Math.sin(start), cosEnd = Math.cos(end), sinEnd = Math.sin(end), longArc = options.end - start < Math.PI ? 0 : 1;
return [
M,
x + radius * cosStart,
y + radius * sinStart,
'A',
radius,
radius,
0,
longArc,
1,
x + radius * cosEnd,
y + radius * sinEnd,
L,
x + innerRadius * cosEnd,
y + innerRadius * sinEnd,
'A',
innerRadius,
innerRadius,
0,
longArc,
0,
x + innerRadius * cosStart,
y + innerRadius * sinStart,
'Z'
];
}
};
SVGRender.prototype.clipRect = function (x, y, width, height) {
var wrapper, id = PREFIX + _counter++, clipPath = this.createElement('clipPath');
clipPath.attr({
id: id
});
$(this.defs).append(clipPath.element);
wrapper = this.rect(x, y, width, height, 0).add(clipPath);
wrapper.id = id;
wrapper.clipPath = clipPath;
return wrapper;
};
SVGRender.prototype._parsegradientcolor = function (gradient) {
var self = this, dots = [], dot, par, i, start, end, ii, j, d;
if(self.gradientCache[gradient]) {
return self.gradientCache[gradient];
}
for(i = 0 , ii = gradient.length; i < ii; i++) {
dot = {
};
par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
dot.color = Raphael.getRGB(par[1]);
if(dot.color.error) {
return null;
}
dot.color = dot.color.hex;
if(par[2]) {
dot.offset = par[2] + "%";
}
dots.push(dot);
}
for(i = 1 , ii = dots.length - 1; i < ii; i++) {
if(!dots[i].offset) {
start = parseFloat(dots[i - 1].offset || 0);
end = 0;
for(j = i + 1; j < ii; j++) {
if(dots[j].offset) {
end = dots[j].offset;
break;
}
}
if(!end) {
end = 100;
j = ii;
}
end = parseFloat(end);
d = (end - start) / (j - i + 1);
for(; i < j; i++) {
start += d;
dots[i].offset = start + "%";
}
}
}
self.gradientCache[gradient] = dots;
return dots;
};
SVGRender.prototype._color = function (color, elem, prop) {
var self = this, type = "color", fx = 0.5, fy = 0.5, gradients = self.gradients, gradientObject, gradient, x1, y1, x2, y2, stopColor, vector, max, stopOpacity, key = color, id, angle, stops;
if(regLinearGradient.test(color)) {
type = "linear";
} else {
color = color.replace(regRadialGradient, function (all, _fx, _fy) {
type = "radial";
if(_fx && _fy) {
fx = parseFloat(_fx);
fy = parseFloat(_fy);
var dir = ((fy > 0.5) ? 1 : 0 * 2 - 1);
if(Math.pow(fx - 0.5, 2) + Math.pow(fy - 0.5, 2) > 0.25 && (fy = Math.sqrt(0.25 - Math.pow(fx - 0.5, 2)) * dir + 0.5) && fy !== 0.5) {
fy = parseFloat(fy.toFixed(5)) - 1e-5 * dir;
}
}
return "";
});
}
if(type === "linear" || type === "radial") {
gradient = color.split(/\s*\-\s*/);
if(type === "linear") {
angle = gradient.shift();
angle = -parseFloat(angle);
if(isNaN(angle)) {
return color;
}
vector = [
0,
0,
Math.cos(Raphael.rad(angle)),
Math.sin(Raphael.rad(angle))
];
max = 1 / (Math.max(Math.abs(vector[2]), Math.abs(vector[3])) || 1);
vector[2] *= max;
vector[3] *= max;
if(vector[2] < 0) {
vector[0] = -vector[2];
vector[2] = 0;
}
if(vector[3] < 0) {
vector[1] = -vector[3];
vector[3] = 0;
}
x1 = vector[0];
y1 = vector[1];
x2 = vector[2];
y2 = vector[3];
}
// If the gradient with the same setup is already created, reuse it
if(gradients[key]) {
id = attr(gradients[key].element, 'id');
// If not, create a new one and keep the reference.
} else {
stops = this._parsegradientcolor(gradient);
$.each(stops, function (i, stop) {
stop.offset = stop.offset ? stop.offset : i ? "100%" : "0%";
});
id = PREFIX + _counter++;
gradientObject = self.createElement(type + "Gradient");
if(type === "radial") {
gradientObject.attr({
id: id,
fx: fx,
fy: fy
});
} else {
gradientObject.attr({
id: id,
x1: x1,
y1: y1,
x2: x2,
y2: y2
});
}
$(this.defs).append(gradientObject.element);
// The gradient needs to keep a list of stops
// to be able to destroy them
gradientObject.stops = [];
$.each(stops, function (i, stop) {
var stopObject;
stopColor = stop.color;
stopOpacity = 1;
stopObject = self.createElement('stop');
stopObject.attr({
offset: stop.offset,
'stop-color': stopColor,
'stop-opacity': stopOpacity
}).add(gradientObject);
// Add the stop element to the gradient
gradientObject.stops.push(stopObject);
});
// Keep a reference to the gradient object so it is
// possible to reuse it and destroy it later
gradients[key] = gradientObject;
}
return 'url(#' + id + ')';
} else {
// Remove the opacity attribute added above.
// Does not throw if the attribute is not there.
elem.removeAttribute(prop + '-opacity');
return color;
}
};
return SVGRender;
})(ChartRender);
var VMLElement = (function (_super) {
__extends(VMLElement, _super);
function VMLElement() {
_super.apply(this, arguments);
}
VMLElement.prototype.init = function (renderer, nodeName) {
var markup = [
'<',
nodeName,
' filled="f" stroked="f"'
], style = [
'position: ',
ABSOLUTE,
';'
];
if(nodeName === 'shape' || nodeName === DIV) {
style.push('left:0;top:0;width:10px;height:10px;');
}
if(docMode8) {
style.push('visibility: ', nodeName === DIV ? HIDDEN : VISIBLE);
}
markup.push(' style="', style.join(''), '"/>');
if(nodeName) {
markup = nodeName === DIV || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup);
this.element = createElement(markup);
}
this.renderer = renderer;
};
VMLElement.prototype.add = function (parent) {
var self = this, renderer = self.renderer, element = self.element, box = renderer.box, inverted = parent && parent.inverted, parentNode = parent ? parent.element || parent : box;
if(inverted) {
// to do this method?
//renderer.invertChild(element, parentNode);
}
if(docMode8 && parentNode.gVis === HIDDEN) {
css(element, {
visibility: HIDDEN
});
}
parentNode.appendChild(element);
self.added = true;
return self;
};
VMLElement.prototype.attr = function (hash, val) {
var key, value, i, self = this, element = self.element || {
}, elemStyle = element.style, nodeName = element.nodeName, symbolName = self.symbolName, renderer = self.renderer, childNodes, hasSetSymbolSize, shadows = self.shadows, skipAttr, convertedPath, ret = self;
if(hash === undefined) {
return ret;
}
if(isString(hash) && defined(val)) {
key = hash;
hash = {
};
hash[key] = val;
}
if(isString(hash)) {
key = hash;
if(key === 'strokeWidth' || key === 'stroke-width') {
ret = self.strokeweight;
} else {
ret = self[key];
}
} else if(hash) {
$.each(hash, function (key, v) {
value = v;
skipAttr = false;
if(symbolName && /^(x|y|r|start|end|width|height|innerR)/.test(key)) {
if(!hasSetSymbolSize) {
self.symbolAttr(hash);
hasSetSymbolSize = true;
}
skipAttr = true;
} else if(key === 'd') {
value = value || [];
self.d = value.join(' ');
i = value.length;
convertedPath = [];
while(i--) {
if(isNumber(value[i])) {
convertedPath[i] = Math.round(value[i] * 10) - 5;
} else if(value[i] === 'Z') {
convertedPath[i] = 'x';
} else {
convertedPath[i] = value[i];
}
}
value = convertedPath.join(' ') || 'x';
element.path = value;
if(shadows) {
i = shadows.length;
while(i--) {
shadows[i].path = value;
}
}
skipAttr = true;
} else if(key === 'zIndex' || key === VISIBILITY) {
if(docMode8 && key === VISIBILITY && nodeName === DIV) {
element.gVis = value;
childNodes = element.childNodes;
i = childNodes.length;
while(i--) {
css(childNodes[i], {
visibility: value
});
}
if(value === VISIBLE) {
value = null;
}
}
if(value) {
elemStyle[key] = value;
}
skipAttr = true;
} else if(key === 'class') {
element.className = value;
} else if(key === 'stroke') {
key = 'strokecolor';
} else if(key === 'stroke-width' || key === 'strokeWidth') {
element.stroked = value ? true : false;
key = 'strokeweight';
self[key] = value;
if(isNumber(value)) {
value += PX;
}
} else if(key === 'fill') {
if(nodeName === 'SPAN') {
elemStyle.color = value;
} else {
element.filled = value !== NONE ? true : false;
value = renderer.color(value, element, key);
key = 'fillcolor';
}
}
if(!skipAttr) {
if(key === "opacity") {
key = "fill-opacity";
}
if(docMode8) {
element[key] = value;
} else {
attr(element, key, value);
}
}
//save the attribute to attrs
element.attrs = element.attrs || {
};
element.attrs[key] = value;
});
}
return ret;
};
VMLElement.prototype.scale = function (x, y) {
var self = this, strokeWidth = self.attr("stroke-width") || 0;
self.css({
filter: "progid:DXImageTransform.Microsoft.Matrix(M11=" + x + "," + ", M12=0, M21=0, M22=" + y + ", Dx=0, Dy=0, sizingmethod='auto expand')"
}).attr("stroke-width", strokeWidth);
};
VMLElement.prototype.clip = function (clipRect) {
var self = this, clipMembers = clipRect.members;
clipMembers.push(self);
return self.css(clipRect.getCSS(self.inverted));
};
VMLElement.prototype.css = function (styles) {
var self = this, element = self.element, textWidth = styles && element.tagName === 'SPAN' && styles.width;
if(textWidth) {
delete styles.width;
self.textWidth = textWidth;
}
self.styles = $.extend(self.styles, styles);
css(self.element, styles);
return self;
};
VMLElement.prototype.destroy = function () {
var self = this;
if(self["destroyClip"]) {
self["destroyClip"]();
}
return SVGElement.prototype.destroy.apply(self);
};
VMLElement.prototype.empty = function () {
var element = this.element, childNodes = element.childNodes, i = childNodes.length, node;
while(i--) {
node = childNodes[i];
node.parentNode.removeChild(node);
$(node).remove();
}
};
VMLElement.prototype.getBBox = function () {
var self = this, element = self.element, bBox = self.bBox;
if(!bBox) {
if(element.nodeName === 'text') {
element.style.position = ABSOLUTE;
}
bBox = self.bBox = {
x: element.offsetLeft,
y: element.offsetTop,
width: element.offsetWidth,
height: element.offsetHeight
};
}
return bBox;
};
return VMLElement;
})(SVGElement);
var VMLRender = (function (_super) {
__extends(VMLRender, _super);
function VMLRender() {
_super.apply(this, arguments);
this.isIE8 = $.browser.msie && parseInt($.browser.version) === 8;
}
VMLRender.prototype.init = function (container, width, height) {
var self = this, boxWrapper;
this.Element = VMLElement;
this.symbols = VMLRender._symbols;
if($(container).hasClass("vmlcontainer")) {
self.box = container;
boxWrapper = new this.Element();
boxWrapper.element = container;
boxWrapper.render = this;
self.boxWrapper = boxWrapper;
} else {
boxWrapper = self.createElement(DIV);
container.appendChild(boxWrapper.element);
self.box = boxWrapper.element;
self.boxWrapper = boxWrapper;
self.setSize(width, height);
}
if(!doc.namespaces["v"]) {
doc.namespaces.add('v', 'urn:schemas-microsoft-com:vml');
doc.createStyleSheet().cssText = 'v\\:fill, v\\:path, v\\:shape, v\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } ';
}
};
VMLRender.prototype.clipRect = function (x, y, width, height) {
var clipRect = this.createElement();
$.extend(clipRect, {
members: [],
left: x,
top: y,
width: width,
height: height,
getCSS: function (inverted) {
var rect = this, top = rect.top, left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = {
clip: 'rect(' + Math.round(inverted ? left : top) + 'px,' + Math.round(inverted ? bottom : right) + 'px,' + Math.round(inverted ? right : bottom) + 'px,' + Math.round(inverted ? top : left) + 'px)'
};
if(!inverted && docMode8) {
$.extend(ret, {
width: right + PX,
height: bottom + PX
});
}
return ret;
},
updateClipping: function () {
each(clipRect.members, function (i, member) {
member.css(clipRect.getCSS(member.inverted));
});
}
});
return clipRect;
};
VMLRender.prototype.color = function (color, elem, prop) {
var markup, self = this, type = "color", gradient, stopColor, color1, color2, colors = [], ele, strokeNodes, fxfy, stops, angle = 0;
if(regLinearGradient.test(color)) {
type = "linear";
} else {
color = color.replace(regRadialGradient, function (all, fx, fy) {
type = "radial";
if(fx && fy) {
fx = parseFloat(fx);
fy = parseFloat(fy);
if(Math.pow(fx - 0.5, 2) + Math.pow(fy - 0.5, 2) > 0.25) {
fy = Math.sqrt(0.25 - Math.pow(fx - 0.5, 2)) * ((fy > 0.5 ? 1 : 0) * 2 - 1) + 0.5;
}
fxfy = fx + " " + fy;
}
return "";
});
//type = "radial";
}
if(type === "linear" || type === "radial") {
gradient = color.split(/\s*\-\s*/);
if(type === "linear") {
angle = gradient.shift();
angle = -parseFloat(angle.toString());
}
stops = self._parsegradientcolor(gradient);
$.each(stops, function (i, stop) {
stop.offset = stop.offset ? stop.offset : i ? "100%" : "0%";
colors.push(stop.offset + " " + stop.color);
stopColor = stop.color;
if(!i) {
// first
color1 = stopColor;
} else {
color2 = stopColor;
}
});
if(type === "radial") {
markup = [
'<fill colors="',
colors.join(),
'" angle="0"',
'" focusposition="',
fxfy,
'" color="',
color1,
'" color2="',
color2,
'" focussize="0 0"',
' type="gradientTitle" focus="100%" method="none" />'
];
} else {
markup = [
'<fill colors="',
colors.join(),
'" angle="',
angle.toString(),
'" type="gradient" focus="100%" method="sigma" />'
];
}
ele = createElement(self.prepVML(markup));
$(elem).append(ele);
} else {
strokeNodes = elem.getElementsByTagName(prop);
if(strokeNodes.length) {
strokeNodes[0].opacity = 1;
}
return color;
}
};
VMLRender.prototype.prepVML = function (markup) {
var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8;
markup = markup.join('');
if(isIE8) {
markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />');
if(markup.indexOf('style="') === -1) {
markup = markup.replace('/>', ' style="' + vmlStyle + '" />');
} else {
markup = markup.replace('style="', 'style="' + vmlStyle);
}
} else {
markup = markup.replace('<', '<v:');
}
return markup;
};
VMLRender.prototype.path = function (path) {
var ret = this.createElement('shape');
ret.attr({
coordsize: '100 100',
d: path
});
return ret;
};
VMLRender.prototype.g = function (name) {
var wrapper, attribs;
if(name) {
attribs = {
'className': PREFIX + name,
'class': PREFIX + name
};
}
wrapper = this.createElement(DIV).attr(attribs);
return wrapper;
};
VMLRender.prototype.text = function (x, y, text) {
var wrapper = this.createElement("span"), ele = wrapper.element, width, height;
ele.innerHTML = text;
$(ele).appendTo("body");
width = $(ele).width();
height = $(ele).height();
x -= width / 2;
y -= height / 2;
wrapper.x = x;
wrapper.y = y;
$(ele).css({
position: "absolute",
"white-space": "nowrap",
"font-family": "Arial",
"font-size": "10",
left: x + "px",
top: y + "px"
});
return wrapper;
};
VMLRender._symbols = $.extend({
}, SVGRender._symbols, {
arc: function (x, y, radius, options) {
var start = options.start, end = options.end, cosStart = Math.cos(start), sinStart = Math.sin(start), cosEnd = Math.cos(end), sinEnd = Math.sin(end), innerRadius = options.innerR, circleCorrection = 0.07 / radius, innerCorrection = (innerRadius && 0.1 / innerRadius) || 0;
if(end - start === 0) {
return [
'x'
];
} else if(2 * Math.PI - end + start < circleCorrection) {
cosEnd = -circleCorrection;
} else if(end - start < innerCorrection) {
cosEnd = Math.cos(start + innerCorrection);
}
return [
'wa',
x - radius,
// left
y - radius,
// top
x + radius,
// right
y + radius,
// bottom
x + radius * cosStart,
// start x
y + radius * sinStart,
// start y
x + radius * cosEnd,
// end x
y + radius * sinEnd,
// end y
'at',
x - innerRadius,
// left
y - innerRadius,
// top
x + innerRadius,
// right
y + innerRadius,
// bottom
x + innerRadius * cosEnd,
// start x
y + innerRadius * sinEnd,
// start y
x + innerRadius * cosStart,
// end x
y + innerRadius * sinStart,
// end y
'x',
// finish path
'e'
];
// close
},
circle: function (x, y, r) {
return [
'wa',
// clockwisearcto
x - r,
// left
y - r,
// top
x + r,
// right
y + r,
// bottom
x + r,
// start x
y,
// start y
x + r,
// end x
y,
// end y
//'x', // finish path
'e'
];
// close
},
rect: function (left, top, r, options) {
if(!defined(options)) {
return [];
}
var width = options.width, height = options.height, right = left + width, bottom = top + height;
r = Math.min(r, width, height);
return [
M,
left + r,
top,
L,
right - r,
top,
'wa',
right - 2 * r,
top,
right,
top + 2 * r,
right - r,
top,
right,
top + r,
L,
right,
bottom - r,
'wa',
right - 2 * r,
bottom - 2 * r,
right,
bottom,
right,
bottom - r,
right - r,
bottom,
L,
left + r,
bottom,
'wa',
left,
bottom - 2 * r,
left + 2 * r,
bottom,
left + r,
bottom,
left,
bottom - r,
L,
left,
top + r,
'wa',
left,
top,
left + 2 * r,
top + 2 * r,
left,
top + r,
left + r,
top,
'x',
'e'
];
}
});
return VMLRender;
})(SVGRender);
function createRender(container, width, height) {
if(hasSVG) {
return new SVGRender(container, width, height);
} else {
return new VMLRender(container, width, height);
}
}
render.createRender = createRender;
})(chart.render || (chart.render = {}));
var render = chart.render;
})(wijmo.chart || (wijmo.chart = {}));
var chart = wijmo.chart;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../wijchart/jquery.wijmo.wijchartcore.ts"/>
/// <reference path="../external/declarations/globalize.d.ts"/>
/*globals jQuery, Globalize*/
/*
* Depends:
* raphael.js
* globalize.js
* jquery.ui.widget.js
* jquery.wijmo.wijchartcore.js
*
*/
(function (chart) {
var maxSize = 10000, bubMax = 0, bubMin = 0, bubDiff = 0;
/**
* @widget
*/
var wijbubblechart = (function (_super) {
__extends(wijbubblechart, _super);
function wijbubblechart() {
_super.apply(this, arguments);
}
wijbubblechart.prototype._setOption = function (key, value) {
var self = this, o = self.options;
//self.bubbles = [];
//self.bubbleInfos = [];
if(key === "minimumSize" || key === "minimumSize") {
if(isNaN(value) || value < 0) {
value = 0;
} else if(value > maxSize) {
value = maxSize;
}
o[key] = value;
self.redraw();
} else if(key === "chartLabel") {
$.extend(o.chartLabel, value);
self.redraw();
} else {
if(key === "showChartLabels" || key === "chartLabelStyle") {
o[key] = value;
self._setLabelOption();
}
_super.prototype._setOption.call(this, key, value);
}
if(key === "seriesList") {
self.indexs = null;
self.bubbleRadius = null;
}
};
wijbubblechart.prototype._create = function () {
var self = this, o = self.options, defFill = self._getDefFill();
this._handleChartStyles();
//$.each(o.seriesStyles, function (idx, style) {
// if (!style.fill) {
// style.fill = defFill[idx];
// }
//});
self._setLabelOption();
_super.prototype._create.call(this);
self.chartElement.addClass(o.wijCSS.bubbleChart);
};
wijbubblechart.prototype._setLabelOption = function () {
var o = this.options;
if(o.showChartLabels !== true && o.chartLabel.visible === true) {
o.chartLabel.visible = false;
}
if(!$.isPlainObject(o.chartLabel.style) && $.isPlainObject(o.chartLabelStyle)) {
o.chartLabel.style = o.chartLabelStyle;
}
};
wijbubblechart.prototype._clearChartElement = function () {
var self = this, o = self.options, fields = self.chartElement.data("fields");
_super.prototype._clearChartElement.call(this);
if(fields && fields.bubbleInfos) {
$.each(fields.bubbleInfos, function (i, n) {
if(n.bubble) {
n.bubble.wijRemove();
}
if(n.dcl) {
n.dcl.wijRemove();
}
if(n.symbol) {
n.symbol.wijRemove();
}
});
}
if(fields && fields.bubbles) {
self._destroyRaphaelArray(fields.bubbles);
}
self.element.removeData("plotInfos");
if(!o.seriesTransition.enabled) {
if(fields && fields.bubblesAnimationInfos) {
fields.bubblesAnimationInfos = null;
}
}
};
wijbubblechart.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this;
self.chartElement.removeClass(self.options.wijCSS.bubbleChart + " ui-helper-reset");
self._destroyEles();
_super.prototype.destroy.call(this);
};
wijbubblechart.prototype.getBubble = /**
* Returns the bubble which has a Raphael's object that represents bubbles for the series data with the given index.
* @param {number} index The index of the bubble.
* @returns {Raphael Element} The bubble object.
*/
function (index) {
return this.chartElement.data("fields").bubbles[index];
};
wijbubblechart.prototype.redraw = /** @ignore*/
function (ifNeed) {
this.bubbleRadius = null;
_super.prototype.redraw.call(this, ifNeed);
};
wijbubblechart.prototype._destroyEles = function () {
var self = this, ele = self.element, fields = ele.data("fields");
if(fields.bubbleInfos) {
$.each(fields.bubbleInfos, function (i, n) {
self._removeEle(n.bubble);
self._removeEle(n.dcl);
self._removeEle(n.symbol);
n = null;
});
//self.bubbleInfos = [];
}
ele.removeData("fields");
//self.bubbles = [];
self.bubbleRadius = [];
//self.seriesEles = [];
//self.tooltipbubbles = [];
};
wijbubblechart.prototype._removeEle = function (ele) {
if(ele) {
if(ele.node) {
$(ele.node).removeData();
}
ele.wijRemove();
ele = null;
}
};
wijbubblechart.prototype._paintPlotArea = function () {
var self = this, element = this.chartElement, o = self.options, seriesList = o.seriesList, nSeries = seriesList.length, seriesStyles = [].concat(o.seriesStyles.slice(0, nSeries)), seriesHoverStyles = [].concat(o.seriesHoverStyles.slice(0, nSeries)), canvasBounds = self.canvasBounds, xaxis = //startLocation = { x: canvasBounds.startX, y: canvasBounds.startY },
//width = canvasBounds.endX - startLocation.x,
//height = canvasBounds.endY - startLocation.y,
self.axisInfo.x, yaxis = //todo need add chartarea
self.axisInfo.y[0];
if(nSeries === 0) {
return;
}
//self._paintcircles(seriesList, seriesStyles, seriesHoverStyles,
// xaxis, yaxis, width, height, startLocation);
self._prepBubbleData();
this.bubbleChartRender = new BubbleChartRender(this.chartElement, {
seriesList: seriesList,
seriesStyles: seriesStyles,
seriesHoverStyles: seriesHoverStyles,
canvas: self.canvas,
bounds: canvasBounds,
xAxisInfo: xaxis,
yAxisInfo: yaxis,
chartLabel: o.chartLabel,
textStyle: o.textStyle,
chartLabelStyle: o.chartLabelStyle,
chartLabelFormatString: o.chartLabelFormatString,
bubbleRadius: self.bubbleRadius,
animation: o.animation,
seriesTransition: o.seriesTransition,
sizingMethod: o.sizingMethod,
minimumSize: o.minimumSize,
maximumSize: o.maximumSize,
mouseDown: $.proxy(self._mouseDown, self),
mouseUp: $.proxy(self._mouseUp, self),
mouseOver: $.proxy(self._mouseOver, self),
mouseOut: $.proxy(self._mouseOut, self),
mouseMove: $.proxy(self._mouseMove, self),
click: $.proxy(self._click, self),
disabled: o.disabled,
culture: self._getCulture(),
wijCSS: o.wijCSS,
shadow: o.shadow,
widget: this
});
this.bubbleChartRender.render();
self.tooltipbubbles = [];
$.each(element.data("fields").bubbleInfos, function (idx, bubbleInfo) {
self.tooltipbubbles.push(bubbleInfo.bubble);
if(bubbleInfo.dcl) {
self.tooltipbubbles.push(bubbleInfo.dcl);
}
if(bubbleInfo.symbol) {
self.tooltipbubbles.push(bubbleInfo.symbol);
}
});
if(self.tooltip) {
self.tooltip.setTargets(self.tooltipbubbles);
}
//self._playAnimation(self.bubbleInfos);
};
wijbubblechart.prototype._paintLegendIcon = function (x, y, width, height, style, legendIndex, seriesIndex, legendCss, series, leg) {
var self = this, r = Math.min(width, height), markerStyle, type, icon;
markerStyle = series.markerStyle;
markerStyle = $.extend({
fill: style.fill,
stroke: style.stroke,
opacity: 1
}, markerStyle);
if(series.markers) {
type = series.markers.type;
}
if(!type) {
type = "circle";
}
icon = self.canvas.paintMarker(type, x + width / 2, y + height / 2, r / 2);
$(icon.node).data("legendIndex", legendIndex).data("index", seriesIndex);
self.legendIcons.push(icon);
icon.attr(markerStyle);
$.wijraphael.addClass($(icon.node), legendCss);
return icon;
};
wijbubblechart.prototype._getbubbleIndexs = function (width, height) {
var self = this, o = self.options, xmax = o.axis.x.max, xmin = o.axis.x.min, ymin = o.axis.y.min, ymax = o.axis.y.max, xsub = //width = self.element.width(),
//height = self.element.height(),
[], ysub = [], xadd = [], yadd = [], datax = [], datay = [], xminIndex = -1, yminIndex = -1, xmaxIndex = -1, ymaxIndex = -1;
self.bubbleRadius = [];
self._prepBubbleData();
$.each(o.seriesList, function (idx, series) {
var data = series.data, markers = series.markers || {
}, markerType = markers.type || "circle";
if(data.y1 === undefined) {
return true;
}
$.each(data.y1, function (i, yval) {
var r = wijbubblechart.transform(yval, o.maximumSize, o.minimumSize, self.canvasBounds, bubMin, bubDiff, o.sizingMethod, markerType), x, y;
if(self._isDate(data.x[i])) {
x = $.toOADate(data.x[i]);
} else if(isNaN(data.x[i])) {
x = i;
} else {
x = data.x[i];
}
y = data.y[i];
if(self._isDate(y)) {
y = $.toOADate(y);
}
xsub.push(x - r * (xmax - xmin) / width);
ysub.push(y - r * (ymax - ymin) / height);
xadd.push(x + r * (xmax - xmin) / width);
yadd.push(y + r * (ymax - ymin) / height);
datax.push(x);
datay.push(y);
self.bubbleRadius.push(r);
});
});
xminIndex = self._getMinIndex(xsub);
yminIndex = self._getMinIndex(ysub);
xmaxIndex = self._getMaxIndex(xadd);
ymaxIndex = self._getMaxIndex(yadd);
self.indexs = {
xMin: {
x: datax[xminIndex],
y: datay[xminIndex],
r: self.bubbleRadius[xminIndex]
},
xMax: {
x: datax[xmaxIndex],
y: datay[xmaxIndex],
r: self.bubbleRadius[xmaxIndex]
},
yMin: {
x: datax[yminIndex],
y: datay[yminIndex],
r: self.bubbleRadius[yminIndex]
},
yMax: {
x: datax[ymaxIndex],
y: datay[ymaxIndex],
r: self.bubbleRadius[ymaxIndex]
}
};
};
wijbubblechart.prototype._calculateParameters = function (axisInfo, options) {
_super.prototype._calculateParameters.call(this, axisInfo, options);
var self = this;
if(!options.autoMax && !options.autoMin) {
return;
}
self._adjust(options, axisInfo);
};
wijbubblechart.prototype._adjust = function (options, axisInfo) {
var unitMinor = options.unitMinor, self = this, autoMin = options.autoMin, autoMax = options.autoMax, canvasBounds = self.canvasBounds, startLocation = {
x: canvasBounds.startX,
y: canvasBounds.startY
}, width = canvasBounds.endX - startLocation.x, height = canvasBounds.endY - startLocation.y, omax = axisInfo.max, omin = axisInfo.min, origin = options.origin;
if(!self.indexs) {
self._getbubbleIndexs(width, height);
}
if(axisInfo.id === "x") {
if(autoMin) {
omin = self._getMinTick(self.indexs.xMin.x, self.indexs.xMin.r, omin, omax, width, unitMinor);
}
if(autoMax) {
omax = self._getMaxTick(self.indexs.xMax.x, self.indexs.xMax.r, omin, omax, width, unitMinor);
}
} else {
if(autoMin) {
omin = self._getMinTick(self.indexs.yMin.y, self.indexs.yMin.r, omin, omax, height, unitMinor);
}
if(autoMax) {
omax = self._getMaxTick(self.indexs.yMax.y, self.indexs.yMax.r, omin, omax, height, unitMinor);
}
}
if(omax !== axisInfo.max || omin !== axisInfo.min) {
// Fixed an issue that if the origin is less than the min value and more than the max value,
// the axis will adjust wrong value.
if(origin !== null && origin !== undefined) {
if(origin < omin) {
omin = origin;
} else if(origin > omax) {
omax = origin;
}
}
axisInfo.min = omin;
axisInfo.max = omax;
this._calculateMajorMinor(options, axisInfo);
self._adjust(options, axisInfo);
}
};
wijbubblechart.prototype._getMinTick = function (val, r, min, max, length, unitMinor) {
if((val - min) * length / (max - min) < r) {
return min - unitMinor;
} else {
return min;
}
};
wijbubblechart.prototype._getMaxTick = function (val, r, min, max, length, unitMinor) {
if((val - min) * length / (max - min) + r > length) {
return max + unitMinor;
} else {
return max;
}
};
wijbubblechart.prototype._getMinIndex = function (arr) {
var index = -1, min = 0;
$.each(arr, function (i, n) {
if(i === 0) {
min = n;
} else {
if(n < min) {
min = n;
}
}
});
$.each(arr, function (i, n) {
if(n === min) {
index = i;
return false;
}
});
return index;
};
wijbubblechart.prototype._getMaxIndex = function (arr) {
var index = -1, max = 0;
$.each(arr, function (i, n) {
if(i === 0) {
max = n;
} else {
if(n > max) {
max = n;
}
}
});
$.each(arr, function (i, n) {
if(n === max) {
index = i;
return false;
}
});
return index;
};
wijbubblechart.prototype._showSerieEles = function (seriesEle) {
$.each(seriesEle, function (i, bubbleInfo) {
if(bubbleInfo.bubble) {
bubbleInfo.bubble.show();
if(bubbleInfo.bubble.shadow) {
bubbleInfo.bubble.shadow.show();
}
if(bubbleInfo.bubble.tracker) {
bubbleInfo.bubble.tracker.show();
}
if($(bubbleInfo.bubble.node).data("wijchartDataObj")) {
$(bubbleInfo.bubble.node).data("wijchartDataObj").visible = true;
}
}
if(bubbleInfo.dcl) {
bubbleInfo.dcl.show();
}
if(bubbleInfo.symbol) {
bubbleInfo.symbol.show();
}
});
};
wijbubblechart.prototype._hideSerieEles = function (seriesEle) {
$.each(seriesEle, function (i, bubbleInfo) {
if(bubbleInfo.bubble) {
bubbleInfo.bubble.hide();
if(bubbleInfo.bubble.shadow) {
bubbleInfo.bubble.shadow.hide();
}
if(bubbleInfo.bubble.tracker) {
bubbleInfo.bubble.tracker.hide();
}
if($(bubbleInfo.bubble.node).data("wijchartDataObj")) {
$(bubbleInfo.bubble.node).data("wijchartDataObj").visible = false;
}
}
if(bubbleInfo.dcl) {
bubbleInfo.dcl.hide();
}
if(bubbleInfo.symbol) {
bubbleInfo.symbol.hide();
}
});
};
wijbubblechart.prototype._indicatorLineShowing = function (objs) {
_super.prototype._indicatorLineShowing.call(this, objs);
$.each(objs, function (i, obj) {
if(obj.bubble) {
obj.bubble.attr(obj.hoverStyle);
}
});
};
wijbubblechart.prototype._removeIndicatorStyles = function (objs) {
$.each(objs, function (i, obj) {
if(obj.bubble) {
obj.bubble.attr(obj.style);
}
});
};
wijbubblechart.prototype._parseTable = function () {
if(!this.element.is("table")) {
return;
}
var self = this, ele = self.element, o = self.options, captions = //header & footer
$("caption", ele), theaders = $("thead th", ele), seriesList = [], sList = $("tbody tr", ele), label = null, series = null, xValues = [], yValues = [], y1Values = [], getValue = function (val) {
var ret = $.trim(val);
if(!isNaN(val)) {
ret = parseFloat(val.toString());
}
return ret;
};
if(captions.length) {
o.header = $.extend({
visible: true,
text: $.trim($(captions[0]).text())
}, o.header);
if(captions.length > 1) {
o.footer = $.extend({
visibel: true,
text: $.trim($(captions[1]).text())
}, o.footer);
}
}
//legend
o.legend = $.extend({
visible: true
}, o.legend);
label = $.trim(theaders.eq(1).text());
//seriesList
sList.each(function (i, tr) {
var tds = $("td", tr);
if(tds.length >= 3) {
xValues.push(getValue(tds.eq(0).text()));
yValues.push(getValue(tds.eq(1).text()));
y1Values.push(getValue(tds.eq(2).text()));
}
return this;
});
series = {
label: label,
legendEntry: true,
data: {
x: xValues,
y: yValues,
y1: y1Values
}
};
seriesList.push(series);
self.options.seriesList = seriesList;
};
wijbubblechart.prototype._unbindLiveEvents = function () {
var self = this;
$("." + self.options.wijCSS.bubbleElement, self.chartElement[0]).off(// for jQuery 1.7.1
".wijbubblechart").off("wijbubblechart");
if(self.tooltip) {
self.tooltip.destroy();
self.tooltip = null;
}
};
wijbubblechart.prototype._paintTooltip = function () {
var self = this, fields = self.chartElement.data("fields");
_super.prototype._paintTooltip.call(this);
if(self.tooltip) {
if(fields && fields.trackers && fields.trackers.length) {
self.tooltip.setTargets(fields.trackers);
self.tooltip.setOptions({
relatedElement: fields.trackers[0]
});
}
}
};
wijbubblechart.prototype._getTooltipText = function (fmt, target) {
var tar = $(target.node), dataObj, obj;
//value = dataObj.data,
if(tar.data("owner")) {
tar = tar.data("owner");
}
dataObj = tar.data("wijchartDataObj");
obj = {
data: dataObj,
value: dataObj.value,
label: dataObj.label,
total: dataObj.total,
target: target,
fmt: fmt,
x: dataObj.x,
y: dataObj.y,
y1: dataObj.y1
};
return $.proxy(fmt, obj)();
};
wijbubblechart.prototype._prepBubbleData = function () {
var self = this, seriesList = self.options.seriesList, ymax = -999999999999, ymin = 9999999999999, data;
$.each(seriesList, function (i, n) {
data = n.data;
if(data && data.y1) {
$.each(data.y1, function (j, m) {
ymax = Math.max(ymax, m);
ymin = Math.min(ymin, m);
});
}
});
bubMax = ymax;
bubMin = ymin;
bubDiff = ymax - ymin;
};
wijbubblechart.transform = /**
* @ignore
*/
function transform(yval, maxSize, minSize, bounds, bubMin, bubDiff, sizingMethod, markerType) {
var yscale, val = yval, bubSizeDiff = maxSize - minSize, width = bounds.endX - bounds.startX, height = bounds.endY - bounds.startY;
// adjust the bubble size calculate.
//val -= bubMin;
if(val < 0) {
val = 0;
}
if(bubDiff === 0) {
val = 1;
} else {
val /= bubMax;
}
val = wijbubblechart.transformByArea(val, sizingMethod, markerType);
val *= bubSizeDiff;
val += minSize;
yscale = Math.min(width, height);
val *= yscale / 200.0;
//val = $.wijbubble.transformByArea(val,sizingMethod, markerType)
return val;
//return Math.round(val);
};
wijbubblechart.transformByArea = /**
* @ignore
*/
function transformByArea(yval, sizingMethod, markerType) {
var val = yval;
if(sizingMethod === "area") {
switch(markerType) {
case "circle":
val = Math.sqrt(val / Math.PI);
break;
case "tri":
case "invertedTri":
val = Math.sqrt(val / (3 * Math.sin(Math.PI / 6) * Math.cos(Math.PI / 6)));
break;
case "box":
val = Math.sqrt(val / 2);
break;
case "diamond":
case "cross":
val = Math.sqrt(val / 2);
break;
default:
val = Math.sqrt(4 * val / Math.PI);
break;
}
}
return val;
};
return wijbubblechart;
})(chart.wijchartcore);
chart.wijbubblechart = wijbubblechart;
wijbubblechart.prototype.widgetEventPrefix = "wijbubblechart";
var wijbubblechart_options = (function () {
function wijbubblechart_options() {
/**
* Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijbubblechart')";
/**
* @ignore
*/
this.wijCSS = {
bubbleChart: "wijmo-wijbubblechart",
bubbleElement: "wijbubblechart-bubble",
bubbleTracker: "bubbletracker",
bubbleLabel: "wijbubblechart-label",
bubbleSymbol: "wijbubblechart-symbol"
};
/**
* The minimum bubble size represents the percentage of the diameter (or area) of the plot area.
*/
this.minimumSize = 5;
/**
* The maximum bubble size represents the percentage of the diameter (or area) of the plot area.
*/
this.maximumSize = 20;
/**
* A value that indicates how to calculate the bubble size.
* @remarks
* Valid Values: "area" and "diameter"
* area: Render the bubble's area based on the y1 value.
* diameter: Render the bubble's diameter based on the y1 value.
*/
this.sizingMethod = "diameter";
/**
* The animation option defines the animation effect and controls other aspects of the widget's animation,
* such as duration and easing.
*/
this.animation = {
enabled: /**
* A value that determines whether to show animation. Set this option to false in order to disable animation.
*/
true,
duration: /**
* The duration option defines the length of the animation effect in milliseconds.
*/
1000,
easing: /**
* Sets the type of animation easing effect that users experience when they load the wijbubblechart series.
* @remarks
* The easing is defined in Raphael, the documentation is:http://raphaeljs.com/reference.html#Raphael.easing_formulas
*/
">"
};
/**
* The seriesTransition option is used to animate series in the chart when just their values change. This is
* helpful for visually showing changes in data for the same series.
*/
this.seriesTransition = {
enabled: /**
* A value that determines whether to show animation when reload.
*/
true,
duration: /**
* A value that indicates the duration for the series transition.
*/
400,
easing: /**
* A value that indicates the easing for the series transition.
* @remarks
* The easing is defined in Raphael, the documentation is:http://raphaeljs.com/reference.html#Raphael.easing_formulas
*/
">"
};
/**
* Sets the data for the chart to display.
* @example
* $("#bubblechart").wijbubblechart({
* seriesList: [{
* label: "Q1",
* legendEntry: true,
* data: {
* x: [1, 2, 3, 4, 5],
* y: [12, 21, 9, 29, 30],
* y1:[3, 5, 1, 6, 2]
* }
* }, {
* label: "Q2",
* legendEntry: true,
* data: {
* xy: [1, 21, 2, 10, 3, 19, 4, 31, 5, 20],
* y1:[3, 5, 1, 6, 2]
* }
* }]
* OR
* seriesList: [{
* label: "Q1",
* legendEntry: true,
* data: {
* x: ["A", "B", "C", "D", "E"],
* y: [12, 21, 9, 29, 30],
* y1:[3, 5, 1, 6, 2]
* }
* }]
* OR
* seriesList: [{
* label: "Q1",
* legendEntry: true,
* data: {
* x: [new Date(1978, 0, 1), new Date(1980, 0, 1),
* new Date(1981, 0, 1), new Date(1982, 0, 1),
* new Date(1983, 0, 1)],
* y: [12, 21, 9, 29, 30],
* y1:[3, 5, 1, 6, 2]
* }
* }]
* });
*/
this.seriesList = [];
/**
* An array collection that contains the style applied to the chart elements. For more information on the available
* style parameters.
* @example
* $("#bubblechart").wijbubblechart("option", "seriesHoverStyles", {
* seriesHoverStyles: [
* {fill: "rgb(255,0,0)", stroke:"none"},
* { fill: "rgb(255,125,0)", stroke: "none" }
* ]});
*/
this.seriesHoverStyles = [
{
opacity: 1,
"stroke-width": 5
},
{
opacity: 1,
"stroke-width": 5
},
{
opacity: 1,
"stroke-width": 5
},
{
opacity: 1,
"stroke-width": 5
},
{
opacity: 1,
"stroke-width": 5
},
{
opacity: 1,
"stroke-width": 5
},
{
opacity: 1,
"stroke-width": 5
},
{
opacity: 1,
"stroke-width": 5
},
{
opacity: 1,
"stroke-width": 5
},
{
opacity: 1,
"stroke-width": 5
},
{
opacity: 1,
"stroke-width": 5
},
{
opacity: 1,
"stroke-width": 5
}
];
/**
* Creates a chartLabel object that defines all of the settings used to draw a label for each bubble in the chart.
* @example
* // This code creates a chart with a label outside (and to the south) of each bubble with the numbers formatted
* // as percentages with no decimal spaces, in purple size 14 font
* $(document).ready(function () {
* $("#wijbubblechart").wijbubblechart({
* axis: {
* y: { text: "Number of Products" },
* x: { text: "Sales", annoFormatString: "C0" }
* },
* chartLabel: {
* chartLabelFormatString: "P0",
* compass: "south",
* position: "outside",
* style: { fill: "purple", "font-size": 14 }
* },
* legend: { visible: false },
* seriesList: [
* {
* label: "Company A Market Share",
* data: { y: [14], x: [12200], y1: [.15] }
* }, {
* label: "Company B Market Share",
* data: { y: [20], x: [60000], y1: [.23] }
* }, {
* label: "Company C Market Share",
* data: { y: [18], x: [24400], y1: [.1] }
* }]
* });
*});
*/
this.chartLabel = {
position: /**
* A value that indicates whether to draw a label inside our outside of each bubble in the chart.
* @remarks
* If set to "outside," the compass attribute sets where to draw the label.
* The value should be "inside" or "outside".
*/
"inside",
compass: /**
* A value that indicates the compass position at which to draw a chart label next to each bubble
* when you set the position option for the label to "outside." If the position is set to "inside,"
* this attribute is ignored.
* @remarks
* The value should be "north", "east", "west" or "south"
*/
"north",
visible: /**
* The visible option indicates whether to draw a label on each bubble in the chart.
*/
true,
style: /**
* A value that indicates the style parameters to apply to the labels on each bubble in the chart.
* @remarks
* Note: If you do not set any value for this style, the fallback style is chartLabelStyle.
* The style is defined in Raphael here is the documentation: http://raphaeljs.com/reference.html#Element.attr.
* The style is the “attr” method’s parameters.
*/
{
},
chartLabelFormatString: /**
* Sets the numeric format of the chart labels that show the value of each bubble.
* @remarks
* You can use Standard Numeric Format Strings. You can also change the style of these labels using
* chartLabelStyle, or to hide them
*/
""
};
/**
* Fires when the user clicks a mouse button.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IBubbleChartEventArgs} data Information about an event
*/
this.mouseDown = null;
/**
* Fires when the user releases a mouse button while the pointer is over the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IBubbleChartEventArgs} data Information about an event
*/
this.mouseUp = null;
/**
* Fires when the user first places the pointer over the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IBubbleChartEventArgs} data Information about an event
*/
this.mouseOver = null;
/**
* Fires when the user moves the pointer off of the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IBubbleChartEventArgs} data Information about an event
*/
this.mouseOut = null;
/**
* Fires when the user moves the mouse pointer while it is over a chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IBubbleChartEventArgs} data Information about an event
*/
this.mouseMove = null;
/**
* Fires when the user clicks the chart element.
* @param {jQuery.Event} e Standard jQuery event object
* @param {IBubbleChartEventArgs} data Information about an event
*/
this.click = null;
}
return wijbubblechart_options;
})();
wijbubblechart.prototype.options = $.extend(true, {
}, chart.wijchartcore.prototype.options, new wijbubblechart_options());
//$.widget("wijmo.wijbubblechart", WijBubbleChart.prototype);
$.wijmo.registerWidget("wijbubblechart", wijbubblechart.prototype);
/**
* @ignore
*/
var BubbleChartRender = (function () {
function BubbleChartRender(element, options) {
this.element = element;
this.options = options;
this._init();
}
BubbleChartRender.prototype._init = function () {
var o = this.options, bounds = o.bounds;
this.fields = this.element.data("fields") || {
};
this.canvas = o.canvas;
this.seriesList = $.arrayClone(o.seriesList);
this.seriesStyles = o.seriesStyles;
this.seriesHoverStyles = o.seriesHoverStyles;
this.startLocation = {
x: bounds.startX,
y: bounds.startY
};
this.width = bounds.endX - this.startLocation.x;
this.height = bounds.endY - this.startLocation.y;
this.seriesEles = [];
this.bubbles = [];
this.bubbleInfos = [];
this.trackers = this.canvas.set();
this.currentIndex = 0;
};
BubbleChartRender.prototype.initAnimationState = function (bubbleInfo, bounds) {
var bubble = bubbleInfo.bubble, symbol = bubbleInfo.symbol, bbox;
if(bubble.type === "circle") {
bubble.attr({
r: 0.0001,
cx: bounds.startX,
cy: bounds.endY
});
} else {
bbox = bubble.wijGetBBox();
//when play animation, it will added the transform to move and scale the bubble element to start point and small size.
// the exists transform string should put behind of the animation transform.
bubble.transform("t" + (bounds.startX - bbox.x) + "," + (bounds.endY - bbox.y) + "s0.001...");
if(bubble.shadow) {
bubble.shadow.transform("t" + (bounds.startX - bbox.x) + "," + (bounds.endY - bbox.y) + "s0.001...");
}
}
if(symbol) {
symbol.hide();
}
};
BubbleChartRender.prototype.playAnimation = function () {
var self = this, o = self.options, animation = o.animation, bounds = o.bounds, bubblesAnimationInfos = self.fields.bubblesAnimationInfos, animationInfos = [], bubbleInfos = self.fields.bubbleInfos, seriesTransition = o.seriesTransition, duration, easing, rate;
if(animation && animation.enabled) {
duration = animation.duration || 400;
easing = animation.easing;
$.each(bubbleInfos, function (idx, bubbleInfo) {
var bubble = bubbleInfo.bubble, params, bubblesAnimationInfo, bbox = bubble.wijGetBBox();
if(bubble.type === "circle") {
params = {
r: bubble.attr("r"),
cx: bubble.attr("cx"),
cy: bubble.attr("cy")
};
} else {
params = {
transform: //directly use the transform srtring before playing animation.
bubble.matrix.toTransformString(),
"stroke-width": bubble.attr("stroke-width"),
width: bbox.width,
x: bbox.x,
y: bbox.y
};
}
if(bubble.shadow) {
bubble.shadow.hide();
}
if(bubblesAnimationInfos && seriesTransition.enabled) {
bubblesAnimationInfo = bubblesAnimationInfos[idx];
if(bubblesAnimationInfo) {
if(bubble.type === "circle") {
bubble.attr({
cx: bubblesAnimationInfo.cx,
cy: bubblesAnimationInfo.cy,
r: bubblesAnimationInfo.r
});
} else {
bbox = bubble.wijGetBBox();
rate = bubblesAnimationInfo.width / bbox.width;
//directly use the transform before playing animatin.
params.transform = bubble.matrix.toTransformString();
bubble.transform(Raphael.format("s{0}t{1}{2}...", rate, bubblesAnimationInfo.x - bbox.x, bubblesAnimationInfo.y - bbox.y));
if(bubble.shadow) {
bubble.shadow.transform(Raphael.format("s{0}t{1}{2}...", rate, bubblesAnimationInfo.x - bbox.x, bubblesAnimationInfo.y - bbox.y));
}
}
duration = seriesTransition.duration;
easing = seriesTransition.easing;
} else {
self.initAnimationState(bubbleInfo, bounds);
}
} else {
self.initAnimationState(bubbleInfo, bounds);
}
animationInfos.push(params);
bubble.wijAnimate(params, duration, easing, function () {
if($(bubbleInfo.bubble.node).data("wijchartDataObj") && $(bubbleInfo.bubble.node).data("wijchartDataObj").visible) {
if(bubbleInfo.dcl) {
bubbleInfo.dcl.show();
}
if(bubbleInfo.symbol) {
bubbleInfo.symbol.show();
}
if(bubble.shadow) {
bubble.shadow.show();
}
}
});
});
self.fields.bubblesAnimationInfos = animationInfos;
} else {
$.each(bubbleInfos, function (idx, bubbleInfo) {
if($(bubbleInfo.bubble.node).data("wijchartDataObj") && $(bubbleInfo.bubble.node).data("wijchartDataObj").visible) {
if(bubbleInfo.dcl) {
bubbleInfo.dcl.show();
}
if(bubbleInfo.symbol) {
bubbleInfo.symbol.show();
}
}
});
}
};
BubbleChartRender.prototype.getSymbol = function (symbols, index) {
var symbol;
$.each(symbols, function (i, n) {
if(i === index) {
symbol = n;
return false;
}
});
return symbol;
};
BubbleChartRender.prototype.getLabelVisible = function (visibles, index) {
var visible = true;
$.each(visibles, function (i, n) {
if(index === n) {
visible = false;
return false;
}
});
return visible;
};
BubbleChartRender.prototype.paintMarker = function (type, x, y, length) {
var marker;
if(this.canvas[type]) {
marker = this.canvas[type](x, y, length);
}
return marker;
};
BubbleChartRender.prototype.getLabelBox = function (val) {
var text = this.canvas.text(0, 0, val), bbox = text.wijGetBBox(), ret;
ret = {
width: bbox.width,
height: bbox.height
};
text.remove();
return ret;
};
BubbleChartRender.prototype.applyLabelCompass = function (rf, text) {
var compass = this.options.chartLabel.compass || "north", labelBox = this.getLabelBox(text), r = rf.r;
switch(compass) {
case "north":
rf.y -= (r + labelBox.height / 2);
break;
case "south":
rf.y += (r + labelBox.height / 2);
break;
case "east":
rf.x += (r + labelBox.width / 2);
break;
case "west":
rf.x -= (r + labelBox.width / 2);
break;
}
};
BubbleChartRender.prototype.paintDefaultChartLabel = function (rf, val) {
var o = this.options, chartLabel = o.chartLabel, culture = o.culture, textStyle = $.extend(true, {
}, o.textStyle, o.chartLabelStyle, chartLabel.style), text = $.round(val, 2), chartLabelFormatString = chartLabel.chartLabelFormatString === "" ? o.chartLabelFormatString : chartLabel.chartLabelFormatString, widget = this.options.widget, dcl;
if(chartLabelFormatString && chartLabelFormatString.length) {
text = Globalize.format(text, chartLabelFormatString, culture);
}
dcl = widget._text.call(widget, rf.x, rf.y, text).attr(textStyle);
return dcl;
};
BubbleChartRender.prototype.paintbubble = function (series, seriesStyle, seriesHoverStyle, xAxisInfo, yAxisInfo, width, height, startLocation) {
var data = series.data, minX = xAxisInfo.min, minY = yAxisInfo.min, maxX = xAxisInfo.max, maxY = yAxisInfo.max, kx = width / (maxX - minX), ky = height / (maxY - minY), serieEles = [], o = this.options, self = this, bounds = o.bounds, wijCSS = o.wijCSS, widget = o.widget, chartLabel = o.chartLabel, bubbleRadius = o.bubbleRadius, dcl, imgWidth, imgHeight, pointX;
if(data.y1 === undefined) {
return;
}
$.each(data.y1, function (i, y1) {
if(data.x === undefined || data.y === undefined) {
return true;
}
var x = data.x[i], y = data.y[i], markers = series.markers || {
}, markerType = markers.type || "circle", symbols = markers.symbol, invisibleMarkLabels = series.invisibleMarkLabels || [], rf, bubbleInfo, wijchartDataObj, bubble, sX, sY, symbol, symbolEl, r, tracker;
if(bubbleRadius) {
r = bubbleRadius[self.currentIndex];
self.currentIndex++;
} else {
r = wijbubblechart.transform(y1, o.maximumSize, o.minimumSize, o.bounds, bubMin, bubDiff, o.sizingMethod, markerType);
}
if(xAxisInfo.isTime) {
x = $.toOADate(x);
} else if(isNaN(x)) {
x = i;
}
if(yAxisInfo.isTime) {
y = $.toOADate(y);
}
sX = bounds.startX + (x - minX) * kx;
sY = bounds.startY + (maxY - y) * ky;
if(symbols) {
symbol = self.getSymbol(symbols, i);
}
bubble = self.paintMarker(markerType, sX, sY, r);
bubble.attr(seriesStyle);
if(symbol) {
imgWidth = symbol.width || (r * 2);
imgHeight = symbol.height || (r * 2);
symbolEl = self.canvas.image(symbol.url, sX - r, sY - r, imgWidth, imgHeight);
}
if(self.options.shadow) {
chart.ChartUtil.paintShadow(bubble, 2, null);
}
$.wijraphael.addClass($(bubble.node), wijCSS.canvasObject + " " + wijCSS.bubbleElement);
if(symbol) {
bubble.attr("opacity", 0.1);
}
wijchartDataObj = $.extend(false, {
index: i,
bubble: bubble,
style: seriesStyle,
y1: y1,
x: x,
y: y,
type: "bubble",
hoverStyle: seriesHoverStyle,
visible: true
}, series);
if(symbol) {
wijchartDataObj.symbol = true;
wijchartDataObj.hoverStyle = $.extend({
}, seriesHoverStyle, {
opacity: 0.1
});
$(symbolEl.node).data("wijchartDataObj", wijchartDataObj);
$.wijraphael.addClass($(symbolEl.node), wijCSS.bubbleSymbol);
}
$(bubble.node).data("wijchartDataObj", wijchartDataObj);
// cache the bar position to show indicator line.
widget.dataPoints = widget.dataPoints || {
};
widget.pointXs = widget.pointXs || [];
pointX = $.round(sX, 2);
if(!widget.dataPoints[pointX.toString()]) {
widget.dataPoints[pointX.toString()] = [];
widget.pointXs.push(pointX);
}
widget.dataPoints[pointX.toString()].push(wijchartDataObj);
tracker = bubble.clone();
//.attr({ opacity: 0.01, fill: "white", "fill-opacity": 0.01 });
// in vml, if the tracker has a stroke, the boder is black.
if($.browser.msie && parseInt($.browser.version) < 9) {
tracker.attr({
opacity: 0.01,
fill: "white",
"stroke-width": 0,
"fill-opacity": 0.01
});
} else {
tracker.attr({
opacity: 0.01,
fill: "white",
"fill-opacity": 0.01
});
}
$(tracker.node).data("owner", $(bubble.node));
$.wijraphael.addClass($(tracker.node), wijCSS.canvasObject + " " + wijCSS.bubbleElement + " " + wijCSS.bubbleTracker);
bubble.tracker = tracker;
self.trackers.push(tracker);
self.bubbles.push(bubble);
self.fields.bubbles = self.bubbles;
rf = {
x: sX,
y: sY,
r: r
};
if(chartLabel.visible && self.getLabelVisible(invisibleMarkLabels, i)) {
if(chartLabel.position === "outside") {
self.applyLabelCompass(rf, y1);
}
dcl = self.paintDefaultChartLabel(rf, y1);
dcl.hide();
$(dcl.node).data("wijchartDataObj", wijchartDataObj);
$.wijraphael.addClass($(dcl.node), wijCSS.bubbleLabel);
}
bubbleInfo = {
bubble: bubble,
dcl: dcl,
symbol: symbolEl
};
self.bubbleInfos.push(bubbleInfo);
serieEles.push(bubbleInfo);
if(series.visible === false) {
bubble.hide();
if(dcl) {
dcl.hide();
}
tracker.hide();
if(symbolEl) {
symbolEl.hide();
}
}
});
self.fields.bubbleInfos = self.bubbleInfos;
self.seriesEles.push(serieEles);
};
BubbleChartRender.prototype.paintBubbles = function () {
var self = this, o = self.options, xAxisInfo = o.xAxisInfo, yAxisInfo = o.yAxisInfo;
$.each(self.seriesList, function (i, series) {
var seriesStyle = self.seriesStyles[i], seriesHoverStyle = self.seriesHoverStyles[i];
self.paintbubble(series, seriesStyle, seriesHoverStyle, xAxisInfo, yAxisInfo, self.width, self.height, self.startLocation);
});
};
BubbleChartRender.prototype.bindLiveEvents = function (element, mouseDown, mouseUp, mouseOver, mouseOut, mouseMove, click, disabled) {
var o = this.options, wijCSS = o.wijCSS, proxyObj = {
mousedown: function (e) {
if(disabled) {
return;
}
var target = $(e.target), dataObj;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
mouseDown.call(element, e, dataObj);
},
mouseup: function (e) {
if(disabled) {
return;
}
var target = $(e.target), dataObj;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
mouseUp.call(element, e, dataObj);
},
mouseover: function (e) {
if(disabled) {
return;
}
var target = $(e.target), dataObj, bubble;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
bubble = dataObj.bubble;
if(!dataObj.hoverStyle) {
if(bubble) {
bubble.attr({
opacity: "0.8"
});
}
} else {
bubble.attr(dataObj.hoverStyle);
if(bubble.shadow) {
bubble.shadow.attr(dataObj.hoverStyle);
}
}
mouseOver.call(element, e, dataObj);
},
mouseout: function (e) {
if(disabled) {
return;
}
var target = $(e.target), dataObj, bubble;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
bubble = dataObj.bubble;
if(dataObj.symbol) {
return;
}
if(!dataObj.hoverStyle) {
if(bubble) {
bubble.attr({
opacity: "1"
});
}
} else {
if(dataObj.hoverStyle["stroke-width"] && !dataObj.style["stroke-width"]) {
bubble.attr("stroke-width", "");
if(bubble.shadow) {
bubble.shadow.attr("stroke-width", "");
}
}
bubble.wijAttr({
transform: ""
});
bubble.wijAttr(dataObj.style);
if(dataObj.style.opacity) {
bubble.attr("opacity", dataObj.style.opacity);
if(bubble.shadow) {
bubble.shadow.attr("opacity", dataObj.style.opacity);
}
}
}
mouseOut.call(element, e, dataObj);
},
mousemove: function (e) {
if(disabled) {
return;
}
var target = $(e.target), dataObj, bubble;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
mouseMove.call(element, e, dataObj);
},
click: function (e) {
if(disabled) {
return;
}
var target = $(e.target), dataObj;
if(target.data("owner")) {
target = target.data("owner");
}
dataObj = target.data("wijchartDataObj");
click.call(element, e, dataObj);
}
};
$.each([
"click",
"mouseover",
"mouseout",
"mousemove",
"mousedown",
"mouseup"
], function (i, n) {
$("." + wijCSS.bubbleTracker, element).on(n + ".wijbubblechart", proxyObj[n]);
});
};
BubbleChartRender.prototype.render = function () {
var o = this.options, mouseDown = o.mouseDown, mouseUp = o.mouseUp, mouseOver = o.mouseOver, mouseOut = o.mouseOut, mouseMove = o.mouseMove, click = o.click, disabled = o.disabled;
this.paintBubbles();
this.fields.seriesEles = this.seriesEles;
this.playAnimation();
this.trackers.toFront();
this.fields.trackers = this.trackers;
this.bindLiveEvents(this.element, mouseDown, mouseUp, mouseOver, mouseOut, mouseMove, click, disabled);
this.element.data("fields", this.fields);
};
return BubbleChartRender;
})();
chart.BubbleChartRender = BubbleChartRender;
})(wijmo.chart || (wijmo.chart = {}));
var chart = wijmo.chart;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/// <reference path="../wijpager/jquery.wijmo.wijpager.ts" />
/// <reference path="../wijslider/jquery.wijmo.wijslider.ts" />
/*globals jQuery, window, XMLHttpRequest*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
(function (carousel) {
"use strict";
var $ = jQuery, widgetName = "wijcarousel", cssPrefix = "wijmo-wijcarousel-", baseCss = "wijmo-wijcarousel ", listCss = cssPrefix + "list", itemCss = cssPrefix + "item ", clipCss = cssPrefix + "clip", currentCss = cssPrefix + "current", horizontalMultiCss = cssPrefix + "horizontal-multi", horizontalCss = cssPrefix + "horizontal", btnCss = cssPrefix + "button", verticalMultiCss = cssPrefix + "vertical-multi", verticalCss = cssPrefix + "vertical", nextBtnCss = cssPrefix + "button-next", prevBtnCss = cssPrefix + "button-previous", previewCss = cssPrefix + "preview", btnHtml = "<a><span></span></a>", ctrlSelector = ".wijmo-wijcarousel-pager,." + btnCss + ",." + nextBtnCss + ",." + prevBtnCss, captionHtml = "<div></div>", pagerHtml = "<li class=\"wijmo-wijcarousel-page\"><a></a></li>", liSel = "li.wijmo-wijcarousel-page", captionSel = ".wijmo-wijcarousel-text,.wijmo-wijcarousel-caption", previewNum = 1;
/** @widget */
var wijcarousel = (function (_super) {
__extends(wijcarousel, _super);
function wijcarousel() {
_super.apply(this, arguments);
}
wijcarousel.prototype._handleDisabledOption = function (disabled, ele) {
var self = this, o = self.options;
if(self.pager && !self.pager.is(":hidden")) {
self.disabledEles = self.disabledEles.add(self.pager);
}
if(disabled) {
self.element.addClass(o.wijCSS.stateDisabled);
if(!self.disabledDiv.length) {
self._createDisabledDiv();
}
self.disabledDiv.appendTo("body");
} else if(self.disabledDiv) {
self.element.removeClass(o.wijCSS.stateDisabled);
self.disabledDiv.remove();
self.disabledDiv = $();
}
};
wijcarousel.prototype._createDisabledDiv = function () {
var self = this, o = self.options;
self.disabledEles.each(function (idx, data) {
var ele = $(data), eleOffset = ele.offset(), disabledWidth = ele.outerWidth(), disabledHeight = ele.outerHeight(), div = $("<div></div>").addClass(o.wijCSS.stateDisabled).css({
"z-index": "99999",
position: "absolute",
width: disabledWidth,
height: disabledHeight,
left: eleOffset.left,
top: eleOffset.top
});
if($.browser.msie) {
div.css("background-color", "white");
if($.browser.version === "9.0") {
div.css("opacity", "0.1");
}
}
self.disabledDiv = self.disabledDiv.add(div);
});
};
wijcarousel.prototype._initStates = function (o, el) {
var self = this;
self.count = 0;
self.currentIdx = o.start;
self.timeout = null;
self.isHorizontal = o.orientation === "horizontal";
self.width = el.width() || 640;
self.height = el.height() || 480;
self.offset = 0;
self.disabledEles = el;
self.disabledDiv = $();
};
wijcarousel.prototype._create = function () {
var self = this, o = self.options, el = self.element;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
self._initStates(o, el);
self._createDom(self.isHorizontal);
self.list.bind("click." + self.widgetName, $.proxy(self._itemClick, self));
if(o.showControlsOnHover) {
self.container.bind("mouseenter." + self.widgetName, function () {
self._showControls();
}).bind("mouseleave." + self.widgetName, function () {
self._hideControls();
});
self.container.find(ctrlSelector).hide();
}
if(o.loadCallback && $.isFunction(o.loadCallback)) {
self._trigger("loadCallback", null, self);
}
if(o.disabledState) {
var dis = o.disabled;
self.disable();
o.disabled = dis;
} else if(o.auto) {
self.play();
}
//update for visibility change
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
self.refresh();
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
}, "wijcarousel");
}
};
wijcarousel.prototype._showControls = function () {
this.container.find(ctrlSelector).stop(true, true).fadeIn(600, function () {
$(this).css("opacity", "");
});
};
wijcarousel.prototype._hideControls = function () {
this.container.find(ctrlSelector).stop(true, true).fadeOut(600);
};
wijcarousel.prototype._applyContainerStyle = function (isHorizontal, isPreviewCreated) {
/// <summary>
/// Apply special styles. after create dom element.
/// </summary>
var self = this, o = self.options, style = {
}, list = self.list, listSize = 0, size, left = 0, dir = isHorizontal ? "left" : "top", i = 0, citem, sizeKey = isHorizontal ? "width" : "height";
size = self.itemBound[isHorizontal ? "w" : "h"];
self.count = self.list.children("li").length;
listSize = self.count * size;
self.list[sizeKey](listSize);
self.clip[sizeKey](o.display * size);
//self.container[sizeKey](o.display * size);
self.clip[isHorizontal ? "height" : "width"](self.itemBound[isHorizontal ? "h" : "w"]);
if(!o.loop) {
style[dir] = -size * self.currentIdx;
list.css(style);
} else {
citem = list.find(">li:first");
// if preview mode the cuurent item is the second item of ul
if(o.preview && !!isPreviewCreated) {
citem = citem.next()//previewNum
;
}
i = citem.data("itemIndex");
for(i; i < self.currentIdx; i++) {
list.children("li:first").appendTo(list);
}
if(o.preview) {
if(!isPreviewCreated) {
for(i = 0; i < previewNum; i++) {
list.children("li:last").prependTo(list);
}
}
left = -size * previewNum;
}
style[dir] = left;
list.css(style);
}
};
wijcarousel.prototype._applyListStyle = function () {
var self = this, o = self.options, isHorizontal = o.orientation === "horizontal", listSize = 0, size, sizeKey = isHorizontal ? "width" : "height";
self.itemBound = self._getItemBound();
size = self.itemBound[isHorizontal ? "w" : "h"];
listSize = self.count * size;
self.list[sizeKey](listSize);
};
wijcarousel.prototype._createButtons = function (prevIconCss, nextIconCss) {
var self = this, o = self.options, hover, disableClass = o.wijCSS.stateDisabled;
$.each([
"prevBtn",
"nextBtn"
], function (i, n) {
var css = o[n + "Class"], is = n === "nextBtn", func = is ? "next" : "previous", btnCss = is ? nextBtnCss : prevBtnCss, iconCss = is ? nextIconCss : prevIconCss;
if(css && css.defaultClass) {
disableClass = css.disableClass || disableClass;
hover = css.hoverClass//|| hover;
;
self[n] = $("<a class=\"" + o.wijCSS.stateDefault + "\"></a>").addClass(css.defaultClass).mouseover(function () {
if(!$(this).hasClass(disableClass)) {
$(this).addClass(hover);
}
}).mouseout(function () {
if(!$(this).hasClass(disableClass)) {
$(this).removeClass(hover);
}
});
} else {
self[n] = $(self._createBtn(btnCss, iconCss));
}
//self[n].bind("click." + self.widgetName, $.proxy(self[func], self))
self[n].bind("click." + self.widgetName, function (event) {
var btn = $(this);
if(btn.hasClass(o.wijCSS.stateDisabled)) {
return;
}
self[func].call(self);
}).appendTo(self.container);
});
};
wijcarousel.prototype._applyBtnClass = function () {
var self = this, o = self.options, disable = o.wijCSS.stateDisabled, hover = o.wijCSS.stateHover;
$.each([
"prevBtn",
"nextBtn"
], function (i, n) {
var css = o[n + "Class"], con, btn = self[n];
if(css) {
disable = css.disableClass || disable;
hover = css.hoverClass || hover;
}
con = n === "prevBtn" ? (self.currentIdx <= 0) : ((self.currentIdx + o.display) >= self.count);
if(con && !o.loop) {
btn.removeClass(hover).addClass(disable);
} else if(btn.hasClass(disable)) {
btn.removeClass(disable);
}
});
};
wijcarousel.prototype._applyBtnStyle = function (isHorizontal) {
var self = this, buttonSize = 0, buttonOffset, css = self.options.wijCSS, nextPosition = {
collision: "none",
of: self.container,
my: isHorizontal ? "right{offset} center" : "center bottom{offset}",
at: isHorizontal ? "right center" : "center bottom"
}, prevPosition = {
collision: "none",
of: self.container,
my: isHorizontal ? "left{offset} center" : "center top{offset}",
at: isHorizontal ? "left center" : "center top"
}, inside = self.options.buttonPosition === "inside", nextCorner, prevCorner, dirs = [
"cornerBottom",
"cornerTop",
"cornerRight",
"cornerLeft"
], ndir = (isHorizontal ? 1 : 0) * 2 + (inside ? 1 : 0), pdir = (isHorizontal ? 1 : 0) * 2 + (!inside ? 1 : 0), appltStyle = function (btn, c1, c2, offset, position) {
var off = "";
btn.removeClass(c1).addClass(c2);
if(!isNaN(offset) && offset !== 0) {
if(offset > 0) {
off = "+" + offset;
} else {
off = "-" + (-offset);
}
}
position.my = position.my.replace(/\{offset\}/, off);
btn.position(position);
};
buttonSize = isHorizontal ? self.prevBtn.width() : self.prevBtn.height();
buttonOffset = inside ? 0 : buttonSize;
nextCorner = css[dirs[ndir]];
prevCorner = css[dirs[pdir]];
appltStyle(self.nextBtn, prevCorner, nextCorner, buttonOffset, nextPosition);
appltStyle(self.prevBtn, nextCorner, prevCorner, -buttonOffset, prevPosition);
self._applyBtnClass();
};
wijcarousel.prototype._createDom = function (isHorizontal) {
/// <summary>
/// Create base dom , apply styles , bind event
/// </summary>
var self = this, o = self.options, el = self.element, containerCss, nextIconCss, prevIconCss, allCss;
if(el.is("div")) {
self.list = el.children("ul:eq(0)");
self.container = self.element;
if(!self.list.length) {
self.list = $("<ul></ul>").appendTo(self.container);
}
} else if(el.is("ul")) {
self.list = el;
self.container = el.parent();
} else {
return;
}
self.itemBound = self._getItemBound();
if(isHorizontal) {
containerCss = (o.display > 1 && !o.preview) ? horizontalMultiCss : horizontalCss;
nextIconCss = o.wijCSS.iconArrowRight;
prevIconCss = o.wijCSS.iconArrowLeft;
} else {
containerCss = (o.display > 1 && !o.preview) ? verticalMultiCss : verticalCss;
nextIconCss = o.wijCSS.iconArrowDown;
prevIconCss = o.wijCSS.iconArrowUp;
}
self.list.addClass(listCss).addClass(o.wijCSS.helperClearFix);
allCss = baseCss + o.wijCSS.widget + " " + containerCss + " " + (o.preview ? (previewCss + " ") : "") + (o.display > 1 ? o.wijCSS.content + " " + o.wijCSS.cornerAll : "");
self.container.addClass(allCss);
self._createItems(isHorizontal);
self._createClip(isHorizontal);
self._applyContainerStyle(isHorizontal);
self._createButtons(prevIconCss, nextIconCss);
self._applyBtnStyle(isHorizontal);
if(o.preview) {
self._createPreview();
}
if(o.showTimer) {
self._createTimer();
}
if(o.showPager) {
self._createPager();
}
if(o.showControls) {
self._createControls();
}
};
wijcarousel.prototype._createPreview = // add new feature
function () {
var self = this, o = self.options, offset, size, isH = o.orientation === "horizontal", dir = isH ? "left" : "top", antiDir = isH ? "right" : "bottom", bound, idx;
size = self.itemBound[isH ? "w" : "h"];
offset = self.offset = Math.round(size / 4);
bound = o.display * size + offset * 2;
self.clip[isH ? "width" : "height"](bound);
self.list.css(dir, function (i, v) {
return parseFloat(v) + offset;
});
self.clip.css(dir, function (i, v) {
return -offset;
});
self.container.css("margin-" + dir, offset + "px").css("margin-" + antiDir, offset + "px");
self.list.find(captionSel).hide();
for(idx = 0; idx < o.display; idx++) {
self._getItemByIndex(self.currentIdx + idx).find(captionSel).show();
}
};
wijcarousel.prototype._createItemsFromData = function (data) {
var self = this;
if(!$.isArray(data) || !data.length || !$.isPlainObject(data[0]) || $.isEmptyObject(data[0])) {
return;
}
self.list.empty();
$.each(data, function (idx, item) {
var li;
if(!$.isPlainObject(item)) {
return true;
}
li = self._generateMarkup(item);
self.list.append(li);
});
};
wijcarousel.prototype._generateMarkup = function (item) {
//item is js object
var li, a;
if(!$.isPlainObject(item)) {
return;
}
li = $("<li></li>");
if(typeof item.linkUrl === "string" && item.linkUrl) {
a = $("<a>").attr("href", item.linkUrl);
a.appendTo(li);
}
if(typeof item.imageUrl === "string" && item.imageUrl) {
$("<img>").attr("src", item.imageUrl).appendTo(a || li);
}
if(typeof item.caption === "string" && item.caption) {
$("<span>").html(item.caption).appendTo(li);
}
return li;
};
wijcarousel.prototype._createItems = function (isHorizontal) {
var self = this, displays, i, o = self.options, currentItem, item;
if(self.list) {
self._createItemsFromData(o.data);
self.list.children("li").each(function (idx, data) {
var item = $(data);
self._createItem(item, idx);
});
currentItem = self.list.children("li").eq(self.currentIdx).addClass(currentCss);
if(o.preview && o.display > 1) {
displays = item = currentItem;
for(i = 0; i < o.display - 1; i++) {
item = item.next();
displays = displays.add(item);
}
displays.find("div.wijmo-wijcarousel-mask").css({
opacity: 0
});
}
}
};
wijcarousel.prototype._createItem = function (item, idx) {
var self = this, o = self.options, img, span;
img = item.addClass(itemCss).addClass(o.wijCSS.helperClearFix).find("img:eq(0)").attr("role", "img").addClass("wijmo-wijcarousel-image");
self._applyItemBound(item);
span = item.children("span:eq(0)").hide();
self._createCaption(item, img, span);
if(o.preview) {
$("<div class=\"wijmo-wijcarousel-mask\">").appendTo(item);
}
item.data("itemIndex", idx);
return item;
};
wijcarousel.prototype._applyItemBound = function (item) {
var self = this, w = self.itemBound.w, h = self.itemBound.h;
if(!self.itemWidth || !self.itemHeight) {
item.width(w).height(h);
self.itemWidth = w - (item.outerWidth(true) - w);
self.itemHeight = h - (item.outerHeight(true) - h);
}
item.width(self.itemWidth).height(self.itemHeight);
};
wijcarousel.prototype._createCaption = function (item, img, span) {
var self = this, o = self.options, caption, text, content, overlay, height;
if(o.showCaption) {
caption = span.html() || img.attr("title");
if(caption && caption.length) {
content = $("<span></span>").html(caption);
overlay = $(captionHtml).addClass([
o.wijCSS.helperClearFix,
"wijmo-wijcarousel-caption"
].join(' ')).appendTo(item);
text = $(captionHtml).addClass([
o.wijCSS.helperClearFix,
o.wijCSS.content,
"wijmo-wijcarousel-text"
].join(' ')).append(content).appendTo(item);
self._applyCaptionStyle(overlay, text);
}
}
};
wijcarousel.prototype._applyCaptionStyle = function (overlay, text) {
var caption = overlay.add(text), height;
caption.width(this.itemWidth);
if($.browser.webkit) {
height = text.children("span").css("display", "inline-block").height();
text.children("span").css("display", "");
} else {
height = text.children("span").height();
}
caption.height(height);
};
wijcarousel.prototype._showCaption = function (idx, lastIndex) {
var self = this, item = self._getItemByIndex(idx), text = item.find(".wijmo-wijcarousel-text"), caption = item.find(".wijmo-wijcarousel-caption");
if(text.length) {
text.fadeIn(300, function () {
if(idx < lastIndex) {
self._showCaption(idx + 1, lastIndex);
}
});
}
if(caption.length) {
caption.show();
caption.animate({
opacity: 0.5
}, 300);
}
};
wijcarousel.prototype._hideCaption = function () {
this.element.find(captionSel).hide();
};
wijcarousel.prototype._createClip = function (isHorizontal) {
this.clip = this.list.wrap("<div></div>").parent().addClass(clipCss);
};
wijcarousel.prototype._createBtn = function (btnClass, itemClass) {
var btn = $(btnHtml), o = this.options;
btn.addClass(o.wijCSS.stateDefault + ' ' + btnClass).attr("role", "button").mouseover(function () {
if(!$(this).hasClass(o.wijCSS.stateDisabled)) {
$(this).addClass(o.wijCSS.stateHover);
}
}).mouseout(function () {
if(!$(this).hasClass(o.wijCSS.stateDisabled)) {
$(this).removeClass(o.wijCSS.stateHover);
}
}).children("span:eq(0)").addClass(o.wijCSS.icon + ' ' + itemClass);
return btn;
};
wijcarousel.prototype._createControls = function () {
var self = this, o = self.options, position = {
collision: "none",
of: self.container,
my: "center bottom",
at: "center bottom"
};
if(o.control) {
self.controls = $(o.control).css({
position: "absolute"
}).appendTo(self.container);
$.extend(position, o.controlPosition);
self.controls.position(position);
}
};
wijcarousel.prototype._createTimer = function () {
var self = this, o = self.options;
self._createPausePlay();
self.progressBar = $("<div></div>").addClass("wijmo-wijcarousel-timerbar-inner " + o.wijCSS.cornerAll).css({
width: "0%"
}).attr("role", "progressbar");
self.timer = $("<div></div>").addClass("wijmo-wijcarousel-timerbar " + o.wijCSS.cornerAll).appendTo(self.container).append(self.progressBar).append(self.playPauseBtn);
};
wijcarousel.prototype._createPausePlay = function () {
var self = this, o = self.options;
self.playPauseBtn = $(self._createBtn(btnCss, o.auto ? o.wijCSS.iconPause : o.wijCSS.iconPlay)).bind("click." + self.widgetName, function () {
var icon = $(this).children("span:eq(0)");
self[icon.hasClass(o.wijCSS.iconPlay) ? "play" : "pause"]();
});
};
wijcarousel.prototype._createPagingItem = function (isDot, thumbOpt, ul, idx) {
var item = $(pagerHtml).attr({
"role": "tab",
"aria-label": idx + 1,
"title": idx + 1
}).addClass(this.options.wijCSS.stateDefault), width, height;
if(isDot) {
item.addClass("wijmo-wijcarousel-dot");
} else {
if(thumbOpt && thumbOpt.images && thumbOpt.images[idx]) {
width = thumbOpt.imageWidth;
height = thumbOpt.imageHeight;
if(width && height) {
item.width(width).height(height);
}
item.children("a").append($("<img>").attr("src", thumbOpt.images[idx]));
} else {
return;
}
}
ul.append(item);
};
wijcarousel.prototype._createPaging = function (type) {
var self = this, o = self.options, i, ul, li, thumbOpt = o.thumbnails, isDot = type === "dots";
self.container.append(self.pager = $("<div><ul class=\"wijmo-list " + o.wijCSS.cornerAll + " " + o.wijCSS.helperClearFix + " role=\"tablist\"></ul></div>"));
if(!isDot) {
self.pager.addClass("wijmo-wijcarousel-thumbnails");
}
ul = self.pager.children("ul.wijmo-list");
for(i = 0; i < self.count; i++) {
self._createPagingItem(isDot, thumbOpt, ul, i);
}
li = self.pager.find("li").eq(self.currentIdx);
if(li.length) {
self._activePagerItem(li);
}
//Add support for jUICE!
if(thumbOpt) {
$.each([
"mousedown",
"mouseup",
"mouseover",
"mouseout",
"click"
], function (i, n) {
var c = thumbOpt[n];
if(c && (typeof c === "string") && window[c]) {
thumbOpt[n] = window[c];
}
});
}
//end
self.pager.bind("mouseover." + self.widgetName, function (event) {
self._pageingEvents(event, "mouseover", thumbOpt, isDot, function (li) {
li.addClass(o.wijCSS.stateHover);
});
}).bind("mouseout." + self.widgetName, function (event) {
self._pageingEvents(event, "mouseout", thumbOpt, isDot, function (li) {
li.removeClass(o.wijCSS.stateHover);
});
}).bind("click." + self.widgetName, function (event) {
self._pageingEvents(event, "click", thumbOpt, isDot, function (li) {
self.scrollTo(li.index());
self._activePagerItem(li);
});
});
if(!isDot) {
$.each([
"mousedown",
"mouseup"
], function (i, n) {
if($.isFunction(thumbOpt[n])) {
self.pager.bind(n, function (event) {
var li = $(event.target).closest(liSel);
if(li.length) {
thumbOpt[n].call(li, event);
}
});
}
});
}
};
wijcarousel.prototype._pageingEvents = function (event, type, thumbOpt, isDot, func) {
var li = $(event.target).closest(liSel);
if(li.length) {
if($.isFunction(func)) {
func.call(event, li);
}
if(!isDot && $.isFunction(thumbOpt[type])) {
thumbOpt[type].call(li, event);
}
}
};
wijcarousel.prototype._activePagerItem = function (li) {
var activeCSS = this.options.wijCSS.stateActive;
li.addClass(activeCSS).attr("aria-selected", "true").siblings("li").removeClass(activeCSS).removeAttr("aria-selected");
};
wijcarousel.prototype._createWijSlider = function () {
var self = this, sOri = self.options.sliderOrientation, options = {
orientation: sOri,
range: false,
min: 0,
max: self.count - 1,
step: //pageSize
1,
value: self.currentIdx,
buttonClick: function (event, ui) {
var idx = ui.value;
self.scrollTo(idx);
},
slide: function (event, ui) {
var idx = ui.value;
self.scrollTo(idx);
}
}, slider = $("<div></div>").css("margin-bottom", "10px").css(sOri === "horizontal" ? "width" : "height", "200px").appendTo(self.container);
self.pager = slider.wijslider(options).parent().wrap("<div>").parent().addClass("wijmo-wijcarousel-slider-wrapper");
};
wijcarousel.prototype._createWijPager = function () {
var self = this, options = {
pageCount: self.count,
pageIndex: self.currentIdx,
pageButtonCount: self.count,
mode: "numeric",
pageIndexChanged: function (event, ui) {
var idx = ui.newPageIndex;
self.scrollTo(idx);
}
}, pager = $("<div></div>").appendTo(self.container);
self.pager = pager.wijpager(options).css({
position: "absolute"
});
};
wijcarousel.prototype._createPager = function () {
var self = this, o = self.options, position = {
collision: "none",
of: self.container,
my: "right top",
at: "right bottom"
};
if(o.pagerType === "numbers") {
self._createWijPager();
} else if(o.pagerType === "dots" || o.pagerType === "thumbnails") {
self._createPaging(o.pagerType);
self.pager.css({
position: "absolute"
});
} else if($.wijmo.wijslider && o.pagerType === "slider") {
self._createWijSlider();
if(o.sliderOrientation !== "horizontal") {
position.my = "left center";
position.at = "right center";
}
} else {
return;
}
self.pager.width(self.pager.width() + 1);
$.extend(position, o.pagerPosition);
o.pagerPosition = position;
self.pager.addClass("wijmo-wijcarousel-pager").position(position);
};
wijcarousel.prototype._setOption = function (key, value) {
var self = this, o = self.options, el, create, old, isHorizontal = o.orientation === "horizontal";
if(key === "pagerPosition" || key === "animation" || key === "controlPosition") {
$.extend(true, o[key], value);
} else {
old = o[key];
$.Widget.prototype._setOption.apply(self, arguments);
switch(key) {
case "showControls":
case "showPager":
case "showTimer":
if(value === old) {
break;
}
el = key.replace(/show/i, "").toLowerCase();
create = key.replace(/show/i, "_create");
if(value === true) {
if(!self[el]) {
self[create]();
} else if(self[el].jquery) {
self[el].show();
}
} else {
self[el].hide();
}
break;
case "loop":
case "orientation":
case "display":
case "preview":
if(value !== old) {
self._wijdestroy();
self._create();
}
break;
case "data":
self._createItems(isHorizontal);
self._applyContainerStyle(isHorizontal);
self._applyBtnClass();
if(o.showPager) {
self._createPager();
}
break;
case "showCaption":
if(value) {
self._createItems(isHorizontal)//re-create item with captions.
;
} else {
self.element.find(captionSel).remove();
}
break;
case "buttonPosition":
self._applyBtnStyle(isHorizontal);
break;
case "pagerType":
if(value !== old) {
if(self.pager && self.pager.jquery) {
self.pager.remove();
self.pager = null;
}
self._createPager();
}
break;
case "disabled":
self._handleDisabledOption(value, self.element);
break;
default:
break;
}
}
};
wijcarousel.prototype._getItemBound = function () {
var bound = {
}, self = this, o = self.options;
if(o.orientation === "horizontal") {
bound = {
w: Math.round(self.width / o.display),
h: self.height
};
} else {
bound = {
w: self.width,
h: Math.round(self.height / o.display)
};
}
return bound;
};
wijcarousel.prototype._stopAnimation = function () {
var self = this;
if(self.isPlaying && self.progressBar) {
self.progressBar.stop().css({
width: "0%"
});
}
self.list.stop(true, true);
};
wijcarousel.prototype._itemClick = function (event) {
var el = $(event.target), self = this, o = self.options, cIdx = self.currentIdx, item = el.closest("li." + itemCss), itemIdx = item.data("itemIndex"), idx, forward;
if(item.length > 0) {
if(o.preview && itemIdx < cIdx || itemIdx > cIdx + o.display - 1) {
idx = self._getItemByIndex(cIdx).index();
forward = (item.index() > idx) ? "next" : "previous";
self[forward]();
}
self._trigger("itemClick", event, {
index: itemIdx,
el: item
});
}
};
wijcarousel.prototype._wijdestroy = function () {
var self = this, wijCSS = self.options.wijCSS;
self.container.removeClass("wijmo-wijcarousel " + wijCSS.widget).removeClass("wijmo-wijcarousel-horizontal").removeClass("wijmo-wijcarousel-vertical");
if(self.timeout) {
self.list.stop(true);
window.clearTimeout(self.timeout);
self.timeout = null;
}
self.list.unwrap().removeClass("wijmo-wijcarousel-list").removeClass(wijCSS.helperClearFix).unbind("." + self.widgetName).removeAttr("style").children("li").each(function (idx, data) {
var item = $(data);
item.removeClass("wijmo-wijcarousel-item").removeClass(wijCSS.helperClearFix).removeClass(currentCss);
item.children("img").removeClass("wijmo-wijcarousel-image");
item.children(captionSel).remove();
item.css({
width: "",
height: ""
});
item.removeData("itemIndex");
});
self.itemWidth = self.itemHeight = undefined;
self.element.find(ctrlSelector + ",.wijmo-wijcarousel-timerbar").remove();
if(self.pager) {
self.pager.remove();
}
self.element.find("li>span").css("display", "");
if(self.disabledDiv.length) {
self.disabledDiv.remove();
self.disabledDiv = $();
}
};
wijcarousel.prototype.destroy = /**
* Removes the wijcarousel functionality completely. This returns the element to its pre-init state.
*/
function () {
this._wijdestroy();
$.Widget.prototype.destroy.apply(this);
};
wijcarousel.prototype._resetDom = function () {
var self = this;
//reset list item container
self._applyListStyle();
self.list.children("li").each(function (idx, data) {
var li = $(data), caption = li.children("div.wijmo-wijcarousel-caption"), text = li.children("div.wijmo-wijcarousel-text");
self._applyItemBound(li);
self._setStyle(caption.add(text), function () {
self._applyCaptionStyle(caption, text);
});
});
self._applyContainerStyle(self.isHorizontal, true);
//reset preview
if(self.options.preview) {
self._createPreview();
}
//reset controls(button, pager, controls)
self._setStyle(self.prevBtn.add(self.nextBtn), function () {
self._applyBtnStyle(self.isHorizontal);
});
self._setStyle(self.pager, function () {
self.pager.position(self.options.pagerPosition);
});
self._setStyle(self.controls, function () {
self.controls.position(self.options.controlPosition);
});
};
wijcarousel.prototype._setStyle = function (control, func) {
var isShow = true;
if(!control || control.length === 0) {
return;
}
if(control.css("display") == "none") {
isShow = false;
control.css("display", "");
}
func.call(this);
if(!isShow) {
control.css("display", "none");
}
};
wijcarousel.prototype.refresh = /**
* Refresh the carousel layout.Reset the layout, scrolled.
*/
function () {
var self = this, o = self.options, el = self.element;
//reset variable
self.width = el.width() || 640;
self.height = el.height() || 480;
self.itemWidth = self.itemHeight = 0;
self._resetDom();
self.pause();
};
wijcarousel.prototype.play = /**
* Starts automatically displaying each of the images in order.
*/
function () {
var self = this, o = self.options;
if(self.isPlaying || o.disabled) {
return;
}
if(o.interval === 0) {
return self.pause();
}
if(o.showTimer && self.progressBar) {
self.progressBar.css({
width: "0%"
});
self.playPauseBtn.children("span:eq(0)").removeClass(o.wijCSS.iconPlay).addClass(o.wijCSS.iconPause);
self.progressBar.animate({
width: "100%"
}, o.interval, null, function () {
self._scroll("next", o.step);
});
} else {
if(self.timeout) {
return;
}
self.timeout = window.setTimeout(function () {
self.next();
}, o.interval);
}
self.isPlaying = true;
};
wijcarousel.prototype.pause = /**
* Stops automatically displaying the images in order.
*/
function () {
var self = this, o = self.options;
if(o.showTimer && self.progressBar) {
self.progressBar.stop().css({
width: "0%"
});
self.playPauseBtn.children("span:eq(0)").removeClass(o.wijCSS.iconPause).addClass(o.wijCSS.iconPlay);
} else {
if(self.timeout === null) {
return;
}
window.clearTimeout(self.timeout);
self.timeout = null;
}
self.isPlaying = false;
};
wijcarousel.prototype.next = /**
* Shows the next picture.
*/
function () {
var self = this, step = self.options.step;
if(typeof step !== "number" || step < 1) {
return;
}
self._stopAnimation();
self._scroll("next", step);
};
wijcarousel.prototype.previous = /**
* Shows the previous picture.
*/
function () {
var self = this, step = self.options.step;
if(typeof step !== "number" || step < 1) {
return;
}
self._stopAnimation();
self._scroll("previous", step);
};
wijcarousel.prototype.scrollTo = /**
* Scrolls to the picture at the specified index.
* @param {number} index The zero-based index of the picture to which to scroll.
* @example $("#element").wijcarousel("scrollTo", 2);
*/
function (idx) {
var self = this, forward, step;
self._stopAnimation();
forward = idx > self.currentIdx ? "next" : "previous";
step = Math.abs(idx - self.currentIdx);
if(idx !== self.currentIdx) {
self._scroll(forward, step);
}
};
wijcarousel.prototype._scroll = function (forward, step) {
var self = this, o = self.options, list = self.list, offset = 0, mask, i, isHorizontal = o.orientation === "horizontal", option = {
}, size = self.itemBound[isHorizontal ? "w" : "h"], dir = isHorizontal ? "left" : "top", scrolled = step, css = {
}, previewOffset = 0, currentLeft = self.currentIdx * size;
if(!o.loop) {
if(forward === "next") {
if(self.currentIdx + o.display + step <= self.count) {
offset = -currentLeft - size * scrolled;
} else if(self.currentIdx + o.display < self.count) {
scrolled = self.count - self.currentIdx - o.display;
offset = -currentLeft - size * scrolled;
} else {
return;
}
} else {
if(self.currentIdx - step >= 0) {
offset = -currentLeft + size * scrolled;
} else if(self.currentIdx > 0) {
scrolled = self.currentIdx;
offset = 0;
}
}
if(offset !== undefined) {
//self.offset for preview mode.
option[dir] = offset + self.offset;
//if ($.browser.webkit) {
// self.list.css(dir, -currentLeft);
//}
self._doAnimation(forward, option, scrolled);
}
} else {
if(o.preview) {
offset = previewOffset = -size * previewNum + self.offset;
}
if(forward === "next") {
offset += -size * scrolled;
option[dir] = offset;
} else {
for(i = 0; i < step; i++) {
offset -= size;
list.children("li:last").prependTo(list);
}
css[dir] = offset;
option[dir] = previewOffset;
list.css(css);
}
self._doAnimation(forward, option, step, dir, size);
}
if(o.preview) {
mask = $();
for(i = 0; i < o.display; i++) {
mask = mask.add(self._getItemByIndex(self.currentIdx + i).find("div.wijmo-wijcarousel-mask:eq(0)"));
}
mask.stop(true).animate({
opacity: 0.6
}, o.animation.duration / 2, function () {
//mask.css({ opacity: "" });
self._getItemByIndex(self.currentIdx).removeClass(currentCss);
});
}
};
wijcarousel.prototype._doAnimation = function (action, option, scrolled, dir, size) {
var self = this, list = self.list, o = self.options, data, i, animation = {
complete: null
}, completeCallback, css = {
}, to;
if(!self.list.children().length) {
return;
}
if(action === "next") {
to = self.currentIdx + scrolled;
} else {
to = self.currentIdx - scrolled;
}
if(!o.loop) {
completeCallback = function () {
self.currentIdx = to;
self._setCurrentState(self.currentIdx);
};
} else {
to = to % self.count + (to < 0 ? self.count : 0);
completeCallback = function () {
//self.isAnimating = false;
var left = 0;
if(o.preview) {
left = self.offset - previewNum * size;
}
if(action === "next") {
for(i = 0; i < scrolled; i++) {
list.children("li:first").appendTo(list);
}
if(dir) {
css[dir] = left;
list.css(css);
}
}
self.currentIdx = to;
self._setCurrentState(self.currentIdx);
};
}
animation.complete = completeCallback;
data = {
index: self.currentIdx,
to: to,
el: self._getItemByIndex(self.currentIdx)
};
if(!self._trigger("beforeScroll", null, data)) {
return;
}
if(o.animation && o.animation.complete) {
o.animation.complete = undefined;
}
$.extend(animation, o.animation);
self._hideCaption();
list.animate(option, animation);
};
wijcarousel.prototype._setCurrentState = function (idx) {
var self = this, o = self.options, li, data, shouldPlay, lastIdx = idx + o.display - 1, currentItem, mask, i;
if(!o.loop) {
shouldPlay = (idx + o.display) < self.count;
if(self.isPlaying && shouldPlay) {
window.clearTimeout(self.timeout);
self.timeout = null;
self.isPlaying = false;
self.play();
} else if(self.progressBar) {
self.pause();
}
self._applyBtnClass();
} else if(self.isPlaying) {
window.clearTimeout(self.timeout);
self.timeout = null;
self.isPlaying = false;
self.play();
}
if(o.preview) {
mask = $();
currentItem = self._getItemByIndex(idx);
for(i = 0; i < o.display; i++) {
mask = mask.add(self._getItemByIndex(idx + i).find("div.wijmo-wijcarousel-mask:eq(0)"));
}
mask.animate({
opacity: 0
}, o.animation.duration / 2, function () {
currentItem.addClass(currentCss);
self._showCaption(idx, lastIdx);
});
} else {
self._showCaption(idx, lastIdx);
}
if(self.pager) {
if($.wijmo.wijslider && self.pager.find(":wijmo-wijslider").length) {
self.pager.find(":wijmo-wijslider:eq(0)").wijslider("value", idx);
} else if($.wijmo.wijpager && self.pager.is(":wijmo-wijpager")) {
self.pager.wijpager("option", "pageIndex", idx);
} else if(self.pager.jquery) {
li = self.pager.find(">ul:eq(0)>li").eq(idx);
if(li.length) {
self._activePagerItem(li);
}
}
}
data = {
firstIndex: idx,
lastIndex: lastIdx
};
self._trigger("afterScroll", null, data);
};
wijcarousel.prototype._getItemByIndex = function (idx) {
var self = this, list = self.list, item, index = idx % self.count;
if(!self.options.loop) {
return list.children("li").eq(index);
}
list.children("li").each(function (i) {
var li = $(this);
if(li.data("itemIndex") === index) {
item = li;
return false;
}
});
return item;
};
wijcarousel.prototype._collectionChanged = function (action) {
var self = this;
self.count = self.count + (action === "add" ? 1 : -1);
self._applyListStyle();
if(self.pager && self.pager.jquery) {
self.pager.remove();
self.pager = null;
self._createPager();
}
self._applyBtnClass();
};
wijcarousel.prototype.add = /**
* Add a custom item with specified index.
* @param {string|jQuery} ui The node content or innerHTML.
* @param {number} index Specified the postion to insert at.
*/
function (ui, index) {
var self = this, item, li;
if(typeof ui === "string") {
item = $(ui);
} else if(ui.jquery) {
item = ui;
} else if($.isPlainObject(ui)) {
item = self._generateMarkup(ui);
} else {
return;
}
if(!item.is("li")) {
item = item.wrap("<li></li>").parent();
}
li = item;
if(typeof index === "number" && index >= 0 && index < self.count) {
li.insertBefore(self._getItemByIndex(index));
self.list.children("li").each(function (i, data) {
var item = $(data);
if(item.data("itemIndex") >= index) {
item.data("itemIndex", item.data("itemIndex") + 1);
}
});
} else {
if(index == 0) {
li.appendTo(self.list);
}
li.insertAfter(self._getItemByIndex(self.count - 1));
}
self._createItem(item, index !== undefined ? index : self.count);
self._collectionChanged("add");
};
wijcarousel.prototype.remove = /**
* Remove the item at specified index.
* @param {number} index Specified which item should be removed.
*/
function (index) {
var self = this, item;
if(typeof index === "number" && index >= 0 && index < self.count) {
item = self._getItemByIndex(index);
self.list.children("li").each(function (i, data) {
var li = $(data);
if(li.data("itemIndex") > index) {
li.data("itemIndex", li.data("itemIndex") - 1);
}
});
} else {
item = self._getItemByIndex(self.count - 1);
}
if(item) {
item.remove();
}
self._collectionChanged("remove");
};
return wijcarousel;
})(wijmo.wijmoWidget);
carousel.wijcarousel = wijcarousel;
var wijcarousel_options = (function () {
function wijcarousel_options() {
/**
* Mobile CSS.
* @ignore
*/
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body-a",
stateDefault: "ui-btn-up-a",
stateHover: "ui-btn-down-a",
stateActive: "ui-btn-down-b",
iconPlay: "ui-icon-arrow-r",
iconPause: "ui-icon-grid"
};
/** Selector option for auto self initialization.
* This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijcarousel')";
/** An object collection that contains the data of the carousel.
* @example:
* $("#element").wijcarousel( { data: [{
* imageUrl: "../thumb/image1.jpg",
* linkUrl: "../images/image1.jpg",
* content: "",
* caption: "<span>Word Caption 1</span>"
* },{
* imageUrl: "../thumb/image2.jpg",
* linkUrl: "../images/image2.jpg",
* content: "",
* caption: "<span>Word Caption 2</span>"
* }] } );
*/
this.data = [];
/** Allows pictures to be played automatically.
* @example $("#element").wijcarousel( { auto: true } );
*/
this.auto = false;
/** Determines the time span between two pictures showing in autoplay mode.
* @example $("#element").wijcarousel( { interval: 3000 } );
*/
this.interval = 5000;
/** Determines if the timer of the carousel should be shown.
* If true, the timer appears by default at the top of the carousel with a play/pause button allowing carousel items to be automatically cycled through at run time.
* @example $("#element").wijcarousel( { showTimer: true } );
*/
this.showTimer = false;
/** Determines the position value for next button and previous button.
* Possible values are: "inside" and "outside".
* @example $("#element").wijcarousel( { buttonPosition: "outside" } );
*/
this.buttonPosition = "inside";
/** Determines whether to show the pager element.
* By default, if showPager is set to true, the pager will appear at the bottom right of the widget and allows run time carousel item navigation.
* You can customize the location and appearance of the pager by using the pagerPosition and pagerType options.
* @example $("#element").wijcarousel( { showPager: true } );
*/
this.showPager = false;
/** Determines the class of custom previous button.
* Includes the following sub-options "defaultClass", "hoverClass", "disableClass".
* @example $("#element").wijcarousel( { prevBtnClass: {
* }});
*/
this.prevBtnClass = {
defaultClass: "",
hoverClass: "",
disableClass: ""
};
/** Determines the class of custom previous button.
* Includes the following sub-options "defaultClass", "hoverClass", "disableClass".
* @example $("#element").wijcarousel( { nextBtnClass: {
* }});
*/
this.nextBtnClass = {
defaultClass: "",
hoverClass: "",
disableClass: ""
};
/** Determines the type of the pager in the carousel.
* Possible values are: "slider", "numbers", "dots", "thumbnails".
* For a live example, see the Carousel Paging page in the Explore sample.
* @example $("#element").wijcarousel( { pagerType: "numbers" } );
*/
this.pagerType = "numbers";
/** Determines the thumbnails list for a pager when pagerType is "thumbnails".
* @type {object}
* @example $("#element").wijcarousel( { thumbnails: [] } );
*/
this.thumbnails = {
mouseover: null,
mouseout: null,
mousedown: null,
mouseup: null,
click: null,
imageWidth: 58,
imageHeight: 74,
images: []
};
/** A value that indicates the position settings for the pager.
* @type {object}
* @example $("#element").wijcarousel( {
* pagerPosition: {
* my: 'left bottom',
* at: 'right top',
* offset: '0 0'}
* });
*/
this.pagerPosition = {
};
/** Determines the orientation of the pager.
* Possible values are: "vertical" & "horizontal"
* @example $("#element").wijcarousel( { orientation: "vertical" } );
*/
this.orientation = "horizontal";
/** Determines the orientation of the slider.
* Possible values are: "vertical" & "horizontal"
* @example $("#element").wijcarousel( { sliderOrientation: "vertical" } );
*/
this.sliderOrientation = "horizontal";
/** Allows the carousel to loop back to the beginning.
* @example $("#element").wijcarousel( { loop: true } );
*/
this.loop = true;
/** The animation option determines whether and how images are scroll in the carousel.
* It defines the animation effect and controls other aspects of the widget's animation, such as duration and easing.
* Set the disable attribute to true in order to disable the animation effect.
* For a live example, see the Carousel Animation page in the Explore sample.
* @type {object}
* @example $("#element").wijcarousel( {
* animation {
* queue: true,
* disable: false,
* duration: true,
* easing: "easeOutCubic"
* }
* } );
*/
this.animation = {
queue: /** This value determines whether to queue animation operations.
* @type {boolean}
*/
true,
disable: /** A value that determines whether to show animation. Set this option to true in order to disable easing.
* @type {boolean}
*/
false,
duration: /** The duration option defines the length of the scrolling animation effect in milliseconds.
* @type {number}
*/
1000,
easing: /** Sets the type of animation easing effect that users experience when the wijcarousel is scrolled to another image. For example, the wijcarousel can bounce several times as it loads.
* @type {string}
* Valid Values:
* easeInCubic ¨C Cubic easing in.Begins at zero velocity and then accelerates.
* easeOutCubic ¨C Cubic easing in and out.Begins at full velocity and then decelerates to zero.
* easeInOutCubic ¨C Begins at zero velocity, accelerates until halfway, and then decelerates to zero velocity again.
* easeInBack ¨C Begins slowly and then accelerates.
* easeOutBack ¨C Begins quickly and then decelerates.
* easeOutElastic ¨C Begins at full velocity and then decelerates to zero.
* easeOutBounce ¨C Begins quickly and then decelerates.The number of bounces is related to the duration, longer durations produce more bounces.
* Default: "linear".
* Type: string.
*/
"linear"
};
/** Determines the custom start position of the image list in wijcarousel.
* @example $("#element").wijcarousel( { start: 2 } );
*/
this.start = 0;
/** Determines how many images should be shown in the view area.
* @example $("#element").wijcarousel( { display: 2 } );
*/
this.display = 1;
/** Determines if we should preview the last and next images.
* loop == false , orintation == "horizontal",display == 1.
* @example $("#element").wijcarousel( { preview: false } );
*/
this.preview = false;
/** Determines how many images will be scrolled
* when you click the Next/Previous button.
* @example $("#element").wijcarousel( { step: 2 } );
*/
this.step = 1;
/** Determines whether the custom control should be shown.
* @example $("#element").wijcarousel( { showControls: true } );
*/
this.showControls = false;
/** Determines the innerHtml of the custom control.
* @example $("#element").wijcarousel( { control: "<div>Blah</div>" } );
*/
this.control = "";
/** A value that indicates the position settings for the custom control.
* @type {object}
* @example $("#element").wijcarousel( {
* controlPosition: {
* my: 'left bottom',
* at: 'right top ',
* offset: '0 0'
* }
* });
*/
this.controlPosition = {
};
/** Determines whether the caption of items should be shown.
* @example $("#element").wijcarousel( { showCaption: true } );
*/
this.showCaption = true;
/** Determines whether the controls should be shown after created
* or when hovering on the dom element.
* @example $("#element").wijcarousel( { showControlsOnHover: true } );
*/
this.showControlsOnHover = false;
/** This is the itemClick event handler.
* It is a function called when the image is clicked.
* @event
* @dataKey {number} index This is the index of the clicked image.
* @dataKey {DOMElement} el This is the dom element of this item.
*/
this.itemClick = null;
/** This is the beforeScroll event handler.
* It is a function called before scrolling to another image.
* @event
* @dataKey {number} index This is the index of the clicked image.
* @dataKey {DOMElement} to The index of the image that will scrolled to.
*/
this.beforeScroll = null;
/** This is the afterScroll event handler.
* It is a function called after scrolling to another image.
* @event
* @dataKey {number} index The index of the last image.
* @dataKey {DOMElement} to The index of the current image.
*/
this.afterScroll = null;
/** This is the loadCallback event handler.
* It is a function called after creating the dom element.
* @event
* @param {jQuery.Event} e jQuery Event object
* @param {object} data The node widget that relates to this event.
*/
this.loadCallback = null;
}
return wijcarousel_options;
})();
wijcarousel.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijcarousel_options());
$.wijmo.registerWidget("wijcarousel", wijcarousel.prototype);
})(wijmo.carousel || (wijmo.carousel = {}));
var carousel = wijmo.carousel;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/// <reference path="../wijslider/jquery.wijmo.wijslider.ts" />
/// <reference path="../wijpager/jquery.wijmo.wijpager.ts" />
/*globals jQuery, window, XMLHttpRequest*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
(function (gallery) {
"use strict";
var $ = jQuery, widgetName = "wijgallery", baseCss = "wijmo-wijgallery", cssPrefix = "wijmo-wijgallery-", selectedCss = cssPrefix + "selected", btnCssPrefix = cssPrefix + "button-", btnCss = cssPrefix + "button", pointerCss = "wijmo-wijgallery-thumbs-pointer-{0}", flashCss = "wijmo-wijgallery-flashwrapper", frameHtml = "<div class=\"wijmo-wijgallery-frame\">" + "<div class=\"wijmo-wijgallery-content\"></div></div>", thumbsHtml = "<div class=\"wijmo-wijgallery-thumbs\"></div>", btnHtml = "<a><span></span></a>", navHtml = "<div class=\"wijmo-wijgallery-frame-{0}\">" + "<a href=\"#\" class=\"wijmo-wijgallery-frame-link\"></a></div>", captionHtml = "<div></div>", carouselItem = "li.wijmo-wijcarousel-item";
if(!window["S"] && window["swfobject"]) {
window["S"] = {
flash: window["swfobject"]
};
}
/** @widget */
var wijgallery = (function (_super) {
__extends(wijgallery, _super);
function wijgallery() {
_super.apply(this, arguments);
}
wijgallery.prototype._setOption = function (key, value) {
var self = this, o = self.options, el, create, old, text;
if(key === "framePosition" || key === "thumbnailPosition" || key === "transitions" || key === "pagingPosition") {
$.extend(true, o[key], value);
} else {
old = o[key];
$.Widget.prototype._setOption.apply(self, arguments);
switch(key) {
case "disabled":
self._handleDisabledOption(value, self.element);
break;
case "thumbnailOrientation":
self.thumbs[self.thumbWidgetName]({
orientation: value
});
break;
case "thumbsDisplay":
self.thumbs[self.thumbWidgetName]({
display: value
});
break;
case "autoPlay":
self[value ? "play" : "pause"]();
break;
case "showCounter":
case "showTimer":
case "showControls":
el = key.replace(/show/i, "").toLowerCase();
create = key.replace(/show/i, "_create");
if(value !== old) {
if(value === true) {
if(!self[el]) {
self[create]();
} else if(self[el].jquery) {
self[el].show();
}
} else {
self[el].hide();
}
}
break;
case "showCaption":
if(value) {
self._createCaption(self.size);
text = self._loadCaption(self.images[self.currentIdx]);
text.show();
} else {
self.element.find(".wijmo-wijgallery-caption,.wijmo-wijgallery-text").remove();
}
break;
case "showPager":
case "thumbsLength":
case "thumbnailDirection":
case "showControlsOnHover":
case "mode":
case "data":
self._wijdestroy();
self._create();
break;
default:
break;
}
}
};
wijgallery.prototype._handleDisabledOption = function (disabled, ele) {
var self = this;
if(self.pager && !self.pager.is(":hidden")) {
self.disabledEles = self.disabledEles.add(self.pager);
}
if(disabled) {
if(!self.disabledDiv.length) {
self._createDisabledDiv();
}
self.disabledDiv.appendTo("body");
} else if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = $();
}
};
wijgallery.prototype._createDisabledDiv = function () {
var self = this;
self.disabledEles.each(function (idx, data) {
var ele = $(data), eleOffset = ele.offset(), disabledWidth = ele.outerWidth(), disabledHeight = ele.outerHeight(), div = $("<div></div>").css({
"z-index": "99999",
position: "absolute",
width: disabledWidth,
height: disabledHeight,
left: eleOffset.left,
top: eleOffset.top
});
if($.browser.msie && parseInt($.browser.version) < 10) {
div.css("background-color", "white");
if($.browser.version === "9.0") {
div.css("opacity", "0.1");
}
}
self.disabledDiv = self.disabledDiv.add(div);
});
};
wijgallery.prototype._initLi = function (li) {
var a = li.children("a:eq(0)"), img = li.find("img:eq(0)"), caption = li.find("span:eq(0)"), imgData = {
url: null,
thumbUrl: null,
title: img.attr("alt"),
caption: undefined
};
if(a.length && a.attr("href")) {
imgData.url = a.attr("href");
if(!imgData.title) {
imgData.title = a.attr("title");
}
} else if(img.length) {
imgData.url = img.attr("src");
}
if(caption.length) {
imgData.caption = caption;
} else if(img.attr("title")) {
imgData.caption = $("<span>").html(img.attr("title"));
}
imgData.thumbUrl = img.attr("src");
return imgData;
};
wijgallery.prototype._initStatus = function () {
var self = this, lis;
self.images = [];
self.ul = self.element.children("ul");
lis = self.ul.children("li");
self._count = lis.length;
lis.each(function (i) {
var imgData = self._initLi($(this));
self.images.push(imgData);
});
};
wijgallery.prototype._createMarkupFromData = function () {
var self = this, o = self.options, items = o.data, el = self.element, ul = el.children("ul:eq(0)");
self.images = items;
if(ul.length) {
ul.empty();
} else {
ul = $("<ul>").appendTo(el);
}
self.ul = ul;
$.each(items, function (idx, item) {
var link = $("<a>"), li = $("<li>"), img = $("<img>");
if(item.url) {
link.attr("href", item.url);
}
if(item.thumbUrl) {
img.attr("src", item.thumbUrl);
}
if(item.title) {
img.attr("alt");
}
link.append(img).appendTo(li);
li.appendTo(ul);
});
self._count = items.length;
};
wijgallery.prototype._create = function () {
var self = this, o = self.options;
self.container = self.element;
self.container.addClass([
baseCss,
o.wijCSS.widget
].join(' '));
self.currentThumbIdx = 0;
self.currentIdx = -1;
self.disabledEles = self.element;
self.disabledDiv = $();
//number of setTimeOut(ensure only 1 timer at same time)
self.timerCount = 0;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
if(o.showPager) {
//remove this.
o.pagingPosition = true;
o.thumbnails = false;
} else {
o.thumbnails = true;
}
if(o.data && o.data.length) {
self._createMarkupFromData();
} else {
self._initStatus();
}
if(o.loadCallback && $.isFunction(o.loadCallback)) {
self._trigger("loadCallback", null, self);
}
self._createDom();
if(o.autoPlay) {
self._play(true);
}
if(o.showControlsOnHover) {
self.frame.find(".wijmo-wijpager," + ".wijmo-wijgallery-button-next,.wijmo-wijgallery-counter," + ".wijmo-wijgallery-button-previous").hide();
if(!self.isPlaying && self.timer) {
self.timer.hide();
}
}
if(o.disabled) {
self.disable();
}
//update for visibility change
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
//self.refresh();
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
}, "wijgallery");
}
};
wijgallery.prototype._createDom = function () {
var self = this, o = self.options;
if(o.thumbnails) {
self._createThumbnails();
} else {
self.ul.hide();
}
self._createFrame();
if(o.control) {
self._createControls();
}
if(o.showCounter) {
self._createCounter();
}
if(o.showTimer) {
self._createTimer();
}
if(o.showPager) {
self._createPager();
}
};
wijgallery.prototype._getFrameSize = function () {
var self = this, or = self.options.thumbnailOrientation === "horizontal", height = self.element.height() - (or ? (self.thumbs ? self.thumbs.outerHeight(true) : 0) : 0), width = self.element.width() - (or ? 0 : (self.thumbs ? self.thumbs.outerWidth(true) : 0));
return {
w: (width < 2 || !width) ? 750 : width,
h: (height < 2 || !height) ? 300 : height
};
};
wijgallery.prototype._createFrame = function () {
var self = this, o = self.options, w, h, size = //currentImg = self.images[self.currentIdx],
self._getFrameSize(), d = o.thumbnailDirection === "after";
self.frame = $(frameHtml).addClass(o.wijCSS.content + " " + o.wijCSS.helperClearFix)[d ? "prependTo" : "appendTo"](self.container).setOutWidth(size.w - 1).setOutHeight(//fixed 1px in all browser
//.setOutWidth($.browser.msie ? size.w - 1 : size.w)//fixed 1px in ie
size.h).wrap("<div class=\"wijmo-wijgallery-framewrapper\">");
self.size = size;
w = self.frame.width();
h = self.frame.height();
self.frameWrapper = self.frame.parent();
if(o.thumbnailOrientation === "vertical") {
self.frameWrapper.addClass("wijmo-wijgallery-framewrapper-vertical");
}
if(o.showControlsOnHover) {
self.frame.bind("mouseenter." + self.widgetName, function () {
self._showControls("controls");
}).bind("mouseleave." + self.widgetName, function () {
self._hideControls("controls");
});
}
self.content = self.frame.children("div.wijmo-wijgallery-content");
if(o.mode === "img") {
self._createFrameMask();
}
self._createPrevNextBtn();
self._createCaption(size);
self._createLoading();
self.last = $("<div class=\"" + o.wijCSS.overlay + " wijmo-wijgallery-last\"></div>").appendTo(self.content).width(w).height(h).css({
"line-height": size.h + "px"
});
self.current = $("<div class=\"" + o.wijCSS.overlay + " wijmo-wijgallery-current\"></div>").appendTo(self.content).width(w).height(h).css({
"line-height": size.h + "px"
});
self._show(0);
};
wijgallery.prototype._createControls = function () {
var self = this, o = self.options, position = {
collision: "none",
of: self.container,
my: "center bottom",
at: "center bottom"
};
if(o.control) {
self.controls = $(o.control).css({
position: "absolute"
}).appendTo(self.container);
$.extend(position, o.controlPosition);
self.controls.position(position);
}
};
wijgallery.prototype._createLoading = function () {
var self = this;
self.loading = $("<div></div>").addClass("wijmo-wijgallery-loading").appendTo(self.content);
self.loading.css({
left: (self.content.width() - self.loading.width()) / 2,
top: (self.content.height() - self.loading.height()) / 2
});
self.loading.hide();
};
wijgallery.prototype._createFrameMask = function () {
var self = this, o = self.options;
$.each([
"previous",
"next"
], function (i, n) {
var nav = $(navHtml.replace(/\{0\}/, n)).appendTo(self.frame), link = nav.children("a");
if($.browser.msie && parseInt($.browser.version) <= 9) {
nav.css({
"background-color": "#fff"
});
}
if(o.showControlsOnHover) {
nav.bind("mouseenter." + self.widgetName, function () {
self._showControls(n);
}).bind("mouseleave." + self.widgetName, function () {
self._hideControls(n);
});
}
link.bind("click." + self.widgetName, function (event) {
self[n]();
event.preventDefault();
});
});
};
wijgallery.prototype._createCounter = function () {
var self = this, o = self.options;
if(!o.showCounter) {
if(self.counter) {
self.counter.remove();
self.counter = undefined;
}
return;
}
if(!self.counter) {
self.counter = $("<div></div>").addClass("wijmo-wijgallery-counter " + o.wijCSS.stateDefault + " " + o.wijCSS.cornerTL).appendTo(self.frame);
}
self._refreshCounter();
};
wijgallery.prototype._refreshCounter = function () {
var self = this, o = self.options, counter;
if(!self.counter) {
return;
}
self.counter.empty();
if(o.counter) {
counter = o.counter.replace(/\[i\]/, self.currentIdx + 1);
counter = counter.replace(/\[n\]/, self._count);
$("<span></span>").text(counter).appendTo(self.counter);
}
};
wijgallery.prototype._createPrevNextBtn = function () {
var self = this, wijCSS = self.options.wijCSS;
$.each([
"next",
"previous"
], function (i, n) {
var css = n === "next" ? wijCSS.iconArrowRight : wijCSS.iconArrowLeft, panel;
panel = self.frame.find(".wijmo-wijgallery-frame-" + n);
if(!panel.length || self.options.mode !== "img") {
panel = self.frame;
}
self[n + "Btn"] = $(self._createBtn(btnCssPrefix + n, css)).bind("click." + self.widgetName, $.proxy(self[n], self)).appendTo(panel);
self._applyBtnStyle(n);
});
};
wijgallery.prototype._applyBtnStyle = function (dir) {
var self = this, o = self.options, isNext = dir === "next", btn = self[dir + "Btn"], at = isNext ? "right center" : "left center", my = at, wijCSS = o.wijCSS, css = isNext ? wijCSS.cornerLeft : wijCSS.cornerRight, condition = dir === "next" ? (self.currentIdx >= self._count) : (self.currentIdx <= 0), nextPosition = {
collision: "none",
of: self.frame,
my: my,
at: at
};
btn.addClass(css).position(nextPosition);
if(condition) {
btn.removeClass(wijCSS.stateHover).addClass(wijCSS.stateDisabled);
} else if(btn.hasClass(wijCSS.stateDisabled)) {
btn.removeClass(wijCSS.stateDisabled);
}
};
wijgallery.prototype._createCaption = function (size) {
var self = this, o = self.options, css = o.wijCSS;
if(o.showCaption) {
self.overlay = $(captionHtml).addClass([
css.content,
css.helperClearFix,
"wijmo-wijgallery-caption"
].join(' ')).width(size.w).appendTo(self.content);
self.caption = $(captionHtml).addClass([
css.content,
css.helperClearFix,
"wijmo-wijgallery-text"
].join(' ')).width(size.w).appendTo(self.content);
}
};
wijgallery.prototype._loadCaption = function (image) {
var self = this, content = image.caption, height, caption = $("<span></span>"), text = self.element.find(".wijmo-wijgallery-text," + ".wijmo-wijgallery-caption");
if(content) {
text.show();
if(content.jquery) {
content.show();
}
caption.html(content);
self.caption.empty().append(caption);
height = caption.outerHeight(true);
text.height(height);
//ie get wrong height at first time. the 2nd is right.
if($.browser.msie) {
text.height(caption.css("display", "block").outerHeight(true));
}
}
text.hide();
return text;
};
wijgallery.prototype._showCaption = function (img) {
var self = this;
if(img && img.caption) {
if(self.caption.length) {
self.caption.fadeIn(500);
}
if(self.overlay.length) {
self.overlay.show().animate({
opacity: 0.5
}, 500);
}
}
};
wijgallery.prototype._createTooltip = function (dir) {
var self = this, wijCSS = self.options.wijCSS, d = dir || "bottom";
self.pointer = $("<div>").addClass([
wijCSS.content,
wijCSS.stateDefault,
pointerCss.replace(/\{0\}/, d)
].join(' '));
self.pointer.appendTo(self.thumbsWrapper).hide();
};
wijgallery.prototype._createThumbnails = function () {
var self = this, o = self.options, d = o.thumbnailDirection === "after", thumbClass = "wijmo-wijgallery-thumbs-{0}", or = o.thumbnailOrientation === "horizontal", postFix = d ? (or ? "bottom" : "right") : (or ? "top" : "left");
self.thumbPosition = postFix;
self.thumbs = $(thumbsHtml).appendTo(self.container).addClass(o.wijCSS.content).addClass(or ? "wijmo-wijcarousel-horizontal-multi" : "wijmo-wijcarousel-vertical-multi");
if(or) {
self.thumbs.css({
height: o.thumbsLength + "px"
}).setOutWidth(self.element.width());
} else {
self.thumbs.css({
width: o.thumbsLength + "px"
}).setOutHeight(self.element.height());
}
self.ul.appendTo(self.thumbs);
self.ul.children("li").each(function (i, data) {
var link = $(data).children("a"), imgData = self.images[i], href = imgData.thumbUrl;
if(!link.length) {
link = $(data).wrapInner("<a>").children("a");
link.attr("href", href);
}
});
if($[self.namespace][self.thumbWidgetName]) {
self.thumbs.addClass(thumbClass.replace(/\{0\}/, postFix)).find("li").addClass(o.wijCSS.stateDefault).hover(function () {
$(this).addClass(o.wijCSS.stateHover);
}, function () {
$(this).removeClass(o.wijCSS.stateHover);
});
self.thumbsWrapper = self.thumbs[self.thumbWidgetName]({
display: o.thumbsDisplay,
step: o.thumbsDisplay - 1,
itemPadding: "0 10px",
showCaption: o.showThumbnailCaptions,
orientation: o.thumbnailOrientation,
loop: false,
itemClick: function (event, ui) {
var idx = ui.index;
self.show(idx);
event.preventDefault();
},
afterScroll: function (event, ui) {
self.currentThumbIdx = ui.firstIndex;
if(self.activeLi && self.activeLi.is("li") && self.activeLi.index() >= ui.firstIndex && self.activeLi.index() <= ui.lastIndex) {
self._highlightThumb(self.activeLi);
}
self.isScrolling = false;
},
beforeScroll: function (event, ui) {
self.isScrolling = true;
if(o.mode === "swf" || o.mode === "flv") {
self.pointer.hide();
} else {
self.pointer.fadeOut(100);
}
}
}).wrap("<div class=\"wijmo-wijgallery-thumbswrapper\">").parent();
if(!or) {
self.thumbsWrapper.addClass("wijmo-wijgallery-thumbswrapper-vertical");
}
self._createTooltip(postFix);
}
};
wijgallery.prototype._calculatePosition = function (offset, w, h, lw, lh, b) {
var self = this;
if(self.thumbPosition === "bottom") {
offset.left = offset.left + (lw - w) / 2 + b;
offset.top = offset.top - h;
} else if(self.thumbPosition === "top") {
offset.left = offset.left + (lw - w) / 2 + b;
offset.top = offset.top + lh + 2 * b;
} else if(self.thumbPosition === "left") {
offset.left = offset.left + lw + 2 * b;
offset.top = offset.top + (lh - h) / 2 + b;
} else if(self.thumbPosition === "right") {
offset.left = offset.left - w;
offset.top = offset.top + (lh - h) / 2 + b;
}
};
wijgallery.prototype._highlightThumb = function (li) {
var self = this, w, h, lw, lh, offset, b, css = [
selectedCss,
self.options.wijCSS.stateActive
].join(' ');
if(li && li.length) {
li.siblings("li." + selectedCss).removeClass(css);
li.addClass(css);
w = self.pointer.outerWidth(true);
h = self.pointer.outerHeight(true);
lw = li.width();
lh = li.height();
offset = li.offset();
//b = li.outerWidth(true)- li.outerWidth();
// get border of li.
b = 5;
self._calculatePosition(offset, w, h, lw, lh, b);
self.pointer.fadeIn(100);
self.pointer.offset(offset);
}
};
wijgallery.prototype._getSelector = function (content, includeTimer) {
var selector, btnPrefix = ".wijmo-wijgallery-button-", controls = ".wijmo-wijpager,.wijmo-wijgallery-counter";
if(includeTimer) {
controls += ",.wijmo-wijgallery-timerbar";
}
if(content === "next" || content === "previous") {
selector = btnPrefix + content;
} else if(content === "controls") {
selector = controls;
} else {
selector = controls + "," + btnPrefix + "next," + btnPrefix + "previous";
}
return selector;
};
wijgallery.prototype._showControls = function (content) {
var self = this, selector;
selector = self._getSelector(content, !self.isPlaying && self.timer);
self.frame.find(selector).stop(true, true).fadeIn(400, function () {
$(this).css('opacity', '');
});
};
wijgallery.prototype._hideControls = function (content) {
var self = this, selector;
selector = self._getSelector(content, !self.isPlaying && self.timer);
this.frame.find(selector).stop(true, true).fadeOut(600);
};
wijgallery.prototype._createPager = function () {
var self = this, o = self.options, pager, display = o.thumbsDisplay, pageCount = 1, pageIndex = self.currentIdx, currentIdx = self.currentIdx, position = {
collision: "none",
of: self.container,
my: "right top",
at: "right bottom"
};
if(o.thumbnails) {
pager = $("<div></div>").appendTo(self.thumbs);
if(display !== 0) {
pageCount = Math.ceil(self._count / display);
pageIndex = Math.ceil(self.currentIdx / display);
}
self.pager = pager.wijpager({
pageCount: pageCount,
pageIndex: pageIndex,
pageButtonCount: pageCount,
mode: "numeric",
pageIndexChanged: function (event, ui) {
var idx = ui.newPageIndex;
if(currentIdx < idx * display || currentIdx >= (idx + 1) * display) {
self.thumbs[self.thumbWidgetName]("scrollTo", (idx * display));
}
event.preventDefault();
}
}).css({
position: "absolute"
});
} else {
pager = $("<div></div>").appendTo(self.container);
self.pager = pager.wijpager({
pageCount: self._count,
pageIndex: self.currentIdx,
pageButtonCount: self._count,
mode: "numeric",
pageIndexChanged: function (event, ui) {
var idx = ui.newPageIndex;
self._show(idx);
}
}).css({
position: "absolute"
});
$.extend(position, o.pagingPosition);
self.pager.addClass("wijmo-wijgallery-pager").position(position);
}
};
wijgallery.prototype._createBtn = function (btnClass, itemClass) {
var btn = $(btnHtml), o = this.options;
btn.addClass(o.wijCSS.stateDefault + ' ' + btnClass).attr("role", "button").bind("mouseover" + this.widgetName, function () {
if($(this).hasClass(o.wijCSS.stateDisabled)) {
return;
}
$(this).addClass(o.wijCSS.stateHover);
}).bind("mouseout" + this.widgetName, function () {
if($(this).hasClass(o.wijCSS.stateDisabled)) {
return;
}
$(this).removeClass(o.wijCSS.stateHover);
});
btn.children("span:eq(0)").addClass(o.wijCSS.icon + ' ' + itemClass);
return btn;
};
wijgallery.prototype._createTimer = function () {
var self = this, o = self.options;
self._createPausePlay();
self.progressBar = $("<div></div>").addClass("wijmo-wijgallery-timerbar-inner " + o.wijCSS.cornerAll).css({
width: "0%"
}).attr("role", "progressbar");
self.timer = $("<div></div>").addClass("wijmo-wijgallery-timerbar " + o.wijCSS.cornerAll).appendTo(self.frame).append(self.progressBar).append(self.playPauseBtn);
};
wijgallery.prototype._createPausePlay = function () {
var self = this, o = self.options;
self.playPauseBtn = $(self._createBtn(btnCss, o.autoPlay ? o.wijCSS.iconPause : o.wijCSS.iconPlay)).bind("click." + self.widgetName, function () {
if(!$(this).hasClass(o.wijCSS.stateDisabled)) {
var icon = $(this).children("span:eq(0)");
self[icon.hasClass(o.wijCSS.iconPlay) ? "play" : "pause"]();
}
});
};
wijgallery.prototype._show = function (index) {
var self = this, img = self.images[index], iframeContent, lastContent, newImg, size = self._getFrameSize(), o = self.options, m = o.mode;
if(self.currentIdx === index) {
return;
}
if(img && $.isPlainObject(img)) {
self.loading.delay(500).fadeIn(100);
newImg = self.last.children("img,div." + flashCss);
if(newImg.length) {
newImg.remove();
}
if(m === "swf" || m === "flv") {
self.last.hide();
self.current.empty();
self._wrapFlash(self.current, m, img.url);
self.picture = self.current.children("div." + flashCss);
self._setCurrentStates(index);
//self.picture.fadeIn(100);
self.loading.stop().hide();
self._thumbsScroll(index);
} else if(m === "img") {
if(self.picture && self.picture.length) {
self.last.append(self.picture.unbind("load"));
}
self.current.hide();
self.last.show();
self.picture = $("<img>").attr({
src: img.url,
alt: img.title
}).appendTo(self.current).data("itemIndex", index);
if($.browser.msie && self.picture[0].hasAttribute("complete")) {
self._imageLoaded(self, size);
} else {
self.picture.bind("load", function () {
self._imageLoaded(self, size);
});
}
} else if(m === "iframe") {
if(self.current.is(":hidden")) {
iframeContent = self.current;
lastContent = self.last;
} else {
iframeContent = self.last;
lastContent = self.current;
}
self.picture = $('<iframe></iframe>').addClass('wijmo-wijgallery-iframe').attr({
frameborder: '0',
marginwidth: '0',
marginheight: '0',
scrolling: 'auto',
allowtransparency: 'true',
src: img.url
}).hide().appendTo(iframeContent).data("itemIndex", index).bind('load', function () {
var pic = $(this), index = pic.data("itemIndex");
self.loading.stop().hide();
if(self.pointer) {
self.pointer.fadeOut(100);
}
self._setCurrentStates(index);
if(index !== undefined) {
if(o.showCaption) {
//self._loadCaption(self.images[index]);
//self._showCaption(self.images[index]);
}
pic.show();
lastContent.fadeOut(function () {
lastContent.empty();
});
iframeContent.fadeIn();
}
});
}
}
};
wijgallery.prototype._imageLoaded = function (self, size) {
var pic = self.picture.attr("role", "img"), index = pic.data("itemIndex"), w = pic[0].naturalWidth || pic.width(), h = pic[0].naturalHeight || pic.height(), image = self.images[index];
self.loading.stop().hide();
if(self.pointer) {
self.pointer.fadeOut(100);
}
if(w > size.w || h > size.h) {
if(w / h > size.w / size.h) {
pic.css({
width: "100%"
});
} else {
pic.css({
height: "100%"
});
}
} else if(w < size.w && h < size.h) {
pic.addClass(self.options.wijCSS.stateDefault).addClass("wijmo-wijgallery-small-image");
}
if(index !== undefined) {
if(self.options.showCaption && self.caption) {
self._loadCaption(image);
}
self._animate(index);
}
};
wijgallery.prototype._animate = function (index) {
var self = this, o = self.options, animate = o.transitions, hori = o.thumbnailOrientation === "horizontal", width, height, wrapper, half, data, forward, effect = animate.animated, duration = animate.duration;
//if (!self.last.find("img").attr("src") &&
//!self.last.find("div."+flashCss)) {
if(!self.last.children().length) {
self._setCurrentStates(index);
self.last.hide();
self.current.show();
return;
}
data = {
index: self.currentIdx,
to: index,
toImg: self.images[index]
};
if(!self._trigger("beforeTransition", null, data)) {
return;
}
if(effect) {
if(effect === "slide") {
width = self.size.w;
height = self.size.h;
self.current.show();
forward = self.currentIdx > index ? true : false;
wrapper = $.createWrapper(self.last).css({
overflow: 'hidden',
width: hori ? width * 2 : width,
height: hori ? height : height * 2,
left: hori ? (forward ? -width : 0) : 0,
top: hori ? 0 : (forward ? -height : 0)
});
wrapper[forward ? "prepend" : "append"](self.current);
wrapper.animate({
left: hori ? (forward ? 0 : -width) : 0,
top: hori ? 0 : (forward ? 0 : -height)
}, duration, function () {
if(self.last.parent().is(".ui-effects-wrapper")) {
self.last.unwrap();
}
self.last.hide();
self._setCurrentStates(index);
});
} else {
if($.mobile) {
half = duration / 2;
self.last.fadeOut(half, function () {
self.current.stop(true, true).fadeIn(half, function () {
self._setCurrentStates(index);
});
});
} else {
if(effect === "explode" || effect === "scale" || effect === "blind" || effect === "fold") {
self.current.css({
position: "absolute"
});
self.current.stop(true, true).show(effect, duration, function () {
self.last.hide();
self._setCurrentStates(index);
});
} else if(effect === "size") {
self.last.hide();
self.current.stop(true, true).show(effect, duration, function () {
self.last.hide();
self._setCurrentStates(index);
});
} else {
half = duration / 2;
self.last.hide(effect, half, function () {
self.last.hide();
self.current.stop(true, true).show(effect, half, function () {
self._setCurrentStates(index);
});
});
}
}
}
} else {
self.last.hide();
self.current.show();
self._setCurrentStates(index);
}
self._thumbsScroll(index);
};
wijgallery.prototype._thumbsScroll = function (index) {
var scrollIdx, self = this, o = self.options;
if(self.thumbs && self.thumbs[self.thumbWidgetName]) {
if(o.scrollWithSelection) {
scrollIdx = index - Math.ceil(o.thumbsDisplay / 2) + 1;
self.thumbs[self.thumbWidgetName]("scrollTo", scrollIdx);
} else {
if(index > (o.thumbsDisplay + self.currentThumbIdx - 1)) {
self.thumbs[self.thumbWidgetName]("scrollTo", index - o.thumbsDisplay + 1);
} else if(index < self.currentThumbIdx) {
self.thumbs[self.thumbWidgetName]("scrollTo", index);
}
}
}
};
wijgallery.prototype._setCurrentStates = function (index) {
var self = this, o = self.options, shouldPlay, data, last;
last = self.currentIdx;
self.currentIdx = index;
shouldPlay = (index + 1) < self._count;
if(self.isPlaying && shouldPlay) {
self.timeout = null;
self.isPlaying = false;
self._play();
} else if(self.progressBar) {
self.pause();
}
// add disable to play btn.
if((index + 1) >= self._count) {
self.nextBtn.add(self.playPauseBtn).removeClass(o.wijCSS.stateHover).addClass(o.wijCSS.stateDisabled);
} else {
self.nextBtn.add(self.playPauseBtn).removeClass(o.wijCSS.stateDisabled);
}
if(index <= 0) {
self.previousBtn.removeClass(o.wijCSS.stateHover).addClass(o.wijCSS.stateDisabled);
} else {
self.previousBtn.removeClass(o.wijCSS.stateDisabled);
}
if(o.showCaption) {
self._showCaption(self.images[index]);
}
if(self.thumbs && self.thumbs[self.thumbWidgetName]) {
self.activeLi = self.thumbs.find(carouselItem).eq(index);
if(!self.isScrolling) {
self._highlightThumb(self.activeLi);
}
} else if(self.pager) {
if(self.pager.is(":wijmo-wijpager")) {
self.pager.wijpager("option", "pageIndex", index);
}
}
self._refreshCounter();
self._clearCss();
data = {
last: last,
index: self.currentIdx,
toImg: self.images[self.currentIdx]
};
self._trigger("afterTransition", null, data);
};
wijgallery.prototype._clearCss = function () {
this.current.css({
position: "",
visibility: ""
});
};
wijgallery.prototype._resetState = function () {
var self = this;
self._stopAnimation();
if(self.isPlaying && self.progressBar) {
self.progressBar.stop();
self.progressBar.css({
width: "0%"
});
}
};
wijgallery.prototype._stopAnimation = function () {
var self = this, wrapper;
wrapper = self.content.find(".ui-effects-wrapper");
if(wrapper.length) {
wrapper.stop(true, true);
}
self.current.stop(true, true);
self.last.stop(true, true);
};
wijgallery.prototype.count = /**
* Returns a count of the number of items in the gallery.
* @returns {number} The number of items in the gallery
*/
function () {
return this._count;
};
wijgallery.prototype._wijdestroy = function () {
var self = this, wijCSS = self.options.wijCSS;
self.frame.unwrap().remove();
if(self.options.thumbnails) {
if($[self.namespace][self.thumbWidgetName]) {
self.thumbs[self.thumbWidgetName]("destroy");
self.element.find("li").unbind().removeClass(wijCSS.stateActive).filter("." + selectedCss).removeClass(selectedCss);
self.thumbs.children("ul").unwrap().unwrap();
}
} else {
if(self.pager && self.pager.length) {
self.pager.remove();
}
self.element.find("ul").css({
display: ""
});
}
if(self.pointer) {
self.pointer.remove();
}
self.element.removeClass([
baseCss,
wijCSS.widget,
wijCSS.content,
wijCSS.cornerAll
].join(' '));
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
};
wijgallery.prototype.destroy = /**
* Removes the wijgallery functionality completely. This returns the element to its pre-init state.
*/
function () {
this._wijdestroy();
$.Widget.prototype.destroy.apply(this);
};
wijgallery.prototype.show = /**
* Shows the picture at the specified index.
* @example $("#element").wijgallery("show", 1);
* @param {number} index The zero-based index of the picture to show.
*/
function (index) {
var self = this;
self._resetState();
self._show(index);
};
wijgallery.prototype.next = /**
* Shows the next picture.
*/
function () {
var self = this, idx;
self._resetState();
idx = self.currentIdx + 1;
if(idx < self._count) {
self._show(idx);
}
};
wijgallery.prototype.previous = /**
* Shows the previous picture.
*/
function () {
var self = this, idx;
self._resetState();
idx = self.currentIdx - 1;
if(idx >= 0) {
self._show(idx);
}
};
wijgallery.prototype.play = /**
* Starts automatically displaying each of the images in order.
*/
function () {
this._play();
};
wijgallery.prototype._play = function (isFirst) {
var self = this, o = self.options;
if(self.isPlaying || o.disabled) {
return;
}
if(o.interval === 0) {
return self.pause();
}
if(isFirst) {
//if called by autoplay, images will be played after first image loaded.
self.isPlaying = true;
return;
}
if(o.showTimer && self.progressBar) {
self.progressBar.css({
width: "0%"
});
self.playPauseBtn.children("span:eq(0)").removeClass(o.wijCSS.iconPlay).addClass(o.wijCSS.iconPause);
self.progressBar.animate({
width: "100%"
}, o.interval, null, function () {
self._show(self.currentIdx + 1);
});
} else {
if(self.timeout) {
return;
}
self.timeout = window.setTimeout(function () {
if(self.timerCount <= 1) {
//ensure only one timer call "next" at same time.
self.next();
}
self.timerCount--;
}, o.interval);
self.timerCount++;
}
self.isPlaying = true;
};
wijgallery.prototype.pause = /**
* Stops automatically displaying the images in order.
*/
function () {
var self = this, o = self.options;
if(o.showTimer && self.progressBar) {
self.progressBar.stop();
self.progressBar.css({
width: "0%"
});
self.playPauseBtn.children("span:eq(0)").removeClass(o.wijCSS.iconPause).addClass(o.wijCSS.iconPlay);
} else {
if(self.timeout === null) {
return;
}
window.clearTimeout(self.timeout);
self.timeout = null;
}
self.isPlaying = false;
};
wijgallery.prototype.add = /**
* Adds a custom item with specified index.
* The first parameter is the new item to add,
* it should be a jQuery Element or HTML string.
* The second parameter is the index of item to add ,
* If no index specified the item will be added at the last of item collection.
* @example
* $("#element").wijgallery("add", "<li><img..></li>", index);
* @param {string|jQuery} ui The node content or innerHTML.
* @param {number} index Specified the postion to insert at.
*/
function (ui, index) {
var self = this, item, idx, data;
if(typeof ui === "string") {
item = $(ui);
data = self._initLi(item);
} else if(ui.jquery) {
item = ui;
data = self._initLi(item);
} else if($.isPlainObject(ui)) {
data = ui;
} else {
return;
}
//image
if(!index || index > self._count) {
idx = self._count;
} else if(index < 0) {
idx = 0;
} else {
idx = index;
}
self.images.splice(idx, 0, data);
self._count++;
if(self.thumbs && self.thumbs[self.thumbWidgetName]) {
self.thumbs[self.thumbWidgetName]("add", item, index);
}
};
wijgallery.prototype.remove = /**
* Removes the item at specified index.
* The parameter is the index of item to add ,
* If no index specified the last item will be removed.
* @example
* $("#element").wijgallery("remove", index);
* @param {number} index Specified which item should be removed.
*/
function (index) {
var self = this, idx;
if(isNaN(index) || index > self._count) {
idx = self._count;
} else if(index < 0) {
idx = 0;
} else {
idx = index;
}
self.images.splice(idx, 1);
self._count--;
if(self.thumbs && self.thumbs[self.thumbWidgetName]) {
self.thumbs[self.thumbWidgetName]("remove", index);
}
if(self.currentIdx == index) {
self.current.children("img").remove();
self.last.children("img").remove();
self.picture = null;
self.currentIdx = -1;
self.show(index);
} else if(self.currentIdx > index) {
var ci = self.currentIdx;
self.currentIdx = -1;
self.show(ci);
}
};
wijgallery.prototype._getExt = function (url) {
var ext, m, regExt = /[0-9a-z]+$/i, q = url.indexOf("?");
if(q > -1) {
url = url.substring(0, q);
}
m = url.match(regExt);
if(m) {
ext = m[0].toLowerCase();
}
return ext;
};
wijgallery.prototype._getPlayerName = function (url) {
if(url.indexOf("#") === 0 || (url.indexOf("#") > 0 && url.indexOf(document.location.href) === 0)) {
return "inline";
}
var imgExt = [
"bmp",
"gif",
"jpg",
"jpeg",
"png"
], swfExt = [
"swf"
], flvExt = [
"flv",
"m4v"
], qtExt = [
"dv",
"mov",
"moov",
"movie",
"mp4",
"avi",
"mpg",
"mpeg"
], wmpExt = [
"asf",
"avi",
"mpg",
"mpeg",
"wm",
"wmv"
], ext = this._getExt(url);
if(ext) {
if($.inArray(ext, imgExt) >= 0) {
return "img";
}
if($.inArray(ext, swfExt) >= 0) {
return "swf";
}
if($.inArray(ext, flvExt) >= 0) {
return "flv";
}
if($.inArray(ext, wmpExt) >= 0) {
return "wmp";
}
if($.inArray(ext, qtExt) >= 0) {
return "qt";
}
}
return "unknown";
};
wijgallery.prototype._wrapFlash = function (container, type, url) {
var self = this, lo = self.options, swf = url, wrapper, width = '100%', height = '100%', express = lo.flashInstall, version = lo.flashVersion, flashvars = lo.flashVars, params = lo.flashParams, id = self._newId();
if(type === "flv") {
swf = lo.flvPlayer;
flashvars = $.extend({
file: url,
width: width,
height: height,
autostart: (lo.autoPlayMovies ? 'true' : 'false'),
controlbar: (lo.showMovieControls ? 'bottom' : "none"),
backcolor: "0x000000",
frontcolor: "0xCCCCCC",
lightcolor: "0x557722"
}, lo.flashVars);
params = $.extend({
autostart: (lo.autoPlayMovies ? 'true' : 'false'),
allowscriptaccess: 'always'
}, lo.flashParams);
}
wrapper = $('<div/>').addClass(flashCss).appendTo(container);
$('<div/>').css({
width: '100%',
height: '100%',
overflow: 'hidden'
}).attr('id', id).appendTo(wrapper);
S.flash.embedSWF(swf, id, width, height, version, express, flashvars, params);
};
wijgallery.prototype._newId = function () {
var chars = "a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z", charArray = [], id = "", i;
charArray = chars.split("|");
for(i = 0; i < 16; i++) {
id += charArray[Math.round(Math.random() * 25)];
}
return id;
};
return wijgallery;
})(wijmo.wijmoWidget);
gallery.wijgallery = wijgallery;
wijgallery.prototype.thumbWidgetName = "wijcarousel";
var wijgallery_options = (function () {
function wijgallery_options() {
/**
* wijMobileCSS
* @ignore
*/
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body-a",
stateDefault: "ui-btn-up-a",
stateHover: "ui-btn-down-a",
stateActive: "ui-btn-down-b",
iconPlay: "ui-icon-arrow-r",
iconPause: "ui-icon-grid"
};
/** Selector option for auto self initialization.
* This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijgallery')";
/** Allows pictures to be played automatically.
* @example $("#element").wijgallery( { autoPlay: true } );
*/
this.autoPlay = false;
/** If set to true, the thumbnails will auto
* scrolled after you select the image.
* @example $("#element").wijgallery( { scrollWithSelection: true } );
*/
this.scrollWithSelection = false;
/** Determines if the timer bar should be shown.
* @example $("#element").wijgallery( { showTimer: false } );
*/
this.showTimer = true;
/** Determines the time span between 2 pictures showing in autoplay mode.
* @example $("#element").wijgallery( { interval: 3000 } );
*/
this.interval = 5000;
/** Determines whether the caption of items should be shown.
* @example $("#element").wijgallery( { showCaption: true } );
*/
this.showCaption = true;
/** Determines whether to show captions for the thumbnails in the gallery.
* @example $("#element").wijgallery( { showThumbnailCaptions: true } );
*/
this.showThumbnailCaptions = false;
/** An object collection that contains the data of the gallery.
* @example
* $("#element").wijgallery( { data: [{
* url: "../thumb/image1.jpg",
* thumbUrl: "../images/image1.jpg",
* title: "<span>Word Caption 1</span>"
* },{
* imageUrl: "../thumb/image2.jpg",
* linkUrl: "../images/image2.jpg",
* title: "<span>Word Caption 2</span>"
* }] } );
*/
this.data = [];
/** Determines whether the custom control should be shown.
* @example $("#element").wijgallery( { showControls: true } );
*/
this.showControls = false;
/** Determines the innerHTML of the custom control.
* @example $("#element").wijgallery( { control: "<div>Blah</div>" } );
*/
this.control = "";
/** A value that indicates the position settings for the custom control.
* @type {object}
* @example $("#element").wijgallery( {
* controlPosition: {
* my: 'left bottom',
* at: 'right top',
* offset: '0 0'}
* });
*/
this.controlPosition = {
};
/** Determines whether the controls should be shown after the dom element is created or hovered on.
* @example $("#element").wijgallery( {
* showCounter: false
* });
*/
this.showCounter = true;
/** Determines the text format of counter.
* @remarks
* '[i]' and '[n]' are built-in parameters represents
* the current page index and the number of pages.
* @example
* $("#id").wijgallery({
* counter: '[i]/[n]'
* });
*/
this.counter = "[i] of [n]";
/** Determines if the pager should be shown.
* @example $("#element").wijgallery( {
* showPager: false
* } );
*/
this.showPager = false;
/** Determines the position of the pager.
* @type {object}
* @example $("#element").wijgallery( {
* pagingPosition: { my:{ },at:{ } } ;
* } );
*/
this.pagingPosition = {
};
/** Determines the orientation of the thumbnails. Possible values are: "vertical" and "horizontal".
* @example $("#element").wijgallery( {
* thumbnailOrientation: "vertical"
* } );
*/
this.thumbnailOrientation = "horizontal";
/** Determines the direction of the thumbnails. Possible values are: "before" and "after".
* @example $("#element").wijgallery( {
* thumbnailOrientation: "before"
* } );
*/
this.thumbnailDirection = "after";
//
/** A value that determines the settings of the animation effect to be used when the wijgallery is scrolling.
* @type {object}
* @example $("#element").wijgallery( {
* transitions: {
* animated: "slide",
* duration: 1000
* }
* } );
*/
this.transitions = {
animated: "slide",
duration: 1000,
easing: null
};
/** Determines whether the controls should be shown after the dom element is created or hovered on.
* @example $("#element").wijgallery( { showControlsOnHover: true } );
*/
this.showControlsOnHover = true;
/** Determines how many thumbnails should be displayed.
* @example $("#element").wijgallery( { thumbsDisplay: 6 } );
*/
this.thumbsDisplay = 5;
/** Determines the length of the thumbnails.
* @example $("#element").wijgallery( { thumbsLength: 6 } );
*/
this.thumbsLength = 100;
/** This is the beforeTransition event handler. It is a function called before transitioning to another image.
* @event
* @dataKey {number} index The index of the current image.
* @dataKey {number} to The index of the image that will scrolled to.
*/
this.beforeTransition = null;
/** The afterTransition event handler. A function called after the transition is over.
* @event
* @dataKey {number} index The index of the current image.
* @dataKey {number} to The index of the image that will scrolled to.
*/
this.afterTransition = null;
/** The loadCallback event handler. A function called after the dom element is created.
* @event
* @param {object} data The node widget that relates to this event.
*/
this.loadCallback = null;
/** Determines whether to turn on the movie controls in movie player.
* @example
* $("#id").wijgallery({
* showMovieControls: false
* });
*/
this.showMovieControls = false;
/** Determines whether to turn on the autoplay option in movie player.
* @example
* $("#id").wijgallery({
* autoPlayMovies: false
* });
*/
this.autoPlayMovies = true;
/** A hash object that contains parameters for flash object.
* @type{object}
* @example
* $("#id").wijgallery({
* flashParams: { allowfullscreen: false }
* });
*/
this.flashParams = {
bgcolor: "#000000",
allowfullscreen: true,
wmode: "transparent"
};
/** A hash object that contains variants for flash object.
* @type {object}
* @example
* $("#id").wijgallery({ flashVars: { width:300, height:400 } });
*/
this.flashVars = {
};
/** Version of flash object.
* @example
* $("#id").wijgallery({ flashVersion: "8.0" })
*/
this.flashVersion = "9.0.115";
/** The relative path and name of the flash vedio player.
* @example
* $("#id").wijgallery({ flvPlayer: "player\\player2.swf " });
*/
this.flvPlayer = 'player\\player.swf';
/** The relative path and name of the flash installation guide.
* @example
* $("#id").wijgallery({ flashInstall: " player\expressInstall2.swf " });
*/
this.flashInstall = 'player\\expressInstall.swf';
/** Determines the display mode of the gallery.
* Possible values: "img", "iframe", "swf", "flv"
* @example
* $("#id").wijgallery({ mode: "swf" });
*/
this.mode = "img";
}
return wijgallery_options;
})();
wijgallery.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijgallery_options());
$.wijmo.registerWidget("wijgallery", wijgallery.prototype);
})(wijmo.gallery || (wijmo.gallery = {}));
var gallery = wijmo.gallery;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/// <reference path="../wijutil/jquery.wijmo.raphael.ts"/>
/// <reference path="../external/declarations/globalize.d.ts"/>
/*
* Depends:
* raphael.js
* globalize.min.js
* jquery.ui.widget.js
* jquery.wijmo.raphael.js
*/
(function (gauge) {
var $ = jQuery;
/** @ignore */
(function (Compass) {
Compass._map = [];
Compass._map[0] = "east";
Compass.east = 0;
Compass._map[1] = "west";
Compass.west = 1;
Compass._map[2] = "south";
Compass.south = 2;
Compass._map[3] = "north";
Compass.north = 3;
})(gauge.Compass || (gauge.Compass = {}));
var Compass = gauge.Compass;
/** @ignore */
var GaugeUtil = (function () {
function GaugeUtil() { }
GaugeUtil.mod360 = function mod360(value) {
var result = value % 360;
if(value < 0) {
result += 360;
}
return result;
};
GaugeUtil.getAngle = function getAngle(p1, pivot, p2) {
var self = this, a = self.distance(pivot, p2), b = self.distance(pivot, p1), c = self.distance(p2, p1), a2 = a * a, b2 = b * b, c2 = c * c, angleRadians = Math.acos((c2 - b2 - a2) / (-2 * b * a));
return Math.round(180 / Math.PI * angleRadians);
};
GaugeUtil.distance = function distance(a, b) {
return Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2));
};
GaugeUtil.log = function log(val, base) {
if(val <= 0) {
return NaN;
}
if(base === 1 || base < 0) {
return NaN;
}
return Math.log(val) / Math.log(base);
};
GaugeUtil.generateValues = function generateValues(from, to, interval) {
var list = [], qty, i;
if(to > from && interval > 0) {
qty = parseInt(((to - from) / interval + 1).toString(), 10);
for(i = 0; i < qty; i++) {
list.push(from + i * interval);
}
} else if(interval === 0) {
list.push(from);
}
return list;
};
GaugeUtil.isInRange = function isInRange(value, min, max) {
return (value >= min && value <= max) || (value <= min && value >= max);
};
GaugeUtil.paintMarker = function paintMarker(canvas, marker, x, y, length, width, isHorizontal) {
var ele;
if(marker === "rect") {
return canvas.rect(x - length / 2, y - width / 2, length, width);
} else {
if(isHorizontal) {
if(marker === "tri") {
ele = canvas.isoTri(x, y, length, width);
} else {
ele = canvas.paintMarker(marker, x, y, width);
}
} else {
ele = canvas.paintMarker(marker, x, y, length);
}
return ele;
}
};
GaugeUtil.formatString = function formatString(str, format) {
if($.isFunction(format)) {
return format.call(this, str);
} else if(format !== "") {
var reg = /\{0(?::((?:n|d|p|c)\d?))?\}/gi, match, formater;
if(reg.test(format)) {
match = format.match(reg);
formater = "$1";
return format.replace(/\{0(?::(?:(?:n|d|p|c)\d?))?\}/gi, Globalize.format(str, formater));
}
}
return str;
};
GaugeUtil.getPositionByAngle = function getPositionByAngle(cx, cy, r, angle) {
var point = {
x: 0,
y: 0
}, rad = Raphael.rad(angle);
point.x = cx - r * Math.cos(rad);
point.y = cy - r * Math.sin(rad);
return point;
};
GaugeUtil.donut = function donut(canvas, cx, cy, outerR, innerR, startAngle, endAngle) {
var getPosByAngle = this.getPositionByAngle, outerS = getPosByAngle(cx, cy, outerR, startAngle), outerE = getPosByAngle(cx, cy, outerR, endAngle), innerS = getPosByAngle(cx, cy, innerR, startAngle), innerE = getPosByAngle(cx, cy, innerR, endAngle), largeAngle = endAngle - startAngle > 180, path;
if((endAngle - startAngle) % 360 !== 0) {
path = [
"M",
outerS.x,
outerS.y,
"A",
outerR,
outerR,
0,
+largeAngle,
1,
outerE.x,
outerE.y,
"L",
innerE.x,
innerE.y,
"A",
innerR,
innerR,
0,
+largeAngle,
1,
innerS.x,
innerS.y,
"L",
outerS.x,
outerS.y,
"z"
];
canvas.path(path);
} else {
canvas.circle(cx, cy, outerR);
}
};
return GaugeUtil;
})();
gauge.GaugeUtil = GaugeUtil;
Raphael.fn.isoTri = function (x, y, width, height, compass) {
var x1 = x, y1 = y + height / 2, x2 = x + width, y2 = y, x3 = x + width, y3 = y + height, arrPath;
if(compass == Compass.north) {
x1 = x;
y1 = y;
x2 = x - width / 2;
y2 = y + height;
x3 = x + width / 2;
y3 = y + height;
} else if(compass === Compass.east) {
x1 = x - width / 2;
y1 = y - height / 2;
x2 = x - width / 2;
y2 = y + height / 2;
x3 = x + width / 2;
y3 = y;
} else if(compass === Compass.west) {
x1 = x - width / 2;
y1 = y;
x2 = x + width / 2;
y2 = y - height / 2;
x3 = x + width / 2;
y3 = y + height / 2;
}
arrPath = [
"M",
x1,
y1,
"L",
x2,
y2,
"L",
x3,
y3,
"z"
];
return this.path(arrPath.join(" "));
};
/**
* @widget
*/
var wijgauge = (function (_super) {
__extends(wijgauge, _super);
function wijgauge() {
_super.apply(this, arguments);
}
wijgauge.prototype._create = function () {
var self = this, o = self.options, newEle;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
if(self.element.is(":hidden") && self.element.wijAddVisibilityObserver) {
self.element.wijAddVisibilityObserver(function () {
self.redraw();
if(self.element.wijRemoveVisibilityObserver) {
self.element.wijRemoveVisibilityObserver();
}
}, "wijgauge");
}
if(isNaN(o.width)) {
self._setDefaultWidth();
}
if(isNaN(o.height)) {
self._setDefaultHeight();
}
self._setDefaultWidthHeight();
if(o.disabled) {
self.disable();
}
// handle the juice's function type
if(o.face && o.face.template && typeof o.face.template === "string" && window[o.face.template]) {
o.face.template = window[o.face.template];
}
if(o.pointer && o.pointer.template && typeof o.pointer.template === "string" && window[o.pointer.template]) {
o.pointer.template = window[o.pointer.template];
}
if(o.cap && o.cap.template && typeof o.cap.template === "string" && window[o.cap.template]) {
o.cap.template = window[o.cap.template];
}
self.element.addClass(o.wijCSS.widget).toggleClass(o.wijCSS.stateDisabled, o.disabled);
// if fail to create canvas, move element to body and recreate it
// the issue that creating canvas in ie9 when element is invisible.
try {
self.canvas = Raphael(self.element[0], o.width, o.height);
} catch (e) {
var displayCss = self.element.css("display");
newEle = $("<div></div>").insertBefore(self.element).append(self.element);
self.element.addClass("ui-helper-hidden-accessible").appendTo($('body'));
if(displayCss === "none") {
self.element.css("display", "block");
}
self.canvas = Raphael(self.element[0], o.width, o.height);
self.element.appendTo(newEle).unwrap().removeClass("ui-helper-hidden-accessible");
if(displayCss === "none") {
self.element.css("display", "none");
}
}
self._autoCalculate();
self._draw();
};
wijgauge.prototype._setDefaultWidth = function () {
};
wijgauge.prototype._setDefaultHeight = function () {
};
wijgauge.prototype._setDefaultWidthHeight = function () {
var self = this, ele = self.element, o = self.options, style = ele.get(0).style, width = style.width, height = style.height;
if(width !== "") {
o.width = ele.width();
}
if(height !== "") {
o.height = ele.height();
}
};
wijgauge.prototype._autoCalculate = function () {
};
wijgauge.prototype._setOption = function (key, value) {
var self = this, o = self.options, oldValue = o[key];
if(key === "disabled") {
self._handleDisabledOption(value, self.element);
_super.prototype._setOption.call(this, key, value);
} else if(key === "value") {
if(self._trigger("beforeValueChanged", null, {
newValue: value,
oldValue: oldValue
})) {
_super.prototype._setOption.call(this, key, value);
self._set_value(value, oldValue);
}
self._trigger("valueChanged", null, {
newValue: value,
oldValue: oldValue
});
} else {
_super.prototype._setOption.call(this, key, value);
if($.isPlainObject(value)) {
o[key] = $.extend({
}, oldValue, value);
}
if(o.radius === "auto") {
self._autoCalculate();
self.redraw();
return;
}
if(self["_set_" + key]) {
self["_set_" + key](value, oldValue);
}
}
};
wijgauge.prototype._set_value = function (value, oldValue) {
this._setPointer();
};
wijgauge.prototype._set_max = function () {
this._redrawMarksAndLabels();
this._set_ranges();
this._setPointer();
};
wijgauge.prototype._set_min = function () {
this._redrawMarksAndLabels();
this._set_ranges();
this._setPointer();
};
wijgauge.prototype._set_width = function () {
this.redraw();
};
wijgauge.prototype._set_height = function () {
this.redraw();
};
wijgauge.prototype._set_isInverted = function () {
this.redraw();
};
wijgauge.prototype._set_tickMajor = function () {
this._redrawMarksAndLabels();
};
wijgauge.prototype._set_tickMinor = function () {
this._redrawMarksAndLabels();
};
wijgauge.prototype._set_pointer = function () {
var self = this;
if(self.pointer) {
self.pointer.wijRemove();
self.pointer = null;
}
self._paintPointer();
self._setPointer();
};
wijgauge.prototype._set_islogarithmic = function () {
var self = this;
self._redrawMarksAndLabels();
self._setPointer();
};
wijgauge.prototype._set_logarithmicBase = function () {
var self = this;
self._redrawMarksAndLabels();
self._setPointer();
};
wijgauge.prototype._set_labels = function () {
this._redrawMarksAndLabels();
};
wijgauge.prototype._set_margin = function (value, oldValue) {
if(value !== oldValue) {
this.redraw();
}
};
wijgauge.prototype._set_marginTop = function (value, oldValue) {
this._set_margin(value, oldValue);
};
wijgauge.prototype._set_marginBottom = function (value, oldValue) {
this._set_margin(value, oldValue);
};
wijgauge.prototype._set_marginLeft = function (value, oldValue) {
this._set_margin(value, oldValue);
};
wijgauge.prototype._set_marginRight = function (value, oldValue) {
this._set_margin(value, oldValue);
};
wijgauge.prototype._set_ranges = function () {
var self = this;
self._removeRanges();
self._paintRanges();
self._resetElementPosition();
};
wijgauge.prototype._set_face = function () {
var self = this;
if(self.face) {
self.face.wijRemove();
self.face = null;
self._paintFace();
self._resetElementPosition(true);
}
};
wijgauge.prototype._clearState = function () {
var self = this;
self.labels = [];
self.majorMarks = [];
self.minorMarks = [];
self.face = null;
self.pointer = null;
};
wijgauge.prototype._resetElementPosition = //when redraw the range or face or pointer, reset the z-index of the elements.
function (resetRangePosition) {
var self = this;
if(resetRangePosition && self.ranges) {
$.each(self.ranges, function (i, n) {
n.toFront();
});
}
if(self.majorMarks) {
$.each(self.majorMarks, function (i, mark) {
mark.toFront();
});
}
if(self.minorMarks) {
$.each(self.minorMarks, function (i, mark) {
mark.toFront();
});
}
if(self.labels) {
$.each(self.labels, function (i, label) {
label.toFront();
});
}
if(self.pointer) {
self.pointer.toFront();
}
if(self.cap) {
self.cap.toFront();
}
};
wijgauge.prototype._redrawMarksAndLabels = function () {
var self = this;
self._removeMarksAndLabels();
self._drawMarksAndLabels();
};
wijgauge.prototype._removeMarksAndLabels = function () {
var self = this;
$.each(self.labels, function (i, n) {
n.wijRemove();
self.labels[i] = null;
});
$.each(self.majorMarks, function (i, n) {
n.wijRemove();
self.majorMarks[i] = null;
});
$.each(self.minorMarks, function (i, n) {
n.wijRemove();
self.minorMarks[i] = null;
});
};
wijgauge.prototype._drawMarksAndLabels = function () {
var self = this;
self.labels = [];
self.majorMarks = [];
self.minorMarks = [];
self._paintMarks();
};
wijgauge.prototype._handleDisabledOption = function (disabled, ele) {
var self = this;
if(disabled) {
if(!self.disabledDiv) {
self.disabledDiv = self._createDisabledDiv(ele);
}
self.disabledDiv.appendTo("body");
} else {
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
}
};
wijgauge.prototype._createDisabledDiv = function (outerEle) {
var self = this, o = self.options, ele = //Change your outerelement here
outerEle || self.element, eleOffset = ele.offset(), disabledWidth = o.width || ele.outerWidth(), disabledHeight = o.height || ele.outerHeight(), disabledDiv;
disabledDiv = $("<div></div>").css({
"z-index": "99999",
position: "absolute",
width: disabledWidth,
height: disabledHeight,
left: eleOffset.left,
top: eleOffset.top
});
if(Raphael.vml) {
disabledDiv.addClass(o.stateDisabled).css("background-color", "#fff");
}
return disabledDiv;
};
wijgauge.prototype._triggerPainted = function () {
return this._trigger("painted");
};
wijgauge.prototype._draw = function () {
var self = this, o = self.options;
self.pointer = null;
self._innerBbox = {
width: o.width - o.marginLeft - o.marginRight,
height: o.height - o.marginTop - o.marginBottom,
left: o.marginLeft,
top: o.marginTop
};
self.face = self._paintFace();
if(self.ranges) {
self._removeRanges();
}
self._paintRanges();
self._drawMarksAndLabels();
self._paintPointer();
if(self.pointer) {
self._setOffPointerValue();
self._setPointer();
}
$.wijraphael.clearRaphaelCache();
self._triggerPainted();
};
wijgauge.prototype.redraw = /**
* Redraw the gauge.
*/
function () {
var self = this, o = self.options;
self.element.empty();
this._clearState();
self.canvas = Raphael(self.element[0], o.width, o.height);
self._draw();
};
wijgauge.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this;
self._unbindEvents(self.majorMarks);
self._unbindEvents(self.minorMarks);
self._unbindEvents(self.labels);
self.element.removeClass("ui-widget").empty();
//Add for fixing bug 16039
if(self.disabledDiv) {
self.disabledDiv.remove();
self.disabledDiv = null;
}
//end for bug 16039
_super.prototype.destroy.call(this);
};
wijgauge.prototype.getCanvas = /**
* Returns a reference to the Raphael canvas object.
* @returns {Raphael Element} Reference to raphael canvas object.
*/
function () {
/// <summary>
/// Returns a reference to the Raphael canvas object.
/// Code example:
/// $("gauge").wijgauge("getCanvas");
/// </summary>
/// <returns type="Raphael">
/// Reference to raphael canvas object.
/// </returns>
return this.canvas;
};
wijgauge.prototype._percentage = function () {
var self = this, o = self.options, max = o.max, min = o.min, value = o.value;
if(isNaN(value)) {
return 0;
}
if(max === min) {
return 1;
}
return (value - min) / (max - min);
};
wijgauge.prototype._valueToLogical = function (value) {
var self = this, o = self.options, min = o.min, max = o.max, logarithmicBase = o.logarithmicBase, linerValue, alpha;
if(value < min) {
return 0;
}
if(max < value) {
return 1;
}
linerValue = (value - min) / (max - min);
if(!o.islogarithmic) {
alpha = linerValue;
} else {
alpha = GaugeUtil.log(1 + (logarithmicBase - 1) * linerValue, o.logarithmicBase);
}
return alpha;
};
wijgauge.prototype._logicalToValue = function (alpha) {
var self = this, o = self.options, max = o.max, min = o.min, linearValue;
if(alpha < 0) {
return min;
}
if(1 <= alpha) {
return max;
}
if(!o.islogarithmic) {
linearValue = alpha;
} else {
if(o.logarithmicBase <= 1) {
return o.min;
}
linearValue = (Math.pow(o.logarithmicBase, alpha) - 1) / (o.logarithmicBase - 1);
//linearValue = Math.pow(alpha, o.logarithmicBase);
}
return min + (max - min) * linearValue;
};
wijgauge.prototype._bindClickEvents = function (eles) {
var self = this;
$.each(eles, function (i, n) {
$(n.node).bind("click." + self.widgetName, function (e) {
self._trigger("click", e, {
ele: n
});
});
});
};
wijgauge.prototype._unbindEvents = function (eles) {
var self = this;
$.each(eles, function (i, n) {
$(n.node).unbind("." + self.widgetName);
});
};
wijgauge.prototype._setOffPointerValue = function () {
};
wijgauge.prototype._setPointer = function () {
//$.wijraphael.clearRaphaelCache();
};
wijgauge.prototype._paintPointer = function () {
};
wijgauge.prototype._paintFace = function () {
};
wijgauge.prototype._paintRanges = function () {
var self = this, o = self.options, ranges = o.ranges || [];
self.ranges = [];
$.each(ranges, function (i, n) {
self._paintRange(n);
});
};
wijgauge.prototype._paintRange = function (range) {
};
wijgauge.prototype._removeRanges = function () {
var self = this;
$.each(self.ranges, function (i, n) {
n.wijRemove();
self.ranges[i] = null;
});
};
wijgauge.prototype._paintMarks = function () {
var self = this, o = self.options, generateValues = GaugeUtil.generateValues, majorMarks = generateValues(o.min, o.max, o.tickMajor.interval), minorMarks = generateValues(o.min, o.max, o.tickMinor.interval), labelInfo = o.labels, showLabels = labelInfo.visible;
if(o.tickMajor.visible) {
$.each(majorMarks, function (i, n) {
self.majorMarks.push(self._paintMark(n, o.tickMajor, true));
if(showLabels) {
self.labels.push(self._paintLabel(n, labelInfo));
}
});
}
if(o.tickMinor.visible) {
$.each(minorMarks, function (i, n) {
var IsInMajor = false;
$.each(majorMarks, function (k, m) {
if(n === m) {
IsInMajor = true;
return false;
}
});
if(!IsInMajor) {
self.minorMarks.push(self._paintMark(n, o.tickMinor, false));
}
});
}
self._bindClickEvents(self.majorMarks);
self._bindClickEvents(self.minorMarks);
self._bindClickEvents(self.labels);
};
wijgauge.prototype._paintMark = function (n, tickMajor, tag) {
};
wijgauge.prototype._paintLabel = function (n, labelInfo) {
};
return wijgauge;
})(wijmo.wijmoWidget);
gauge.wijgauge = wijgauge;
var wijgauge_options = (function () {
function wijgauge_options() {
/**
* Sets the value of the gauge, indicated by the pointer.
* @remarks
* This value must fall between the min and max values that you set.
*/
this.value = 0;
/**
* Sets the maximum value of the gauge.
* @remarks
* Use this option along with min to set the numeric scale of values that are shown on the gauge. This setting limits
* your valid values for other options, such as value and ranges.
*/
this.max = 100;
/**
* Sets the minimum value of the gauge.
* @remarks
* Use this option along with min to set the numeric scale of values that are shown on the gauge. This setting limits
* your valid values for other options, such as value and ranges.
*/
this.min = 0;
/**
* Sets the width of the gauge area in pixels.
*/
this.width = 600;
/**
* Sets the height of the gauge area in pixels.
*/
this.height = 400;
/**
* Sets appearance options for the major tick marks that appear next to the numeric labels around the face of the gauge.
* @example
* $(document).ready(function () {
* $("#radialgauge1").wijradialgauge({
* value: 90,
* tickMajor: {
* position: "inside",
* style: { fill: "purple", stroke: "#1E395B"},
* factor: 2.5,
* marker: 'diamond',
* visible: true,
* offset: 27,
* interval: 20
* }
* });
* });
*/
this.tickMajor = {
position: /**
* A value that indicates the position of the major tick marks in relation to the edge of the face
* @remarks
* Valid Values:
* "inside" -- Draws the major tick marks inside the edge of the face.
* "outside" -- Draws the major tick marks outside the edge of the face.
* "cross" -- Draws the major tick marks centered on the edge of the face.
*/
"inside",
style: /**
* A value that indicates the fill color and outline (stroke) of the major tick mark.
*/
{
fill: "#1E395B",
stroke: "none"
},
factor: /**
* A value that indicates how long to draw the major tick marks as a factor of the default length of the minor tick marks.
*/
2,
visible: /**
* A value that indicates whether to show the major tick mark.
*/
true,
marker: /**
* A value that indicates the shape to use in drawing major tick marks.
* @remarks
* Options are 'rect', 'tri', 'circle', 'invertedTri', 'box', 'cross', 'diamond'.
*/
"rect",
offset: /**
* A value that indicates the distance in pixels from the edge of the face to draw the major tick marks.
* The numeric labels are drawn a few pixels
*/
0,
interval: /**
* A value that indicates the frequency of the major tick marks and their numeric labels.
* @remarks
* A setting of 1 renders a major tick mark for every number between the min and max.This setting is useful when
* the spread between min and max is small. The default setting of 10 renders a major tick mark once every 10 numbers
* between the min and the max. A setting of 100 renders a major tick mark once every 100 numbers between the min
* and max. This setting is useful when the spread between min and max is very large.
*/
10
};
/**
* A value that provides information for the minor tick.
* @example
* //This example renders the minor tick marks as purple crosses, at an interval of once every 2 numbers
* $(document).ready(function () {
* $("#radialgauge1").wijradialgauge({
* value: 90,
* tickMinor: {
* position: "inside",
* style: { fill: "#1E395B", stroke: "purple"},
* factor: 2,
* marker: 'cross',
* visible: true,
* offset: 30,
* interval: 2
* }
* });
* });
*/
this.tickMinor = {
position: /**
* A value that indicates the position of the minor tick marks in relation to the edge of the face.
* @remarks
* Valid Values:
* "inside" -- Draws the minor tick marks inside the edge of the face.
* "outside" -- Draws the minor tick marks outside the edge of the face.
* "cross" -- Draws the minor tick marks centered on the edge of the face.
*/
"inside",
style: /**
* A value that indicates the fill color and outline (stroke) of the minor tick mark.
*/
{
fill: "#1E395B",
"stroke": "none"
},
factor: /**
* A value that indicates how long to draw the minor tick marks as a factor of the default length of the minor
* tick marks, which is half the default length of the major tick marks.
*/
1,
visible: /**
* A value that indicates whether to show the minor tick mark.
*/
false,
marker: /**
* A value that indicates the shape to use in drawing minor tick marks.
* @remarks
* In order to use the 'cross' marker shape, you must specify a color for the stroke setting of the style option.
* The other shapes use the fill setting, but since the cross is not a closed shape, fill has no effect, and
* we must use the outline (stroke) color.
* Options are 'rect', 'tri', 'circle', 'invertedTri', 'box', 'cross', 'diamond'.
*/
"rect",
offset: /**
* A value that indicates the distance in pixels from the edge of the face to draw the minor tick marks.
* @remarks
* By default, they are three pixels in from the major tick marks.
*/
0,
interval: /**
* A value that indicates the frequency of the minor tick marks.
*/
5
};
/**
* A value that includes all settings of the gauge pointer.
* @example
* // The example above renders the pointer as a purple-outlined blue rectangle of 125% the length of the radius
* // by 10 pixels wide, offset back through the cap by 50% of the length of the radius
* $(document).ready(function () {
* $("#radialgauge1").wijradialgauge({
* value: 90,
* cap: {visible: true},
* pointer: {
* length: 1.25,
* offset: 0.5,
* shape: "rect",
* style: { fill: "blue", stroke: "purple"},
* width: 10
* }
* });
* });
*/
this.pointer = {
length: /**
* Sets the length of the pointer as a percentage of the radius(or width/height in lineargauge) of the gauge.
* You can set the length to be greater than the radius(or width/height).
*/
1,
style: /**
* Sets the fill and outline (stroke) colors of the pointer.
*/
{
fill: "#1E395B",
stroke: "#1E395B"
},
width: /**
* Sets the width of the pointer in pixels.
*/
8,
offset: /**
* Sets the percentage of the pointer that is shoved backward through the cap.
*/
0,
shape: /**
* Sets the shape in which to render the pointer: triangular or rectangular.
* @remarks
* Options are 'rect', 'tri'.
*/
"tri",
visible: /**
* A value that indicates whether to show the pointer.
*/
true,
template: /**
* A JavaScript callback value that returns a Raphael element that draws the pointer.
* @remarks
* Use this option to customize the pointer. In order to use the template, you must know how to draw Raphael
* graphics For more information,see the Raphael documentation.
* In radial gauge:
* The pointer template's callback contains two arguments:
* startLocation -- The starting point from which to draw the pointer. This argument is defined by x and y coordinates.
* pointerInfo -- A JSON object that extends the gauge's pointer options:
* offset -- Sets the percentage of the pointer that is shoved backward through the origin.
* length -- Sets the absolute value in pixels of the length of the pointer.
* gaugeBBox -- An object that sets the bounding box of the gauge, as defined by x and y coordinates and width and height options.
*/
null
};
/**
* The islogarithmic option, inherited from the jquery.wijmo.wijgauge.js base class, indicates whether to use logarithmic
* scaling for gauge label numeric values.
* @remarks
* This adds space between tick marks that corresponds to the percentage of change between those numbers rather than
* absolute arithmetic values. You would want to use logarithmic scaling if you were displaying really high numbers,
* because it goes higher much more quickly. A linear scale is more difficult to use if you are displaying really high
* numbers. Note: By default, Wijmo uses a logarithmic base of 10, the common logarithm. See logarithmicBase for
* information on changing this value.
* @example
* // The following code creates a gauge with the number labels and tick marks arranged as in the following image.
* $(document).ready(function () {
* $("#radialgauge1").wijradialgauge({
* value: 90,
* islogarithmic: true
* });
* });
*/
this.islogarithmic = false;
/**
* The logarithmicBase option, inherited from the jquery.wijmo.wijgauge.js base class, indicates the logarithmic
* base to use if the islogarithmic option is set to true. The logarithmic base is the number to raise to produce the exponent.
* @remarks
* For example, with the default base 10, a logarithm of 3 produces 1000, or 10 to the power of 3, or 10³ = 10 x 10 x 10 = 1000.
* If you change the base to 2, a logarithm of 3 produces 8, or 2³ = 2 x 2 x 2 = 8. You can use the natural
* logarithm (using a base of ≈ 2.718) by specifying the value Math.e.
*/
this.logarithmicBase = 10;
/**
* Sets all of the appearance options of the numeric labels that appear around the edge of the gauge.
* @example
* // This example sets the color for the labels to purple, and the font to 14 point, bold, Times New Roman.
* $(document).ready(function () {
* $("#radialgauge1").wijradialgauge({
* value: 90,
* labels: {
* style: {
* fill: "purple",
* "font-size": "14pt",
* "font-weight": "bold",
* "font-family": "Times New Roman"
* }
* }
* });
*});
*/
this.labels = {
format: /**
* A value that indicates the globalized format to use for the labels.
* @remarks
* For more information on using jQuery globalize with Wijmo
* Note: If the value is a function rather than a string, the function formats the value and returns it to the gauge.
*/
"",
style: /**
* A value that indicates the color, weight, and size of the numeric labels.
*/
{
fill: "#1E395B",
"font-size": 12,
"font-weight": "800"
},
visible: /**
* A value that indicates whether to show the numeric labels.
*/
true,
offset: /**
* A value in pixels that indicates the distance of the numeric labels from the outer reach of the pointer.
* @remarks
* A value of 50 pixels renders the labels outside the circular gauge area, cutting off the numbers along
* the top. A value of 0 pixels renders the labels just inside the tick marks.
*/
0
};
/**
* Defines the animation effect, controlling aspects such as duration and easing.
*/
this.animation = {
enabled: /**
* A value that determines whether to show animation.
*/
true,
duration: /**
* The duration option defines the length of the animation effect in milliseconds.
*/
2000,
easing: /**
* The easing option uses Raphael easing formulas to add effects to the animation, such as allowing an item to
* bounce realistically.
* @remarks
* Valid Values (see http://raphaeljs.com/easing.html for easing demos):
*/
">"
};
/**
* Sets or draws the image or shape to use for the face of the gauge and the background area.
* @remarks
* The origin is the center of the gauge, but the image draws from the top left, so we first calculate the starting point
* of the top left based on the origin, and we calculate the width and height based on the radius of the face. The radius
* of the face is half of the min of the width and height.
* Note: The fill property is defined using the Raphael framework. Please see the Raphael Element attr method for more
* information. The face can be filled with a simple color, or a gradient. The default fill is a radial gradient,
* indicated by the r in the fill property.
* @example
* // This example uses a custom image for the face of the gauge. The argument that we name ui in the example is a JSON
* // object. This object has a canvas, which is a Raphael paper object, and we use the image method of the Raphael
* // paper that takes five parameters: source, x, y, width, and height. See the Raphael documentation for more information.
* // We also set the radius to 120 pixels to render it inside the white area of the image.
*$(document).ready(function () {
* $("#radialgauge1").wijradialgauge({
* value: 90,
* radius: 120,
* face: {
* style: {},
* template: function (ui) {
* var url = "images/customGaugeFace.png";
* return ui.canvas.image(url, ui.origin.x -ui.r, ui.origin.y -ui.r, ui.r * 2, ui.r * 2);
* }
* }
* });
*});
*/
this.face = {
style: /**
* A value that indicates the fill color (or gradient), and the outline color and width of the gauge face.
*/
{
fill: "270-#FFFFFF-#D9E3F0",
stroke: "#7BA0CC",
"stroke-width": 4
},
template: /**
* A JavaScript callback value that returns a Raphael element (or set) that draws the gauge face.
* @remarks
* If you are only using one shape, the function returns a Raphael element. If you define multiple shapes,
* have the function create a Raphael set object, push all of the Raphael elements to the set, and return the
* set to wijgauge. In order to use the template, you must know how to draw Raphael graphics.
* For more information, see the Raphael documentation.
* In radial gauge
* The face template's callback contains one argument with the following parameters:
* origin -- The starting point from which to draw the center of the face.This argument is defined by x and y coordinates.
* canvas -- A Raphael paper object that you can use to draw the custom graphic to use as the face.
*/
null
};
/**
* Sets a value in pixels that indicates where to render the top edge of the gauge face.
* @remarks
* Note: If the radius of the gauge is too large to fit within the rectangle defined by the width and height less the
* specified margins, and the radius is set to the default value of "auto," Wijmo automatically resizes the gauge to fit.
*/
this.marginTop = 0;
/**
* Sets a value in pixels that indicates where to render the right edge of the gauge face.
* @remarks
* Note: If the radius of the gauge is too large to fit within the rectangle defined by the width and height less
* the specified margins, and the radius is set to the default value of "auto," Wijmo automatically resizes the gauge to fit.
*/
this.marginRight = 0;
/**
* Sets a value in pixels that indicates where to render the bottom edge of the gauge face.
* @remarks
* Note: If the radius of the gauge is too large to fit within the rectangle defined by the width and height less the
* specified margins, and the radius is set to the default value of "auto," Wijmo automatically resizes the gauge to fit.
*/
this.marginBottom = 0;
/**
* Sets a value in pixels that indicates where to render the left edge of the gauge face.
* @remarks
* Note: If the radius of the gauge is too large to fit within the rectangle defined by the width and height less the
* specified margins, and the radius is set to the default value of "auto," Wijmo automatically resizes the gauge to fit.
*/
this.marginLeft = 0;
/**
* Allows you to create an array of ranges to highlight where values fall within the gauge.
*@remarks
* For example, a red range, a yellow range, and a green range. Each range is drawn in the form of a curved bar.
* You can control every aspect of each range with the settings detailed below.
* Options available for each range include:
* startWidth – Sets the thickness of the left side of the range bar in pixels.
* endWidth – Sets the thickness of the right side of the range bar in pixels.
* startValue – Sets the value at which to begin drawing the range bar.This value must fall between the max and min values you set for the gauge.
* endValue – Sets the value at which to end the range bar.This value must fall between the max and min values you set for the gauge.
* startDistance – Sets the distance from the center of the gauge to draw the left side of the range bar.
* endDistance – Sets the distance from the center of the gauge to draw the right side of the range bar.
* style – Sets the colors to use in drawing the range bar with the following options:
*/
this.ranges = [];
/**
* Determines whether to render the gauge in reverse order, with the numbering going from highest to lowest.
*/
this.isInverted = false;
/**
* Fires before the value changes, this event can be called.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IGaugeEventArgs} data Information about an event
*/
this.beforeValueChanged = null;
/**
* Fires before the value changes, this event can be called.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {IGaugeEventArgs} data Information about an event
*/
this.valueChanged = null;
/**
* Fires before the canvas is painted. This event can be cancelled. "return false;" to cancel the event.
* @event
*/
this.painted = null;
}
return wijgauge_options;
})();
wijgauge.prototype.options = $.extend({
}, wijmo.wijmoWidget.prototype.options, new wijgauge_options());
})(wijmo.gauge || (wijmo.gauge = {}));
var gauge = wijmo.gauge;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../wijgauge/jquery.wijmo.wijgauge.ts"/>
/*globals $, Raphael, jQuery, document, window*/
/*
* Depends:
* jQuery.1.5.1.js
* jQuery.ui.core.js
* jQuery.ui.widget.js
* raphael.js
* jQuery.wijmo.rahpael.js
* jquery.wijmo.wijgauge.js
*/
(function (gauge) {
/**
* @widget
*/
var wijlineargauge = (function (_super) {
__extends(wijlineargauge, _super);
function wijlineargauge() {
_super.apply(this, arguments);
}
wijlineargauge.prototype._setDefaultWidth = function () {
var o = this.options;
o.width = o.orientation === "horizontal" ? 310 : 70;
};
wijlineargauge.prototype._setDefaultHeight = function () {
var o = this.options;
o.height = o.orientation === "horizontal" ? 70 : 310;
};
wijlineargauge.prototype._set_orientation = function () {
var self = this;
self._setDefaultWidth();
self._setDefaultHeight();
self.markBbox = null;
self.redraw();
};
wijlineargauge.prototype._set_xAxisLocation = function () {
this.redraw();
};
wijlineargauge.prototype._set_xAxisLength = function () {
this.redraw();
};
wijlineargauge.prototype._set_yAxisLocation = function () {
this.redraw();
};
wijlineargauge.prototype._clearState = function () {
_super.prototype._clearState.call(this);
if(this.markBbox) {
this.markBbox = null;
}
};
wijlineargauge.prototype._create = function () {
_super.prototype._create.call(this);
this.element.addClass(this.options.wijCSS.linearGauge);
};
wijlineargauge.prototype._paintLabel = function (value, labelInfo) {
var self = this, o = self.options, format = labelInfo.format, style = labelInfo.style, offset = labelInfo.offset, text = value, markOption = self.options.tickMajor, position = markOption.position || "inside", point, textEle, markBbox, labelBBox;
if(format !== "") {
text = gauge.GaugeUtil.formatString(value, format);
}
markBbox = self._getMarkerBbox();
labelBBox = self._getLabelBBox(text);
point = self._valueToPoint(value, 0);
if(o.orientation === "horizontal") {
if(position === "inside") {
point.y = markBbox.y - labelBBox.height;
} else {
point.y = markBbox.y + markBbox.height + labelBBox.height / 2;
}
point.y += offset;
} else {
if(position === "inside") {
point.x = markBbox.x - labelBBox.width / 2;
} else {
point.x = markBbox.x + markBbox.width + labelBBox.width / 2;
}
point.x += offset;
}
textEle = self.canvas.text(point.x, point.y, text);
textEle.attr(style);
$.wijraphael.addClass($(textEle.node), o.wijCSS.linearGaugeLabel);
return textEle;
};
wijlineargauge.prototype._getLabelBBox = function (value) {
var self = this, o = self.options, text, bbox;
text = self.canvas.text(0, 0, value);
text.attr(o.gaugeLableStyle);
bbox = text.wijGetBBox();
text.remove();
return bbox;
};
wijlineargauge.prototype._getMarkerBbox = function () {
var self = this, o = self.options, markOption = o.tickMajor, markEle;
if(!self.markBbox) {
markEle = self._paintMark(0, markOption);
self.markBbox = markEle.wijGetBBox();
markEle.remove();
}
return self.markBbox;
};
wijlineargauge.prototype._paintMark = function (value, opt, isMajor) {
var self = this, o = self.options, marker = opt.marker || "rect", baseLength = marker === "rect" ? 5 : 2, point = self._valueToPoint(value, 0), position = opt.position || "inside", offset = opt.offset || 0, width = isMajor ? 2 : 1, length, markEle, style = $.extend({
}, opt.style);
length = baseLength * opt.factor;
if($.isFunction(marker)) {
return marker.call(self, self.canvas, point, o);
} else {
if(marker === "cross") {
style.stroke = style.fill;
}
if(o.orientation === "horizontal") {
markEle = gauge.GaugeUtil.paintMarker(self.canvas, marker, point.x, point.y, width, length, true);
} else {
markEle = gauge.GaugeUtil.paintMarker(self.canvas, marker, point.x, point.y, length, width);
}
}
markEle.attr(style);
$.wijraphael.addClass($(markEle.node), o.wijCSS.linearGaugeMarker);
self._applyPosition(markEle, position, offset, value);
return markEle;
};
wijlineargauge.prototype._applyPosition = function (ele, position, offset, value) {
var left = 0, top = 0, self = this, isHorizontal = self.options.orientation === "horizontal", bbox = ele.wijGetBBox();
switch(position) {
case "inside":
if(isHorizontal) {
top -= bbox.width / 2 + offset;
} else {
left -= bbox.width / 2 + offset;
}
break;
case "outside":
if(isHorizontal) {
top += bbox.width / 2 + offset;
} else {
left += bbox.width / 2 + offset;
}
break;
case "center":
if(isHorizontal) {
top -= offset;
} else {
left -= offset;
}
break;
default:
break;
}
ele.attr("transform", "t" + left + "," + top);
};
wijlineargauge.prototype._paintFace = function () {
var self = this, face, o = self.options, width = self._innerBbox.width, height = self._innerBbox.height, left = self._innerBbox.left, top = self._innerBbox.top, ui = {
width: width,
height: height,
x: left,
y: top,
canvas: self.canvas
};
if(o.face && o.face.template && $.isFunction(o.face.template)) {
return o.face.template.call(self, ui);
}
face = self.canvas.rect(left, top, width, height, 5);
if(o.face && o.face.style) {
face.attr(o.face.style);
}
$.wijraphael.addClass($(face.node), o.wijCSS.linearGaugeFace);
return face;
};
wijlineargauge.prototype._paintPointer = function () {
var self = this, o = self.options, point = self._valueToPoint(o.min, 0), width = self._innerBbox.width, height = self._innerBbox.height, left = self._innerBbox.left, top = self._innerBbox.top, pointerInfo = o.pointer, pointer, length, offset, base;
if(!pointerInfo.visible) {
return;
}
base = o.orientation === "horizontal" ? height : width;
offset = base * pointerInfo.offset;
length = base * pointerInfo.length;
if(pointerInfo.template && $.isFunction(pointerInfo.template)) {
pointer = pointerInfo.template.call(self.canvas, point, $.extend({
}, o.pointer, {
offset: offset,
length: length,
gaugeBBox: self._innerBbox
}));
} else {
if(o.orientation === "horizontal") {
if(pointerInfo.shape === "rect") {
pointer = self.canvas.rect(point.x - pointerInfo.width / 2, height - length - offset + top, pointerInfo.width, length);
} else {
pointer = self.canvas.isoTri(point.x, height - length - offset + top, pointerInfo.width, length, gauge.Compass.north);
}
} else {
if(pointerInfo.shape === "rect") {
pointer = self.canvas.rect(width - length - offset + left, point.y - pointerInfo.width / 2, length, pointerInfo.width);
} else {
pointer = self.canvas.isoTri(width - length - offset + left, point.y - pointerInfo.width / 2, length, pointerInfo.width);
}
}
pointer.attr(pointerInfo.style);
}
$.wijraphael.addClass($(pointer.node), o.wijCSS.linearGaugePointer);
self.pointer = pointer;
};
wijlineargauge.prototype._setPointer = function () {
var self = this, o = self.options;
// orientation = o.orientation,
// fromValue = orientation === "horizontal" ?
// self._minScreenPoint(0).x : self._minScreenPoint(0).y,
// endValue = orientation === "horizontal" ?
// self._maxScreenPoint(0).x : self._maxScreenPoint(0).y;
if(!self.pointer) {
return;
}
_super.prototype._setPointer.call(this);
self._setLinearPointer(o.value);
};
wijlineargauge.prototype._setLinearPointer = function (value) {
var self = this, o = self.options, startPoint = self._valueToPoint(o.min, 0), endPoint = self._valueToPoint(value, 0), animation = // fromBbox = self.pointer.wijGetBBox(),
o.animation, translation = {
x: 0,
y: 0
};
// if use the transform("..."), the memeroy may leak.
// Using the absolute path instead of it.
if(o.orientation === "horizontal") {
//translation.x = endPoint.x - fromBbox.x - fromBbox.width / 2;
translation.x = endPoint.x - startPoint.x;
} else {
//translation.y = endPoint.y - fromBbox.y - fromBbox.height / 2;
translation.y = endPoint.y - startPoint.y;
}
if(animation.enabled) {
self.pointer.stop().wijAnimate({
transform: "t" + translation.x + "," + translation.y
}, animation.duration, animation.easing);
} else {
self.pointer.attr("transform", "t" + translation.x + "," + translation.y);
}
};
wijlineargauge.prototype._minScreenPoint = function (yOffset) {
var self = this, o = self.options, width = self._innerBbox.width, height = self._innerBbox.height, left = self._innerBbox.left, top = self._innerBbox.top, totalOffset = o.yAxisLocation + yOffset;
if(o.orientation === "horizontal") {
return {
x: width * o.xAxisLocation + left,
y: height * totalOffset + top
};
} else {
return {
x: width * totalOffset + left,
y: height * (1 - o.xAxisLocation) + top
};
}
};
wijlineargauge.prototype._maxScreenPoint = function (yOffset) {
var self = this, o = self.options, width = self._innerBbox.width, height = self._innerBbox.height, left = self._innerBbox.left, top = self._innerBbox.top, totalOffset = o.yAxisLocation + yOffset, end = o.xAxisLocation + o.xAxisLength;
if(o.orientation === "horizontal") {
return {
x: width * end + left,
y: height * totalOffset + top
};
} else {
return {
x: width * totalOffset + left,
y: height * (1 - end) + top
};
}
};
wijlineargauge.prototype._paintRange = function (range) {
var self = this, o = self.options, calculateFrom = isNaN(range.startValue) ? 0 : range.startValue, calculateTo = isNaN(range.endValue) ? 0 : range.endValue, calculateStartWidth = isNaN(range.startWidth) ? (isNaN(range.width) ? 0 : range.width) : range.startWidth, calculateEndWidth = isNaN(range.endWidth) ? (isNaN(range.width) ? 0 : range.width) : range.endWidth, startDistance = range.startDistance || 0, endDistance = range.endDistance || 0, coercedFrom, coercedTo;
if(calculateFrom !== calculateTo) {
if(calculateTo > calculateFrom) {
coercedFrom = Math.max(calculateFrom, o.min);
coercedTo = Math.min(o.max, calculateTo);
} else {
coercedFrom = Math.max(o.min, calculateTo);
coercedTo = Math.min(o.max, calculateFrom);
}
self._drawRange(coercedFrom, coercedTo, startDistance, endDistance, calculateStartWidth, calculateEndWidth, range);
}
};
wijlineargauge.prototype._drawRange = function (coercedFrom, coercedTo, startDistance, endDistance, calculateStartWidth, calculateEndWidth, range) {
var self = this, o = self.options, orientation = o.orientation, width = self._innerBbox.width, height = self._innerBbox.height, left = self._innerBbox.left, top = self._innerBbox.top, p1 = self._valueToPoint(coercedFrom, 0), p2 = self._valueToPoint(coercedTo, 0), p3, p4, arrPath, rangeEl, startWidth, endWidth;
if(orientation === "horizontal") {
startWidth = calculateStartWidth * height;
endWidth = calculateEndWidth * height;
if(startDistance !== 0) {
p1.y = startDistance * height + top;
}
if(endDistance !== 0) {
p2.y = endDistance * height + top;
}
p3 = {
x: p1.x,
y: p1.y - startWidth
};
p4 = {
x: p2.x,
y: p2.y - endWidth
};
} else {
startWidth = calculateStartWidth * width;
endWidth = calculateEndWidth * width;
if(startDistance !== 0) {
p1.x = startDistance * width + left;
}
if(endDistance !== 0) {
p2.x = endDistance * width + left;
}
p3 = {
x: p1.x - startWidth,
y: p1.y
};
p4 = {
x: p2.x - endWidth,
y: p2.y
};
}
arrPath = [
"M",
p1.x,
p1.y,
"L",
p2.x,
p2.y,
"L",
p4.x,
p4.y,
"L",
p3.x,
p3.y,
"Z"
];
rangeEl = self.canvas.path(arrPath.concat(" "));
rangeEl.attr(range.style);
$.wijraphael.addClass($(rangeEl.node), o.wijCSS.linearGaugeRange);
self.ranges.push(rangeEl);
};
wijlineargauge.prototype._valueToPoint = function (value, offset) {
var self = this, o = self.options, isInverted = o.isInverted, alpha, minPoint, maxPoint;
if(o.max === o.min) {
return {
x: 0,
y: 0
};
}
alpha = self._valueToLogical(value);
minPoint = self._minScreenPoint(offset);
maxPoint = self._maxScreenPoint(offset);
if(isInverted) {
return {
x: minPoint.x * alpha + maxPoint.x * (1 - alpha),
y: minPoint.y * alpha + maxPoint.y * (1 - alpha)
};
} else {
return {
x: minPoint.x * (1 - alpha) + maxPoint.x * alpha,
y: minPoint.y * (1 - alpha) + maxPoint.y * alpha
};
}
};
return wijlineargauge;
})(gauge.wijgauge);
gauge.wijlineargauge = wijlineargauge;
wijlineargauge.prototype.widgetEventPrefix = "wijlineargauge";
var wijlineargauge_options = (function () {
function wijlineargauge_options() {
/**
* @ignore
*/
this.initSelector = ":jqmData(role='wijlineargauge')";
/**
* @ignore
*/
this.wijCSS = {
linearGauge: "wijmo-wijlineargauge",
linearGaugeLabel: "wijmo-wijlineargauge-label",
linearGaugeMarker: "wijmo-wijlineargauge-mark",
linearGaugeFace: "wijmo-wijlineargauge-face",
linearGaugePointer: "wijmo-wijlineargauge-pointer",
linearGaugeRange: "wijmo-wijlineargauge-range"
};
/**
* Sets the orientation of the gauge, with a setting of horizontal showing values across the gauge from left to right, and a
* setting of vertical showing values along the gauge from top to bottom.
* @example
* // This sample shows how to create vertical linear gauge.
* $(document).ready(function () {
* $("#lineargauge1").wijlineargauge({
* value: 31,
* orientation: "vertical"
* });
* });
*/
this.orientation = "horizontal";
/**
* Sets the starting location of the X axis as a percentage of the width of the gauge.
* @remarks
* Note: By default, the xAxisLength option is set to draw the X axis 80% of the width the gauge, so if you want to center
* the axis within the gauge, you must also adjust that option.
*/
this.xAxisLocation = 0.1;
/**
* Sets the length of the X axis as a percentage of the width of the gauge.
* @remarks
* Note: By default, the xAxisLocation option is set to begin the X axis 10% of the way across from the left edge of the
* gauge, so if you want to use a higher ratio for the xAxisLength, you must also adjust that option.
*/
this.xAxisLength = 0.8;
/**
* Sets the base vertical location of the pointer, tick marks and labels on the X axis as a percentage of the height of the gauge.
* @remarks
* Note that there is no actual Y axis in the LinearGauge. By default, it is centered in the gauge.A setting of 0.8 moves the
* pointer, tick marks, and labels toward the bottom edge of the gauge.
*/
this.yAxisLocation = 0.5;
/**
* Sets the width of the gauge area in pixels.
* @type {number|string}
*/
this.width = "auto";
/**
* Sets the height of the gauge area in pixels.
* @type {number|string}
*/
this.height = "auto";
/**
* Creates an object that includes all settings of the gauge pointer.
*/
this.pointer = {
length: /**
* Sets the length of the pointer as a percentage of the height of the gauge (or the width, if the orientation is set
* to vertical).
* @remarks
* You can set the length to be greater than the height (or width).
*/
0.5,
width: /**
* Sets the width of the pointer in pixels.
*/
4,
offset: /**
* Sets the percentage of the height of the gauge to move the pointer upward (or of the width if the orientation is
* vertical) from the bottom (or right) edge of the gauge.
*/
0,
visible: /**
* A value that indicates whether to show the pointer.
*/
true,
template: /**
* A JavaScript callback value that returns a Raphael element that draws the pointer. Use this option to customize
* the pointer.
* @remarks
* In order to use the template, you must know how to draw Raphael graphics. For more information, see the Raphael documentation.
* The pointer template's callback contains two arguments:
* startLocation -- The starting point from which to draw the pointer. This argument is defined by x and y coordinates.
* pointerInfo -- A JSON object that extends the gauge's pointer options:
* offset -- Sets the percentage of the pointer that is shoved upward from the bottom edge.
* length -- Sets the absolute value in pixels of the length of the pointer.
* gaugeBBox -- An object that sets the bounding box of the gauge, as defined by x and y coordinates and width and height options.
*/
null,
shape: "tri",
style: {
fill: "#1E395B",
stroke: "#1E395B"
}
};
/**
* It is a value in pixels that indicates where to render the left edge of the gauge markers, it may help to also change
* the width option.
*/
this.marginLeft = 5;
/**
* It is a value in pixels that indicates where to render the top edge of the gauge face.
* @remarks
* In order to change the margin settings by more than a few pixels without clipping the gauge face edges, it may help
* to also change the height property.
*/
this.marginTop = 5;
/**
* It is a value in pixels that indicates where to render the right edge of the gauge face.
* @remarks
* In order to change the margin settings without compressing the gauge markers, it may help to also change the width option.
*/
this.marginRight = 5;
/**
* It is a value in pixels that indicates where to render the bottom edge of the gauge face.
* @remarks
* In order to change the margin settings by more than a few pixels without clipping the gauge face edges, it may help to
* also change the height property
*/
this.marginBottom = 5;
}
return wijlineargauge_options;
})();
wijlineargauge.prototype.options = $.extend(true, {
}, gauge.wijgauge.prototype.options, new wijlineargauge_options());
//$.widget("wijmo.wijlineargauge", WijlinearGauge.prototype);
$.wijmo.registerWidget("wijlineargauge", wijlineargauge.prototype);
})(wijmo.gauge || (wijmo.gauge = {}));
var gauge = wijmo.gauge;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../wijgauge/jquery.wijmo.wijgauge.ts"/>
/*globals $, Raphael, jQuery, document, window*/
/*
* Depends:
* jQuery.1.5.1.js
* jQuery.ui.core.js
* jQuery.ui.widget.js
* raphael.js
* globalize.min.js
* jquery.wijmo.raphael.js
*/
(function (gauge) {
var _zeroOffset = 180, interpMinPoints = 9, interJump = 5;
/**
* @widget
*/
var wijradialgauge = (function (_super) {
__extends(wijradialgauge, _super);
function wijradialgauge() {
_super.apply(this, arguments);
}
wijradialgauge.prototype._create = function () {
var self = this;
_super.prototype._create.call(this);
self.element.addClass(this.options.wijCSS.radialGauge);
};
wijradialgauge.prototype._set_radius = function () {
var self = this;
self._redrawMarksAndLabels();
self.pointer.wijRemove();
self._paintPointer();
self._setPointer();
};
wijradialgauge.prototype._set_startAngle = function () {
var self = this;
self._redrawMarksAndLabels();
self._setPointer();
};
wijradialgauge.prototype._set_sweepAngle = function (value) {
var self = this;
if(value > 360) {
self.options.endAngle = 360;
}
self._redrawMarksAndLabels();
self._setPointer();
};
wijradialgauge.prototype._set_width = function () {
var self = this;
self._autoCalculate();
_super.prototype._set_width.call(this);
};
wijradialgauge.prototype._set_height = function () {
var self = this;
self._autoCalculate();
_super.prototype._set_height.call(this);
};
wijradialgauge.prototype._set_origin = function () {
var self = this;
self._autoCalculate();
};
wijradialgauge.prototype._set_cap = function () {
var self = this;
self.pointer.wijRemove();
self._paintPointer();
self._setPointer();
};
wijradialgauge.prototype._clearState = function () {
_super.prototype._clearState.call(this);
this.markBbox = null;
};
wijradialgauge.prototype._valueToAngleIncludeOffset = function (value) {
return gauge.GaugeUtil.mod360(this._valueToAngle(value) + _zeroOffset);
};
wijradialgauge.prototype._valueToAngle = function (value) {
var self = this, alpha = self._valueToLogical(value);
return self._logicalToAngle(alpha);
};
wijradialgauge.prototype._angleToValue = function (angle) {
var self = this, alpha = self._angleToLogical(angle);
return self._logicalToValue(alpha);
};
wijradialgauge.prototype._logicalToAngle = function (alpha) {
var self = this, o = self.options, startAngle = o.startAngle, sweepAngle = o.sweepAngle, isInverted = o.isInverted;
if(isInverted) {
return startAngle * alpha + (startAngle + sweepAngle) * (1 - alpha);
} else {
return startAngle * (1 - alpha) + (startAngle + sweepAngle) * alpha;
}
};
wijradialgauge.prototype._angleToLogical = function (angle) {
var self = this, o = self.options, startAngle = o.startAngle, isInverted = o.isInverted, relativeAngle = gauge.GaugeUtil.mod360(angle - startAngle), absSweepAngle = o.sweepAngle, overflow, underflow;
if(absSweepAngle === 0 || relativeAngle === 0) {
return isInverted ? 1 : 0;
}
if(absSweepAngle < 0) {
relativeAngle = 360 - relativeAngle;
absSweepAngle = -absSweepAngle;
}
overflow = relativeAngle - absSweepAngle;
if(overflow > 0) {
underflow = 360 - relativeAngle;
return overflow < underflow ? 1 : 0;
}
if(isInverted) {
return 1 - relativeAngle / absSweepAngle;
} else {
return relativeAngle / absSweepAngle;
}
};
wijradialgauge.prototype._generatePoints = function (fromAngle, toAngle, fromLength, toLength) {
var self = this, isInverted = self.options.isInverted, max = parseInt((interpMinPoints + interpMinPoints * (Math.abs(parseInt((toAngle - fromAngle).toString(), 10)) / (interpMinPoints * interJump))).toString(), 10), points = [], alpha, length, value, angle, i;
for(i = 0; i < max; i++) {
alpha = i / (max - 1);
length = fromLength + (toLength - fromLength) * alpha;
angle = fromAngle + (toAngle - fromAngle) * alpha;
value = self._angleToValue(angle);
points.push(self._valueToPoint(value, length));
}
return points;
};
wijradialgauge.prototype._valueToPoint = function (value, offset) {
var self = this, angle = self._valueToAngleIncludeOffset(value) * Math.PI / 180, radius = offset;
return {
x: radius * Math.cos(angle),
y: radius * Math.sin(angle)
};
};
wijradialgauge.prototype._pointToValue = function (point) {
var angle = gauge.GaugeUtil.mod360(Math.atan2(point.x, -point.y) * 180 / Math.PI);
return this._angleToValue(angle);
};
wijradialgauge.prototype._radiusScreen = function (offset) {
var self = this, o = self.options;
return Math.max(o.radius * offset, 0);
};
wijradialgauge.prototype._autoCalculate = function () {
var self = this, o = self.options, width = o.width, height = o.height, majorMarkWidth, minorMarkWidth, labelWidth, maxText = gauge.GaugeUtil.formatString(o.max, o.labels.format), offset = 0, faceBorder, innerHeight = height - o.marginTop - o.marginBottom, innerWidth = //add by DH
width - o.marginLeft - o.marginRight;
//add by DH
//self.centerPoint = { x: width * o.origin.x, y: height * o.origin.y };
self.centerPoint = {
x: o.marginLeft + innerWidth * o.origin.x,
y: o.marginTop + innerHeight * o.origin.y
};
self.radius = o.radius;
if(o.radius === "auto") {
//self.faceRadius = Math.min(width, height) / 2;
self.faceRadius = Math.min(innerWidth, innerHeight) / 2//add by DH
;
faceBorder = self._getFaceBorder();
self.faceRadius -= faceBorder;
majorMarkWidth = self._getMarkerbbox(o.tickMajor).width;
minorMarkWidth = self._getMarkerbbox(o.tickMinor).width;
labelWidth = self._getLabelBBox(maxText).width;
if(o.tickMajor.position === "center") {
offset -= majorMarkWidth / 2;
offset -= labelWidth;
} else if(o.tickMajor.position === "outside") {
offset -= majorMarkWidth;
offset -= labelWidth;
}
if(o.tickMinor.position === "center") {
offset = Math.min(offset, -minorMarkWidth / 2);
} else if(o.tickMinor.position === "outside") {
offset = Math.min(offset, -minorMarkWidth);
}
self.radius = self.faceRadius + offset;
if(o.tickMajor.position !== "inside") {
self.faceRadius += offset;
}
}
};
wijradialgauge.prototype._getFaceBorder = function () {
var self = this, face = self._paintFace(), width = face.attr("stroke-width") || 1;
if(face.type === "set") {
width = face[0].attr("stroke-width") || 1;
}
face.wijRemove();
return width;
};
wijradialgauge.prototype._getMaxRangeWidth = function () {
var self = this, o = self.options, maxWidth = 0;
$.each(o.ranges, function (i, n) {
maxWidth = Math.max(maxWidth, n.width || 0);
maxWidth = Math.max(maxWidth, n.startWidth || 0);
maxWidth = Math.max(maxWidth, n.endWidth || 0);
});
return maxWidth;
};
wijradialgauge.prototype._getMarkerbbox = function (opt) {
var self = this, mark = self._paintMarkEle(opt), bbox = mark.wijGetBBox();
mark.wijRemove();
return {
width: bbox.width,
height: bbox.height
};
};
wijradialgauge.prototype._paintMark = function (value, opt, isMajor) {
var self = this, mark, position = opt.position || "inside", offset = opt.offset || 0;
mark = self._paintMarkEle(opt);
mark.attr(opt.style);
$.wijraphael.addClass($(mark.node), self.options.wijCSS.radialGaugeMarker);
$(mark.node).data("value", value);
self._applyAlignment(mark, position, offset);
self._setMarkValue(value, mark);
return mark;
};
wijradialgauge.prototype._applyAlignment = function (ele, alignment, offset) {
if(!ele) {
return;
}
var Bbox = ele.wijGetBBox(), halfWidth = Bbox.width / 2, left = 0;
switch(alignment) {
case "outside":
left -= (halfWidth + offset);
break;
case "inside":
left += (halfWidth + offset);
break;
}
//ele.attr("translation", left + "," + 0);
//ele.attr("transform", "t" + left + "," + 0);
ele.transform("t" + left + "," + 0);
};
wijradialgauge.prototype._paintMarkEle = function (opt) {
var self = this, o = self.options, startLocation = {
x: self.centerPoint.x - self.radius,
y: self.centerPoint.y
}, marker = opt.marker || "circle", baseLength = marker === "rect" ? 5 : 2, width = 2, length, strokeWidth = opt.style["stroke-width"] || 0;
if(marker === "tri" || marker === "invertedTri") {
baseLength = 5;
width = 3;
}
if(marker === "cross") {
opt.style.fill = opt.style.stroke || opt.style.fill;
}
if(isNaN(startLocation.x)) {
startLocation.x = 0;
}
length = baseLength * opt.factor;
width += strokeWidth * 2;
length += strokeWidth * 2;
if($.isFunction(marker)) {
return marker.call(self, self.canvas, startLocation, o);
} else {
return gauge.GaugeUtil.paintMarker(self.canvas, marker, startLocation.x, startLocation.y, length, width);
if(marker === "tri") {
return self.canvas.isoTri(startLocation.x, startLocation.y, length, width, gauge.Compass.west);
} else if(marker === "invertedTri") {
return self.canvas.isoTri(startLocation.x, startLocation.y, length, width, gauge.Compass.east);
}
return gauge.GaugeUtil.paintMarker(self.canvas, marker, startLocation.x, startLocation.y, length, width, true);
}
};
wijradialgauge.prototype._setMarkValue = function (value, mark) {
var self = this, angle = self._valueToAngle(value);
//mark.rotate(angle, self.centerPoint.x, self.centerPoint.y);
mark.transform(Raphael.format("r{0},{1},{2}...", angle, self.centerPoint.x, self.centerPoint.y));
};
wijradialgauge.prototype._paintLabel = function (value, labelInfo) {
var self = this, angle = self._valueToAngle(value), format = labelInfo.format, style = labelInfo.style, offset = labelInfo.offset, text = value.toString(), markOption = self.options.tickMajor, position = markOption.position || "inside", point, textEle, markBbox, newRadius, maxLabelBBox;
if(format !== "") {
text = gauge.GaugeUtil.formatString(value, format);
}
markBbox = self._getMarkerBbox();
maxLabelBBox = self._getLabelBBox(text);
switch(position) {
case "inside":
newRadius = markBbox.x + markBbox.width + maxLabelBBox.width / 2;
break;
case "outside":
newRadius = markBbox.x - maxLabelBBox.width / 2;
break;
default:
newRadius = markBbox.x - maxLabelBBox.width / 2;
break;
}
newRadius = self.centerPoint.x - newRadius + offset;
point = gauge.GaugeUtil.getPositionByAngle(self.centerPoint.x, self.centerPoint.y, newRadius, angle);
textEle = self.canvas.text(point.x, point.y, text);
textEle.attr(style);
$.wijraphael.addClass($(textEle.node), self.options.wijCSS.radialGaugeLabel);
return textEle;
};
wijradialgauge.prototype._getLabelBBox = function (value) {
var self = this, o = self.options, text, bbox;
text = self.canvas.text(0, 0, value);
text.attr(o.gaugeLableStyle);
bbox = text.wijGetBBox();
text.wijRemove();
return bbox;
};
wijradialgauge.prototype._getMarkerBbox = function () {
var self = this, o = self.options, markOption = o.tickMajor, markEle;
if(!self.markBbox) {
markEle = self._paintMarkEle(markOption);
self._applyAlignment(markEle, markOption.position, markOption.offset || 0);
self.markBbox = markEle.wijGetBBox();
markEle.wijRemove();
}
return self.markBbox;
};
wijradialgauge.prototype._paintFace = function () {
var self = this, o = self.options, r = Math.min(o.width, o.height) / 2, face, ui;
if(self.faceRadius) {
r = self.faceRadius;
}
if(o.face && o.face.template && $.isFunction(o.face.template)) {
ui = {
canvas: self.canvas,
r: r,
origin: {
x: self.centerPoint.x,
y: self.centerPoint.y
}
};
return o.face.template.call(self, ui);
}
face = self.canvas.circle(self.centerPoint.x, self.centerPoint.y, r);
if(o.face && o.face.style) {
face.attr(o.face.style);
}
$.wijraphael.addClass($(face.node), o.wijCSS.radialGaugeFace);
return face;
};
wijradialgauge.prototype._paintPointer = function () {
var self = this, o = self.options, pointerInfo = o.pointer, length = self.radius * pointerInfo.length, startLocation = {
x: self.centerPoint.x - length + pointerInfo.offset * self.radius,
y: self.centerPoint.y - pointerInfo.width / 2
}, point;
if(!pointerInfo.visible) {
return;
}
if(o.cap && o.cap.behindPointer && o.cap.visible) {
self._paintCap();
}
if(pointerInfo.template && $.isFunction(pointerInfo.template)) {
point = pointerInfo.template.call(self.canvas, startLocation, $.extend({
}, pointerInfo, {
length: length
}));
} else {
if(pointerInfo.shape === "rect") {
point = self.canvas.rect(startLocation.x - pointerInfo.width / 2, startLocation.y, length, pointerInfo.width);
} else {
point = self.canvas.isoTri(startLocation.x - pointerInfo.width / 2, startLocation.y, length, pointerInfo.width);
}
point.attr(pointerInfo.style);
}
self.pointer = point;
$.wijraphael.addClass($(point.node), o.wijCSS.radialGaugePointer);
if((!o.cap || !o.cap.behindPointer) && o.cap.visible) {
self._paintCap();
}
};
wijradialgauge.prototype._paintCap = function () {
var self = this, o = self.options, capInfo = o.cap, ui;
if(capInfo && capInfo.template && $.isFunction(capInfo.template)) {
ui = {
canvas: self.canvas,
origin: {
x: self.centerPoint.x,
y: self.centerPoint.y
}
};
self.cap = capInfo.template.call(self, ui);
return self.cap;
}
self.cap = self.canvas.circle(self.centerPoint.x, self.centerPoint.y, capInfo.radius);
if(capInfo && capInfo.style) {
self.cap.attr(capInfo.style);
}
$.wijraphael.addClass($(self.cap.node), o.wijCSS.radialGaugeCap);
return self.cap;
//
};
wijradialgauge.prototype._paintRange = function (range) {
var self = this, o = self.options, calculateFrom = isNaN(range.startValue) ? 0 : range.startValue, calculateTo = isNaN(range.endValue) ? 0 : range.endValue, calculateStartWidth = isNaN(range.startWidth) ? (isNaN(range.width) ? 0 : range.width) : range.startWidth, calculateEndWidth = isNaN(range.endWidth) ? (isNaN(range.width) ? 0 : range.width) : range.endWidth, startDistance = range.startDistance || 1, endDistance = range.endDistance || 1, coercedFrom, coercedTo;
if(calculateFrom !== calculateTo) {
if(calculateTo > calculateFrom) {
coercedFrom = Math.max(calculateFrom, o.min);
coercedTo = Math.min(o.max, calculateTo);
} else {
coercedFrom = Math.max(o.min, calculateTo);
coercedTo = Math.min(o.max, calculateFrom);
}
startDistance = startDistance * self.radius;
endDistance = endDistance * self.radius;
self._drawRange(coercedFrom, coercedTo, startDistance, endDistance, calculateStartWidth, calculateEndWidth, range);
}
};
wijradialgauge.prototype._drawRange = function (from, to, startDistance, endDistance, startWidth, endWidth, range) {
var self = this, startAngle = self._valueToAngle(from), endAngle = self._valueToAngle(to), outerPointers = self._generatePoints(startAngle, endAngle, startWidth + startDistance, endWidth + endDistance), innerPointers = self._generatePoints(startAngle, endAngle, startDistance, endDistance), i, rangeEl, path = "";
$.each(outerPointers, function (i, n) {
if(i === 0) {
path += "M" + Math.round(n.x + self.centerPoint.x) + " " + Math.round(n.y + self.centerPoint.y);
} else {
path += "L" + (n.x + self.centerPoint.x) + " " + Math.round(n.y + self.centerPoint.y);
}
});
for(i = innerPointers.length - 1; i >= 0; i--) {
path += "L" + Math.round(innerPointers[i].x + self.centerPoint.x) + " " + Math.round(innerPointers[i].y + self.centerPoint.y);
}
path += "Z";
rangeEl = self.canvas.path(path);
rangeEl.attr(range.style);
self.ranges.push(rangeEl);
$.wijraphael.addClass($(rangeEl.node), self.options.wijCSS.radialGaugeRange);
};
wijradialgauge.prototype._setOffPointerValue = function () {
var self = this, angle = self._valueToAngle(0);
//self.pointer.rotate(angle, self.centerPoint.x, self.centerPoint.y);
self.pointer.transform(Raphael.format("r{0},{1},{2}", angle, self.centerPoint.x, self.centerPoint.y));
};
wijradialgauge.prototype._setPointer = function () {
var self = this, o = self.options, angle = self._valueToAngle(o.value), animation = o.animation;
if(!self.pointer) {
return;
}
_super.prototype._setPointer.call(this);
if(animation.enabled) {
self.pointer.stop().wijAnimate({
transform: "r" + angle + "," + self.centerPoint.x + "," + self.centerPoint.y
}, animation.duration, animation.easing);
} else {
//self.pointer.rotate(angle, self.centerPoint.x, self.centerPoint.y);
self.pointer.transform(Raphael.format("r{0},{1},{2}", angle, self.centerPoint.x, self.centerPoint.y));
}
};
return wijradialgauge;
})(gauge.wijgauge);
gauge.wijradialgauge = wijradialgauge;
wijradialgauge.prototype.widgetEventPrefix = "wijradialgauge";
var wijradialgauge_options = (function () {
function wijradialgauge_options() {
/**
* @ignore
*/
this.initSelector = ":jqmData(role='wijradialgauge')";
/**
* @ignore
*/
this.wijCSS = {
radialGauge: "wijmo-wijradialgauge",
radialGaugeLabel: "wijmo-wijradialgauge-label",
radialGaugeMarker: "wijmo-wijradialgauge-mark",
radialGaugeFace: "wijmo-wijradialgauge-face",
radialGaugePointer: "wijmo-wijradialgauge-pointer",
radialGaugeCap: "wijmo-wijradialgauge-cap",
radialGaugeRange: "wijmo-wijradialgauge-range"
};
/**
* A value that indicates the radius of the radial gauge in pixels, or use "auto" to have the gauge indicators fill the
* gauge area.
* @remarks
* Values between 50 and 200 are most useful when you use the default size for the gauge area.
* @type {number|string}
*/
this.radius = "auto";
/**
* A value that indicates in degrees where to start the lowest number in the numeric labels and tickMarks around the face
* of the RadialGauge.
* @remarks
* The default value of 0 degrees renders the lowest number to the left of the origin.
* A value of -90 degrees renders the lowest number below the origin.
* A value of 90 degrees renders the lowest number above the origin.
* A value of 180 degrees renders the lowest number to the right of the origin.
*/
this.startAngle = 0;
/**
* A value that indicates in degrees where to render the highest number in the numeric labels and tickMarks in relation
* to the startAngle.
* @example
* // This code example renders the labels and tickmarks from a starting angle of -45 degrees to a sweep angle of 270
* degrees, so that the numbers render three quarters of the way around the face
* $(document).ready(function () {
* $("#radialgauge1").wijradialgauge({
* value: 90,
* startAngle: -45,
* sweepAngle: 270
* });
* });
*/
this.sweepAngle = 180;
/**
* A value that includes all settings of the gauge pointer.
* @example
* // The example above renders the pointer as a purple-outlined blue rectangle of 125% the length of the radius by 10
* // pixels wide, offset back through the cap by 50% of the length of the radius.
* $(document).ready(function () {
* $("#radialgauge1").wijradialgauge({
* value: 90,
* cap: {visible: true},
* pointer: {
* length: 1.25,
* offset: 0.5,
* shape: "rect",
* style: { fill: "blue", stroke: "purple"},
* width: 10
* }
* });
* });
*/
this.pointer = {
length: /**
* Sets the length of the pointer as a percentage of the radius of the gauge.
* @remarks
* You can set the length to be greater than the radius.
*/
0.8,
style: /**
* Sets the fill and outline (stroke) colors of the pointer.
*/
{
fill: "#1E395B",
stroke: "#1E395B"
},
width: /**
* Sets the width of the pointer in pixels.
*/
8,
offset: /**
* Sets the percentage of the pointer that is shoved backward through the cap.
*/
0.15,
shape: "tri",
visible: true,
template: null
};
/**
* Sets the starting point for the center of the radial gauge.
*/
this.origin = {
x: 0.5,
y: 0.5
};
/**
* Sets all of the appearance options of the numeric labels that appear around the edge of the gauge.
* @example
* // This example sets the color for the labels to purple, and the font to 14 point, bold, Times New Roman.
* $(document).ready(function () {
* $("#radialgauge1").wijradialgauge({
* value: 90,
* labels: {
* style: {
* fill: "purple",
* "font-size": "14pt",
* "font-weight": "bold",
* "font-family": "Times New Roman"
* }
* }
* });
* });
*/
this.labels = {
format: "",
style: /**
* A value that indicates the color, weight, and size of the numeric labels.
* To use a different font, add "font-family" to the style
*/
{
fill: "#1E395B",
"font-size": 12,
"font-weight": "800"
},
offset: /**
* A value in pixels that indicates the distance of the numeric labels from the outer reach of the pointer.
*/
30,
visible: true
};
/**
* Sets appearance options for the minor tick marks that appear between the numeric labels around the face of the gauge,
* indicating numeric values between the major tick marks.
* @example
* // This example renders the minor tick marks as purple crosses, at an interval of once every 2 numbers
* $(document).ready(function () {
* $("#radialgauge1").wijradialgauge({
* value: 90,
* tickMinor: {
* position: "inside",
* style: { fill: "#1E395B", stroke: "purple"},
* factor: 2,
* marker: 'cross',
* visible: true,
* offset: 30,
* interval: 2
* }
* });
* });
*/
this.tickMinor = {
position: /**
* A value that indicates the position of the minor tick marks in relation to the edge of the face.
* @remarks
* Valid Values:
* "inside" -- Draws the minor tick marks inside the edge of the face.
* "outside" -- Draws the minor tick marks outside the edge of the face.
* "cross" -- Draws the minor tick marks centered on the edge of the face.
*/
"inside",
offset: /**
* A value that indicates the distance in pixels from the edge of the face to draw the minor tick marks.
*/
30,
style: /**
* A value that indicates the fill color and outline (stroke) of the minor tick mark.
*/
{
fill: "#1E395B"
},
visible: /**
* A value that indicates whether to show the minor tick mark.
*/
true,
factor: 1,
marker: "rect",
interval: 5
};
/**
* Sets appearance options for the major tick marks that appear next to the numeric labels around the face of the gauge.
* @example
* // This example renders the major tick marks as slightly larger purple filled diamonds with blue outlines, at an interval
* // of once every 20 numbers
* $(document).ready(function () {
* $("#radialgauge1").wijradialgauge({
* value: 90,
* tickMajor: {
* position: "inside",
* style: { fill: "purple", stroke: "#1E395B"},
* factor: 2.5,
* marker: 'diamond',
* visible: true,
* offset: 27,
* interval: 20
* }
* });
* });
*/
this.tickMajor = {
position: /**
* A value that indicates the position of the major tick marks in relation to the edge of the face.
* @remarks
* Valid Values:
* "inside" -- Draws the major tick marks inside the edge of the face.
* "outside" -- Draws the major tick marks outside the edge of the face.
* "cross" -- Draws the major tick marks centered on the edge of the face.
*/
"inside",
offset: /**
* A value that indicates the distance in pixels from the edge of the face to draw the major tick marks.
* @remarks
* The numeric labels are drawn a few pixels outside of the major tick marks.
*/
27,
style: /**
* A value that indicates the fill color and outline (stroke) of the major tick mark.
*/
{
fill: "#1E395B",
stroke: "#1E395B",
"stroke-width": 1
},
visible: /**
* A value that indicates whether to show the major tick mark.
*/
true,
interval: 10,
factor: 2,
marker: "rect"
};
/**
* Sets the size, color, and other properties of the circle at the center of the gauge that anchors the pointer.
* @example
* // This example creates a rectangular cap that begins 10 pixels to the left of and 10 pixels above the origin, and is 20
* // pixels wide by 20 pixels tall. The cap is filled with purple and has no outline (stroke).
* $(document).ready(function () {
* $("#radialgauge1").wijradialgauge({
* value: 180,
* max: 200,
* min: 0,
* cap: {
* template: function (ui) {
* var origin = ui.origin;
* return ui.canvas.rect(origin.x -10, origin.y -10, 20, 20).attr({fill: "purple", stroke: "none"});
* }
* }
* });
* });
*/
this.cap = {
radius: /**
* A value that indicates the radius of the cap in pixels.
*/
15,
style: /**
* A value that contains the fill color and outline color (stroke) of the cap.
*/
{
fill: "#1E395B",
stroke: "#1E395B"
},
behindPointer: /**
* A value that indicates whether the cap shows behind the pointer or in front.
*/
false,
visible: /**
* A value that indicates whether to show the cap.
*/
true,
template: /**
* A JavaScript callback value that returns a Raphael element (or set) that draws the cap for the pointer.
* @remarks
* If you are only using one shape, the function returns a Raphael element. If you define multiple shapes, have the function
* create a Raphael set object push all of the Raphael elements to the set, and return the set to wijradialgauge.
* In order to use the template, you must know how to draw Raphael graphics. For more information, see the Raphael documentation.
* The cap template's callback contains one argument with two properties:
* origin -- The starting point from which to draw the center of the cap.
* This argument is defined by x and y coordinates.
* canvas -- A Raphael paper object that you can use to draw the custom
* graphic to use as the cap.
*/
null
};
/// <summary>
/// Sets or draws the image or shape to use for the face of the gauge and the
/// background area. The origin is the center of the gauge, but the image
/// draws from the top left, so we first calculate the starting point of the
/// top left based on the origin, and we calculate the width and height based
/// on the radius of the face. The radius of the face is half of the min of
/// the width and height.
/// Note: The fill property is defined using the Raphael framework. Please
/// see the Raphael Element attr method for more information. The face can be
/// filled with a simple color, or a gradient. The default fill is a radial
/// gradient, indicated by the r in the fill property.
/// Default: {fill: ""r(0.9, 0.60)#FFFFFF-#D9E3F0"", stroke: "#7BA0CC",
/// "stroke-width": "4"}, template: null}.
/// Type: Object.
/// Code example:
/// This example uses a custom image for the face of the gauge. The argument
/// that we name ui in the example is a JSON object. This object has a canvas,
/// which is a Raphael paper object, and we use the image method of the
/// Raphael paper that takes five parameters: source, x, y, width, and height.
/// See the Raphael documentation for more information.
/// $(document).ready(function () {
/// $("#radialgauge1").wijradialgauge({
/// value: 90,
/// radius: 120,
/// face: {
/// style: {},
/// template: function (ui) {
/// var url = "images/customGaugeFace.png";
/// return ui.canvas.image(url, ui.origin.x -ui.r, ui.origin.y -ui.r, ui.r * 2, ui.r * 2);
/// }
/// }
/// });
/// });
/// </summary>
/**
* Sets or draws the image or shape to use for the face of the gauge and the background area.
* @remarks
* The origin is the center of the gauge, but the image draws from the top left, so we first calculate the starting point of the
* top left based on the origin, and we calculate the width and height based on the radius of the face. The radius of the face is
* half of the min of the width and height.
* Note: The fill property is defined using the Raphael framework. Please see the Raphael Element attr method for more information.
* The face can be filled with a simple color, or a gradient. The default fill is a radial gradient, indicated by the r in the
* fill property.
* @example
* // This example uses a custom image for the face of the gauge. The argument that we name ui in the example is a JSON object.
* // This object has a canvas, which is a Raphael paper object, and we use the image method of the Raphael paper that takes five
* // parameters: source, x, y, width, and height. See the Raphael documentation for more information.
* $(document).ready(function () {
* $("#radialgauge1").wijradialgauge({
* value: 90,
* radius: 120,
* face: {
* style: {},
* template: function (ui) {
* var url = "images/customGaugeFace.png";
* return ui.canvas.image(url, ui.origin.x -ui.r, ui.origin.y -ui.r, ui.r * 2, ui.r * 2);
* }
* }
* });
* });
*/
this.face = {
style: /**
* A value that indicates the fill color (or gradient), and the outline color and width of the gauge face
*/
{
fill: "r(0.9, 0.60)#FFFFFF-#D9E3F0",
stroke: "#7BA0CC",
"stroke-width": 4
},
template: null
};
}
return wijradialgauge_options;
})();
wijradialgauge.prototype.options = $.extend(true, {
}, gauge.wijgauge.prototype.options, new wijradialgauge_options());
//$.widget("wijmo.wijradialgauge", WijRadialGauge.prototype);
$.wijmo.registerWidget("wijradialgauge", wijradialgauge.prototype);
})(wijmo.gauge || (wijmo.gauge = {}));
var gauge = wijmo.gauge;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/*globals jQuery, window, XMLHttpRequest*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
(function (lightbox) {
"use strict";
var $ = jQuery, widgetName = "wijlightbox";
if(!window["S"] && window["swfobject"]) {
window["S"] = {
flash: window["swfobject"]
};
}
/** @widget */
var wijlightbox = (function (_super) {
__extends(wijlightbox, _super);
function wijlightbox() {
_super.apply(this, arguments);
}
wijlightbox.prototype._keyDownHandler = function (event) {
var o = this.options, self = this, kCode = self.getKeyCodeEnum();
if(event.keyCode && event.keyCode === kCode.ESCAPE) {
if(self._isFullSize()) {
self._toggleFullSize();
} else {
if(o.closeOnEscape) {
self._close();
}
}
event.preventDefault();
return;
}
if(o.keyNav) {
if(event.keyCode) {
switch(event.keyCode) {
case kCode.LEFT:
case kCode.DOWN:
self.back();
event.preventDefault();
break;
case kCode.RIGHT:
case kCode.UP:
self.next();
event.preventDefault();
break;
case kCode.HOME:
if(o.groupItems.length > 0) {
self.show(0);
}
event.preventDefault();
break;
case kCode.END:
if(o.groupItems.length > 0) {
self.show(o.groupItems.length - 1);
}
event.preventDefault();
break;
}
}
}
};
wijlightbox.prototype.getKeyCodeEnum = /** @ignore */
function () {
if($.ui && $.ui.keyCode) {
return $.ui.keyCode;
}
if($.mobile && $.mobile.keyCode) {
return $.mobile.keyCode;
}
throw "keyCode object is not found";
};
wijlightbox.prototype._create = function () {
var o = this.options, self = this;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
if(!o.groupItems) {
o.groupItems = [];
}
this._defaults = {
transAnimation: {
animated: 'fade',
duration: 400,
easing: 'linear'
},
resizeAnimation: {
animated: 'sync',
duration: 400
},
textShowOption: {
duration: 300,
easing: 'linear'
},
textHideOption: {
duration: 300,
easing: 'linear'
}
};
this._parse();
this.container = $('<div/>').addClass('wijmo-wijlightbox ' + o.wijCSS.widget + ' wijmo-wijlightbox-controls-' + o.controlsPosition).css('z-index', o.zIndex).attr({
'tabIndex': -1,
'role': 'dialog'
}).bind('keydown.wijlightbox', $.proxy(self, '_keyDownHandler')).appendTo(document.body).hide();
this.frame = $('<div></div>').addClass([
'wijmo-wijlightbox-frame',
o.wijCSS.content,
o.wijCSS.cornerAll,
o.wijCSS.helperClearFix
].join(' ')).appendTo(this.container);
this.content = $('<div></div>').addClass('wijmo-wijlightbox-content').appendTo(this.frame);
// Active a panel
// use "activeIndex" option or try to retrieve:
// 1. from cookie
// 2. from actived class attribute on panel
if(o.activeIndex === undefined) {
if(typeof o.activeIndex !== 'number' && o.cookie) {
o.activeIndex = parseInt(self._cookie(), 10);
}
o.activeIndex = o.activeIndex || (o.groupItems.length ? 0 : -1);
} else if(o.activeIndex === null) {
// usage of null is deprecated, TODO remove in next release
o.activeIndex = -1;
}
// sanity check - default to first page...
o.activeIndex = ((o.activeIndex >= 0 && o.groupItems[o.activeIndex]) || o.activeIndex < 0) ? o.activeIndex : 0;
this._initClickBehavior();
this._createTimerBar();
this._createDialogButtons();
this._createCtrlButtons();
this._createText();
this._createCounter();
this._refreshCounter();
if(this.toolBox) {
this.toolBox.find('.wijmo-wijlightbox-toolbox-button').bind({
'mouseover': function () {
self._addState('hover', $(this));
},
'mouseout': function () {
self._removeState('hover', $(this));
},
'mousedown': function () {
self._addState('active', $(this));
},
'mouseup': function () {
self._removeState('active', $(this));
}
});
}
if(this._groupMode()) {
this._createNavButtons();
}
this._initHoverBehavior();
this.container.width(this.frame.outerWidth());
};
wijlightbox.prototype.destroy = /**
* Destroys wijlightbox widget and reset the DOM element.
*/
function () {
var o = this.options, self = this;
this._hideWaiting();
this._hideOverlay();
if(o.cookie) {
this._cookie(null, o.cookie);
}
this.container.remove();
$.Widget.prototype.destroy.apply(self, arguments);
return self;
};
wijlightbox.prototype._setOption = function (key, value) {
$.Widget.prototype._setOption.apply(this, arguments);
switch(key) {
case 'groupItems':
if(this.options.activeIndex >= value.length) {
this.show(value.length - 1);
} else {
if(this.options.activeIndex < 0 && value.length) {
this.show(0);
} else {
this.show(this.options.activeIndex);
}
}
break;
case 'activeIndex':
this.show(value);
break;
case 'textPosition':
this._resetText();
break;
case 'clickPause':
this._initClickBehavior();
break;
case 'showNavButtons':
this._createNavButtons();
break;
case 'showControlsOnHover':
this._initHoverBehavior();
break;
}
};
wijlightbox.prototype._initClickBehavior = function () {
var o = this.options, self = this;
this.content.unbind('click');
if(o.clickPause) {
if(this._groupMode()) {
this.content.click(function () {
self[!self.isPlaying() ? 'play' : 'stop']();
});
}
} else {
if(this._groupMode()) {
this.content.click(function (e) {
if(self.isPlaying()) {
return false;
}
var rect = $.extend({
}, $(this).offset(), {
width: $(this).outerWidth(true),
height: $(this).outerHeight(true)
});
if(e.pageX >= rect.left && e.pageX < (rect.left + rect.width / 2)) {
if(!self.backBtn.hasClass(o.wijCSS.stateDisabled)) {
self.back();
}
} else {
if(!self.nextBtn.hasClass(o.wijCSS.stateDisabled)) {
self.next();
}
}
});
}
}
};
wijlightbox.prototype._initHoverBehavior = function () {
var o = this.options, self = this;
this.frame.unbind('.wijlightbox');
if(o.showControlsOnHover) {
this.frame.bind({
'mouseenter.wijlightbox': function () {
if(self.container.data('moving.wijlightbox')) {
return false;
}
self._showAccessories(true);
},
'mouseleave.wijlightbox': function () {
if(self.container.data('moving.wijlightbox')) {
return false;
}
self._hideAccessories(true);
},
'mousemove.wijlightbox': function () {
if(self.container.data('moving.wijlightbox') === false && self.container.data('accessvisible.wijlightbox') === false) {
self.frame.trigger('mouseenter');
}
}
});
}
};
wijlightbox.prototype._getPlugins = function () {
var plugins = this.container.data('plugins.wijlightbox'), names, detectPlugin, f4m;
if(!plugins) {
plugins = {
};
if(window.navigator.plugins && window.navigator.plugins.length) {
names = [];
$.each(window.navigator.plugins, function (i, p) {
names.push(p.name);
});
names = names.join(",");
f4m = names.indexOf("Flip4Mac") > -1;
plugins = {
fla: names.indexOf("Shockwave Flash") > -1,
qt: names.indexOf("QuickTime") > -1,
wmp: !f4m && names.indexOf("Windows Media") > -1,
f4m: f4m
};
} else {
detectPlugin = function (name) {
var axo;
try {
axo = new ActiveXObject(name);
} catch (e) {
}
return !!axo;
};
plugins = {
fla: detectPlugin("ShockwaveFlash.ShockwaveFlash"),
qt: detectPlugin("QuickTime.QuickTime"),
wmp: detectPlugin("wmplayer.ocx"),
f4m: false
};
}
this.container.data('plugins.wijlightbox', plugins);
}
return plugins;
};
wijlightbox.prototype._sanitizeSelector = function (hash) {
// we need this because an id may contain a ":"
return hash.replace(/:/g, '\\:');
};
wijlightbox.prototype._getFragmentId = function (a) {
var fragmentId = /^#.+/, href = // Safari 2 reports '#' for an empty hash
$(a).attr('href') || "", hrefBase = href.split('#')[0], baseEl = $('base')[0];
if(hrefBase && (hrefBase === window.location.toString().split('#')[0] || (baseEl && hrefBase === baseEl.attributes["href"]))) {
href = a.hash;
a.href = href;
}
// inline links
return fragmentId.test(href) ? this._sanitizeSelector(href) : "";
};
wijlightbox.prototype._parseLink = function (a) {
var self = this, o = this.options, $a = $(a), opt = {
href: undefined,
player: undefined,
img: undefined,
gallery: undefined
}, rel, $img, gallery, index, props = [
'href',
'player',
'title',
'alt',
'height',
'width',
'gallery',
'wijvideosrc'
];
if($a.length > 0 && $a[0].tagName.toLowerCase() === 'a') {
rel = $a.attr('rel');
$.each(props, function (i, o) {
opt[o] = $a.attr(o) || '';
});
if(!opt.href) {
return;
}
if(!opt.player) {
opt.player = o.player || self._getPlayerName(opt.href);
}
$img = $a.find('img');
if($img && $img.length === 0) {
$img = $a;
}
if($img && $img.length >= 1) {
$.each([
'title',
'alt'
], function (i, o) {
opt[o] = $img.attr(o) || opt[o];
});
opt.img = $img;
}
if(rel) {
gallery = rel.match(/\[(.*?)\]/);
if(gallery) {
opt.gallery = gallery[1] || opt.gallery;
}
$.each(rel.split(";"), function (i, p) {
var match = p.match(/\s*([a-z_]*?)\s*=\s*(.+)\s*/);
if(match) {
opt[match[1]] = match[2];
}
});
}
if(opt.player === 'inline') {
opt.href = self._getFragmentId(a);
}
if(!opt.gallery) {
$a.bind({
'click': function (e) {
e.stopPropagation();
e.preventDefault();
if(!o.disabled) {
self._open($img, opt);
}
return false;
}
});
} else {
index = o.groupItems.length;
o.groupItems[index] = opt;
$a.bind({
'click': function (e) {
e.stopPropagation();
e.preventDefault();
if(!o.disabled) {
self._open($img, index);
}
return false;
}
});
}
}
};
wijlightbox.prototype._parse = function () {
var self = this;
this._parseLink(this.element);
this.element.find('a[rel^="wijlightbox"], a[rel^="lightbox"]').each(function (index, element) {
self._parseLink(element);
});
};
wijlightbox.prototype._showAccessories = function (fade) {
this.container.data('accessvisible.wijlightbox', true);
this._showNavButtons(fade);
this._showToolboxButtons(fade);
this._showCounter(fade);
};
wijlightbox.prototype._hideAccessories = function (fade) {
this.container.data('accessvisible.wijlightbox', false);
this._hideNavButtons(fade);
this._hideToolboxButtons(fade);
this._hideCounter(fade);
};
wijlightbox.prototype._groupMode = function () {
var o = this.options;
return (o.groupItems && o.groupItems.length > 1);
};
wijlightbox.prototype._resetText = function () {
this._removeText();
this._createText();
};
wijlightbox.prototype._createText = function (updateOnly) {
var self = this, o = self.options, cs, $text, $mask, $title, $detail;
if(o.textPosition === 'none') {
return;
}
if(this.container.find('.wijmo-wijlightbox-text').length) {
return;
}
cs = o.textPosition.toLowerCase();
$text = $('<div></div>').addClass('wijmo-wijlightbox-text wijmo-wijlightbox-text-' + cs + ' ' + o.wijCSS.content + ' ' + o.wijCSS.helperClearFix);
$title = $('<h3></h3>').addClass('wijmo-wijlightbox-title wijmo-wijlightbox-title-' + cs + ' ' + o.wijCSS.helperClearFix).appendTo($text);
$detail = $('<p></p>').addClass('wijmo-wijlightbox-detail wijmo-wijlightbox-detail-' + cs + ' ' + o.wijCSS.helperClearFix).appendTo($text);
if(o.textPosition === 'inside') {
$text.addClass(o.wijCSS.content + ' ' + o.wijCSS.helperClearFix).width(this.frame.width()).appendTo(this.frame);
} else if(o.textPosition === 'outside') {
$text.addClass([
o.wijCSS.content,
o.wijCSS.cornerAll,
o.wijCSS.helperClearFix
].join(' ')).width(this.frame.width()).appendTo(this.container);
} else if(o.textPosition === 'overlay' || o.textPosition === 'titleOverlay') {
$mask = $('<div></div>').addClass('wijmo-wijlightbox-mask wijmo-wijlightbox-mask-' + cs + ' ' + o.wijCSS.helperClearFix).width(this.frame.width()).appendTo(this.frame);
$text.width(this.frame.width()).appendTo(this.frame);
if(o.textPosition === 'titleOverlay') {
$text.bind({
'mouseenter': function () {
$mask.stop();
$text.stop();
var totalHeight = $title.outerHeight(true) + $detail.outerHeight(true), animOption = $.extend({
}, self._defaults.textShowOption, o.textShowOption, {
queue: false
});
$mask.animate({
height: totalHeight
}, animOption);
$text.animate({
height: totalHeight
}, animOption);
},
'mouseleave': function () {
$mask.stop();
$text.stop();
var titleHeight = $title.height(), animOption = $.extend({
}, self._defaults.textHideOption, o.textHideOption, {
queue: false
});
$mask.animate({
height: titleHeight
}, animOption);
$text.animate({
height: titleHeight
}, animOption);
}
});
}
}
this._refreshText(updateOnly);
};
wijlightbox.prototype._removeText = function () {
this.container.find(".wijmo-wijlightbox-text," + ".wijmo-wijlightbox-mask").remove();
};
wijlightbox.prototype._getActiveItem = function () {
var o = this.options;
if(o.groupItems && o.groupItems.length && o.activeIndex >= 0 && o.activeIndex < o.groupItems.length) {
return o.groupItems[o.activeIndex];
}
return null;
};
wijlightbox.prototype._refreshText = function (updateOnly) {
var self = this, o = this.options, item, $text, $title, $detail, $mask;
if(o.textPosition === 'none') {
return;
}
item = this.container.data('item.wijlightbox') || this._getActiveItem();
if(!item) {
return;
}
$text = this.container.find('.wijmo-wijlightbox-text');
$title = this.container.find('.wijmo-wijlightbox-title');
$detail = this.container.find('.wijmo-wijlightbox-detail');
$mask = this.container.find('.wijmo-wijlightbox-mask');
$mask.stop();
$text.stop();
$title.html(item.title);
$detail.html(item.alt);
if(o.textPosition === 'outside') {
$text.width(this.frame.width());
}
var titleHeight = $title.outerHeight(true), detailHeight = $detail.outerHeight(true);
// var toHeight = o.textPosition === 'titleOverlay' ?
// titleHeight :
// $text.height();
var animOption = $.extend({
}, self._defaults.textShowOption, o.textShowOption, {
queue: false
});
if(o.textPosition === 'overlay' || o.textPosition === 'titleOverlay') {
var toHeitht = titleHeight + (o.textPosition === 'overlay' ? detailHeight : 0);
$text.height(0);
$mask.height(0);
$text.animate({
height: toHeitht
}, animOption);
$mask.animate({
height: toHeitht
}, animOption);
} else {
if(!!updateOnly) {
$text.height(titleHeight + detailHeight);
} else {
$text.height(0);
$text.animate({
height: titleHeight + detailHeight
}, animOption);
}
}
};
wijlightbox.prototype._addState = function (state, el) {
if(el.is(':not(.' + this.options.wijCSS.stateDisabled + ')')) {
el.addClass('ui-state-' + state);
}
};
wijlightbox.prototype._removeState = function (state, el) {
el.removeClass('ui-state-' + state);
};
wijlightbox.prototype._createNavButtons = function () {
var self = this, o = this.options;
if(!o.showNavButtons || !this._groupMode()) {
this._removeNavButtons();
return;
}
if(!this.backBtn) {
this.backBtn = $("<a href='#'/>").addClass('wijmo-wijlightbox-button ' + 'wijmo-wijlightbox-button-prev ' + o.wijCSS.stateDefault + ' ' + (o.controlsPosition === 'inside' ? o.wijCSS.cornerRight : o.wijCSS.cornerLeft)).append("<span class='" + o.wijCSS.icon + " " + o.wijCSS.iconArrowLeft + "'></span>").hide().appendTo(this.frame).bind({
'click': function () {
if(!$(this).hasClass(o.wijCSS.stateDisabled)) {
self.back();
}
return false;
},
'mouseover': function () {
self._addState('hover', $(this));
},
'mouseout': function () {
self._removeState('hover', $(this));
},
'mousedown': function () {
self._addState('active', $(this));
},
'mouseup': function () {
self._removeState('active', $(this));
}
});
}
if(!this.nextBtn) {
this.nextBtn = $("<a href='#'/>").addClass('wijmo-wijlightbox-button ' + 'wijmo-wijlightbox-button-next ' + o.wijCSS.stateDefault + ' ' + (o.controlsPosition === 'inside' ? o.wijCSS.cornerLeft : o.wijCSS.cornerRight)).append("<span class='" + o.wijCSS.icon + " " + o.wijCSS.iconArrowRight + "'></span>").hide().appendTo(this.frame).bind({
'click': function () {
if(!$(this).hasClass(o.wijCSS.stateDisabled)) {
self.next();
}
return false;
},
'mouseover': function () {
self._addState('hover', $(this));
},
'mouseout': function () {
self._removeState('hover', $(this));
},
'mousedown': function () {
self._addState('active', $(this));
},
'mouseup': function () {
self._removeState('active', $(this));
}
});
}
};
wijlightbox.prototype._removeNavButtons = function () {
if(this.backBtn) {
this.backBtn.remove();
this.backBtn = undefined;
}
if(this.nextBtn) {
this.nextBtn.remove();
this.nextBtn = undefined;
}
};
wijlightbox.prototype._refreshNavButtons = function () {
var o = this.options, operation;
if(this.backBtn) {
operation = o.activeIndex === 0 ? 'addClass' : 'removeClass';
this.backBtn[operation](o.wijCSS.stateDisabled);
}
if(this.nextBtn) {
operation = o.activeIndex >= o.groupItems.length - 1 ? 'addClass' : 'removeClass';
this.nextBtn[operation](o.wijCSS.stateDisabled);
}
};
wijlightbox.prototype._showNavButtons = function (anim) {
if(this.isPlaying()) {
return;
}
this.container.find('.wijmo-wijlightbox-button').stop(true, true).fadeIn(anim ? 600 : 0, function () {
$(this).css('opacity', '');
});
};
wijlightbox.prototype._hideNavButtons = function (anim) {
this.container.find('.wijmo-wijlightbox-button').stop(true, true).fadeOut(anim ? 600 : 0);
};
wijlightbox.prototype._createToolbox = function () {
if(!this.toolBox) {
this.toolBox = $("<div></div>").addClass('wijmo-wijlightbox-toolbox').appendTo(this.frame);
}
};
wijlightbox.prototype._showToolboxButtons = function (anim) {
this.container.find('.wijmo-wijlightbox-toolbox-button').stop(true, true).fadeIn(anim ? 600 : 0, function () {
$(this).css('opacity', '');
});
};
wijlightbox.prototype._hideToolboxButtons = function (anim) {
this.container.find('.wijmo-wijlightbox-toolbox-button').stop(true, true).fadeOut(anim ? 600 : 0);
};
wijlightbox.prototype._createCtrlButtons = function () {
var self = this, o = this.options, wijCSS = o.wijCSS;
if(!o.ctrlButtons || o.ctrlButtons.length === 0 || !this._groupMode()) {
this._removeCtrlButtons();
return;
}
this._createToolbox();
var buttons = o.ctrlButtons.split('|');
if(buttons.length === 1 && buttons[0] === o.ctrlButtons) {
buttons = o.ctrlButtons.split(',');
}
$.each(buttons, function (index, name) {
name = $.trim(name);
if(name === 'play' && !this.playBtn) {
self.playBtn = $("<a href='#'/>").addClass([
'wijmo-wijlightbox-toolbox-button',
' wijmo-wijlightbox-toolbox-button-play ',
wijCSS.stateDefault,
wijCSS.cornerAll
].join(' ')).append("<span class='" + wijCSS.icon + " " + wijCSS.iconPlay + "'></span>").hide().click(function () {
if(self.isPlaying()) {
self.stop();
} else {
if(o.activeIndex >= o.groupItems.length - 1) {
self.show(0);
}
self.play();
}
return false;
});
} else if(name === 'stop' && !this.stopBtn) {
self.stopBtn = $("<a href='#'/>").addClass([
'wijmo-wijlightbox-toolbox-button',
'wijmo-wijlightbox-toolbox-button-stop',
wijCSS.stateDefault,
wijCSS.stateDisabled,
wijCSS.cornerAll
].join(' ')).append("<span class='" + wijCSS.icon + " " + wijCSS.iconStop + "'></span>").hide().click(function () {
if(self.isPlaying()) {
self.stop();
self.show(0);
}
return false;
});
}
});
if(this.stopBtn) {
this.stopBtn.appendTo(this.toolBox);
}
if(this.playBtn) {
this.playBtn.appendTo(this.toolBox);
}
};
wijlightbox.prototype._removeCtrlButtons = function () {
if(this.playBtn) {
this.playBtn.remove();
this.playBtn = undefined;
}
if(this.stopBtn) {
this.stopBtn.remove();
this.stopBtn = undefined;
}
};
wijlightbox.prototype._refreshCtrlButtons = function () {
var css = this.options.wijCSS;
if(this.playBtn) {
var icon = this.playBtn.find('.' + css.icon);
if(icon) {
icon.removeClass(css.iconPause + ' ' + css.iconPlay);
icon.addClass(this.isPlaying() ? css.iconPause : css.iconPlay);
}
}
if(this.stopBtn) {
this.stopBtn[!this.isPlaying() ? 'addClass' : 'removeClass'](css.stateDisabled);
}
};
wijlightbox.prototype._createDialogButtons = function () {
var self = this, o = this.options, buttons;
if(!o.dialogButtons || o.dialogButtons.length === 0) {
this._removeDialogButtons();
return;
}
this._createToolbox();
buttons = o.dialogButtons.split('|');
if(buttons.length === 1 && buttons[0] === o.dialogButtons) {
buttons = o.dialogButtons.split(',');
}
$.each(buttons, function (index, name) {
name = $.trim(name);
if(name === 'close' && !this.closeBtn) {
self.closeBtn = $("<a href='#'/>").addClass('wijmo-wijlightbox-toolbox-button ' + 'wijmo-wijlightbox-toolbox-button-close ' + o.wijCSS.stateDefault + ' ' + o.wijCSS.cornerAll).append("<span class='" + o.wijCSS.icon + " " + o.wijCSS.iconClose + "'></span>").hide().click(function () {
self._close();
return false;
});
} else if(name === 'fullSize' && !this.fullBtn) {
self.fullBtn = $("<a href='#'/>").addClass('wijmo-wijlightbox-toolbox-button ' + 'wijmo-wijlightbox-toolbox-button-fullsize ' + o.wijCSS.stateDefault + ' ' + o.wijCSS.cornerAll).append("<span class='" + o.wijCSS.icon + " " + o.wijCSS.iconArrow4Diag + "'></span>").hide().click(function () {
self._toggleFullSize();
return false;
});
}
});
if(this.closeBtn) {
this.closeBtn.appendTo(this.toolBox);
}
if(this.fullBtn) {
this.fullBtn.appendTo(this.toolBox);
}
if(!this.btnSep) {
this.btnSep = $("<a href='#'/>").addClass('wijmo-wijlightbox-toolbox-separator').appendTo(this.toolBox);
}
};
wijlightbox.prototype._removeDialogButtons = function () {
if(this.closeBtn) {
this.closeBtn.remove();
this.closeBtn = undefined;
}
if(this.fullBtn) {
this.fullBtn.remove();
this.fullBtn = undefined;
}
};
wijlightbox.prototype._refreshDialogButtons = function () {
var css = this.options.wijCSS;
if(this.fullBtn) {
var icon = this.fullBtn.find('.' + css.icon);
if(icon) {
icon.removeClass(css.iconArrow4Diag + ' ' + css.iconNewWin);
icon.addClass(this._isFullSize() ? css.iconNewWin : css.iconArrow4Diag);
}
}
};
wijlightbox.prototype._createTimerBar = function () {
var self = this, o = self.options;
if(!o.showTimer || !self._groupMode()) {
self._removeTimerBar();
return;
}
self._createToolbox();
if(!self.timerBar) {
self.timerBar = $("<div></div>").addClass('wijmo-wijlightbox-timerbar ' + o.wijCSS.content + ' ui-priority-secondary ' + o.wijCSS.cornerAll).appendTo(self.toolBox);
self.timerMeter = $("<div></div>").addClass('wijmo-wijlightbox-timermeter ui-progressbar-value ' + o.wijCSS.content + ' ' + o.wijCSS.cornerAll).appendTo(self.toolBox);
}
};
wijlightbox.prototype._removeTimerBar = function () {
if(this.timerMeter) {
this.timerMeter.remove();
this.timerMeter = undefined;
}
if(this.timerBar) {
this.timerBar.remove();
this.timerBar = undefined;
}
};
wijlightbox.prototype._createCounter = function () {
var self = this, o = self.options;
if(!o.showCounter || !self._groupMode()) {
self._removeCounter();
return;
}
if(!self.counter) {
self.counter = $("<div></div>").addClass('wijmo-wijlightbox-counter ' + o.wijCSS.stateDefault + ' ' + (o.controlsPosition === 'inside' ? o.wijCSS.cornerTL : o.wijCSS.cornerAll)).hide().appendTo(self.frame);
}
};
wijlightbox.prototype._removeCounter = function () {
if(this.counter) {
this.counter.remove();
this.counter = undefined;
}
};
wijlightbox.prototype._refreshCounter = function (index) {
var self = this, o = this.options, counter = "";
if(!this.counter || !this._groupMode()) {
return;
}
this.counter.empty();
if(o.showCounter && o.groupItems.length > 1 && this.counter) {
if(index === undefined) {
index = o.activeIndex;
}
var len = o.groupItems.length;
if(o.counterType === "sequence") {
var start = 0, end = len, limit = parseInt(o.counterLimit, 10) || 0;
if(limit >= 2 && limit < len) {
var h = Math.floor(limit / 2);
start = Math.min(end - limit, Math.max(start, index - h));
end = Math.min(end, start + limit);
}
while(start !== end) {
$("<a></a>").addClass('wijmo-wijlightbox-counter-item ' + o.wijCSS.content + ' ' + o.wijCSS.stateDefault + (start === index ? ' wijmo-wijlightbox-counter-active ' + o.wijCSS.stateActive : '')).text((++start).toString()).appendTo(this.counter);
}
this.counter.find('a').click(function (event, data) {
if($(this).hasClass('wijmo-wijlightbox-counter-active')) {
return false;
}
self.show(parseInt($(this).text(), 10) - 1);
return false;
});
} else {
var fmt = o.counterFormat || "[i] of [n]";
counter = fmt.replace('[i]', index + 1);
counter = counter.replace('[n]', len);
$("<span></span>").text(counter).appendTo(this.counter);
}
}
};
wijlightbox.prototype._showCounter = function (anim) {
this.container.find('.wijmo-wijlightbox-counter').stop(true, true).fadeIn(anim ? 600 : 0, function () {
$(this).css('opacity', '');
});
};
wijlightbox.prototype._hideCounter = function (anim) {
this.container.find('.wijmo-wijlightbox-counter').stop(true, true).fadeOut(anim ? 600 : 0);
};
wijlightbox.prototype._cookie = function (name, value) {
var cookie = this.cookie || (this.cookie = this.options.cookie.name);
return $.cookie.apply(null, [
cookie
].concat($.makeArray(arguments)));
};
wijlightbox.prototype._showOverlay = function () {
if(this.container.data('overlay.wijlightbox')) {
return;
}
this.container.data('overlay.wijlightbox', new $.wijmo.wijlightbox.overlay(this));
};
wijlightbox.prototype._hideOverlay = function () {
var $overlay = this.container.data('overlay.wijlightbox');
if(!$overlay) {
return;
}
$overlay.close();
this.container.removeData('overlay.wijlightbox');
};
wijlightbox.prototype._hasOverlay = function () {
return this.container.hasData('overlay.wijlightbox');
};
wijlightbox.prototype._showWaiting = function () {
if(this.container.data('waiting.wijlightbox')) {
return;
}
this.container.data('waiting.wijlightbox', new $.wijmo.wijlightbox.overlay(this, true));
};
wijlightbox.prototype._hideWaiting = function () {
var $overlay = this.container.data('waiting.wijlightbox');
if(!$overlay) {
return;
}
$overlay.close();
this.container.removeData('waiting.wijlightbox');
};
wijlightbox.prototype._hasWaiting = function () {
return this.container.hasData('waiting.wijlightbox');
};
wijlightbox.prototype._getUrl = function (item) {
var o = this.options, url = (typeof item === 'string') ? item : item.href, rootUrl = o.rootUrl;
if(rootUrl && rootUrl.length > 0) {
if(rootUrl.indexOf('//') === -1) {
rootUrl = window.location.protocol + '//' + window.location.host + (rootUrl.startsWith('/') ? '' : '/') + rootUrl;
}
if(rootUrl.substr(rootUrl.length - 1, 1) !== '/') {
rootUrl += '/';
}
url = rootUrl + (url.substr(0, 1) === '/' ? url.substr(1) : url);
}
return url;
};
wijlightbox.prototype._preload = function () {
var o = this.options, i;
for(i = Math.max(0, o.activeIndex); i < Math.min(o.activeIndex + 5, o.groupItems.length); i++) {
if(!o.groupItems[i].image) {
o.groupItems[i].image = new Image();
o.groupItems[i].image.src = this._getUrl(o.groupItems[i]);
}
}
};
wijlightbox.prototype._slideAnimate = function (o, el, done) {
var props = [
"position",
"top",
"bottom",
"left",
"right",
"width",
"height"
], mode = $.setMode(el, o.mode || "show"), show = mode === "show", direction = o.direction || "left", ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), distance, animation = {
};
// Adjust
$.save(el, props);
el.show();
distance = o.distance || el[ref === "top" ? "outerHeight" : "outerWidth"](true);
$.createWrapper(el).css({
overflow: "hidden"
});
if(show) {
el.css(ref, positiveMotion ? (isNaN(distance) ? parseInt("-" + distance) : -distance) : distance);
}
// Animation
animation[ref] = (show ? (positiveMotion ? "+=" : "-=") : (positiveMotion ? "-=" : "+=")) + distance;
el.animate(animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function () {
if(mode === "hide") {
el.hide();
}
$.restore(el, props);
$.removeWrapper(el);
done();
}
});
};
wijlightbox.prototype._slideTo = function (prevPlayer, player, animation, next, complete) {
var o = this.options, self = this, curImage = prevPlayer.getElement(), wrapper, slideContainer, direction, w, h, $img, slideCallback, slideOpts;
if(curImage.parent().is('.wijmo-wijlightbox-aniwrapper')) {
wrapper = curImage.parent();
} else {
wrapper = $.createWrapper(curImage).css({
overflow: 'hidden'
});
wrapper.removeClass('ui-effects-wrapper');
wrapper.addClass('wijmo-wijlightbox-aniwrapper');
}
if(wrapper.parent().is('.wijmo-wijlightbox-aniwrapper')) {
slideContainer = wrapper.parent();
} else {
slideContainer = $.createWrapper(wrapper).css({
overflow: 'hidden'
});
slideContainer.removeClass('ui-effects-wrapper');
slideContainer.addClass('wijmo-wijlightbox-aniwrapper');
}
direction = o.slideDirection || 'horizontal';
w = curImage.outerWidth();
h = curImage.outerHeight();
if(direction === 'horizontal') {
curImage.width(w).css('float', next ? 'left' : 'right');
wrapper.width(2 * w).css({
left: (next ? 0 : -1 * w),
position: 'absolute'
});
} else {
curImage.height(h);
wrapper.width(w).css({
top: (next ? 0 : -1 * h),
position: 'absolute'
}).height(2 * h);
}
player.appendTo(wrapper);
$img = player.getElement();
if(direction === 'horizontal') {
$img.width(w).css('float', next ? 'left' : 'right');
} else {
$img.height(h);
}
this.container.data('animating.wijlightbox', true);
slideCallback = function () {
curImage = wrapper.children(':last');
while(curImage.parent().is('.wijmo-wijlightbox-aniwrapper')) {
curImage.parent().replaceWith(curImage);
}
curImage.css({
float: '',
width: '',
height: ''
});
if(o.autoSize && !self._isFullSize()) {
self._resize(complete);
} else {
if($.isFunction(complete)) {
complete.apply(self);
}
self._refreshText();
}
};
slideOpts = {
mode: 'hide',
direction: direction === 'horizontal' ? (next ? 'left' : 'right') : (next ? 'up' : 'down'),
easing: animation.easing,
distance: direction === 'horizontal' ? w : h,
duration: animation.duration
};
if($.effects) {
wrapper.effect('slide', slideOpts, slideCallback);
} else {
self._slideAnimate(slideOpts, wrapper, slideCallback);
}
};
wijlightbox.prototype._moveFrom = function (rect, animation, complete) {
var self = this, o = this.options, toRect;
if($.isFunction(animation)) {
complete = animation;
animation = $.extend({
}, self._defaults.resizeAnimation, o.resizeAnimation);
} else {
animation = $.extend({
}, self._defaults.resizeAnimation, o.resizeAnimation, animation);
}
self._removeText();
if(animation.animated === 'none' || animation.duration <= 0) {
self._createText();
if($.isFunction(complete)) {
complete.apply(self);
}
this.container.data('moving.wijlightbox', false);
return;
}
toRect = $.extend({
width: self.frame.width(),
height: self.frame.height()
}, self.container.offset());
self.frame.width(rect.width).height(rect.height);
self.container.css({
left: rect.left,
top: rect.top,
width: self.frame.outerWidth(),
position: 'absolute',
opacity: ''
});
self._moveTo(toRect, animation, function () {
self.frame.width(toRect.width);
self.container.width(self.frame.outerWidth());
self._createText();
self.container.data('moving.wijlightbox', false);
if($.isFunction(complete)) {
complete.apply(self);
}
});
};
wijlightbox.prototype._moveTo = function (rect, animation, complete) {
var self = this, o = this.options;
if($.isFunction(animation)) {
complete = animation;
animation = $.extend({
}, self._defaults.resizeAnimation, o.resizeAnimation);
} else {
animation = $.extend({
}, self._defaults.resizeAnimation, o.resizeAnimation, animation);
}
var hd = animation.duration / 2, animated = animation.animated, movePos = self._isOpen(), pos1 = animated === 'wh' ? {
left: rect.left,
top: undefined
} : {
top: rect.top
}, pos2 = animated === 'wh' ? {
top: rect.top,
left: undefined
} : {
left: rect.left
}, size1 = animated === 'wh' ? {
width: rect.width,
height: undefined
} : {
height: rect.height
}, size2 = animated === 'wh' ? {
height: rect.height,
width: undefined
} : {
width: rect.width
};
if(animated === 'wh' || animated === 'hw') {
if(movePos) {
self.container.animate(pos1, {
duration: hd,
easing: animation.easing,
queue: true
});
}
self.frame.animate(size1, {
duration: hd,
easing: animation.easing,
complete: function () {
if(movePos) {
self.container.animate(pos2, {
duration: hd,
easing: animation.easing,
queue: true
});
}
self.frame.animate(size2, {
duration: hd,
easing: animation.easing,
complete: function () {
self.container.data('moving.wijlightbox', false);
if($.isFunction(complete)) {
complete.apply(self);
}
}
});
}
});
return;
}
if(movePos) {
self.container.animate({
left: rect.left,
top: rect.top
}, {
duration: animation.duration,
easing: animation.easing,
queue: true
});
}
self.frame.animate({
width: rect.width,
height: rect.height,
opacity: 1
}, {
duration: animation.duration,
easing: animation.easing,
complete: function () {
self.container.data('moving.wijlightbox', false);
if($.isFunction(complete)) {
complete.apply(self);
}
}
});
};
wijlightbox.prototype.show = /** Shows the content in specified index.
* @example $("#id").wijlightbox('show');
* @param {number} index The zero-based index of the picture to show.
*/
function (index) {
this._show(index);
return this;
};
wijlightbox.prototype._resize = function (complete) {
var self = this, rect = $.extend({
}, self.container.offset(), {
width: self.frame.width(),
height: self.frame.height()
});
self._size();
if(self._isOpen()) {
self._position();
}
self._moveFrom(rect, complete);
};
wijlightbox.prototype._onAfterShow = function () {
var self = this, o = this.options, data;
self._refreshNavButtons();
self.container.data('animating.wijlightbox', false);
if(!o.modal) {
self._hideOverlay();
}
data = {
index: o.activeIndex,
item: o.groupItems[o.activeIndex]
};
self._trigger('show', null, data);
self._startTimer();
};
wijlightbox.prototype._show = function (item, next, complete) {
var self = this, o = this.options, sq, index;
if(this.container.data('showing.wijlightbox')) {
sq = [
function () {
self._show(item, next, complete);
} ];
this.container.queue('showqueue', sq);
return this;
}
index = o.activeIndex;
if(!$.isPlainObject(item)) {
index = item;
if(index < 0 || index >= o.groupItems.length) {
return this;
}
item = o.groupItems[index];
}
if(item) {
this.container.data('item.wijlightbox', item);
}
if(this._groupMode()) {
this._preload();
}
if($.isFunction(next)) {
complete = next;
next = undefined;
}
if(!complete) {
complete = self._onAfterShow;
}
var data = {
index: index,
item: item
};
if(self._trigger('beforeShow', null, data) === false) {
return this;
}
this.container.data('showing.wijlightbox', true);
var cleanup = function () {
if($.isFunction(complete)) {
complete.apply(self);
}
self.container.data('showing.wijlightbox', false);
self.container.dequeue('showqueue');
self.container.clearQueue('showqueue');
};
self._refreshCounter(index);
var prevPlayer = this.container.data('player.wijlightbox'), player, onload = function () {
self.container.data('playerwidth.wijlightbox', player.width);
self.container.data('playerheight.wijlightbox', player.height);
var animation = $.extend({
}, self._defaults.transAnimation, o.transAnimation);
if(o.activeIndex === index || animation.animated === 'none' || animation.duration <= 0 || !self._isOpen()) {
o.activeIndex = index;
if(prevPlayer) {
prevPlayer.remove();
}
player.appendTo(self.content);
self._refreshText();
cleanup();
return;
}
if(o.cookie) {
self._cookie(o.activeIndex, o.cookie);
}
if(animation.animated === 'slide') {
next = (next === undefined) ? (index > o.activeIndex) : next;
self._slideTo(prevPlayer, player, animation, next, cleanup);
o.activeIndex = index;
} else {
o.activeIndex = index;
var fadeIn = function () {
if(player) {
player.appendTo(self.content, true);
player.fadeIn(animation.duration, cleanup);
}
};
if($.browser.msie) {
self.frame.trigger('mouseleave');
}
var onFadeOut = function () {
if(prevPlayer) {
prevPlayer.remove();
}
if(o.autoSize && !self._isFullSize()) {
self._resize(fadeIn);
} else {
fadeIn();
self._refreshText();
}
};
if(prevPlayer) {
prevPlayer.fadeOut(animation.duration * 0.4, onFadeOut);
} else {
onFadeOut();
}
}
};
player = this._createPlayer(item, onload);
return this;
};
wijlightbox.prototype.next = /** Moves to the next panel.*/
function () {
var o = this.options;
if(!this._groupMode()) {
return false;
}
var index = o.activeIndex + 1;
if(o.loop) {
index = index % o.groupItems.length;
}
if(index < o.groupItems.length) {
this._show(index, true);
return true;
}
return false;
};
wijlightbox.prototype.back = /** Moves to the previous panel.*/
function () {
var o = this.options;
if(!this._groupMode()) {
return false;
}
var index = o.activeIndex - 1;
if(o.loop) {
index = index < 0 ? o.groupItems.length - 1 : index;
}
if(index >= 0) {
this._show(index, false);
return true;
}
return false;
};
wijlightbox.prototype.adjustPosition = /**
* Adjust the position of lightbox according to the "position" option set it originally to a new location. .
* It is usually called after window resized.
*/
function () {
this._position();
};
wijlightbox.prototype.isPlaying = /**
* Determines whether the lightbox is currently displaying images automatically.See the play method for more information.
* @returns {boolean} A value that indicate whether it is playing.
*/
function () {
return !!this.container.data('playing.wijlightbox');
};
wijlightbox.prototype._startTimer = function () {
if(!this.isPlaying() || !this._groupMode()) {
return;
}
var o = this.options, self = this, width;
if(o.showTimer === true) {
if(!this.timerMeter) {
this._createTimerBar();
}
width = this.timerBar.width();
self.timerMeter.width('0');
self.timerMeter.animate({
width: width
}, o.delay, null, function () {
if(self.isPlaying() && !self.next()) {
self.stop();
}
});
} else {
window.setTimeout(function () {
if(self.isPlaying() && !self.next()) {
self.stop();
}
}, o.delay);
}
};
wijlightbox.prototype.play = /** Starts displaying the images in order automatically.*/
function () {
if(!this._groupMode()) {
return false;
}
if(!this.container.data('playing.wijlightbox')) {
this.container.data('playing.wijlightbox', true);
}
this._refreshCtrlButtons();
this._hideNavButtons();
this._startTimer();
};
wijlightbox.prototype.stop = /** Stops the slide playing mode.*/
function () {
this.container.removeData('playing.wijlightbox');
this._refreshCtrlButtons();
this._removeTimerBar();
};
wijlightbox.prototype._size = function (size, calcOnly) {
var o = this.options, width = o.width, height = o.height, playerWidth = o.autoSize ? (this.container.data('playerwidth.wijlightbox') || width) : width, playerHeight = o.autoSize ? (this.container.data('playerheight.wijlightbox') || height) : height, player, ratio = playerHeight / playerWidth;
if(typeof size === 'boolean') {
calcOnly = size;
} else if($.isPlainObject(size) && ('width' in size) && ('height' in size)) {
width = size.width;
height = size.height;
} else {
player = this.container.data('player.wijlightbox');
if(o.autoSize && (player && player.name === 'img')) {
if(playerWidth > width) {
playerWidth = width;
playerHeight = Math.round(width * ratio);
}
if(playerHeight > height) {
playerHeight = height;
playerWidth = Math.round(height / ratio);
}
}
width = playerWidth;
height = playerHeight;
if(calcOnly) {
return {
width: width,
height: height
};
}
}
this.frame.width(width).height(height);
this.container.width(this.frame.outerWidth(true));
};
wijlightbox.prototype._position = function () {
var o = this.options, myAt = [], offset = [
0,
0
], isVisible, pos = o.position;
if(pos) {
// deep extending converts arrays to objects in jQuery <= 1.3.2 :-(
if(typeof pos === 'string' || (typeof pos === 'object' && '0' in pos)) {
myAt = pos.split ? pos.split(' ') : [
pos[0],
pos[1]
];
if(myAt.length === 1) {
myAt[1] = myAt[0];
}
$.each([
'left',
'top'
], function (i, offsetPosition) {
if(+myAt[i] === myAt[i]) {
offset[i] = myAt[i];
myAt[i] = offsetPosition;
}
});
pos = {
my: myAt.join(" "),
at: myAt.join(" "),
offset: offset.join(" ")
};
}
pos = $.extend({
}, o.position, pos);
}
// need to show the dialog to get the actual offset in the position plugin
isVisible = this.container.is(':visible');
if(!isVisible) {
this.container.show();
}
this.container.css(// workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781
{
top: 0,
left: 0
}).position(pos);
if(!isVisible) {
this.container.hide();
}
};
wijlightbox.prototype._getRelRect = function (rel) {
var rect;
if(rel) {
if($.isPlainObject(rel) && ('left' in rel) && ('top' in rel) && ('width' in rel) && ('height' in rel)) {
rect = $.merge({
}, rel);
} else {
rel = $(rel);
}
if(rel.jquery && rel.length) {
rect = $.extend({
}, rel.offset(), {
width: rel.width(),
height: rel.height()
});
}
}
return rect;
};
wijlightbox.prototype._close = function (rel) {
var o = this.options, self = this, rect, data, complete;
if(!this._isOpen()) {
return;
}
data = {
rel: rel
};
if(false === this._trigger('beforeClose', null, data)) {
return;
}
rel = data.rel;
if(!rel && this._groupMode()) {
rel = o.groupItems[o.activeIndex].img;
}
this.container.data('moving.wijlightbox', true);
this._hideAccessories(false);
this._hideWaiting();
this._hideOverlay();
this.stop();
complete = function () {
self._removePlayer();
self.container.hide();
self._trigger('close');
self.container.unbind('keypress.wijlightbox');
self.container.removeData('open.wijlightbox').removeData('rect.wijlightbox').removeData('moving.wijlightbox').removeData('fullsize.wijlightbox');
$(document).unbind('keydown.wijlightbox').unbind('click.wijlightbox');
};
rect = this._getRelRect(rel);
if(!rect) {
if(this.container.data('rect.wijlightbox')) {
rect = this.container.data('rect.wijlightbox');
}
}
this._removeText();
if(rect) {
this._moveTo(rect, {
animated: 'sync',
duration: 200
}, complete);
return;
}
complete.call();
return this;
};
wijlightbox.prototype._isOpen = function () {
return !!this.container.data('open.wijlightbox');
};
wijlightbox.prototype._open = function (rel, item) {
if(this._isOpen()) {
return;
}
var o = this.options, self = this;
if(this.toolBox) {
if(this._isFullSize()) {
this.toolBox.css({
top: '2px',
right: '4px'
});
} else {
this.toolBox.css({
top: '',
right: ''
});
}
}
var complete = function () {
if(o.modal) {
self._showOverlay();
}
if(o.showControlsOnHover) {
this._hideAccessories(false);
} else {
this._showAccessories(false);
}
var rect = self._getRelRect(rel);
self.container.css('opacity', 0);
self.container.show();
self._size();
self._createText(true);
self._refreshText(true);
self._position();
self.container.data('open.wijlightbox', true);
if(rel && rect) {
self.container.data('rect.wijlightbox', rect);
self._moveFrom(rect, {
animated: 'sync'
});
} else {
var animation = $.extend({
}, self._defaults.transAnimation, o.transAnimation);
if(animation.animated === 'fade') {
self.container.hide();
self.container.fadeIn(animation.duration, function () {
self._createText();
});
} else {
self._createText();
}
this.container.data('moving.wijlightbox', false);
}
$(document).bind('keydown.wijlightbox', $.proxy(self, '_keyDownHandler')).bind('click.wijlightbox', function (e) {
var srcElement = e.target || e.srcElement;
if(self._isOpen() && !!o.closeOnOuterClick) {
if(srcElement !== self.container.get(0) && $(srcElement).parents().index(self.container) < 0) {
self._close();
}
}
});
if(o.autoPlay) {
this.play();
}
self._refreshNavButtons();
self._refreshDialogButtons();
var data = {
index: o.activeIndex,
item: o.groupItems[o.activeIndex]
};
self._trigger('show', null, data);
self._trigger('open');
};
this.container.data('moving.wijlightbox', true);
this._show(item, true, complete);
return this;
};
wijlightbox.prototype._getWinRect = function () {
var $win = $(window);
return $.extend({
width: $win.width(),
height: $win.height()
}, $win.offset() || {
left: 2,
top: 2
});
};
wijlightbox.prototype._resizeHandler = function () {
var self = this;
self._removeText();
self._size(self._getWinRect());
self._createText();
};
wijlightbox.prototype._isFullSize = function () {
return !!this.container.data('fullsize.wijlightbox');
};
wijlightbox.prototype._toggleFullSize = function () {
var self = this, $win = $(window);
if(!self._isOpen()) {
return;
}
if(this._isFullSize()) {
if(self.toolBox) {
self.toolBox.css({
top: '',
right: ''
});
}
this.container.data('fullsize.wijlightbox', false);
$win.unbind('resize.wijlightbox', $.proxy(this, '_resizeHandler'));
self._resize(function () {
self._adjustPlayerSize(self.content.innerWidth(), self.content.innerHeight());
});
} else {
this.container.data('fullsize.wijlightbox', true);
$win.bind('resize.wijlightbox', $.proxy(this, '_resizeHandler'));
var toRect = self._getWinRect(), bd = this.frame.borderSize();
toRect.width -= bd.width;
toRect.height -= bd.height;
self._removeText();
self._moveTo(toRect, {
animated: 'sync'
}, function () {
if(self.toolBox) {
self.toolBox.css({
top: '2px',
right: '4px'
});
}
self.frame.width(toRect.width);
self.container.width(self.frame.outerWidth());
self._createText();
self._adjustPlayerSize(self.content.innerWidth(), self.content.innerHeight());
});
}
this._refreshDialogButtons();
};
wijlightbox.prototype._getExt = function (url) {
var ext, m, regExt = /[0-9a-z]+$/i, q = url.indexOf("?");
if(q > -1) {
url = url.substring(0, q);
}
m = url.match(regExt);
if(m) {
ext = m[0].toLowerCase();
}
return ext;
};
wijlightbox.prototype._getPlayerName = function (url) {
if(url.indexOf("#") === 0 || (url.indexOf("#") > 0 && url.indexOf(document.location.href) === 0)) {
return "inline";
}
var imgExt = [
"bmp",
"gif",
"jpg",
"jpeg",
"png"
], swfExt = [
"swf"
], flvExt = [
"flv",
"m4v"
], qtExt = [
"dv",
"mov",
"moov",
"movie",
"mp4",
"avi",
"mpg",
"mpeg"
], wmpExt = [
"asf",
"avi",
"mpg",
"mpeg",
"wm",
"wmv"
], html5Video = [
"mp4",
"mpg",
"mpeg",
"ogg",
"ogv"
], ext = this._getExt(url);
if(ext) {
if($.inArray(ext, imgExt) >= 0) {
return "img";
}
if($.inArray(ext, swfExt) >= 0) {
return "swf";
}
if($.inArray(ext, flvExt) >= 0) {
return "flv";
}
if($.inArray(ext, wmpExt) >= 0) {
return "wmp";
}
if($.inArray(ext, qtExt) >= 0) {
return "qt";
}
if($.inArray(ext, html5Video) >= 0) {
return "wijvideo";
}
}
return "iframe";
};
wijlightbox.prototype._adjustPlayerSize = function (width, height) {
var player = this.container.data('player.wijlightbox');
if(player && player.adjustSize) {
player.adjustSize(width, height);
}
};
wijlightbox.prototype._removePlayer = function () {
var player = this.container.data('player.wijlightbox');
if(player) {
player.remove();
this.container.data('player.wijlightbox', null);
}
};
wijlightbox.prototype._createPlayer = function (item, onload, onerror) {
var playerName = item.player;
if(!$.isFunction($.wijmo.wijlightbox[playerName])) {
throw "unknown player " + playerName;
}
var self = this, cached = false, player, handleLoad = function () {
cached = true;
this._hideWaiting();
if($.isFunction(onload)) {
window.setTimeout(function () {
onload.apply(self);
}, 1);
}
}, handlerError = function () {
this._hideWaiting();
if($.isFunction(onerror)) {
onerror.apply(self);
}
};
player = new $.wijmo.wijlightbox[playerName](this, item, handleLoad, handlerError);
this.container.data('player.wijlightbox', player);
window.setTimeout(function () {
if(cached === false) {
self._showWaiting();
}
}, 200);
return player;
};
return wijlightbox;
})(wijmo.wijmoWidget);
lightbox.wijlightbox = wijlightbox;
var wijlightbox_options = (function () {
function wijlightbox_options() {
/** wijMobileCSS
* @ignore
*/
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body-c",
stateDefault: "ui-btn-up-a",
stateHover: "ui-btn-down-a",
stateActive: "ui-btn-down-a",
iconPlay: "ui-icon-arrow-r",
iconPause: "ui-icon-grid"
};
/** Selector option for auto self initialization.
* This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijlightbox')";
/** Determines the position of text description.
* Possible values are:
* 'inside', 'outside', 'overlay', 'titleOverlay' and 'none'
* @type {string}
* @example
* $("#id").wijlightbox({
* textPosition: 'titleOverlay'
* });
*/
this.textPosition = 'overlay';
/** Determines the maximum width of the content.
* @example
* $("#id").wijlightbox({
* width: 800
* });
*/
this.width = 600;
/** Determines the maximum height of the content.
* @example
* $("#id").wijlightbox({
* height: 500
* });
*/
this.height = 400;
/** A value determines whether to auto-size to
* keep the original width/height ratio of content.
* @example
* $("#id").wijlightbox({
* autoSize: false
* });
*/
this.autoSize = true;
/** Determines the name of player to host the content.
* Possible values are:
* 'inline', 'iframe', 'img', 'swf', 'flv', 'wmp', 'qt', 'wijvideo'
* @example
* $("#id").wijlightbox({
* player: 'img'
* });
*/
this.player = '';
/** Determines the array of data items.
* @example
* $("#id").wijlightbox({
* groupItems: []
* });
*/
this.groupItems = null;
/** Determines the root url for each item.
*/
this.rootUrl = '';
/** Determines the visibility of the control buttons.
* Possible values are: 'play', 'stop' separated by '|'.
* @example
* $("#id").wijlightbox({
* ctrlButtons: 'play|stop'
* });
*/
this.ctrlButtons = '';
/** Determines the visibility of the dialog buttons.
* Possible values are: 'close', 'fullSize' separated by '|'.
* @example
* $("#id").wijlightbox({
* dialogButtons: 'close|fullSize'
* });
*/
this.dialogButtons = 'close';
/** Determines the type counter style.
* Possible values are: 'default', 'sequence'
* @example
* $("#id").wijlightbox({
* counterType: 'sequence'
* });
*/
this.counterType = 'default';
/** Determines the text format of counter.
* '[i]' and '[n]' are built-in parameters represents
* the current page index and the number of pages.
* @example
* $("#id").wijlightbox({
* counterFormat: '[i]/[n]'
* });
*/
this.counterFormat = '[i] of [n]';
/** Determines the maximum number of
* digit buttons in sequence counter type.
* @example
* $("#id").wijlightbox({
* counterLimit: 5
* });
*/
this.counterLimit = 10;
/** Determines whether to display the counter.
* @example
* $("#id").wijlightbox({
* showCounter: false
* });
*/
this.showCounter = true;
/** Determines whether to display the navigation buttons.
* @example
* $("#id").wijlightbox({
* showNavButtons: false
* });
*/
this.showNavButtons = true;
/** Determines whether to display the time bar.
* @example
* $("#id").wijlightbox({
* showTimer: true
* });
*/
this.showTimer = false;
/** Determines the position of control buttons.
* @remark Possible values are: 'inside', 'outside'
* @example
* $("#id").wijlightbox({
* controlsPosition: 'outside'
* });
*/
this.controlsPosition = 'inside';
/** Determines whether to display the control buttons only when hovering the mouse over the content.
* @example
* $("#id").wijlightbox({
* showControlsOnHover: false
* });
*/
this.showControlsOnHover = true;
/** Determines whether to pause the auto-play when clicking the content.
* @example
* $("#id").wijlightbox({
* clickPause: true
* });
*/
this.clickPause = false;
/** Determines whether to allow keyboard navigation.
* @example
* $("#id").wijlightbox({
* keyNav: true
* });
*/
this.keyNav = false;
/** Determines whether the window is modal.
*/
this.modal = false;
/** Determines the pop-up position of content window.
* Please see jquery.ui.position for possible options.
* @type {object}
*/
this.position = {
my: 'center',
at: 'center',
of: window,
collision: 'fit',
using: // ensure that the titlebar is never outside the document
function (pos) {
var topOffset = $(this).css(pos).offset().top;
if(topOffset < 0) {
$(this).css('top', pos.top - topOffset);
}
}
};
/** Determines the z-index of popup container.
*/
this.zIndex = 1000;
/** Determines whether to close the pop-up window
* when a user presses the ESC key.
*/
this.closeOnEscape = true;
/** Determines whether to close the pop-up window
* when user clicks on the outside of content.
*/
this.closeOnOuterClick = true;
/** Determines whether pages are automatically displayed in order.
*/
this.autoPlay = false;
/** Determines the time span in milliseconds
* between panels in autoplay mode.
*/
this.delay = 2000;
/** Determines whether start from the first page
* when reaching the end in autoplay mode.
*/
this.loop = true;
/** Store the latest active index in a cookie.
* The cookie is then used to determine the initially active index
* @type {object}
* @remarks
* if the activeIndex option is not defined.
* This requires cookie plugin.
* The object needs to have key/value pairs of
* the form the cookie plugin expects as options.
* e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true }
*/
this.cookie = null;
/** Determines the animation style when switching between pages.
* Possible values are 'slide', 'fade', 'none'
* @type {object}
* @example
* $("#id").wijlightbox({
* transAnimation: {
* animated: slide
* }
* });
*/
this.transAnimation = {
animated: "fade",
duration: 400,
easing: 'linear'
};
/** Determines the slide direction.
* Possible values are: 'horizontal', 'vertical'
* @example
* $("#id").wijlightbox({
* slideDirection: 'vertical'
* });
*/
this.slideDirection = 'horizontal';
/** Determines the animation style when resizing.
* @type {object}
* @example
* $("#id").wijlightbox({
* resizeAnimation: { animated: 'wh'}
* });
*/
this.resizeAnimation = {
animated: 'sync',
duration: 400
};
/** Determines the animation style when showing the text.
* @type {object}
* @example
* $("#id").wijlightbox({
* textShowOption: {
* duration: 500,
* easing: 'linear'
* }
* });
*/
this.textShowOption = {
duration: 300,
easing: 'linear'
};
/** Determines the animation style when hidding the text.
* @type {object}
* @example
* $("#id").wijlightbox({
* textHideOption: {
* duration: 500,
* easing: 'linear'
* }
* });
*/
this.textHideOption = {
duration: 300,
easing: 'linear'
};
/** Determines whether to turn on the movie controls in movie player.
*/
this.showMovieControls = true;
/** Determines whether to turn on the autoplay option in movie player.
*/
this.autoPlayMovies = true;
/** Determines a hash object that contains parameters for a flash object.
* @type {object}
* @example
* $("#id").wijlightbox({
* flashParams: {
* autostart: true,
* allowscriptaccess: 'always'
* }
* });
*/
this.flashParams = {
bgcolor: "#000000",
allowfullscreen: true
};
/** Determines a hash object that contains variants for a flash object.
* @type {object}
* @example
* $("#id").wijlightbox({
* flashVars: {
* backcolor: "0x000000",
* frontcolor: "0xCCCCCC"
* }
* });
*/
this.flashVars = {
};
/** Version of Flash object.
* @type {string}
* @example
* $("#id").wijlightbox({
* flashVersion: "9.0.115"
* });
*/
this.flashVersion = "9.0.115";
/** Determines the relative path and name of the flash vedio player.
* @example
* $("#id").wijlightbox({
* flvPlayer: "player\\myplayer.swf"
* });
*/
this.flvPlayer = 'player\\player.swf';
/** Determines the relative path and name of the flash installation guide.
* @example
* $("#id").wijlightbox({
* flashInstall: "player\\installFlash.swf"
* });
*/
this.flashInstall = 'player\\expressInstall.swf';
/** The beforeShow event handler.
* A function called before a page's content is shown.
* @event
*/
this.beforeShow = null;
/** The show event handler.
* A function called after a page's content is shown.
* @event
*/
this.show = null;
/** The open event handler.
* A function called after the popped up container is opened.
* @event
*/
this.open = null;
/** The showbeforeClose event handler.
* A function called before the popped up container is closed.
* @event
*/
this.beforeClose = null;
/** The close event handler.
* A function called after the popped up container is closed.
* @event
*/
this.close = null;
}
return wijlightbox_options;
})();
wijlightbox.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijlightbox_options());
$.wijmo.registerWidget("wijlightbox", wijlightbox.prototype);
$.extend($.wijmo.wijlightbox, {
img: function (lightbox, item, onload, onerror) {
this.name = 'img';
this.lightbox = lightbox;
this.item = item;
this.url = this.lightbox._getUrl(item);
var self = this;
$('<img></img>').css({
width: 'auto',
height: 'auto',
display: 'none'
}).appendTo(document.body).bind({
'load': function () {
var img = $(this);
self.width = item.width ? parseInt(item.width, 10) : img.width();
self.height = item.height ? parseInt(item.height, 10) : img.height();
img.remove();
if(onload && $.isFunction(onload)) {
onload.apply(lightbox);
}
},
'error': function () {
$(this).remove();
if(onerror && $.isFunction(onerror)) {
onerror.apply(lightbox);
}
}
}).attr('src', this.url);
},
swf: function (lightbox, item, onload, onerror) {
this.name = 'swf';
var lo = lightbox.options;
this.id = 'flashhost';
this.lightbox = lightbox;
this.item = item;
this.url = this.lightbox._getUrl(item);
this.width = item.width ? parseInt(item.width, 10) : lo.width;
this.height = item.height ? parseInt(item.height, 10) : lo.height;
if(onload && $.isFunction(onload)) {
onload.apply(lightbox);
}
},
iframe: function (lightbox, item, onload, onerror) {
this.name = 'swf';
this.lightbox = lightbox;
this.item = item;
this.url = this.lightbox._getUrl(item);
if(item.width) {
this.width = parseInt(item.width, 10);
}
if(item.height) {
this.height = parseInt(item.height, 10);
}
this.$iframe = $('<iframe></iframe>').addClass('wijmo-wijlightbox-iframe').attr({
frameborder: '0',
marginwidth: '0',
marginheight: '0',
scrolling: 'auto',
allowtransparency: 'true'
}).hide().appendTo(lightbox.content).bind('load', function () {
if(onload && $.isFunction(onload)) {
onload.apply(lightbox);
}
}).attr('src', this.url);
},
inline: function (lightbox, item, onload, onerror) {
this.name = 'inline';
var lo = lightbox.options, css = lo.wijCSS, frameCSS = "wijmo-wijlightbox-frame " + css.content;
" " + css.cornerAll + " " + css.helperClearFix;
this.lightbox = lightbox;
this.item = item;
this.width = item.width ? parseInt(item.width, 10) : lo.width;
if(item.height) {
this.height = parseInt(item.height, 10);
} else {
var $temp = $(this.item.href).clone().show().append('<br clear="all" />').wrap('<div class="wijmo-wijlightbox ' + css.widget + '">' + '<div class="' + frameCSS + '">' + '<div class="' + frameCSS + '">' + '<div class="wijmo-wijlightbox-content"> ' + '</div></div></div></div>').appendTo(document.body).width(this.width);
this.height = $temp.outerHeight(true) + 10;
$temp.unwrap();
$temp.remove();
}
if(onload && $.isFunction(onload)) {
onload.apply(lightbox);
}
},
flv: function (lightbox, item, onload, onerror) {
this.name = 'flv';
var lo = lightbox.options;
this.id = 'flvhost';
this.lightbox = lightbox;
this.item = item;
this.url = this.lightbox._getUrl(item);
var jwControllerHeight = 20;
this.width = item.width ? parseInt(item.width, 10) : lo.width;
this.height = item.height ? parseInt(item.height, 10) : lo.height;
if(lo.showMovieControls) {
this.height += jwControllerHeight;
}
if(onload && $.isFunction(onload)) {
onload.apply(lightbox);
}
},
wmp: function (lightbox, item, onload, onerror) {
var lo = lightbox.options, wmpControllerHeight;
this.name = 'wmp';
this.id = 'wmphost';
this.lightbox = lightbox;
this.item = item;
this.url = this.lightbox._getUrl(item);
wmpControllerHeight = ($.browser.msie ? 70 : 45);
this.width = item.width ? parseInt(item.width, 10) : lo.width;
this.height = item.height ? parseInt(item.height, 10) : lo.height;
if(lo.showMovieControls) {
this.height += wmpControllerHeight;
}
if(onload && $.isFunction(onload)) {
onload.apply(lightbox);
}
},
qt: function (lightbox, item, onload, onerror) {
var lo = lightbox.options, qtControllerHeight = 16;
this.name = 'qt';
this.id = 'qthost';
this.lightbox = lightbox;
this.item = item;
this.url = this.lightbox._getUrl(item);
this.width = item.width ? parseInt(item.width, 10) : lo.width;
this.height = item.height ? parseInt(item.height, 10) : lo.height;
if(lo.showMovieControls) {
this.height += qtControllerHeight;
}
if(onload && $.isFunction(onload)) {
onload.apply(lightbox);
}
},
wijvideo: function (lightbox, item, onload, onerror) {
var lo = lightbox.options;
this.name = 'wijvideo';
this.id = 'wijvideohost';
this.lightbox = lightbox;
this.item = item;
this.url = this.lightbox._getUrl(item);
this.wijvideosrc = (!!item.wijvideosrc && item.wijvideosrc !== "") ? this.lightbox._getUrl(item.wijvideosrc) : null;
this.width = item.width ? parseInt(item.width, 10) : lo.width;
this.height = item.height ? parseInt(item.height, 10) : lo.height;
if(onload && $.isFunction(onload)) {
onload.apply(lightbox);
}
}
});
$.extend($.wijmo.wijlightbox.img.prototype, {
appendTo: function ($content, hidden) {
this.$element = $('<img></img>').addClass('wijmo-wijlightbox-image').attr('src', this.url);
if(hidden) {
this.$element.hide();
}
if(this.lightbox.options.transAnimation && this.lightbox.options.transAnimation.animated == "fade") {
//fixed bug 20925
//"fade" animation will not clean the prev element sometimes.
if($content.children().length) {
$content.empty();
}
this.$element.prependTo($content);
} else {
this.$element.appendTo($content);
}
},
remove: function () {
if(this.$element) {
this.$element.remove();
}
},
fadeOut: function (duration, complete) {
if(this.$element) {
this.$element.fadeOut(duration, complete);
}
},
fadeIn: function (duration, complete) {
if(this.$element) {
this.$element.fadeIn(duration, complete);
}
},
getElement: function () {
return this.$element;
}
});
$.extend($.wijmo.wijlightbox.swf.prototype, {
appendTo: function ($content) {
this.$container = $('<div/>').css({
width: '100%',
height: '100%',
overflow: 'hidden'
}).attr('id', this.id).appendTo($content);
var lo = this.lightbox.options, express = lo.flashInstall, version = lo.flashVersion, flashvars = lo.flashVars, params = lo.flashParams;
S.flash.embedSWF(this.item.href, this.id, '100%', '100%', version, express, flashvars, params);
},
remove: function () {
S.flash.expressInstallCallback();
S.flash.removeSWF(this.id);
this.$container.remove();
},
fadeOut: function (duration, complete) {
if(this.$container) {
this.$container.fadeOut(duration, complete);
}
},
fadeIn: function (duration, complete) {
if(this.$container) {
this.$container.fadeIn(duration, complete);
}
},
getElement: function () {
return this.$container;
}
});
$.extend($.wijmo.wijlightbox.iframe.prototype, {
appendTo: function ($content, hidden) {
if(!hidden) {
this.$iframe.show();
}
},
remove: function () {
if(this.$iframe) {
this.$iframe.remove();
}
},
fadeOut: function (duration, complete) {
if(this.$iframe) {
this.$iframe.fadeOut(duration, complete);
}
},
fadeIn: function (duration, complete) {
if(this.$iframe) {
this.$iframe.fadeIn(duration, complete);
}
},
getElement: function () {
return this.$iframe;
}
});
$.extend($.wijmo.wijlightbox.inline.prototype, {
appendTo: function ($content, hidden) {
this.$element = $(this.item.href).clone().appendTo($content);
if(!hidden) {
this.$element.show();
}
},
remove: function () {
if(this.$element) {
this.$element.remove();
}
},
fadeOut: function (duration, complete) {
if(this.$element) {
this.$element.fadeOut(duration, complete);
}
},
fadeIn: function (duration, complete) {
if(this.$element) {
this.$element.fadeIn(duration, complete);
}
},
getElement: function () {
return this.$element;
}
});
$.extend($.wijmo.wijlightbox.flv.prototype, {
appendTo: function ($content) {
this.$container = $('<div/>').css({
width: '100%',
height: '100%',
overflow: 'hidden'
}).attr('id', this.id).appendTo($content);
var lo = this.lightbox.options, width = '100%', height = '100%', swf = lo.flvPlayer, express = lo.flashInstall, version = lo.flashVersion, flashvars = $.extend({
file: this.url,
width: width,
height: height,
autostart: (lo.autoPlayMovies ? 'true' : 'false'),
controlbar: (lo.showMovieControls ? 'bottom' : "none"),
backcolor: "0x000000",
frontcolor: "0xCCCCCC",
lightcolor: "0x557722"
}, lo.flashVars), params = $.extend({
autostart: (lo.autoPlayMovies ? 'true' : 'false'),
allowscriptaccess: 'always'
}, lo.flashParams);
S.flash.embedSWF(swf, this.id, width, height, version, express, flashvars, params);
},
remove: function () {
S.flash.expressInstallCallback();
S.flash.removeSWF(this.id);
this.$container.remove();
},
fadeOut: function (duration, complete) {
if(this.$container) {
this.$container.fadeOut(duration, complete);
}
},
fadeIn: function (duration, complete) {
if(this.$container) {
this.$container.fadeIn(duration, complete);
}
},
getElement: function () {
return this.$container;
}
});
$.extend($.wijmo.wijlightbox.wmp.prototype, {
appendTo: function ($content) {
this.$container = $('<div/>').css({
width: '100%',
height: '100%',
overflow: 'hidden'
}).appendTo($content);
var lo = this.lightbox.options, movie = '<object id="' + this.id + '" name="' + this.id + '" height="' + this.height + '" width="' + this.width + '"', params = {
autostart: lo.autoPlayMovies ? 1 : 0,
url: undefined,
uimode: undefined,
showcontrols: undefined
}, p;
if($.browser.msie) {
movie += ' classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6"';
params.url = this.url;
params.uimode = lo.showMovieControls ? "full" : "none";
} else {
movie += ' type="video/x-ms-wmv"';
movie += ' data="' + this.url + '"';
params.showcontrols = lo.showMovieControls ? 1 : 0;
}
movie += ">";
for(p in params) {
movie += '<param name="' + p + '" value="' + params[p] + '">';
}
movie += "</object>";
this.$container.html(movie);
},
remove: function () {
if($.browser.msie) {
try {
window[this.id].controls.stop();
window[this.id].URL = "movie" + now() + ".wmv";
window[this.id] = function () {
};
} catch (e) {
}
}
this.$container.remove();
},
fadeOut: function (duration, complete) {
if(this.$container) {
this.$container.fadeOut(duration, complete);
}
},
fadeIn: function (duration, complete) {
if(this.$container) {
this.$container.fadeIn(duration, complete);
}
},
getElement: function () {
return this.$container;
}
});
$.extend($.wijmo.wijlightbox.qt.prototype, {
appendTo: function ($content, first) {
this.$container = $('<div/>').css({
width: '100%',
height: '100%',
overflow: 'hidden'
}).appendTo($content);
var lo = this.lightbox.options, autoplay = lo.autoPlayMovies ? 'true' : 'false', controls = lo.showMovieControls ? 'true' : 'false', movie = "<object", attrs = {
id: this.id,
name: this.id,
width: this.width,
height: this.height,
kioskmode: "true",
classid: undefined,
codebase: undefined,
type: undefined,
data: undefined
}, m, p;
if($.browser.msie) {
attrs.classid = "clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B";
attrs.codebase = "http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0";
} else {
attrs.type = "video/quicktime";
attrs.data = this.url;
}
for(m in attrs) {
movie += " " + m + '="' + attrs[m] + '"';
}
movie += ">";
var params = {
src: this.url,
scale: "aspect",
controller: controls,
autoplay: autoplay
};
for(p in params) {
movie += '<param name="' + p + '" value="' + params[p] + '">';
}
movie += "</object>";
if(first) {
//fixed bug 20988
$content.hide();
}
this.$container.html(movie);
if(first) {
//fixed bug 20988
$content.show();
}
},
remove: function () {
try {
document[this.id].Stop();
document[this.id] = null;
} catch (e) {
}
this.$container.remove();
},
fadeOut: function (duration, complete) {
complete.call();
return;//?
// if (this.$container) {
// this.$container.fadeOut(duration, complete);
// }
},
fadeIn: function (duration, complete) {
complete.call();
return;//?
// if (this.$container) {
// this.$container.fadeIn(duration, complete);
// }
},
getElement: function () {
return this.$container;
}
});
$.extend($.wijmo.wijlightbox.wijvideo.prototype, {
appendTo: function ($content) {
var lo = this.lightbox.options;
this.$container = $('<video/>').css({
overflow: 'hidden'
}).attr({
width: this.width,
height: this.height,
autoPlay: (lo.autoPlayMovies ? 'true' : 'false'),
controls: (lo.showMovieControls ? 'controls' : '')
}).appendTo($content);
if(!!this.url) {
$('<source/>').attr({
src: this.url
}).appendTo(this.$container);
}
if(!!this.wijvideosrc) {
$('<source/>').attr({
src: this.wijvideosrc
}).appendTo(this.$container);
}
this.$container.wijvideo({
fullScreenButtonVisible: false
});
},
remove: function () {
this.$container.remove();
},
fadeOut: function (duration, complete) {
if(this.$container) {
this.$container.fadeOut(duration, complete);
}
},
fadeIn: function (duration, complete) {
if(this.$container) {
this.$container.fadeIn(duration, complete);
}
},
getElement: function () {
return this.$container;
},
adjustSize: function (width, height) {
this.$container.wijvideo('setWidth', width);
this.$container.wijvideo('setHeight', height);
}
});
$.extend($.wijmo.wijlightbox, {
overlay: function (lightbox, waiting) {
this.mask = $('<div></div>').addClass(lightbox.options.wijCSS.overlay + ' wijmo-wijlightbox-overlay' + (waiting ? " wijmo-wijlightbox-waitingoverlay" : "")).appendTo(document.body).css({
width: this.width(),
height: this.height()
}).bind("click", function () {
if(lightbox.options.closeOnOuterClick) {
lightbox._close();
}
return false;
});
if($.fn.bgiframe) {
this.mask.bgiframe();
}
if(waiting) {
this.mask.css('z-index', this.zIndex);
var $sandglass = $('<div></div>').addClass('wijmo-wijlightbox-waiting').css('z-index', this.zIndex + 1).appendTo(this.mask);
$sandglass.css({
left: (this.mask.width() - $sandglass.width()) / 2,
top: (this.mask.height() - $sandglass.height()) / 2
});
}
// handle window resize
$(window).bind('resize.wijlightbox-overlay', $.proxy(this, 'resize'));
window.setTimeout(function () {
var lay;
if(this.mask) {
lay = $.wijmo.wijlightbox.overlay;
$(document).bind(lay.events, function (event) {
if($(event.target).zIndex() < lay.zIndex) {
return false;
}
});
}
}, 1);
}
});
$.extend($.wijmo.wijlightbox.overlay.prototype, {
mask: null,
zIndex: 1000,
events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','), function (event) {
return event + '.wijlightbox-overlay';
}).join(' '),
close: function () {
$(document).unbind('.wijlightbox-overlay');
$(window).unbind('.wijlightbox-overlay');
this.mask.remove();
this.mask = undefined;
},
height: function () {
var scrollHeight, offsetHeight;
// handle IE 6
if($.browser.msie && parseInt($.browser.version) < 7) {
scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
offsetHeight = Math.max(document.documentElement.offsetHeight, document.body.offsetHeight);
if(scrollHeight < offsetHeight) {
return $(window).height();
} else {
return scrollHeight;
}
// handle "good" browsers
} else {
return $(document).height();
}
},
width: function () {
var scrollWidth, offsetWidth;
// handle IE 6
if($.browser.msie && parseInt($.browser.version) < 7) {
scrollWidth = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth);
offsetWidth = Math.max(document.documentElement.offsetWidth, document.body.offsetWidth);
if(scrollWidth < offsetWidth) {
return $(window).width();
} else {
return scrollWidth;
}
// handle "good" browsers
} else {
return $(document).width();
}
},
resize: function () {
if(this.mask) {
this.mask.css({
width: this.width(),
height: this.height()
});
}
}
});
})(wijmo.lightbox || (wijmo.lightbox = {}));
var lightbox = wijmo.lightbox;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../wijbarchart/jquery.wijmo.wijbarchart.ts"/>
/// <reference path="../wijbubblechart/jquery.wijmo.wijbubblechart.ts"/>
/// <reference path="../wijpiechart/jquery.wijmo.wijpiechart.ts"/>
/// <reference path="../wijlinechart/jquery.wijmo.wijlinechart.ts"/>
/// <reference path="../wijscatterchart/jquery.wijmo.wijscatterchart.ts"/>
/*globals jQuery, Globalize*/
/*
* Depends:
* raphael.js
* globalize.min.js
* jquery.ui.widget.js
* jquery.wijmo.wijchartcore.js
* jquery.wijmo.wijbarchart.js
* jquery.wijmo.wijlinechart.js
* jquery.wijmo.wijpiechart.js
* jquery.wijmo.wijscatterchart.js
*
*/
(function (chart) {
/**
* @widget
*/
var wijcompositechart = (function (_super) {
__extends(wijcompositechart, _super);
function wijcompositechart() {
_super.apply(this, arguments);
}
wijcompositechart.prototype._create = function () {
var self = this, o = self.options, defFill = self._getDefFill(), seriesStyles = o.seriesStyles;
$.each(o.seriesList, function (idx, series) {
if(series.type === "bar") {
$.extend(true, o.axis, {
x: {
compass: "west"
},
y: {
compass: "south"
}
});
return true;
} else if(series.type === "pie" && series.pieSeriesList) {
series.data = series.pieSeriesList;
}
});
$.extend(true, {
compass: "east"
}, o.hint);
// set the is100percent to default value.
if(o.is100Percent) {
o.is100Percent = false;
}
//handle the multiple y axis for extender and controls
if(o.yAxes && $.isArray(o.yAxes) && o.yAxes.length > 0) {
o.axis.y = o.yAxes;
}
self._handleChartStyles();
// default some fills
//$.each(seriesStyles, function (idx, style) {
// if (!style.fill) {
// style.fill = defFill[idx];
// }
//});
seriesStyles = o.seriesStyles;
// extend stock style
$.each(o.seriesList, function (i, series) {
if(self._isStockSeries(series)) {
var seriesStyle = seriesStyles[i], type = series.type, defaultFill = seriesStyle.fill, bakStyle = $.extend({
}, seriesStyle);
if(seriesStyle) {
if(!seriesStyle.highLow) {
seriesStyle.highLow = bakStyle;
}
if(type === "hloc") {
if(!seriesStyle.open) {
seriesStyle.open = bakStyle;
}
if(!seriesStyle.close) {
seriesStyle.close = bakStyle;
}
} else {
if(!seriesStyle.fallingClose) {
seriesStyle.fallingClose = bakStyle;
}
if(!seriesStyle.raisingClose) {
seriesStyle.raisingClose = bakStyle;
}
}
}
}
});
o.seriesStyles = seriesStyles;
if(self._isContainsStock()) {
self.isContainsStock = true;
self._handleXData();
}
_super.prototype._create.call(this);
self.chartElement.addClass(o.wijCSS.compositechart);
};
wijcompositechart.prototype._setOption = function (key, value) {
// ignore the is100Percent option.
if(key !== "is100Percent") {
_super.prototype._setOption.call(this, key, value);
}
};
wijcompositechart.prototype._supportStacked = function () {
return true;
};
wijcompositechart.prototype.destroy = /**
* Remove the functionality completely. This will return the element back to its pre-init state.
*/
function () {
var self = this, element = self.chartElement, fields = element.data("fields"), aniBarsAttr = fields && fields.aniBarsAttr;
element.removeClass(self.options.wijCSS.compositechart);
_super.prototype.destroy.call(this);
self._destroyRaphaelArray(aniBarsAttr);
element.data("fields", null);
};
wijcompositechart.prototype._isBarChart = function () {
return true;
};
wijcompositechart.prototype._clearChartElement = function () {
var self = this, o = self.options, element = self.chartElement, fields = element.data("fields");
if(fields && fields.allElements) {
$.each(fields.allElements, function (key, eles) {
if(key === "scatters") {
if(eles.length) {
$.each(eles, function (i, ele) {
if(ele.length) {
$.each(ele, function (j, n) {
if(n && n.remove) {
n.remove();
}
ele[j] = null;
});
eles[i] = null;
}
});
}
}
self._destroyRaphaelArray(eles);
});
fields.allElements = null;
}
_super.prototype._clearChartElement.call(this);
if(fields && fields.ctracers) {
fields.ctracers = null;
}
self.element.removeData("plotInfos");
if(!o.seriesTransition.enabled) {
if(fields && fields.aniBarsAttr) {
fields.aniBarsAttr = null;
}
}
};
wijcompositechart.prototype._bindData = function () {
var self = this, o = self.options, dataSource = o.dataSource, seriesList = o.seriesList, shareData = o.data, sharedXList;
$.each(seriesList, function (i, series) {
var data = series.data, dataX, dataY, dataY1, ds = series.dataSource || dataSource, type = series.type, dataLabel, dataValue, dataOffset, pieData = [];
if(ds && data) {
if(type === "pie") {
dataLabel = data.label;
dataValue = data.value;
dataOffset = data.offset;
if(dataLabel && dataLabel.bind) {
dataLabel = self._getBindData(ds, dataLabel.bind);
}
if(dataValue && dataValue.bind) {
dataValue = self._getBindData(ds, dataValue.bind);
}
if(dataOffset && dataOffset.bind) {
dataOffset = self._getBindData(ds, dataOffset.bind);
}
if(dataLabel && $.isArray(dataLabel) && dataLabel.length && dataValue && $.isArray(dataValue) && dataValue.length) {
$.each(dataValue, function (idx, val) {
var label, offset = 0;
if(idx >= 0 && idx < dataLabel.length) {
label = dataLabel[idx];
}
if(dataOffset && $.isArray(dataValue) && dataOffset.length && idx >= 0 && idx < dataOffset.length) {
offset = typeof dataOffset[idx] === 'undefined' ? 0 : dataOffset[idx];
}
pieData.push({
data: val,
label: label,
offset: offset,
legendEntry: true
});
});
series.data = pieData;
}
} else {
dataX = data.x;
dataY = data.y;
dataY1 = data.y1;
if(dataX && dataX.bind) {
data.x = self._getBindData(ds, dataX.bind);
} else if(shareData && shareData.x && shareData.x.bind) {
if(sharedXList === undefined) {
sharedXList = self._getBindData(ds, shareData.x.bind);
}
data.x = sharedXList;
}
if(dataY && dataY.bind) {
data.y = self._getBindData(ds, dataY.bind);
}
if(dataY1 && dataY1.bind) {
data.y1 = self._getBindData(ds, dataY1.bind);
}
}
}
});
};
wijcompositechart.prototype.getElement = /**
* Returns the raphael element with the given type and index.
* @param {string} type The type of the chart element.
* @param {number} index The index of the element.
* @param {number} seriesIndex The index of the series.
* @returns {Raphael Element} Returns the specified raphael object.
*/
function (type, index, seriesIndex) {
var element = this.chartElement, fields = element.data("fields"), chartElements = fields.chartElements;
switch(type) {
case "bar":
case "column":
return chartElements.bars[index];
case "line":
case "area":
return chartElements.paths[index];
case "linemarkers":
return chartElements.markersSet[index];
case "pie":
//return chartElements.sectors[index];
return this._getPie(chartElements, index, seriesIndex);
}
return null;
};
wijcompositechart.prototype._getPie = function (chartElements, index, seriesIndex) {
if(seriesIndex !== undefined) {
if(chartElements["sectors" + seriesIndex]) {
return chartElements["sectors" + seriesIndex][index];
}
return null;
} else {
var sectors = [];
$.each(chartElements, function (key, val) {
if(/sectors/.test(key) && key !== "sectors") {
$.each(val, function (i, n) {
sectors.push(n);
});
}
});
if(sectors.length === 0) {
sectors = chartElements.sectors;
}
return sectors[index];
}
};
wijcompositechart.prototype._paintLegendIcon = function (x, y, width, height, style, legendIndex, seriesIndex, legendCss, series, leg) {
var self = this, o = this.options, chartType = series.type, icon, dot, legendHeight = 3, isNewIcon = false, type, markerStyle;
if(chartType === "line" || chartType === "area" || chartType === "spline" || chartType === "bezier") {
icon = self.canvas.path(Raphael.format("M{0},{1}L{2},{3}", x, y + height / 2, x + width, y + height / 2));
if(style) {
if(o.legend.size && o.legend.size.height) {
legendHeight = o.legend.size.height;
}
icon.attr($.extend(true, {
}, style, {
"stroke-width": legendHeight
}));
}
isNewIcon = true;
if(series.markers && series.markers.visible) {
type = series.markers.type;
markerStyle = series.markerStyle;
markerStyle = $.extend({
fill: style.stroke,
stroke: style.stroke,
opacity: 1
}, markerStyle);
if(style["stroke-dasharray"]) {
icon.attr({
"stroke-width": //if stroke-width is bigger than 1,
//it doesn't look good.
1,
"stroke-dasharray": style["stroke-dasharray"]
});
}
if(!type) {
type = "circle";
}
dot = this.canvas.paintMarker(type, x + width / 2, y + height / 2, 3);
$.wijraphael.addClass($(dot.node), Raphael.format("{0} {1} {2}", o.wijCSS.legend, o.wijCSS.legendDot, o.wijCSS.canvasObject));
dot.attr(markerStyle);
$(dot.node).data("index", seriesIndex).data("legendIndex", legendIndex);
this.legendDots[legendIndex] = dot;
}
} else if(chartType === "scatter") {
markerStyle = series.markerStyle;
type = series.markerType , markerStyle = $.extend({
fill: style.stroke,
stroke: style.stroke,
opacity: 1
}, markerStyle);
if(!type) {
type = "circle";
}
icon = self.canvas.paintMarker(type, x + width / 2, y + height / 2, 3);
icon.attr(markerStyle);
if(series.visible === false) {
$(leg.node).data("dotOpacity", icon.attr("opacity") || 1);
icon.attr("opacity", 0.3);
}
isNewIcon = true;
} else if(chartType === "bubble") {
markerStyle = series.markerStyle;
markerStyle = $.extend({
fill: style.stroke,
stroke: style.stroke,
opacity: 1
}, markerStyle);
if(series.markers) {
type = series.markers.type;
}
if(!type) {
type = "circle";
}
icon = self.canvas.paintMarker(type, x + width / 2, y + height / 2, Math.min(width, height) / 2);
icon.attr(markerStyle);
isNewIcon = true;
} else {
icon = _super.prototype._paintLegendIcon.call(this, x, y, width, height, style, legendIndex, seriesIndex, legendCss, series, leg);
}
if(isNewIcon) {
$.wijraphael.addClass($(icon.node), legendCss);
$(icon.node).data("legendIndex", legendIndex).data("index", seriesIndex);
self.legendIcons.push(icon);
}
return icon;
};
wijcompositechart.prototype._showHideStockSeries = function (seriesEle, type) {
$.each(seriesEle, function (i, stockNode) {
if(stockNode.hl) {
stockNode.hl[type]();
}
if(stockNode.o) {
stockNode.o[type]();
}
if(stockNode.c) {
stockNode.c[type]();
}
if(stockNode.path) {
stockNode.path[type]();
}
if(stockNode.h) {
stockNode.h[type]();
}
if(stockNode.l) {
stockNode.l[type]();
}
if(stockNode.oc) {
stockNode.oc[type]();
}
});
};
wijcompositechart.prototype._showSerieEles = function (seriesEle) {
var type = seriesEle.type, eles = seriesEle.eles, showLabels = this.options.showChartLabels, dataObj;
switch(type) {
case "pie":
if(eles.sector) {
eles.sector.show();
if(eles.sector.shadow) {
eles.sector.shadow.show();
}
if(eles.sector.tracker) {
eles.sector.tracker.show();
}
}
if(eles.label) {
eles.label.show();
}
break;
case "line":
case "spline":
case "bezier":
case "area":
if(eles.markers) {
$.each(eles.markers, function (i, marker) {
dataObj = $(marker.node).data("wijchartDataObj");
if(dataObj && dataObj.lineSeries && dataObj.lineSeries.markers) {
if(!dataObj.lineSeries.markers.visible) {
return true;
}
}
marker.show();
});
}
if(eles.dcl) {
$.each(eles.dcl, function (i, dcl) {
if(showLabels) {
dcl.show();
}
});
}
if(eles.path) {
dataObj = $(eles.path.node).data("wijchartDataObj");
if(dataObj.visible) {
eles.path.show();
if(eles.path.shadow) {
eles.path.shadow.show();
}
if(eles.path.area) {
eles.path.area.show();
}
if(eles.path.tracker) {
eles.path.tracker.show();
}
if($(eles.path.node).data("wijchartDataObj") && $(eles.path.node).data("wijchartDataObj").virtualMarkers) {
$.each($(eles.path.node).data("wijchartDataObj").virtualMarkers, function (i, markerObj) {
markerObj.visible = true;
});
}
}
}
break;
case "bar":
case "column":
$.each(eles, function (i, bar) {
if(bar.bar) {
bar.bar.show();
if(bar.bar.shadow) {
bar.bar.shadow.show();
}
if(bar.bar.tracker) {
bar.bar.tracker.show();
}
if($(bar.bar.node).data("wijchartDataObj")) {
$(bar.bar.node).data("wijchartDataObj").visible = true;
}
}
if(bar.dcl) {
bar.dcl.show();
}
if(bar.animatedBar && !bar.animatedBar.removed) {
bar.animatedBar.show();
}
});
break;
case "scatter":
$.each(eles, function (i, dot) {
dot.show();
if(dot.label) {
dot.label.show();
}
if($(dot.element).data("wijchartDataObj")) {
$(dot.element).data("wijchartDataObj").visible = true;
}
});
break;
case "hloc":
case "hl":
case "candlestick":
this._showHideStockSeries(eles, "show");
break;
case "bubble":
$.each(eles, function (i, bubbleInfo) {
if(bubbleInfo.bubble) {
bubbleInfo.bubble.show();
if(bubbleInfo.bubble.tracker) {
bubbleInfo.bubble.tracker.show();
}
}
if(bubbleInfo.dcl) {
bubbleInfo.dcl.show();
}
if(bubbleInfo.symbol) {
bubbleInfo.symbol.show();
}
});
}
};
wijcompositechart.prototype._hideSerieEles = function (seriesEle) {
var type = seriesEle.type, eles = seriesEle.eles;
switch(type) {
case "pie":
if(eles.sector) {
eles.sector.hide();
if(eles.sector.shadow) {
eles.sector.shadow.hide();
}
if(eles.sector.tracker) {
eles.sector.tracker.hide();
}
}
if(eles.label) {
eles.label.hide();
}
break;
case "line":
case "spline":
case "bezier":
case "area":
if(eles.markers) {
$.each(eles.markers, function (i, marker) {
marker.hide();
});
}
if(eles.dcl) {
$.each(eles.dcl, function (i, dcl) {
dcl.hide();
});
}
if(eles.path) {
eles.path.hide();
if(eles.path.shadow) {
eles.path.shadow.hide();
}
if(eles.path.area) {
eles.path.area.hide();
}
if(eles.path.tracker) {
eles.path.tracker.hide();
}
if($(eles.path.node).data("wijchartDataObj") && $(eles.path.node).data("wijchartDataObj").virtualMarkers) {
$.each($(eles.path.node).data("wijchartDataObj").virtualMarkers, function (i, markerObj) {
markerObj.visible = false;
});
}
}
break;
case "bar":
case "column":
$.each(eles, function (i, bar) {
if(bar.bar) {
bar.bar.hide();
if(bar.bar.shadow) {
bar.bar.shadow.hide();
}
if(bar.bar.tracker) {
bar.bar.tracker.hide();
}
if($(bar.bar.node).data("wijchartDataObj")) {
$(bar.bar.node).data("wijchartDataObj").visible = false;
}
}
if(bar.dcl) {
bar.dcl.hide();
}
if(bar.animatedBar && !bar.animatedBar.removed) {
bar.animatedBar.hide();
}
});
break;
case "scatter":
$.each(eles, function (i, dot) {
dot.hide();
if(dot.label) {
dot.label.hide();
}
if($(dot.element).data("wijchartDataObj")) {
$(dot.element).data("wijchartDataObj").visible = false;
}
});
break;
case "hloc":
case "hl":
case "candlestick":
this._showHideStockSeries(eles, "hide");
break;
case "bubble":
$.each(eles, function (i, bubbleInfo) {
if(bubbleInfo.bubble) {
bubbleInfo.bubble.hide();
if(bubbleInfo.bubble.tracker) {
bubbleInfo.bubble.tracker.hide();
}
}
if(bubbleInfo.dcl) {
bubbleInfo.dcl.hide();
}
if(bubbleInfo.symbol) {
bubbleInfo.symbol.hide();
}
});
break;
}
};
wijcompositechart.prototype._indicatorLineShowing = function (objs) {
var type;
_super.prototype._indicatorLineShowing.call(this, objs);
$.each(objs, function (i, obj) {
type = obj.type;
if(type === "column" || type === "bar") {
obj.bar.attr(obj.hoverStyle);
} else if(type === "marker") {
obj.marker.attr(obj.markerHoverStyle);
} else if(type === "scatter") {
obj.dot.attr(obj.hoverStyle);
obj.dot.scale(1.5, 1.5);
}
});
};
wijcompositechart.prototype._removeIndicatorStyles = function (objs) {
var type;
$.each(objs, function (i, obj) {
type = obj.type;
if(type === "column" || type === "bar") {
obj.bar.attr(obj.style);
} else if(type === "marker") {
obj.marker.attr(obj.markerStyle);
obj.marker.transform("s1");
} else if(type === "scatter") {
obj.dot.attr(obj.style);
obj.dot.scale(1, 1);
}
});
};
wijcompositechart.prototype._paintTooltip = function () {
var self = this, element = self.chartElement, fields = element.data("fields") || {
}, ctracers = fields.ctracers || [];
_super.prototype._paintTooltip.call(this);
if(self.tooltip) {
$.each(ctracers, function (idx, ctracer) {
if(ctracer.trackers && ctracer.trackers.length) {
if(idx === 0) {
self.tooltip.setOptions({
relatedElement: ctracer.trackers[0]
});
}
}
});
}
};
wijcompositechart.prototype._isContainsStock = // begin for stock chart
function () {
var isContainsStock = false, self = this, o = self.options, seriesList = o.seriesList;
$.each(seriesList, function (i, series) {
var type = series.type;
if(type === "hloc" || type === "hl" || type === "candlestick") {
isContainsStock = true;
return false;
}
});
return isContainsStock;
};
wijcompositechart.prototype._handleXData = function () {
// TO DO for stockchart
//var self = this,
// o = self.options,
// seriesList = o.seriesList,
// xValues = [];
//$.each(seriesList, function (i, series) {
// xValues = xValues.concat(series.data.x);
//});
//self.timeUtil = new $.wijstockchart.datetimeUtil(xValues);
//$.each(seriesList, function (i, series) {
// series.data.x = $.map(series.data.x, function (n, i) {
// return self.timeUtil.getTimeIndex(n);
// })
//});
};
wijcompositechart.prototype._isStockSeries = function (series) {
var type = series.type;
return type === "hloc" || type === "hl" || type === "candlestick";
};
wijcompositechart.prototype._paintChartArea = function () {
var self = this, o = self.options, data = o.data;
if(self._isSeriesDataEmpty()) {
return;
}
// add the hl to data.y
$.each(o.seriesList, function (i, n) {
var data = n.data;
if(self._isStockSeries(n)) {
data.y = [].concat(data.high).concat(data.low);
}
});
_super.prototype._paintChartArea.call(this);
// delete data.y
$.each(o.seriesList, function (i, n) {
if(self._isStockSeries(n)) {
delete n.data.y;
}
});
};
wijcompositechart.prototype._isSeriesDataEmpty = function () {
var self = this, sl = self.options.seriesList;
if(!sl || sl.length === 0) {
return true;
}
$.each(sl, function (idx, s) {
var type = s.type;
if(type === "hloc" || type === "candlestick") {
if(!s.data || (!s.data.x || !s.data.high || !s.data.low || !s.data.open || !s.data.close)) {
return true;
}
} else if(type === "hl") {
if(!s.data || (!s.data.x || !s.data.high || !s.data.low)) {
return true;
}
} else if(type === "pie" && (!s.data || !s.label || s.label.length === 0)) {
return true;
} else {
if(!s.data || ((!s.data.x || !s.data.y) && !s.data.xy)) {
return true;
}
}
});
return false;
};
wijcompositechart.prototype._validateSeriesData = function (series) {
var type = this.options.type, data = series.data;
if(type === "hl") {
if(data.x === undefined && data.high === undefined && data.low === undefined) {
return false;
}
} else {
if(data.x === undefined && data.high === undefined && data.low === undefined && data.open === undefined && data.close === undefined) {
return false;
}
}
return true;
};
wijcompositechart.prototype._isStockChart = function () {
if(this.isContainsStock) {
return true;
}
return false;
};
wijcompositechart.prototype._calculateStockParameters = function (axisInfo, options) {
// check for bar chart and x axis expansion
if(axisInfo.id === "x") {
var minor = options.unitMinor, autoMin = options.autoMin, autoMax = options.autoMax, adj = this._getStockAdjustment(axisInfo);
if(this.timeUtil && this.timeUtil.getCount) {
axisInfo.max = this.timeUtil.getCount() - 1;
}
if(adj === 0) {
adj = minor;
} else {
if(minor < adj && minor !== 0) {
adj = Math.floor(adj / minor) * minor;
}
}
if(autoMin) {
axisInfo.min -= adj;
}
if(autoMax) {
axisInfo.max += adj;
}
this._calculateMajorMinor(options, axisInfo);
}
};
wijcompositechart.prototype._getStockAdjustment = function (axisInfo) {
var self = this, o = self.options, max = axisInfo.max, min = axisInfo.min, length, series = o.seriesList;
$.each(series, function (i, s) {
if(!length) {
length = s.data.x.length;
} else {
length = Math.max(s.data.x.length);
}
});
return (max - min) / length;
};
wijcompositechart.prototype._calculateMajorMinor = function (axisOptions, axisInfo) {
var self = this, o = self.options, canvasBounds = axisInfo.bounds || self.canvasBounds, autoMajor = axisOptions.autoMajor, autoMinor = axisOptions.autoMinor, maxData = axisInfo.max, minData = axisInfo.min, isTime = axisInfo.isTime, tinc = axisInfo.tinc, formatString = axisInfo.annoFormatString, maxText = null, minText = null, sizeMax = null, sizeMin = null, mx = null, mn = null, prec = null, _prec = null, textStyle = null, dx = maxData - minData, width = 0, height = 0, nticks = 0, major = 0;
if(!self.isContainsStock) {
_super.prototype._calculateMajorMinor.call(this, axisOptions, axisInfo);
return;
}
if(autoMajor) {
textStyle = $.extend(true, {
}, o.textStyle, axisOptions.textStyle, axisOptions.labels.style);
if(axisInfo.id === "x") {
if(minData < 0) {
minData = 0;
}
if(maxData > self.timeUtil.getCount() - 1) {
maxData = self.timeUtil.getCount() - 1;
}
maxData = self.timeUtil.getOATime(maxData);
minData = self.timeUtil.getOATime(minData);
if(!self.formatString) {
formatString = formatString || chart.ChartDataUtil.getTimeDefaultFormat(maxData, minData);
self.formatString = formatString;
} else {
formatString = self.formatString;
}
maxText = Globalize.format($.fromOADate(maxData), formatString, self._getCulture());
minText = Globalize.format($.fromOADate(minData), formatString, self._getCulture());
mx = self._text(-1000, -1000, maxText).attr(textStyle);
mn = self._text(-1000, -1000, minText).attr(textStyle);
sizeMax = mx.wijGetBBox();
sizeMin = mn.wijGetBBox();
mx.wijRemove();
mx = null;
mn.wijRemove();
mn = null;
} else {
prec = chart.ChartDataUtil.nicePrecision(dx);
_prec = prec + 1;
if(_prec < 0 || _prec > 15) {
_prec = 0;
}
mx = self._text(-1000, -1000, $.round(maxData, _prec).toString()).attr(textStyle);
mn = self._text(-1000, -1000, $.round(minData, _prec).toString()).attr(textStyle);
sizeMax = mx.wijGetBBox();
sizeMin = mn.wijGetBBox();
mx.wijRemove();
mx = null;
mn.wijRemove();
mn = null;
}
if(sizeMax.width < sizeMin.width) {
sizeMax.width = sizeMin.width;
}
if(sizeMax.height < sizeMin.height) {
sizeMax.height = sizeMin.height;
}
if(!self._isVertical(axisOptions.compass)) {
// Add comments by RyanWu@20100907.
// Subtract axisTextOffset because we must left
// the space between major text and major rect.
width = canvasBounds.endX - canvasBounds.startX - axisInfo.vOffset - axisInfo.axisTextOffset;
major = width / sizeMax.width;
if(Number.POSITIVE_INFINITY === major) {
nticks = 0;
} else {
nticks = parseInt(major.toString(), 10);
}
} else {
height = canvasBounds.endY - canvasBounds.startY - axisInfo.vOffset - axisInfo.axisTextOffset;
major = height / sizeMax.height;
if(Number.POSITIVE_INFINITY === major) {
nticks = 0;
} else {
nticks = parseInt(major.toString(), 10);
}
}
major = dx;
if(nticks > 0) {
dx /= nticks;
axisInfo.tprec = chart.ChartDataUtil.nicePrecision(dx);
major = chart.ChartDataUtil.niceNumber(2 * dx, -prec, true);
if(major < dx) {
major = chart.ChartDataUtil.niceNumber(dx, -prec + 1, false);
}
if(major < dx) {
major = chart.ChartDataUtil.niceTickNumber(dx);
}
// }
}
axisOptions.unitMajor = major;
}
if(autoMinor && axisOptions.unitMajor && !isNaN(axisOptions.unitMajor)) {
axisOptions.unitMinor = axisOptions.unitMajor / 2;
}
};
wijcompositechart.prototype._getTickText = function (text) {
//return text;
var self = this, formatString = self.formatString;
if(self.isContainsStock) {
return Globalize.format(self.timeUtil.getTime(text), formatString, self._getCulture());
}
return text;
};
wijcompositechart.prototype._AdjustAxisBounds = function (axisInfo, axisOptions) {
var self = this, o = self.options, mx, mn, sizeMax, sizeMin, maxData = axisInfo.max, minData = axisInfo.min, dx = maxData - minData, prec = chart.ChartDataUtil.nicePrecision(dx), _prec = prec + 1, bounds = axisInfo.bounds, textStyle = $.extend(true, {
}, o.textStyle, axisOptions.textStyle, axisOptions.labels.style);
mx = self._text(-1000, -1000, $.round(maxData, _prec).toString()).attr(textStyle);
mn = self._text(-1000, -1000, $.round(minData, _prec).toString()).attr(textStyle);
sizeMax = mx.wijGetBBox();
sizeMin = mn.wijGetBBox();
if(!axisInfo.isStartAxis) {
bounds.startY += sizeMin.height;
}
if(!axisInfo.isLastAxis) {
bounds.endY -= (sizeMax.height) / 2;
}
};
wijcompositechart.prototype._initYAxisHeight = function () {
var self = this, o = self.options, axisOpt = o.axis, yaxisOpt = axisOpt.y, bounds = self.canvasBounds, width = bounds.endX - bounds.startX, height = bounds.endY - bounds.startY, axisInfo = self.axisInfo, yAxisInfo = axisInfo.y, othersHeight = 0, autoHeightIndex = -1, totalHeight = 0, lastBounds;
if($.isArray(yaxisOpt)) {
$.each(yaxisOpt, function (i, axisOpt) {
if(axisOpt.height && !isNaN(axisOpt.height)) {
othersHeight += axisOpt.height;
} else if(axisOpt.height === "auto") {
autoHeightIndex = i;
}
yAxisInfo[i].height = axisOpt.height;
});
if(autoHeightIndex > -1) {
yAxisInfo[autoHeightIndex].height = height - othersHeight;
}
$.each(yAxisInfo, function (i, axis) {
var yHeight = axis.height;
if(yHeight === undefined) {
return true;
}
if(yHeight > 0) {
axis.isPartAxis = true;
axis.isLastAxis = (parseInt(i) === yaxisOpt.length - 1);
axis.isStartAxis = parseInt(i) === 0;
}
if(!lastBounds) {
axis.bounds = {
startY: bounds.startY,
endY: bounds.startY + yHeight
};
} else {
axis.bounds = {
startY: lastBounds.endY,
endY: lastBounds.endY + yHeight
};
}
axis.bounds.startX = bounds.startX;
axis.bounds.endX = bounds.endX;
self._AdjustAxisBounds(axis, yaxisOpt[i]);
if(axis.bounds) {
lastBounds = $.extend({
}, axis.bounds);
}
});
}
};
wijcompositechart.prototype._getDataExtreme = function (isMultiYAxis) {
var self = this;
self._initYAxisHeight();
return _super.prototype._getDataExtreme.call(this, isMultiYAxis);
};
wijcompositechart.prototype._paintPlotArea = function () {
var self = this, o = self.options, seriesList = "seriesList", seriesStyles = "seriesStyles", seriesHoverStyles = "seriesHoverStyles", styles = o[seriesStyles], hoverStyles = o[seriesHoverStyles], bounds = self.canvasBounds, charts = {
}, index = 0, pSIndex = -1, seriesIndexs = [], isMulityYAxis = $.isArray(o.axis.y), options = {
canvas: self.canvas,
tooltip: self.tooltip,
bounds: bounds,
widgetName: self.widgetName,
seriesTransition: o.seriesTransition,
showChartLabels: o.showChartLabels,
textStyle: o.textStyle,
chartLabelStyle: o.chartLabelStyle,
chartLabelFormatString: o.chartLabelFormatString,
shadow: o.shadow,
hint: o.hint,
animation: o.animation,
disabled: o.disabled,
culture: self._getCulture(),
widget: this,
wijCSS: o.wijCSS,
mouseDown: function (e, args) {
self._trigger("mouseDown", e, args);
},
mouseUp: function (e, args) {
self._trigger("mouseUp", e, args);
},
mouseOver: function (e, args) {
self._trigger("mouseOver", e, args);
},
mouseOut: function (e, args) {
self._trigger("mouseOut", e, args);
},
mouseMove: function (e, args) {
self._trigger("mouseMove", e, args);
},
click: function (e, args) {
self._trigger("click", e, args);
}
}, fields = self.chartElement.data("fields"), tmpOptions, chartgroup, _chartRender, isContainsStock = self._isContainsStock();
if(fields) {
fields.ctracers = [];
}
if(isContainsStock) {
self._handleXData();
}
$.each(o[seriesList], function (i, series) {
var type = series.type, chart = {
}, chartType = type, pie = {
}, style = $.extend({
}, styles[index]), hoverStyle = $.extend({
}, hoverStyles[index]), yAxis = series.yAxis;
if(!type || type.length === 0) {
return true;
}
if(chartType === "spline" || chartType === "bezier") {
chartType = "line";
}
chart = charts[chartType];
if(!chart) {
if(type === "pie") {
chart = [];
} else {
chart = {
};
}
charts[chartType] = chart;
if(series.hint) {
chart.hint = series.hint;
if(!o.hint.content) {
o.hint.content = series.hint.content;
}
if(!o.hint.title) {
o.hint.title = series.hint.title;
}
}
}
if(type === "pie") {
$.each(series.data, function (j, data) {
style = $.extend({
}, styles[index]);
hoverStyle = $.extend({
}, hoverStyles[index]);
if(!pie[seriesList]) {
pie[seriesList] = [];
}
if(!pie[seriesStyles]) {
pie[seriesStyles] = [];
}
if(!pie[seriesHoverStyles]) {
pie[seriesHoverStyles] = [];
}
data.pieID = i + 1;
pie[seriesList].push(data);
pie[seriesStyles].push(style);
pie[seriesHoverStyles].push(hoverStyle);
// save the index of the seriesIndex for legend click.
if(pSIndex === -1) {
pSIndex = index;
}
index++;
});
pie.sIndex = pSIndex;
pie.radius = series.radius;
pie.center = series.center;
pie.label = series.label;
pSIndex = -1;
chart.push(pie);
return true;
} else if(type === "column") {
chart.horizontal = false;
} else if(type === "bar") {
chart.horizontal = true;
} else if(type === "spline") {
series.fitType = "spline";
} else if(type === "bezier") {
series.fitType = "bezier";
}
if(chartType === "stock" && series.data.high && series.data.low) {
series.data.y = [].concat(series.data.high).concat(series.data.low);
}
if(isMulityYAxis) {
chart.yAxis = yAxis || 0;
}
if(type === "line" || type === "spline" || type === "bezier") {
delete style.fill;
delete hoverStyle.fill;
}
if(!chart[seriesList]) {
chart[seriesList] = [];
}
if(!chart[seriesStyles]) {
chart[seriesStyles] = [];
}
if(!chart[seriesHoverStyles]) {
chart[seriesHoverStyles] = [];
}
if(type === "scatter") {
chart.showChartLabels = o.showChartLabels;
if(series.showChartLabels !== undefined) {
chart.showChartLabels = series.showChartLabels;
}
}
series.sIndex = index;
chart[seriesList].push(series);
chart[seriesStyles].push(style);
chart[seriesHoverStyles].push(hoverStyle);
index++;
});
$.each(charts, function (type, chart) {
var chartModule = wijmo.chart;
var yAxisIndex = chart.yAxis, chartLabel = o.chartLabel;
if(yAxisIndex !== undefined && self.axisInfo.y[yAxisIndex].bounds) {
options.bounds = self.axisInfo.y[yAxisIndex].bounds;
}
switch(type) {
case "pie":
var pSIndex;
$.each(chart, function (idx, pie) {
var center = pie.center, r = // fixed the issue 39375, if radius is not set, the default value should be 50 as early versions.
pie.radius || 50, pieBounds, width = bounds.endX - bounds.startX, height = bounds.endY - bounds.startY;
if(width < 2 * r) {
r = width / 2;
}
if(height < 2 * r) {
r = height / 2;
}
pie.radius = r;
pieBounds = center ? {
startX: center.x - r,
startY: center.y - r,
endX: center.x + r,
endY: center.y + r
} : {
startX: bounds.startX + 10,
startY: bounds.startY + 10,
endX: bounds.startX + 10 + 2 * r,
endY: bounds.startY + 10 + 2 * r
};
tmpOptions = $.extend(true, {
}, options, {
bounds: pieBounds,
radius: r
}, pie);
_chartRender = new chartModule.PieChartRender(self.chartElement, tmpOptions);
_chartRender.render();
self.chartElement.data("fields").aniSectorAttrs = null;
self.chartElement.data("fields").aniLabelAttrs = null;
self._savechartData(type, pie.sIndex);
});
break;
case "bar":
case "column":
tmpOptions = $.extend(true, {
}, options, {
stacked: o.stacked,
axis: o.axis,
clusterOverlap: o.clusterOverlap,
clusterWidth: o.clusterWidth,
clusterSpacing: o.clusterSpacing,
is100Percent: o.is100Percent,
clusterRadius: o.clusterRadius,
isYTime: self.axisInfo.y[0].isTime,
isXTime: self.axisInfo.x.isTime,
yAxisInfo: self.axisInfo.y,
yAxisIndex: yAxisIndex
}, chart);
_chartRender = new chartModule.BarChartRender(self.chartElement, tmpOptions);
_chartRender.render();
seriesIndexs = [];
$.each(chart.seriesList, function (i, sl) {
seriesIndexs.push(sl.sIndex);
});
self._savechartData(type, seriesIndexs);
break;
case "line":
case "spline":
case "bezier":
case "area":
chartgroup = self._getyAxisGroup(chart);
$.each(chartgroup, function (ykey, subchart) {
if(!self.aniPathsAttr) {
self.aniPathsAttr = [];
}
tmpOptions = $.extend(true, {
}, options, {
axis: o.axis,
isXTime: self.axisInfo.x.isTime,
isYTime: self.axisInfo.y[0].isTime,
type: //aniPathsAttr: self.aniPathsAttr,
//chartLabelEles: self.chartLabelEles,
type === "area" ? "area" : "line",
hole: o.hole
}, subchart);
tmpOptions.aniPathsAttr = self.aniPathsAttr;
tmpOptions.chartLabelEles = self.chartLabelEles;
tmpOptions.axis.y = o.axis.y[ykey] || o.axis.y;
tmpOptions.extremeValue = {
txx: self.extremeValue.txx,
txn: self.extremeValue.txn,
tyx: self.extremeValue.y[ykey].tyx,
tyn: self.extremeValue.y[ykey].tyn
};
_chartRender = new chartModule.LineChartRender(self.chartElement, tmpOptions);
_chartRender.render();
seriesIndexs = [];
$.each(subchart.seriesList, function (i, sl) {
seriesIndexs.push(sl.sIndex);
});
self._savechartData(type, seriesIndexs, true);
});
break;
case "scatter":
chartgroup = self._getyAxisGroup(chart);
$.each(chartgroup, function (ykey, subchart) {
tmpOptions = $.extend(true, {
}, options, {
axis: o.axis,
isXTime: self.axisInfo.x.isTime,
isYTime: self.axisInfo.y[0].isTime,
zoomOnHover: o.zoomOnHover
}, subchart);
tmpOptions.axis.y = o.axis.y[ykey] || o.axis.y;
_chartRender = new chartModule.ScatterChartRender(self.chartElement, tmpOptions);
_chartRender.render();
seriesIndexs = [];
$.each(subchart.seriesList, function (i, sl) {
seriesIndexs.push(sl.sIndex);
});
self._savechartData(type, seriesIndexs);
});
break;
case "hloc":
case "hl":
case "candlestick":
// now do not support the stock chart.
//chartgroup = self._getyAxisGroup(chart);
//$.each(chartgroup, function (ykey, subchart) {
// tmpOptions = $.extend(true, {}, options, {
// axis: o.axis,
// isXTime: self.axisInfo.x.isTime,
// isYTime: self.axisInfo.y[0].isTime,
// timeUtil: self.timeUtil,
// maxWidth: o.maxWidth || 15,
// type: type
// }, subchart);
// tmpOptions.axis.y = o.axis.y[ykey] || o.axis.y;
// self.chartElement.wijstock(tmpOptions);
// self._savechartData(type);
//});
break;
case "bubble":
chartgroup = self._getyAxisGroup(chart);
if(!chartLabel) {
chartLabel = {
visible: o.showChartLabels,
style: o.chartLabelStyle
};
}
$.each(chartgroup, function (ykey, subchart) {
tmpOptions = $.extend(true, {
}, options, {
axis: o.axis,
isXTime: self.axisInfo.x.isTime,
isYTime: self.axisInfo.y[0].isTime,
xAxisInfo: self.axisInfo.x,
yAxisInfo: self.axisInfo.y,
chartLabel: chartLabel,
minimumSize: o.minimumSize || 5,
maximumSize: o.maximumSize || 20,
sizingMethod: o.sizingMethod || "diameter"
}, subchart);
tmpOptions.axis.y = o.axis.y[ykey] || o.axis.y;
tmpOptions.yAxisInfo = self.axisInfo.y[ykey] || self.axisInfo.y[0];
_chartRender = new chartModule.BubbleChartRender(self.chartElement, tmpOptions);
_chartRender.render();
seriesIndexs = [];
$.each(subchart.seriesList, function (i, sl) {
seriesIndexs.push(sl.sIndex);
});
self._savechartData(type, seriesIndexs);
});
break;
break;
}
});
self.chartElement.data("fields").seriesEles = null;
self._bindtooltip();
};
wijcompositechart.prototype._savechartData = function (type, sIndex, notrackers) {
var self = this, fields = self.chartElement.data("fields"), seriesEles = fields.seriesEles, allElements = fields.allElements || {
}, ctracers, index = sIndex;
if($.isArray(index)) {
index = 0;
}
$.each(seriesEles, function (i, ele) {
// fixed the issue for legend click.
if($.isArray(sIndex)) {
self.seriesEles[sIndex[index]] = {
eles: ele,
type: type
};
index++;
} else {
self.seriesEles[index] = {
eles: ele,
type: type
};
index++;
}
//self.seriesEles.push({ eles: ele, type: type });
});
if(notrackers) {
//fields.ctracers = [];
} else {
ctracers = fields.ctracers || [];
ctracers.push({
trackers: fields.trackers,
type: type
});
fields.ctracers = ctracers;
}
if(fields && fields.chartElements) {
$.each(fields.chartElements, function (key, eles) {
self._copyElements(allElements, key, eles);
});
}
fields.allElements = allElements;
};
wijcompositechart.prototype._copyElements = function (target, key, source) {
var tar;
if(source && $.isArray(source)) {
tar = target[key] || [];
target[key] = tar.concat(source);
} else if(source) {
tar = target[key] || [];
tar.concat([
source
]);
}
};
wijcompositechart.prototype._getyAxisGroup = function (chart) {
var group = {
};
$.each(chart.seriesList, function (idx, series) {
var yAxis = series.yAxis || 0;
if(!group[yAxis]) {
group[yAxis] = {
seriesList: [],
seriesStyles: [],
seriesHoverStyles: []
};
}
group[yAxis].seriesList.push(series);
group[yAxis].seriesStyles.push(chart.seriesStyles[idx]);
group[yAxis].seriesHoverStyles.push(chart.seriesHoverStyles[idx]);
});
return group;
};
wijcompositechart.prototype._bindtooltip = function () {
var self = this, namespace = self.widgetName, fields = self.chartElement.data("fields");
if(fields && fields.ctracers) {
$.each(fields.ctracers, function (index, ctracer) {
var type = ctracer.type;
if(type === "hloc") {
} else {
if(ctracer.trackers) {
ctracer.trackers.toFront();
}
}
});
}
self.chartElement.delegate(".linetracker, .wijchart-canvas-marker, .bartracker, .pietracker, .wijscatterchart, .bubbletracker", "mouseover." + namespace, $.proxy(self._tooltipMouseOver, self));
self.chartElement.delegate(".linetracker, .wijchart-canvas-marker, .bartracker, .pietracker, .wijscatterchart, .bubbletracker", "mouseout." + namespace, $.proxy(self._tooltipMouseOut, self));
self.chartElement.delegate(".linetracker, .wijchart-canvas-marker, .bartracker, .pietracker, .wijscatterchart, .bubbletracker", "mousemove." + namespace, $.proxy(self._tooltipMouseMove, self));
};
wijcompositechart.prototype._tooltipMouseOver = function (e) {
var target = e.target, self = this, tooltip = self.tooltip, hint = self.options.hint, op = null, title = hint.title, content = hint.content, hintStyle = hint.style, isTitleFunc = $.isFunction(title), isContentFunc = $.isFunction(content), data, bbox, position, raphaelObj;
position = $(self.canvas.canvas.parentNode).offset();
if(self.indicatorLine) {
return;
}
if($(target).data("owner")) {
target = $(target).data("owner");
}
target = $(target);
data = target.data("wijchartDataObj");
if(self.tooltip) {
op = tooltip.getOptions();
if(isTitleFunc || isContentFunc) {
if(isTitleFunc) {
op.title = $.proxy(title, data);
}
if(isContentFunc) {
op.content = $.proxy(content, data);
}
}
if(data.type === "line" || data.type === "marker") {
if(data.type === "marker") {
data = data.lineSeries;
}
if(data.path.removed) {
return;
}
if(self.hoverLine !== data || self.hoverLine === null) {
self.isNewLine = true;
if(self.hoverLine) {
if(!self.hoverLine.path.removed) {
self.hoverLine.path.wijAttr(self.hoverLine.lineStyle);
if(self.hoverPoint && !self.hoverPoint.isSymbol) {
self.hoverPoint.marker.wijAttr(self.hoverPoint.markerStyle);
self.hoverPoint.marker.transform("s1");
}
}
}
if(data.lineHoverStyle) {
data.path.wijAttr(data.lineHoverStyle);
}
self.hoverLine = data;
self.hoverPoint = null;
self.hoverVirtualPoint = null;
}
} else if(data.type === "scatter" || hint.relativeTo === "element") {
self._clearHoverState();
if(data.type === "scatter") {
bbox = data.dot.getBBox();
} else // fixed an issue that when the hint's relativeTo is "element",
// the tooltip will shows with the mouse.
if(target[0] && target[0].raphael && target[0].raphaelid) {
raphaelObj = self.canvas.getById(target[0].raphaelid);
if(raphaelObj) {
bbox = raphaelObj.getBBox();
}
}
op.style.stroke = hintStyle.stroke || target.attr("stroke");
if(bbox) {
self.tooltip.showAt({
x: bbox.x + bbox.width / 2,
y: bbox.y
}, e);
}
} else {
self._clearHoverState();
op.style.stroke = hintStyle.stroke || target.attr("stroke");
self.tooltip.showAt({
x: e.pageX - position.left,
y: e.pageY - position.top
}, e);
}
}
};
wijcompositechart.prototype._tooltipMouseMove = function (e) {
var self = this, target = e.target, data, hint = self.options.hint, position = $(self.canvas.canvas.parentNode).offset();
if($(target).data("owner")) {
target = $(target).data("owner");
}
target = $(target);
data = target.data("wijchartDataObj");
if(self.tooltip && !this.indicatorLine) {
if(data.type !== "line" && data.type !== "marker" && data.type !== "scatter" && hint.relativeTo !== "element") {
self.tooltip.showAt({
x: e.pageX - position.left,
y: e.pageY - position.top
}, e);
}
}
};
wijcompositechart.prototype._tooltipMouseOut = function (e) {
var self = this, target = e.target, data;
if($(target).data("owner")) {
target = $(target).data("owner");
}
target = $(target);
data = target.data("wijchartDataObj");
if(data.type !== "line" && data.type !== "marker" && !self.indicatorLine) {
if(self.tooltip) {
self.tooltip.hide();
}
}
};
wijcompositechart.prototype._mouseMoveInsidePlotArea = function (e, mousePos) {
var self = this, tooltip = self.tooltip, hint = self.options.hint, markers, virtualMarkers, idx = 0, p, point, valueX, valueY, s = null, dataObj = null, op = null, title = hint.title, content = hint.content, isTitleFunc = $.isFunction(title), isContentFunc = $.isFunction(content), distance = 0, hoverLine;
if(tooltip) {
op = tooltip.getOptions();
}
if(self.hoverLine && !self.indicatorLine) {
hoverLine = self.hoverLine;
if(self.isNewLine) {
if(hint.enable && tooltip) {
tooltip.hide();
}
self.isNewLine = false;
}
markers = hoverLine.lineMarkers;
virtualMarkers = hoverLine.virtualMarkers;
idx = -1;
p = {
x: 0,
y: 0
};
if(markers && markers.length) {
$.each(markers, function (i, marker) {
if(marker.removed) {
return true;
}
var box = marker.wijGetBBox(), pos = box.x + box.width / 2, dis = Math.abs(pos - mousePos.left);
if(i === 0 || dis < distance) {
distance = dis;
idx = i;
p = {
x: pos,
y: box.y + box.height / 2
};
}
});
if(self.hoverPoint && self.hoverPoint.index === idx) {
return;
}
if(idx > -1) {
if(markers[idx].removed) {
return;
}
point = $(markers[idx].node).data("wijchartDataObj");
if(point) {
if(self.hoverPoint && !self.hoverPoint.isSymbol) {
if(!self.hoverPoint.removed) {
self.hoverPoint.marker.wijAttr(self.hoverPoint.markerStyle);
self.hoverPoint.marker.transform("s1");
}
}
if(!point.isSymbol) {
if(!point.marker.removed) {
point.marker.wijAttr(point.markerHoverStyle);
}
}
}
self.hoverPoint = point;
self.hoverVirtualPoint = virtualMarkers[idx];
}
} else {
$.each(virtualMarkers, function (i, marker) {
var dis = Math.abs(marker.x - mousePos.left);
if(i === 0 || dis < distance) {
distance = dis;
idx = i;
p = {
x: marker.x,
y: marker.y
};
}
});
if(self.hoverVirtualPoint && self.hoverVirtualPoint.index === idx) {
return;
}
if(idx > -1) {
self.hoverPoint = null;
self.hoverVirtualPoint = virtualMarkers[idx];
}
}
if(tooltip) {
dataObj = self.hoverVirtualPoint;
valueX = dataObj.valX;
valueY = dataObj.valY;
//dataObj = self.hoverPoint;
//valueX = dataObj.valX;
//valueY = dataObj.valY;
if(isTitleFunc || isContentFunc) {
if(isTitleFunc) {
op.title = function () {
var obj = {
pointIndex: idx,
lineIndex: //lineIndex: dataObj.lineSeries.index,
hoverLine.index,
x: valueX,
y: valueY,
label: //label: dataObj.lineSeries.label,
hoverLine.label,
data: dataObj,
fmt: title
}, fmt = $.proxy(obj.fmt, obj), tit = fmt();
return tit;
};
}
if(isContentFunc) {
op.content = function () {
var obj = {
pointIndex: idx,
lineIndex: //lineIndex: dataObj.lineSeries.index,
hoverLine.index,
x: valueX,
y: valueY,
label: //label: dataObj.lineSeries.label,
hoverLine.label,
data: dataObj,
fmt: content
}, fmt = $.proxy(obj.fmt, obj), con = fmt();
return con;
};
}
}
s = $.extend({
stroke: hoverLine.path.attr("stroke")
}, hint.style);
op.style.stroke = s.stroke;
tooltip.showAt(p);
}
}
_super.prototype._mouseMoveInsidePlotArea.call(this, e, mousePos);
};
wijcompositechart.prototype._mouseDownInsidePlotArea = function (e, mousePos) {
_super.prototype._mouseDownInsidePlotArea.call(this, e, mousePos);
this._clearHoverState(true);
};
wijcompositechart.prototype._mouseMoveOutsidePlotArea = function (e, mousePos) {
var self = this;
self._clearHoverState();
_super.prototype._mouseMoveOutsidePlotArea.call(this, e, mousePos);
};
wijcompositechart.prototype._clearHoverState = function (keepTooltip) {
var self = this, tooltip = self.tooltip, hint = self.options.hint;
if(self.hoverLine) {
if(hint.enable && tooltip && !keepTooltip) {
tooltip.hide();
}
if(!self.hoverLine.path.removed) {
self.hoverLine.path.wijAttr(self.hoverLine.lineStyle);
if(self.hoverPoint && !self.hoverPoint.isSymbol) {
self.hoverPoint.marker.wijAttr(self.hoverPoint.markerStyle);
//hoverPoint.marker.scale(1, 1);
self.hoverPoint.marker.transform("s1");
}
}
}
self.hoverLine = null;
self.hoverPoint = null;
self.hoverVirtualPoint = null;
};
wijcompositechart.prototype._getTooltipText = function (fmt, target) {
return "";
};
wijcompositechart.prototype._calculateParameters = function (axisInfo, options) {
var self = this, hasBarType = false, minor, adj;
_super.prototype._calculateParameters.call(this, axisInfo, options);
// handle stock chart.
if(self.isContainsStock) {
self._calculateStockParameters(axisInfo, options);
return;
}
$.each(self.options.seriesList, function (idx, series) {
if(series.type === "column" || series.type === "bar") {
hasBarType = true;
return false;
}
});
if(!hasBarType) {
return;
}
// check for bar chart and x axis expansion
if(axisInfo.id === "x") {
minor = options.unitMinor;
adj = self._getBarAdjustment(axisInfo);
if(adj === 0) {
adj = minor;
} else {
if(minor < adj && minor !== 0) {
adj = Math.floor(adj / minor) * minor;
}
}
axisInfo.min -= adj;
axisInfo.max += adj;
self._calculateMajorMinor(options, axisInfo);
}
};
wijcompositechart.prototype._getBarAdjustment = function (axisInfo) {
var len = 0, o = this.options, max = axisInfo.max, min = axisInfo.min, xLen = 0;
$.each(o.seriesList, function (idx, series) {
if(series.type === "pie") {
return true;
}
if(series.data.x === undefined || series.data.y === undefined) {
return true;
}
xLen = series.data.x.length;
if(len < xLen) {
len = xLen;
}
});
if(len > 1) {
return (max - min) / len * o.clusterWidth * 0.0125;
} else if(len === 1) {
if(min === 0.0 && max === 1.0) {
min = -1.0;
axisInfo.min = min;
}
return (max - min) * 0.0125;
} else {
return 0;
}
};
return wijcompositechart;
})(chart.wijchartcore);
chart.wijcompositechart = wijcompositechart;
wijcompositechart.prototype.widgetEventPrefix = "wijcompositechart";
var wijcompositechart_options = (function () {
function wijcompositechart_options() {
/**
* Selector option for auto self initialization. This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijcompositechart')";
/**
* @ignore
*/
this.wijCSS = {
compositechart: "wijmo-wijcompositechart",
barLabel: "wijbarchart-label",
barElement: "wijbarchart",
barTracker: "bartracker",
bubbleElement: "wijbubblechart-bubble",
bubbleTracker: "bubbletracker",
bubbleLabel: "wijbubblechart-label",
bubbleSymbol: "wijbubblechart-symbol",
scatterElement: "wijscatterchart",
pieLabel: "wijpiechart-label",
pieElement: "wijpiechart",
pieTracker: "pietracker",
lineLabel: "wijlinechart-label",
lineElement: "wijlinechart",
areaElement: "wijlinechart-area",
lineTracker: "linetracker",
canvasMarker: "wijchart-canvas-marker"
};
/**
* A value that determines whether to show a stacked chart.
*/
this.stacked = false;
/**
* A value that indicates the percentage of bar elements in the same cluster overlap.
*/
this.clusterOverlap = 0;
/**
* A value that indicates the percentage of the plot area that each bar cluster occupies.
*/
this.clusterWidth = 85;
/**
* A value that indicates the corner-radius for the bar.
*/
this.clusterRadius = 0;
/**
* A value that indicates the spacing between the adjacent bars.
*/
this.clusterSpacing = 0;
/**
* An array collection that contains the data that will be displayed by the chart."
* @example
* $("#compositechart").wijcompositechart({
* seriesList: [{
* type: "bar",
* label: "Q1",
* legendEntry: true,
* data: {
* x: [1, 2, 3, 4, 5],
* y: [12, 21, 9, 29, 30]
* }}, {
* type: "bar",
* label: "Q2",
* legendEntry: true,
* data: {
* xy: [1, 21, 2, 10, 3, 19, 4, 31, 5, 20]
* }}, {
* type: "line",
* label: "Q3",
* legendEntry: true,
* data: {
* x: [1, 2, 3, 4, 5],
* y: [12, 21, 9, 29, 30]
* }}, {
* type: "pie",
* label: "title for pie chart",
* legendEntry: false,
* data: [{
* label: "Q4",
* data: 12,
* offset: 15
* }, {
* label: "Q5",
* data: 21,
* offset: 0
* }, {
* label: "Q5",
* data: 21,
* offset: 0
* }],
* center: {
* x: 150,
* y: 150
* },
* radius: 100
* }
* }]
* OR
* seriesList: [{
* type: "bar"
* label: "Q1",
* legendEntry: true,
* data: {
* x: ["A", "B", "C", "D", "E"],
* y: [12, 21, 9, 29, 30]
* }
* }, {
* type: "line"
* label: "Q1",
* legendEntry: true,
* data: {
* x: ["A", "B", "C", "D", "E"],
* y: [12, 21, 9, 29, 30]
* }
* }
* ]
* OR
* seriesList: [{
* type: "bar",
* label: "Q1",
* legendEntry: true,
* data: {
* x: [new Date(1978, 0, 1), new Date(1980, 0, 1),
* new Date(1981, 0, 1), new Date(1982, 0, 1),
* new Date(1983, 0, 1)],
* y: [12, 21, 9, 29, 30]
* }
* }, {
* type: "bar",
* label: "Q2",
* legendEntry: true,
* data: {
* x: [new Date(1978, 0, 1), new Date(1980, 0, 1),
* new Date(1981, 0, 1), new Date(1982, 0, 1),
* new Date(1983, 0, 1)],
* y: [10, 25, 5, 25, 35]
* }
* }]
* });
*/
this.seriesList = [];
/**
* The animation option defines the animation effect and controls other aspects of the widget's animation,
* such as duration and easing.
*/
this.animation = {
enabled: /**
* A value that determines whether to show animation.
*/
true,
duration: /**
* The duration option defines the length of the animation effect in milliseconds.
*/
400,
easing: /**
* Sets the type of animation easing effect that users experience when the wijcompositechart series is loaded to the page.
* @remarks
* The easing is defined in Raphael, the documentation is:http://raphaeljs.com/reference.html#Raphael.easing_formulas
*/
">"
};
/**
* The seriesTransition option is used to animate series in the chart when just their values change.
* @remarks
* This is helpful for visually showing changes in data for the same series.
* Note: When programmatically updating the seriesList with a different number of series in the array make sure
* to disable seriesTransition like the following:
* seriesTransition: { enabled: false}
*/
this.seriesTransition = {
enabled: /**
* A value that determines whether to show animation when reloading data.
*/
true,
duration: /**
* A value that indicates the duration for the series transition.
*/
400,
easing: /**
* Sets the type of animation easing effect that users experience when the wijcompositechart series is
* reloaded after they have changed the data for the seriesList option.
*/
">"
};
/**
* Occurs when the user clicks a mouse button.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {ICompositeChartEventArgs} data Information about an event
*/
this.mouseDown = null;
/**
* Occurs when the user releases a mouse button while the pointer is over the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {ICompositeChartEventArgs} data Information about an event
*/
this.mouseUp = null;
/**
* Occurs when the user first places the pointer over the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {ICompositeChartEventArgs} data Information about an event
*/
this.mouseOver = null;
/**
* Occurs when the user moves the pointer off of the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {ICompositeChartEventArgs} data Information about an event
*/
this.mouseOut = null;
/**
* Occurs when the user moves the mouse pointer while it is over a chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {ICompositeChartEventArgs} data Information about an event
*/
this.mouseMove = null;
/**
* Occurs when the user clicks the chart element.
* @event
* @param {jQuery.Event} e Standard jQuery event object
* @param {ICompositeChartEventArgs} data Information about an event
*/
this.click = null;
}
return wijcompositechart_options;
})();
wijcompositechart.prototype.options = $.extend(true, {
}, chart.wijchartcore.prototype.options, new wijcompositechart_options());
$.wijmo.registerWidget("wijcompositechart", wijcompositechart.prototype);
})(wijmo.chart || (wijmo.chart = {}));
var chart = wijmo.chart;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../external/declarations/globalize.d.ts" />
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/// <reference path="../wijpopup/jquery.wijmo.wijpopup.ts" />
/*globals jQuery,$,window,alert,document,confirm,location,setTimeout, Globalize,
clearTimeout,amplify*/
/*jslint white: false */
/*jslint nomen: false*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* globalize.js
* jquery.wijmo.wijpopup.js
* jquery.ui.wijutil.js
*
*/
(function (datepager) {
"use strict";
var $ = jQuery, widgetName = "wijdatepager";
/** @widget */
var wijdatepager = (function (_super) {
__extends(wijdatepager, _super);
function wijdatepager() {
_super.apply(this, arguments);
}
wijdatepager.prototype._setOption = function (key, value) {
$.wijmo.widget.prototype._setOption.apply(this, arguments);
switch(key) {
case "culture":
this.options.culture = value;
this._initBackground();
break;
case "selectedDate":
this.options.selectedDate = value;
this._initBackground();
break;
case "disabled":
if(value) {
this._disable();
} else {
this._enable();
}
break;
case "viewType":
this.options.viewType = value;
this._initBackground();
break;
case "nextTooltip":
//this.element.find(".wijmo-wijdatepager-increment").text(value).button("refresh");
this.element.find(".wijmo-wijdatepager-increment").attr("title", value);
break;
case "prevTooltip":
//this.element.find(".wijmo-wijdatepager-decrement").text(value).button("refresh");
this.element.find(".wijmo-wijdatepager-decrement").attr("title", value);
break;
case "firstDayOfWeek":
this.options.firstDayOfWeek = value;
if(this.options.viewType === "week") {
this._initBackground();
}
break;
}
return this;
};
wijdatepager.prototype._disable = function () {
this.element.addClass(this.options.wijCSS.stateDisabled);
this.element.find(".wijmo-wijdatepager-decrement").button("option", "disabled", true);
this.element.find(".wijmo-wijdatepager-increment").button("option", "disabled", true);
};
wijdatepager.prototype._enable = function () {
this.element.removeClass(this.options.wijCSS.stateDisabled);
this.element.find(".wijmo-wijdatepager-decrement").button("option", "disabled", false);
this.element.find(".wijmo-wijdatepager-increment").button("option", "disabled", false);
};
wijdatepager.prototype._create = /// <summary>
/// Creates date pager DOM elements and binds interactive events.
/// </summary>
function () {
var o = this.options, resizeHandler, decBtn, incBtn;
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
if(!o.selectedDate) {
o.selectedDate = new Date();
}
this._dtpagernamespacekey = "dtpager" + new Date().getTime();
this.element.addClass("wijmo-wijdatepager " + o.wijCSS.widget + " ui-helper-clearfix");
resizeHandler = $.proxy(this.invalidate, this);
$(window).bind("resize." + this._dtpagernamespacekey, resizeHandler);
if(this.element.disableSelection) {
this.element.disableSelection();
}
this.element.append($("<a class=\"wijmo-wijdatepager-decrement\"><span>" + o.prevTooltip + "</span></a>")).append("<div class=\"wijmo-wijdatepager-container " + o.wijCSS.content + "\">" + "<div class=\"wijmo-wijdatepager-pages\"></div>" + "</div>" + "<a class=\"wijmo-wijdatepager-increment\"><span>" + o.nextTooltip + "</span></a>");
$.wijmo.widget.prototype._create.apply(this, arguments);
decBtn = this.element.find(".wijmo-wijdatepager-decrement");
incBtn = this.element.find(".wijmo-wijdatepager-increment");
if($.mobile == null) {
decBtn.button({
icons: {
primary: "ui-icon-triangle-1-w"
},
text: false
});
incBtn.button({
icons: {
primary: "ui-icon-triangle-1-e"
},
text: false
});
} else {
decBtn.html("");
decBtn.attr("data-icon", "arrow-l");
decBtn.button({
text: false
});
incBtn.html("");
incBtn.attr("data-icon", "arrow-r");
incBtn.button({
text: false
});
}
decBtn.click($.proxy(this.goLeft, this));
incBtn.click($.proxy(this.goRight, this));
this._initBackground();
if(o.disabled) {
this._disable();
}
};
wijdatepager.prototype.destroy = /** Destroys the widget and resets the DOM element.*/
function () {
this.element.removeClass("wijmo-wijdatepager");
$(window).unbind("." + this._dtpagernamespacekey);
};
wijdatepager.prototype.refresh = /** Refreshes the widget layout.*/
function () {
this.invalidate();
};
wijdatepager.prototype.invalidate = /** Redraws the widget layout.*/
function () {
var selectedPage, selectedDate = this.options.selectedDate, newIndex, container = this.element.find(".wijmo-wijdatepager-container"), decBtn = this.element.find(".wijmo-wijdatepager-decrement"), incBtn = this.element.find(".wijmo-wijdatepager-increment"), innerWidth = this.element.innerWidth(), decBtnW = decBtn.is(":visible") ? decBtn.outerWidth(true) : 0, incBtnW = incBtn.is(":visible") ? incBtn.outerWidth(true) : 0, pagesBg, pageLabels, pageWidth;
selectedPage = this.element.find(".wijmo-wijdatepager-pagelabel." + this._getDateClass(selectedDate));
if(selectedPage.length !== 1) {
selectedPage = $(this.element.find(".wijmo-wijdatepager-pagelabel")[this._index]);
} else {
newIndex = this.element.find(".wijmo-wijdatepager-pagelabel").index(selectedPage);
this._index = newIndex;
/*
if (this._index !== newIndex) {
this._index = newIndex;
}*/
}
this.element.find(".wijmo-wijdatepager-pagelabel." + this.options.wijCSS.stateActive).removeClass(this.options.wijCSS.stateActive);
selectedPage.addClass(this.options.wijCSS.stateActive);
container.css("left", decBtnW);
this.element.removeClass("wijmo-wijdatepager-width-smallest" + " wijmo-wijdatepager-width-small wijmo-wijdatepager-width-medium" + " wijmo-wijdatepager-width-normal");
if(innerWidth < 300) {
this.element.addClass("wijmo-wijdatepager-width-smallest");
} else if(innerWidth < 475) {
this.element.addClass("wijmo-wijdatepager-width-small");
} else if(innerWidth < 600) {
this.element.addClass("wijmo-wijdatepager-width-medium");
} else {
this.element.addClass("wijmo-wijdatepager-width-normal");
}
container.outerWidth(innerWidth - decBtnW - incBtnW);
//ie6/7 don't support display: table and display: table-cell,
//so set width to each page label.
if($.browser.msie && parseInt($.browser.version, 10) <= 7) {
pagesBg = this.element.find(".wijmo-wijdatepager-pages");
pageLabels = pagesBg.find(".wijmo-wijdatepager-pagelabel");
pageWidth = Math.round(pagesBg.width() / this._datesDef.length) - (pageLabels.outerWidth(true) - pageLabels.width());
pageLabels.width(pageWidth);
}
};
wijdatepager.prototype.goLeft = /** Selects the previous date.
* @param {Object} ev The event of firing the select previous date.
*/
function (ev) {
var o = this.options;
if(o.disabled) {
return;
}
this._setSelectedIndex(this._index - 1, true);
if(ev) {
ev.preventDefault();
return false;
}
};
wijdatepager.prototype.goRight = /** Selects the next date.*/
function () {
var o = this.options;
if(o.disabled) {
return;
}
this._setSelectedIndex(this._index + 1);
};
wijdatepager.prototype._getCulture = // culture:
function (name) {
if (typeof name === "undefined") { name = null; }
return Globalize.findClosestCulture(name || this.options.culture);
};
wijdatepager.prototype._isRTL = function () {
return !!this._getCulture().isRTL;
};
wijdatepager.prototype._initBackground = function (animate, isRightToLeft) {
if (typeof animate === "undefined") { animate = false; }
if (typeof isRightToLeft === "undefined") { isRightToLeft = false; }
var s, i, oldBg, newBg, pageLabels, newPageIndPos, self = this, pageWidth;
if(this._isInAnimate) {
return;
}
this._index = 0;
this._datesDef = this._getDatesDefinition();
this._min = 0;
this._max = this._datesDef.length - 1;
s = "";
for(i = 0; i < this._datesDef.length; i += 1) {
s += "<div class=\"wijmo-wijdatepager-pagelabel" + (i === 0 ? " wijmo-wijdatepager-pagelabel-first" : "") + (this._datesDef[i].range ? " wijmo-wijdatepager-pagerange" : "") + (this._datesDef[i].header ? " wijmo-wijdatepager-pageheader ui-state-highlight" : "") + (i === this._datesDef.length - 1 ? " wijmo-wijdatepager-pagelabel-last" : "") + " " + this._getDateClass(this._datesDef[i].d) + "\">" + this._datesDef[i].l + "</div>";
}
newBg = this.element.find(".wijmo-wijdatepager-pages");
if(animate) {
this._isInAnimate = true;
oldBg = newBg.clone(true);
newBg.html(s);
pageLabels = newBg.find(".wijmo-wijdatepager-pagelabel");
if(!isRightToLeft) {
oldBg.insertBefore(newBg);
newPageIndPos = $(pageLabels[this._index]).offset().left;
newBg.css("opacity", 0).css("left", oldBg.outerWidth(true)).stop().animate({
left: "0px",
opacity: 100
});
oldBg.stop().animate({
left: "-" + oldBg.outerWidth(true) + "px",
opacity: 0
}, function () {
oldBg.remove();
self._isInAnimate = false;
self.invalidate();
});
} else {
oldBg.insertAfter(newBg);
newPageIndPos = $(pageLabels[this._index]).offset().left;
newBg.css("opacity", 0).css("left", -oldBg.outerWidth(true)).stop().animate({
left: "0px",
opacity: 100
});
oldBg.css("left", 0).stop().animate({
left: oldBg.outerWidth(true) + "px",
opacity: 0
}, function () {
oldBg.remove();
self._isInAnimate = false;
self.invalidate();
});
}
} else {
newBg.html(s);
this.invalidate();
}
//.stop().animate({ left: "0px" })
pageLabels = newBg.find(".wijmo-wijdatepager-pagelabel");
pageLabels.hover($.proxy(this._pagelabelHover, this), $.proxy(this._pagelabelHout, this));
pageLabels.bind("mousedown", $.proxy(this._pagelabelMouseDown, this));
pageLabels.click($.proxy(function (e) {
var target = $(e.target), ind;
ind = this.element.find(".wijmo-wijdatepager-pagelabel").index(target);
this._setSelectedIndex(ind);
}, this));
};
wijdatepager.prototype._getDateClass = function (dt) {
return "c1dt" + dt.getFullYear() + "_" + dt.getMonth() + "_" + dt.getDate();
};
wijdatepager.prototype._addDays = function (dt, num) {
return new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() + num);
};
wijdatepager.prototype._getDatesDefinition = function () {
var o = this.options, viewType = o.viewType.toLowerCase(), i, dt, curDt, nextDt, endDt, datesDef = [], selectedDate = o.selectedDate;
switch(viewType) {
case "week":
curDt = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), -6);
i = o.firstDayOfWeek - curDt.getDay();
if(Math.abs(i) > 6) {
i = curDt.getDay() - o.firstDayOfWeek;
}
curDt = this._addDays(curDt, i);
endDt = new Date(selectedDate.getFullYear(), selectedDate.getMonth() + 1, 7);
i = 0;
while(curDt < endDt || curDt.getMonth() === selectedDate.getMonth()) {
nextDt = this._addDays(curDt, 7);
datesDef.push({
l: this._formatString(this.localizeString("weekViewLabelFormat", "{0:MMM dd}-{1:dd}"), curDt, this._addDays(curDt, 6)),
d: curDt,
d2: this._addDays(curDt, 6)
});
if(selectedDate >= curDt && selectedDate <= nextDt) {
this._index = i;
}
curDt = nextDt;
i += 1;
}
break;
case "month":
dt = new Date(selectedDate.getFullYear() - 1, 0, 1);
datesDef.push({
l: dt.getFullYear(),
d: dt,
range: true
});
dt = new Date(selectedDate.getFullYear(), 0, 1);
datesDef.push({
l: dt.getFullYear(),
d: dt,
header: true
});
for(i = 0; i < 12; i += 1) {
dt = new Date(selectedDate.getFullYear(), i, 1);
datesDef.push({
l: this._formatString(this.localizeString("monthViewLabelFormat", "{0:MMM}"), dt),
d: dt
});
nextDt = new Date(selectedDate.getFullYear(), i + 1, 1);
if(selectedDate >= dt && selectedDate <= nextDt) {
this._index = i + 2;
}
}
dt = new Date(selectedDate.getFullYear() + 1, 0, 1);
datesDef.push({
l: dt.getFullYear(),
d: dt,
range: true
});
break;
default:
//case "day":
dt = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), 0);
datesDef.push({
l: Globalize.format(dt, "MMM", this._getCulture()),
d: dt,
range: true
});
dt = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), 1);
datesDef.push({
l: Globalize.format(dt, "MMM", this._getCulture()),
d: dt,
header: true
});
curDt = dt;
i = 2;
while(curDt.getMonth() === selectedDate.getMonth()) {
nextDt = new Date(curDt.getFullYear(), curDt.getMonth(), curDt.getDate() + 1);
datesDef.push({
l: this._formatString(this.localizeString("dayViewLabelFormat", "{0:d }"), curDt),
d: curDt
});
if(selectedDate >= curDt && selectedDate <= nextDt) {
this._index = i;
}
curDt = nextDt;
i += 1;
}
dt = new Date(selectedDate.getFullYear(), selectedDate.getMonth() + 1, 1);
datesDef.push({
l: Globalize.format(dt, "MMM", this._getCulture()),
d: dt,
range: true
});
break;
}
return datesDef;
};
wijdatepager.prototype._setSelectedIndex = function (ind, skipHeader) {
if (typeof skipHeader === "undefined") { skipHeader = false; }
var o = this.options, pendingSelectedDate;
if(o.disabled) {
return;
}
if(ind >= this._min && ind <= this._max) {
if(this._dragActivated) {
this._showTooltip(ind);
}
if(this._index !== ind) {
if(this._datesDef[ind].header) {
if(skipHeader) {
ind = ind - 1;
} else {
return;
}
}
this._index = ind;
pendingSelectedDate = this._datesDef[ind].d;
o.selectedDate = pendingSelectedDate;
/*
if (this._index === this._max) {
if (o.viewType === "week") {
o.selectedDate = new Date(o.selectedDate.getFullYear(),
o.selectedDate.getMonth(), o.selectedDate.getDate() + 7);
}
}*/
if(this._max > 2 && this._index === 0) {
this._initBackground(true, true);
} else if(this._index === this._max) {
if(o.viewType === "week") {
o.selectedDate = new Date(o.selectedDate.getFullYear(), o.selectedDate.getMonth(), o.selectedDate.getDate() + 7);
}
this._initBackground(true, false);
o.selectedDate = pendingSelectedDate;
} else {
this.invalidate();
}
this._trigger("selectedDateChanged", null, {
selectedDate: o.selectedDate
});
}
}
};
wijdatepager.prototype._pagelabelHover = function (e) {
var target = $(e.target), o = this.options;
if(target.hasClass("wijmo-wijdatepager-pageheader")) {
return;
}
target.addClass(o.wijCSS.stateHover);
};
wijdatepager.prototype._showTooltip = function (ind) {
var o = this.options, dateDef = this._datesDef[ind], viewType = o.viewType, s, target = this.element.find(".wijmo-wijdatepager-pagelabel")[ind];
if(!this._tooltip) {
this._tooltip = $("<div class=\"wijmo-wijdatepager-tooltip\">" + "<div class=\"wijmo-wijdatepager-tooltip-inner\">" + "</div>" + "<div class=\"wijmo-wijdatepager-triangle\"></div>" + "</div>");
this.element.append(this._tooltip);
this._tooltip.wijpopup();
}
s = "";
switch(viewType) {
case "week":
if(dateDef.d.getMonth() !== dateDef.d2.getMonth()) {
s = this._formatString(this.localizeString("weekViewTooltip2MonthesFormat", "{0:MMMM d} - {1:MMMM d, yyyy}"), dateDef.d, dateDef.d2);
} else {
s = this._formatString(this.localizeString("weekViewTooltipFormat", "{0:MMMM d} - {1:d, yyyy}"), dateDef.d, dateDef.d2);
}
break;
case "month":
s = this._formatString(this.localizeString("monthViewTooltipFormat", "{0:MMMM yyyy}"), dateDef.d);
break;
default:
//case "day":
s = this._formatString(this.localizeString("dayViewTooltipFormat", "{0:dddd, MMMM d, yyyy}"), dateDef.d);
break;
break;
}
if($.ui) {
//disable popup for mobile mode
this._tooltip.wijpopup("show", {
of: target,
my: "center bottom",
at: "center top",
offset: "-10 -10"
});
this._tooltip.find(".wijmo-wijdatepager-tooltip-inner").html(s);
}
//Monday, 31st, 2001
//
};
wijdatepager.prototype._hideTooltip = function () {
this._tooltip.wijpopup("hide");
};
wijdatepager.prototype._pagelabelHout = function (e) {
$(e.target).removeClass(this.options.wijCSS.stateHover);
};
wijdatepager.prototype._pagelabelMouseDown = function (e) {
this._dragActivated = false;
if(this.options.disabled) {
return;
}
e.preventDefault();
var target = $(e.target), ind;
if(target.hasClass("wijmo-wijdatepager-pageheader")) {
return;
}
ind = this.element.find(".wijmo-wijdatepager-pagelabel").index(target);
this._dragActivated = true;
this._setSelectedIndex(ind);
this._mouseDownTimeFix20555 = new Date().getTime();
this._startClientX = e.pageX;
this._startInd = ind;
$(document).bind("mousemove." + this._dtpagernamespacekey, $.proxy(this._pageindicatorMouseMove, this));
$(document).bind("mouseup." + this._dtpagernamespacekey, $.proxy(this._pageindicatorMouseUp, this));
};
wijdatepager.prototype._detectLeftButton = function (event) {
if(event.originalEvent) {
event = event.originalEvent;
}
if("buttons" in event) {
return event.buttons === 1;
} else if("which" in event) {
return event.which === 1;
} else {
return event.button === 1;
}
};
wijdatepager.prototype._pageindicatorMouseMove = function (e) {
if(!this._detectLeftButton(e)) {
this._pageindicatorMouseUp();
return;
}
e.preventDefault();
if(this._isInAnimate) {
return;
}
var startPage = this.element.find(".wijmo-wijdatepager-pagelabel")[this._startInd], newPos, ind;
if(!startPage) {
return;
}
newPos = startPage.offsetLeft + Math.round(startPage.offsetWidth / 2) + (e.pageX - this._startClientX);
ind = this._findClosesPageIndexByPos(newPos);
if(this._prevMoveInd === ind) {
// fix for [20534] case 1:
return;
}
this._prevMoveInd = ind;
if((this._mouseDownTimeFix20555 + 150) > new Date().getTime()) {
// fix for [20555]
return;
}
if(ind !== -1 && ind !== this._index) {
this._setSelectedIndex(ind);
}
//this.element.find(".wijmo-wijdatepager-pagelabel").css(left;
};
wijdatepager.prototype._pageindicatorMouseUp = function () {
this._dragActivated = false;
$(document).unbind("." + this._dtpagernamespacekey);
this._hideTooltip();
};
wijdatepager.prototype._findClosesPageIndexByPos = function (pos) {
var pagelabels = this.element.find(".wijmo-wijdatepager-pages").find(".wijmo-wijdatepager-pagelabel"), i;
for(i = 0; i < pagelabels.length; i += 1) {
if((pagelabels[i].offsetLeft) < pos && (pagelabels[i].offsetLeft + pagelabels[i].offsetWidth) > pos) {
return i;
}
}
return -1;
};
wijdatepager.prototype.localizeString = /** @ignore */
function (key, defaultValue) {
var o = this.options;
if(o.localization && o.localization[key]) {
return o.localization[key];
}
return defaultValue;
//("buttonToday", "today")
};
wijdatepager.prototype._formatString = function (fmt, arg0, arg1, arg2) {
var r, args = arguments, i, funcArgs, self = this;
if(args.length <= 1) {
return Globalize.format(args);
}
if(typeof fmt === "string") {
/*
if (fmt === "_formatWeekTitle") {
fmt = this._formatWeekTitle;
}
else if (fmt === "_formatMonthTitle") {
fmt = this._formatMonthTitle;
}
else
*/
if(typeof window[fmt] === "function") {
fmt = window[fmt];
}
}
if(typeof fmt === "function") {
funcArgs = [];
for(i = 1; i < args.length; i += 1) {
funcArgs[i - 1] = args[i];
}
return fmt.apply(this, funcArgs);
}
r = new RegExp("\\{(\\d+)(?:,([-+]?\\d+))?(?:\\:" + "([^(^}]+)(?:\\(((?:\\\\\\)|[^)])+)\\)){0,1}){0,1}\\}", "g");
return fmt.replace(r, function (m, num, len, f, params) {
m = args[Number(num) + 1];
if(f) {
return Globalize.format(m, f, self._getCulture());
} else {
return m;
}
});
};
return wijdatepager;
})(wijmo.wijmoWidget);
datepager.wijdatepager = wijdatepager;
var wijdatepager_options = (function () {
function wijdatepager_options() {
/** @ignore */
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body ui-body-c",
stateDefault: "ui-btn-up-c"
};
/** @ignore */
this.initSelector = ":jqmData(role='wijdatepager')";
/** Culture name, e.g. "de-DE".
* @example
* // This markup sets the culture to German:
* $("#element").wijdatepager( { culture: "de-DE" } );
*/
this.culture = "";
/** Use the localization option in order to provide custom localization.
* @remarks Default:
* {
* dayViewTooltipFormat: "{0:dddd, MMMM d, yyyy}",
* weekViewTooltipFormat: "{0:MMMM d} - {1:d, yyyy}",
* weekViewTooltip2MonthesFormat: "{0:MMMM d} - {1:MMMM d, yyyy}",
* monthViewTooltipFormat: "{0:MMMM yyyy}",
* dayViewLabelFormat": "{0:d }",
* weekViewLabelFormat: "{0:MMM dd}-{1:dd}",
* monthViewLabelFormat: "{0:MMM}"
* }
* @example
* $("#datepager").wijdatepager(
* {
* localization: {
* weekViewTooltip2MonthesFormat: "{0:MMMM d} - {1:MMMM d}",
* dayViewTooltipFormat: "{0:dddd, MMMM d}"
* }
* });
*/
this.localization = null;
/** The first day of the week (from 0 to 6). Sunday is 0, Monday is 1, and so on.*/
this.firstDayOfWeek = 0;
/** The selected date.
* @type {Date}
*/
this.selectedDate = null;
/** The active view type.
* @remarks Possible values are: day, week, month.
*/
this.viewType = "day";
/** Gets or sets the text for the 'next' button's ToolTip.
*/
this.nextTooltip = "right";
/** Gets or sets the text for the 'previous' button's ToolTip.
*/
this.prevTooltip = "left";
}
return wijdatepager_options;
})();
/*Available Events:
/// <summary>
/// Occurs when the selectedDate option has been changed.
/// Type: Function
/// Event type: wijdatepagerselecteddatechanged
/// Code example:
/// Supply a callback function to handle the selectedDateChanged event
/// as an option.
/// $("#wijdatepager").wijdatepager(
/// { selectedDateChanged: function (e, args) {
/// alert("selected date:" + args.selectedDate);
/// }
/// });
/// Bind to the event by type: wijdatepagerselecteddatechanged.
/// $("#wijdatepager").bind( "wijdatepagerselecteddatechanged",
/// function(e, args) {
/// alert("selected date:" + args.selectedDate);
/// });
/// </summary>
/// <param name="e" type="Object">The jQuery.Event object.</param>
/// <param name="args" type="Object">
/// args.selectedDate - the new selectedDate option value.</param>
selectedDateChanged(e, args)
*/
;
wijdatepager.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijdatepager_options());
$.wijmo.registerWidget(widgetName, wijdatepager.prototype);
})(wijmo.datepager || (wijmo.datepager = {}));
var datepager = wijmo.datepager;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/*globals jQuery,$,window,alert,document,confirm,location,setTimeout, Globalize,
amplify*/
/*jslint white: false */
/*jslint nomen: false*/
/*jslint browser: true*/
/*jslint continue: true*/
/*jslint devel: true*/
/*jslint forin: true*/
/*jslint maxlen: 110*/
/*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* globalize.js
* jquery.mousewheel.js
* jquery.plugin.wijtextselection.js
* jquery.wijmo.wijutil.js
* jquery.wijmo.wijinputcore.js
* jquery.wijmo.wijinputdate.js
* jquery.wijmo.wijinputnumber.js
* jquery.wijmo.wijcalendar.js
* jquery.wijmo.wijdialog.js
* jquery.wijmo.wijcombobox.js
* jquery.wijmo.wijdatepager.js
Following dependencies are needed if you wish to enable built-in client side data-storage:
* amplify.core.js
* amplify.store.js
*/
/*
//qq: move to module:
interface IEvent {
/// id - String, unique event id, this field generated automatically;
id: string;
/// calendar - String, calendar id to which the event belongs;
calendar: string;
/// subject - String, event title;
subject: string;
/// location - String, event location;
location: string;
/// start - Date, start date/time;
start: Date;
/// end - Date, end date/time;
end: Date;
/// description - String, event description;
description: string;
/// color - String, event color;
color: string;
/// allday - Boolean, indicates all day event
allday: bool;
/// tag - String, this field can be used to store custom information.
tag: string;
/// Internal field.
prevData: any;
/// parentRecurrenceId - String, id of the event object that
/// defines the recurrence criteria for this event object.
/// If an event is recurring it represents an occurrence in the series that is
/// started and defined by a specific pattern event.
/// Use the getPatern method in order to obtain the pattern
/// of the current event. A pattern event can be recognized by its
/// recurrenceState field set to the "master" value.
/// The recurrence information defined by the pattern event
/// can be accessed via the recurrencePattern field of the event.
/// If this event is a not member of a recurrence,
/// or is itself a root event, this field will be null.
parentRecurrenceId: string;
/// recurrenceState - String, indicates the recurrence state of the event.
/// (possible values are "notRecurring"(or null), "master", "occurrence",
/// "exception", "removed")
recurrenceState: string;
/// recurrencePattern - Object, represents the recurrence attributes
/// of an event. Only master events can have this field
/// (recurrenceState is "master")
/// Object syntax:
/// parentRecurrenceId - String, id of the event object
/// which represents the master event for this
/// recurrencePattern object.
/// recurrenceType - String, determines the type of recurrence:
/// daily - the recurring event reoccurs on a daily basis.
/// workdays - the recurring event reoccurs every working day.
/// monthly - the recurring event reoccurs on a monthly basis.
/// monthlyNth - the recurring event reoccurs every N months.
/// weekly - the recurring event reoccurs on a weekly basis.
/// yearly - the recurring event reoccurs on an yearly basis.
/// yearlyNth - the recurring event reoccurs every N years.
/// interval - Number, specifies the interval between occurrences
/// of the recurrence.
/// The interval field works in conjunction with
/// the "recurrenceType" field to determine the cycle of the recurrence.
/// The maximum allowable value is 99 for weekly patterns and 999
/// for daily patterns.
/// The default value is 1.
/// For example, if the recurrenceType is set
/// to daily, and the "interval" is set to 3,
/// the recurrence will occur every third day.
/// startTime - Date, indicates the start time for the given
/// occurrence of the recurrence pattern.
/// endTime - Date, indicates the end time for the given
/// occurrence of the recurrence pattern.
/// patternStartDate - Date, indicates the start date of the
/// recurrence pattern.
/// patternEndDate - Date, indicates the end date of the
/// recurrence pattern.
/// This field is optional but must be coordinated
/// with other fields when setting up a recurrence pattern.
/// If this field or the "occurrences" field is set,
/// the pattern is considered to be finite, and the "noEndDate"
/// field is false.
/// If neither "patternEndDate" nor "occurrences" is set,
/// the pattern is considered infinite and "noEndDate" is true.
/// The "interval" field must be set before
/// setting "patternEndDate".
/// occurrences - Number, the number of occurrences for the
/// recurrence pattern. This field allows the definition of
/// a recurrence pattern that is only valid for the specified
/// number of subsequent occurrences.
/// For example, you can set this property to 10 for a formal
/// training course that will be held on the next ten Thursday
/// evenings. The default value is 0. This field must be
/// coordinated with other fields when setting up a recurrence pattern.
/// If the "patternEndDate" field or the "occurrences" field
/// is set, the pattern is considered to be finite and the
/// "noEndDate" field is false.
/// If neither "patternEndDate" nor "occurrences" is set,
/// the pattern is considered infinite and "noEndDate" is true.
/// instance - String, determines the week in a month in which
/// the event will occur. This field is only valid for recurrences of
/// the "monthlyNth" and "yearlyNth" types and allows the definition
/// of a recurrence pattern that is only valid for the Nth occurrence,
/// such as "the 2nd Sunday in March" pattern.
/// The default value is "first".
/// Possible values are:
/// first - the recurring event will occur on the specified
/// day or days of the first week in the month.
/// second - The recurring event will occur on the specified
/// day or days of the second week in the month.
/// third = - The recurring event will occur on the specified
/// day or days of the third week in the month.
/// fourth - The recurring event will occur on the specified
/// day or days of the fourth week in the month.
/// last - The recurring event will occur on the specified
/// day or days of the last week in the month.
/// dayOfWeekMask - String, contains set of values representing the mask
/// for week days on which the recurring event occurs.
/// Monthly and yearly patterns are only valid for a single day.
/// The default value is "none".
/// When the "RecurrenceType" field is set to "daily",
/// the "DayOfWeekMask" field can only be set to "everyDay";
/// setting the field to any other value will result in an exception.
/// When the "recurrenceType" field is set to
/// "workdays", the "dayOfWeekMask" field
/// can only be set to "workDays"; setting the field
/// to any other value will result in an exception.
/// When the "recurrenceType" field is set to
/// "weekly", the "dayOfWeekMask" field
/// cannot be set to "none"; doing so will result
/// in an exception being thrown.
/// When the recurrenceType" field is set to
/// "monthly" or "yearly" the "dayOfWeekMask" field is not applicable.
/// Possible values are:
/// none - no specific value; the actual value is obtained from
/// the root event object.
/// sunday - specifies Sunday.
/// monday - Specifies Monday.
/// tuesday - Specifies Tuesday.
/// wednesday - Specifies Wednesday.
/// thursday - Specifies Thursday.
/// friday - Specifies Friday.
/// saturday - Specifies Saturday.
/// weekendDays - Specifies Saturday and Sunday (or what ever days according
/// to the settings of the C1EventsCalendar).
/// workDays - Specifies work days (all days except weekend).
/// everyDay - Specifies every day of the week.
/// dayOfMonth - Number, the number of the day in its respective month on which
/// each occurrence will occur. Applicable only when the recurrenceType
/// field is set to "monthly" or "yearly".
/// The default value is 1.
/// monthOfYear - Number, indicates which month of the year is valid
/// for the specified recurrence pattern. Can be a number from 1 to 12.
/// This field is only valid for recurrence patterns whose recurrenceType"
/// field is set to "yearlyNth" or "yearly".
/// The default value is 1.
/// noEndDate - Boolean, indicates if the recurrence pattern is endless.
/// The default value is True. This field must be coordinated with
/// other fields when setting up a recurrence pattern. If the patternEndDate field
/// or the occurrences field is set, the pattern is considered
/// to be finite and the "noEndDate" field is false.
/// If neither patternEndDate nor occurrences is set,
/// the pattern is considered infinite and "noEndDate" is true.
/// exceptions - Array, holds the list of event object ids that
/// define the exceptions to that series of events.
/// This field is read-only.
/// removedOccurrences - Array, holds the list of event object's ids
/// removed from that series of events.
recurrencePattern: any;
};
*/
/*
block comments:
// util methods:
// format date/time:
// public methods
// _parseDateFromClass
// Event object fields:
/// id - String, unique event id, this field generated automatically;
/// calendar - String, calendar id to which the event belongs;
/// subject - String, event title;
/// location - String, event location;
/// start - Date, start date/time;
/// end - Date, end date/time;
/// description - String, event description;
/// color - String, event color;
/// allday - Boolean, indicates all day event
/// tag - String, this field can be used to store custom information.
/// parentRecurrenceId - String, id of the event object that
/// defines the recurrence criteria for this event object.
/// If an event is recurring it represents an occurrence in the series that is
/// started and defined by a specific pattern event.
/// Use the getPatern method in order to obtain the pattern
/// of the current event. A pattern event can be recognized by its
/// recurrenceState field set to the "master" value.
/// The recurrence information defined by the pattern event
/// can be accessed via the recurrencePattern field of the event.
/// If this event is a not member of a recurrence,
/// or is itself a root event, this field will be null.
/// recurrenceState - String, indicates the recurrence state of the event.
/// (possible values are "notRecurring"(or null), "master", "occurrence",
/// "exception", "removed")
/// recurrencePattern - Object, represents the recurrence attributes
/// of an event. Only master events can have this field
/// (recurrenceState is "master")
/// Object syntax:
/// parentRecurrenceId - String, id of the event object
/// which represents the master event for this
/// recurrencePattern object.
/// recurrenceType - String, determines the type of recurrence:
/// daily - the recurring event reoccurs on a daily basis.
/// workdays - the recurring event reoccurs every working day.
/// monthly - the recurring event reoccurs on a monthly basis.
/// monthlyNth - the recurring event reoccurs every N months.
/// weekly - the recurring event reoccurs on a weekly basis.
/// yearly - the recurring event reoccurs on an yearly basis.
/// yearlyNth - the recurring event reoccurs every N years.
/// interval - Number, specifies the interval between occurrences
/// of the recurrence.
/// The interval field works in conjunction with
/// the "recurrenceType" field to determine the cycle of the recurrence.
/// The maximum allowable value is 99 for weekly patterns and 999
/// for daily patterns.
/// The default value is 1.
/// For example, if the recurrenceType is set
/// to daily, and the "interval" is set to 3,
/// the recurrence will occur every third day.
/// startTime - Date, indicates the start time for the given
/// occurrence of the recurrence pattern.
/// endTime - Date, indicates the end time for the given
/// occurrence of the recurrence pattern.
/// patternStartDate - Date, indicates the start date of the
/// recurrence pattern.
/// patternEndDate - Date, indicates the end date of the
/// recurrence pattern.
/// This field is optional but must be coordinated
/// with other fields when setting up a recurrence pattern.
/// If this field or the "occurrences" field is set,
/// the pattern is considered to be finite, and the "noEndDate"
/// field is false.
/// If neither "patternEndDate" nor "occurrences" is set,
/// the pattern is considered infinite and "noEndDate" is true.
/// The "interval" field must be set before
/// setting "patternEndDate".
/// occurrences - Number, the number of occurrences for the
/// recurrence pattern. This field allows the definition of
/// a recurrence pattern that is only valid for the specified
/// number of subsequent occurrences.
/// For example, you can set this property to 10 for a formal
/// training course that will be held on the next ten Thursday
/// evenings. The default value is 0. This field must be
/// coordinated with other fields when setting up a recurrence pattern.
/// If the "patternEndDate" field or the "occurrences" field
/// is set, the pattern is considered to be finite and the
/// "noEndDate" field is false.
/// If neither "patternEndDate" nor "occurrences" is set,
/// the pattern is considered infinite and "noEndDate" is true.
/// instance - String, determines the week in a month in which
/// the event will occur. This field is only valid for recurrences of
/// the "monthlyNth" and "yearlyNth" types and allows the definition
/// of a recurrence pattern that is only valid for the Nth occurrence,
/// such as "the 2nd Sunday in March" pattern.
/// The default value is "first".
/// Possible values are:
/// first - the recurring event will occur on the specified
/// day or days of the first week in the month.
/// second - The recurring event will occur on the specified
/// day or days of the second week in the month.
/// third = - The recurring event will occur on the specified
/// day or days of the third week in the month.
/// fourth - The recurring event will occur on the specified
/// day or days of the fourth week in the month.
/// last - The recurring event will occur on the specified
/// day or days of the last week in the month.
/// dayOfWeekMask - String, contains set of values representing the mask
/// for week days on which the recurring event occurs.
/// Monthly and yearly patterns are only valid for a single day.
/// The default value is "none".
/// When the "RecurrenceType" field is set to "daily",
/// the "DayOfWeekMask" field can only be set to "everyDay";
/// setting the field to any other value will result in an exception.
/// When the "recurrenceType" field is set to
/// "workdays", the "dayOfWeekMask" field
/// can only be set to "workDays"; setting the field
/// to any other value will result in an exception.
/// When the "recurrenceType" field is set to
/// "weekly", the "dayOfWeekMask" field
/// cannot be set to "none"; doing so will result
/// in an exception being thrown.
/// When the recurrenceType" field is set to
/// "monthly" or "yearly" the "dayOfWeekMask" field is not applicable.
/// Possible values are:
/// none - no specific value; the actual value is obtained from
/// the root event object.
/// sunday - specifies Sunday.
/// monday - Specifies Monday.
/// tuesday - Specifies Tuesday.
/// wednesday - Specifies Wednesday.
/// thursday - Specifies Thursday.
/// friday - Specifies Friday.
/// saturday - Specifies Saturday.
/// weekendDays - Specifies Saturday and Sunday (or what ever days according
/// to the settings of the C1EventsCalendar).
/// workDays - Specifies work days (all days except weekend).
/// everyDay - Specifies every day of the week.
/// dayOfMonth - Number, the number of the day in its respective month on which
/// each occurrence will occur. Applicable only when the recurrenceType
/// field is set to "monthly" or "yearly".
/// The default value is 1.
/// monthOfYear - Number, indicates which month of the year is valid
/// for the specified recurrence pattern. Can be a number from 1 to 12.
/// This field is only valid for recurrence patterns whose recurrenceType"
/// field is set to "yearlyNth" or "yearly".
/// The default value is 1.
/// noEndDate - Boolean, indicates if the recurrence pattern is endless.
/// The default value is True. This field must be coordinated with
/// other fields when setting up a recurrence pattern. If the patternEndDate field
/// or the occurrences field is set, the pattern is considered
/// to be finite and the "noEndDate" field is false.
/// If neither patternEndDate nor occurrences is set,
/// the pattern is considered infinite and "noEndDate" is true.
/// exceptions - Array, holds the list of event object ids that
/// define the exceptions to that series of events.
/// This field is read-only.
/// removedOccurrences - Array, holds the list of event object's ids
/// removed from that series of events.
/// Calendar object fields:
/// id - String, unique calendar id, this field generated automatically;
/// name - String, calendar name;
/// location - String, location field;
/// description - String, calendar description;
/// color - String, calendar color;
/// tag - String, this field can be used to store custom information.
*/
(function (evcal) {
"use strict";
var $ = jQuery, widgetName = "wijevcal";
/////////////// utils:
function _toDayDate(dt) {
return new Date(dt.getFullYear(), dt.getMonth(), dt.getDate());
}
function _generateGuid() {
var result, i, j;
result = "";
for(j = 0; j < 32; j += 1) {
if(j === 8 || j === 12 || j === 16 || j === 20) {
result = result + "-";
}
i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
result = result + i;
}
return result;
}
/////////////// abstract data layer implementation
// (web sql database / amplify.store)
var database, databaseName = "C1EventsCalendarDB", databaseVer = "1.1", isAmplifyStoreUsed = false, amplifyTables;
function ensureTableCreated(tableName, fields, callback) {
/* ensureTableCreated("events",
"(id TEXT PRIMARY KEY, calendar TEXT, subject TEXT, location TEXT, " +
"start TIMESTAMP, end TIMESTAMP, description TEXT)");*/
if(isAmplifyStoreUsed) {
amplifyTables = amplify.store("wijevcal_tables1");
if(!amplifyTables) {
amplifyTables = {
};
}
//alert("isAmplifyStoreUsed?" + amplifyTables[tableName]);
if(!amplifyTables[tableName]) {
amplifyTables[tableName] = {
fields: fields
};
amplify.store("wijevcal_tables1", amplifyTables);
amplify.store("wijevcal_tbl_" + tableName, {
});
}
if(callback) {
callback();
}
} else if(database) {
database.transaction(function (tx) {
tx.executeSql("SELECT COUNT(*) FROM " + tableName, [], function () {
if(callback) {
callback();
}
}, function (tx, error) {
tx.executeSql("CREATE TABLE " + tableName + " " + fields, [], callback, callback);
});
});
}
}
function executeSql(sqlCommand, params, successHandler, errorHandler) {
/*
executeSql("SELECT * FROM events", []
executeSql("INSERT OR REPLACE INTO events " +
"(id, calendar, subject, location, start, end, description) " +
"VALUES(?,?,?,?,?,?,?);",
[o.id, o.calendar, o.subject, o.location,
o.start.getTime(), o.end.getTime(), o.description],
*/
var data = {
rowsAffected: 0,
rows: new Array()
}, o, i, selectRegexp, insertRegexp, deleteRegexp, match, tblName, tblDesc, tblData, k, paramsDesc, paramName, s, orConditions;
if(!params) {
params = [];
}
if(!data.rows["item"]) {
data.rows["item"] = function (i) {
return this[i];
};
}
if(isAmplifyStoreUsed) {
//executeSql("DELETE FROM calendars " + "WHERE name='" + name + "'",
//executeSql("DELETE FROM events WHERE id='" + id + "'", [],
try {
selectRegexp = new RegExp("(SELECT) *(.*) *FROM (\\w+)");
insertRegexp = new RegExp("(INSERT OR REPLACE|INSERT) *(.*) *INTO *(\\w*) *\\(([\\w|,| ]*)\\)");
deleteRegexp = new RegExp("(DELETE) *(.*) *FROM (\\w+) *(\\w*)WHERE (\\w+)='*([^']+)");
if(sqlCommand.match(insertRegexp)) {
match = insertRegexp.exec(sqlCommand);
if(match && match.length > 1) {
tblName = match[3];
tblDesc = amplifyTables[tblName];
tblData = amplify.store("wijevcal_tbl_" + tblName);
if(tblData) {
paramsDesc = match[4].split(",");
o = {
};
for(i = 0; i < paramsDesc.length; i += 1) {
if(paramsDesc[i]) {
if(i === 0) {
//qq: this will work only when first
// field is unique, elaborate:
tblData[params[i]] = o;
}
paramName = paramsDesc[i].replace(" ", "");
o[paramName] = params[i];
}
}
}
amplify.store("wijevcal_tbl_" + tblName, tblData);
}
} else if(sqlCommand.match(selectRegexp)) {
match = selectRegexp.exec(sqlCommand);
if(match && match.length > 1) {
tblName = match[3];
tblDesc = amplifyTables[tblName];
tblData = amplify.store("wijevcal_tbl_" + tblName);
if(tblData) {
s = sqlCommand.replace(selectRegexp, "");
if(s.toUpperCase().indexOf(" WHERE ") === 0) {
// WHERE found
s = s.substr(7);
orConditions = s.split(" OR ");
for(i = 0; i < orConditions.length; i += 1) {
orConditions[i] = orConditions[i].split("=");
s = orConditions[i][1];
if(s.indexOf("'") === 0) {
s = s.substring(1, s.length - 1);
orConditions[i][1] = s;
} else {
//qq: elaborate other types
orConditions[i][1] = parseFloat(s);
}
}
}
for(k in tblData) {
if(tblData.hasOwnProperty(k)) {
o = tblData[k];
if(o) {
if(orConditions) {
for(i = 0; i < orConditions.length; i += 1) {
if(o[orConditions[i][0]] === orConditions[i][1]) {
data.rows.push(o);
}
}
} else {
data.rows.push(o);
}
}
}
}
}
}
} else if(sqlCommand.match(deleteRegexp)) {
match = deleteRegexp.exec(sqlCommand);
if(match && match.length > 1) {
tblName = match[3];
tblDesc = amplifyTables[tblName];
tblData = amplify.store("wijevcal_tbl_" + tblName);
// match[5] key name (e.g. id)
// match[6] key value (e.g. ASD-AS@--FSAFS$%-!)
if(tblData) {
// qq: test for calendars
if(tblData[match[6]]) {
delete tblData[match[6]];
}
}
amplify.store("wijevcal_tbl_" + tblName, tblData);
}
}
if(successHandler) {
successHandler(data);
}
} catch (ex1) {
if(errorHandler) {
errorHandler(ex1);
}
}
} else {
if(!database) {
errorHandler("Local data storage not found.");
return;
}
database.transaction(function (tx) {
tx.executeSql(sqlCommand, params, function (tx, result) {
if(successHandler) {
successHandler(result);
}
}, function (tx, error) {
if(errorHandler) {
errorHandler(error.message);
}
return;
});
});
}
}
/////////////// <end of data layer
/** @widget */
var wijevcal = (function (_super) {
__extends(wijevcal, _super);
function wijevcal() {
_super.apply(this, arguments);
this._dynIdCounter = 0;
}
wijevcal.prototype._setOption = // handle option changes:
function (key, value) {
// when the setOption runs in chrome, because the web local storage is asynchronous,
// when set the event data to the event calender, the init data from local storage
// is getting the data, if this time set the value, the local storage data will override
// the set value.
// defined some deffered object
var self = this, newDfd = $.when.apply(this, self._defferObjs), val;
// when all deffered object has complete, fire the callbacks
newDfd.always(function () {
self._setOptionCallbacks.fire();
self._setOptionCallbacks.empty();
self._defferObjs = [];
});
// if the deffered object is not complete, put the setOption method to the callback
if(newDfd.state() === "pending") {
this._setOptionCallbacks.add(function () {
if($.isPlainObject(value)) {
val = $.extend(true, {
}, value);
} else if($.isArray(value)) {
val = [].concat(value);
} else {
val = value;
}
self._setOptionInternal(key, val);
});
} else// if the deffered object is complete, direct call the set option method.
{
this._setOptionInternal(key, value);
}
};
wijevcal.prototype._setOptionInternal = function (key, value) {
var o = this.options;
switch(key) {
case "dataSource":
o.dataSource = value;
this._bindDataView();
break;
case "eventsData":
o.eventsData = value;
o.appointments = value//remove deprecated appointments option?
;
this._onEventsDataChanged();
this._bindEvents();
break;
case "appointments":
o.eventsData = value;
o.appointments = value//remove deprecated appointments option?
;
this._onEventsDataChanged();
this._bindEvents();
break;
case "localization":
this._setLocalization(value);
break;
case "culture":
o.culture = value;
this.element.find(".wijmo-wijdatepager").wijdatepager("option", "culture", o.culture);
if(this._editEventDialog) {
this._editEventDialog.find(".wijmo-wijinput-date").wijinputdate("option", "culture", o.culture);
}
this.element.find(".wijmo-wijcalendar").wijcalendar("option", "culture", o.culture);
this._redrawActiveView()// fix for 23766
;
break;
case "disabled":
if(o.disabled !== value) {
o.disabled = value;
this._ensureDisabled();
}
break;
case "enableLogs":
o.enableLogs = value;
this._initLogPanel();
break;
case "selectedDate":
if(value) {
value = _toDayDate(value);
if(o.selectedDates[0].getTime() !== value.getTime()) {
o.selectedDates[0] = value;
this._onSelectedDatesChanged();
}
}
return;
case "selectedDates":
if(value) {
o.selectedDates = value;
this._onSelectedDatesChanged();
}
return;
case "statusBarVisible":
o.statusBarVisible = value;
this._initStatusbar();
this.invalidate();
return;
case "headerBarVisible":
o.headerBarVisible = value;
this._initHeaderbar();
this.invalidate();
return;
case "navigationBarVisible":
o.navigationBarVisible = value;
this._initNavigationbar();
this.invalidate();
return;
case "rightPaneVisible":
o.rightPaneVisible = value;
this._initRightPane();
this.invalidate();
return;
case "timeInterval":
if(o.timeInterval !== value) {
o.timeInterval = value;
this._redrawActiveView();
}
break;
case "timeIntervalHeight":
if(o.timeIntervalHeight !== value) {
o.timeIntervalHeight = value;
this._redrawActiveView();
}
break;
case "timeRulerInterval":
if(o.timeRulerInterval !== value) {
o.timeRulerInterval = value;
this._redrawActiveView();
}
break;
case "viewType":
if(o.viewType !== value) {
o.viewType = value;
this._onViewTypeChanged();
}
break;
default:
break;
}
$.wijmo.widget.prototype._setOption.apply(this, arguments);
};
wijevcal.prototype._setLocalization = function (value) {
this._destroyInternal();
this.options.localization = value;
this._create();
this._init();
};
wijevcal.prototype._ensureDisabled = function () {
var o = this.options;
if(o.disabled) {
this.element.addClass(o.wijCSS.stateDisabled);
try {
this.element.find(".wijmo-wijcalendar").wijcalendar("option", "disabled", true);
this.element.find(".wijmo-wijsuperpanel").wijsuperpanel("option", "disabled", true);
this.element.find(".wijmo-wijdatepager").wijdatepager("option", "disabled", true);
if($().buttonset) {
this.element.find(".ui-buttonset").buttonset("option", "disabled", true);
}
this.element.find(".wijmo-wijev-today.ui-button").button("option", "disabled", true);
//this.element.find(".ui-button.ui-widget").button("option", "disabled", true);
} catch (ex) {
this.log(ex, "error");
//fix for:
//Error: cannot call methods on button prior to initialization; attempted to call method 'option'
}
this._unbindEvents();
} else {
this.element.removeClass(o.wijCSS.stateDisabled);
try {
this.element.find(".wijmo-wijcalendar").wijcalendar("option", "disabled", false);
this.element.find(".wijmo-wijsuperpanel").wijsuperpanel("option", "disabled", false);
this.element.find(".wijmo-wijdatepager").wijdatepager("option", "disabled", false);
if($().buttonset) {
this.element.find(".ui-buttonset").buttonset("option", "disabled", false);
}
this.element.find(".wijmo-wijev-today.ui-button").button("option", "disabled", false);
//this.element.find(".ui-button").button("option", "disabled", false);
} catch (ex) {
this.log(ex, "error");
//fix for:
//Error: cannot call methods on button prior to initialization; attempted to call method 'option'
}
this._bindEvents();
this._updateTitleText();
}
};
wijevcal.prototype._onViewTypeChanged = function () {
this._renderActiveView();
this._updateTitleText();
this._trigger("viewTypeChanged", null, this.options.viewType);
this.element.find(".wijmo-wijev-datepager").wijdatepager("option", "viewType", this.options.viewType);
};
wijevcal.prototype._onSelectedDatesChanged = function () {
var o = this.options;
o.selectedDate = o.selectedDates[0];
this.element.find(".wijmo-wijev-datepager").wijdatepager("option", "selectedDate", o.selectedDate);
this._trigger("selectedDatesChanged", null, {
selectedDates: o.selectedDates
});
this._renderActiveView();
this._updateTitleText();
};
wijevcal.prototype._updateHeaderTitleText = //
function () {
var o = this.options, fmt = o.titleFormat, viewStart = o.selectedDates[0], viewEnd = o.selectedDates[o.selectedDates.length - 1];
if(fmt[o.viewType]) {
fmt = fmt[o.viewType];
} else if(fmt[o.viewType] === false) {
this.element.find(".wijmo-wijev-view .wijmo-wijev-header-title").hide();
return;
} else {
fmt = fmt.toString();
}
if(o.viewType === "list") {
viewEnd = this._addDays(viewStart, 14);
}
this.element.find(".wijmo-wijev-view .wijmo-wijev-header-title").show().html(this._formatString(fmt, viewStart, viewEnd));
};
wijevcal.prototype._updateTitleText = function () {
var o = this.options, viewStart = o.selectedDates[0], viewEnd = o.selectedDates[o.selectedDates.length - 1], todayDate = new Date(), isTodayShown = false;
isTodayShown = this._compareDayDates(viewStart, todayDate) === 0 || (viewStart < todayDate && viewEnd > todayDate);
if($.mobile == null) {
this.element.find(".wijmo-wijev-navigationbar .wijmo-wijev-today").button("option", "disabled", isTodayShown);
}
this._updateHeaderTitleText();
};
wijevcal.prototype.localizeString = /** Get the localized string by key
* @param {string} key The key of the localized string.
* @param {string} defaultValue The default value of the localized string.
* @returns {string} The localized string.
*/
function (key, defaultValue) {
var o = this.options;
if(o.localization && o.localization[key]) {
return o.localization[key];
}
return defaultValue;
//("buttonToday", "today")
};
wijevcal.prototype._create = function () {
// enable touch support:
if(window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
this._defferObjs = [];
this._chromeLoadDataDeffer = $.Deferred();
this._defferObjs.push(this._chromeLoadDataDeffer);
this._setOptionCallbacks = $.Callbacks("once");
// Add for parse date options for jUICE. D.H
if($.isFunction(window["wijmoASPNetParseOptions"])) {
window["wijmoASPNetParseOptions"](this.options);
}
var navigationbar, toolsBar, o = this.options;
// fix problem with array options:
if(!o.colors) {
o.colors = [
"red",
"darkorchid",
"green",
"blue",
"cornflowerblue",
"yellow",
"bronze"
];
}
if(!this.wijevcalnamespacekey) {
this.wijevcalnamespacekey = "wijevcal" + new Date().getTime();
}
if(!this.element[0].id) {
this.element[0].id = "wijevcal_dynid_" + new Date().getTime();
}
this._uidPref = this.element[0].id + "evcdynid";
this.element.addClass("wijmo-wijevcal wijmo-wijev " + o.wijCSS.widget + " ui-helper-reset " + o.wijCSS.stateDefault);
// ui-helper-clearfix ui-corner-all
//<fieldset data-role="controlgroup" data-type="horizontal" >
$("<div class=\"wijmo-wijev-headerbar ui-widget-header ui-corner-top\">" + "<fieldset class=\"wijmo-wijev-tools\">" + "<input id=\"" + this._uidPref + "_daybtn\" name=\"viewselection\"" + " type=\"radio\" class=\"wijmo-wijev-day\" />" + "<label for=\"" + this._uidPref + "_daybtn\">" + this.localizeString("buttonDayView", "Day") + "</label>" + "<input id=\"" + this._uidPref + "_weekbtn\" name=\"viewselection\"" + " type=\"radio\" class=\"wijmo-wijev-week\" />" + "<label for=\"" + this._uidPref + "_weekbtn\">" + this.localizeString("buttonWeekView", "Week") + "</label>" + "<input id=\"" + this._uidPref + "_monthbtn\" name=\"viewselection\"" + " type=\"radio\" class=\"wijmo-wijev-month\" />" + "<label for=\"" + this._uidPref + "_monthbtn\">" + this.localizeString("buttonMonthView", "Month") + "</label>" + "<input id=\"" + this._uidPref + "_listbtn\" name=\"viewselection\"" + " type=\"radio\" class=\"wijmo-wijev-list\" />" + "<label for=\"" + this._uidPref + "_listbtn\">" + this.localizeString("buttonListView", "List") + "</label>" + "</fieldset>" + "</div>").appendTo(this.element);
$("<div class=\"wijmo-wijev-view-container\">" + "<div class=\"wijmo-wijev-leftpane wijmo-wijev-viewdetails " + o.wijCSS.content + " wijmo-wijev-day-details\">" + "<div class=\"wijmo-wijev-leftpane-inner\">" + "<div class=\"wijmo-wijev-daycalendar\"></div>" + "<div class=\"wijmo-wijev-monthday-container\">" + "<div class=\"wijmo-wijev-monthday-label\">...</div>" + "<div class=\"wijmo-wijev-fulldate-label\">" + this.localizeString("activityLoading", "Loading...") + "</div>" + "<div class=\"wijmo-wijev-year-label\">...</div>" + "</div>" + "<div class=\"wijmo-wijev-agenda-container " + o.wijCSS.content + " " + o.wijCSS.cornerAll + " ui-helper-clearfix" + "\"></div>" + "</div>" + "</div>" + "<div class=\"wijmo-wijev-leftpane wijmo-wijev-viewdetails " + o.wijCSS.content + " wijmo-wijev-list-details\">" + "<div class=\"wijmo-wijev-leftpane-inner\">" + "<div class=\"wijmo-wijev-agenda-container " + o.wijCSS.content + " " + o.wijCSS.cornerAll + " ui-helper-clearfix\"> " + "</div>" + "</div>" + "</div>" + "<div class=\"wijmo-wijev-rightpane\">" + " </div>" + "</div>").appendTo(this.element);
$("<div class=\"wijmo-wijev-loading-modal-frame\"></div>" + "<div class=\"wijmo-wijev-loading\">" + "<div class=\"wijmo-wijev-loading-text\">" + this.localizeString("activityLoading", "Loading...") + "</div></div>").appendTo(this.element);
$("<div class=\"wijmo-wijev-navigationbar" + " ui-widget-header ui-corner-bottom ui-helper-clearfix\">" + "<a class=\"wijmo-wijev-today\">" + this.localizeString("buttonToday", "today") + "</a>" + "<div class=\"wijmo-wijev-datepager\">" + "</div>" + "</div>").appendTo(this.element);
//
$("<div class=\"wijmo-wijev-statusbar ui-widget-header ui-corner-bottom\">" + "</div>").appendTo(this.element);
navigationbar = this.element.find(".wijmo-wijev-navigationbar");
toolsBar = this.element.find(".wijmo-wijev-headerbar .wijmo-wijev-tools");
navigationbar.find(".wijmo-wijev-today").button({
text: this.localizeString("buttonToday", "today")
}).click($.proxy(this._onTodayClick, this));
this.element.find(".wijmo-wijev-datepager").wijdatepager({
selectedDate: o.selectedDate,
localization: o.datePagerLocalization,
culture: o.culture,
viewType: o.viewType,
nextTooltip: this.localizeString("navigatorBarNextTooltip", "right"),
prevTooltip: this.localizeString("navigatorBarPrevTooltip", "left"),
firstDayOfWeek: o.firstDayOfWeek,
selectedDateChanged: $.proxy(function (e, args) {
this.goToDate(args.selectedDate);
}, this)
});
if($.mobile == null) {
toolsBar.find(".wijmo-wijev-day").button();
toolsBar.find(".wijmo-wijev-week").button();
toolsBar.find(".wijmo-wijev-month").button();
toolsBar.find(".wijmo-wijev-list").button();
toolsBar.buttonset();
} else {
toolsBar.attr("data-role", "controlgroup");
toolsBar.attr("data-type", "horizontal");
//toolsBar.attr("data-mini", "true");
toolsBar.parent().trigger("create");
toolsBar.controlgroup("refresh");
}
toolsBar.find(".wijmo-wijev-day").click($.proxy(this._onDayViewClick, this));
toolsBar.find(".wijmo-wijev-week").click($.proxy(this._onWeekViewClick, this));
toolsBar.find(".wijmo-wijev-month").click($.proxy(this._onMonthViewClick, this));
toolsBar.find(".wijmo-wijev-list").click($.proxy(this._onListViewClick, this));
//
this.showLoadingLabel();
};
wijevcal.prototype.showLoadingLabel = /** @ignore*/
function (text, isModal) {
if(text === false) {
this.element.find(".wijmo-wijev-loading-text").hide();
} else {
this.element.find(".wijmo-wijev-loading-text").show();
if(!text) {
text = this.localizeString("activityLoading", "Loading...");
}
}
if(isModal === undefined || isModal === true) {
this.element.find(".wijmo-wijev-loading-modal-frame").show();
}
this.element.find(".wijmo-wijev-loading").show();
this.element.find(".wijmo-wijev-loading-text").html(text);
};
wijevcal.prototype.hideLoadingLabel = /** hide the loading label*/
function () {
this.element.find(".wijmo-wijev-loading-modal-frame").hide();
this.element.find(".wijmo-wijev-loading").hide();
};
wijevcal.prototype._init = /* initialization code > */
function () {
var o = this.options;
if(o.selectedDates && o.selectedDates.length > 0) {
o.selectedDate = o.selectedDates[0] = _toDayDate(o.selectedDates[0]);
} else if(o.selectedDate) {
o.selectedDate = _toDayDate(o.selectedDate);
if(!o.selectedDates) {
o.selectedDates = [];
}
o.selectedDates[0] = o.selectedDate;
} else {
o.selectedDate = _toDayDate(new Date());
o.selectedDates = [
o.selectedDate
];
}
if(o.disabled) {
this.element.addClass(o.wijCSS.stateDisabled);
}
this._initHeaderbar();
this._initNavigationbar();
this._initStatusbar();
this._initRightPane();
if(o.fullScreen) {
this._onFullScreenModeChanged(o.fullScreen);
}
this._initLogPanel();
this._initLocalDataStorage()// _loadData called here
;
this.element.ajaxError(jQuery.proxy(this._onAjaxError, this));
$(window).bind("resize." + this.wijevcalnamespacekey, $.proxy(this._onWindowResize, this));
this._renderActiveView()// invalidate called here
;
//this._bindEvents();this._updateTitleText(); called here:
this._bindDataView();
};
wijevcal.prototype._onFullScreenModeChanged = function (isFullscreen) {
//qq:todo fullscreenmode
};
wijevcal.prototype._isDataViewLoaded = // wijdataview implementation
function (dv) {
return dv && (dv.isLoaded() || (dv.count() > 0));
};
wijevcal.prototype._isDataview = function (dv) {
if(dv && typeof (dv) === "object" && !$.isArray(dv)) {
return true;
}
};
wijevcal.prototype._getDataViewInst = function () {
return this.element.data("wijdataview");
};
wijevcal.prototype._bindDataView = function () {
var o = this.options, dataSource = o.dataSource, dataSource, self = this;
if(!dataSource && this._getDataViewInst()) {
dataSource = this._getDataViewInst();
dataSource = o.dataSource = dataSource;
}
if(dataSource && this._isDataview(dataSource)) {
if(this._isDataViewLoaded(dataSource)) {
this._dataView = dataSource;
this._setOption("eventsData", dataSource.toArray());
} else {
dataSource.element.bind("dataloaded", function () {
self._dataView = dataSource;
self._setOption("eventsData", dataSource.toArray());
});
/*
//qq:?
.bind("datachange", function (e, args) {
if (args && args.length && args[0].changeType !== "reset") {
self.dataList = dataSource.dataView.toArray();
self._bindData();
self.redraw();
}
});*/
}
} else {
this._dataView = null;
}
/*
qq:?
if (!self._needloaded) {
self._bindData();
}*/
};
wijevcal.prototype._initLocalDataStorage = function () {
/* local data storage initialization >> */
try {
isAmplifyStoreUsed = false;
if(window["amplify"] && window["amplify"].store) {
try {
amplifyTables = amplify.store("wijevcal_tables1");
isAmplifyStoreUsed = true;
this.log("Using amplify.store for the local data storage");
} catch (amplex) {
this.log("amplify.store exception:" + amplex);
// attempt to load data using web service or custom methods
this._loadData();
return;
}//amplify.store("key", "test-1")
} else if(window["openDatabase"]) {
try {
database = window["openDatabase"](databaseName, databaseVer, "Wijmo Events Calendar Offline DB", 200000);
} catch (ex) {
this.log("web sql database error: " + ex);
// attempt to load data using web service or custom methods
this._loadData();
return;
}
if(!database) {
this.log("Failed to open the database on disk." + " This is probably because the version was bad or" + " there is not enough space left in this domain's quota");
// attempt to load data using web service or custom methods
this._loadData();
return;
}
this.log("Using Web SQL Database for the local data storage.");
} else {
this.log(this.localizeString("logCouldntOpenLocalStorage", "Couldn't open built-in local data storage." + " Please, add amplify.store references."));
// attempt to load data using web service or custom methods
this._loadData();
return;
}
// Create tables:
ensureTableCreated("calendars", "(id TEXT PRIMARY KEY, name TEXT, location TEXT, description TEXT, " + "color TEXT, tag TEXT)");
var tableDeffered = $.Deferred(), self = this;
this._defferObjs.push(tableDeffered);
ensureTableCreated("events", "(id TEXT PRIMARY KEY, calendar TEXT, subject TEXT, location TEXT, " + "start TIMESTAMP, end TIMESTAMP, description TEXT, color TEXT, " + "allday INTEGER, properties TEXT, tag TEXT)", function () {
self._loadData();
tableDeffered.resolve();
});
//();
/*
TEXT
NUMERIC
INTEGER
REAL
NONE
*/
} catch (err) {
this.log("local datastorage initialization error:" + err);
}/* << end of local data storage initialization */
};
wijevcal.prototype._initStatusbar = function () {
var statusbar = this.element.find(".wijmo-wijev-statusbar");
if(!this.options.statusBarVisible) {
statusbar.hide();
return;
} else {
statusbar.show();
}
if(this.statusbarEventsAdded) {
return true;
}
//statusbar.addClass("ui-widget-header");
this.statusbarEventsAdded = true;
};
wijevcal.prototype._initHeaderbar = function () {
var headerbar = this.element.find(".wijmo-wijev-headerbar");
if(!this.options.headerBarVisible) {
headerbar.hide();
return;
} else {
headerbar.show();
}
};
wijevcal.prototype._initNavigationbar = function () {
var navigationbar = this.element.find(".wijmo-wijev-navigationbar");
if(!this.options.navigationBarVisible) {
navigationbar.hide();
return;
} else {
navigationbar.show();
}
};
wijevcal.prototype._initRightPane = //
function () {
var rightpane = this.element.find(".wijmo-wijev-rightpane");
if(!this.options.rightPaneVisible) {
rightpane.hide();
return;
} else {
rightpane.show();
}
};
wijevcal.prototype._initLogPanel = function () {
if(this.options.enableLogs) {
this._createLogPanel();
this.log = this._log;
} else {
if(this.logDialog) {
this.logDialog.wijdialog("close");
}
this.log = function () {
};
}
};
wijevcal.prototype._handleServerError = /* < end of initialization code*/
function (answer) {
if(answer && answer.toString().indexOf("error:") === 0) {
this.status(answer.toString(), "error");
return true;
}
return false;
};
wijevcal.prototype._loadData = function () {
var o = this.options, self = this, i, count, cal, appt, calendarsById, eventsDataById, query, loadCalendarsCallback, loadEventsCallback, errorCallback, calendarDeffered, eventDeffered, needLoadEventsData;
//successCallback
this.showLoadingLabel();
errorCallback = function (e) {
// fixed an issue that if the can't support the local storage and not set the dataStorage, webServiceUrl,
// when user set the eventsData in the option, the widget will not show the events data.
if(e === "Local data storage not found.") {
needLoadEventsData = true;
}
self.hideLoadingLabel();
};
o.calendars = [];
calendarsById = this._calendarsById = {
};
loadCalendarsCallback = function (calendars) {
if(!calendars) {
return;
}
if(typeof calendars === "string") {
if(self._handleServerError(calendars)) {
errorCallback(calendars);
return;
}
try {
calendars = self._jsonParse(calendars);
} catch (ex) {
self.status("Unable to parse received calendars data. " + ex, "error");
return;
}
}
if(calendars.calendars && calendars.calendars.length) {
calendars = calendars.calendars;
}
for(i = 0; i < calendars.length; i += 1) {
cal = self._cloneObj(calendars[i]);
cal.prevData = self._cloneObj(cal);
o.calendars.push(cal);
calendarsById[cal.id] = cal;
}
self._onCalendarsChanged();
};
if(o.dataStorage.loadCalendars) {
o.dataStorage.loadCalendars(loadCalendarsCallback, errorCallback);
} else if(o.webServiceUrl) {
$.getJSON(o.webServiceUrl + "?clientId=" + this.element[0].id + "&command=loadCalendars" + "&calendars=" + o.calendars, loadCalendarsCallback);
} else {
executeSql("SELECT * FROM calendars", [], function (data) {
for(i = 0 , count = data.rows.length; i < count; i += 1) {
cal = self._cloneObj(data.rows.item(i));
cal.prevData = self._cloneObj(cal);
o.calendars.push(cal);
calendarsById[cal.id] = cal;
}
self._onCalendarsChanged();
}, errorCallback);
}
if(this._dataView) {
o.eventsData = this._dataView.toArray();
} else {
//if init set the event data, when run it browser, the data will be cleared by the below code
//o.eventsData = [];
}
if(!this._eventsDataById) {
eventsDataById = this._eventsDataById = {
};
} else {
eventsDataById = this._eventsDataById;
}
loadEventsCallback = function (events) {
if(!events) {
return;
}
if(typeof events === "string") {
if(self._handleServerError(events)) {
errorCallback(events);
return;
}
try {
events = self._jsonParse(events);
} catch (ex) {
self.log("Unable to parse received calendars data. " + ex);
return;
}
}
if(events.events && events.events.length) {
events = events.events;
}
for(i = 0; i < events.length; i += 1) {
appt = self._readEventData(events[i]);
self._storeEventWithSort(appt);
}
self._onEventsDataChanged();
self._onInitialized();
};
if(o.dataStorage.loadEvents) {
o.dataStorage.loadEvents(o.visibleCalendars, loadEventsCallback, errorCallback);
self._chromeLoadDataDeffer.resolve();
} else if(o.webServiceUrl) {
$.ajax({
url: o.webServiceUrl + "?clientId=" + this.element[0].id + "&command=loadEvents×tamp=" + new Date().getTime(),
dataType: "text",
cache: /*dataType: "json",*/
false,
contentType: "application/json; charset=utf-8",
type: "POST",
success: //data: "jsonData=" +
// this._jsonStringify({ visibleCalendars: o.visibleCalendars }),
loadEventsCallback,
error: errorCallback
});
self._chromeLoadDataDeffer.resolve();
} else {
if(this._dataView) {
this._onInitialized();
return;
}
query = "SELECT * FROM events where ";
for(i = 0; i < o.visibleCalendars.length; i += 1) {
if(i > 0) {
query += " OR ";
}
query += "calendar='" + o.visibleCalendars[i] + "'";
}
executeSql(query, [], function (data) {
for(i = 0 , count = data.rows.length; i < count; i += 1) {
appt = self._readEventData(data.rows.item(i));
self._storeEventWithSort(appt);
}
self._onEventsDataChanged();
self._onInitialized();
self._chromeLoadDataDeffer.resolve();
}, function () {
errorCallback.apply(this, arguments);
// if can't get the data from local storage, init the event by the option's data.
if(needLoadEventsData) {
self._onEventsDataChanged();
self._onInitialized();
}
self._chromeLoadDataDeffer.resolve();
});
}
};
wijevcal.prototype._onInitialized = function () {
this._ensureDisabled();
this.hideLoadingLabel();
this._trigger("initialized");
};
wijevcal.prototype._readEventData = function (data) {
var appt = this._cloneObj(data);
appt.start = new Date(appt["start"]);
appt.end = new Date(appt["end"]);
if(typeof appt.allday === "string") {
if(appt["allday"] === "false") {
appt.allday = false;
}
if(appt["allday"] === "true") {
appt.allday = true;
}
}
if(appt.start.getTime() >= appt.end.getTime()) {
// duration can not be 0.
appt.end = this._addMinutes(appt.start, this.options.timeInterval);
}
this._deSerializeProperties(appt["properties"], appt);
appt.prevData = this._cloneObj(appt);
return appt;
};
wijevcal.prototype._prepareEventsForView = function () {
this._eventsView = this.getOccurrences();
};
wijevcal.prototype._cloneObj = function (o1) {
var o2 = {
}, k;
for(k in o1) {
if(o1.hasOwnProperty(k)) {
o2[k] = o1[k];
}
}
return o2;
};
wijevcal.prototype._onDayViewClick = function () {
var o = this.options;
if(o.viewType !== "day") {
o.viewType = "day";
this._onViewTypeChanged();
}
o.selectedDates = [
o.selectedDate
];
this._onSelectedDatesChanged();
};
wijevcal.prototype._onWeekViewClick = function () {
var o = this.options, startDt, dt, i;
if(o.viewType !== "week") {
o.viewType = "week";
this._onViewTypeChanged();
}
startDt = o.selectedDate;
i = o.firstDayOfWeek - startDt.getDay();
if(Math.abs(i) > 6) {
i = startDt.getDay() - o.firstDayOfWeek;
}
startDt = this._addDays(startDt, i);
o.selectedDates = [];
for(i = 0; i < 7; i += 1) {
dt = this._addDays(startDt, i);
o.selectedDates.push(dt);
}
this._onSelectedDatesChanged();
};
wijevcal.prototype._onMonthViewClick = function () {
var o = this.options;
if(o.viewType !== "month") {
o.viewType = "month";
this._onViewTypeChanged();
}
};
wijevcal.prototype._onListViewClick = function () {
var o = this.options;
if(o.viewType !== "list") {
o.viewType = "list";
this._onViewTypeChanged();
}
o.selectedDates = [
o.selectedDate
];
this._onSelectedDatesChanged();
};
wijevcal.prototype._ensureEditCalendarDialogCreated = // UI behavior
/* dialogs */
function () {
var o = this.options, dialogContent, buttonsHash = {
};
if(!this._editCalendarDialog) {
dialogContent = o.editCalendarTemplate;
if(!dialogContent) {
dialogContent = "<p><label>" + this.localizeString("labelCalendarName", "Calendar name") + "</label>" + "<input type=\"text\" class=\"wijmo-wijev-name\" value=\"\"> " + "<div class=\"wijmo-wijev-color-button\">" + "<div class=\"wijmo-wijev-color ui-wijmo-wijev-event-color-default\"> </div>" + "</div>" + "</p>" + "<p><label>" + this.localizeString("labelLocation", "Location") + "</label>" + "<input type=\"text\" class=\"wijmo-wijev-location\" value=\"\"></p>" + "<p><label>" + this.localizeString("labelDescription", "Description") + "</label><textarea class=\"wijmo-wijev-description\" /></p>";
}
this._editCalendarDialog = $("<div class=\"wijmo-wijev-editcalendar-dialog\">" + dialogContent + "</div>");
this.element.append(this._editCalendarDialog);
buttonsHash[this.localizeString("buttonSave", "Save")] = $.proxy(function () {
try {
var cal = this._validateAndReadCalendarDialogFields(this._editCalendarDialog);
if(cal.prevData) {
this.updateCalendar(cal);
} else {
this.addCalendar(cal);
}
this._editCalendarDialog.wijdialog("close");
} catch (ex) {
alert(ex);
}
}, this);
this._editCalendarDialog.wijdialog({
autoOpen: true,
height: 340,
width: 440,
modal: true,
title: this.localizeString("titleEditCalendar", "Edit calendar"),
buttons: buttonsHash,
captionButtons: {
pin: {
visible: false
},
refresh: {
visible: false
},
toggle: {
visible: false
},
minimize: {
visible: false
},
maximize: {
visible: false
}
}
});
/*,
open: $.proxy(function () {
}, this)*/
this._editCalendarDialog.find(".wijmo-wijev-name, .wijmo-wijev-location, .wijmo-wijev-description").wijtextbox();
//
this._editCalendarDialog.find(".wijmo-wijev-color-button").button({
icons: {
primary: "ui-icon-triangle-1-s"
}
}).click($.proxy(this._onColorButtonClick, {
dlg: this._editCalendarDialog,
self: this
}));
}
};
wijevcal.prototype._ensureEditEventDialogCreated = function () {
var o = this.options, dialogTemplate;
if(!this._editEventDialog) {
dialogTemplate = this.options.editEventDialogTemplate;
if(!dialogTemplate) {
dialogTemplate = "<div class=\"" + "wijmo-wijev-event-dialog " + this.options.wijCSS.content + " " + o.wijCSS.cornerAll + "\">" + "<ul class=\"wijmo-wijev-brief-content\">" + "<li><label>" + this.localizeString("labelName", "name") + "</label>" + "<input type=\"text\" name=\"subject\" class=\"wijmo-wijev-subject\" value=\"\">" + "<div class=\"wijmo-wijev-color-button\">" + "<div class=\"wijmo-wijev-color ui-wijmo-wijev-event-color-default\"> </div>" + "</div>" + "</li>" + "<li><label for=\"" + this._uidPref + "_alldaybtn\">" + this.localizeString("labelAllDay", "all-day") + "</label>" + "<input type=\"checkbox\" class=\"wijmo-wijev-allday\" id=\"" + this._uidPref + "_alldaybtn\" />" + "</li>" + "<li><label>" + this.localizeString("labelStarts", "Starts") + "</label>" + "<input type=\"text\" class=\"wijmo-wijev-start\" value=\"\">" + "<input type=\"text\" class=\"wijmo-wijev-start-time\" value=\"\">" + "</li>" + "<li><label>" + this.localizeString("labelEnds", "Ends") + "</label>" + "<input type=\"text\" class=\"wijmo-wijev-end\" value=\"\">" + "<input type=\"text\" class=\"wijmo-wijev-end-time\" value=\"\">" + "</li>" + "</ul>" + "<ul class=\"wijmo-wijev-detailed-content " + o.wijCSS.cornerAll + "\">" + "<li><label>" + this.localizeString("labelLocation", "Location") + "</label>" + "<input type=\"text\" class=\"wijmo-wijev-location\" value=\"\"></li>" + "<li><label>" + this.localizeString("labelRepeat", "Repeat") + "</label>" + "<select class=\"wijmo-wijev-repeat\">" + "<option value=\"none\">" + this.localizeString("repeatNone", "None") + "</option>" + "<option value=\"daily\">" + this.localizeString("repeatDaily", "Every Day") + "</option>" + "<option value=\"workdays\">" + this.localizeString("repeatWorkDays", "Work days") + "</option>" + "<option value=\"weekly\">" + this.localizeString("repeatWeekly", "Every Week") + "</option>" + "<option value=\"monthly\">" + this.localizeString("repeatMonthly", "Every Month") + "</option>" + "<option value=\"yearly\">" + this.localizeString("repeatYearly", "Every Year") + "</option>" + /*"<option value=\"custom\">Custom...</option>" +*/
"</select></li>" + "<li><label>" + this.localizeString("labelCalendar", "Calendar") + "</label>" + "<select class=\"wijmo-wijev-calendar\"></select></li>" + "<li class=\"wijmo-wijev-description-item\"><label>" + this.localizeString("labelDescription", "Description") + "</label>" + "<textarea class=\"wijmo-wijev-description\" /></li>" + "</ul>" + "<div class=\"footer\">" + "<a href=\"#\" class=\"wijmo-wijev-delete\">" + this.localizeString("buttonDelete", "Delete") + "</a>" + "<a href=\"#\" class=\"wijmo-wijev-save\">" + this.localizeString("buttonOK", "OK") + "</a>" + "<a href=\"#\" class=\"wijmo-wijev-cancel\">" + this.localizeString("buttonCancel", "Cancel") + "</a>" + "</div>" + "<div class=\"wijmo-wijev-angle\"></div>" + "</div>";
}
this._editEventDialog = $(dialogTemplate);
this.element.append(this._editEventDialog);
//color
this._editEventDialog.find(".wijmo-wijev-color-button").button({
icons: {
primary: "ui-icon-triangle-1-s"
}
}).click($.proxy(this._onColorButtonClick, {
dlg: this._editEventDialog,
self: this
}));
/*
this._editEventDialog.find(".wijmo-wijev-color-arrow").button({
icons: { primary: "ui-icon-triangle-1-s" },
text: false
}).click($.proxy(this._onColorButtonClick, this)).parent().buttonset();
*/
//delete
this._editEventDialog.find(".wijmo-wijev-delete").button().click($.proxy(function () {
this.deleteEvent(this._editEventDialog.appt);
this._editEventDialog.wijpopup("hide");
}, this));
//close
this._editEventDialog.find(".wijmo-wijev-cancel").button().click($.proxy(function (ev) {
this._editEventDialog.wijpopup("hide");
ev.preventDefault();
}, this));
this._editEventDialog.find(".wijmo-wijev-start").width(114).wijinputdate({
culture: this.options.culture,
titleFormat: this.localizeString("calendarTitleFormat", "MMMM yyyy"),
toolTipFormat: this.localizeString("calendarToolTipFormat", "dddd, MMMM dd, yyyy"),
nextTooltip: this.localizeString("calendarNextTooltip", "Next"),
prevTooltip: this.localizeString("calendarPrevTooltip", "Previous"),
showTrigger: true,
dateFormat: "d",
dateChanged: $.proxy(function (e, args) {
var endDt = this._editEventDialog.find(".wijmo-wijev-end").wijinputdate("option", "date");
if(args.date > endDt) {
this._editEventDialog.find(".wijmo-wijev-end").wijinputdate("option", "date", args.date);
}
}, this)
});
this._editEventDialog.find(".wijmo-wijev-start-time").width(80).wijinputdate({
culture: this.options.culture,
titleFormat: this.localizeString("calendarTitleFormat", "MMMM yyyy"),
toolTipFormat: this.localizeString("calendarToolTipFormat", "dddd, MMMM dd, yyyy"),
nextTooltip: this.localizeString("calendarNextTooltip", "Next"),
prevTooltip: this.localizeString("calendarPrevTooltip", "Previous"),
dateFormat: "t",
dateChanged: $.proxy(function (e, args) {
var endDt = this._editEventDialog.find(".wijmo-wijev-end-time").wijinputdate("option", "date"), startDate = this._editEventDialog.find(".wijmo-wijev-start").wijinputdate("option", "date");
if(args.date.getDate() !== startDate.getDate()) {
args.date.setDate(startDate.getDate());
this._editEventDialog.find(".wijmo-wijev-start-time").wijinputdate("option", "date", args.date);
}
if(args.date > endDt) {
this._editEventDialog.find(".wijmo-wijev-end-time").wijinputdate("option", "date", args.date);
}
}, this)
});
this._editEventDialog.find(".wijmo-wijev-end").width(114).wijinputdate({
culture: this.options.culture,
titleFormat: this.localizeString("calendarTitleFormat", "MMMM yyyy"),
toolTipFormat: this.localizeString("calendarToolTipFormat", "dddd, MMMM dd, yyyy"),
nextTooltip: this.localizeString("calendarNextTooltip", "Next"),
prevTooltip: this.localizeString("calendarPrevTooltip", "Previous"),
showTrigger: true,
dateFormat: "d",
dateChanged: $.proxy(function (e, args) {
var startDt = this._editEventDialog.find(".wijmo-wijev-start").wijinputdate("option", "date");
if(args.date < startDt) {
this._editEventDialog.find(".wijmo-wijev-start").wijinputdate("option", "date", args.date);
}
}, this)
});
this._editEventDialog.find(".wijmo-wijev-end-time").width(80).wijinputdate({
culture: this.options.culture,
titleFormat: this.localizeString("calendarTitleFormat", "MMMM yyyy"),
toolTipFormat: this.localizeString("calendarToolTipFormat", "dddd, MMMM dd, yyyy"),
nextTooltip: this.localizeString("calendarNextTooltip", "Next"),
prevTooltip: this.localizeString("calendarPrevTooltip", "Previous"),
dateFormat: "t"
});
/*,
dateChanged: $.proxy(function (e, args) {
var startDt = this._editEventDialog
.find(".wijmo-wijev-start-time")
.wijinputdate("option", "date"),
endDate = this._editEventDialog
.find(".wijmo-wijev-end")
.wijinputdate("option", "date");
if (args.date.getDate() !== endDate.getDate()) {
args.date.setDate(endDate.getDate());
this._editEventDialog
.find(".wijmo-wijev-end-time")
.wijinputdate("option", "date", args.date);
}
if (args.date < startDt) {
this._editEventDialog
.find(".wijmo-wijev-start-time")
.wijinputdate("option", "date", args.date);
}
}, this)*/
this._editEventDialog.find(".wijmo-wijev-allday").wijcheckbox().change($.proxy(this._eventDialogEnsureTimePartState, this));
this._editEventDialog.find(".wijmo-wijev-subject,.wijmo-wijev-location,.wijmo-wijev-description").wijtextbox();
// save:
this._editEventDialog.find(".wijmo-wijev-save").button().click($.proxy(function (e) {
try {
var appt = this._validateAndReadApptDialogFields(this._editEventDialog);
if(appt.prevData) {
this.updateEvent(appt);
} else {
this.addEvent(appt);
}
this._editEventDialog.wijpopup("hide");
} catch (ex) {
alert(ex);
}
}, this));
//////////
this._editEventDialog.wijpopup({
autoHide: true,
hiding: /*qq*/
$.proxy(function (e) {
if(this._colorMenu) {
this._colorMenu.wijpopup("hide");
}
this.element.find(".wijmo-wijev-dayview .ui-selected").removeClass("ui-selected");
}, this),
shown: $.proxy(function (e) {
var self = this;
if(!this._dropDownInitialized) {
// fix for wijdropdown,
// create widget when select element is shown.
this._editEventDialog.find(".wijmo-wijev-calendar").wijdropdown().bind("change", function (e) {
var cal = self._calendarsById[this.value];
if(cal && cal.color) {
self._addColorClass(self._editEventDialog.find(".wijmo-wijev-color"), cal.color);
} else {
if(self._editEventDialog.appt && self._editEventDialog.appt.color) {
self._addColorClass(self._editEventDialog.find(".wijmo-wijev-color"), self._editEventDialog.appt.color);
}
}
});
this._editEventDialog.find(".wijmo-wijev-repeat").wijdropdown().bind("change", function (e) {
var repeat = this.value, appt = self._editEventDialog.appt;
switch(repeat) {
case "none":
appt.recurrenceState = null;
appt.recurrencePattern = null;
break;
case "daily":
appt.recurrenceState = "master";
appt.recurrencePattern = {
parentRecurrenceId: appt.id,
recurrenceType: "daily"
};
break;
case "workdays":
appt.recurrenceState = "master";
appt.recurrencePattern = {
parentRecurrenceId: appt.id,
recurrenceType: "workdays"
};
break;
case "weekly":
appt.recurrenceState = "master";
appt.recurrencePattern = {
parentRecurrenceId: appt.id,
recurrenceType: "weekly"
};
break;
case "monthly":
appt.recurrenceState = "master";
appt.recurrencePattern = {
parentRecurrenceId: appt.id,
recurrenceType: "monthly"
};
break;
case "yearly":
appt.recurrenceState = "master";
appt.recurrencePattern = {
parentRecurrenceId: appt.id,
recurrenceType: "yearly"
};
break;
case "custom":
alert("show custom recurrence pattern.");
break;
}
});
this._dropDownInitialized = true;
} else {
// refresh wijdropdown only when select element is shown.
this._editEventDialog.find(".wijmo-wijev-calendar").wijdropdown("refresh");
this._editEventDialog.find(".wijmo-wijev-repeat").wijdropdown("refresh");
}
this._onEditEventDialogShown(this._editEventDialog, this._editEventDialog.appt);
this._editEventDialog.find(".wijmo-wijev-subject").focus();
this._updateEditEventPopupCallout();
}, this)
});
}
};
wijevcal.prototype._updateEditEventPopupCallout = function () {
if(this._editEventDialog && this._editEventDialog._arrowTarget) {
var dlg = this._editEventDialog, target = $(dlg._arrowTarget), targetOffset = target.offset(), dlgOffset = dlg.offset(), verticalPos;
if(targetOffset.left === dlgOffset.left) {
// fix for 33872
dlg.removeClass("wijmo-wijev-rightangle").removeClass("wijmo-wijev-leftangle");
} else if(targetOffset.left < dlgOffset.left) {
dlg.removeClass("wijmo-wijev-rightangle").addClass("wijmo-wijev-leftangle");
} else {
dlg.removeClass("wijmo-wijev-leftangle").addClass("wijmo-wijev-rightangle");
}
verticalPos = Math.round(targetOffset.top - dlgOffset.top + target.outerHeight(true) / 2);
this._editEventDialog.find(".wijmo-wijev-angle").css("top", verticalPos);
}
};
wijevcal.prototype._onColorButtonClick = function () {
var self = this["self"], dlg = this["dlg"], i, o = self.options, colors = o.colors, s = "";
if(colors && colors.length > 0) {
for(i = 0; i < colors.length; i += 1) {
s += "<span class=\"wijmo-wijev-listcolor wijmo-wijev-event-color-" + colors[i] + "\"> </span>";
}
}
if(!self._colorMenu) {
self._colorMenu = $("<div class=\"wijmo-wijev-color-menu " + o.wijCSS.content + " " + o.wijCSS.cornerAll + "\"></div>");
dlg.append(self._colorMenu);
self._colorMenu.wijpopup({
autoHide: true/*qq*/
});
}
self._colorMenu.html(s);
self._colorMenu.find(".wijmo-wijev-listcolor").click($.proxy(function (e) {
this._addColorClass(dlg.find(".wijmo-wijev-color"), this._readColorFromClass($(e.target), "default"));
self._colorMenu.wijpopup("hide");
}, self));
self._colorMenu.wijpopup("show", {
of: dlg.find(".wijmo-wijev-color-button"),
my: "left top",
at: "left bottom"
});
};
wijevcal.prototype._validateAndReadCalendarDialogFields = function (dlg) {
var cal = dlg.cal || {
};
cal.name = dlg.find(".wijmo-wijev-name").val();
cal.location = dlg.find(".wijmo-wijev-location").val();
cal.description = dlg.find(".wijmo-wijev-description").val();
cal.color = this._readColorFromClass(dlg.find(".wijmo-wijev-color"), cal.color || "default");
if(!cal.name) {
throw "Calendar name can not be empty";
}
return cal;
};
wijevcal.prototype._validateAndReadApptDialogFields = function (dlg) {
var appt = dlg.appt, startDate, endDate, startTime, endTime, recurrencePattern;
startDate = _toDayDate(dlg.find(".wijmo-wijev-start").wijinputdate("option", "date"));
endDate = _toDayDate(dlg.find(".wijmo-wijev-end").wijinputdate("option", "date"));
startTime = dlg.find(".wijmo-wijev-start-time").wijinputdate("option", "date");
endTime = dlg.find(".wijmo-wijev-end-time").wijinputdate("option", "date");
if(startDate.getTime() === endDate.getTime() && startTime.getTime() > endTime.getTime()) {
throw this.localizeString("messageEndOccursBeforeStart", "The end date you entered occurs before the start date.");
}
appt.subject = dlg.find(".wijmo-wijev-subject").val();
appt.location = dlg.find(".wijmo-wijev-location").val();
appt.start = startDate;
appt.end = endDate;
if(dlg.find(".wijmo-wijev-allday").length > 0) {
appt.allday = dlg.find(".wijmo-wijev-allday")[0].checked;
}
if(!appt.allday) {
appt.start = new Date(appt.start.getFullYear(), appt.start.getMonth(), appt.start.getDate(), startTime.getHours(), startTime.getMinutes(), startTime.getSeconds());
appt.end = new Date(appt.end.getFullYear(), appt.end.getMonth(), appt.end.getDate(), endTime.getHours(), endTime.getMinutes(), endTime.getSeconds());
} else {
if(appt.start.getTime() >= appt.end.getTime()) {
// duration can not be 0.
// fix for [22972] Newly created allday events are not
// visible for all views except list view until page refresh:
appt.end = this._addMinutes(appt.start, this.options.timeInterval);
}
}
appt.calendar = dlg.find(".wijmo-wijev-calendar").val();
appt.description = dlg.find(".wijmo-wijev-description").val();
appt.color = this._readColorFromClass(dlg.find(".wijmo-wijev-color"), appt.color);
// update recurrence pattern fields:
recurrencePattern = appt.recurrencePattern;
if(recurrencePattern && appt.recurrenceState === "master") {
// fix for 22970:
recurrencePattern.startTime = appt.start;
recurrencePattern.endTime = appt.end;
recurrencePattern.patternStartDate = appt.start;
}
return appt;
};
wijevcal.prototype._bindApptToDialog = function (appt) {
if(!appt) {
return;
}
var dlg = this._editEventDialog, cal, color;
dlg.appt = appt;
dlg.find(".wijmo-wijev-subject").val(appt.subject || "");
dlg.find(".wijmo-wijev-location").val(appt.location || "");
try {
dlg.find(".wijmo-wijev-start").wijinputdate("option", "date", appt.start);
dlg.find(".wijmo-wijev-start-time").wijinputdate("option", "date", appt.start);
dlg.find(".wijmo-wijev-end").wijinputdate("option", "date", appt.end);
dlg.find(".wijmo-wijev-end-time").wijinputdate("option", "date", appt.end);
} catch (ex) {
alert("[e0001a] wijinputdate/wijtextselection firefox error\n" + ex);
}
if(dlg.find(".wijmo-wijev-allday").length > 0) {
dlg.find(".wijmo-wijev-allday")[0].checked = appt.allday;
}
dlg.find(".wijmo-wijev-allday").wijcheckbox("refresh");
this._fillCalendarsSelect(dlg.find(".wijmo-wijev-calendar"), appt.calendar);
this._loadRepeatValue(appt, dlg.find(".wijmo-wijev-repeat"));
dlg.find(".wijmo-wijev-description").val(appt.description || "");
if(!appt.prevData) {
dlg.find(".wijmo-wijev-delete").hide();
} else {
dlg.find(".wijmo-wijev-delete").show();
}
if(dlg.find(".wijmo-wijev-calendar").length > 0) {
cal = this._calendarsById[dlg.find(".wijmo-wijev-calendar")[0].value];
}
color = appt.color;
if(!color && cal && cal.color) {
color = cal.color;
}
this._addColorClass(dlg.find(".wijmo-wijev-color"), color);
this._eventDialogEnsureTimePartState();
};
wijevcal.prototype._onEditEventDialogShown = function (dlg, appt) {
// fix for jquery-ui-1.9pre problem
// (cannot call methods on wijdropdown prior to initialization)
if(appt.recurrenceState === "exception") {
dlg.find(".wijmo-wijev-repeat").wijdropdown("option", "disabled", true);
} else {
dlg.find(".wijmo-wijev-repeat").wijdropdown("option", "disabled", false);
}
};
wijevcal.prototype._eventDialogEnsureTimePartState = function () {
var dlg = this._editEventDialog;
if(dlg.find(".wijmo-wijev-allday").length > 0) {
if(dlg.find(".wijmo-wijev-allday")[0].checked) {
dlg.find(".wijmo-wijev-start-time").wijinputdate("option", "disabled", true);
dlg.find(".wijmo-wijev-end-time").wijinputdate("option", "disabled", true);
} else {
dlg.find(".wijmo-wijev-start-time").wijinputdate("option", "disabled", false);
dlg.find(".wijmo-wijev-end-time").wijinputdate("option", "disabled", false);
}
}
};
wijevcal.prototype._loadRepeatValue = function (appt, repeatSelect) {
var repeatVal = "none";
if(appt.recurrencePattern) {
switch(appt.recurrencePattern.recurrenceType) {
case "daily":
repeatVal = "daily";
break;
case "workdays":
repeatVal = "workdays";
break;
case "weekly":
repeatVal = "weekly";
break;
case "monthly":
repeatVal = "monthly";
break;
case "yearly":
repeatVal = "yearly";
break;
default:
repeatVal = "custom";
break;
}
}
repeatSelect.val(repeatVal);
};
wijevcal.prototype._addColorClass = function (el, color) {
var colorClass, regexp = new RegExp("wijmo-wijev-event-color-(\\w+)\\s*");
if(el.length > 0) {
colorClass = el[0].className;
el[0].className = colorClass.replace(regexp, "");
el.addClass("wijmo-wijev-event-color-" + (color || "default"));
}
};
wijevcal.prototype._readColorFromClass = function (el, defaultColor) {
var regexp = new RegExp("wijmo-wijev-event-color-(\\w+)\\s*"), match;
if(el.length > 0) {
match = regexp.exec(el[0].className);
if(match && match.length > 1) {
return match[1];
}
}
return defaultColor;
};
wijevcal.prototype._fillCalendarsSelect = function ($select, selectedVal) {
var s = "", o = this.options, i, j, found, calendars = o.calendars.slice(0), visibleCalendars = o.visibleCalendars;
if(visibleCalendars && visibleCalendars.length > 0) {
for(i = 0; i < visibleCalendars.length; i += 1) {
found = false;
for(j = 0; j < calendars.length; j += 1) {
if(calendars[j].name === visibleCalendars[i]) {
found = true;
}
}
if(!found) {
calendars.push({
id: visibleCalendars[i],
name: visibleCalendars[i]
});
}
}
}
if(calendars.length === 0) {
$select.html("");
return;
}
for(i = 0; i < calendars.length; i += 1) {
s += "<option value=\"" + calendars[i].id + "\">" + calendars[i].name + "</option>";
}
$select.html(s).val(selectedVal);
};
wijevcal.prototype._bindCalendarToDialog = function (cal) {
if(!cal) {
return;
}
var dlg = this._editCalendarDialog;
dlg.cal = cal;
dlg.find(".wijmo-wijev-name").val(cal.name || "");
dlg.find(".wijmo-wijev-location").val(cal.location || "");
dlg.find(".wijmo-wijev-description").val(cal.description || "");
this._addColorClass(dlg.find(".wijmo-wijev-color"), cal.color);
};
wijevcal.prototype._onTodayClick = /*--------*/
function () {
this.goToday();
return false;
};
wijevcal.prototype._bindEvents = // <--
function () {
if(!this._eventsAttached) {
$(this.element).on("click." + this.wijevcalnamespacekey, ".wijmo-wijev-appointment", $.proxy(this._onAppointmentClick, this));
/*this.element.find(".wijmo-wijev-appointment")
.live("click." + this.wijevcalnamespacekey,
$.proxy(this._onAppointmentClick, this));*/
$(this.element).on("mousedown." + this.wijevcalnamespacekey, ".wijmo-wijev-dayview .wijmo-wijev-appointment", $.proxy(this._onDayViewAppointmentMouseDown, this));
$(this.element).on("mousedown." + this.wijevcalnamespacekey, ".wijmo-wijev-monthview .wijmo-wijev-appointment", $.proxy(this._onMonthViewAppointmentMouseDown, this));
$(this.element).on("click." + this.wijevcalnamespacekey, ".wijmo-wijev-dayview .wijmo-wijev-timeinterval", $.proxy(this._onDayViewTimeIntervalClick, this));
$(this.element).on("click." + this.wijevcalnamespacekey, ".wijmo-wijev-dayview .wijmo-wijev-allday-cell", $.proxy(this._onDayViewAllDayCellClick, this));
$(this.element).on("click." + this.wijevcalnamespacekey, ".wijmo-wijev-monthview .wijmo-wijev-monthcellheader", $.proxy(this._onMonthViewDayLabelClick, this));
$(this.element).on("click." + this.wijevcalnamespacekey, ".wijmo-wijev-monthview .wijmo-wijev-monthcell-showmore", $.proxy(this._onMonthViewDayLabelClick, this));
$(this.element).on("click." + this.wijevcalnamespacekey, ".wijmo-wijev-weekview .wijmo-wijev-daylabel", $.proxy(this._onMonthViewDayLabelClick, this));
$(this.element).on("click." + this.wijevcalnamespacekey, ".wijmo-wijev-monthview .wijmo-wijev-monthcell", $.proxy(this._onMonthViewCellClick, this));
//
this._eventsAttached = true;
}
};
wijevcal.prototype._unbindEvents = function () {
if(this._eventsAttached) {
$(this.element).off("mousedown." + this.wijevcalnamespacekey);
$(this.element).off("click." + this.wijevcalnamespacekey);
/*
$(this.element).off("click." + this.wijevcalnamespacekey, ".wijmo-wijev-appointment");
$(this.element).off("mousedown." + this.wijevcalnamespacekey, ".wijmo-wijev-dayview .wijmo-wijev-daycolumn .wijmo-wijev-appointment");
$(this.element).off("click." + this.wijevcalnamespacekey, ".wijmo-wijev-dayview .wijmo-wijev-dayheadercolumn .wijmo-wijev-daylabel");
$(this.element).off("click." + this.wijevcalnamespacekey, ".wijmo-wijev-dayview .wijmo-wijev-timeinterval");
$(this.element).off("click." + this.wijevcalnamespacekey, ".wijmo-wijev-dayview .wijmo-wijev-allday-cell");
$(this.element).off("click." + this.wijevcalnamespacekey, ".wijmo-wijev-monthview .wijmo-wijev-monthcellheader");
$(this.element).off("click." + this.wijevcalnamespacekey, ".wijmo-wijev-monthview .wijmo-wijev-monthcell-showmore");
$(this.element).off("click." + this.wijevcalnamespacekey, ".wijmo-wijev-weekview .wijmo-wijev-daylabel");
$(this.element).off("click." + this.wijevcalnamespacekey, ".wijmo-wijev-monthview .wijmo-wijev-monthcell");
*/
this._eventsAttached = false;
}
};
wijevcal.prototype.destroy = /**
* Removes the wijevcal functionality completely. This returns the element to its pre-init state.
*/
function () {
this._destroyInternal();
$.wijmo.widget.prototype.destroy.apply(this, arguments);
};
wijevcal.prototype._destroyInternal = function () {
var o = this.options;
this.element.removeClass("wijmo-wijev wijmo-wijevcal " + o.wijCSS.widget + " ui-helper-reset");
$(window).unbind("resize." + this.wijevcalnamespacekey);
this._unbindEvents();
this.element.empty();
this.wijevcalnamespacekey = null;
this._uidPref = null;
this._isUpdating = null;
this._resolveDayApptConflictsTimeout = null;
this._pendingRedrawActiveView = null;
this._listViewDetailsInit = null;
this._dayViewDetailsInit = null;
this._eventsAttached = null;
this.statusbarEventsAdded = null;
this._dataView = null;
this._eventsView = null;
this._eventsDataById = null;
this._calendarsById = null;
this._dayViewCache = null;
this._templateDayColumn = null;
this._templateDayHeader = null;
this._dayViewScrollToEvent = null;
this._maxAllDayEventCount = null;
this._dayColumnsToResolve = null;
this._dayColumnResolveIdx = null;
this.logDialog = null;
this.logPanel = null;
this._editCalendarDialog = null;
this._editEventDialog = null;
this._renderAgendaEventsTimeoutId = null;
this.__targetAppt = null;
this._isApptResize = null;
this.__startApptH = null;
this.__startApptY = null;
this.__startClientY = null;
this._apptDragResizeFlag = null;
this._apptMovedFlag = null;
this._movedFromTimeInervalApptElem = null;
this.__targetApptChanged = null;
this._defferObjs = null;
this._setOptionCallbacks = null;
this._chromeLoadDataDeffer = null;
};
wijevcal.prototype.deleteCalendar = // public methods
/**
* Deletes the existing calendar from the current data source.
* @example $("#wijevcal").wijevcal("deleteCalendar", "My calendar");
* @param {object} o Calendar id, name or calendar object.
* @param {function} successCallback Function that will be called when calendar is deleted.
* @param {function} errorCallback Function that will be called when calendar can not be deleted.(e.g. due to data source or memory problems).
*/
function (o, successCallback, errorCallback) {
var i, calendars = this.options.calendars, id = o.id || o, found = false, deleteCalendarCallback, deleteCalendarErrorCallback, k, self = this;
for(i = 0; i < calendars.length; i += 1) {
if(calendars[i].id === id) {
found = true;
o = calendars[i];
if(!this._trigger("beforeDeleteCalendar", null, {
data: o
})) {
return false;
}
delete this._calendarsById[o.id];
calendars.splice(i, 1);
break;
}
}
if(!found) {
// try search by name
for(i = 0; i < calendars.length; i += 1) {
if(calendars[i].name === id) {
found = true;
o = calendars[i];
if(!this._trigger("beforeDeleteCalendar", null, {
data: o
})) {
return false;
}
delete this._calendarsById[o.id];
calendars.splice(i, 1);
break;
}
}
}
if(!found) {
this.status("Calendar with id/name '" + id + "' not found.");
return false;
}
this.showLoadingLabel(this.localizeString("activityDeletingCalendar", "Deleting calendar..."));
deleteCalendarCallback = function (sqlResult) {
self.status("Calendar '" + o.name + "' deleted.");
self._onCalendarsChanged();
self.hideLoadingLabel();
if(successCallback) {
successCallback(sqlResult);
}
};
deleteCalendarErrorCallback = function (e) {
self.status("Unable to delete calendar '" + o.name + "': " + e);
self.hideLoadingLabel();
if(errorCallback) {
errorCallback(e);
}
};
if(this.options.dataStorage.deleteCalendar) {
this.options.dataStorage.deleteCalendar(o, deleteCalendarCallback, deleteCalendarErrorCallback);
} else if(this.options.webServiceUrl) {
try {
k = this._jsonStringify(o);
} catch (ex) {
this.status("Unable to prepare calendar data for server. " + ex, "error");
deleteCalendarErrorCallback("Unable to prepare calendar data for server. " + ex);
return;
}
$.ajax({
url: this.options.webServiceUrl + "?clientId=" + this.element[0].id + "&command=deleteCalendar×tamp=" + new Date().getTime(),
dataType: "text",
contentType: "application/json; charset=utf-8",
type: "POST",
data: "jsonData=" + k,
success: deleteCalendarCallback,
error: deleteCalendarErrorCallback
});
} else {
executeSql("DELETE FROM calendars " + "WHERE id='" + o.id + "'", [], deleteCalendarCallback, deleteCalendarErrorCallback);
}
};
wijevcal.prototype.addCalendar = /**
* Adds a new calendar.
* @example
* $("#wijevcal").wijevcal("addCalendar", {
* name: "My calendar",
* location: "Home",
* description: "Some description",
* color: "lime"
* });
* @param {object} o
* Calendar object.
* Calendar object fields:
* id - String, unique calendar id, this field generated automatically;
* name - String, calendar name;
* location - String, location field;
* description - String, calendar description;
* color - String, calendar color;
* tag - String, this field can be used to store custom information.
* @param {function} successCallback Function that will be called when calendar is added.
* @param {function} errorCallback Function that will be called when calendar can not be added.(e.g. due to data source or memory problems).
*/
function (o, successCallback, errorCallback) {
var addCalendarCallback, k, addCalendarErrorCallback, self = this;
if(!this._trigger("beforeAddCalendar", null, {
data: o,
prevData: o.prevData || {
}
})) {
if(o.prevData) {
for(k in o.prevData) {
if(o.prevData.hasOwnProperty(k)) {
o[k] = o.prevData[k];
}
}
}
return false;
}
if(!o.id) {
if(!this._dynIdCounter) {
this._dynIdCounter = 0;
}
this._dynIdCounter += 1;
o.id = "dynid" + this._dynIdCounter + "ts" + new Date().getTime();
}
this.showLoadingLabel(this.localizeString("activityCreatingCalendar", "Creating calendar..."));
addCalendarCallback = function (sqlResult) {
if(self._handleServerError(sqlResult)) {
addCalendarErrorCallback(sqlResult);
return;
}
self._readUpdatedServerDataIfAny(sqlResult, o);
if(!self._calendarsById[o.id]) {
self.options.calendars.push(o);
self._calendarsById[o.id] = o;
self.status("Calendar '" + o.name + "' added.");
} else {
self.status("Calendar '" + o.name + "' added.");
}
o.prevData = self._cloneObj(o);
self._onCalendarsChanged();
self.hideLoadingLabel();
if(successCallback) {
successCallback(sqlResult);
}
};
addCalendarErrorCallback = function (e) {
self.status("Unable to add calendar '" + o.name + "': " + e);
self.hideLoadingLabel();
if(errorCallback) {
errorCallback(e);
}
};
if(this.options.dataStorage.addCalendar) {
this.options.dataStorage.addCalendar(o, addCalendarCallback, addCalendarErrorCallback);
} else if(this.options.webServiceUrl) {
try {
k = this._jsonStringify(o);
} catch (ex) {
this.status("Unable prepare calendar data for server." + ex, "error");
addCalendarErrorCallback("Unable to prepare calendar data for server." + ex);
return;
}
$.ajax({
url: this.options.webServiceUrl + "?clientId=" + this.element[0].id + "&command=addCalendar×tamp=" + new Date().getTime(),
dataType: "text",
contentType: "application/json; charset=utf-8",
type: "POST",
data: "jsonData=" + k,
success: addCalendarCallback,
error: addCalendarErrorCallback
});
} else {
executeSql("INSERT OR REPLACE INTO calendars " + "(id, name, location, description, color, tag) " + "VALUES(?,?,?,?,?,?);", [
o.id,
o.name,
o.location,
o.description,
o.color,
o.tag
], addCalendarCallback, addCalendarErrorCallback);
}
};
wijevcal.prototype.updateCalendar = /**
* Updates the existing calendar.
* @example
* $("#wijevcal").wijevcal("updateCalendar", {
* name: "My calendar",
* location: "Home",
* description: "Some description",
* color: "lime"
* });
* @param {object} o
* Calendar object.
* Calendar object fields:
* id - String, unique calendar id, this field generated automatically;
* name - String, calendar name;
* location - String, location field;
* description - String, calendar description;
* color - String, calendar color;
* tag - String, this field can be used to store custom information.
* @param {function} successCallback Function that will be called when calendar is updated.
* @param {function} errorCallback Function that will be called when calendar can not be updated.(e.g. due to data source or memory problems).
*/
function (o, successCallback, errorCallback) {
var updateCalendarCallback, k, updateCalendarErrorCallback, self = this;
if(!this._trigger("beforeUpdateCalendar", null, {
data: o,
prevData: o.prevData || {
}
})) {
if(o.prevData) {
for(k in o.prevData) {
if(o.prevData.hasOwnProperty(k)) {
o[k] = o.prevData[k];
}
}
}
return false;
}
if(!o.id) {
if(!this._dynIdCounter) {
this._dynIdCounter = 0;
}
this._dynIdCounter += 1;
o.id = "dynid" + this._dynIdCounter + "ts" + new Date().getTime();
}
this.showLoadingLabel(this.localizeString("activityUpdatingCalendar", "Updating calendar..."));
updateCalendarCallback = function (sqlResult) {
if(self._handleServerError(sqlResult)) {
updateCalendarErrorCallback(sqlResult);
return;
}
self._readUpdatedServerDataIfAny(sqlResult, o);
if(!self._calendarsById[o.id]) {
self.options.calendars.push(o);
self._calendarsById[o.id] = o;
self.status("Calendar '" + o.name + "' added.");
} else {
self.status("Calendar '" + o.name + "' updated.");
}
o.prevData = self._cloneObj(o);
self._onCalendarsChanged();
self.hideLoadingLabel();
if(successCallback) {
successCallback(sqlResult);
}
};
updateCalendarErrorCallback = function (e) {
self.status("Unable to update calendar '" + o.name + "': " + e);
self.hideLoadingLabel();
if(errorCallback) {
errorCallback(e);
}
};
if(this.options.dataStorage.updateCalendar) {
this.options.dataStorage.updateCalendar(o, updateCalendarCallback, updateCalendarErrorCallback);
} else if(this.options.webServiceUrl) {
try {
k = this._jsonStringify(o);
} catch (ex) {
this.status("Unable prepare calendar data for server. " + ex, "error");
updateCalendarErrorCallback("Unable to prepare calendar data for server. " + ex);
return;
}
$.ajax({
url: this.options.webServiceUrl + "?clientId=" + this.element[0].id + "&command=updateCalendar×tamp=" + new Date().getTime(),
dataType: "text",
contentType: "application/json; charset=utf-8",
type: "POST",
data: "jsonData=" + k,
success: updateCalendarCallback,
error: updateCalendarErrorCallback
});
} else {
executeSql("INSERT OR REPLACE INTO calendars " + "(id, name, location, description, color, tag) " + "VALUES(?,?,?,?,?,?);", [
o.id,
o.name,
o.location,
o.description,
o.color,
o.tag
], updateCalendarCallback, updateCalendarErrorCallback);
}
};
wijevcal.prototype.addEvent = /**
* Adds a new event.
* @example
* $("#wijevcal").wijevcal("addEvent", {
* start: new Date(2011, 4, 2, 0, 32),
* end: new Date(2011, 4, 2, 0, 50),
* subject: "Subject" });
* @param {object} o
* Event object.
* Event object fields:
* id - String, unique event id, this field generated automatically;
* calendar - String, calendar id to which the event belongs;
* subject - String, event title;
* location - String, event location;
* start - Date, start date/time;
* end - Date, end date/time;
* description - String, event description;
* color - String, event color;
* allday - Boolean, indicates all day event
* tag - String, this field can be used to store custom information.
* @param {function} successCallback Function that will be called when event is added.
* @param {function} errorCallback Function that will be called when event can not be added.(e.g. due to data source or memory problems).
*/
function (o, successCallback, errorCallback) {
var addEventCallback, addEventErrorCallback, k, self = this;
if(!this._trigger("beforeAddEvent", null, {
data: o,
prevData: o.prevData || {
}
})) {
if(o.prevData) {
for(k in o.prevData) {
if(o.prevData.hasOwnProperty(k)) {
o[k] = o.prevData[k];
}
}
}
return false;
}
if(!o.id) {
if(!this._dynIdCounter) {
this._dynIdCounter = 0;
}
this._dynIdCounter += 1;
o.id = _generateGuid()// "dynid" + this._dynIdCounter + "ts" + new Date().getTime();
;
}
if(!o.calendar) {
o.calendar = "Default";
}
this.showLoadingLabel(this.localizeString("activityCreatingEvent", "Creating event..."));
addEventErrorCallback = function (e) {
self.hideLoadingLabel();
self.status("Unable to add event '" + o.subject + "': " + e, "error");
if(o.prevData) {
for(k in o.prevData) {
if(o.prevData.hasOwnProperty(k)) {
o[k] = o.prevData[k];
}
}
}
if(errorCallback) {
errorCallback(e);
}
};
addEventCallback = function (result) {
if(self._handleServerError(result)) {
addEventErrorCallback(result);
return;
}
self._readUpdatedServerDataIfAny(result, o);
if(!self._eventsDataById[o.id] || o.recurrenceState === "exception") {
self._storeEventWithSort(o);
self.status("Event '" + o.subject + "' added.");
} else {
self.status("Event '" + o.subject + "' added.");
}
o.prevData = self._cloneObj(o);
self._onEventsDataChanged();
self.hideLoadingLabel();
if(successCallback) {
successCallback(result);
}
};
if(this.options.dataStorage.addEvent) {
this.options.dataStorage.addEvent(o, addEventCallback, addEventErrorCallback);
} else if(this.options.webServiceUrl) {
try {
k = this._jsonStringify(o);
} catch (ex) {
this.status("Unable prepare event data for server. " + ex, "error");
addEventErrorCallback("Unable to prepare event data for server. " + ex);
return;
}
$.ajax({
url: this.options.webServiceUrl + "?clientId=" + this.element[0].id + "&command=addEvent×tamp=" + new Date().getTime(),
dataType: "text",
contentType: "application/json; charset=utf-8",
type: "POST",
data: "jsonData=" + k,
success: addEventCallback,
error: addEventErrorCallback
});
} else {
// if not reference the amplify and the browser is not support local storage. just added
if(!isAmplifyStoreUsed && !window["openDatabase"]) {
addEventCallback.call(this, {
rowsAffected: 0,
rows: [
o
]
});
return;
}
executeSql("INSERT OR REPLACE INTO events " + "(id, calendar, subject, location, start, end," + " description, color, allday, properties, tag) " + "VALUES(?,?,?,?,?,?,?,?,?,?,?);", [
o.id,
o.calendar,
o.subject,
o.location,
o.start.getTime(),
o.end.getTime(),
o.description,
o.color,
o.allday,
this._serializeProperties(o),
o.tag
], addEventCallback, addEventErrorCallback);
}
};
wijevcal.prototype._storeEventWithSort = function (o) {
// fix for
// [19618] [C1EventsCalendar] Request to provide sorting behavior
// in C1EventsCalendar with all view types:
var apps = this.options.eventsData, i, c;
this._eventsDataById[o.id] = o;
for(i = 0 , c = apps.length; i < c; i += 1) {
if(apps[i].start > o.start) {
apps.splice(i, 0, o);
return;
} else if(apps[i].start.getTime() === o.start.getTime()) {
if(apps[i].subject > o.subject) {
apps.splice(i, 0, o);
return;
}
}
}
apps.push(o);
};
wijevcal.prototype._readUpdatedServerDataIfAny = function (result, o) {
var k = null, j;
if(typeof result === "string" && result.indexOf("update:") === 0) {
result = result.toString().substr("update:".length);
try {
k = this._jsonParse(result);
} catch (ex) {
this.status("Unable to read updated server data. " + ex, "warning");
}
if(k) {
for(j in k) {
if(k[j]) {
o[j] = k[j];
/*
if (k.hasOwnProperty(j)) {
o[j] = k[j];
}*/
}
}
}
}
};
wijevcal.prototype.updateEvent = /**
* Updates the existing event.
* @example
* $("#wijevcal").wijevcal("updateEvent", {
* start: new Date(2011, 4, 2, 0, 32),
* end: new Date(2011, 4, 2, 0, 50),
* subject: "Subject" });
* @param {object} o
* Event object.
* Event object fields:
* id - String, unique event id, this field generated automatically;
* calendar - String, calendar id to which the event belongs;
* subject - String, event title;
* location - String, event location;
* start - Date, start date/time;
* end - Date, end date/time;
* description - String, event description;
* color - String, event color;
* allday - Boolean, indicates all day event
* tag - String, this field can be used to store custom information.
* @param {function} successCallback Function that will be called when event is updated.
* @param {function} errorCallback Function that will be called when event can not be updated.(e.g. due to data source or memory problems).
*/
function (o, successCallback, errorCallback) {
var updateEventCallback, updateEventErrorCallback, k, self = this;
if(!this._trigger("beforeUpdateEvent", null, {
data: o,
prevData: o.prevData || {
}
})) {
if(o.prevData) {
for(k in o.prevData) {
if(o.prevData.hasOwnProperty(k)) {
o[k] = o.prevData[k];
}
}
}
this._updateAppointmentVisual(o);
return false;
}
if(!o.calendar) {
o.calendar = "Default";
}
this.showLoadingLabel(this.localizeString("activityUpdatingEvent", "Updating event..."));
updateEventErrorCallback = function (e) {
self.hideLoadingLabel();
self.status("Unable to update event '" + o.subject + "': " + e, "error");
if(o.prevData) {
for(k in o.prevData) {
if(o.prevData.hasOwnProperty(k)) {
o[k] = o.prevData[k];
}
}
}
self._updateAppointmentVisual(o);
if(errorCallback) {
errorCallback(e);
}
};
if(!o.id) {
updateEventErrorCallback("id is empty");
return;
}
if(o.recurrenceState === "exception" || o.recurrenceState === "occurrence") {
if(!this._eventsDataById[o.parentRecurrenceId]) {
updateEventErrorCallback("Unable to find master event for event with id:" + o.id);
return;
}
if(o.recurrenceState === "occurrence") {
this.log(this._formatString("[updateEvent->addEvent] recurrenceState for event {0} changed to 'exception'.", o.id));
o.recurrenceState = "exception";
return this.addEvent(o, successCallback, errorCallback);
}
}
updateEventCallback = function (result) {
if(self._handleServerError(result)) {
updateEventErrorCallback(result);
return;
}
self._readUpdatedServerDataIfAny(result, o);
if(!self._eventsDataById[o.id]) {
self._storeEventWithSort(o);
self.status("Event '" + o.subject + "' added.");
} else {
self.status("Event '" + o.subject + "' updated.");
}
o.prevData = self._cloneObj(o);
self._onEventsDataChanged();
self.hideLoadingLabel();
if(successCallback) {
successCallback(result);
}
};
if(this.options.dataStorage.updateEvent) {
this.options.dataStorage.updateEvent(o, updateEventCallback, updateEventErrorCallback);
} else if(this.options.webServiceUrl) {
try {
k = this._jsonStringify(o);
} catch (ex) {
this.status("Unable prepare event data for server. " + ex, "error");
updateEventErrorCallback("Unable to prepare event data for server. " + ex);
return;
}
$.ajax({
url: this.options.webServiceUrl + "?clientId=" + this.element[0].id + "&command=updateEvent×tamp=" + new Date().getTime(),
dataType: "text",
contentType: "application/json; charset=utf-8",
type: "POST",
data: "jsonData=" + k,
success: updateEventCallback,
error: updateEventErrorCallback
});
} else {
executeSql("INSERT OR REPLACE INTO events " + "(id, calendar, subject, location, start, end," + " description, color, allday, properties, tag) " + "VALUES(?,?,?,?,?,?,?,?,?,?,?);", [
o.id,
o.calendar,
o.subject,
o.location,
o.start.getTime(),
o.end.getTime(),
o.description,
o.color,
o.allday,
this._serializeProperties(o),
o.tag
], updateEventCallback, updateEventErrorCallback);
}
};
wijevcal.prototype._serializeProperties = function (appt) {
var s = "", props = {
};
props.parentRecurrenceId = appt.parentRecurrenceId;
props.recurrenceState = appt.recurrenceState;
props.recurrencePattern = appt.recurrencePattern;
props.color = appt.color;
props.allday = appt.allday;
/// color - String, event color;
/// allday - Boolean, indicates all day event
/// parentRecurrenceId - String, id of the event object that
/// defines the recurrence criteria for this event object.
/// If an event is recurring (see isRecurring)
/// it represents an occurrence in the series that is
/// started and defined by a specific pattern event.
/// Use the getPatern method in order to obtain the pattern
/// of the current event. A pattern event can be recognized by its
/// recurrenceState field set to the "master" value.
/// The recurrence information defined by the pattern event
/// can be accessed via the recurrencePattern field of the event.
/// If this event is a not member of a recurrence,
/// or is itself a root event, this field will be null.
/// recurrenceState - String, indicates the recurrence state of the event.
/// (possible values are "notRecurring"(or null),
/// "master", "occurrence","exception", "removed")
/// recurrencePattern - Object, represents the recurrence attributes
try {
s = this._jsonStringify(props);
} catch (ex) {
this.status("Unable save additional event properties. " + ex, "error");
}
return s;
};
wijevcal.prototype._deSerializeProperties = function (s, appt) {
var props = {
}, pattern;
if(s) {
if(typeof s === "string") {
try {
props = this._jsonParse(s);
} catch (ex) {
this.status("Unable to load additional event properties. " + ex, "error");
return;
}
} else {
props = s;
}
if(props.parentRecurrenceId) {
appt.parentRecurrenceId = props.parentRecurrenceId;
}
if(props.recurrenceState) {
appt.recurrenceState = props.recurrenceState;
}
if(props.recurrencePattern) {
appt.recurrencePattern = props.recurrencePattern;
}
if(props.color) {
appt.color = props.color;
}
if(props.allday) {
appt.allday = props.allday;
}
}
if(appt && appt.recurrencePattern) {
// ensure recurrencePattern date properties loaded correctly:
pattern = appt.recurrencePattern;
pattern.patternStartDate = pattern.patternStartDate ? new Date(pattern.patternStartDate) : pattern.patternStartDate;
pattern.startTime = pattern.startTime ? new Date(pattern.startTime) : pattern.startTime;
pattern.endTime = pattern.endTime ? new Date(pattern.endTime) : pattern.endTime;
// duration can not be 0.
if(pattern.startTime.getTime() >= pattern.endTime.getTime()) {
pattern.endTime = this._addMinutes(pattern.startTime, this.options.timeInterval);
}
}
};
wijevcal.prototype._jsonStringify = function (o) {
var s;
if(window["__JSONC1"]) {
s = window["__JSONC1"].stringify(o);
} else if(window["JSON"]) {
s = JSON.stringify(o);
} else {
throw "JSON not found.";
}
return s;
};
wijevcal.prototype._jsonParse = function (s) {
var o, reISO, reMsAjax;
if(window["__JSONC1"]) {
o = window["__JSONC1"].parse(s);
} else if(window["JSON"]) {
reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/;
reMsAjax = /^\/Date\((d|-|.*)\)\/$/;
o = window["JSON"].parse(s, function (key, value) {
if(typeof value === 'string') {
var a = reISO.exec(value), b;
if(a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
}
a = reMsAjax.exec(value);
if(a) {
b = a[1].split(/[-,.]/);
return new Date(+b[0]);
}
}
return value;
});
} else {
throw "JSON variable not found.";
}
return o;
};
wijevcal.prototype.getOccurrences = /**
* Retrieves the array which contains
* the full list of Event objects in the specified time interval.
* Note, this method will create instances of the Event
* object for recurring events.
* @param {Date} start The Date value which specifies
* the start date and time of the interval.
* @param {Date} end The Date value which specifies
* the end date and time of the interval.
* @returns {array} events array
*/
function (start, end) {
var o = this.options, appts = o.eventsData, appt, occurrenceAppt, exceptionAppt, pattern, i, j, icnt, jcnt, maxOccurrenceCount = 100, patternStart, patternStartTime, patternEndTime, eventsArr = [], exceptionsArr = [], removedArr = [], occurrenceHash = {
};
if(!this._eventsDataById) {
this._eventsDataById = {
};
}
for(i = 0 , icnt = appts.length; i < icnt; i += 1) {
appt = appts[i];
this._eventsDataById[appt.id] = appt;
if(appt.recurrenceState === "master") {
pattern = appt.recurrencePattern;
if(pattern.removedOccurrences) {
removedArr = removedArr.concat(pattern.removedOccurrences);
}
// populate pattern:
jcnt = pattern.occurrences || maxOccurrenceCount;
patternStart = pattern.patternStartDate || appt.start;
patternStartTime = pattern.startTime || appt.start;
patternEndTime = pattern.endTime || appt.end;
//alert("pattern.recurrenceType=" + pattern.recurrenceType);
switch(pattern.recurrenceType) {
case "daily":
for(j = 0; j < jcnt; j += 1) {
occurrenceAppt = this._cloneObj(appt);
occurrenceAppt.parentRecurrenceId = appt.id;
occurrenceAppt.recurrenceState = "occurrence";
occurrenceAppt.start = this._setTime(this._addDays(patternStart, j), patternStartTime);
occurrenceAppt.end = this._setTime(occurrenceAppt.start, patternEndTime, patternStartTime);
occurrenceAppt.recurrencePattern = null;
if(this._testIsEventInTimeInterval(occurrenceAppt, start, end)) {
occurrenceAppt.id = this._formatString("{0}_OCCR_{1:yyyy_MM_dd}", appt.id, occurrenceAppt.start);
occurrenceHash[occurrenceAppt.id] = occurrenceAppt;
}
}
break;
case "workdays":
for(j = 0; j < jcnt; j += 1) {
occurrenceAppt = this._cloneObj(appt);
occurrenceAppt.parentRecurrenceId = appt.id;
occurrenceAppt.recurrenceState = "occurrence";
occurrenceAppt.start = this._setTime(this._addDays(patternStart, j), patternStartTime);
//getDay() : Sunday is 0, Monday is 1, and so on.
if(occurrenceAppt.start.getDay() === 0 || occurrenceAppt.start.getDay() === 6) {
continue;
}
occurrenceAppt.end = this._setTime(occurrenceAppt.start, patternEndTime, patternStartTime);
occurrenceAppt.recurrencePattern = null;
if(this._testIsEventInTimeInterval(occurrenceAppt, start, end)) {
occurrenceAppt.id = this._formatString("{0}_OCCR_{1:yyyy_MM_dd}", appt.id, occurrenceAppt.start);
occurrenceHash[occurrenceAppt.id] = occurrenceAppt;
}
}
break;
case "weekly":
for(j = 0; j < jcnt; j += 1) {
occurrenceAppt = this._cloneObj(appt);
occurrenceAppt.parentRecurrenceId = appt.id;
occurrenceAppt.recurrenceState = "occurrence";
occurrenceAppt.start = this._setTime(this._addDays(patternStart, j * 7), patternStartTime);
occurrenceAppt.end = this._setTime(occurrenceAppt.start, patternEndTime, patternStartTime);
occurrenceAppt.recurrencePattern = null;
if(this._testIsEventInTimeInterval(occurrenceAppt, start, end)) {
occurrenceAppt.id = this._formatString("{0}_OCCR_{1:yyyy_MM_dd}", appt.id, occurrenceAppt.start);
occurrenceHash[occurrenceAppt.id] = occurrenceAppt;
}
}
break;
case "monthly":
for(j = 0; j < jcnt; j += 1) {
occurrenceAppt = this._cloneObj(appt);
occurrenceAppt.parentRecurrenceId = appt.id;
occurrenceAppt.recurrenceState = "occurrence";
occurrenceAppt.start = this._setTime(new Date(patternStart), patternStartTime);
occurrenceAppt.start.setMonth(occurrenceAppt.start.getMonth() + j);
occurrenceAppt.end = this._setTime(occurrenceAppt.start, patternEndTime, patternStartTime);
occurrenceAppt.recurrencePattern = null;
if(this._testIsEventInTimeInterval(occurrenceAppt, start, end)) {
occurrenceAppt.id = this._formatString("{0}_OCCR_{1:yyyy_MM_dd}", appt.id, occurrenceAppt.start);
occurrenceHash[occurrenceAppt.id] = occurrenceAppt;
}
}
break;
case "yearly":
for(j = 0; j < jcnt; j += 1) {
occurrenceAppt = this._cloneObj(appt);
occurrenceAppt.parentRecurrenceId = appt.id;
occurrenceAppt.recurrenceState = "occurrence";
occurrenceAppt.start = this._setTime(new Date(patternStart), patternStartTime);
occurrenceAppt.start.setYear(occurrenceAppt.start.getFullYear() + j);
occurrenceAppt.end = this._setTime(occurrenceAppt.start, patternEndTime, patternStartTime);
occurrenceAppt.recurrencePattern = null;
if(this._testIsEventInTimeInterval(occurrenceAppt, start, end)) {
occurrenceAppt.id = this._formatString("{0}_OCCR_{1:yyyy_MM_dd}", appt.id, occurrenceAppt.start);
occurrenceHash[occurrenceAppt.id] = occurrenceAppt;
}
}
break;
case "monthlyNth":
break;
case "yearlyNth":
break;
}
} else {
if(this._testIsEventInTimeInterval(appt, start, end)) {
if(appt.recurrenceState === "exception") {
exceptionsArr.push(appt);
} else {
if(appt.recurrenceState === "removed") {
removedArr.push(appt.id);
this.log("[warning] Seems we found removed event inside events storage, id:" + appt.id);
} else {
eventsArr.push(appt);
}
}
}
}
}
for(i = 0 , icnt = exceptionsArr.length; i < icnt; i += 1) {
exceptionAppt = exceptionsArr[i];
if(occurrenceHash[exceptionAppt.id]) {
delete occurrenceHash[exceptionAppt.id];
}
eventsArr.push(exceptionAppt);
this._eventsDataById[exceptionAppt.id] = exceptionAppt;
}
for(i = 0 , icnt = removedArr.length; i < icnt; i += 1) {
if(occurrenceHash[removedArr[i]]) {
delete occurrenceHash[removedArr[i]];
}
}
for(i in occurrenceHash) {
occurrenceAppt = occurrenceHash[i];
eventsArr.push(occurrenceAppt);
this._eventsDataById[occurrenceAppt.id] = occurrenceAppt;
}
//eventsArr.push(occurrenceAppt);
//this._eventsDataById[occurrenceAppt.id] = occurrenceAppt;
return eventsArr;
/// parentRecurrenceId - String, id of the event object that
/// defines the recurrence criteria for this event object.
/// If an event is recurring (see isRecurring)
/// it represents an occurrence in the series that is
/// started and defined by a specific pattern event.
/// Use the getPatern method in order to obtain the pattern
/// of the current event. A pattern event can be recognized by its
/// recurrenceState field set to the "master" value.
/// The recurrence information defined by the pattern event
/// can be accessed via the recurrencePattern field of the
/// event.
/// If this event is a not member of a recurrence,
/// or is itself a root event, this field will be null.
/// recurrenceState - String, indicates the recurrence state of
/// the event.
/// (possible values are "notRecurring"(or null), "master",
/// "occurrence", "exception", "removed")
/// recurrencePattern - Object, represents the recurrence attributes
/// of an event. Only master events can have this field
/// (recurrenceState is "master")
/// Object syntax:
/// parentRecurrenceId - String, id of the event object
/// which represents the master event for this
/// recurrencePattern object.
/// recurrenceType - String, determines the type of recurrence:
/// daily - the recurring event reoccurs on a daily basis.
/// workdays - the recurring event reoccurs every working
/// day.
/// weekly - the recurring event reoccurs on
/// a weekly basis.
/// monthly - the recurring event reoccurs on
/// a monthly basis.
/// monthlyNth - the recurring event reoccurs
/// every N months.
/// yearly - the recurring event reoccurs on
/// an yearly basis.
/// yearlyNth - the recurring event reoccurs every N years.
/// interval - Number, specifies the interval between
/// occurrences of the recurrence.
/// The interval field works in conjunction with
/// the "recurrenceType" field to determine the cycle
/// of the recurrence.
/// The maximum allowable value is 99 for weekly patterns
/// and 999 for daily patterns.
/// The default value is 1.
/// For example, if the recurrenceType is set
/// to daily, and the "interval" is set to 3,
/// the recurrence will occur every third day.
/// startTime - Date, indicates the start time for the given
/// occurrence of the recurrence pattern.
/// endTime - Date, indicates the end time for the given
/// occurrence of the recurrence pattern.
/// patternStartDate - Date, indicates the start date of the
/// recurrence pattern.
/// patternEndDate - Date, indicates the end date of the
/// recurrence pattern.
/// This field is optional but must be coordinated
/// with other fields when setting up a recurrence pattern.
/// If this field or the "occurrences" field is set,
/// the pattern is considered to be finite, and the "noEndDate"
/// field is false.
/// If neither "patternEndDate" nor "occurrences" is set,
/// the pattern is considered infinite and "noEndDate" is true.
/// The "interval" field must be set before
/// setting "patternEndDate".
/// occurrences - Number, the number of occurrences for the
/// recurrence pattern. This field allows the definition of
/// a recurrence pattern that is only valid for the specified
/// number of subsequent occurrences.
/// For example, you can set this property to 10 for a formal
/// training course that will be held on the next ten Thursday
/// evenings. The default value is 0. This field must be
/// coordinated with other fields when setting up a recurrence pattern.
/// If the "patternEndDate" field or the "occurrences" field
/// is set, the pattern is considered to be finite and the
/// "noEndDate" field is false.
/// If neither "patternEndDate" nor "occurrences" is set,
/// the pattern is considered infinite and "noEndDate" is true.
/// instance - String, determines the week in a month in which
/// the event will occur. This field is only valid for recurrences of
/// the "monthlyNth" and "yearlyNth" types and allows the definition
/// of a recurrence pattern that is only valid for the Nth occurrence,
/// such as "the 2nd Sunday in March" pattern.
/// The default value is "first".
/// Possible values are:
/// first - the recurring event will occur on the specified
/// day or days of the first week in the month.
/// second - The recurring event will occur on the specified
/// day or days of the second week in the month.
/// third = - The recurring event will occur on the specified
/// day or days of the third week in the month.
/// fourth - The recurring event will occur on the specified
/// day or days of the fourth week in the month.
/// last - The recurring event will occur on the specified
/// day or days of the last week in the month.
/// dayOfWeekMask - String, contains set of values representing the mask
/// for week days on which the recurring event occurs.
/// Monthly and yearly patterns are only valid for a single day.
/// The default value is "none".
/// When the "RecurrenceType" field is set to "daily",
/// the "DayOfWeekMask" field can only be set to "everyDay";
/// setting the field to any other value will result in an exception.
/// When the "recurrenceType" field is set to
/// "workdays", the "dayOfWeekMask" field
/// can only be set to "workDays"; setting the field
/// to any other value will result in an exception.
/// When the "recurrenceType" field is set to
/// "weekly", the "dayOfWeekMask" field
/// cannot be set to "none"; doing so will result
/// in an exception being thrown.
/// When the recurrenceType" field is set to
/// "monthly" or "yearly" the "dayOfWeekMask" field is not applicable.
/// Possible values are:
/// none - no specific value; the actual value is obtained from
/// the root event object.
/// sunday - specifies Sunday.
/// monday - Specifies Monday.
/// tuesday - Specifies Tuesday.
/// wednesday - Specifies Wednesday.
/// thursday - Specifies Thursday.
/// friday - Specifies Friday.
/// saturday - Specifies Saturday.
/// weekendDays - Specifies Saturday and Sunday
/// (or what ever days according
/// to the settings of the C1EventsCalendar).
/// workDays - Specifies work days (all days except weekend).
/// everyDay - Specifies every day of the week.
/// dayOfMonth - Number, the number of the day in its respective month on which
/// each occurrence will occur. Applicable only when the recurrenceType
/// field is set to "monthly" or "yearly".
/// The default value is 1.
/// monthOfYear - Number, indicates which month of the year is valid
/// for the specified recurrence pattern. Can be a number from 1 to 12.
/// This field is only valid for recurrence patterns whose recurrenceType"
/// field is set to "yearlyNth" or "yearly".
/// The default value is 1.
/// noEndDate - Boolean, indicates if the recurrence pattern is endless.
/// The default value is True. This field must be coordinated with
/// other fields when setting up a recurrence pattern.
/// If the patternEndDate field or the occurrences field is set,
/// the pattern is considered to be finite and the "noEndDate"
/// field is false.
/// If neither patternEndDate nor occurrences is set,
/// the pattern is considered infinite and "noEndDate" is true.
/// exceptions - Array, holds the list of event objects that
/// define the exceptions to that series of events.
/// Event objects are added to the exceptions whenever a field
/// in the corresponding event object is altered.
/// removedOccurrences - Array, holds the list of event objects
/// removed from that series of events.
};
wijevcal.prototype._testIsEventInTimeInterval = function (appt, start, end) {
if(!start || !end) {
return true;
}
if(appt.start < end && appt.end > start) {
return true;
}
return false;
};
wijevcal.prototype.deleteEvent = /**
* Deletes the event.
* @example
* $("#wijevcal").wijevcal("deleteEvent", eventId);
* @param {number} id
* Event object or event id.
* @param {function} successCallback Function that will be called when event is deleted.
* @param {function} errorCallback Function that will be called when event can not be deleted.(e.g. due to data source or memory problems).
*/
function (id, successCallback, errorCallback) {
if(id.id) {
id = id.id;
}
var o = this._eventsDataById[id], i, appts, deleteEventCallback, deleteEventErrorCallback, self = this, k, masterAppt;
if(!this._trigger("beforeDeleteEvent", null, {
data: o
})) {
return false;
}
this.showLoadingLabel(this.localizeString("activityDeletingEvent", "Deleting event..."));
deleteEventErrorCallback = function (e) {
self.status("Unable to delete event '" + (o ? o.subject : "undefined") + "': " + e);
self.hideLoadingLabel();
if(errorCallback) {
errorCallback(e);
}
};
if(o.recurrenceState === "exception" || o.recurrenceState === "occurrence") {
masterAppt = this._eventsDataById[o.parentRecurrenceId];
if(masterAppt) {
this.log(this._formatString("[deleteEvent] removing {0} with id {1}. Updating master event with id {2}", o.recurrenceState, o.id, masterAppt.id));
if(!masterAppt.recurrencePattern.removedOccurrences) {
masterAppt.recurrencePattern.removedOccurrences = [];
}
masterAppt.recurrencePattern.removedOccurrences.push(o.id);
this.updateEvent(masterAppt, successCallback, errorCallback);
if(o.recurrenceState === "occurrence") {
this.log("No need to delete occurrence from store. Master event should be updated.");
return;
}
} else {
if(o.recurrenceState === "exception") {
//allow delete exception from events storage.
} else {
deleteEventErrorCallback("Unable to find master event with id " + o.parentRecurrenceId);
return false;
}
}
}
if(o.recurrenceState === "master") {
//qq: delete all exceptions from events storage, as well?
}
deleteEventCallback = function (result) {
if(self._handleServerError(result)) {
deleteEventErrorCallback(result);
return;
}
if(self._eventsDataById[o.id]) {
appts = self.options.eventsData;
for(i = 0; i < appts.length; i = i + 1) {
if(appts[i].id === id) {
appts.splice(i, 1);
}
}
delete self._eventsDataById[o.id];
self.status("Event '" + o.subject + "' deleted.");
} else {
self.status("Event '" + o.subject + "' deleted.");
}
o.prevData = self._cloneObj(o);
self._onEventsDataChanged();
self.hideLoadingLabel();
if(successCallback) {
successCallback(result);
}
};
if(this.options.dataStorage.deleteEvent) {
this.options.dataStorage.deleteEvent(o, deleteEventCallback, deleteEventErrorCallback);
} else if(this.options.webServiceUrl) {
try {
k = this._jsonStringify(o);
} catch (ex) {
this.status("Unable prepare event data for server. " + ex, "error");
deleteEventErrorCallback("Unable prepare event data for server. " + ex);
return;
}
$.ajax({
url: this.options.webServiceUrl + "?clientId=" + this.element[0].id + "&command=deleteEvent×tamp=" + new Date().getTime(),
dataType: "text",
contentType: "application/json; charset=utf-8",
type: "POST",
data: "jsonData=" + k,
success: deleteEventCallback,
error: deleteEventErrorCallback
});
} else {
executeSql("DELETE FROM events WHERE id='" + id + "'", [], deleteEventCallback, deleteEventErrorCallback);
}
};
wijevcal.prototype.beginUpdate = /**
* Use beginUpdate and endUpdate when making a large number of changes
* to widget options.
* @example
* $("#wijevcal").wijevcal("beginUpdate");
* $("#wijevcal").wijevcal("option", "timeInterval", 10);
* $("#wijevcal").wijevcal("option", "timeRulerInterval", 20);
* $("#wijevcal").wijevcal("endUpdate");
*/
function () {
this._isUpdating = true;
this.showLoadingLabel("Updating...");
};
wijevcal.prototype.endUpdate = /**
* Use beginUpdate and endUpdate when making a large number of changes
* to widget options.
* @example
* $("#wijevcal").wijevcal("beginUpdate");
* $("#wijevcal").wijevcal("option", "timeInterval", 10);
* $("#wijevcal").wijevcal("option", "timeRulerInterval", 20);
* $("#wijevcal").wijevcal("endUpdate");
*/
function () {
this._isUpdating = false;
if(this._pendingRedrawActiveView) {
this._redrawActiveView();
}
this.hideLoadingLabel();
};
wijevcal.prototype.goToEvent = /**
* Navigates to the event given by the parameter id.
* @example
* $("#wijevcal").wijevcal("goToEvent",
* "apptid_dynid1ts1320322142549");
* @param {object} id Event object or event id.
*/
function (id) {
if(id.id) {
id = id.id;
}
var o = this.options, visual, appt = this.findEventById(id);
switch(o.viewType) {
case "day":
case "week":
case "list":
visual = this.element.find(".wijmo-wijev-dayview .wijmo-wijev-daycolumn ." + this._eventIdToCssClass(id));
if(visual.length > 0) {
this.element.find(".wijmo-wijev-scrollpanel").wijsuperpanel("scrollChildIntoView", visual);
} else {
this._dayViewScrollToEvent = appt;
this.goToDate(appt.start);
}
break;
case "month":
this.goToDate(appt.start);
break;
}
};
wijevcal.prototype.isAllDayEvent = /**
* Tests to see if event duration is more or equals to one day.
* @example
* var isAllDay = $("#wijevcal").wijevcal("isAllDayEvent",
* "apptid_dynid1ts1320322142549");
* @param {object} id Event object or event id.
* @returns {boolean} if event duration is more or equals to one day, return true
*/
function (id) {
var appt = id;
if(!id.id) {
appt = this.findEventById(id);
}
if(appt.allday) {
if((appt.end.getTime() - appt.start.getTime()) / (1000 * 60 * 60 * 24) >= 1) {
return true;
}
return true;
}
return false;
};
wijevcal.prototype.goToDate = /**
* Navigates to the date given by parameter dt.
* @example
* $("#wijevcal").wijevcal("goToDate", new Date());
* @param {Date} dt Javascript date.
*/
function (dt) {
dt = _toDayDate(dt);
var o = this.options, weekDay = dt.getDay(), i, daysCor, dUTC, sdUTC, sd0, selectedDates = o.selectedDates;
if(selectedDates && selectedDates.length > 0) {
if(this._isContainsDayDate(selectedDates, dt)) {
return;
} else {
// fixed 35356 by Daniel.He, caused by "Pacific Daylight Time" 1h offset.
// convert to UTC time dUTC, sdUTC,
sd0 = selectedDates[0];
dUTC = Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate());
sdUTC = Date.UTC(sd0.getFullYear(), sd0.getMonth(), sd0.getDate());
daysCor = (dUTC - sdUTC) / 86400000;
if(o.viewType === "week") {
for(i = 0; i < selectedDates.length; i += 1) {
if(selectedDates[i].getDay() === weekDay) {
daysCor = daysCor - i;
break;
}
}
}
for(i = 0; i < selectedDates.length; i += 1) {
selectedDates[i] = this._addDays(selectedDates[i], daysCor);
}
this._onSelectedDatesChanged();
}
} else {
o.selectedDates = [
dt
];
this._onSelectedDatesChanged();
}
};
wijevcal.prototype.goToTime = /**
* Scrolls view to time given by parameter time.
* @example
* $("#wijevcal").wijevcal("goToTime", new Date());
* @param {Date} time Javascript date.
*/
function (time) {
var firstTimeInervalCell = this.element.find(".wijmo-wijev-daycolumn .wijmo-wijev-timeinterval:first-child"), lastTimeInervalCell = this.element.find(".wijmo-wijev-daycolumn .wijmo-wijev-timeinterval:last-child"), ys = firstTimeInervalCell.position().top, ye = lastTimeInervalCell.position().top + lastTimeInervalCell.height(), yt, tt, te;
te = 24 * 60 * 60;
tt = time.getHours() * 60 * 60 + time.getMinutes() * 60;
yt = (ye - ys) * tt / te + ys;
this.element.find(".wijmo-wijev-scrollpanel").wijsuperpanel("vScrollTo", yt);
};
wijevcal.prototype.goToday = /**
* Navigates to today's date.
* @example
* $("#wijevcal").wijevcal("goToday");
*/
function () {
this.goToDate(new Date());
};
wijevcal.prototype.goLeft = /**
* Navigates to the previous date.
* @example
* $("#wijevcal").wijevcal("goLeft");
*/
function () {
var offset, o = this.options, view = o.viewType, selectedDates = o.selectedDates;
if(view === "month") {
this.goToDate(this._addMonths(selectedDates[0], -1));
} else {
offset = -7;
if(selectedDates.length === 1) {
offset = -1;
}
this.goToDate(this._addDays(selectedDates[0], offset));
}
};
wijevcal.prototype.goRight = /**
* Navigates to the next date.
* @example
* $("#wijevcal").wijevcal("goRight");
*/
function () {
var offset, o = this.options, view = o.viewType, selectedDates = o.selectedDates;
if(view === "month") {
this.goToDate(this._addMonths(selectedDates[0], 1));
} else {
offset = 7;
if(selectedDates.length === 1) {
offset = 1;
}
this.goToDate(this._addDays(selectedDates[0], offset));
}
};
wijevcal.prototype.refresh = /**
* Invalidates the entire surface of the control
* and causes the control to be redrawn.
*/
function () {
this.invalidate();
};
wijevcal.prototype.invalidate = /**
* Invalidates the entire surface of the control
* and causes the control to be redrawn.
*/
function () {
var o = this.options;
switch(o.viewType.toLowerCase()) {
case "list":
case "day":
case "week":
this._invalidateDayView();
break;
case "month":
this._invalidateMonthView();
break;
default:
break;
}
};
wijevcal.prototype.showEditCalendarDialog = /**
* Call this method in order to display built-in "edit calendar" dialog box.
* @example
* Display dialog for a new calendar:
* $("#wijevcal").wijevcal("showEditCalendarDialog", null);
* @param {object} calendar
* Calendar object or calendar name.
* Calendar object fields:
* id - String, unique calendar id, this field generated automatically;
* name - String, calendar name;
* location - String, location field;
* description - String, calendar description;
* color - String, calendar color;
* tag - String, this field can be used to store custom information.
*/
function (calendar) {
var o = this.options, calendars = o.calendars, i;
if(!calendar) {
calendar = {
name: "",
description: "",
location: "",
color: ""
};
} else if(!calendar.name) {
for(i = 0; i < calendars.length; i += 1) {
if(calendars[i].name === calendar) {
calendar = calendars[i];
break;
}
}
}
this._ensureEditCalendarDialogCreated();
this._bindCalendarToDialog(calendar);
this._editCalendarDialog.wijdialog("open");
};
wijevcal.prototype.showEditEventDialog = /**
* Call this method in order to display built-in "edit event" dialog box.
* @example
* Display dialog for a new event:
* $("#wijevcal").wijevcal("showEditEventDialog", null);
* @param {object} calendar
* Event object.
* Event object fields:
* id - String, unique event id, this field generated automatically;
* calendar - String, calendar id to which the event belongs;
* subject - String, event title;
* location - String, event location;
* start - Date, start date/time;
* end - Date, end date/time;
* description - String, event description;
* color - String, event color;
* allday - Boolean, indicates all day event
* tag - String, this field can be used to store custom information.
* @param {object} offsetElement
* Optional.
* DOM element which will be used to calculate dialog position.
*/
function (appt, offsetElement, e) {
var o = this.options, masterAppt, parentColumn, startdt, targetCell = offsetElement ? $(offsetElement) : (e ? $(e.target) : null);
this._ensureEditEventDialogCreated();
this.element.find(".wijmo-wijev-dayview .ui-selected").removeClass("ui-selected");
if(targetCell && targetCell.hasClass("wijmo-wijev-daylabel")) {
targetCell = targetCell.parent(".wijmo-wijev-allday-cell");
}
if(!appt) {
appt = {
subject: this.localizeString("textNewEvent", "New event")
};
appt.isNewEvent = true;
if(targetCell && targetCell.length > 0) {
this._editEventDialog._arrowTarget = targetCell;
targetCell.addClass("ui-selected");
parentColumn = targetCell.parent(".wijmo-wijev-daycolumn");
if(parentColumn.length < 1) {
parentColumn = targetCell.parent(".wijmo-wijev-dayheadercolumn");
}
parentColumn = parentColumn[0];
//wijmo-wijev-allday-cell
if(targetCell.hasClass("wijmo-wijev-allday-cell")) {
appt.allday = true;
} else if(targetCell.hasClass("wijmo-wijev-monthcellcontainer")) {
parentColumn = targetCell[0];
appt.allday = true;
} else {
appt.allday = false;
}
if(parentColumn) {
startdt = this._parseDateFromClass(parentColumn.className, appt.allday ? null : targetCell[0].className);
appt.start = startdt;
if(appt.allday) {
appt.end = this._addMinutes(appt.start, 60 * 24);
} else {
appt.end = this._addMinutes(appt.start, o.timeInterval);
}
}
} else {
appt.start = new Date(o.selectedDates[0]);
appt.end = this._addMinutes(appt.start, o.timeInterval);
}
} else {
this._editEventDialog._arrowTarget = targetCell;
if(appt.recurrenceState === "occurrence") {
masterAppt = this._eventsDataById[appt.parentRecurrenceId];
if(window.confirm(this._formatString(this.localizeString("promptOpenOccurrenceFormat", "{2} is recurring event. Do you want to open only this occurrence?"), appt.start, appt.end, appt.subject, appt.location))) {
// edit exception: set inside addEvent/updateEvent method
//appt.recurrenceState = "exception";
} else {
// edit master event:
appt = masterAppt;
}
}
/*
if (appt.recurrenceState === "exception") {
//alert("Exception found:" + appt.id);
}*/
}
if(this._trigger("beforeEditEventDialogShow", null, {
data: appt,
targetCell: targetCell
})) {
this._bindApptToDialog(appt);
this._editEventDialog.wijpopup("show", {
of: targetCell,
my: "left center",
at: "right center",
offset: (targetCell && e ? Math.round(e.offsetX - targetCell.width()) : 10) + " 0",
collision: "fit"
});
}
};
wijevcal.prototype._renderActiveView = /** Private methods */
// render views
function () {
var o = this.options, toolsBar = this.element.find(".wijmo-wijev-headerbar .wijmo-wijev-tools");
this.element.find(".wijmo-wijev-view").hide();
this.element.find(".wijmo-wijev-viewdetails").hide();
this.element.find(".wijmo-wijev-" + o.viewType.toLowerCase() + "-details").show();
switch(o.viewType.toLowerCase()) {
case "day":
case "week":
case "list":
this.element.find(".wijmo-wijev-view.wijmo-wijev-dayview").show();
this._renderDayView();
break;
case "month":
this.element.find(".wijmo-wijev-view.wijmo-wijev-monthview").show();
this._renderMonthView();
break;
default:
break;
}
toolsBar.find(".wijmo-wijev-" + o.viewType.toLowerCase())[0]["checked"] = true;
if($().buttonset) {
toolsBar.buttonset("refresh");
}
};
wijevcal.prototype._redrawActiveView = function () {
if(this._isUpdating) {
this._pendingRedrawActiveView = true;
return;
}
switch(this.options.viewType.toLowerCase()) {
case "day":
case "week":
this._clearDayViewCache();
this._templateDayColumn = null;
break;
}
this._renderActiveView();
};
wijevcal.prototype._getDayColumnDates = /* DAY(S)/WEEK view*/
function (updateSelectedDates) {
var o = this.options, columnDates = o.selectedDates, startDt, dt, i;
if(!columnDates) {
columnDates = [
new Date()
];
}
if(o.viewType === "week") {
startDt = o.selectedDate || columnDates[0];
i = o.firstDayOfWeek - startDt.getDay();
if(Math.abs(i) > 6) {
i = startDt.getDay() - o.firstDayOfWeek;
}
startDt = this._addDays(startDt, i);
columnDates = [];
for(i = 0; i < 7; i += 1) {
dt = this._addDays(startDt, i);
columnDates.push(dt);
}
}
if(updateSelectedDates) {
o.selectedDates = columnDates;
}
return columnDates;
};
wijevcal.prototype._renderDayView = function () {
var o = this.options, curMinute = 0, lastMinute = 24 * 60, s, cellClass, timeRulerCellClass, columnDates = this._getDayColumnDates(true), i, curDayHeader, curDayColumn, curDayDate, todayDate = new Date(), columnCount, skipNextBorder = false, dayview = this.element.find(".wijmo-wijev-dayview"), headercontainer, scrollcontent, timeruler, curTimeRulerInterval = 0, isOddRow;
if(dayview.length === 0) {
dayview = $("<div class=\"wijmo-wijev-view wijmo-wijev-dayview " + o.wijCSS.content + "\">" + "<h3 class=\"wijmo-wijev-header-title\">title" + "</h3>" + "<div class=\"wijmo-wijev-dayview-inner\">" + "<div class=\"wijmo-wijev-headercontainer\">" + "<div class=\"wijmo-wijev-sizer\">" + "<div class=\"wijmo-wijev-gmtlabel\">" + this.localizeString("labelAllDay", "all-day") + /*GMT" +
(new Date().getTimezoneOffset() / 60) +*/
"</div>" + "</div>" + "</div>" + "<div class=\"wijmo-wijev-scrollpanel\">" + "<div class=\"wijmo-wijev-scrollcontent\">" + "<div class=\"wijmo-wijev-timeruler\">" + "<div class=\"wijmo-wijev-currenttime-indicator\">" + "<div class=\"wijmo-wijev-currenttime-indicator-arrow ui-state-error\"></div>" + "<div class=\"wijmo-wijev-currenttime-indicator-line ui-state-error\"></div>" + "</div>" + "</div>" + "</div>" + "</div>" + "</div>" + "</div>");
dayview.appendTo(this.element.find(".wijmo-wijev-view-container"));
this.element.find(".wijmo-wijev-scrollpanel").wijsuperpanel({
hScroller: {
scrollBarVisibility: "hidden"
},
animationOptions: {
disabled: true
}
});
}
dayview.removeClass("wijmo-wijev-weekview wijmo-wijev-listview");
dayview.addClass("wijmo-wijev-" + o.viewType.toLowerCase() + "view");
headercontainer = this.element.find(".wijmo-wijev-headercontainer");
scrollcontent = this.element.find(".wijmo-wijev-scrollcontent");
timeruler = scrollcontent.find(".wijmo-wijev-timeruler");
if(!this._templateDayColumn) {
timeruler.find(".wijmo-wijev-timerulerinterval").remove();
s = "<div class=\"wijmo-wijev-daycolumn\">";
isOddRow = true;
while(curMinute < lastMinute) {
cellClass = "wijmo-wijev-timeinterval " + o.wijCSS.content + " wijmo-wijev-minute-" + curMinute;
if(isOddRow) {
cellClass += " wijmo-wijev-oddrow";
}
isOddRow = !isOddRow;
timeRulerCellClass = "wijmo-wijev-timerulerinterval " + o.wijCSS.content + " wijmo-wijev-minute-" + curMinute;
s += "<div class=\"" + cellClass + "\" style=\"height: " + o.timeIntervalHeight + "px\"></div>";
curMinute += o.timeInterval;
curTimeRulerInterval += o.timeInterval;
if(curTimeRulerInterval >= o.timeRulerInterval) {
cellClass += " wijmo-wijev-timeinterval-hourstart";
timeRulerCellClass += " wijmo-wijev-timerulerinterval-hourstart";
timeruler.append($("<div class=\"" + timeRulerCellClass + "\" style=\"height:" + (curTimeRulerInterval / o.timeInterval) * o.timeIntervalHeight + "px\">" + this._formatString(o.timeRulerFormat, new Date(todayDate.getFullYear(), todayDate.getMonth(), todayDate.getDate(), 0, (curMinute - curTimeRulerInterval))) + "</div>"));
curTimeRulerInterval = 0;
}
}
s += "</div>";
this._templateDayColumn = $(s);
this._templateDayHeader = $("<div class=\"wijmo-wijev-dayheadercolumn " + o.wijCSS.content + "\">" + //
//left: 82px; right: 34px; top: 8px; height: 26px;
"<div class=\"wijmo-wijev-allday-cell " + o.wijCSS.content + "\">" + "<div class=\"wijmo-wijev-daylabel\">3 Monday</div>" + /*"<div class=\"wijmo-wijev-allday-label ui-priority-secondary\">all-day events</div>" +*/
"</div>" + "</div>");
}
headercontainer.find(".wijmo-wijev-dayheadercolumn").remove();
scrollcontent.find(".wijmo-wijev-daycolumn").remove();
for(i = 0 , columnCount = columnDates.length; i < columnCount; i = i + 1) {
curDayDate = columnDates[i];
curDayHeader = this._getCachedDayHeader(curDayDate);
curDayColumn = this._getCachedDayColumn(curDayDate);
if(!curDayHeader) {
curDayHeader = this._templateDayHeader.clone(true);
curDayColumn = this._templateDayColumn.clone(true);
curDayHeader.addClass(this._dayDateToCssClass(curDayDate));
curDayHeader.find(".wijmo-wijev-daylabel").html(this._formatDayHeaderDate(curDayDate));
curDayColumn.addClass(this._dayDateToCssClass(curDayDate));
if(skipNextBorder) {
skipNextBorder = false;
} else {
curDayColumn.addClass("wijmo-wijev-leftborder");
curDayHeader.addClass("wijmo-wijev-leftborder");
}
if(this._compareDayDates(curDayDate, todayDate) === 0) {
curDayColumn.addClass("wijmo-wijev-today ui-state-highlight");
curDayColumn.addClass("wijmo-wijev-leftborder");
curDayColumn.addClass("wijmo-wijev-rightborder");
curDayHeader.addClass("wijmo-wijev-today").find(".wijmo-wijev-allday-cell").addClass("ui-state-highlight");
curDayHeader.addClass("wijmo-wijev-leftborder");
curDayHeader.addClass("wijmo-wijev-rightborder");
skipNextBorder = true;
}
if(i === columnCount - 1) {
curDayColumn.addClass("wijmo-wijev-rightborder");
curDayHeader.addClass("wijmo-wijev-rightborder");
}
} else {
curDayHeader = $(curDayHeader);
curDayHeader.find(".wijmo-wijev-daylabel").html(this._formatDayHeaderDate(curDayDate));
}
headercontainer.append(curDayHeader);
scrollcontent.append(curDayColumn);
}
this._invalidateDayView();
this._renderDayViewAppointments();
};
wijevcal.prototype._getCachedDayHeader = // view cache>>
function (dt) {
var h = null;
if(this._dayViewCache) {
if(this._dayViewCache[dt]) {
h = this._dayViewCache[dt].h;
}
}
return h;
};
wijevcal.prototype._getCachedDayColumn = function (dt) {
var c = null;
if(this._dayViewCache) {
if(this._dayViewCache[dt]) {
c = this._dayViewCache[dt].c;
}
}
return c;
};
wijevcal.prototype._storeDayCache = function (dt, h, c) {
if(!this._dayViewCache) {
this._dayViewCache = {
};
}
this._dayViewCache[dt] = {
"h": h,
"c": c
};
};
wijevcal.prototype._clearViewsCache = function () {
this._clearDayViewCache();
this._clearListViewCache();
};
wijevcal.prototype._clearDayViewCache = function () {
this._dayViewCache = {
};
};
wijevcal.prototype._clearListViewCache = function () {
var $agendaList = this.element.find(".wijmo-wijev-list-details .wijmo-wijev-agenda-container .wijmo-wijsuperpanel-templateouterwrapper");
// fixed the issue in IE10.
if(!$agendaList[0]) {
$agendaList = this.element.find(".wijmo-wijev-list-details .wijmo-wijev-agenda-container .wijmo-wijsuperpanel-contentwrapper-touch");
}
$agendaList.data("wijevcal_agenda_initialized", false);
$agendaList.data("wijevcal_agenda_loadedeventscount", 0);
};
wijevcal.prototype._invalidateDayView = //<< end of views cache
function (scrollHeightOnly) {
var headercontainer = this.element.find(".wijmo-wijev-headercontainer"), scrollcontent = this.element.find(".wijmo-wijev-scrollcontent"), timeruler = scrollcontent.find(".wijmo-wijev-timeruler"), dayHeaderColumns = headercontainer.find(".wijmo-wijev-dayheadercolumn"), dayColumns = scrollcontent.find(".wijmo-wijev-daycolumn"), title = this.element.find(".wijmo-wijev-view .wijmo-wijev-header-title"), headerTitleH, viewWidth, allDayCellH, allDayApptH, allDayLabelH, maxAllDayApptCount, curAllDayApptCount, timeRulerOuterWidth = timeruler.outerWidth(), i, dayscontainerWidth, dayscontainerHeight, columnOuterWidth, scrollpanel;
this._updateHeaderTitleText()// ensure header title visibility
;
headerTitleH = title.is(":visible") ? title.outerHeight(true) : 0;
this._invalidateView();
if(!this._maxAllDayEventCount) {
this._maxAllDayEventCount = 0;
}
allDayApptH = headercontainer.find(".wijmo-wijev-dayheadercolumn .wijmo-wijev-appointment").outerHeight(true);
if(!allDayApptH) {
allDayApptH = 17;
}
allDayLabelH = headercontainer.find(".wijmo-wijev-daylabel").outerHeight(true);
maxAllDayApptCount = 0;
for(i = 0; i < dayHeaderColumns.length; i += 1) {
curAllDayApptCount = $(dayHeaderColumns[i]).find(".wijmo-wijev-allday-cell .wijmo-wijev-appointment").length;
if(curAllDayApptCount > maxAllDayApptCount) {
maxAllDayApptCount = curAllDayApptCount;
}
}
allDayCellH = allDayApptH * maxAllDayApptCount + allDayLabelH + allDayApptH;
headercontainer.outerHeight(allDayCellH + Math.round(allDayApptH / 2));
headercontainer.find(".wijmo-wijev-allday-cell").outerHeight(allDayCellH);
viewWidth = this.element.find(".wijmo-wijev-view").innerWidth();
dayscontainerWidth = viewWidth - timeRulerOuterWidth;
dayscontainerWidth = dayscontainerWidth - 18//vertical scrollbar width
;
dayscontainerHeight = this.element.find(".wijmo-wijev-view").innerHeight() - headercontainer.outerHeight(true) - headerTitleH;
columnOuterWidth = Math.floor(dayscontainerWidth / dayColumns.length);
headercontainer.outerWidth(viewWidth);
scrollcontent.outerWidth(viewWidth);
dayHeaderColumns.outerWidth(columnOuterWidth);
dayColumns.outerWidth(columnOuterWidth);
this._invalidateCurrentTimeIndicator();
scrollpanel = this.element.find(".wijmo-wijev-scrollpanel");
scrollpanel.outerWidth(viewWidth);
scrollpanel.outerHeight(dayscontainerHeight);
scrollpanel.wijsuperpanel("refresh");
switch(this.options.viewType.toLowerCase()) {
case "day":
this._updateDayViewDetails();
break;
case "list":
this._updateListViewDetails();
break;
}
};
wijevcal.prototype._updateDayViewDetails = /* view details */
function () {
var o = this.options, selectedDate = o.selectedDate, leftPane = this.element.find(".wijmo-wijev-leftpane"), agendaContainer = leftPane.find(".wijmo-wijev-agenda-container");
if(!this._dayViewDetailsInit) {
this._dayViewDetailsInit = true;
this.element.find(".wijmo-wijev-day-details .wijmo-wijev-daycalendar").wijcalendar({
culture: o.culture,
titleFormat: this.localizeString("calendarTitleFormat", "MMMM yyyy"),
toolTipFormat: this.localizeString("calendarToolTipFormat", "dddd, MMMM dd, yyyy"),
showTitle: false,
showOtherMonthDays: false,
showWeekNumbers: false,
selectionMode: {
day: true,
days: false
},
selectedDatesChanged: $.proxy(function (e, args) {
if(args.dates && !o.disabled) {
this.goToDate(args.dates[0]);
}
}, this),
nextTooltip: this.localizeString("calendarNextTooltip", "Next"),
prevTooltip: this.localizeString("calendarPrevTooltip", "Previous")
});
this.element.find(".wijmo-wijev-day-details .wijmo-wijev-agenda-container").wijsuperpanel();
}
this.element.find(".wijmo-wijev-day-details .wijmo-wijev-daycalendar").wijcalendar("option", "displayDate", selectedDate).wijcalendar("unSelectAll").wijcalendar("selectDate", selectedDate);
this.element.find(".wijmo-wijev-day-details .wijmo-wijev-daycalendar").wijcalendar("refresh");
this.element.find(".wijmo-wijev-day-details .wijmo-wijev-monthday-label").html(selectedDate.getDate());
this.element.find(".wijmo-wijev-day-details .wijmo-wijev-fulldate-label").html(this._formatString(this.localizeString("dayDetailsLabelFulldateFormat", "{0:dddd, MMMM d}"), selectedDate));
//Tuesday, November 1
this.element.find(".wijmo-wijev-day-details .wijmo-wijev-year-label").html(this._formatString(this.localizeString("dayDetailsLabelYearFormat", "{0:yyyy}"), selectedDate));
//selectedDate.getFullYear()
this._updateAgendaList(this.element.find(".wijmo-wijev-day-details .wijmo-wijev-agenda-container"), selectedDate, selectedDate, false);
};
wijevcal.prototype._listViewAgendaScrolled = function (e, data) {
var supPanel = this.element.find(".wijmo-wijev-list-details .wijmo-wijev-agenda-container"), vScroller = supPanel.wijsuperpanel("option", "vScroller"), $agendaList, scrollValue = vScroller.scrollValue, scrollMax = vScroller.scrollMax - vScroller.scrollLargeChange * 2, eventType = e.type, isEnd = false, position;
// in IE10, the superpanel's event is scroll.
if(eventType === "wijsuperpanelscroll") {
position = data.position;
$agendaList = supPanel.find(".wijmo-wijsuperpanel-contentwrapper-touch");
if(supPanel.height() + position >= $agendaList.height()) {
isEnd = true;
}
} else {
$agendaList = supPanel.find(".wijmo-wijsuperpanel-templateouterwrapper");
}
if(scrollValue >= scrollMax || isEnd) {
if($agendaList.data("wijevcal_agenda_loadnextpage")) {
$agendaList.data("wijevcal_agenda_loadnextpage", false);
$agendaList.find(".wijmo-wijev-agenda-more-events").show().html(this.localizeString("agendaLoadingMoreEvents", "Loading more events..."));
if(this._renderAgendaEventsTimeoutId) {
clearTimeout(this._renderAgendaEventsTimeoutId);
this._renderAgendaEventsTimeoutId = null;
}
this._renderAgendaEventsTimeoutId = setTimeout($.proxy(function () {
this._renderAgendaEventsTimeoutId = null;
this._renderAgendaEvents($agendaList, null, null, true);
// fix for 29488:
$agendaList.find(".wijmo-wijev-agenda-more-events").remove();
}, this), 100);
}
}
};
wijevcal.prototype._updateListViewDetails = function () {
if(!this._listViewDetailsInit) {
this._listViewDetailsInit = true;
if($.support.isTouchEnabled && $.support.isTouchEnabled()) {
this.element.find(".wijmo-wijev-list-details .wijmo-wijev-agenda-container").wijsuperpanel({
scroll: $.proxy(this._listViewAgendaScrolled, this)
});
//scrolling
} else {
this.element.find(".wijmo-wijev-list-details .wijmo-wijev-agenda-container").wijsuperpanel({
scrolled: $.proxy(this._listViewAgendaScrolled, this)
});
//scrolling
}
}
this._updateAgendaList(this.element.find(".wijmo-wijev-list-details .wijmo-wijev-agenda-container"), null, null, true);
};
wijevcal.prototype._updateAgendaList = function (agendaContainer, startDt, endDt, listViewMode) {
var leftPane = this.element.find(".wijmo-wijev-leftpane"), $agendaList = agendaContainer;
///////////
// invalidate agenda height when text is changed(fix for 21282):
agendaContainer.outerHeight(leftPane.innerHeight() - agendaContainer[0].offsetTop);
if($agendaList.find(".wijmo-wijsuperpanel-templateouterwrapper").length > 0) {
$agendaList = $agendaList.find(".wijmo-wijsuperpanel-templateouterwrapper");
}
if($.support.isTouchEnabled && $.support.isTouchEnabled()) {
$agendaList = $agendaList.find(".wijmo-wijsuperpanel-contentwrapper-touch");
}
if(listViewMode && $agendaList.data("wijevcal_agenda_initialized")) {
/*fix for 24623 */
$agendaList.parents(".wijmo-wijsuperpanel").wijsuperpanel("refresh");
return;
}
$agendaList.data("wijevcal_agenda_initialized", true);
$agendaList.data("wijevcal_agenda_loadedeventscount", 0);
/////////
$agendaList.html("");
this._renderAgendaEvents($agendaList, startDt, endDt, listViewMode);
};
wijevcal.prototype._renderAgendaEvents = function ($agendaList, startDt, endDt, listViewMode) {
var appts = this._eventsView, appt, i, apptsCount, daysCount, dayIdx = 0, curDayApptsCount, s = "", s2 = "", viewStart = null, viewEnd = null, o = this.options, curDayStart, curDayEnd, eventsPerPage = 100, loadedEventsCount = $agendaList.data("wijevcal_agenda_loadedeventscount");
if(startDt) {
viewStart = _toDayDate(startDt);
viewEnd = this._addDays(_toDayDate(endDt), 1);
daysCount = (viewEnd.getTime() - viewStart.getTime()) / (1000 * 60 * 60 * 24);
}
if(appts) {
apptsCount = (appts.length < (eventsPerPage + loadedEventsCount) || !listViewMode) ? appts.length : (eventsPerPage + loadedEventsCount);
$agendaList.data("wijevcal_agenda_loadedeventscount", apptsCount);
if(!viewStart) {
s2 = "";
for(i = loadedEventsCount; i < apptsCount; i += 1) {
appt = appts[i];
if(i === loadedEventsCount || curDayStart.getDate() !== appt.start.getDate()) {
curDayStart = appt.start;
if(i !== 0) {
s += "<ul class=\"wijmo-wijev-agenda-list\">" + s2 + "</ul>";
s += "</div>";
}
s += "<div class=\"wijmo-wijev-agenda-day-container " + this._dayDateToCssClass(curDayStart) + "\">";
if(listViewMode) {
s += this._renderAgendaDayHeader(curDayStart);
}
s2 = "";
}
s2 += this._renderAgendaAppointmentVisual(appt);
curDayApptsCount += 1;
if(i === apptsCount - 1) {
s += "<ul class=\"wijmo-wijev-agenda-list\">" + s2 + "</ul>";
s += "</div>";
if(apptsCount < appts.length) {
s += "<div class=\"wijmo-wijev-agenda-more-events\">";
s += this._formatString(this.localizeString("agendaMoreEventsFormat", "More events ({0})..."), (appts.length - apptsCount));
s += "<div>";
$agendaList.data("wijevcal_agenda_loadnextpage", true);
} else {
$agendaList.data("wijevcal_agenda_loadnextpage", false);
}
}
}
} else {
while(dayIdx < daysCount) {
curDayStart = this._addDays(viewStart, dayIdx);
curDayStart = new Date(curDayStart.getFullYear(), curDayStart.getMonth(), curDayStart.getDate());
curDayEnd = new Date(curDayStart.getFullYear(), curDayStart.getMonth(), curDayStart.getDate(), 23, 59, 59);
curDayApptsCount = 0;
s2 = "";
for(i = loadedEventsCount; i < apptsCount; i += 1) {
appt = appts[i];
if((appt.start < viewEnd && appt.end > viewStart) && (appt.start < curDayEnd && appt.start >= curDayStart)) {
s2 += this._renderAgendaAppointmentVisual(appt);
curDayApptsCount += 1;
}
}
if(s2 !== "") {
s += "<div class=\"wijmo-wijev-agenda-day-container " + this._dayDateToCssClass(curDayStart) + "\">";
if(listViewMode) {
s += this._renderAgendaDayHeader(curDayStart);
}
s += "<ul class=\"wijmo-wijev-agenda-list\">" + s2 + "</ul>";
s += "</div>";
}
dayIdx += 1;
}
}
$(s).appendTo($agendaList);
}
$agendaList.on("click", ".wijmo-wijev-agenda-event", $.proxy(this._onAgendaEventClick, this)).on("mouseover", ".wijmo-wijev-agenda-event", function (e) {
$(this).addClass(o.wijCSS.stateHover);
}).on("mouseout", ".wijmo-wijev-agenda-event", function (e) {
$(this).removeClass(o.wijCSS.stateHover).removeClass(o.wijCSS.stateActive);
}).on("mousedown", ".wijmo-wijev-agenda-event", function () {
$(this).addClass(o.wijCSS.stateActive);
}).on("mouseup", ".wijmo-wijev-agenda-event", function () {
$(this).removeClass(o.wijCSS.stateActive);
});
$agendaList.parents(".wijmo-wijsuperpanel").wijsuperpanel("refresh");
};
wijevcal.prototype._renderAgendaDayHeader = function (curDayStart) {
var s = "<div class=\"wijmo-wijev-agenda-header ui-widget-header\">" + "<div class=\"wijmo-wijev-weekday\">" + this._formatString("{0:dddd}", curDayStart) + "</div>" + "<div class=\"wijmo-wijev-date\">" + this._formatString(this.localizeString("agendaHeaderFullDateFormat", "{0:MMMM d, yyyy}"), curDayStart) + "</div>" + "</div>";
return s;
};
wijevcal.prototype._onAgendaEventClick = function (e) {
var target = $(e.target);
if(!target.hasClass("wijmo-wijev-agenda-event")) {
target = target.parent(".wijmo-wijev-agenda-event");
}
if(target.length > 0) {
//alert(this._parseEventIdFromClass(target[0].className) + "," + target[0].className);
this.goToEvent(this._parseEventIdFromClass(target[0].className));
//this.goToDate(this._parseDateFromClass(target[0].className));
}
};
wijevcal.prototype._renderAgendaAppointmentVisual = function (ev) {
var s = "<li class=\"wijmo-wijev-agenda-event " + this._dayDateToCssClass(ev.start) + " " + this._eventIdToCssClass(ev.id) + " " + this.options.wijCSS.stateDefault + " ui-helper-clearfix\">" + "<div class=\"wijmo-wijev-agenda-event-color " + "wijmo-wijev-event-color-" + (ev.color || "default") + "\">" + "<div></div>" + "</div>" + "<div class=\"wijmo-wijev-agenda-event-title\">" + ev.subject + "</div>" + "<div class=\"wijmo-wijev-agenda-event-time\">" + (this.isAllDayEvent(ev) ? this.localizeString("labelAllDay", "all-day") : this._formatString(this.localizeString("agendaTimeFormat", "{0:hh:mm tt} to {1:hh:mm tt}"), ev.start, ev.end)) + "</div>" + "</li>";
return s;
};
wijevcal.prototype._invalidateCurrentTimeIndicator = //wijmo-wijev-day-details
function () {
var timeInicator = this.element.find(".wijmo-wijev-timeruler .wijmo-wijev-currenttime-indicator"), curTime = new Date(), o = this.options;
curTime = curTime.getMinutes() + curTime.getHours() * 60;
timeInicator.css("top", (curTime / o.timeInterval) * o.timeIntervalHeight);
};
wijevcal.prototype._onEventsDataChanged = // <- end of day view
function () {
this._clearViewsCache();
this._prepareEventsForView();
this._renderActiveView();
this._trigger("eventsDataChanged", null, {
eventsData: this.options.eventsData
});
};
wijevcal.prototype._onCalendarsChanged = function () {
this._trigger("calendarsChanged", null, {
calendars: this.options.calendars
});
};
wijevcal.prototype._renderDayViewAppointments = function () {
var appts = this._eventsView, appt, i, j, apptsCount, daysCount, headercontainer = this.element.find(".wijmo-wijev-headercontainer"), scrollcontent = this.element.find(".wijmo-wijev-scrollcontent"), dayHeaderColumns = headercontainer.find(".wijmo-wijev-dayheadercolumn"), dayColumns = scrollcontent.find(".wijmo-wijev-daycolumn"), curDayStart, curDayEnd, o = this.options, columnDates = this._getDayColumnDates(), viewStart = columnDates[0], viewEnd, allDayCellChanged, apptVisual, visualStartDt, visualEndDt, visualStartMin, visualEndMin, visualStartPx, visualEndPx, conflictColumns = [];
viewEnd = columnDates[columnDates.length - 1];
viewEnd = new Date(viewEnd.getFullYear(), viewEnd.getMonth(), viewEnd.getDate(), 23, 59, 59);
if(appts) {
for(j = 0 , daysCount = columnDates.length; j < daysCount; j += 1) {
if(!dayColumns[j]._cached) {
curDayStart = columnDates[j];
curDayStart = new Date(curDayStart.getFullYear(), curDayStart.getMonth(), curDayStart.getDate());
curDayEnd = new Date(curDayStart.getFullYear(), curDayStart.getMonth(), curDayStart.getDate(), 23, 59, 59);
for(i = 0 , apptsCount = appts.length; i < apptsCount; i += 1) {
appt = appts[i];
if((appt.start < viewEnd && appt.end > viewStart) && (appt.start < curDayEnd && appt.end > curDayStart)) {
if(this.isAllDayEvent(appt)) {
allDayCellChanged = true;
apptVisual = $(this._getAllDayEventMarkup(appt));
$(dayHeaderColumns[j]).find(".wijmo-wijev-allday-cell").append(apptVisual);
} else {
visualStartDt = appt.start;
visualEndDt = appt.end;
if(visualStartDt < curDayStart) {
visualStartDt = curDayStart;
}
if(visualEndDt > curDayEnd) {
visualEndDt = curDayEnd;
}
visualStartMin = (((visualStartDt - curDayStart) / 1000) / 60);
visualEndMin = (((visualEndDt - curDayStart) / 1000) / 60);
visualStartPx = Math.round(visualStartMin * o.timeIntervalHeight / o.timeInterval);
visualEndPx = Math.round(visualEndMin * o.timeIntervalHeight / o.timeInterval);
apptVisual = $(this._getEventMarkup(appt));
apptVisual.css("top", visualStartPx);
apptVisual.outerHeight(visualEndPx - visualStartPx);
$(dayColumns[j]).append(apptVisual);
}
}
}//<for (i = 0
//
this._storeDayCache(columnDates[j], dayHeaderColumns[j], dayColumns[j]);
dayColumns[j]._cached = true;
conflictColumns.push(dayColumns[j]);
} else//<if(!dayColumns[j]._cached
{
// fix for 30112 case 1:
conflictColumns.push(dayColumns[j]);
}
}//<for (j = 0
}
this._dayColumnsToResolve = conflictColumns;
this._dayColumnResolveIdx = 0;
if(!this._resolveDayApptConflictsTimeout) {
clearTimeout(this._resolveDayApptConflictsTimeout);
this._resolveDayApptConflictsTimeout = null;
}
this._resolveDayApptConflictsTimeout = setTimeout($.proxy(this._resolveDayViewAppointmentConflictsCb1, this), 1);
// adjust scroll height according new all day cells height:
if(allDayCellChanged) {
this._invalidateDayView(true);
}
if(this._dayViewScrollToEvent) {
apptVisual = this.element.find(".wijmo-wijev-dayview .wijmo-wijev-daycolumn ." + this._eventIdToCssClass(this._dayViewScrollToEvent.id));
if(apptVisual.length > 0) {
this.element.find(".wijmo-wijev-scrollpanel").wijsuperpanel("scrollChildIntoView", apptVisual);
}
//this._dayViewScrollToEvent = null;
}
};
wijevcal.prototype._getAllDayEventMarkup = function (appt) {
return "<div class=\"wijmo-wijev-appointment " + this._eventIdToCssClass(appt.id) + "\">" + "<div class=\"" + " wijmo-wijev-colordot wijmo-wijev-event-color-" + (appt.color || "default") + "\"></div>" + "<div class=\"wijmo-wijev-event-title\">" + appt.subject + "</div>" + "</div>";
};
wijevcal.prototype._getEventMarkup = function (appt) {
return "<div class=\"wijmo-wijev-appointment wijmo-wijev-event-color-" + (appt.color || "default") + " " + this._eventIdToCssClass(appt.id) + "\">" + "<div class=\"wijmo-wijev-content\"><div class=\"wijmo-wijev-title\">" + this._formatString(this.options.eventTitleFormat, appt.start, appt.end, appt.subject, appt.location, "", appt.description/*"<strong>ICONS</strong>"*/ ) + "</div></div>" + "<div class=\"wijmo-wijev-resizer\">" + "<div class=\"ui-icon ui-icon-grip-solid-horizontal\">" + " </div></div>" + "</div>";
};
wijevcal.prototype._resolveDayViewAppointmentConflictsCb1 = function () {
this._resolveDayApptConflictsTimeout = null;
if(!this._dayColumnsToResolve || this._dayColumnResolveIdx >= this._dayColumnsToResolve.length) {
return;
}
this._resolveDayViewAppointmentConflicts(this._dayColumnsToResolve[this._dayColumnResolveIdx]);
this._dayColumnResolveIdx = this._dayColumnResolveIdx + 1;
setTimeout($.proxy(this._resolveDayViewAppointmentConflictsCb1, this), 1);
};
wijevcal.prototype._resolveDayViewAppointmentConflicts = function (col) {
var eventsData = $(col).find(".wijmo-wijev-appointment"), eventDataArray, intersections = [], arr1, i, j, appt1, appt2, count1, count2, v, startIndex = 0;
eventDataArray = $(eventsData).toArray().sort(this._sortOffsetTop);
for(i = 0 , count1 = eventsData.length; i < count1; i += 1) {
if(i < startIndex) {
continue;
}
appt1 = eventDataArray[i];
for(j = i; j < count1; j += 1) {
if(j !== i) {
appt2 = eventDataArray[j];
if((appt1.offsetTop) < (appt2.offsetTop + appt2.offsetHeight) && (appt1.offsetTop + appt1.offsetHeight) > appt2.offsetTop) {
if(!intersections[i]) {
intersections[i] = [
appt1
];
}
intersections[i].push(appt2);
appt1 = appt2;
} else {
break;
}
}
}
startIndex = j;
}
for(i = 0 , count1 = intersections.length; i < count1; i += 1) {
arr1 = intersections[i];
if(arr1) {
count2 = arr1.length;
arr1.sort(this._sortOffsetTop);
for(j = 0; j < count2; j += 1) {
appt1 = arr1[j];
appt1.style.width = Math.floor(100 / count2) + "%";
v = Math.floor(100 * j / count2);
appt1.style.marginLeft = v + "%";
appt1.style.zIndex = v;
}
}
}
};
wijevcal.prototype._sortOffsetTop = function (a, b) {
if(a.offsetTop < b.offsetTop) {
return -1;
} else if(a.offsetTop > b.offsetTop) {
return 1;
}
return 0;
};
wijevcal.prototype._onDayViewTimeIntervalClick = // day view time interval
function (e) {
if(this.options.readOnly) {
return;
}
this.showEditEventDialog(null, e.target, e);
};
wijevcal.prototype._onDayViewAllDayCellClick = function (e) {
if(this.options.readOnly) {
return;
}
var targetAppt = $(e.target);
if(targetAppt.hasClass("wijmo-wijev-appointment") || targetAppt.parents(".wijmo-wijev-appointment").length > 0) {
return;
}
if((targetAppt.hasClass("wijmo-wijev-daylabel") || targetAppt.parents(".wijmo-wijev-daylabel").length > 0)) {
return;
}
//
this.showEditEventDialog(null, e.target, e);
};
wijevcal.prototype._onMonthViewDayLabelClick = function (e) {
var monthcellcontainer = $(e.target).parents(".wijmo-wijev-monthcellcontainer"), o = this.options, cellDate;
if(monthcellcontainer.length < 1) {
monthcellcontainer = $(e.target).parents(".wijmo-wijev-dayheadercolumn");
}
//
if(monthcellcontainer[0]) {
cellDate = this._parseDateFromClass(monthcellcontainer[0].className);
if(o.viewType !== "day") {
o.viewType = "day";
this._onViewTypeChanged();
}
o.selectedDates = [
new Date(cellDate)
];
this._onSelectedDatesChanged();
}
};
wijevcal.prototype._onMonthViewCellClick = function (e) {
var monthcellcontainer = $(e.target).parent(".wijmo-wijev-monthcellcontainer");
if(this.options.readOnly) {
return;
}
if(monthcellcontainer.length < 1) {
return;
}
this.showEditEventDialog(null, monthcellcontainer, e);
};
wijevcal.prototype._onAppointmentClick = function (e) {
var target = $(e.target), appt;
if(this.options.readOnly) {
return;
}
if(this._apptDragResizeFlag) {
return;
}
if(!target.hasClass("wijmo-wijev-appointment")) {
target = target.parents(".wijmo-wijev-appointment");
}
if(target.length > 0) {
appt = this.findEventById(target[0].className);
this.showEditEventDialog(appt, target, e);
}
};
wijevcal.prototype.findEventById = /** Find event object by id
* @returns {object} events data.
*/
function (id) {
var i;
if(id) {
i = id.indexOf("apptid_");
if(i !== -1) {
id = this._parseEventIdFromClass(id);
}
if(this._eventsDataById) {
return this._eventsDataById[id];
}
}
return null;
};
wijevcal.prototype._onMonthViewAppointmentMouseDown = // month view appointment drag/drop
function (e) {
if(this.options.readOnly) {
return;
}
var target = $(e.target), appt = target.hasClass("wijmo-wijev-appointment") ? target : target.parents(".wijmo-wijev-appointment");
e.preventDefault();
this.__targetAppt = appt;
$(document).bind("mouseup.tmp_wijevcal", $.proxy(this._onMonthViewAppointmentMouseUp, this));
this.element.find(".wijmo-wijev-monthview .wijmo-wijev-monthcellcontainer").bind("mouseover.tmp_wijevcal", $.proxy(this._onMonthViewCellMouseOver, this));
};
wijevcal.prototype._onDayViewAppointmentMouseDown = // day view appointment drag/drop/resize/inline edit
function (e) {
if(this.options.readOnly) {
return;
}
var target = $(e.target), appt = target.hasClass("wijmo-wijev-appointment") ? target : target.parents(".wijmo-wijev-appointment"), isResize = target.hasClass("wijmo-wijev-resizer") || target.parents(".wijmo-wijev-resizer").length > 0;
if(this.options.disabled) {
//fix for 20811
return;
}
this._isApptResize = isResize;
e.preventDefault();
if(this._isApptResize) {
this.__startApptH = appt[0].offsetHeight;
this.__startApptY = appt[0].offsetTop;
} else {
this.__startApptY = appt[0].offsetTop;
}
this.__startClientY = e.clientY;
this.__targetAppt = appt;
$(document).bind("mousemove.tmp_wijevcal", $.proxy(this._onDayViewAppointmentMouseMove, this));
$(document).bind("mouseup.tmp_wijevcal", $.proxy(this._onDayViewAppointmentMouseUp, this));
$(this.element).find(".wijmo-wijev-dayview .wijmo-wijev-daycolumn").bind("mouseover.tmp_wijevcal", $.proxy(this._onDayViewColumnMouseOver, this));
$(this.element).find(".wijmo-wijev-dayview .wijmo-wijev-allday-cell").bind("mouseover.tmp_wijevcal", $.proxy(this._onDayViewAllDayMouseOver, this));
};
wijevcal.prototype._onDayViewAppointmentMouseMove = function (e) {
e.preventDefault();
var ychange = e.clientY - this.__startClientY, top, o = this.options, newHeight, offsetTop;
if(!e.ctrlKey) {
ychange = Math.round(ychange / o.timeIntervalHeight) * o.timeIntervalHeight;
}
if(ychange !== 0 && !this._apptDragResizeFlag) {
this._apptDragResizeFlag = true;
this.__targetAppt.addClass("wijmo-wijev-dragging");
this.__targetAppt.css("width", "100%").css("margin-left", "0").css("z-index", "1000");
}
if(this._apptDragResizeFlag) {
if(this._isApptResize) {
newHeight = this.__startApptH + ychange;
if(newHeight < 0) {
newHeight = Math.abs(newHeight);
top = this.__startApptY - newHeight;
if(top >= 0) {
this.__targetAppt.css("height", newHeight);
this.__targetAppt.css("top", top);
}
} else {
this.__targetAppt.css("height", newHeight);
}
} else {
top = this.__startApptY + ychange;
if(top < 0) {
top = 0;
}
this.__targetAppt.css("top", top);
offsetTop = this.__targetAppt.offset().top;
//fix for 25070 (part 1):
this.element.find(".wijmo-wijev-scrollpanel").wijsuperpanel("scrollChildIntoView", this.__targetAppt);
this.__startApptY = this.__startApptY - (this.__targetAppt.offset().top - offsetTop);
}
this._onApptVisualDargOrResize(this.__targetAppt, this.findEventById(this.__targetAppt[0].className));
}
};
wijevcal.prototype._onDayViewAppointmentMouseUp = function (e) {
if(this.__targetAppt) {
this.__targetAppt.removeClass("wijmo-wijev-dragging");
}
$(document).unbind(".tmp_wijevcal");
$(this.element).find(".wijmo-wijev-dayview .wijmo-wijev-daycolumn").unbind(".tmp_wijevcal");
$(this.element).find(".wijmo-wijev-dayview .wijmo-wijev-allday-cell").unbind(".tmp_wijevcal");
if(this._apptDragResizeFlag || this._apptMovedFlag) {
var o = this.findEventById(this.__targetAppt[0].className);
this._onApptVisualDargOrResize(this.__targetAppt, o);
this._apptMovedFlag = false;
this._movedFromTimeInervalApptElem = null;
this.updateEvent(o);
window.setTimeout($.proxy(function () {
if(this.__targetAppt && !this.__targetAppt.hasClass("wijmo-wijev-dragging")) {
this._apptDragResizeFlag = false;
// fix for 30112 case 2
this._resolveDayViewAppointmentConflicts(this.__targetAppt.parents(".wijmo-wijev-daycolumn"));
}
}, this), 1);
}
};
wijevcal.prototype._updateAppointmentVisual = function (appt) {
var visual = this.element.find(".wijmo-wijev-dayview ." + this._eventIdToCssClass(appt.id)), o = this.options, visualStartMin, visualEndMin, visualStartPx, visualEndPx, curDayStart, columnDateClass, sourceCol, targetCol;
if(visual.length === 1) {
this._addColorClass(visual, appt.color);
visual.find(".wijmo-wijev-title").html(this._formatString(o.eventTitleFormat, appt.start, appt.end, appt.subject, appt.location, "", appt.description/*"<strong>ICONS</strong>"*/ ));
curDayStart = _toDayDate(appt.start);
visualStartMin = (((appt.start - curDayStart) / 1000) / 60);
visualEndMin = (((appt.end - curDayStart) / 1000) / 60);
visualStartPx = Math.round(visualStartMin * o.timeIntervalHeight / o.timeInterval);
visualEndPx = Math.round(visualEndMin * o.timeIntervalHeight / o.timeInterval);
visual.css("top", visualStartPx);
visual.css("height", (visualEndPx - visualStartPx));
columnDateClass = this._dayDateToCssClass(curDayStart);
if(visual.parents(".wijmo-wijev-daycolumn." + columnDateClass).length !== 1) {
sourceCol = visual[0].parentNode;
targetCol = this.element.find(".wijmo-wijev-daycolumn." + columnDateClass);
sourceCol.removeChild(visual[0]);
//this._resolveDayViewAppointmentConflicts(sourceCol); //qq:not works.
visual.appendTo(targetCol);
//this._resolveDayViewAppointmentConflicts(targetCol); //qq:not works.
}
//daycolumn date_2011_7_7
/*
Math.round(visualStartPx * o.timeInterval / o.timeIntervalHeight)
= visualStartMin;
visualStartMin * 60 * 1000 + curDayStart = visualStartDt
visualStartMin = (((visualStartDt - curDayStart)/1000) / 60);
visualEndMin = (((visualEndDt - curDayStart) / 1000) / 60);
visualStartPx = Math.round(visualStartMin *
o.timeIntervalHeight / o.timeInterval);
visualEndPx = Math.round(visualEndMin *
o.timeIntervalHeight / o.timeInterval);
*/
}
};
wijevcal.prototype._onApptVisualDargOrResize = function (visual, appt) {
var o = this.options, visualStartPx = visual[0].offsetTop, visualEndPx = visualStartPx + visual[0].offsetHeight, visualStartMin, visualEndMin, visualStartDt, visualEndDt, realEndDt, durationMs, curDayStart, parentCol;
if(visual.parents(".wijmo-wijev-dayheadercolumn").length > 0) {
parentCol = visual.parents(".wijmo-wijev-dayheadercolumn")[0];
} else {
parentCol = visual.parents(".wijmo-wijev-daycolumn")[0];
}
curDayStart = this._parseDateFromClass(parentCol.className, null);
visualStartMin = Math.round(visualStartPx * o.timeInterval / o.timeIntervalHeight);
visualEndMin = Math.round(visualEndPx * o.timeInterval / o.timeIntervalHeight);
visualStartDt = new Date(visualStartMin * 60 * 1000 + curDayStart.getTime());
visualEndDt = new Date(visualEndMin * 60 * 1000 + curDayStart.getTime());
if(appt) {
if(!this._isApptResize) {
// fix for 25120
// do not change duration for drag action
durationMs = appt.end.getTime() - appt.start.getTime();
realEndDt = new Date(visualStartDt.getTime() + durationMs);
} else {
realEndDt = visualEndDt;
}
appt.allday = visual.parents(".wijmo-wijev-dayheadercolumn").length > 0;
appt.start = visualStartDt;
appt.end = realEndDt//visualEndDt;
;
visual.find(".wijmo-wijev-title").html(this._formatString(o.eventTitleFormat, appt.start, appt.end, appt.subject, appt.location, "", appt.description/*"<strong>ICONS</strong>"*/ ));
if(!this._isApptResize && realEndDt.getTime() !== visualEndDt.getTime()) {
// fix for 25120
// Update visual height
visual.css("height", (Math.round((((appt.end - _toDayDate(appt.start)) / 1000) / 60) * o.timeIntervalHeight / o.timeInterval) - Math.round((((appt.start - _toDayDate(appt.start)) / 1000) / 60) * o.timeIntervalHeight / o.timeInterval)));
}
}
};
wijevcal.prototype._onDayViewColumnMouseOver = function (e) {
var targetCol = $(e.target).parents(".wijmo-wijev-daycolumn"), sourceCol = this.__targetAppt.parents(".wijmo-wijev-daycolumn");
if(targetCol.length < 1) {
return;
}
if(sourceCol.length < 1) {
sourceCol = this.__targetAppt.parents(".wijmo-wijev-dayheadercolumn");
if(sourceCol.length < 1) {
return;
} else {
// move from all day event cell to time interval.
if(this._movedFromTimeInervalApptElem) {
// fix for 25070 case 2.
this.__targetAppt.replaceWith(this._movedFromTimeInervalApptElem);
this.__targetAppt = $(this._movedFromTimeInervalApptElem);
this._movedFromTimeInervalApptElem = null;
} else {
this.__targetAppt.html(this._getEventMarkup(this.findEventById(this.__targetAppt[0].className)));
}
}
}
if(targetCol[0].className !== sourceCol[0].className) {
this.__targetAppt[0].parentNode.removeChild(this.__targetAppt[0]);
this._resolveDayViewAppointmentConflicts(sourceCol);
this.__targetAppt.appendTo(targetCol);
this._apptMovedFlag = true;
}
};
wijevcal.prototype._onMonthViewCellMouseOver = function (e) {
var target = $(e.target), targetCell = target.hasClass("wijmo-wijev-monthcellcontainer") ? target : target.parents(".wijmo-wijev-monthcellcontainer"), sourceCell = this.__targetAppt.parents(".wijmo-wijev-monthcellcontainer");
if(targetCell.length < 1 || sourceCell.length < 1) {
return;
}
if(targetCell[0].className !== sourceCell[0].className) {
this.__targetAppt[0].parentNode.removeChild(this.__targetAppt[0]);
this.__targetAppt.appendTo(targetCell.find(".wijmo-wijev-monthcell"));
this.__targetApptChanged = true;
}
};
wijevcal.prototype._onMonthViewAppointmentMouseUp = function () {
var appt, parentCell = this.__targetAppt.parents(".wijmo-wijev-monthcellcontainer")[0], curDayStart = this._parseDateFromClass(parentCell.className, null), daysDiff;
$(document).unbind(".tmp_wijevcal");
this.element.find(".wijmo-wijev-monthview .wijmo-wijev-monthcellcontainer").unbind(".tmp_wijevcal");
if(this.__targetApptChanged) {
this.__targetApptChanged = false;
appt = this.findEventById(this.__targetAppt[0].className);
daysDiff = (curDayStart.getTime() - _toDayDate(appt.start).getTime()) / (1000 * 60 * 60 * 24);
appt.start = this._addDays(appt.start, daysDiff);
appt.end = this._addDays(appt.end, daysDiff);
this.updateEvent(appt);
}
};
wijevcal.prototype._onDayViewAllDayMouseOver = function (e) {
var targetCol = $(e.target).parents(".wijmo-wijev-dayheadercolumn"), sourceCol = this.__targetAppt.parents(".wijmo-wijev-daycolumn"), newVisual;
if(targetCol.length < 1) {
return;
}
if(sourceCol.length > 0) {
// update appointment element
// move from time interval to all day cell
newVisual = $(this._getAllDayEventMarkup(this.findEventById(this.__targetAppt[0].className)));
// fix for 25070 case 2:
this._movedFromTimeInervalApptElem = this.__targetAppt[0].cloneNode(true);
this.__targetAppt.replaceWith(newVisual);
this.__targetAppt = newVisual;
} else {
// move from all day cell to another all day cell
sourceCol = this.__targetAppt.parents(".wijmo-wijev-dayheadercolumn");
}
if(sourceCol.length < 1) {
return;
}
if(targetCol[0].className !== sourceCol[0].className) {
this.__targetAppt[0].parentNode.removeChild(this.__targetAppt[0]);
this._resolveDayViewAppointmentConflicts(sourceCol);
this.__targetAppt.appendTo($(targetCol).find(".wijmo-wijev-allday-cell"));
this._apptMovedFlag = true;
}
};
wijevcal.prototype._renderMonthView = // <-
/* MONTH view */
function () {
var o = this.options, selectedDate = o.selectedDate, firstDayOfWeek = o.firstDayOfWeek, isToday = false, isOtherMonth = false, curDate, startDate, endDate, todayDate = new Date(), curColumnInd, curRowInd, skipNextBorder = false, containerClass, sCols = [
"",
"",
"",
"",
"",
"",
""
], s, i, monthview = this.element.find(".wijmo-wijev-view.wijmo-wijev-monthview"), monthviewinner, dayHeaderFormat = o.dayHeaderFormat, firstRowDayHeaderFormat = o.firstRowDayHeaderFormat;
if(!selectedDate) {
selectedDate = new Date();
}
startDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), 1);
while(startDate.getDay() !== parseInt(firstDayOfWeek)) {
startDate = this._addDays(startDate, -1);
}
endDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), this._daysInMonth(selectedDate.getMonth(), selectedDate.getFullYear()));
curDate = startDate;
curColumnInd = 0;
curRowInd = 0;
while(curDate < endDate || curColumnInd < 7) {
if(curDate > endDate) {
endDate = curDate;
}
s = "";
containerClass = "wijmo-wijev-monthcellcontainer " + o.wijCSS.content + " " + this._dayDateToCssClass(curDate);
isOtherMonth = curDate.getMonth() !== selectedDate.getMonth();
if(isOtherMonth) {
// ui-priority-secondary
containerClass += " wijmo-wijev-othermonth";
}
if(skipNextBorder) {
skipNextBorder = false;
} else {
containerClass += " wijmo-wijev-leftborder";
if(curColumnInd === 6) {
containerClass += " wijmo-wijev-rightborder";
}
}
isToday = this._compareDayDates(curDate, todayDate) === 0;
if(isToday) {
// ui-state-highlight
containerClass += " wijmo-wijev-today";
containerClass += " wijmo-wijev-rightborder";
skipNextBorder = true;
}
s += "<div class=\"" + containerClass + "\">";
s += "<div class=\"wijmo-wijev-monthcellheader";
if(isOtherMonth) {
s += " ui-priority-secondary";
}
if(isToday) {
s += " ui-state-highlight";
}
s += "\">";
if(isToday) {
s += "<span class=\"wijmo-wijev-todaylabel\">" + this.localizeString("labelToday", "Today") + "</span>";
}
if(curRowInd === 0) {
s += this._formatString(firstRowDayHeaderFormat, curDate);
} else {
s += this._formatString(dayHeaderFormat, curDate);
}
s += "</div>";
s += "<div class=\"wijmo-wijev-monthcell";
if(isOtherMonth) {
s += " ui-priority-secondary";
}
if(isToday) {
s += " ui-state-highlight";
}
s += "\"></div>";
s += "</div>";
sCols[curColumnInd] = sCols[curColumnInd] + s;
curColumnInd += 1;
curDate = this._addDays(curDate, 1);
if(curColumnInd > 6) {
if(curDate > endDate) {
break;
}
curColumnInd = 0;
curRowInd += 1;
}
}
if(monthview.length === 0) {
monthview = $("<div class=\"wijmo-wijev-view wijmo-wijev-monthview " + o.wijCSS.content + "\">" + "<h3 class=\"wijmo-wijev-header-title\">title" + "</h3>" + "<div class=\"wijmo-wijev-monthview-inner\">" + "</div>" + "</div>");
monthview.appendTo(this.element.find(".wijmo-wijev-view-container"));
}
monthviewinner = monthview.find(".wijmo-wijev-monthview-inner");
monthviewinner.find(".wijmo-wijev-monthcolumn").remove();
curDate = startDate;
for(i = 0; i < 7; i += 1) {
monthviewinner.append("<div class=\"wijmo-wijev-monthcolumn\">" + sCols[i] + "</div>");
curDate = this._addDays(curDate, 1);
}
this._invalidateMonthView();
this._renderMonthViewAppointments();
};
wijevcal.prototype._invalidateMonthView = function () {
var monthview = this.element.find(".wijmo-wijev-monthview"), monthviewinner = monthview.find(".wijmo-wijev-monthview-inner"), monthColumns = monthview.find(".wijmo-wijev-monthcolumn"), monthcellcontainers = monthview.find(".wijmo-wijev-monthcellcontainer"), title = this.element.find(".wijmo-wijev-monthview .wijmo-wijev-header-title"), viewWidth, viewHeight, columnOuterWidth, monthcellcontainerH, monthHeaderH, monthCellH, weekdaynameH, diff;
this._invalidateView();
if(monthColumns.length < 1) {
return;
}
viewWidth = monthview.innerWidth();
viewHeight = monthview.innerHeight() - title.outerHeight(true);
monthviewinner.outerWidth(viewWidth);
monthviewinner.outerHeight(viewHeight);
viewWidth = viewWidth - (monthviewinner.outerWidth(true) - monthviewinner.innerWidth());
viewHeight = viewHeight - (monthviewinner.outerHeight(true) - monthviewinner.innerHeight());
//viewHeight = monthviewinner.();
columnOuterWidth = Math.floor(viewWidth / monthColumns.length);
monthColumns.outerWidth(columnOuterWidth);
diff = viewWidth - columnOuterWidth * monthColumns.length;
if(diff > 0) {
$(monthColumns[monthColumns.length - 1]).outerWidth(columnOuterWidth + diff);
}
weekdaynameH = $(monthColumns[0]).find(".wijmo-wijev-weekdayname").outerHeight(true);
if(!weekdaynameH) {
//(20120830) fix for 27354(regression issue?):
weekdaynameH = 0;
}
monthcellcontainerH = Math.floor((viewHeight - weekdaynameH) / $(monthColumns[0]).find(".wijmo-wijev-monthcellcontainer").length);
monthcellcontainers.height(monthcellcontainerH);
//outerHeight(monthcellcontainerH);
monthHeaderH = $(monthcellcontainers[0]).find(".wijmo-wijev-monthcellheader").outerHeight(true);
monthCellH = monthcellcontainerH - monthHeaderH;
monthcellcontainers.find(".wijmo-wijev-monthcell").outerHeight(monthCellH);
};
wijevcal.prototype._renderMonthViewAppointments = function () {
var appts = this._eventsView, appt, i, j, apptsCount, daysCount, monthcellcontainers = this.element.find(".wijmo-wijev-monthcellcontainer"), monthcellcontainer, curDayStart, curDayEnd, apptVisual;
if(appts) {
for(j = 0 , daysCount = monthcellcontainers.length; j < daysCount; j += 1) {
monthcellcontainer = monthcellcontainers[j];
curDayStart = this._parseDateFromClass(monthcellcontainer.className);
curDayEnd = new Date(curDayStart.getFullYear(), curDayStart.getMonth(), curDayStart.getDate(), 23, 59, 59);
for(i = 0 , apptsCount = appts.length; i < apptsCount; i += 1) {
appt = appts[i];
if((appt.start < curDayEnd && appt.end > curDayStart)) {
apptVisual = $("<div class=\"wijmo-wijev-appointment " + this._eventIdToCssClass(appt.id) + "\">" + "<div class=\"" + " wijmo-wijev-colordot wijmo-wijev-event-color-" + (appt.color || "default") + "\"></div>" + "<div class=\"wijmo-wijev-event-title\">" + appt.subject + "</div>" + "</div>");
$(monthcellcontainer).find(".wijmo-wijev-monthcell").append(apptVisual);
}
}//<for (i = 0
}//<for (j = 0
}
// display "show more..." if needed:
monthcellcontainers.find(".wijmo-wijev-monthcell").each($.proxy(function (i, el) {
var monthcell = $(el), apps = monthcell.find(".wijmo-wijev-appointment"), monthcellH = monthcell.outerHeight(), appH = apps.outerHeight(), appsH = apps.length * appH, hiddenCount = 0;
if(appsH > monthcellH) {
apps.each(function (j, a) {
if((j * appH + appH) > monthcellH) {
a["style"].display = "none";
hiddenCount += 1;
}
});
if(hiddenCount > 0) {
if(monthcell.find(".wijmo-wijev-monthcell-showmore").length < 1) {
monthcell.append($("<div class=\"wijmo-wijev-monthcell-showmore\">" + this._formatString(this.localizeString("monthCellMoreEventsFormat", "{0} more..."), hiddenCount) + "</div>"));
}
}
}
}, this));
};
wijevcal.prototype.log = /** Sends a log message to built-in log console.
* Note: n order to use this method, you must set the enableLogs option to true.
* @param {string} msg Log message.
* @param {string} className
* Optional. CSS class name that will be applied to the destination message.
* Few predefined classes are available:
* "error", "warning", "information", "status"
*/
function (msg, className) {
};
wijevcal.prototype._log = function (msg, className) {
var dt;
if(this.logPanel) {
dt = new Date();
this.logPanel.prepend($('<span class="' + (className ? className : "wijmo-wijev-information") + '">' + '[' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds() + '] ' + msg + '</span><br/>'));
}
};
wijevcal.prototype._createLogPanel = function () {
if(!this.logPanel) {
this.logDialog = $('<div title="Log">' + '<div class="wijmo-wijev-log"></div></div>');
this.logDialog.appendTo(this.element);
var btnsHash = {
};
btnsHash[this.localizeString("buttonClearAll", "Clear All")] = function () {
$(this).find(".wijmo-wijev-log").html("");
};
btnsHash[this.localizeString("buttonClose", "Close")] = function () {
$(this).wijdialog("close");
};
this.logPanel = this.logDialog.wijdialog({
captionButtons: {
},
buttons: /*pin: { visible: false },
refresh: { visible: false },
toggle: { visible: false },
minimize: { visible: false }*/
btnsHash,
width: 600,
height: 420,
position: [
"right",
"top"
]
}).find(".wijmo-wijev-log");
}
this.logDialog.wijdialog("open");
};
wijevcal.prototype.status = /**
* Changes status label text.
* @param {string} txt The new status text.
*/
function (txt, className) {
this.element.find(".wijmo-wijev-statusbar").html("<span class='" + (className ? className : "wijmo-wijev-status") + "'>" + txt + "</span>");
this.log(txt, className ? className : "wijmo-wijev-status");
};
wijevcal.prototype._invalidateView = //<--
/* common view code */
function () {
var rightPane = this.element.find(".wijmo-wijev-rightpane"), leftPane = this.element.find(".wijmo-wijev-leftpane"), header = this.element.find(".wijmo-wijev-headerbar"), navigationbar = this.element.find(".wijmo-wijev-navigationbar"), footer = this.element.find(".wijmo-wijev-statusbar"), viewContainer = this.element.find(".wijmo-wijev-view-container"), view = this.element.find(".wijmo-wijev-view"), elemInnerW, elemInnerH, headerH, navigationbarH, footerH, viewHeight, viewWidth, leftPaneW, rightPaneW, i, elementWidth, minWidth = this.options.minWidth;
elementWidth = this.element.innerWidth();
if(elementWidth < minWidth) {
elementWidth = minWidth;
this.element.width(minWidth);
}
elemInnerW = elementWidth - (viewContainer.outerWidth(true) - viewContainer.innerWidth());
elemInnerH = this.element.innerHeight() - (viewContainer.outerHeight(true) - viewContainer.innerHeight());
headerH = header.is(":visible") ? header.outerHeight(true) : 0;
navigationbarH = navigationbar.is(":visible") ? navigationbar.outerHeight(true) : 0;
footerH = footer.is(":visible") ? footer.outerHeight(true) : 0;
viewContainer.outerWidth(elemInnerW);
viewContainer.outerHeight(elemInnerH - headerH - navigationbarH - footerH);
leftPaneW = 0;
for(i = 0; i < leftPane.length; i += 1) {
if($(leftPane[i]).is(":visible")) {
leftPaneW += $(leftPane[i]).outerWidth();
}
}
rightPaneW = rightPane.is(":visible") ? rightPane.outerWidth() : 0;
viewHeight = elemInnerH - headerH - navigationbarH - footerH;
// -1 is fix for [29300] [JPN issue]
// [Sample][EventCalendar]List view of EventCalendar gets control desorted
viewWidth = elemInnerW - rightPaneW - leftPaneW - 1;
//alert("leftPaneW=" + leftPaneW + ",viewWidth=" + viewWidth);
view.outerHeight(viewHeight);
view.outerWidth(viewWidth);
header.outerWidth(viewWidth + leftPaneW);
navigationbar.outerWidth(this.element.innerWidth());
footer.outerWidth(viewWidth + leftPaneW + rightPaneW);
leftPane.outerHeight(elemInnerH - headerH - navigationbarH - footerH);
/*
//agendaContainer invalidated later(fix for 21282) when date label text is changed.
agendaContainer.outerHeight(leftPane.innerHeight() -
agendaContainer[0].offsetTop);
*/
rightPane.outerHeight(elemInnerH + 100);
this.element.find(".wijmo-wijev-datepager").wijdatepager("refresh");
};
wijevcal.prototype._daysInMonth = //<-
// util methods:
// note, month is zero-based(0-11)
function (month, year) {
var dd = new Date(year, month + 1, 0);
return dd.getDate();
};
wijevcal.prototype._addMinutes = function (dt, num) {
return new Date(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes() + num);
};
wijevcal.prototype._addDays = function (dt, num) {
return new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() + num, dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds());
};
wijevcal.prototype._setTime = function (dt, timePart, daysTestPart) {
var daysDuration;
dt = new Date(dt);
dt.setHours(timePart.getHours());
dt.setMinutes(timePart.getMinutes());
dt.setSeconds(timePart.getSeconds());
dt.setMilliseconds(timePart.getMilliseconds());
if(daysTestPart) {
daysDuration = Math.floor((timePart.getTime() - daysTestPart.getTime()) / (1000 * 60 * 60 * 24));
if(daysDuration > 0) {
dt = this._addDays(dt, daysDuration);
}
}
return dt;
};
wijevcal.prototype._addMonths = function (dt, num) {
return new Date(dt.getFullYear(), dt.getMonth() + num, dt.getDate());
};
wijevcal.prototype._compareDayDates = function (dt1, dt2) {
dt1 = new Date(dt1.getFullYear(), dt1.getMonth(), dt1.getDate());
dt2 = new Date(dt2.getFullYear(), dt2.getMonth(), dt2.getDate());
if(dt1 < dt2) {
return -1;
} else if(dt1 > dt2) {
return 1;
}
return 0;
};
wijevcal.prototype._dayDateToCssClass = function (dt) {
return "wijmo-wijev-date_" + dt.getFullYear() + "_" + dt.getMonth() + "_" + dt.getDate();
};
wijevcal.prototype._parseDateFromClass = function (dateClass, minuteClass, defaultVal) {
var dt, min, datearr, minregexp = new RegExp("wijmo-wijev-minute-(\\d+)\\s"), dateregexp = new RegExp("wijmo-wijev-date_(\\d+_\\d+_\\d+)\\s");
if(dateClass) {
datearr = dateregexp.exec(dateClass + " ")[1].split("_");
dt = new Date(parseInt(datearr[0], 10), parseInt(datearr[1], 10), parseInt(datearr[2], 10));
if(minuteClass) {
min = minregexp.exec(minuteClass + " ");
if(min) {
min = parseInt(min[1], 10);
dt.setMinutes(min);
}
}
return dt;
} else {
return defaultVal || null;
}
};
wijevcal.prototype._eventIdToCssClass = function (id) {
return "apptid_" + id;
};
wijevcal.prototype._parseEventIdFromClass = function (cssClass) {
var id = "", regexp, match;
regexp = new RegExp("apptid_(\\S+)");
match = regexp.exec(cssClass);
if(match && match.length > 1) {
id = match[1];
}
return id;
};
wijevcal.prototype._isContainsDayDate = function (arr, dt) {
var i;
if(arr) {
for(i = 0; i < arr.length; i += 1) {
if(this._compareDayDates(arr[i], dt) === 0) {
return true;
}
}
} else {
return false;
}
};
wijevcal.prototype._formatString = //format:
function (fmt, arg0, arg1, arg2, arg3, arg4, arg5, arg6) {
var r, args = arguments, i, funcArgs, self = this;
if(args.length <= 1) {
return Globalize.format(args);
}
if(typeof fmt === "string") {
if(fmt === "_formatWeekTitle") {
fmt = this._formatWeekTitle;
} else if(fmt === "_formatMonthTitle") {
fmt = this._formatMonthTitle;
} else if(typeof window[fmt] === "function") {
fmt = window[fmt];
}
}
if(typeof fmt === "function") {
funcArgs = [];
for(i = 1; i < args.length; i += 1) {
funcArgs[i - 1] = args[i];
}
return fmt.apply(this, funcArgs);
}
r = new RegExp("\\{(\\d+)(?:,([-+]?\\d+))?(?:\\:" + "([^(^}]+)(?:\\(((?:\\\\\\)|[^)])+)\\)){0,1}){0,1}\\}", "g");
return fmt.replace(r, function (m, num, len, f, params) {
m = args[Number(num) + 1];
if(f) {
return Globalize.format(m, f, self._getCulture());
} else {
return m;
}
});
};
wijevcal.prototype._formatMonthTitle = function (dt) {
return this._formatString(this.localizeString("monthViewHeaderFormat", "{0:MMMM yyyy}"), dt);
};
wijevcal.prototype._formatWeekTitle = function (start, end) {
if(start.getMonth() !== end.getMonth()) {
return this._formatString(this.localizeString("weekViewHeaderFormat2Months", "{0:MMMM} - {1:MMMM yyyy}"), start, end);
} else {
return this._formatString(this.localizeString("weekViewHeaderFormat", "{0:MMMM yyyy}"), start);
}
};
wijevcal.prototype._formatDayHeaderDate = // format date/time:
function (dt) {
var o = this.options, viewType = o.viewType.toLowerCase(), dayViewHeaderFormat = this.options.dayViewHeaderFormat;
if(dayViewHeaderFormat[viewType]) {
dayViewHeaderFormat = dayViewHeaderFormat[viewType];
} else if(!dayViewHeaderFormat[viewType]) {
return "";
}
//return Globalize.format(date, format, this._getCulture());
return this._formatString(dayViewHeaderFormat, dt);
};
wijevcal.prototype._getCulture = // culture:
function (name) {
return Globalize.findClosestCulture(name || this.options.culture);
};
wijevcal.prototype._isRTL = function () {
return !!this._getCulture().isRTL;
};
wijevcal.prototype._onAjaxError = //<--
function (event, jqXHR, ajaxSettings, thrownError) {
if(jqXHR) {
this.status("Ajax error " + jqXHR.status + " (" + jqXHR.statusText + ")", "error");
this.log("Error, requested url: " + ajaxSettings.url, "error");
if(jqXHR.responseText) {
this.log("Error, response text: " + jqXHR.responseText, "error");
}
} else {
this.status("Ajax error detected.", "error");
this.log("Error, requested url: " + ajaxSettings.url, "error");
}
};
wijevcal.prototype._onWindowResize = function () {
this.invalidate();
};
return wijevcal;
})(wijmo.wijmoWidget);
evcal.wijevcal = wijevcal;
var wijevcal_options = (function () {
function wijevcal_options() {
/** wijMobileCSS
* @ignore
*/
this.wijMobileCSS = {
header: "ui-header ui-bar-a",
content: "ui-body ui-body-c",
stateDefault: "ui-btn-up-c"
};
/** Selector option for auto self initialization.
* This option is internal.
* @ignore
*/
this.initSelector = ":jqmData(role='wijevcal')";
/** Determines the culture to be used, for example, "de-DE" is German.
* Date and time formatting depends on the culture option.
*/
this.culture = "";
/** Use the localization option in order to localize
* text which not depends on culture option.
* @default {
* messageEndOccursBeforeStart: "The end date you entered occurs before the start date.",
* activityLoading: "Loading...",
* activityDeletingCalendar: "Deleting calendar...",
* activityCreatingCalendar: "Creating calendar...",
* activityUpdatingCalendar: "Updating calendar...",
* activityCreatingEvent: "Creating event...",
* activityUpdatingEvent: "Updating event...",
* activityDeletingEvent: "Deleting event...",
* activityUpdating: "Updating...",
* agendaLoadingMoreEvents: "Loading more events...",
* agendaMoreEventsFormat: "More events ({0})...", // (0) - Number, invisible events count
* agendaTimeFormat: "{0:hh:mm tt} to {1:hh:mm tt}", // {0} Date, event start time, {1} - Date, event end time
* buttonToday: "today",
* buttonDayView: "Day",
* buttonWeekView: "Week",
* buttonMonthView: "Month",
* buttonListView: "List",
* buttonDelete: "Delete",
* buttonOK: "OK",
* buttonCancel: "Cancel",
* calendarNextTooltip: "Next",
* calendarPrevTooltip: "Previous",
* navigatorBarNextTooltip: "right",
* navigatorBarPrevTooltip: "left",
* labelAllDay: "all-day",
* labelToday: "Today",
* labelName: "name",
* labelStarts: "starts",
* labelEnds: "ends",
* labelLocation: "location",
* labelRepeat: "repeat",
* labelCalendar: "calendar",
* labelDescription: "description",
* monthCellMoreEventsFormat: "{0} more...", // (0) - Number, invisible events count
* promptOpenOccurrenceFormat: "{2} is recurring event. Do you want to open only this occurrence?", // {0} = Start, {1} = End, {2} = Subject, {3} = Location
* textNewEvent: "New event",
* repeatNone: "None",
* repeatDaily: "Every Day",
* repeatWorkDays: "Work days",
* repeatWeekly: "Every Week",
* repeatMonthly: "Every Month",
* repeatYearly: "Every Year",
* labelCalendarName: "Calendar name",
* labelColor: "Color",
* buttonSave: "Save",
* titleEditCalendar: "Edit calendar",
* calendarToolTipFormat: "dddd, MMMM dd, yyyy",
* calendarTitleFormat: "MMMM yyyy",
* dayDetailsLabelFulldateFormat: "{0:dddd, MMMM d}",
* dayDetailsLabelYearFormat: "{0:yyyy}"
* weekViewHeaderFormat2Months: "{0:MMMM} - {1:MMMM yyyy}",
* weekViewHeaderFormat: "{0:MMMM yyyy}",
* monthViewHeaderFormat: "{0:MMMM yyyy}",
* agendaHeaderFullDateFormat": "{0:MMMM d, yyyy}",
* logCouldntOpenLocalStorage: "Couldn't open built-in local data storage. Please, add amplify.store references."
* buttonClearAll: "Clear All",
* buttonClose: "Close"
* }
* @type {object}
* @example $("#eventscalendar").wijevcal(
* {
* localization: {
* buttonToday: "Go today",
* buttonListView: "Agenda"
* }
* });
*/
this.localization = null;
/** Use the datePagerLocalization option in order to localize
* bottom date pager.
* @ignore
*/
this.datePagerLocalization = null;
/** Set this option to true if you want to prevent users to edit events data.
* @example
* $("#report").wijevcal({
* readOnly: true
* });
*/
this.readOnly = false;
/** Determines the URL of the web service which will be used to store information about events.
* @example
* $("#report").wijevcal({
* webServiceUrl: "http://mysite/c1evcalservice.ashx"
* });
*/
this.webServiceUrl = "";
//c1evcalservice.ashx
/** The colors option specifies the name of the colors that will be shown in the color name drop-down list.
* "blue", "cornflowerblue", "yellow", "bronze"]
* @type {Array}
* @example $("#eventscalendar").wijevcal(
* { colors: ["cornflowerblue", "yellow"]);
*/
this.colors = null;
/** Data storage methods. Use this option in order to implement custom
* data storage layer.
* @type {object}
* @example $("#eventscalendar").wijevcal(
* { dataStorage: {
* addEvent: function(obj, successCallback, errorCallback) {
* },
* updateEvent: function(obj, successCallback, errorCallback) {
* },
* deleteEvent: function(obj, successCallback, errorCallback) {
* },
* loadEvents: function(visibleCalendars,
* successCallback, errorCallback) {
* },
* addCalendar: function(obj, successCallback, errorCallback) {
* },
* updateCalendar: function(obj, successCallback, errorCallback) {
* },
* deleteCalendar: function(obj, successCallback, errorCallback) {
* },
* loadCalendars: function(successCallback, errorCallback) {
* }
* });
*/
this.dataStorage = {
addEvent: null,
updateEvent: null,
deleteEvent: null,
loadEvents: null,
addCalendar: null,
updateCalendar: null,
deleteCalendar: null,
loadCalendars: null
};
/** A dataview object to bind to events data
* @type {object}
* @example
* var dv = $.wijmo.wijdataview({....});
* $("#eventscalendar").wijevcal({
* dataSource: dv
* })
*/
this.dataSource = null;
/** The event objects array.
* @example $("#eventscalendar").wijevcal(
* { eventsData: [{id: "appt1",
* start: new Date(2011, 4, 6, 17, 30),
* end: new Date(2011, 4, 6, 17, 35) }] });
*/
this.eventsData = [];
/** The event objects array. This option is read-only.
* This option is deprecated:
* please, use eventsData option, instead.
* @example $("#eventscalendar").wijevcal(
* { eventsData: [{id: "appt1",
* start: new Date(2011, 4, 6, 17, 30),
* end: new Date(2011, 4, 6, 17, 35) }] });
*/
this.appointments = [];
/** Available calendar objects array.
* This option is read-only.
* Use addCalendar/updateCalendar/deleteCalendar methods in order
* to add/edit or delete a calendar.
* @example
* var calendars = $("#eventscalendar")
* .wijevcal("option", "calendars");
*/
this.calendars = [];
/** Specifies whether the events calendar is disabled.
* @example $("#eventscalendar").wijevcal("option",
* "disabled", true);
*/
this.disabled = false;
/** The calendar dialog box template.
* @example $("#eventscalendar").wijevcal(
* { editCalendarTemplate: "html content");
*/
this.editCalendarTemplate = "";
/** Enables a built-in log console.
* @example
* $("#eventscalendar").wijevcal({ enableLogs: true });
*/
this.enableLogs = false;
/** Format of the title text for the event.
* Format arguments:
* {0} = Start, {1} = End, {2} = Subject, {3} = Location, {4} = Icons,
* {5} = Description.
* @example
* $("#eventscalendar").wijevcal({
* eventTitleFormat: "{0:h:mmtt}-{1:h:mmtt} {4} {2}" });
*/
this.eventTitleFormat = "{2}";
/** The title text format that will be shown under the header bar.
* {0} = start date. {1} = end date.
* @type {object}
* @example
* Specify common title format:
* $("#eventscalendar").wijevcal(
* {
* titleFormat: "First date: {0:d} Last date: {1:d}"
* }
* );
* Specify separate format for the each view:
* $("#eventscalendar").wijevcal(
* {
* titleFormat: {
* function customFormatFunc will be called
* //in order to format string:
* day: customFormatFunc,
* week: "Week {0:d} : {1:d}",
* month: "{0:yyyy, MMMM}",
* list: "Events until {1:d}"
* }
* }
*);
*/
this.titleFormat = {
day: false,
week: "_formatWeekTitle",
month: "_formatMonthTitle",
list: false
};
/** The first day of the week (from 0 to 6).
* Sunday is 0, Monday is 1, and so on.
* @example $("#eventscalendar").wijevcal(
* { firstDayOfWeek: 1 });
*/
this.firstDayOfWeek = 0;
/** Indicates whether the header bar will be visible.
* @example
* $("#element").wijevcal({ headerBarVisible: false });
*/
this.headerBarVisible = true;
/** Indicates whether the bottom navigation bar will be visible.
* @example $("#element").wijevcal({ navigationBarVisible: false });
*/
this.navigationBarVisible = true;
/** Indicates whether the right pane will be visible.
* By default the right pane are empty.
* You can use this pane in order to provide additional custom UI.
* @example
* $("#element").wijevcal({ rightPaneVisible: false });
*/
this.rightPaneVisible = false;
/** The selected date.
* @type {Date}
* @example $("#eventscalendar").wijevcal(
* { selectedDate: new Date(2015, 11, 21) });
*/
this.selectedDate = null;
/** The selected dates.
* @type {Date}
* @example $("#eventscalendar").wijevcal(
* { selectedDates: [new Date(2012, 11, 21), new Date(2015, 11, 21)] });
*/
this.selectedDates = null;
/** Indicates whether the status bar will be visible.
* @example $("#element").c1reportviewer({ statusBarVisible: false });
*/
this.statusBarVisible = false;
/** The time interval in minutes for the Day view.
* @example $("#eventscalendar").wijevcal(
* { timeInterval: 10 });
*/
this.timeInterval = 30;
/** The Day view time interval row height in pixels.
* @example $("#eventscalendar").wijevcal(
* { timeIntervalHeight: 30 });
*/
this.timeIntervalHeight = 15;
/** Time ruler interval for the Day view (in minutes).
* @example $("#eventscalendar").wijevcal(
* { timeRulerInterval: 60 });
*/
this.timeRulerInterval = 60;
/** Time ruler format for the Day view.
* @remarks
* Format argument:
* {0} = Current ruler time.
* @example $("#eventscalendar").wijevcal(
* { timeRulerFormat: "{0:t}" });
*/
this.timeRulerFormat = "{0:h tt}";
/** Format of the text for the day cell header(month view).
* Format argument:
* {0} = Day date.
* @example
* $("#eventscalendar").wijevcal(
* { dayHeaderFormat: "{0}" });
*/
this.dayHeaderFormat = "{0:d }";
/** Format of the text for the first cell header in the first row of the month view.
* Format argument:
* {0} = Day date.
* @example
* $("#eventscalendar").wijevcal(
* { firstRowDayHeaderFormat: "{0}" });
*/
this.firstRowDayHeaderFormat = "{0:ddd d}";
/** Format of the text for the day header in the day view. Format argument: {0} = Day date.
* @remarks
* Format argument:
* {0} = Day date.
* day: "all-day events",
* week: "{0:d dddd}",
* list: "{0:d dddd}"
* }
* @example
* $("#eventscalendar").wijevcal(
* { dayViewHeaderFormat: "{0: d}" });
*/
this.dayViewHeaderFormat = {
day: "all-day events",
week: "{0:d dddd}",
list: "{0:d dddd}"
};
/** The active view type. Possible values are: day, week, month, list.
* @example $("#eventscalendar").wijevcal(
* { viewType: "month" });
*/
this.viewType = "day";
/** Array of the calendar names which need to be shown.
* @type {Array}
* @example
* $("#eventscalendar").wijevcal("option",
* "visibleCalendars", ["My Calendar"]);
*/
this.visibleCalendars = new Array("Default");
/**
* The minimum width of the eventcalendar.
*/
this.minWidth = 750;
/** Occurs when calendars option has been changed.
* @event
* @dataKey {object} calendars the new calendars option value.
*/
this.calendarsChanged = null;
/** Occurs when events calendar is constructed and events
* data is loaded from an external or local data source.
* @event
*/
this.initialized = null;
/** Occurs when selectedDates option has been changed.
* Event type: wijevcalselecteddateschanged
* @event
* @dataKey {object} selectedDates the new selectedDates value.
*/
this.selectedDatesChanged = null;
/** Occurs when viewType option has been changed.
* @event
* @param {string} viewType The new viewType value.
*/
this.viewTypeChanged = null;
/** Occurs before the built-in event dialog is shown.
* Return false or call event.preventDefault() in order to cancel event and
* prevent the built-in dialog to be shown.
* @event
* @dataKey {object} data This is the event data.
* @dataKey {DOMElement} targetCell This is target offset DOM element which can be used for popup callout.
*/
this.beforeEditEventDialogShow = null;
/** Occurs before the add event action.
* Return false or call event.preventDefault() in order to cancel event and
* prevent the add action.
* @event
* @dataKey {object} data This is the new event data that should be added to a data source.
*/
this.beforeAddEvent = null;
/** Occurs before the update event action.
* Return false or call event.preventDefault() in order to cancel event and
* prevent the update action.
* @event
* @dataKey {object} data This is the new event data that should be added to a data source.
* @dataKey {object} prevData This is previous event data.
*/
this.beforeUpdateEvent = null;
/** Occurs before the delete action.
* Return false or call event.preventDefault() in order to cancel event and
* prevent the delete action.
* @event
* @dataKey {object} data This is the event object that should be deleted.
*/
this.beforeDeleteEvent = null;
/** Occurs before the add calendar action.
* Return false or call event.preventDefault() in order to cancel event and
* prevent the add action.
* @event
* @dataKey {object} data This is the new calendar data that should be added to a data source.
*/
this.beforeAddCalendar = null;
/** Occurs before the update calendar action.
* Return false or call event.preventDefault() in order to cancel event and
* prevent the update action.
* @event
* @dataKey {object} data This is the new event data that should be added to a data source.
* @dataKey {object} prevData This is previous event data.
*/
this.beforeUpdateCalendar = null;
/** Occurs before the delete calendar action.
* Return false or call event.preventDefault() in order to cancel event and
* prevent the delete action.
* @event
* @dataKey {object} data This is the calendar data that should be deleted from a data source.
*/
this.beforeDeleteCalendar = null;
/** Occurs when the eventsData option is changed.
* @event
* @dataKey {object} eventsData This is array of the event objects.
*/
this.eventsDataChanged = null;
}
return wijevcal_options;
})();
wijevcal.prototype.options = $.extend(true, {
}, wijmo.wijmoWidget.prototype.options, new wijevcal_options());
$.wijmo.registerWidget(widgetName, wijevcal.prototype);
})(wijmo.evcal || (wijmo.evcal = {}));
var evcal = wijmo.evcal;
})(wijmo || (wijmo = {}));
;
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
/// <reference path="../Base/jquery.wijmo.widget.ts" />
/*globals jQuery*/
/*
* Depends:
* jquery.mobile.js
*
*/
(function (appview) {
"use strict";
var $ = jQuery, widgetName = "wijappview", roles = {
menu: "menu",
content: "content",
header: "header",
footer: "footer",
page: "appviewpage"
}, dataAttributes = {
adjusted: widgetName + "-adjusted"
}, initialHash = "", forceUpdateUrl = false;
$.fn.findRole = function (role) {
return this.find(":jqmData(role='" + role + "')");
};
var wijappview = (function (_super) {
__extends(wijappview, _super);
function wijappview() {
_super.apply(this, arguments);
this._updatingUrl = false;
}
wijappview.prototype._appViewCSS = // #region Initialization
function () {
return this.options.wijCSS.wijappview;
};
wijappview.prototype._initMenu = function () {
this._menuDiv = this.element.findRole(roles.menu);
if(!this._menuDiv.length) {
throw "A DIV with data-role='" + roles.menu + "' not found!";
}
this._linkList = this._menuDiv.find("ul");
if(!this._linkList.length) {
throw "Invalid markup. Link list not found";
}
this._menuDiv.addClass(this._appViewCSS().menu);
};
wijappview.prototype._initPages = function ($pages, fileUrl) {
var pageStore = this._pageStore, css = this._appViewCSS();
$pages.each(function () {
var page = $(this).addClass(css.page), id = page.attr("id"), dataUrl = fileUrl;
if(page.jqmData("url")) {
return;
}
if(id) {
dataUrl += "#" + id;
}
page.attr("data-url", dataUrl);
});
};
wijappview.prototype._initPageContainer = function () {
var css = this._appViewCSS(), pageStore = this._pageStore;
this._pageContainer = $("<div/>").addClass(css.pageContainer).prependTo(this.element);
var pages = this.element.findRole(roles.page);
this._initPages(pages, this._documentUrl);
pages.each(function (index) {
pageStore.push($(this).clone());
if(index > 0) {
$(this).remove();
}
});
this._firstPage = pages.first().addClass(css.pageActive).appendTo(this._pageContainer);
this._initCurrentPage();
};
wijappview.prototype._getUrl = function (elem) {
var urlAttrName = elem.is("form") ? "action" : "href", url = elem.attr(urlAttrName);
if(!url || url === "#") {
return null;
}
if($.mobile.path.isRelativeUrl(url)) {
elem.parents(":jqmData(url)").each(function (_, parent) {
var parentUrl = $(parent).jqmData("url");
if(parentUrl && $.mobile.path.isAbsoluteUrl(parentUrl)) {
url = $.mobile.path.makeUrlAbsolute(url, parentUrl);
return false;
}
});
}
return url;
};
wijappview.prototype._hijackLinks = function (root) {
var _this = this;
root.on("click." + widgetName, "a, .ui-btn", function (e) {
if(e.isDefaultPrevented()) {
return;
}
var link = _this._findClosestLink(e.target);
if(!link || $(link).jqmData("appviewpage") === false) {
return;
}
var url = _this._getUrl($(link));
if(url) {
e.preventDefault();
e.stopPropagation();
_this.changePage(url);
}
});
};
wijappview.prototype._hijackForms = function (root) {
var _this = this;
root.on("submit." + widgetName, "form", function (e) {
if(e.isDefaultPrevented()) {
return;
}
var $form = $(e.currentTarget), $page = $form.closest("." + _this._appViewCSS().page);
if(!$.mobile.ajaxEnabled || // test that the form is, itself, ajax false
$form.is(":jqmData(ajax='false')") || // test that $.mobile.ignoreContentEnabled is set and
// the form or one of it's parents is ajax=false
!$form.jqmHijackable().length) {
return;
}
var type = $form.attr("method"), target = $form.attr("target"), url = _this._getUrl($form);
e.preventDefault();
e.stopPropagation();
_this.changePage(url, {
type: type && type.length && type.toLowerCase() || "get",
data: $form.serialize(),
reloadPage: true
});
});
};
wijappview.prototype._initNavigation = function () {
var _this = this;
this._onPopStateScoped = this._onPopStateScoped || $.proxy(this._onPopState, this);
$(window).bind("popstate." + widgetName, this._onPopStateScoped);
$(window).bind("appviewpagehashchange." + widgetName, function () {
return _this._navigateToCurrentLocation();
});
this._onNavigateScoped = this._onNavigateScoped || $.proxy(this._onNavigate, this);
$($.mobile.pageContainer).bind("navigate." + widgetName, this._onNavigateScoped);
};
wijappview.prototype._create = function () {
this._pageStore = [];
this._documentUrl = this._removePageUrlParam(location.href);
this.element.attr("data-url", this._documentUrl);
this.element.addClass(this._appViewCSS().outerDiv);
this._initMenu();
this._initPageContainer();
this._hijackLinks(this.element);
this._hijackForms(this.element);
this._initNavigation();
this._navigateToCurrentLocation();
};
wijappview.prototype.destroy = function () {
_super.prototype.destroy.call(this);
var dotNs = "." + widgetName;
this.element.unbind(dotNs);
$(window).unbind(dotNs);
$($.mobile.pageContainer).unbind(dotNs);
};
wijappview.prototype._initCurrentPage = // #endregion
function () {
var css = this._appViewCSS();
var page = this.activePage();
page.findRole(roles.content).addClass(css.content);
var header = page.findRole(roles.header).addClass(css.header);
var position = header.jqmData("position");
var headerFixed = !position || position === "fixed";
if(headerFixed) {
header.addClass("ui-header-fixed");
}
this.element.toggleClass(css.withFixedHeader, headerFixed);
};
wijappview.prototype._findClosestLink = function (ele) {
while(ele && !(typeof ele.nodeName === "string" && ele.nodeName.toLowerCase() === "a")) {
ele = ele.parentNode;
}
return ele;
};
wijappview.prototype._clickHandler = function (e) {
var target = $(e.currentTarget), url = target.is("li") ? target.jqmData("url") : target.is("a") ? target.attr("href") : null;
if(!url) {
return;
}
e.preventDefault();
e.stopPropagation();
this.changePage(url);
};
wijappview.prototype._inheritAttribute = function (src, dest, attrName) {
if(src.attr(attrName) && !dest.attr(attrName)) {
dest.attr(attrName, src.attr(attrName));
}
};
wijappview.prototype.loadPage = function (url, options) {
var _this = this;
url = url || "";
// This function uses deferred notifications to let callers
// know when the page is done loading, or if an error has occurred.
var deferred = $.Deferred(), path = $.mobile.path, settings = $.extend({
}, this.options.loadSettings, options), isLocal = !url || url.charAt(0) === "#", page = // The DOM element for the page after it has been loaded.
null, dupCachedPage = // If the reloadPage option is true, and the page is already
// in the DOM, dupCachedPage will be set to the page element
// so that it can be removed after the new version of the
// page is loaded off the network.
null, absUrl = this._makeAbsoluteUrl(url);
// ==== Disable caching for now ====
// Check to see if the page already exists in the DOM.
// NOTE do _not_ use the :jqmData psuedo selector because parenthesis
// are a valid url char and it breaks on the first occurence
// page = $($.grep(this._pageStore, (p) => p.jqmData("url") === absUrl)[0]).clone();
// If the page we are interested in is already in the DOM,
// and the caller did not indicate that we should force a
// reload of the file, we are done. Otherwise, track the
// existing page as a duplicated.
//if (page.length) {
// if (isLocal || !settings.reloadPage) {
// // enhancePage(page, settings.role);
// deferred.resolve(absUrl, options, page);
// return deferred.promise();
// }
// dupCachedPage = page;
//}
if(settings.data) {
switch(settings.type) {
case "get":
absUrl = path.addSearchParams(absUrl, settings.data);
settings.data = undefined;
break;
case "post":
settings.reloadPage = true;
break;
}
}
var pblEvent = $.Event("pagebeforeload"), triggerData = {
url: url,
absUrl: absUrl,
dataUrl: absUrl,
deferred: deferred,
options: settings
};
// Let listeners know we're about to load a page.
this._trigger(pblEvent.type, pblEvent, triggerData);
// If the default behavior is prevented, stop here!
if(pblEvent.isDefaultPrevented()) {
return deferred.promise();
}
if(!$.mobile.allowCrossDomainPages && !path.isSameDomain(path.parseLocation(), absUrl)) {
deferred.reject(absUrl, options);
return deferred.promise();
}
// The absolute version of the URL minus any dialog/subpage params.
// In otherwords the real URL of the page to be loaded.
var fileUrl = absUrl && path.getFilePath(absUrl).replace(/#.+/, "");
// Load the new page.
var xhr = $.ajax({
url: fileUrl,
type: settings.type,
data: settings.data,
dataType: "html",
success: function (html, textStatus, xhr) {
//pre-parse html to check for a data-url,
//use it as the new fileUrl, base path, etc
var all = $("<div></div>"), pageElemRegex = // TODO handle dialogs again
new RegExp("(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?" + roles.page + "[\"']?[^>]*>)"), dataUrlRegex = new RegExp("\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?");
function tryMakeAbsolute(url) {
if(path.isAbsoluteUrl(url) || /^(\w+:|#|\/)/.test(url)) {
return null;
}
return path.makeUrlAbsolute(url, fileUrl);
}
if($.browser.msie && parseFloat($.browser.version) <= 7) {
// for some reason IE7 automatically makes all links absolute before I do it.
// I have to use regex in this case
html = html.replace(/<a[^>]+href=['"][^'"]+['"]/g, function (link) {
return link.replace(/href=['"]([^'"]+)['"]/, function (m, url) {
url = tryMakeAbsolute(url) || url;
return "href='" + url + "'";
});
});
}
//workaround to allow scripts to execute when included in page divs
all.get(0).innerHTML = html;
var allPages = _this._getAllPages(all, url);
//if page elem couldn't be found, create one and insert the body element's contents
if(!allPages.length) {
allPages = $("<div/>").attr("data-role", roles.page).html(html.split(/<\/?body[^>]*>/gmi)[1]);
}
var pageTitleFromHead = html.match(/<title[^>]*>([^<]*)/) && RegExp["$1"];
if(pageTitleFromHead && ~pageTitleFromHead.indexOf("&")) {
pageTitleFromHead = $("<div>" + pageTitleFromHead + "</div>").text();
}
// fix data-title
allPages.each(function (i, page) {
page = $(page);
page.attr("data-external-page", true);
// fix data-title
if(!page.jqmData("title") && pageTitleFromHead) {
page.attr("data-title", pageTitleFromHead);
}
//rewrite src and href attrs to use a base url
var newPath = path.get(fileUrl);
page.find("[src], [href]").each(function () {
var thisAttr = $(this).is('[href]') ? 'href' : $(this).is('[src]') ? 'src' : 'action', url = tryMakeAbsolute($(this).attr(thisAttr));
if(url) {
$(this).attr(thisAttr, url);
}
});
});
_this._initPages(allPages, fileUrl);
// Let listeners know the page loaded successfully.
// Add the page reference and xhr to our triggerData.
page = allPages.filter(function () {
return $(this).jqmData("url") === absUrl;
});
if(!page.length) {
page = allPages.first();
}
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.page = page;
triggerData.allPages = allPages;
_this._trigger("pageload", null, triggerData);
allPages.each(function (i, p) {
_this._pageStore.push($(p).clone());
});
deferred.resolve(absUrl, options, page, dupCachedPage);
},
error: function (xhr, textStatus, errorThrown) {
// Add error info to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.errorThrown = errorThrown;
var plfEvent = $.Event("pageloadfailed");
// Let listeners know the page load failed.
_this._trigger(plfEvent.type, plfEvent, triggerData);
// If the default behavior is prevented, stop here!
// Note that it is the responsibility of the listener/handler
// that called preventDefault(), to resolve/reject the
// deferred object within the triggerData.
if(plfEvent.isDefaultPrevented()) {
return;
}
// Remove loading message.
//if (settings.showLoadMsg) {
// Remove loading message.
// hideMsg();
// show error message
// $.mobile.showPageLoadingMsg($.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true);
// hide after delay
// setTimeout($.mobile.hidePageLoadingMsg, 1500);
//}
deferred.reject(absUrl, options);
}
});
deferred.fail(function () {
xhr.abort();
});
return deferred;
};
wijappview.prototype._getAllPages = function (html, url) {
return html.findRole(roles.page);
};
wijappview.prototype.activePage = function () {
return this._pageContainer.children("." + this._appViewCSS().pageActive).first();
};
wijappview.prototype.isMenuUrl = function (url) {
var that = this;
url = url.toLowerCase();
return this._menuDiv.find("a").is(function () {
return that._getUrl($(this)).toLowerCase() === url;
});
};
wijappview.prototype.showLoading = function () {
$.mobile.loading("show");
};
wijappview.prototype.hideLoading = function () {
$.mobile.loading("hide");
};
wijappview.prototype.changePage = function (toPage, options) {
var _this = this;
options = $.extend({
updateUrl: true
}, options);
var triggerData = {
toPage: toPage,
options: options
};
if(this._curRequest && this._curRequest.state() === "pending" && this._curRequest.rejectWith) {
this._curRequest.rejectWith(this, [
toPage,
options,
true
]);
}
if(typeof toPage === "string") {
var currentDataUrl = this.activePage().data("url");
var toPageAbs = this._makeAbsoluteUrl(toPage);
this._updateUIBeforeChange(toPageAbs);
this.showLoading();
this._curRequest = this.loadPage(toPage, options).always(function () {
_this.hideLoading();
_this._curRequest = null;
}).done(function (url, options, page, dupCachedPage) {
_this._updateUIAfterChange(page.jqmData("url"));
_this.changePage(page, options);
}).fail(function (url, options, anotherPage) {
if(!anotherPage) {
_this._updateUI(currentDataUrl);
}
_this._trigger("pagechangefailed", null, triggerData);
});
return;
}
var pbcEvent = $.Event("pagebeforechange");
this._trigger(pbcEvent.type, pbcEvent, triggerData);
if(pbcEvent.isDefaultPrevented()) {
return;
}
var absUrl = toPage.jqmData("url"), relUrl = null;
this._updateUI(absUrl);
if(absUrl) {
relUrl = this._makeRelative(absUrl);
if(relUrl != null) {
relUrl = this._makeRelative(relUrl);
}
}
var pageTitle = toPage.jqmData("title"), header = toPage.findRole("header"), css = this._appViewCSS();
if(!header.length && pageTitle) {
header = $("<div data-role='header'/>").append($("<h2/>").text(pageTitle)).prependTo(toPage);
}
if(header.length && !header.jqmData(dataAttributes.adjusted)) {
header.jqmData(dataAttributes.adjusted, true);
var oldHeader = this._firstPage.findRole(roles.header);
if(oldHeader) {
this._inheritAttribute(oldHeader, header, "data-position");
}
if(this.isMenuUrl(absUrl) && !header.find("a[data-icon=back]").length) {
$("<a/>").attr({
href: this._documentUrl,
"data-icon": "back"
}).text("Back").prependTo(header);
}
}
if(pageTitle) {
document.title = pageTitle;
}
this._pageContainer.children().removeClass(css.pageActive);
toPage.addClass(css.pageActive).appendTo(this._pageContainer.empty());
this._initCurrentPage();
if(options.updateUrl || forceUpdateUrl) {
this._updateUrl(absUrl, relUrl, document.title);
forceUpdateUrl = false;
}
toPage.jqmData("page", $.mobile.activePage.jqmData("page")).trigger("pagecreate").trigger(this.widgetEventPrefix + "pageinit", triggerData);
// TODO: temporary workaround
this._trigger("pagechange", null, triggerData);
};
wijappview.prototype._updateUIBeforeChange = function (pageUrl) {
var that = this, isRoot = pageUrl === this._documentUrl;
var menuItems = this._linkList.find("li"), activeClass = this._appViewCSS().menuItemActive;
if(isRoot) {
menuItems.removeClass(activeClass);
} else {
var newMenuItem = menuItems.filter(function () {
var url = that._getUrl($(this).find("a"));
return url && url.toLowerCase() === pageUrl.toLowerCase();
});
if(newMenuItem.length && !newMenuItem.hasClass(activeClass)) {
menuItems.removeClass(activeClass);
newMenuItem.addClass(activeClass);
}
}
};
wijappview.prototype._updateUIAfterChange = function (pageUrl) {
var css = this._appViewCSS(), isRoot = pageUrl === this._documentUrl;
this.element.toggleClass(css.inPage, !isRoot);
};
wijappview.prototype._updateUI = function (pageUrl) {
this._updateUIBeforeChange(pageUrl);
this._updateUIAfterChange(pageUrl);
};
wijappview.prototype._changePageIfDifferent = function (toPage, options) {
var targetUrl = typeof toPage === "string" ? toPage : toPage.jqmData("url");
if(this.activePage().jqmData("url") !== targetUrl) {
this.changePage(toPage, options);
}
};
wijappview.prototype._onNavigate = function (e) {
var hashRgx = new RegExp("^#?" + this.options.urlParamName + "=");
if(history.state && history.state.wijappview || document.location.hash.match(hashRgx)) {
e.preventDefault();
}
};
wijappview.prototype._removePageUrlParam = function (url) {
return url.replace(/\#.*$/, "");
};
wijappview.prototype._addUrl = function (pageUrl) {
var param = this.options.urlParamName;
var url = this._removePageUrlParam(location.href);
if(pageUrl) {
url += "#" + param + "=" + pageUrl;
}
return url;
};
wijappview.prototype._makeRelative = function (absUrl) {
var loc = $.mobile.path.parseLocation();
var url = absUrl;
if(absUrl) {
var baseDir = loc.domain + loc.directory;
if(absUrl.substr(0, loc.hrefNoHash.length) === loc.hrefNoHash) {
url = absUrl.substr(loc.hrefNoHash.length);
} else if(absUrl.substr(0, baseDir.length) === baseDir) {
url = absUrl.substr(baseDir.length);
}
}
return url;
};
wijappview.prototype._makeAbsoluteUrl = function (url) {
var path = $.mobile.path, activePage = this.activePage(), curAbsUrl = path.makeUrlAbsolute(activePage.jqmData("url") || this._documentUrl, this._documentUrl);
if(!curAbsUrl.match(/\/$/) && !curAbsUrl.match(/\./)) {
curAbsUrl += "/";
}
return url && path.makeUrlAbsolute(url, curAbsUrl);
};
wijappview.prototype._onPopState = function (e) {
if(this._updatingUrl) {
return;
}
if(history.state && history.state.wijappview) {
this._changePageIfDifferent(history.state.absUrl || this._firstPage, {
updateUrl: false
});
} else {
this._navigateToCurrentLocation();
}
};
wijappview.prototype._navigateToCurrentLocation = function () {
var rgx = new RegExp("#" + this.options.urlParamName + "=(.+)"), match = rgx.exec(location.href) || initialHash && rgx.exec(initialHash), toPage = match ? $.mobile.path.makeUrlAbsolute(match[1], this._documentUrl) : this._firstPage;
initialHash = "";
this._changePageIfDifferent(toPage, {
updateUrl: false
});
};
wijappview.prototype._updateUrl = function (absUrl, relUrl, title) {
this._updatingUrl = true;
try {
$.mobile.urlHistory.ignoreNextHashChange = true;
document.location.hash = absUrl === this._documentUrl ? "" : this.options.urlParamName + "=" + relUrl;
}finally {
this._updatingUrl = false;
}
};
return wijappview;
})(wijmo.wijmoWidget);
appview.wijappview = wijappview;
var mainClass = "wijmo-wijappview", classPrefix = mainClass + "-";
wijappview.prototype.options = $.extend({
}, wijmo.wijmoWidget.prototype.options, {
urlParamName: "appviewpage",
loadSettings: {
type: "GET",
data: undefined,
reloadPage: false,
showLoadMsg: false,
loadMsgDelay: 50
},
wijCSS: // This delay allows loads that pull from browser cache to occur without showing the loading message.
{
wijappview: {
outerDiv: mainClass,
inPage: classPrefix + "in-page",
menu: classPrefix + "menu",
menuItemActive: "ui-btn-down-b",
page: classPrefix + "page",
pageActive: classPrefix + "page-active",
pageContainer: classPrefix + "page-container",
content: classPrefix + "content",
header: classPrefix + "header",
withFixedHeader: classPrefix + "with-fixed-header"
}
}
});
function isAppViewPageUrl() {
return document.location.hash.match(/^#\w+=/);
}
if($.mobile) {
$.wijmo.registerWidget(widgetName, wijappview.prototype);
$(window).bind("hashchange", function (e) {
if(isAppViewPageUrl()) {
e.stopImmediatePropagation();
$(window).trigger("appviewpagehashchange");
}
});
// prevent initial jQM page transition
if(isAppViewPageUrl()) {
initialHash = document.location.hash;
$(window).bind("pagecontainercreate", function () {
document.location.hash = "";
forceUpdateUrl = true;
});
}
}
})(wijmo.appview || (wijmo.appview = {}));
var appview = wijmo.appview;
})(wijmo || (wijmo = {}));
/*
*
* Wijmo Library 3.20132.9
* http://wijmo.com/
*
* Copyright(c) GrapeCity, Inc. All rights reserved.
*
* Dual licensed under the MIT or GPL Version 2 licenses.
* licensing@wijmo.com
* http://wijmo.com/widgets/license/
*
*/
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var wijmo;
(function (wijmo) {
(function (ng) {
// declare the Node variable explicitly because IE8 and older versions do not expose it.
var Node;
(function (Node) {
Node._map = [];
Node.ELEMENT_NODE = 1;
Node.ATTRIBUTE_NODE = 2;
Node.TEXT_NODE = 3;
Node.CDATA_SECTION_NODE = 4;
Node.ENTITY_REFERENCE_NODE = 5;
Node.ENTITY_NODE = 6;
Node.PROCESSING_INSTRUCTION_NODE = 7;
Node.COMMENT_NODE = 8;
Node.DOCUMENT_NODE = 9;
Node.DOCUMENT_TYPE_NODE = 10;
Node.DOCUMENT_FRAGMENT_NODE = 11;
Node.NOTATION_NODE = 12;
})(Node || (Node = {}));
function getTypeDefFromExample(value) {
if(value == null) {
return {
};
}
var meta = {
type: angular.isArray(value) ? "array" : typeof value
};
switch(meta.type) {
case "object":
meta.properties = {
};
if(value) {
$.each(value, function (key, propValue) {
meta.properties[key] = getTypeDefFromExample(propValue);
});
}
break;
case "array":
meta.elementType = getTypeDefFromExample(value[0]);
break;
}
return meta;
}
var propPath;
(function (propPath) {
function partition(path) {
if(typeof path !== "string") {
return path;
}
var parts = path.split(/[\.\[\]]/g);
for(var i = parts.length - 1; i >= 0; i--) {
if(!parts[i]) {
parts.splice(i, 1);
}
}
return parts;
}
propPath.partition = partition;
function get(obj, path) {
var parts = partition(path);
for(var i = 0; obj && i < parts.length; i++) {
obj = obj[parts[i]];
}
return obj;
}
propPath.get = get;
function set(obj, path, value) {
var parts = partition(path);
var last = parts.pop();
obj = get(obj, parts);
if(obj) {
obj[last] = value;
}
}
propPath.set = set;
})(propPath || (propPath = {}));
var ngTools;
(function (ngTools) {
function onDigest(scope, fn) {
var removeWatcher;
var removeWatcher = scope.$watch("any", function () {
if(removeWatcher) {
removeWatcher();
removeWatcher = null;
}
fn();
});
}
ngTools.onDigest = onDigest;
})(ngTools || (ngTools = {}));
function safeApply(scope, data) {
var phase = scope.$root.$$phase;
if(phase !== '$apply' && phase !== '$digest') {
scope.$apply(data);
}
}
var Subelement = (function () {
function Subelement(element, link) {
this.element = element;
this.link = link;
}
return Subelement;
})();
var TextEvalEntry = (function () {
function TextEvalEntry(expr) {
this.expr = expr;
}
return TextEvalEntry;
})();
var TextEval = (function () {
function TextEval(text, scope, onChange) {
this.text = text;
this.scope = scope;
this.onChange = onChange;
var _this = this;
this.entries = {
};
var match;
while(match = TextEval.exprRegex.exec(text)) {
var expr = match[1];
if(this.entries[expr]) {
continue;
}
this.entries[expr] = new TextEvalEntry(expr);
}
angular.forEach(this.entries, function (e) {
var assigned = false;
scope.$watch(e.expr, function (value) {
assigned = true;
if(e.value == value) {
return;
}
e.value = value;
_this.update();
});
if(!assigned) {
e.value = scope.$eval(expr);
}
});
this.update();
}
TextEval.exprRegex = /{{([^}]+)}}/g;
TextEval.prototype.update = function () {
var _this = this;
var result = this.text.replace(TextEval.exprRegex, function (m, name) {
var entry = _this.entries[name];
return entry && entry.value;
});
if(result == this.result) {
return;
}
this.result = result;
if(this.onChange) {
this.onChange(result);
}
};
return TextEval;
})();
function parsePrimitiveValue(text, type) {
// if the type is a number or boolean, then parse it.
// if it is not an object or the node is not an element, return the text
switch(type.toLowerCase()) {
case "boolean":
return text.toLowerCase() === "true";
case "number":
return parseFloat(text);
case "date":
case "datetime":
return Globalize.parseDate(text);
default:
return null;
}
}
var Markup = (function () {
function Markup(node, typeDef, selector, services) {
this.selector = selector;
this.services = services;
this.innerMarkupTemplate = "<div/>";
this.bindings = [];
this.subElements = [];
var $node = $(node);
this.parseInnerMarkup($node);
this.parseOptions($node, typeDef);
}
Markup.prototype.moveContents = function (from, to) {
function moveAttr(name) {
var value = from.attr(name);
if(value) {
to.attr(name, value);
from.removeAttr(name);
}
}
from.children().each(function (_, child) {
return to.append(child);
});
if(!to.children().length) {
to.text(from.text());
}
moveAttr("id");
moveAttr("style");
moveAttr("class");
return to;
};
Markup.prototype.extractSubelements = function (element) {
if(!this.selector) {
return;
}
var e = $(element);
if(e.is(this.selector)) {
var clone = element.clone();
var converted = this.moveContents(element, $(this.innerMarkupTemplate));
this.subElements.push(new Subelement(clone, this.services.$compile(converted)));
e.empty();
}
};
Markup.allowedInnerHtmlSelector = "div, span, table, ul, ol, p, li, h1, h2, h3, h4";
Markup.prototype.parseInnerMarkup = function (element) {
var _this = this;
var addInnerNode = function ($node) {
var clone = $node.clone();
_this.subElements.push(new Subelement(clone, _this.services.$compile($node)));
$node.remove();
};
element.children(Markup.allowedInnerHtmlSelector).each(function (_, e) {
return addInnerNode($(e));
});
var container = element.children("inner-markup");
if(container.length > 0) {
container.children().each(function (_, e) {
return addInnerNode($(e));
});
container.remove();
}
};
Markup.prototype.apply = function (scope, parentElement) {
angular.forEach(this.subElements, function (se) {
return se.link(scope.$parent, function (el) {
return parentElement.append(el);
});
});
};
Markup.prototype.getNameMap = // get camelCase name -> lowercase property name mapping
function (obj) {
var map = {
}, key;
for(key in obj) {
map[key.toLowerCase()] = key;
}
return map;
};
Markup.prototype.parseOptions = function ($node, typeDef) {
this.options = this.parse($node, typeDef, "");
};
Markup.prototype.parse = function ($node, typeDef, path) {
var _this = this;
var readNode = function (node) {
var $node = $(node), value, name, propPath;
switch(node.nodeType) {
case Node.ATTRIBUTE_NODE:
value = $node.val();
break;
case Node.ELEMENT_NODE:
value = $node.text();
break;
default:
return;
}
// restore the original property name casing if possible
name = node.nodeName || node.name;
name = name.toLowerCase();
if(map[name]) {
name = map[name];
} else if(name.match(/-/)) {
var parts = name.split("-");
name = parts.shift();
angular.forEach(parts, function (p) {
return name += p.charAt(0).toUpperCase() + p.substring(1);
});
}
var metadata = properties && properties[name];
if(!hasChildElements(node) && value && value.match(/{{/)) {
toRemove.push(node);
_this.bindings.push({
typeDef: metadata,
path: (path && path + ".") + name,
dynamicText: value
});
return;
}
if(node.nodeType === Node.ELEMENT_NODE && array) {
// then push the sub-element
array.push(_this.parse($node, typeDef && typeDef.elementType, path + "[" + array.length + "]"));
} else {
if(value.match(/^[^\d]/) && node.nodeType === Node.ATTRIBUTE_NODE && metadata && (metadata.changeEvent || metadata.twoWayBinding)) {
toRemove.push(node);
_this.bindings.push({
path: (path && path + ".") + name,
expression: value
});
} else {
obj[name] = _this.parse($node, metadata, (path && path + ".") + name);
}
}
};
var node = $node[0], text = node.nodeType === Node.TEXT_NODE ? (node).wholeText : (node).value, isArray = typeDef && typeDef.type === "array", properties = typeDef && typeDef.properties, map = // we need this lowercase name map because HTML IS NOT CASE-SENSITIVE! Chris said that.
properties && this.getNameMap(properties) || {
}, toRemove = [], obj, array, primitiveTypeRequested;
if(node.nodeType === Node.ELEMENT_NODE) {
this.extractSubelements($node);
}
var primitiveValue = typeDef && typeDef.type ? parsePrimitiveValue(text, typeDef && typeDef.type) : null;
if(primitiveValue !== null) {
return primitiveValue;
} else if(primitiveValue == null) {
primitiveTypeRequested = typeDef && typeDef.type && typeDef.type !== "object" && typeDef.type !== "array";
if(primitiveTypeRequested || node.nodeType !== Node.ELEMENT_NODE) {
return text;
}
}
// parse a DOM element to an object/array
if(isArray) {
array = [];
} else {
obj = {
};
}
// read attributes
angular.forEach(node.attributes, readNode);
angular.forEach(node.childNodes, readNode);
$.each(toRemove, function (_, node) {
if(node.nodeType === Node.ATTRIBUTE_NODE) {
$(node.ownerElement).removeAttr(node.name);
} else {
$(node).remove();
}
});
return obj || array;
};
return Markup;
})();
var definitions;
(function (definitions) {
var DirectiveBase = (function () {
function DirectiveBase(widgetName, namespace, clazz, services) {
this.widgetName = widgetName;
this.namespace = namespace;
this.services = services;
this.internalEventPrefix = "wijmo-angular";
this.fullWidgetName = namespace + widgetName.charAt(0).toUpperCase() + widgetName.substr(1);
this.wijMetadata = DirectiveBase.mergeMetadata(widgetName, clazz.prototype.options);
this.eventPrefix = clazz.prototype.widgetEventPrefix || widgetName;
}
DirectiveBase.mergeMetadata = function mergeMetadata(widgetName, options) {
var fromOptions = {
properties: getTypeDefFromExample(options).properties
}, result = $.extend({
}, fromOptions, widgetMetadata["base"]), inheritanceStack = [], parentName = widgetName;
do {
inheritanceStack.unshift(parentName);
parentName = widgetMetadata[parentName] && widgetMetadata[parentName].inherits;
}while(parentName);
angular.forEach(inheritanceStack, function (name) {
return $.extend(true, result, widgetMetadata[name]);
});
return result;
};
DirectiveBase.prototype.transition = function () {
if(Object.create) {
try {
return Object.create(this);
} catch (err) {
}
}
var Clazz = function () {
};
Clazz.prototype = this;
return new Clazz();
};
DirectiveBase.prototype.compile = // ----- compiled state -----
function (tElem, tAttrs, $compile) {
return this.transition()._compile(tElem, tAttrs, $compile);
};
DirectiveBase.prototype._compile = function (tElem, tAttrs, $compile) {
return $.proxy(this.link, this);
};
DirectiveBase.prototype._initWidget = function () {
this.widget = this.element.data(this.widgetName) || this.element.data(this.fullWidgetName);
};
DirectiveBase.prototype.link = function (scope, elem, attrs) {
var transitioned = this.transition();
transitioned.$scope = scope;
transitioned.element = elem;
transitioned._link(attrs);
};
DirectiveBase.prototype._link = function (attrs) {
var _this = this;
ngTools.onDigest(this.$scope.$parent, function () {
_this._createInstance(attrs);
_this._initWidget();
});
};
DirectiveBase.prototype._createInstance = function (attrs) {
};
DirectiveBase.prototype.bindToWidget = function (name, handler) {
var fullName = this.eventPrefix + name.toLowerCase() + "." + this.internalEventPrefix;
this.element.bind(fullName, handler);
};
return DirectiveBase;
})();
definitions.DirectiveBase = DirectiveBase;
var AttributeDirective = (function (_super) {
__extends(AttributeDirective, _super);
function AttributeDirective(widgetName, namespace, clazz, services) {
_super.call(this, widgetName, namespace, clazz, services);
this.delay = false;
}
AttributeDirective.prototype._createInstance = // ----- linked state-----
function (attrs) {
var _this = this;
var create = function () {
_this.element[_this.widgetName]();
};
if(this.delay) {
setTimeout(create, 0);
} else {
create();
}
};
return AttributeDirective;
})(DirectiveBase);
definitions.AttributeDirective = AttributeDirective;
var ElementDirective = (function (_super) {
__extends(ElementDirective, _super);
function ElementDirective(widgetName, namespace, clazz, services) {
_super.call(this, widgetName, namespace, clazz, services);
this.expectedTemplate = "<div/>";
this.restrict = 'E';
// require mapping to a DOM element
this.replace = true;
this.scope = {
};
this.innerMarkupSelector = null;
this.scopeWatchers = {
};
this.registerEvents();
}
ElementDirective.prototype.registerEvents = function () {
var _this = this;
// TODO: optimize this. No need to watch for all events if handlers are not specified
if(!this.wijMetadata.events) {
return;
}
$.each(this.wijMetadata.events, function (name) {
_this.scope[name] = "=" + name.toLowerCase();
_this.scopeWatchers[name] = function (handler) {
this.bindToWidget(name, handler);
};
});
};
ElementDirective.prototype.createMarkup = function (elem, typeDef) {
return new Markup(elem[0], typeDef, this.innerMarkupSelector, this.services);
};
ElementDirective.prototype.parseMarkup = function (elem) {
var markup = this.createMarkup(elem, {
type: "object",
properties: this.wijMetadata.properties
});
markup.options.dataSource = [];
return markup;
};
ElementDirective.prototype._compile = // ---- compiled state-----
function (tElem, tAttrs, $compile) {
this.markup = this.parseMarkup(tElem);
return _super.prototype._compile.call(this, tElem, tAttrs, $compile);
};
ElementDirective.prototype._link = // ----- linked state -----
function (attrs) {
// create a widget instance
this.element = $(this.expectedTemplate).replaceAll(this.element);
this.markup.apply(this.$scope, this.element);
_super.prototype._link.call(this, attrs);
};
ElementDirective.prototype.createInstanceCore = function (options) {
this.element[this.widgetName](options);
};
ElementDirective.prototype._createInstance = function (attrs) {
// move style and class to the new element
this.element.attr({
style: attrs.style,
id: attrs.id,
"class": attrs["class"]
});
this.createInstanceCore(this.markup.options);
this._initWidget();
this.wireData();
};
ElementDirective.prototype.wireData = function () {
var _this = this;
var parentScope = this.$scope.$parent, applyingOptions = {
};
// setup directive scope watches
$.each(this.scopeWatchers, function (name, handler) {
return _this.$scope.$watch(name, $.proxy(handler, _this), true);
});
// establish two-way data binding between widget options and a view model (parent scope)
$.each(this.markup.bindings, function (_, binding) {
if(binding.dynamicText) {
var textEval = new TextEval(binding.dynamicText, parentScope, function (text) {
var value = text;
if(binding.typeDef && binding.typeDef.type) {
value = parsePrimitiveValue(value, binding.typeDef.type) || value;
}
_this.setOption(binding.path, value);
});
return;
}
// listen to changes in the view model
var didAssign = false;
parentScope.$watch(binding.expression, function (value) {
if(applyingOptions[binding.path] && _this.widget.option(binding.path) === value) {
return;
}
_this.setOption(binding.path, value);
didAssign = true;
}, true);
if(!didAssign) {
_this.setOption(binding.path, parentScope.$eval(binding.expression));
}
// listen to changes in the widget options
var meta = propPath.get(_this.wijMetadata.properties, binding.path);
var changeEvent = meta && meta.changeEvent;
if(!changeEvent) {
changeEvent = binding.path + "Changed";
if(!(changeEvent in _this.widget.options)) {
changeEvent = null;
}
}
if(changeEvent) {
if(typeof changeEvent != "string" && changeEvent.join) {
changeEvent = changeEvent.join(" ");
}
_this.bindToWidget(changeEvent, function () {
applyingOptions[binding.path] = true;
try {
propPath.set(parentScope, binding.expression, _this.widget.option(binding.path));
safeApply(parentScope, binding.expression);
}finally {
applyingOptions[binding.path] = false;
}
});
}
});
};
ElementDirective.prototype.setOption = function (path, value) {
var parts = propPath.partition(path);
if(parts.length == 1) {
this.widget.option(path, value);
} else {
var optionName = parts.shift();
var optionValue = this.widget.option(optionName);
propPath.set(optionValue, parts, value);
this.widget.option(optionName, optionValue);
}
};
return ElementDirective;
})(DirectiveBase);
definitions.ElementDirective = ElementDirective;
var GridMarkup = (function (_super) {
__extends(GridMarkup, _super);
function GridMarkup() {
_super.apply(this, arguments);
}
GridMarkup.prototype.extactCellTemplate = function ($col, name) {
var templateContainer = $col.children(name);
if(templateContainer.length === 0) {
return null;
}
var template = templateContainer.children().clone();
if(template.length === 0) {
return null;
}
templateContainer.remove();
return {
element: template,
link: this.services.$compile(template)
};
};
GridMarkup.prototype.extractCellTemplates = function (node) {
var _this = this;
this.cellTemplates = this.cellTemplates || [];
$(node).children("columns").children().each(function (index, col) {
var $col = $(col);
var cellTemplate = _this.extactCellTemplate($col, "cellTemplate");
var editorTemplate = _this.extactCellTemplate($col, "editorTemplate");
if(cellTemplate || editorTemplate) {
_this.cellTemplates[index] = {
view: cellTemplate,
edit: editorTemplate
};
}
});
};
GridMarkup.prototype.parseOptions = function ($node, typeDef) {
this.extractCellTemplates($node);
_super.prototype.parseOptions.call(this, $node, typeDef);
this.options.data = [];
};
return GridMarkup;
})(Markup);
var wijgrid = (function (_super) {
__extends(wijgrid, _super);
function wijgrid() {
_super.apply(this, arguments);
this.expectedTemplate = "<table/>";
}
wijgrid.prototype.createMarkup = function (elem, typeDef) {
return new GridMarkup(elem[0], typeDef, this.innerMarkupSelector, this.services);
};
wijgrid.prototype.dataOptionExression = function () {
var expr = null;
$.each(this.markup.bindings, function (_, b) {
if(b.path === "data") {
expr = b.expression;
return false;
}
});
return expr;
};
wijgrid.prototype.applyCellTemplates = function (scope, options) {
var _this = this;
function applyCellTemplate(index, container, template) {
if(index < 0) {
return false;
}
var items = scope.$parent.$eval(dataExpr);
if(!items) {
return false;
}
var rowScope = scope.$new();
rowScope.rowData = items[index];
template.link(rowScope, function (el) {
container.empty().append(el);
});
container.children().data(ngKey, true);
return true;
}
var columns = options.columns, dataExpr = this.dataOptionExression(), ngKey = "wijmoNg";
if(!dataExpr) {
return;
}
var hasEditTemplates = false;
$.each(this.markup.cellTemplates, function (index, template) {
if(!template) {
return;
}
var column = (columns[index] = columns[index] || {
});
if(template.view) {
var origFormatter = column.cellFormatter;
column.cellFormatter = function (args) {
return $.isFunction(origFormatter) && origFormatter(args) || applyCellTemplate(args.row.dataItemIndex, args.$container, template.view);
};
}
if(template.edit) {
hasEditTemplates = true;
}
});
if(hasEditTemplates) {
var origBeforeCellEdit = options.beforeCellEdit;
var origAfterCellEdit = options.afterCellEdit;
options.beforeCellEdit = function (e, args) {
if($.isFunction(origBeforeCellEdit)) {
origBeforeCellEdit(args);
if(args.handled) {
return;
}
}
var col = args.cell.column();
if(!col || col.dataIndex < 0 || col.dataIndex >= _this.markup.cellTemplates.length) {
return;
}
var row = args.cell.row();
if(!row || row.dataItemIndex < 0) {
return;
}
var container = args.cell.container();
if(!container || container.length == 0) {
return;
}
var template = _this.markup.cellTemplates[col.dataIndex];
if(!template) {
return;
}
if(applyCellTemplate(row.dataItemIndex, container, template.edit)) {
args.handled = true;
}
};
options.afterCellEdit = function (e, args) {
if($.isFunction(origAfterCellEdit)) {
origAfterCellEdit(args);
if(args.handled) {
return;
}
}
var container = args.cell.container();
if(container && container.children().data(ngKey)) {
container.empty();
}
};
}
};
wijgrid.prototype.createInstanceCore = function (options) {
// apply column templates
options = $.extend(true, {
}, options);
this.applyCellTemplates(this.$scope, options);
_super.prototype.createInstanceCore.call(this, options);
};
return wijgrid;
})(ElementDirective);
definitions.wijgrid = wijgrid;
var wijcombobox = (function (_super) {
__extends(wijcombobox, _super);
function wijcombobox() {
_super.apply(this, arguments);
this.expectedTemplate = "<input/>";
}
return wijcombobox;
})(ElementDirective);
definitions.wijcombobox = wijcombobox;
var wijinputcore = (function (_super) {
__extends(wijinputcore, _super);
function wijinputcore() {
_super.apply(this, arguments);
this.expectedTemplate = "<input/>";
}
return wijinputcore;
})(ElementDirective);
definitions.wijinputcore = wijinputcore;
var wijinputdate = (function (_super) {
__extends(wijinputdate, _super);
function wijinputdate() {
_super.apply(this, arguments);
}
return wijinputdate;
})(wijinputcore);
definitions.wijinputdate = wijinputdate;
var wijinputmask = (function (_super) {
__extends(wijinputmask, _super);
function wijinputmask() {
_super.apply(this, arguments);
}
return wijinputmask;
})(wijinputcore);
definitions.wijinputmask = wijinputmask;
var wijinputnumber = (function (_super) {
__extends(wijinputnumber, _super);
function wijinputnumber() {
_super.apply(this, arguments);
}
return wijinputnumber;
})(wijinputcore);
definitions.wijinputnumber = wijinputnumber;
var wijcheckbox = (function (_super) {
__extends(wijcheckbox, _super);
function wijcheckbox() {
_super.apply(this, arguments);
this.expectedTemplate = "<input type='checkbox'/>";
this.delay = true;
}
return wijcheckbox;
})(AttributeDirective);
definitions.wijcheckbox = wijcheckbox;
var wijradio = (function (_super) {
__extends(wijradio, _super);
function wijradio() {
_super.apply(this, arguments);
}
return wijradio;
})(wijcheckbox);
definitions.wijradio = wijradio;
var wijsplitter = (function (_super) {
__extends(wijsplitter, _super);
function wijsplitter() {
_super.apply(this, arguments);
this.innerMarkupSelector = "panel1, panel2";
}
return wijsplitter;
})(ElementDirective);
definitions.wijsplitter = wijsplitter;
var wijexpander = (function (_super) {
__extends(wijexpander, _super);
function wijexpander() {
_super.apply(this, arguments);
this.innerMarkupSelector = "h1, div";
}
return wijexpander;
})(ElementDirective);
definitions.wijexpander = wijexpander;
var wijmenu = (function (_super) {
__extends(wijmenu, _super);
function wijmenu() {
_super.apply(this, arguments);
this.expectedTemplate = "<ul/>";
}
return wijmenu;
})(ElementDirective);
definitions.wijmenu = wijmenu;
var TabsMarkup = (function (_super) {
__extends(TabsMarkup, _super);
function TabsMarkup(node, typeDef, services) {
_super.call(this, node, typeDef, "tab", services);
this.services = services;
}
TabsMarkup.prototype.apply = function (scope, parentElement) {
_super.prototype.apply.call(this, scope, parentElement);
var ul = parentElement.children("ul").first();
if(ul.length == 0) {
ul = $("<ul/>");
ul.prependTo(parentElement);
}
angular.forEach(this.subElements, function (se) {
if(!se.element.is("tab")) {
return;
}
var id = se.element.attr("id"), anchor = $("<a/>").text(se.element.attr("title"));
if(id) {
anchor.attr("href", "#" + id);
}
$("<li/>").append(anchor).appendTo(ul);
});
};
return TabsMarkup;
})(Markup);
var wijtabs = (function (_super) {
__extends(wijtabs, _super);
function wijtabs() {
_super.apply(this, arguments);
}
wijtabs.prototype.createMarkup = function (element, typeDef) {
return new TabsMarkup(element, typeDef, this.services);
};
return wijtabs;
})(ElementDirective);
definitions.wijtabs = wijtabs;
var gcSpread = (function (_super) {
__extends(gcSpread, _super);
function gcSpread() {
_super.apply(this, arguments);
}
gcSpread.prototype.setOption = function (path, value) {
if(path === "dataSource") {
this.widget.sheets[0].setDataSource(value);
} else {
_super.prototype.setOption.call(this, path, value);
}
};
return gcSpread;
})(ElementDirective);
definitions.gcSpread = gcSpread;
function findDirectiveClass(widgetName) {
var metadata = widgetMetadata[widgetName], parentMetadata;
return definitions[widgetName] || metadata && metadata.inherits && findDirectiveClass(metadata.inherits);
}
definitions.findDirectiveClass = findDirectiveClass;
})(definitions || (definitions = {}));
// define the wijmo module
var wijModule = angular["module"]('wijmo', []);
function registerDirective(widgetName, namespace, clazz, directiveName) {
var meta = widgetMetadata[widgetName], isDecorator = meta && meta.isDecorator, directiveClass = definitions.findDirectiveClass(widgetName) || (isDecorator ? definitions.AttributeDirective : definitions.ElementDirective);
wijModule.directive(directiveName || widgetName.toLowerCase(), [
"$compile",
function ($compile) {
return new directiveClass(widgetName, namespace, clazz, {
$compile: $compile
});
} ]);
}
var widgetMetadata = {
"base": {
events: {
"create": {
},
"change": {
}
}
},
"wijtooltip": {
"events": {
"showing": {
},
"shown": {
},
"hiding": {
},
"hidden": {
}
},
"properties": {
"group": {
},
"ajaxCallback": {
}
}
},
"wijslider": {
"events": {
"buttonMouseOver": {
},
"buttonMouseOut": {
},
"buttonMouseDown": {
},
"buttonMouseUp": {
},
"buttonClick": {
},
"start": {
},
"stop": {
}
},
"properties": {
"value": {
changeEvent: "change"
},
"values": {
changeEvent: "change"
}
}
},
"wijsplitter": {
"events": {
"sized": {
},
"load": {
},
"sizing": {
}
},
"properties": {
"expand": {
},
"collapse": {
},
"expanded": {
},
"collapsed": {
},
splitterDistance: {
type: "number",
changeEvent: "sized"
}
}
},
"wijprogressbar": {
"properties": {
"progressChanging": {
},
"beforeProgressChanging": {
},
"progressChanged": {
},
value: {
type: "number",
changeEvent: "change"
}
}
},
"wijdialog": {
"events": {
"blur": {
},
"buttonCreating": {
},
"resize": {
},
"stateChanged": {
},
"focus": {
},
"resizeStart": {
},
"resizeStop": {
}
},
"properties": {
"hide": {
},
"show": {
},
"collapsingAnimation": {
},
"expandingAnimation": {
}
}
},
"wijaccordion": {
"events": {
"beforeSelectedIndexChanged": {
},
"selectedIndexChanged": {
}
},
"properties": {
"duration": {
},
selectedIndex: {
type: "number",
changeEvent: "selectedindexchanged"
}
}
},
"wijpopup": {
"events": {
"showing": {
},
"shown": {
},
"hiding": {
},
"hidden": {
},
"posChanged": {
}
}
},
"wijsuperpanel": {
"events": {
"dragStop": {
},
"painted": {
},
"scroll": {
},
"scrolling": {
},
"scrolled": {
},
"resized": {
}
},
"properties": {
"hScrollerActivating": {
},
"vScrollerActivating": {
}
}
},
"wijcheckbox": {
isDecorator: true,
"properties": {
"checked": {
type: "bool",
changeEvent: "changed"
}
}
},
"wijradio": {
isDecorator: true,
"properties": {
"checked": {
type: "bool",
changeEvent: "changed"
}
}
},
"wijlist": {
"events": {
"focusing": {
},
"focus": {
},
"blur": {
},
"selected": {
},
"listRendered": {
},
"itemRendering": {
},
"itemRendered": {
}
},
"properties": {
"superPanelOptions": {
}
}
},
"wijcalendar": {
"events": {
"beforeSlide": {
},
"beforeSelect": {
},
"selectedDatesChanged": {
},
"afterSelect": {
},
"afterSlide": {
}
},
"properties": {
"customizeDate": {
},
"title": {
},
selectedDates: {
type: "array",
elementType: "date",
changeEvent: "selecteddateschanged"
}
}
},
wijdropdown: {
isDecorator: true
},
"wijexpander": {
"events": {
"beforeCollapse": {
},
"afterCollapse": {
},
"beforeExpand": {
},
"afterExpand": {
}
},
properties: {
expanded: {
type: "bool",
attachEvents: [
"aftercollapse",
"afterexpand"
]
}
}
},
"wijmenu": {
"events": {
"focus": {
},
"blur": {
},
"select": {
},
"showing": {
},
"shown": {
},
"hidding": {
},
"hidden": {
}
},
"properties": {
"superPanelOptions": {
}
}
},
"wijmenuitem": {
"events": {
"hidding": {
},
"hidden": {
},
"showing": {
},
"shown": {
}
}
},
"wijtabs": {
"properties": {
"ajaxOptions": {
},
"cookie": {
},
"hideOption": {
},
"showOption": {
},
"add": {
},
"remove": {
},
"select": {
},
"beforeShow": {
},
"show": {
},
"load": {
},
"disable": {
},
"enable": {
}
}
},
wijtextbox: {
isDecorator: true
},
"wijpager": {
"events": {
"pageIndexChanging": {
},
"pageIndexChanged": {
}
},
properties: {
pageIndex: {
type: "numeric",
changeEvent: "pageindexchanged"
}
}
},
"wijcombobox": {
"events": {
"select": {
},
"search": {
},
"open": {
},
"close": {
}
},
"properties": {
dataSource: {
type: "array",
twoWayBinding: true
},
data: {
twoWayBinding: true
},
value: {
changeEvent: "change"
},
"labelText": {
},
"showingAnimation": {
},
"hidingAnimation": {
},
selectedIndex: {
type: "numeric",
changeEvent: "changed"
},
selectedValue: {
changeEvent: "changed"
},
text: {
changeEvent: "changed"
},
inputTextInDropDownList: {
changeEvent: "changed"
},
"listOptions": {
}
}
},
"wijinputcore": {
"events": {
"initializing": {
},
"initialized": {
},
"triggerMouseDown": {
},
"triggerMouseUp": {
},
"initialized": {
},
"textChanged": {
},
"invalidInput": {
}
}
},
"wijinputdate": {
inherits: "wijinputcore",
"events": {
"dateChanged": {
}
},
"properties": {
date: {
type: "datetime",
changeEvent: [
"dateChanged",
"textChanged"
]
},
"minDate": {
},
"maxDate": {
}
}
},
"wijinputmask": {
inherits: "wijinputcore",
"properties": {
"text": {
type: "string",
changeEvent: "textChanged"
}
}
},
"wijinputnumber": {
inherits: "wijinputcore",
"events": {
"valueChanged": {
},
"valueBoundsExceeded": {
}
},
"properties": {
value: {
type: "number",
changeEvent: [
"valueChanged",
"textChanged"
]
}
}
},
"wijgrid": {
"properties": {
data: {
changeEvent: "afterCellEdit"
},
dataSource: {
twoWayBinding: true
},
"columns": {
type: "array",
elementType: {
type: "object",
properties: {
readOnly: {
type: "bool"
},
"dataKey": {
type: "string"
},
"dataType": {
type: "string"
},
"headerText": {
type: "string"
},
groupInfo: {
type: "object",
properties: {
headerText: {
},
footerText: {
},
outlineMode: {
}
}
}
}
}
}
},
"events": {
"ajaxError": {
},
"dataLoading": {
},
"dataLoaded": {
},
"loading": {
},
"loaded": {
},
"columnDropping": {
},
"columnDropped": {
},
"columnGrouping": {
},
"columnGrouped": {
},
"columnUngrouping": {
},
"columnUngrouped": {
},
"filtering": {
},
"filtered": {
},
"sorting": {
},
"sorted": {
},
"currentCellChanged": {
},
"pageIndexChanging": {
},
"pageIndexChanged": {
},
"rendering": {
},
"rendered": {
},
"columnResizing": {
},
"columnResized": {
},
"currentCellChanging": {
},
"afterCellEdit": {
},
"afterCellUpdate": {
},
"beforeCellEdit": {
},
"beforeCellUpdate": {
},
"columnDragging": {
},
"columnDragged": {
},
"filterOperatorsListShowing": {
},
"groupAggregate": {
},
"groupText": {
},
"invalidCellValue": {
},
"selectionChanged": {
}
}
},
"wijchartcore": {
"events": {
"beforeSeriesChange": {
},
"afterSeriesChange": {
},
"seriesChanged": {
},
"beforePaint": {
},
"painted": {
},
"mouseDown": {
},
"mouseUp": {
},
"mouseOver": {
},
"mouseOut": {
},
"mouseMove": {
},
"click": {
}
},
"properties": {
data: {
twoWayBinding: true
},
dataSource: {
twoWayBinding: true
},
"width": {
type: "number"
},
"height": {
type: "number"
},
seriesList: {
changeEvent: "serieschanged",
type: "array"
}
}
},
"wijcompositechart": {
inherits: "wijchartcore"
},
"wijbarchart": {
inherits: "wijchartcore"
},
"wijlinechart": {
inherits: "wijchartcore",
"properties": {
"hole": {
}
}
},
"wijscatterchart": {
inherits: "wijchartcore"
},
"wijbubblechart": {
inherits: "wijchartcore"
},
"wijpiechart": {
inherits: "wijchartcore",
"properties": {
"radius": {
type: "number"
}
}
},
"wijtree": {
"events": {
"nodeBeforeDropped": {
},
"nodeDropped": {
},
"nodeBlur": {
},
"nodeFocus": {
},
"nodeClick": {
},
"nodeCheckChanged": {
},
"nodeCollapsed": {
},
"nodeExpanded": {
},
"nodeDragging": {
},
"nodeDragStarted": {
},
"nodeMouseOver": {
},
"nodeMouseOut": {
},
"nodeTextChanged": {
},
"selectedNodeChanged": {
},
"nodeExpanding": {
},
"nodeCollapsing": {
}
},
properties: {
nodes: {
type: "array",
changeEvent: [
"nodeCheckChanged",
"nodeCollapsed",
"nodeExpanded",
"nodeTextChanged",
"selectedNodeChanged"
]
}
}
},
"wijtreenode": {
"events": {
"nodeTextChanged": {
},
"nodeDragStarted": {
},
"nodeDragging": {
},
"nodeCheckChanged": {
},
"nodeFocus": {
},
"nodeBlur": {
},
"nodeClick": {
},
"selectedNodeChanged": {
},
"nodeMouseOver": {
},
"nodeMouseOut": {
}
}
},
"wijupload": {
"events": {
"cancel": {
},
"totalComplete": {
},
"progress": {
},
"complete": {
},
"totalProgress": {
},
"upload": {
},
"totalUpload": {
}
}
},
"wijwizard": {
"events": {
"show": {
},
"add": {
},
"remove": {
},
"activeIndexChanged": {
},
"validating": {
},
"load": {
}
},
"properties": {
"ajaxOptions": {
},
"cookie": {
}
}
},
"wijribbon": {
"events": {
"click": {
}
}
},
"wijeditor": {
"events": {
"commandButtonClick": {
},
"textChanged": {
}
},
"properties": {
"simpleModeCommands": {
},
"text": {
},
"localization": {
},
text: {
type: "string",
changeEvent: "textChanged"
}
}
},
"wijrating": {
"events": {
"hover": {
},
"rating": {
},
"rated": {
},
"reset": {
}
},
"properties": {
"min": {
},
"max": {
},
"animation": {
},
value: {
type: "numeric",
changeEvent: [
"rated",
"reset"
]
}
}
},
"wijcarousel": {
"events": {
"loadCallback": {
},
"itemClick": {
},
"beforeScroll": {
},
"afterScroll": {
},
"create": {
}
}
},
"wijgallery": {
"events": {
"loadCallback": {
},
"beforeTransition": {
},
"afterTransition": {
},
"create": {
}
}
},
"wijgauge": {
"properties": {
"ranges": {
type: "array",
elementType: {
type: "object",
properties: {
"startValue": {
type: "number"
},
"endValue": {
type: "number"
},
"startDistance": {
type: "number"
},
"endDistance": {
type: "number"
},
"startWidth": {
type: "number"
},
"endWidth": {
type: "number"
}
}
}
}
},
"events": {
"beforeValueChanged": {
},
"valueChanged": {
},
"painted": {
},
"click": {
},
"create": {
}
}
},
"wijlineargauge": {
inherits: "wijgauge"
},
"wijradialgauge": {
inherits: "wijgauge"
},
"wijlightbox": {
"events": {
"show": {
},
"beforeShow": {
},
"beforeClose": {
},
"close": {
},
"open": {
}
},
"properties": {
"cookie": {
}
}
},
"wijdatepager": {
"events": {
"selectedDateChanged": {
}
},
"properties": {
"localization": {
}
}
},
"wijevcal": {
"events": {
"viewTypeChanged": {
},
"selectedDatesChanged": {
},
"initialized": {
},
"beforeDeleteCalendar": {
},
"beforeAddCalendar": {
},
"beforeUpdateCalendar": {
},
"beforeAddEvent": {
},
"beforeUpdateEvent": {
},
"beforeDeleteEvent": {
},
"beforeEditEventDialogShow": {
},
"eventsDataChanged": {
},
"calendarsChanged": {
}
},
"properties": {
"localization": {
},
"datePagerLocalization": {
},
"colors": {
},
"selectedDate": {
type: "date",
changeEvent: "selectedDatesChanged"
},
"selectedDates": {
type: "date",
changeEvent: "selectedDatesChanged"
},
eventsData: {
type: "array",
changeEvent: "eventsdatachanged"
},
appointments: {
type: "array",
changeEvent: "eventsdatachanged"
}
}
},
wijvideo: {
isDecorator: true
},
"gcSpread": {
properties: {
dataSource: {
type: "array"
},
sheetCount: {
type: "number"
},
sheets: {
type: "array",
elementType: {
type: "object",
properties: {
rowCount: {
type: "number"
},
colCount: {
type: "number"
},
defaultRowCount: {
type: "number"
},
defaultColCount: {
type: "number"
}
}
}
}
}
}
};
// register directives for all widgets
$.each($.wijmo, function (name, clazz) {
if(!name.match(/^wij/)) {
return;
}
var directiveName = "wij" + name.charAt(3).toUpperCase() + name.substring(4);
registerDirective(name, "wijmo", clazz, directiveName);
});
$.each($.ui, function (name, clazz) {
return registerDirective(name, "ui", clazz, "jqui" + name.charAt(0).toUpperCase() + name.substring(1));
});
function hasChildElements(node) {
if(!node || !node.childNodes) {
return false;
}
var len = node.childNodes.length;
for(var i = 0; i < len; i++) {
var child = node.childNodes[i];
if(child.nodeType == Node.ELEMENT_NODE) {
return true;
}
}
return false;
}
})(wijmo.ng || (wijmo.ng = {}));
var ng = wijmo.ng;
})(wijmo || (wijmo = {}));