aboutsummaryrefslogtreecommitdiff
path: root/wqflask
diff options
context:
space:
mode:
Diffstat (limited to 'wqflask')
-rwxr-xr-xwqflask/base/data_set.py202
-rwxr-xr-xwqflask/base/mrna_assay_tissue_data.py7
-rwxr-xr-xwqflask/base/trait.py52
-rwxr-xr-xwqflask/base/webqtlCaseData.py2
-rwxr-xr-xwqflask/base/webqtlConfig.py2
-rwxr-xr-xwqflask/cfg/default_settings.py6
-rwxr-xr-xwqflask/maintenance/gen_select_dataset.py52
-rwxr-xr-xwqflask/maintenance/get_group_samplelists.py18
-rwxr-xr-xwqflask/other_config/nginx_conf/gn2_zach.conf5
-rwxr-xr-xwqflask/runserver.py10
-rwxr-xr-xwqflask/secure_server.py3
-rw-r--r--wqflask/utility/chunks.py (renamed from wqflask/wqflask/my_pylmm/pyLMM/chunks.py)0
-rw-r--r--wqflask/utility/tools.py84
-rwxr-xr-xwqflask/utility/webqtlUtil.py17
-rwxr-xr-xwqflask/wqflask/__init__.py8
-rwxr-xr-xwqflask/wqflask/collect.py4
-rwxr-xr-xwqflask/wqflask/correlation/show_corr_results.py112
-rwxr-xr-xwqflask/wqflask/correlation_matrix/show_corr_matrix.py68
-rwxr-xr-xwqflask/wqflask/database.py7
-rwxr-xr-xwqflask/wqflask/do_search.py512
-rwxr-xr-xwqflask/wqflask/docs.py4
-rwxr-xr-xwqflask/wqflask/gsearch.py92
-rw-r--r--wqflask/wqflask/heatmap/heatmap.py635
-rwxr-xr-xwqflask/wqflask/interval_mapping/interval_mapping.py114
-rw-r--r--wqflask/wqflask/marker_regression/gemma_mapping.py44
-rwxr-xr-xwqflask/wqflask/marker_regression/marker_regression.py229
-rw-r--r--wqflask/wqflask/marker_regression/marker_regression_old.py576
-rwxr-xr-xwqflask/wqflask/model.py9
-rw-r--r--wqflask/wqflask/my_pylmm/README.md52
-rwxr-xr-xwqflask/wqflask/my_pylmm/data/genofile_parser.py31
-rw-r--r--wqflask/wqflask/my_pylmm/pyLMM/__init__.py1
-rw-r--r--wqflask/wqflask/my_pylmm/pyLMM/convertlmm.py178
-rw-r--r--wqflask/wqflask/my_pylmm/pyLMM/genotype.py50
-rw-r--r--wqflask/wqflask/my_pylmm/pyLMM/gwas.py173
-rw-r--r--wqflask/wqflask/my_pylmm/pyLMM/input.py267
-rw-r--r--wqflask/wqflask/my_pylmm/pyLMM/kinship.py177
-rw-r--r--wqflask/wqflask/my_pylmm/pyLMM/lmm.py900
-rw-r--r--wqflask/wqflask/my_pylmm/pyLMM/lmm2.py410
-rw-r--r--wqflask/wqflask/my_pylmm/pyLMM/optmatrix.py55
-rw-r--r--wqflask/wqflask/my_pylmm/pyLMM/phenotype.py40
-rw-r--r--wqflask/wqflask/my_pylmm/pyLMM/plink.py107
-rw-r--r--wqflask/wqflask/my_pylmm/pyLMM/runlmm.py212
-rw-r--r--wqflask/wqflask/my_pylmm/pyLMM/tsvreader.py76
-rwxr-xr-xwqflask/wqflask/search_results.py119
-rwxr-xr-xwqflask/wqflask/show_trait/SampleList.py155
-rwxr-xr-xwqflask/wqflask/show_trait/show_trait.py256
-rwxr-xr-xwqflask/wqflask/static/new/css/bar_chart.css38
-rw-r--r--wqflask/wqflask/static/new/css/charts.css2
-rw-r--r--wqflask/wqflask/static/new/css/prob_plot.css3
-rw-r--r--wqflask/wqflask/static/new/css/scatter-matrix.css8
-rw-r--r--wqflask/wqflask/static/new/css/show_trait.css4
-rwxr-xr-xwqflask/wqflask/static/new/javascript/bar_chart.coffee556
-rwxr-xr-xwqflask/wqflask/static/new/javascript/bar_chart.js905
-rw-r--r--wqflask/wqflask/static/new/javascript/chr_lod_chart.coffee16
-rw-r--r--wqflask/wqflask/static/new/javascript/chr_lod_chart.js68
-rw-r--r--wqflask/wqflask/static/new/javascript/corr_matrix.js15
-rw-r--r--wqflask/wqflask/static/new/javascript/create_corr_matrix.js16
-rw-r--r--wqflask/wqflask/static/new/javascript/create_lodchart.coffee49
-rw-r--r--wqflask/wqflask/static/new/javascript/create_lodchart.js110
-rwxr-xr-xwqflask/wqflask/static/new/javascript/dataset_menu_structure.json696
-rw-r--r--wqflask/wqflask/static/new/javascript/dataset_select_menu.js11
-rw-r--r--wqflask/wqflask/static/new/javascript/draw_probability_plot.coffee129
-rw-r--r--wqflask/wqflask/static/new/javascript/draw_probability_plot.js150
-rwxr-xr-xwqflask/wqflask/static/new/javascript/histogram.coffee27
-rwxr-xr-xwqflask/wqflask/static/new/javascript/histogram.js245
-rw-r--r--wqflask/wqflask/static/new/javascript/lod_chart.coffee1031
-rw-r--r--wqflask/wqflask/static/new/javascript/lod_chart.js89
-rw-r--r--wqflask/wqflask/static/new/javascript/panelutil.coffee19
-rw-r--r--wqflask/wqflask/static/new/javascript/panelutil.js26
-rw-r--r--wqflask/wqflask/static/new/javascript/probability_plot.coffee424
-rw-r--r--wqflask/wqflask/static/new/javascript/probability_plot.js408
-rw-r--r--wqflask/wqflask/static/new/javascript/scatterplot.coffee2
-rwxr-xr-xwqflask/wqflask/static/new/javascript/search_results.coffee3
-rwxr-xr-xwqflask/wqflask/static/new/javascript/search_results.js114
-rwxr-xr-xwqflask/wqflask/static/new/javascript/show_trait.coffee141
-rwxr-xr-xwqflask/wqflask/static/new/javascript/show_trait.js923
-rwxr-xr-xwqflask/wqflask/static/new/javascript/show_trait_mapping_tools.coffee110
-rwxr-xr-xwqflask/wqflask/static/new/javascript/show_trait_mapping_tools.js452
-rw-r--r--wqflask/wqflask/static/new/js_external/chroma.js2464
-rw-r--r--wqflask/wqflask/static/new/js_external/jstat.min.js2
-rw-r--r--wqflask/wqflask/static/new/js_external/jszip.min.js14
-rw-r--r--wqflask/wqflask/static/new/js_external/shapiro-wilk.js197
-rwxr-xr-xwqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables.css609
-rw-r--r--wqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables.min.css1
-rwxr-xr-xwqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables_themeroller.css614
-rw-r--r--wqflask/wqflask/static/new/packages/DataTables/extensions/buttons.bootstrap.css89
-rw-r--r--wqflask/wqflask/static/new/packages/DataTables/extensions/buttons.dataTables.css297
-rw-r--r--wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.colReorder.js1372
-rw-r--r--wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.colResize.js846
-rw-r--r--wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.colResize2.js943
-rw-r--r--wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.fixedHeader.css4
-rw-r--r--wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.fixedHeader.min.js14
-rwxr-xr-xwqflask/wqflask/static/new/packages/DataTables/js/jquery.dataTables.js18722
-rwxr-xr-xwqflask/wqflask/static/new/packages/DataTables/js/jquery.dataTables.min.js313
-rwxr-xr-xwqflask/wqflask/static/new/packages/DataTables/js/jquery.js7
-rw-r--r--wqflask/wqflask/static/new/packages/noUiSlider/nouislider.css162
-rw-r--r--wqflask/wqflask/static/new/packages/noUiSlider/nouislider.js1629
-rw-r--r--wqflask/wqflask/static/new/packages/noUiSlider/nouislider.pips.css98
-rw-r--r--wqflask/wqflask/static/new/packages/nvd3/nv.d3.css641
-rw-r--r--wqflask/wqflask/static/new/packages/nvd3/nv.d3.js13362
-rw-r--r--wqflask/wqflask/static/new/packages/nvd3/nv.d3.min.css1
-rw-r--r--wqflask/wqflask/static/new/packages/nvd3/nv.d3.min.js8
-rwxr-xr-xwqflask/wqflask/static/packages/TableTools/media/css/TableTools.css5
-rwxr-xr-xwqflask/wqflask/static/packages/bootstrap/css/bootstrap.css13
-rwxr-xr-xwqflask/wqflask/templates/base.html55
-rw-r--r--wqflask/wqflask/templates/base_macro.html28
-rwxr-xr-xwqflask/wqflask/templates/collections/add.html6
-rwxr-xr-xwqflask/wqflask/templates/collections/list.html31
-rwxr-xr-xwqflask/wqflask/templates/collections/view.html66
-rwxr-xr-xwqflask/wqflask/templates/correlation_matrix.html147
-rwxr-xr-xwqflask/wqflask/templates/correlation_page.html292
-rw-r--r--wqflask/wqflask/templates/empty_collection.html15
-rwxr-xr-xwqflask/wqflask/templates/gsearch_gene.html188
-rwxr-xr-xwqflask/wqflask/templates/gsearch_pheno.html154
-rwxr-xr-xwqflask/wqflask/templates/index_page.html76
-rwxr-xr-xwqflask/wqflask/templates/interval_mapping.html116
-rwxr-xr-xwqflask/wqflask/templates/marker_regression.html109
-rwxr-xr-xwqflask/wqflask/templates/new_security/login_user.html43
-rwxr-xr-xwqflask/wqflask/templates/old_index_page.html320
-rw-r--r--wqflask/wqflask/templates/pair_scan_results.html22
-rw-r--r--wqflask/wqflask/templates/search_error.html21
-rwxr-xr-xwqflask/wqflask/templates/search_result_page.html249
-rwxr-xr-xwqflask/wqflask/templates/show_trait.html253
-rwxr-xr-xwqflask/wqflask/templates/show_trait_calculate_correlations.html28
-rwxr-xr-xwqflask/wqflask/templates/show_trait_details.html97
-rwxr-xr-xwqflask/wqflask/templates/show_trait_edit_data.html44
-rwxr-xr-xwqflask/wqflask/templates/show_trait_mapping_tools.html192
-rwxr-xr-xwqflask/wqflask/templates/show_trait_progress_bar.html15
-rwxr-xr-xwqflask/wqflask/templates/show_trait_statistics_new.html56
-rw-r--r--wqflask/wqflask/templates/wgcna_results.html76
-rw-r--r--wqflask/wqflask/templates/wgcna_setup.html28
-rwxr-xr-xwqflask/wqflask/views.py145
-rwxr-xr-xwqflask/wqflask/wgcna/__init__.py0
-rw-r--r--wqflask/wqflask/wgcna/wgcna_analysis.py156
134 files changed, 40289 insertions, 18089 deletions
diff --git a/wqflask/base/data_set.py b/wqflask/base/data_set.py
index 489bd374..d6a46c2e 100755
--- a/wqflask/base/data_set.py
+++ b/wqflask/base/data_set.py
@@ -29,6 +29,7 @@ import json
import gzip
import cPickle as pickle
import itertools
+from operator import itemgetter
from redis import Redis
Redis = Redis()
@@ -42,7 +43,7 @@ from base import species
from dbFunction import webqtlDatabaseFunction
from utility import webqtlUtil
from utility.benchmark import Bench
-from wqflask.my_pylmm.pyLMM import chunks
+from utility import chunks
from maintenance import get_group_samplelists
@@ -88,7 +89,7 @@ class Dataset_Types(object):
for group in data['datasets'][species]:
for dataset_type in data['datasets'][species][group]:
for dataset in data['datasets'][species][group][dataset_type]:
- print("dataset is:", dataset)
+ #print("dataset is:", dataset)
short_dataset_name = dataset[0]
if dataset_type == "Phenotypes":
@@ -162,8 +163,6 @@ class Markers(object):
for marker in markers:
if (marker['chr'] != "X") and (marker['chr'] != "Y"):
marker['chr'] = int(marker['chr'])
- #else:
- # marker['chr'] = 20
print("Mb:", marker['Mb'])
marker['Mb'] = float(marker['Mb'])
@@ -278,7 +277,7 @@ class DatasetGroup(object):
"""
def __init__(self, dataset):
"""This sets self.group and self.group_id"""
- print("dataset name:", dataset.name)
+ print("DATASET NAME2:", dataset.name)
self.name, self.id = g.db.execute(dataset.query_for_group).fetchone()
if self.name == 'BXD300':
self.name = "BXD"
@@ -292,6 +291,7 @@ class DatasetGroup(object):
self.incparentsf1 = False
self.allsamples = None
+ self._datasets = None
def get_specified_markers(self, markers = []):
self.markers = HumanMarkers(self.name, markers)
@@ -305,6 +305,75 @@ class DatasetGroup(object):
self.markers = marker_class(self.name)
+ def datasets(self):
+ key = "group_dataset_menu:v2:" + self.name
+ print("key is2:", key)
+ #with Bench("Loading cache"):
+ # result = Redis.get(key)
+ #if result:
+ # self._datasets = pickle.loads(result)
+ # return self._datasets
+
+ dataset_menu = []
+ print("[tape4] webqtlConfig.PUBLICTHRESH:", webqtlConfig.PUBLICTHRESH)
+ print("[tape4] type webqtlConfig.PUBLICTHRESH:", type(webqtlConfig.PUBLICTHRESH))
+ results = g.db.execute('''
+ (SELECT '#PublishFreeze',PublishFreeze.FullName,PublishFreeze.Name
+ FROM PublishFreeze,InbredSet
+ WHERE PublishFreeze.InbredSetId = InbredSet.Id
+ and InbredSet.Name = %s
+ and PublishFreeze.public > %s)
+ UNION
+ (SELECT '#GenoFreeze',GenoFreeze.FullName,GenoFreeze.Name
+ FROM GenoFreeze, InbredSet
+ WHERE GenoFreeze.InbredSetId = InbredSet.Id
+ and InbredSet.Name = %s
+ and GenoFreeze.public > %s)
+ UNION
+ (SELECT Tissue.Name, ProbeSetFreeze.FullName,ProbeSetFreeze.Name
+ FROM ProbeSetFreeze, ProbeFreeze, InbredSet, Tissue
+ WHERE ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id
+ and ProbeFreeze.TissueId = Tissue.Id
+ and ProbeFreeze.InbredSetId = InbredSet.Id
+ and InbredSet.Name like %s
+ and ProbeSetFreeze.public > %s
+ ORDER BY Tissue.Name, ProbeSetFreeze.CreateTime desc, ProbeSetFreeze.AvgId)
+ ''', (self.name, webqtlConfig.PUBLICTHRESH,
+ self.name, webqtlConfig.PUBLICTHRESH,
+ "%" + self.name + "%", webqtlConfig.PUBLICTHRESH))
+
+ the_results = results.fetchall()
+
+ #for tissue_name, dataset in itertools.groupby(the_results, itemgetter(0)):
+ for dataset_item in the_results:
+ tissue_name = dataset_item[0]
+ dataset = dataset_item[1]
+ dataset_short = dataset_item[2]
+ if tissue_name in ['#PublishFreeze', '#GenoFreeze']:
+ dataset_menu.append(dict(tissue=None, datasets=[(dataset, dataset_short)]))
+ else:
+ dataset_sub_menu = [item[1:] for item in dataset]
+
+ tissue_already_exists = False
+ tissue_position = None
+ for i, tissue_dict in enumerate(dataset_menu):
+ if tissue_dict['tissue'] == tissue_name:
+ tissue_already_exists = True
+ tissue_position = i
+ break
+
+ if tissue_already_exists:
+ print("dataset_menu:", dataset_menu[i]['datasets'])
+ dataset_menu[i]['datasets'].append((dataset, dataset_short))
+ else:
+ dataset_menu.append(dict(tissue=tissue_name,
+ datasets=[(dataset, dataset_short)]))
+
+ Redis.set(key, pickle.dumps(dataset_menu, pickle.HIGHEST_PROTOCOL))
+ Redis.expire(key, 60*5)
+ self._datasets = dataset_menu
+
+ return self._datasets
def get_f1_parent_strains(self):
try:
@@ -319,7 +388,7 @@ class DatasetGroup(object):
self.parlist = [maternal, paternal]
def get_samplelist(self):
- key = "samplelist:v4:" + self.name
+ key = "samplelist:v2:" + self.name
print("key is:", key)
with Bench("Loading cache"):
result = Redis.get(key)
@@ -332,14 +401,29 @@ class DatasetGroup(object):
print(" self.samplelist: ", self.samplelist)
else:
print("Cache not hit")
- try:
- self.samplelist = get_group_samplelists.get_samplelist(self.name + ".geno")
- except IOError:
+
+ from utility.tools import plink_command
+ PLINK_PATH,PLINK_COMMAND = plink_command()
+
+ geno_file_path = webqtlConfig.GENODIR+self.name+".geno"
+ plink_file_path = PLINK_PATH+"/"+self.name+".fam"
+
+ if os.path.isfile(plink_file_path):
+ self.samplelist = get_group_samplelists.get_samplelist("plink", plink_file_path)
+ elif os.path.isfile(geno_file_path):
+ self.samplelist = get_group_samplelists.get_samplelist("geno", geno_file_path)
+ else:
self.samplelist = None
print("after get_samplelist")
Redis.set(key, json.dumps(self.samplelist))
Redis.expire(key, 60*5)
+ def all_samples_ordered(self):
+ result = []
+ lists = (self.parlist, self.f1list, self.samplelist)
+ [result.extend(l) for l in lists if l]
+ return result
+
def read_genotype_file(self):
'''Read genotype from .geno file instead of database'''
#if self.group == 'BXD300':
@@ -434,6 +518,8 @@ class DataSet(object):
self.group.get_samplelist()
self.species = species.TheSpecies(self)
+ print("TESTING!!!")
+
def get_desc(self):
"""Gets overridden later, at least for Temp...used by trait's get_given_name"""
@@ -473,29 +559,39 @@ class DataSet(object):
This is not meant to retrieve the data set info if no name at all is passed.
"""
-
- query_args = tuple(escape(x) for x in (
- (self.type + "Freeze"),
- str(webqtlConfig.PUBLICTHRESH),
- self.name,
- self.name,
- self.name))
- print("query_args are:", query_args)
-
- #print("""
- # SELECT Id, Name, FullName, ShortName
- # FROM %s
- # WHERE public > %s AND
- # (Name = '%s' OR FullName = '%s' OR ShortName = '%s')
- # """ % (query_args))
try:
- self.id, self.name, self.fullname, self.shortname = g.db.execute("""
- SELECT Id, Name, FullName, ShortName
- FROM %s
- WHERE public > %s AND
- (Name = '%s' OR FullName = '%s' OR ShortName = '%s')
- """ % (query_args)).fetchone()
+ if self.type == "ProbeSet":
+ query_args = tuple(escape(x) for x in (
+ str(webqtlConfig.PUBLICTHRESH),
+ self.name,
+ self.name,
+ self.name))
+
+ self.id, self.name, self.fullname, self.shortname, self.tissue = g.db.execute("""
+ SELECT ProbeSetFreeze.Id, ProbeSetFreeze.Name, ProbeSetFreeze.FullName, ProbeSetFreeze.ShortName, Tissue.Name
+ FROM ProbeSetFreeze, ProbeFreeze, Tissue
+ WHERE ProbeSetFreeze.public > %s AND
+ ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id AND
+ ProbeFreeze.TissueId = Tissue.Id AND
+ (ProbeSetFreeze.Name = '%s' OR ProbeSetFreeze.FullName = '%s' OR ProbeSetFreeze.ShortName = '%s')
+ """ % (query_args)).fetchone()
+ else:
+ query_args = tuple(escape(x) for x in (
+ (self.type + "Freeze"),
+ str(webqtlConfig.PUBLICTHRESH),
+ self.name,
+ self.name,
+ self.name))
+
+ self.tissue = "N/A"
+ self.id, self.name, self.fullname, self.shortname = g.db.execute("""
+ SELECT Id, Name, FullName, ShortName
+ FROM %s
+ WHERE public > %s AND
+ (Name = '%s' OR FullName = '%s' OR ShortName = '%s')
+ """ % (query_args)).fetchone()
+
except TypeError:
print("Dataset {} is not yet available in GeneNetwork.".format(self.name))
pass
@@ -633,14 +729,14 @@ class PhenotypeDataSet(DataSet):
'sequence', 'units', 'comments']
# Fields displayed in the search results table header
- self.header_fields = ['',
- 'ID',
+ self.header_fields = ['Index',
+ 'Record',
'Description',
'Authors',
'Year',
'Max LRS',
'Max LRS Location',
- 'Add. Effect<a href="http://genenetwork.org//glossary.html#A" target="_blank"><sup style="color:#f00"> ?</sup></a>']
+ 'Additive Effect']
self.type = 'Publish'
@@ -719,7 +815,6 @@ class PhenotypeDataSet(DataSet):
Geno.Name = %s and
Geno.SpeciesId = Species.Id
""", (species, this_trait.locus)).fetchone()
- #result = self.cursor.fetchone()
if result:
if result[0] and result[1]:
@@ -737,7 +832,7 @@ class PhenotypeDataSet(DataSet):
this_trait.LRS_score_repr = LRS_score_repr = '%3.1f' % this_trait.lrs
this_trait.LRS_score_value = LRS_score_value = this_trait.lrs
- this_trait.LRS_location_repr = LRS_location_repr = 'Chr %s: %.4f Mb' % (LRS_Chr, float(LRS_Mb))
+ this_trait.LRS_location_repr = LRS_location_repr = 'Chr%s: %.6f' % (LRS_Chr, float(LRS_Mb))
def retrieve_sample_data(self, trait):
query = """
@@ -753,11 +848,11 @@ class PhenotypeDataSet(DataSet):
WHERE
PublishXRef.InbredSetId = PublishFreeze.InbredSetId AND
PublishData.Id = PublishXRef.DataId AND PublishXRef.Id = %s AND
- PublishFreeze.Id = %d AND PublishData.StrainId = Strain.Id
+ PublishFreeze.Id = %s AND PublishData.StrainId = Strain.Id
Order BY
Strain.Name
- """ % (trait, self.id)
- results = g.db.execute(query).fetchall()
+ """
+ results = g.db.execute(query, (trait, self.id)).fetchall()
return results
@@ -777,7 +872,7 @@ class GenotypeDataSet(DataSet):
'sequence']
# Fields displayed in the search results table header
- self.header_fields = ['',
+ self.header_fields = ['Index',
'ID',
'Location']
@@ -828,7 +923,7 @@ class GenotypeDataSet(DataSet):
else:
trait_location_value = ord(str(this_trait.chr).upper()[0])*1000 + this_trait.mb
- this_trait.location_repr = 'Chr%s: %.4f' % (this_trait.chr, float(this_trait.mb) )
+ this_trait.location_repr = 'Chr%s: %.6f' % (this_trait.chr, float(this_trait.mb) )
this_trait.location_value = trait_location_value
def retrieve_sample_data(self, trait):
@@ -840,15 +935,17 @@ class GenotypeDataSet(DataSet):
left join GenoSE on
(GenoSE.DataId = GenoData.Id AND GenoSE.StrainId = GenoData.StrainId)
WHERE
- Geno.SpeciesId = %s AND Geno.Name = '%s' AND GenoXRef.GenoId = Geno.Id AND
+ Geno.SpeciesId = %s AND Geno.Name = %s AND GenoXRef.GenoId = Geno.Id AND
GenoXRef.GenoFreezeId = GenoFreeze.Id AND
- GenoFreeze.Name = '%s' AND
+ GenoFreeze.Name = %s AND
GenoXRef.DataId = GenoData.Id AND
GenoData.StrainId = Strain.Id
Order BY
Strain.Name
- """ % (webqtlDatabaseFunction.retrieve_species_id(self.group.name), trait, self.name)
- results = g.db.execute(query).fetchall()
+ """
+ results = g.db.execute(query,
+ (webqtlDatabaseFunction.retrieve_species_id(self.group.name),
+ trait, self.name)).fetchall()
return results
@@ -893,15 +990,15 @@ class MrnaAssayDataSet(DataSet):
'flag']
# Fields displayed in the search results table header
- self.header_fields = ['',
- 'ID',
+ self.header_fields = ['Index',
+ 'Record',
'Symbol',
'Description',
'Location',
- 'Mean Expr',
+ 'Mean',
'Max LRS',
'Max LRS Location',
- 'Add. Effect<a href="http://genenetwork.org//glossary.html#A" target="_blank"><sup style="color:#f00"> ?</sup></a>']
+ 'Additive Effect']
# Todo: Obsolete or rename this field
self.type = 'ProbeSet'
@@ -1055,7 +1152,7 @@ class MrnaAssayDataSet(DataSet):
# this_trait.mb)
#ZS: Put this in function currently called "convert_location_to_value"
- this_trait.location_repr = 'Chr %s: %.4f Mb' % (this_trait.chr,
+ this_trait.location_repr = 'Chr%s: %.6f' % (this_trait.chr,
float(this_trait.mb))
this_trait.location_value = trait_location_value
@@ -1074,7 +1171,8 @@ class MrnaAssayDataSet(DataSet):
mean = result[0] if result else 0
- this_trait.mean = "%2.3f" % mean
+ if mean:
+ this_trait.mean = "%2.3f" % mean
#LRS and its location
this_trait.LRS_score_repr = 'N/A'
@@ -1111,7 +1209,7 @@ class MrnaAssayDataSet(DataSet):
this_trait.LRS_score_repr = '%3.1f' % this_trait.lrs
this_trait.LRS_score_value = this_trait.lrs
- this_trait.LRS_location_repr = 'Chr %s: %.4f Mb' % (lrs_chr, float(lrs_mb))
+ this_trait.LRS_location_repr = 'Chr%s: %.6f' % (lrs_chr, float(lrs_mb))
def convert_location_to_value(self, chromosome, mb):
@@ -1159,7 +1257,7 @@ class MrnaAssayDataSet(DataSet):
Strain.Name
""" % (escape(trait), escape(self.name))
results = g.db.execute(query).fetchall()
- print("RETRIEVED RESULTS HERE:", results)
+ #print("RETRIEVED RESULTS HERE:", results)
return results
diff --git a/wqflask/base/mrna_assay_tissue_data.py b/wqflask/base/mrna_assay_tissue_data.py
index 1a05fce7..54a7ce8e 100755
--- a/wqflask/base/mrna_assay_tissue_data.py
+++ b/wqflask/base/mrna_assay_tissue_data.py
@@ -40,7 +40,6 @@ class MrnaAssayTissueData(object):
# with highest mean value
# Due to the limit size of TissueProbeSetFreezeId table in DB,
# performance of inner join is acceptable.MrnaAssayTissueData(gene_symbols=symbol_list)
- #print("len(gene_symbols): ", len(gene_symbols))
if len(gene_symbols) == 0:
query += '''Symbol!='' and Symbol Is Not Null group by Symbol)
as x inner join TissueProbeSetXRef as t on t.Symbol = x.Symbol
@@ -49,6 +48,8 @@ class MrnaAssayTissueData(object):
else:
in_clause = db_tools.create_in_clause(gene_symbols)
+ #ZS: This was in the query, not sure why: http://docs.python.org/2/library/string.html?highlight=lower#string.lower
+
query += ''' Symbol in {} group by Symbol)
as x inner join TissueProbeSetXRef as t on t.Symbol = x.Symbol
and t.Mean = x.maxmean;
@@ -58,8 +59,8 @@ class MrnaAssayTissueData(object):
for result in results:
symbol = result[0]
- if symbol in gene_symbols:
- #gene_symbols.append(symbol)
+ if symbol.lower() in [gene_symbol.lower() for gene_symbol in gene_symbols]:
+ #gene_symbols.append(symbol)
symbol = symbol.lower()
self.data[symbol].gene_id = result.GeneId
diff --git a/wqflask/base/trait.py b/wqflask/base/trait.py
index 58bed865..ff80795c 100755
--- a/wqflask/base/trait.py
+++ b/wqflask/base/trait.py
@@ -53,7 +53,8 @@ class GeneralTrait(object):
self.pvalue = None
self.mean = None
self.num_overlap = None
-
+ self.strand_probe = None
+ self.symbol = None
if kw.get('fullname'):
name2 = value.split("::")
@@ -250,14 +251,7 @@ class GeneralTrait(object):
# Todo: is this necessary? If not remove
self.data.clear()
- if self.dataset.group.parlist:
- all_samples_ordered = (self.dataset.group.parlist +
- self.dataset.group.f1list +
- self.dataset.group.samplelist)
- elif self.dataset.group.f1list:
- all_samples_ordered = self.dataset.group.f1list + self.dataset.group.samplelist
- else:
- all_samples_ordered = self.dataset.group.samplelist
+ all_samples_ordered = self.dataset.group.all_samples_ordered()
if results:
for item in results:
@@ -297,7 +291,7 @@ class GeneralTrait(object):
PublishFreeze.Id = %s
""" % (self.name, self.dataset.id)
- print("query is:", query)
+ print("query is:", query)
trait_info = g.db.execute(query).fetchone()
#XZ, 05/08/2009: Xiaodong add this block to use ProbeSet.Id to find the probeset instead of just using ProbeSet.Name
@@ -336,10 +330,10 @@ class GeneralTrait(object):
trait_info = g.db.execute(query).fetchone()
#print("trait_info is: ", pf(trait_info))
else: #Temp type
- query = """SELECT %s FROM %s WHERE Name = %s
- """ % (string.join(self.dataset.display_fields,','),
- self.dataset.type, self.name)
- trait_info = g.db.execute(query).fetchone()
+ query = """SELECT %s FROM %s WHERE Name = %s"""
+ trait_info = g.db.execute(query,
+ (string.join(self.dataset.display_fields,','),
+ self.dataset.type, self.name)).fetchone()
if trait_info:
self.haveinfo = True
@@ -422,6 +416,8 @@ class GeneralTrait(object):
if result:
self.locus_chr = result[0]
self.locus_mb = result[1]
+ else:
+ self.locus = self.locus_chr = self.locus_mb = ""
else:
self.locus = self.locus_chr = self.locus_mb = ""
else:
@@ -533,12 +529,27 @@ class GeneralTrait(object):
return setDescription
@property
+ def name_header_fmt(self):
+ '''Return a human-readable name for use in page header'''
+ if self.dataset.type == 'ProbeSet':
+ return self.symbol
+ elif self.dataset.type == 'Geno':
+ return self.name
+ elif self.dataset.type == 'Publish':
+ return self.post_publication_abbreviation
+ else:
+ return "unnamed"
+
+ @property
def description_fmt(self):
'''Return a text formated description'''
- if self.description:
- formatted = self.description
- if self.probe_target_description:
- formatted += "; " + self.probe_target_description
+ if self.dataset.type == 'ProbeSet':
+ if self.description:
+ formatted = self.description
+ if self.probe_target_description:
+ formatted += "; " + self.probe_target_description
+ elif self.dataset.type == 'Publish':
+ formatted = self.post_publication_description
else:
formatted = "Not available"
return formatted.capitalize()
@@ -549,6 +560,9 @@ class GeneralTrait(object):
if self.alias:
alias = string.replace(self.alias, ";", " ")
alias = string.join(string.split(alias), ", ")
+ else:
+ alias = 'Not available'
+
return alias
@@ -649,4 +663,4 @@ def get_sample_data():
# jsonable_sample_data[sample] = trait_ob.data[sample].value
#
#return jsonable_sample_data
- \ No newline at end of file
+
diff --git a/wqflask/base/webqtlCaseData.py b/wqflask/base/webqtlCaseData.py
index 5927b0f4..42763aed 100755
--- a/wqflask/base/webqtlCaseData.py
+++ b/wqflask/base/webqtlCaseData.py
@@ -34,8 +34,6 @@ class webqtlCaseData(object):
self.value = value # Trait Value
self.variance = variance # Trait Variance
self.num_cases = num_cases # Number of individuals/cases
- self.prob_plot_value = None # Ordered value for probability plot; this is sort of wrong but not sure how else to do this
- self.z_score = None
self.extra_attributes = None
self.this_id = None # Set a sane default (can't be just "id" cause that's a reserved word)
self.outlier = None # Not set to True/False until later
diff --git a/wqflask/base/webqtlConfig.py b/wqflask/base/webqtlConfig.py
index 48d8cd0a..330fec56 100755
--- a/wqflask/base/webqtlConfig.py
+++ b/wqflask/base/webqtlConfig.py
@@ -53,7 +53,7 @@ GNROOT = "/home/zas1024/gene/" # Will remove this and dependent items later
SECUREDIR = GNROOT + 'secure/'
COMMON_LIB = GNROOT + 'support/admin'
HTMLPATH = GNROOT + 'genotype_files/'
-PYLMM_PATH = '/home/zas1024/plink/'
+PYLMM_PATH = '/home/zas1024/plink_gemma/'
SNP_PATH = '/home/zas1024/snps/'
IMGDIR = GNROOT + '/wqflask/wqflask/images/'
IMAGESPATH = HTMLPATH + 'images/'
diff --git a/wqflask/cfg/default_settings.py b/wqflask/cfg/default_settings.py
index 8b5d1313..88159321 100755
--- a/wqflask/cfg/default_settings.py
+++ b/wqflask/cfg/default_settings.py
@@ -14,4 +14,8 @@ SECURITY_EMAIL_SENDER = "no-reply@genenetwork.org"
SECURITY_POST_LOGIN_VIEW = "/thank_you"
-SQLALCHEMY_POOL_RECYCLE = 3600 \ No newline at end of file
+SQLALCHEMY_POOL_RECYCLE = 3600
+
+SECURITY_PASSWORD_HASH = "bcrypt"
+SESSION_TYPE = "filesystem"
+SECRET_KEY = "secretkey"
diff --git a/wqflask/maintenance/gen_select_dataset.py b/wqflask/maintenance/gen_select_dataset.py
index 694efeca..a2ad8c91 100755
--- a/wqflask/maintenance/gen_select_dataset.py
+++ b/wqflask/maintenance/gen_select_dataset.py
@@ -35,7 +35,9 @@ from __future__ import print_function, division
#config = config.Config(cdict).from_envvar('WQFLASK_SETTINGS')
#print("cdict is:", cdict)
-import our_settings
+import sys
+sys.path.append("/home/zas1024/")
+import zach_settings
import MySQLdb
@@ -47,7 +49,7 @@ import urlparse
from pprint import pformat as pf
-#Engine = sa.create_engine(our_settings.SQLALCHEMY_DATABASE_URI)
+#Engine = sa.create_engine(zach_settings.SQLALCHEMY_DATABASE_URI)
# build MySql database connection
@@ -60,7 +62,7 @@ from pprint import pformat as pf
def parse_db_uri(db_uri):
"""Converts a database URI to the db name, host name, user name, and password"""
- parsed_uri = urlparse.urlparse(our_settings.DB_URI)
+ parsed_uri = urlparse.urlparse(zach_settings.DB_URI)
db_conn_info = dict(
db = parsed_uri.path[1:],
@@ -104,12 +106,48 @@ def get_types(groups):
types[species] = {}
for group_name, _group_full_name in group_dict:
# make group an alias to shorten the code
- types[species][group_name] = [("Phenotypes", "Phenotypes"), ("Genotypes", "Genotypes")]
- types[species][group_name] += build_types(species, group_name)
+ #types[species][group_name] = [("Phenotypes", "Phenotypes"), ("Genotypes", "Genotypes")]
+ if phenotypes_exist(group_name):
+ types[species][group_name] = [("Phenotypes", "Phenotypes")]
+ if genotypes_exist(group_name):
+ if group_name in types[species]:
+ types[species][group_name] += [("Genotypes", "Genotypes")]
+ else:
+ types[species][group_name] = [("Genotypes", "Genotypes")]
+ if group_name in types[species]:
+ types[species][group_name] += build_types(species, group_name)
+ else:
+ types[species][group_name] = build_types(species, group_name)
return types
+def phenotypes_exist(group_name):
+ print("group_name:", group_name)
+ Cursor.execute("""select Name from PublishFreeze
+ where PublishFreeze.Name = %s""", (group_name+"Publish"))
+
+ results = Cursor.fetchone()
+ print("RESULTS:", results)
+
+ if results != None:
+ return True
+ else:
+ return False
+
+def genotypes_exist(group_name):
+ print("group_name:", group_name)
+ Cursor.execute("""select Name from GenoFreeze
+ where GenoFreeze.Name = %s""", (group_name+"Geno"))
+
+ results = Cursor.fetchone()
+ print("RESULTS:", results)
+
+ if results != None:
+ return True
+ else:
+ return False
+
def build_types(species, group):
"""Fetches tissues
@@ -196,7 +234,7 @@ def build_datasets(species, group, type_name):
def main():
"""Generates and outputs (as json file) the data for the main dropdown menus on the home page"""
- parse_db_uri(our_settings.DB_URI)
+ parse_db_uri(zach_settings.DB_URI)
species = get_species()
groups = get_groups(species)
@@ -236,6 +274,6 @@ def _test_it():
#print("build_datasets:", pf(datasets))
if __name__ == '__main__':
- Conn = MySQLdb.Connect(**parse_db_uri(our_settings.DB_URI))
+ Conn = MySQLdb.Connect(**parse_db_uri(zach_settings.DB_URI))
Cursor = Conn.cursor()
main()
diff --git a/wqflask/maintenance/get_group_samplelists.py b/wqflask/maintenance/get_group_samplelists.py
index c9ec3872..b8397b47 100755
--- a/wqflask/maintenance/get_group_samplelists.py
+++ b/wqflask/maintenance/get_group_samplelists.py
@@ -17,8 +17,13 @@ def process_genofiles(geno_dir=webqtlConfig.GENODIR):
sample_list = get_samplelist(geno_file)
-def get_samplelist(geno_file):
- genofilename = os.path.join(webqtlConfig.GENODIR, geno_file)
+def get_samplelist(file_type, geno_file):
+ if file_type == "geno":
+ return get_samplelist_from_geno(geno_file)
+ elif file_type == "plink":
+ return get_samplelist_from_plink(geno_file)
+
+def get_samplelist_from_geno(genofilename):
if os.path.isfile(genofilename + '.gz'):
genofilename += '.gz'
genofile = gzip.open(genofilename)
@@ -41,3 +46,12 @@ def get_samplelist(geno_file):
samplelist = headers[3:]
return samplelist
+def get_samplelist_from_plink(genofilename):
+ genofile = open(genofilename)
+
+ samplelist = []
+ for line in genofile:
+ line = line.split(" ")
+ samplelist.append(line[0])
+
+ return samplelist \ No newline at end of file
diff --git a/wqflask/other_config/nginx_conf/gn2_zach.conf b/wqflask/other_config/nginx_conf/gn2_zach.conf
index e7284e8c..23f3995f 100755
--- a/wqflask/other_config/nginx_conf/gn2_zach.conf
+++ b/wqflask/other_config/nginx_conf/gn2_zach.conf
@@ -28,6 +28,11 @@ server {
# root /gene/wqflask/wqflask/static/;
#}
+ location /plink_gemma/ {
+ root /home/zas1024/gene/wqflask/wqflask/;
+ autoindex on;
+ }
+
location / {
proxy_pass http://127.0.0.1:5002/;
proxy_redirect off;
diff --git a/wqflask/runserver.py b/wqflask/runserver.py
index 9d5686a9..59ebf0d4 100755
--- a/wqflask/runserver.py
+++ b/wqflask/runserver.py
@@ -18,9 +18,10 @@ from wqflask import app
#_ch = logging.StreamHandler()
#_log.addHandler(_ch)
+print app.config
+
import logging
-#from themodule import TheHandlerYouWant
-file_handler = logging.FileHandler("/tmp/flask_gn_log_danny_unsecure")
+file_handler = logging.FileHandler(app.config['LOGFILE'])
file_handler.setLevel(logging.DEBUG)
app.logger.addHandler(file_handler)
@@ -28,7 +29,8 @@ import logging_tree
logging_tree.printout()
app.run(host='0.0.0.0',
- port=5003,
- use_debugger=False,
+ port=app.config['SERVER_PORT'],
+ debug=True,
+ use_debugger=True,
threaded=True,
use_reloader=True)
diff --git a/wqflask/secure_server.py b/wqflask/secure_server.py
index 975c97c0..fc258578 100755
--- a/wqflask/secure_server.py
+++ b/wqflask/secure_server.py
@@ -66,11 +66,8 @@ def check_send_mail_running():
if __name__ == '__main__':
#create_user()
-
-
check_send_mail_running()
-
app.run(host='0.0.0.0',
port=5002,
use_debugger=True,
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/chunks.py b/wqflask/utility/chunks.py
index 9565fb96..9565fb96 100644
--- a/wqflask/wqflask/my_pylmm/pyLMM/chunks.py
+++ b/wqflask/utility/chunks.py
diff --git a/wqflask/utility/tools.py b/wqflask/utility/tools.py
new file mode 100644
index 00000000..760ded7c
--- /dev/null
+++ b/wqflask/utility/tools.py
@@ -0,0 +1,84 @@
+# Tools/paths finder resolves external paths from settings and/or environment
+# variables
+#
+# Currently supported:
+#
+# PYLMM_PATH finds the root of the git repository of the pylmm_gn2 tool
+
+import os
+import sys
+from wqflask import app
+
+def get_setting(id,default,guess,get_valid_path):
+ """
+ Resolve a setting from the environment or the global settings in app.config
+ """
+ # ---- Check whether environment exists
+ path = get_valid_path(os.environ.get(id))
+ # ---- Check whether setting exists
+ setting = app.config.get(id)
+ if not path:
+ path = get_valid_path(setting)
+ # ---- Check whether default exists
+ if not path:
+ path = get_valid_path(default)
+ # ---- Guess directory
+ if not path:
+ if not setting:
+ setting = guess
+ path = get_valid_path(guess)
+ if not path:
+ raise Exception(id+' '+setting+' path unknown or faulty (update settings.py?). '+id+' should point to the root of the git repository')
+
+ return path
+
+def pylmm_command(default=None):
+ """
+ Return the path to the repository and the python command to call
+ """
+ def get_valid_path(path):
+ """Test for a valid repository"""
+ if path:
+ sys.stderr.write("Trying PYLMM_PATH in "+path+"\n")
+ if path and os.path.isfile(path+'/pylmm_gn2/lmm.py'):
+ return path
+ else:
+ None
+
+ guess = os.environ.get('HOME')+'/pylmm_gn2'
+ path = get_setting('PYLMM_PATH',default,guess,get_valid_path)
+ pylmm_command = 'python '+path+'/pylmm_gn2/lmm.py'
+ return path,pylmm_command
+
+def plink_command(default=None):
+ """
+ Return the path to the repository and the python command to call
+ """
+ def get_valid_path(path):
+ """Test for a valid repository"""
+ if path:
+ sys.stderr.write("Trying PLINK_PATH in "+path+"\n")
+ if path and os.path.isfile(path+'/plink'):
+ return path
+ else:
+ None
+
+ guess = os.environ.get('HOME')+'/plink'
+ path = get_setting('PLINK_PATH',default,guess,get_valid_path)
+ plink_command = path+'/plink'
+ return path,plink_command
+
+def gemma_command(default=None):
+ def get_valid_path(path):
+ """Test for a valid repository"""
+ if path:
+ sys.stderr.write("Trying PLINK_PATH in "+path+"\n")
+ if path and os.path.isfile(path+'/plink'):
+ return path
+ else:
+ None
+
+ guess = os.environ.get('HOME')+'/plink'
+ path = get_setting('PLINK_PATH',default,guess,get_valid_path)
+ gemma_command = path+'/gemma'
+ return path, gemma_command \ No newline at end of file
diff --git a/wqflask/utility/webqtlUtil.py b/wqflask/utility/webqtlUtil.py
index 4d7981d9..f842dde0 100755
--- a/wqflask/utility/webqtlUtil.py
+++ b/wqflask/utility/webqtlUtil.py
@@ -43,6 +43,7 @@ ParInfo ={
'BXH':['BHF1', 'HBF1', 'C57BL/6J', 'C3H/HeJ'],
'AKXD':['AKF1', 'KAF1', 'AKR/J', 'DBA/2J'],
'BXD':['B6D2F1', 'D2B6F1', 'C57BL/6J', 'DBA/2J'],
+'C57BL-6JxC57BL-6NJF2':['', '', 'C57BL/6J', 'C57BL/6NJ'],
'BXD300':['B6D2F1', 'D2B6F1', 'C57BL/6J', 'DBA/2J'],
'B6BTBRF2':['B6BTBRF1', 'BTBRB6F1', 'C57BL/6J', 'BTBRT<+>tf/J'],
'BHHBF2':['B6HF2','HB6F2','C57BL/6J','C3H/HeJ'],
@@ -880,22 +881,6 @@ def cmpGenoPos(A,B):
except:
return 0
-#XZhou: Must use "BINARY" to enable case sensitive comparison.
-def authUser(name,password,db, encrypt=None):
- try:
- if encrypt:
- query = 'SELECT privilege, id,name,password, grpName FROM User WHERE name= BINARY \'%s\' and password= BINARY \'%s\'' % (name,password)
- else:
- query = 'SELECT privilege, id,name,password, grpName FROM User WHERE name= BINARY \'%s\' and password= BINARY SHA(\'%s\')' % (name,password)
- db.execute(query)
- records = db.fetchone()
- if not records:
- raise ValueError
- return records#(privilege,id,name,password,grpName)
- except:
- return (None, None, None, None, None)
-
-
def hasAccessToConfidentialPhenotypeTrait(privilege, userName, authorized_users):
access_to_confidential_phenotype_trait = 0
if webqtlConfig.USERDICT[privilege] > webqtlConfig.USERDICT['user']:
diff --git a/wqflask/wqflask/__init__.py b/wqflask/wqflask/__init__.py
index 8e648c63..478d0a71 100755
--- a/wqflask/wqflask/__init__.py
+++ b/wqflask/wqflask/__init__.py
@@ -6,16 +6,14 @@ print("sys.path is:", sys.path)
import jinja2
from flask import Flask
-
from utility import formatting
app = Flask(__name__)
-app.config.SECURITY_PASSWORD_HASH='bcrypt'
+app.config.from_object('cfg.default_settings') # Get the defaults from cfg.default_settings
+app.config.from_envvar('WQFLASK_SETTINGS') # See http://flask.pocoo.org/docs/config/#configuring-from-files
-# See http://flask.pocoo.org/docs/config/#configuring-from-files
-app.config.from_object('cfg.default_settings')
-app.config.from_envvar('WQFLASK_SETTINGS')
+print("Current application configuration:", app.config)
app.jinja_env.globals.update(
undefined = jinja2.StrictUndefined,
diff --git a/wqflask/wqflask/collect.py b/wqflask/wqflask/collect.py
index df4507fb..750f4757 100755
--- a/wqflask/wqflask/collect.py
+++ b/wqflask/wqflask/collect.py
@@ -181,6 +181,8 @@ def collections_new():
if "anonymous_add" in params:
AnonCollection().add_traits(params, "Default")
return redirect(url_for('view_collection'))
+ elif "sign_in" in params:
+ return redirect(url_for('login'))
collection_name = params['new_collection']
@@ -329,6 +331,8 @@ def view_collection():
# dis=trait_ob.description))
#json_version.append(trait_ob.__dict__th)
+ print("trait_obs:", trait_obs)
+
if "uc_id" in params:
collection_info = dict(trait_obs=trait_obs,
uc = uc)
diff --git a/wqflask/wqflask/correlation/show_corr_results.py b/wqflask/wqflask/correlation/show_corr_results.py
index aa37c29e..2612857f 100755
--- a/wqflask/wqflask/correlation/show_corr_results.py
+++ b/wqflask/wqflask/correlation/show_corr_results.py
@@ -104,6 +104,28 @@ class CorrelationResults(object):
self.sample_data = {}
self.corr_type = start_vars['corr_type']
self.corr_method = start_vars['corr_sample_method']
+ if 'min_expr' in start_vars:
+ if start_vars['min_expr'] != "":
+ self.min_expr = float(start_vars['min_expr'])
+ else:
+ self.min_expr = None
+ self.p_range_lower = float(start_vars['p_range_lower'])
+ self.p_range_upper = float(start_vars['p_range_upper'])
+
+ if ('loc_chr' in start_vars and
+ 'min_loc_mb' in start_vars and
+ 'max_loc_mb' in start_vars):
+
+ self.location_chr = start_vars['loc_chr']
+ if start_vars['min_loc_mb'].isdigit():
+ self.min_location_mb = start_vars['min_loc_mb']
+ else:
+ self.min_location_mb = None
+ if start_vars['max_loc_mb'].isdigit():
+ self.max_location_mb = start_vars['max_loc_mb']
+ else:
+ self.max_location_mb = None
+
self.get_formatted_corr_type()
self.return_number = int(start_vars['corr_return_results'])
@@ -127,7 +149,6 @@ class CorrelationResults(object):
if corr_samples_group == 'samples_other':
primary_samples = [x for x in primary_samples if x not in (
self.dataset.group.parlist + self.dataset.group.f1list)]
- print("primary_samples:", primary_samples)
self.process_samples(start_vars, self.this_trait.data.keys(), primary_samples)
self.target_dataset = data_set.create_dataset(start_vars['corr_dataset'])
@@ -161,31 +182,75 @@ class CorrelationResults(object):
key=lambda t: -abs(t[1][0])))
+ if self.dataset.type == "ProbeSet" or self.dataset.type == "Geno":
+ #ZS: Convert min/max chromosome to an int for the location range option
+ range_chr_as_int = None
+ for order_id, chr_info in self.dataset.species.chromosomes.chromosomes.iteritems():
+ if chr_info.name == self.location_chr:
+ range_chr_as_int = order_id
+
for _trait_counter, trait in enumerate(self.correlation_data.keys()[:self.return_number]):
- print("trait name:", trait)
trait_object = GeneralTrait(dataset=self.target_dataset, name=trait, get_qtl_info=True)
- (trait_object.sample_r,
- trait_object.sample_p,
- trait_object.num_overlap) = self.correlation_data[trait]
+ if self.dataset.type == "ProbeSet" or self.dataset.type == "Geno":
+ #ZS: Convert trait chromosome to an int for the location range option
+ chr_as_int = 0
+ for order_id, chr_info in self.dataset.species.chromosomes.chromosomes.iteritems():
+ if chr_info.name == trait_object.chr:
+ chr_as_int = order_id
+
+ if (float(self.correlation_data[trait][0]) >= self.p_range_lower and
+ float(self.correlation_data[trait][0]) <= self.p_range_upper):
+
+ if self.dataset.type == "ProbeSet" or self.dataset.type == "Geno":
+
+ if (self.min_expr != None) and (float(trait_object.mean) < self.min_expr):
+ continue
+ elif range_chr_as_int != None and (chr_as_int != range_chr_as_int):
+ continue
+ elif (self.min_location_mb != None) and (float(trait_object.mb) < float(self.min_location_mb)):
+ continue
+ elif (self.max_location_mb != None) and (float(trait_object.mb) > float(self.max_location_mb)):
+ continue
+
+ (trait_object.sample_r,
+ trait_object.sample_p,
+ trait_object.num_overlap) = self.correlation_data[trait]
- #trait_object.sample_p = self.correlation_data[trait][1]
- #trait_object.num_overlap = self.correlation_data[trait][2]
+ #Get symbol for trait and call function that gets each tissue value from the database (tables TissueProbeSetXRef,
+ #TissueProbeSetData, etc) and calculates the correlation (cal_zero_order_corr_for_tissue in correlation_functions)
- #Get symbol for trait and call function that gets each tissue value from the database (tables TissueProbeSetXRef,
- #TissueProbeSetData, etc) and calculates the correlation (cal_zero_order_corr_for_tissue in correlation_functions)
+ # Set some sane defaults
+ trait_object.tissue_corr = 0
+ trait_object.tissue_pvalue = 0
+ trait_object.lit_corr = 0
+ if self.corr_type == "tissue":
+ trait_object.tissue_corr = tissue_corr_data[trait][1]
+ trait_object.tissue_pvalue = tissue_corr_data[trait][2]
+ elif self.corr_type == "lit":
+ trait_object.lit_corr = lit_corr_data[trait][1]
+ self.correlation_results.append(trait_object)
+ else:
+ (trait_object.sample_r,
+ trait_object.sample_p,
+ trait_object.num_overlap) = self.correlation_data[trait]
- # Set some sane defaults
- trait_object.tissue_corr = 0
- trait_object.tissue_pvalue = 0
- trait_object.lit_corr = 0
- if self.corr_type == "tissue":
- trait_object.tissue_corr = tissue_corr_data[trait][1]
- trait_object.tissue_pvalue = tissue_corr_data[trait][2]
- elif self.corr_type == "lit":
- trait_object.lit_corr = lit_corr_data[trait][1]
- self.correlation_results.append(trait_object)
-
+ #Get symbol for trait and call function that gets each tissue value from the database (tables TissueProbeSetXRef,
+ #TissueProbeSetData, etc) and calculates the correlation (cal_zero_order_corr_for_tissue in correlation_functions)
+
+ # Set some sane defaults
+ trait_object.tissue_corr = 0
+ trait_object.tissue_pvalue = 0
+ trait_object.lit_corr = 0
+ if self.corr_type == "tissue":
+ trait_object.tissue_corr = tissue_corr_data[trait][1]
+ trait_object.tissue_pvalue = tissue_corr_data[trait][2]
+ elif self.corr_type == "lit":
+ trait_object.lit_corr = lit_corr_data[trait][1]
+ self.correlation_results.append(trait_object)
+
+ self.target_dataset.get_trait_info(self.correlation_results, self.target_dataset.group.species)
+
if self.corr_type != "lit" and self.dataset.type == "ProbeSet" and self.target_dataset.type == "ProbeSet":
self.do_lit_correlation_for_trait_list()
@@ -431,8 +496,6 @@ class CorrelationResults(object):
FROM GeneIDXRef
WHERE rat='%s'""" % escape(gene_id)
- print("GENE_ID QUERY: ", query)
-
result = g.db.execute(query).fetchone()
if result != None:
mouse_gene_id = result.mouse
@@ -443,13 +506,9 @@ class CorrelationResults(object):
FROM GeneIDXRef
WHERE human='%s'""" % escape(gene_id)
- print("GENE_ID QUERY: ", query)
-
result = g.db.execute(query).fetchone()
if result != None:
mouse_gene_id = result.mouse
-
- print("mouse_geneid:", mouse_gene_id)
return mouse_gene_id
@@ -476,6 +535,7 @@ class CorrelationResults(object):
this_trait_vals, target_vals, num_overlap = corr_result_helpers.normalize_values(
this_trait_vals, target_vals)
+ #ZS: 2015 could add biweight correlation, see http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3465711/
if self.corr_method == 'pearson':
sample_r, sample_p = scipy.stats.pearsonr(this_trait_vals, target_vals)
else:
diff --git a/wqflask/wqflask/correlation_matrix/show_corr_matrix.py b/wqflask/wqflask/correlation_matrix/show_corr_matrix.py
index e1df5b24..2cdd989f 100755
--- a/wqflask/wqflask/correlation_matrix/show_corr_matrix.py
+++ b/wqflask/wqflask/correlation_matrix/show_corr_matrix.py
@@ -72,7 +72,7 @@ class CorrelationMatrix(object):
self.traits = []
for trait_db in self.trait_list:
this_trait = trait_db[0]
- self.traits.append(this_trait.name)
+ self.traits.append(this_trait)
this_sample_data = this_trait.data
for sample in this_sample_data:
@@ -96,7 +96,7 @@ class CorrelationMatrix(object):
self.sample_data.append(this_trait_vals)
self.corr_results = []
- self.corr_rseults_for_pca = []
+ self.corr_results_for_pca = []
for trait_db in self.trait_list:
this_trait = trait_db[0]
this_db = trait_db[1]
@@ -115,14 +115,15 @@ class CorrelationMatrix(object):
# self.all_sample_list.append(sample)
corr_result_row = []
+ is_spearman = False #ZS: To determine if it's above or below the diagonal
for target in self.trait_list:
target_trait = target[0]
target_db = target[1]
target_samples = target_db.group.samplelist
- if this_trait == target_trait and this_db == target_db:
- corr_result_row.append(1)
- continue
+ #if this_trait == target_trait and this_db == target_db:
+ # corr_result_row.append(1)
+ # continue
target_sample_data = target_trait.data
print("target_samples", len(target_samples))
@@ -137,12 +138,18 @@ class CorrelationMatrix(object):
this_trait_vals.append(sample_value)
target_vals.append(target_sample_value)
- this_trait_vals, target_vals, num_overlap = corr_result_helpers.normalize_values(
- this_trait_vals, target_vals)
-
- sample_r, sample_p = scipy.stats.pearsonr(this_trait_vals, target_vals)
-
- corr_result_row.append(sample_r)
+ this_trait_vals, target_vals, num_overlap = corr_result_helpers.normalize_values(this_trait_vals, target_vals)
+ if num_overlap == 0:
+ corr_result_row.append([target_trait, 0, num_overlap])
+ else:
+ if is_spearman == False:
+ sample_r, sample_p = scipy.stats.pearsonr(this_trait_vals, target_vals)
+ if sample_r == 1:
+ is_spearman = True
+ else:
+ sample_r, sample_p = scipy.stats.spearmanr(this_trait_vals, target_vals)
+
+ corr_result_row.append([target_trait, sample_r, num_overlap])
self.corr_results.append(corr_result_row)
@@ -152,15 +159,25 @@ class CorrelationMatrix(object):
for sample in self.all_sample_list:
groups.append(1)
- pca = self.calculate_pca(self.corr_results, range(len(self.traits)))
+ #pca = self.calculate_pca(self.corr_results, range(len(self.traits)))
- self.js_data = dict(traits = self.traits,
+
+ self.js_data = dict(traits = [trait.name for trait in self.traits],
groups = groups,
cols = range(len(self.traits)),
rows = range(len(self.traits)),
samples = self.all_sample_list,
- sample_data = self.sample_data,
- corr_results = self.corr_results,)
+ sample_data = self.sample_data,)
+ # corr_results = [result[1] for result in result_row for result_row in self.corr_results])
+
+
+ #self.js_data = dict(traits = self.traits,
+ # groups = groups,
+ # cols = range(len(self.traits)),
+ # rows = range(len(self.traits)),
+ # samples = self.all_sample_list,
+ # sample_data = self.sample_data,
+ # corr_results = self.corr_results,)
@@ -194,21 +211,8 @@ class CorrelationMatrix(object):
print("eigen:", eigen)
pca = stats.princomp(m, cor = "TRUE")
print("pca:", pca)
+ print("loadings:", pca.rx('loadings'))
+ print("scores:", pca.rx('scores'))
+ print("scale:", pca.rx('scale'))
- return pca
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ return pca \ No newline at end of file
diff --git a/wqflask/wqflask/database.py b/wqflask/wqflask/database.py
index e55f06a7..159c5d6c 100755
--- a/wqflask/wqflask/database.py
+++ b/wqflask/wqflask/database.py
@@ -13,6 +13,11 @@ db_session = scoped_session(sessionmaker(autocommit=False,
Base = declarative_base()
Base.query = db_session.query_property()
+#import logging
+#
+#logging.basicConfig()
+#logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
+
def init_db():
# import all modules here that might define models so that
# they will be registered properly on the metadata. Otherwise
@@ -23,4 +28,4 @@ def init_db():
Base.metadata.create_all(bind=engine)
print("Done creating all...")
-init_db() \ No newline at end of file
+init_db()
diff --git a/wqflask/wqflask/do_search.py b/wqflask/wqflask/do_search.py
index 921a4a47..617d7942 100755
--- a/wqflask/wqflask/do_search.py
+++ b/wqflask/wqflask/do_search.py
@@ -3,6 +3,8 @@
from __future__ import print_function, division
+import string
+
from flask import Flask, g
from MySQLdb import escape_string as escape
@@ -40,6 +42,13 @@ class DoSearch(object):
results = g.db.execute(query, no_parameters=True).fetchall()
return results
+ def handle_wildcard(self, str):
+ keyword = str.strip()
+ keyword.replace("*",".*")
+ keyword.replace("?",".")
+
+ return keyword
+
#def escape(self, stringy):
# """Shorter name than self.db_conn.escape_string"""
# return escape(str(stringy))
@@ -58,7 +67,17 @@ class DoSearch(object):
@classmethod
def get_search(cls, search_type):
print("search_types are:", pf(cls.search_types))
- return cls.search_types[search_type]
+
+ search_type_string = search_type['dataset_type']
+ if 'key' in search_type:
+ search_type_string += '_' + search_type['key']
+
+ print("search_type_string is:", search_type_string)
+
+ if search_type_string in cls.search_types:
+ return cls.search_types[search_type_string]
+ else:
+ return None
class QuickMrnaAssaySearch(DoSearch):
"""A general search for mRNA assays"""
@@ -73,7 +92,7 @@ class QuickMrnaAssaySearch(DoSearch):
ProbeSet.name_num as ProbeSet_name_num
FROM ProbeSet """
- header_fields = ['',
+ header_fields = ['Index',
'Record',
'Symbol',
'Location']
@@ -99,7 +118,7 @@ class MrnaAssaySearch(DoSearch):
DoSearch.search_types['ProbeSet'] = "MrnaAssaySearch"
- base_query = """SELECT ProbeSet.Name as TNAME,
+ base_query = """SELECT distinct ProbeSet.Name as TNAME,
0 as thistable,
ProbeSetXRef.Mean as TMEAN,
ProbeSetXRef.LRS as TLRS,
@@ -110,7 +129,7 @@ class MrnaAssaySearch(DoSearch):
ProbeSet.name_num as TNAME_NUM
FROM ProbeSetXRef, ProbeSet """
- header_fields = ['',
+ header_fields = ['Index',
'Record',
'Symbol',
'Description',
@@ -120,6 +139,28 @@ class MrnaAssaySearch(DoSearch):
'Max LRS Location',
'Additive Effect']
+ def get_where_clause(self):
+
+ if self.search_term[0] != "*":
+ match_clause = """(MATCH (ProbeSet.Name,
+ ProbeSet.description,
+ ProbeSet.symbol,
+ alias,
+ GenbankId,
+ UniGeneId,
+ Probe_Target_Description)
+ AGAINST ('%s' IN BOOLEAN MODE)) and
+ """ % (escape(self.search_term[0]))
+ else:
+ match_clause = ""
+
+ where_clause = (match_clause +
+ """ProbeSet.Id = ProbeSetXRef.ProbeSetId
+ and ProbeSetXRef.ProbeSetFreezeId = %s
+ """ % (escape(str(self.dataset.id))))
+
+ return where_clause
+
def compile_final_query(self, from_clause = '', where_clause = ''):
"""Generates the final query string"""
@@ -138,23 +179,7 @@ class MrnaAssaySearch(DoSearch):
return query
- def get_where_clause(self):
- where_clause = """(MATCH (ProbeSet.Name,
- ProbeSet.description,
- ProbeSet.symbol,
- alias,
- GenbankId,
- UniGeneId,
- Probe_Target_Description)
- AGAINST ('%s' IN BOOLEAN MODE))
- and ProbeSet.Id = ProbeSetXRef.ProbeSetId
- and ProbeSetXRef.ProbeSetFreezeId = %s
- """ % (escape(self.search_term[0]),
- escape(str(self.dataset.id)))
-
- return where_clause
-
- def run_combined(self, from_clause, where_clause):
+ def run_combined(self, from_clause = '', where_clause = ''):
"""Generates and runs a combined search of an mRNA expression dataset"""
print("Running ProbeSetSearch")
@@ -173,7 +198,6 @@ class MrnaAssaySearch(DoSearch):
print("final query is:", pf(query))
-
return self.execute(query)
def run(self):
@@ -210,7 +234,7 @@ class PhenotypeSearch(DoSearch):
'Publication.Authors',
'PublishXRef.Id')
- header_fields = ['',
+ header_fields = ['Index',
'Record',
'Description',
'Authors',
@@ -219,28 +243,62 @@ class PhenotypeSearch(DoSearch):
'Max LRS Location',
'Additive Effect']
- def get_fields_clause(self):
+ def get_where_clause(self):
"""Generate clause for WHERE portion of query"""
#Todo: Zach will figure out exactly what both these lines mean
#and comment here
if "'" not in self.search_term[0]:
- search_term = "[[:<:]]" + self.search_term[0] + "[[:>:]]"
+ search_term = "[[:<:]]" + self.handle_wildcard(self.search_term[0]) + "[[:>:]]"
# This adds a clause to the query that matches the search term
# against each field in the search_fields tuple
- fields_clause = []
+ where_clause_list = []
for field in self.search_fields:
- fields_clause.append('''%s REGEXP "%s"''' % (field, search_term))
- fields_clause = "(%s) and " % ' OR '.join(fields_clause)
+ where_clause_list.append('''%s REGEXP "%s"''' % (field, search_term))
+ where_clause = "(%s) " % ' OR '.join(where_clause_list)
- return fields_clause
+ return where_clause
def compile_final_query(self, from_clause = '', where_clause = ''):
"""Generates the final query string"""
from_clause = self.normalize_spaces(from_clause)
+ if self.search_term[0] == "*":
+ query = (self.base_query +
+ """%s
+ WHERE PublishXRef.InbredSetId = %s
+ and PublishXRef.PhenotypeId = Phenotype.Id
+ and PublishXRef.PublicationId = Publication.Id
+ and PublishFreeze.Id = %s""" % (
+ from_clause,
+ escape(str(self.dataset.group.id)),
+ escape(str(self.dataset.id))))
+ else:
+ query = (self.base_query +
+ """%s
+ WHERE %s
+ and PublishXRef.InbredSetId = %s
+ and PublishXRef.PhenotypeId = Phenotype.Id
+ and PublishXRef.PublicationId = Publication.Id
+ and PublishFreeze.Id = %s""" % (
+ from_clause,
+ where_clause,
+ escape(str(self.dataset.group.id)),
+ escape(str(self.dataset.id))))
+
+ print("query is:", pf(query))
+
+ return query
+
+ def run_combined(self, from_clause, where_clause):
+ """Generates and runs a combined search of an phenotype dataset"""
+
+ print("Running PhenotypeSearch")
+
+ from_clause = self.normalize_spaces(from_clause)
+
query = (self.base_query +
"""%s
WHERE %s
@@ -253,14 +311,15 @@ class PhenotypeSearch(DoSearch):
escape(str(self.dataset.group.id)),
escape(str(self.dataset.id))))
- print("query is:", pf(query))
+ print("final query is:", pf(query))
- return query
+
+ return self.execute(query)
def run(self):
"""Generates and runs a simple search of a phenotype dataset"""
- query = self.compile_final_query(where_clause = self.get_fields_clause())
+ query = self.compile_final_query(where_clause = self.get_where_clause())
return self.execute(query)
@@ -310,7 +369,7 @@ class QuickPhenotypeSearch(PhenotypeSearch):
def run(self):
"""Generates and runs a search across all phenotype datasets"""
- query = self.compile_final_query(where_clause = self.get_fields_clause())
+ query = self.compile_final_query(where_clause = self.get_where_clause())
return self.execute(query)
@@ -329,40 +388,47 @@ class GenotypeSearch(DoSearch):
search_fields = ('Name', 'Chr')
- header_fields = ['',
+ header_fields = ['Index',
'Record',
'Location']
- def get_fields_clause(self):
+ def get_where_clause(self):
"""Generate clause for part of the WHERE portion of query"""
# This adds a clause to the query that matches the search term
# against each field in search_fields (above)
- fields_clause = []
+ where_clause = []
if "'" not in self.search_term[0]:
self.search_term = "[[:<:]]" + self.search_term[0] + "[[:>:]]"
for field in self.search_fields:
- fields_clause.append('''%s REGEXP "%s"''' % ("%s.%s" % self.mescape(self.dataset.type,
+ where_clause.append('''%s REGEXP "%s"''' % ("%s.%s" % self.mescape(self.dataset.type,
field),
self.search_term))
- print("hello ;where_clause is:", pf(fields_clause))
- fields_clause = "(%s)" % ' OR '.join(fields_clause)
+ print("hello ;where_clause is:", pf(where_clause))
+ where_clause = "(%s) " % ' OR '.join(where_clause)
- return fields_clause
+ return where_clause
def compile_final_query(self, from_clause = '', where_clause = ''):
"""Generates the final query string"""
from_clause = self.normalize_spaces(from_clause)
- query = (self.base_query +
- """WHERE %s and
- Geno.Id = GenoXRef.GenoId and
- GenoXRef.GenoFreezeId = GenoFreeze.Id and
- GenoFreeze.Id = %s"""% (where_clause,
- escape(str(self.dataset.id))))
+
+ if self.search_term[0] == "*":
+ query = (self.base_query +
+ """WHERE Geno.Id = GenoXRef.GenoId
+ and GenoXRef.GenoFreezeId = GenoFreeze.Id
+ and GenoFreeze.Id = %s"""% (escape(str(self.dataset.id))))
+ else:
+ query = (self.base_query +
+ """WHERE %s
+ and Geno.Id = GenoXRef.GenoId
+ and GenoXRef.GenoFreezeId = GenoFreeze.Id
+ and GenoFreeze.Id = %s"""% (where_clause,
+ escape(str(self.dataset.id))))
print("query is:", pf(query))
@@ -373,14 +439,20 @@ class GenotypeSearch(DoSearch):
#Todo: Zach will figure out exactly what both these lines mean
#and comment here
- self.query = self.compile_final_query(where_clause = self.get_fields_clause())
+ if self.search_term[0] == "*":
+ self.query = self.compile_final_query()
+ else:
+ self.query = self.compile_final_query(where_clause = self.get_where_clause())
return self.execute(self.query)
class RifSearch(MrnaAssaySearch):
"""Searches for traits with a Gene RIF entry including the search term."""
- DoSearch.search_types['RIF'] = "RifSearch"
+ DoSearch.search_types['ProbeSet_RIF'] = "RifSearch"
+
+ def get_from_clause(self):
+ return ", GeneRIF_BASIC "
def get_where_clause(self):
where_clause = """( %s.symbol = GeneRIF_BASIC.symbol and
@@ -390,13 +462,9 @@ class RifSearch(MrnaAssaySearch):
return where_clause
def run(self):
- #where_clause = """( %s.symbol = GeneRIF_BASIC.symbol and
- # MATCH (GeneRIF_BASIC.comment)
- # AGAINST ('+%s' IN BOOLEAN MODE)) """ % (self.dataset.type, self.search_term[0])
-
+ from_clause = self.get_from_clause()
where_clause = self.get_where_clause()
- from_clause = ", GeneRIF_BASIC "
query = self.compile_final_query(from_clause, where_clause)
return self.execute(query)
@@ -404,7 +472,10 @@ class RifSearch(MrnaAssaySearch):
class WikiSearch(MrnaAssaySearch):
"""Searches GeneWiki for traits other people have annotated"""
- DoSearch.search_types['WIKI'] = "WikiSearch"
+ DoSearch.search_types['ProbeSet_WIKI'] = "WikiSearch"
+
+ def get_from_clause(self):
+ return ", GeneRIF "
def get_where_clause(self):
where_clause = """%s.symbol = GeneRIF.symbol
@@ -416,16 +487,9 @@ class WikiSearch(MrnaAssaySearch):
return where_clause
def run(self):
- #where_clause = """%s.symbol = GeneRIF.symbol
- # and GeneRIF.versionId=0 and GeneRIF.display>0
- # and (GeneRIF.comment REGEXP '%s' or GeneRIF.initial = '%s')
- # """ % (self.dataset.type,
- # "[[:<:]]"+str(self.search_term[0])+"[[:>:]]",
- # str(self.search_term[0]))
-
+ from_clause = self.get_from_clause()
where_clause = self.get_where_clause()
- from_clause = ", GeneRIF "
query = self.compile_final_query(from_clause, where_clause)
return self.execute(query)
@@ -433,9 +497,16 @@ class WikiSearch(MrnaAssaySearch):
class GoSearch(MrnaAssaySearch):
"""Searches for synapse-associated genes listed in the Gene Ontology."""
- DoSearch.search_types['GO'] = "GoSearch"
+ DoSearch.search_types['ProbeSet_GO'] = "GoSearch"
- def run(self):
+ def get_from_clause(self):
+ from_clause = """, db_GeneOntology.term as GOterm,
+ db_GeneOntology.association as GOassociation,
+ db_GeneOntology.gene_product as GOgene_product """
+
+ return from_clause
+
+ def get_where_clause(self):
field = 'GOterm.acc'
go_id = 'GO:' + ('0000000'+self.search_term[0])[-7:]
@@ -446,16 +517,18 @@ class GoSearch(MrnaAssaySearch):
where_clause = " %s = '%s' and %s " % (field, go_id, statements)
- from_clause = """ , db_GeneOntology.term as GOterm,
- db_GeneOntology.association as GOassociation,
- db_GeneOntology.gene_product as GOgene_product """
+ return where_clause
+
+ def run(self):
+ from_clause = self.get_from_clause()
+ where_clause = self.get_where_clause()
query = self.compile_final_query(from_clause, where_clause)
return self.execute(query)
#ZS: Not sure what the best way to deal with LRS searches is
-class LrsSearch(MrnaAssaySearch):
+class LrsSearch(DoSearch):
"""Searches for genes with a QTL within the given LRS values
LRS searches can take 3 different forms:
@@ -470,163 +543,162 @@ class LrsSearch(MrnaAssaySearch):
DoSearch.search_types['LRS'] = 'LrsSearch'
def get_from_clause(self):
- if self.search_operator == "=":
- return ", Geno"
- else:
- return ""
+ #If the user typed, for example "Chr4", the "Chr" substring needs to be removed so that all search elements can be converted to floats
+ if len(self.search_term) > 2 and "Chr" in self.search_term[2]:
+ chr_num = self.search_term[2].replace("Chr", "")
+ self.search_term[2] = chr_num
- def get_where_clause(self):
self.search_term = [float(value) for value in self.search_term]
+ if len(self.search_term) > 2:
+ from_clause = ", Geno"
+ else:
+ from_clause = ""
+
+ return from_clause
+
+ def get_where_clause(self):
if self.search_operator == "=":
assert isinstance(self.search_term, (list, tuple))
- self.lrs_min, self.lrs_max = self.search_term[:2]
+ lrs_min, lrs_max = self.search_term[:2]
- self.sub_clause = """ %sXRef.LRS > %s and
- %sXRef.LRS < %s and """ % self.mescape(self.dataset.type,
- min(self.lrs_min, self.lrs_max),
+ where_clause = """ %sXRef.LRS > %s and
+ %sXRef.LRS < %s """ % self.mescape(self.dataset.type,
+ min(lrs_min, lrs_max),
self.dataset.type,
- max(self.lrs_min, self.lrs_max))
+ max(lrs_min, lrs_max))
if len(self.search_term) > 2:
- self.chr_num = self.search_term[2]
- self.sub_clause += """ Geno.Chr = %s and """ % (self.chr_num)
+ chr_num = self.search_term[2]
+ where_clause += """ and Geno.Chr = %s """ % (chr_num)
if len(self.search_term) == 5:
- self.mb_low, self.mb_high = self.search_term[3:]
- self.sub_clause += """ Geno.Mb > %s and
- Geno.Mb < %s and
- """ % self.mescape(min(self.mb_low, self.mb_high),
- max(self.mb_low, self.mb_high))
- print("self.sub_clause is:", pf(self.sub_clause))
-
- #%s.Chr = Geno.Chr
- where_clause = self.sub_clause + """ %sXRef.Locus = Geno.name and
+ mb_low, mb_high = self.search_term[3:]
+ where_clause += """ and Geno.Mb > %s and
+ Geno.Mb < %s
+ """ % self.mescape(min(mb_low, mb_high),
+ max(mb_low, mb_high))
+
+ where_clause += """ and %sXRef.Locus = Geno.name and
Geno.SpeciesId = %s
""" % self.mescape(self.dataset.type,
self.species_id)
else:
# Deal with >, <, >=, and <=
print("self.search_term is:", self.search_term)
- self.sub_clause = """ %sXRef.LRS %s %s """ % self.mescape(self.dataset.type,
+ where_clause = """ %sXRef.LRS %s %s """ % self.mescape(self.dataset.type,
self.search_operator,
self.search_term[0])
- where_clause = self.sub_clause
-
-
+
return where_clause
- def get_final_query(self):
+
+ def run(self):
+
self.from_clause = self.get_from_clause()
self.where_clause = self.get_where_clause()
+
self.query = self.compile_final_query(self.from_clause, self.where_clause)
- return self.query
+ return self.execute(self.query)
+
+class MrnaLrsSearch(LrsSearch, MrnaAssaySearch):
+
+ DoSearch.search_types['ProbeSet_LRS'] = 'MrnaLrsSearch'
def run(self):
self.from_clause = self.get_from_clause()
+ self.where_clause = self.get_where_clause()
+
+ self.query = self.compile_final_query(from_clause = self.from_clause, where_clause = self.where_clause)
+
+ return self.execute(self.query)
- #self.search_term = [float(value) for value in self.search_term]
- #
- #if self.search_operator == "=":
- # assert isinstance(self.search_term, (list, tuple))
- # self.lrs_min, self.lrs_max = self.search_term[:2]
- #
- # self.sub_clause = """ %sXRef.LRS > %s and
- # %sXRef.LRS < %s and """ % self.mescape(self.dataset.type,
- # min(self.lrs_min, self.lrs_max),
- # self.dataset.type,
- # max(self.lrs_min, self.lrs_max))
- #
- # if len(self.search_term) > 2:
- # self.chr_num = self.search_term[2]
- # self.sub_clause += """ Geno.Chr = %s and """ % (escape(self.chr_num))
- # if len(self.search_term) == 5:
- # self.mb_low, self.mb_high = self.search_term[3:]
- # self.sub_clause += """ Geno.Mb > %s and
- # Geno.Mb < %s and
- # """ % self.mescape(min(self.mb_low, self.mb_high),
- # max(self.mb_low, self.mb_high))
- # print("self.sub_clause is:", pf(self.sub_clause))
- #else:
- # # Deal with >, <, >=, and <=
- # print("self.search_term is:", self.search_term)
- # self.sub_clause = """ %sXRef.LRS %s %s and """ % self.mescape(self.dataset.type,
- # self.search_operator,
- # self.search_term[0])
- #
- #self.where_clause = self.sub_clause + """ %sXRef.Locus = Geno.name and
- # Geno.SpeciesId = %s and
- # %s.Chr = Geno.Chr
- # """ % self.mescape(self.dataset.type,
- # self.species_id,
- # self.dataset.type)
+class PhenotypeLrsSearch(LrsSearch, PhenotypeSearch):
+
+ DoSearch.search_types['Publish_LRS'] = 'PhenotypeLrsSearch'
+ def run(self):
+
+ self.from_clause = self.get_from_clause()
self.where_clause = self.get_where_clause()
- self.query = self.compile_final_query(self.from_clause, self.where_clause)
+ self.query = self.compile_final_query(from_clause = self.from_clause, where_clause = self.where_clause)
return self.execute(self.query)
-class CisTransLrsSearch(LrsSearch):
- def real_run(self, the_operator):
- #if isinstance(self.search_term, basestring):
- # self.search_term = [self.search_term]
- print("self.search_term is:", self.search_term)
+class CisTransLrsSearch(DoSearch):
+
+ def get_from_clause(self):
+ return ", Geno"
+
+ def get_where_clause(self, cis_trans):
self.search_term = [float(value) for value in self.search_term]
self.mb_buffer = 5 # default
-
- self.from_clause = ", Geno "
+ if cis_trans == "cis":
+ the_operator = "<"
+ else:
+ the_operator = ">"
if self.search_operator == "=":
if len(self.search_term) == 2:
- self.lrs_min, self.lrs_max = self.search_term
+ lrs_min, lrs_max = self.search_term
#[int(value) for value in self.search_term]
elif len(self.search_term) == 3:
- self.lrs_min, self.lrs_max, self.mb_buffer = self.search_term
+ lrs_min, lrs_max, self.mb_buffer = self.search_term
else:
SomeError
- self.sub_clause = """ %sXRef.LRS > %s and
+ sub_clause = """ %sXRef.LRS > %s and
%sXRef.LRS < %s and """ % (
escape(self.dataset.type),
- escape(min(self.lrs_min, self.lrs_max)),
+ escape(str(min(lrs_min, lrs_max))),
escape(self.dataset.type),
- escape(max(self.lrs_min, self.lrs_max))
+ escape(str(max(lrs_min, lrs_max)))
)
else:
# Deal with >, <, >=, and <=
- self.sub_clause = """ %sXRef.LRS %s %s and """ % (
+ sub_clause = """ %sXRef.LRS %s %s and """ % (
escape(self.dataset.type),
escape(self.search_operator),
escape(self.search_term[0])
)
- self.where_clause = self.sub_clause + """
- ABS(%s.Mb-Geno.Mb) %s %s and
- %sXRef.Locus = Geno.name and
- Geno.SpeciesId = %s and
- %s.Chr = Geno.Chr""" % (
- escape(self.dataset.type),
- the_operator,
- escape(self.mb_buffer),
- escape(self.dataset.type),
- escape(self.species_id),
- escape(self.dataset.type)
- )
-
- print("where_clause is:", pf(self.where_clause))
-
- self.query = self.compile_final_query(self.from_clause, self.where_clause)
-
- return self.execute(self.query)
-
+ if cis_trans == "cis":
+ where_clause = sub_clause + """
+ ABS(%s.Mb-Geno.Mb) %s %s and
+ %sXRef.Locus = Geno.name and
+ Geno.SpeciesId = %s and
+ %s.Chr = Geno.Chr""" % (
+ escape(self.dataset.type),
+ the_operator,
+ escape(str(self.mb_buffer)),
+ escape(self.dataset.type),
+ escape(str(self.species_id)),
+ escape(self.dataset.type)
+ )
+ else:
+ where_clause = sub_clause + """
+ %sXRef.Locus = Geno.name and
+ Geno.SpeciesId = %s and
+ ((ABS(%s.Mb-Geno.Mb) %s %s and %s.Chr = Geno.Chr) or
+ (%s.Chr != Geno.Chr))""" % (
+ escape(self.dataset.type),
+ escape(str(self.species_id)),
+ escape(self.dataset.type),
+ the_operator,
+ escape(str(self.mb_buffer)),
+ escape(self.dataset.type),
+ escape(self.dataset.type)
+ )
-class CisLrsSearch(CisTransLrsSearch):
+ return where_clause
+
+class CisLrsSearch(CisTransLrsSearch, MrnaAssaySearch):
"""
Searches for genes on a particular chromosome with a cis-eQTL within the given LRS values
@@ -643,12 +715,20 @@ class CisLrsSearch(CisTransLrsSearch):
"""
- DoSearch.search_types['CISLRS'] = "CisLrsSearch"
+ DoSearch.search_types['ProbeSet_CISLRS'] = 'CisLrsSearch'
+
+ def get_where_clause(self):
+ return CisTransLrsSearch.get_where_clause(self, "cis")
def run(self):
- return self.real_run("<")
+ self.from_clause = self.get_from_clause()
+ self.where_clause = self.get_where_clause()
+
+ self.query = self.compile_final_query(self.from_clause, self.where_clause)
+
+ return self.execute(self.query)
-class TransLrsSearch(CisTransLrsSearch):
+class TransLrsSearch(CisTransLrsSearch, MrnaAssaySearch):
"""Searches for genes on a particular chromosome with a cis-eQTL within the given LRS values
A transLRS search can take 3 forms:
@@ -664,16 +744,24 @@ class TransLrsSearch(CisTransLrsSearch):
"""
- DoSearch.search_types['TRANSLRS'] = "TransLrsSearch"
+ DoSearch.search_types['ProbeSet_TRANSLRS'] = 'TransLrsSearch'
+
+ def get_where_clause(self):
+ return CisTransLrsSearch.get_where_clause(self, "trans")
def run(self):
- return self.real_run(">")
+ self.from_clause = self.get_from_clause()
+ self.where_clause = self.get_where_clause()
+
+ self.query = self.compile_final_query(self.from_clause, self.where_clause)
+
+ return self.execute(self.query)
class MeanSearch(MrnaAssaySearch):
"""Searches for genes expressed within an interval (log2 units) determined by the user"""
- DoSearch.search_types['MEAN'] = "MeanSearch"
+ DoSearch.search_types['ProbeSet_MEAN'] = "MeanSearch"
def get_where_clause(self):
self.search_term = [float(value) for value in self.search_term]
@@ -704,24 +792,6 @@ class MeanSearch(MrnaAssaySearch):
return self.query
def run(self):
-
- #self.search_term = [float(value) for value in self.search_term]
- #
- #if self.search_operator == "=":
- # assert isinstance(self.search_term, (list, tuple))
- # self.mean_min, self.mean_max = self.search_term[:2]
- #
- # self.where_clause = """ %sXRef.mean > %s and
- # %sXRef.mean < %s """ % self.mescape(self.dataset.type,
- # min(self.mean_min, self.mean_max),
- # self.dataset.type,
- # max(self.mean_min, self.mean_max))
- #else:
- # # Deal with >, <, >=, and <=
- # self.where_clause = """ %sXRef.mean %s %s """ % self.mescape(self.dataset.type,
- # self.search_operator,
- # self.search_term[0])
-
self.where_clause = self.get_where_clause()
print("where_clause is:", pf(self.where_clause))
@@ -732,7 +802,7 @@ class MeanSearch(MrnaAssaySearch):
class RangeSearch(MrnaAssaySearch):
"""Searches for genes with a range of expression varying between two values"""
- DoSearch.search_types['RANGE'] = "RangeSearch"
+ DoSearch.search_types['ProbeSet_RANGE'] = "RangeSearch"
def get_where_clause(self):
if self.search_operator == "=":
@@ -758,27 +828,6 @@ class RangeSearch(MrnaAssaySearch):
return where_clause
def run(self):
-
- #self.search_term = [float(value) for value in self.search_term]
- #
- #if self.search_operator == "=":
- # assert isinstance(self.search_term, (list, tuple))
- # self.range_min, self.range_max = self.search_term[:2]
- # self.where_clause = """ (SELECT Pow(2, max(value) -min(value))
- # FROM ProbeSetData
- # WHERE ProbeSetData.Id = ProbeSetXRef.dataId) > %s AND
- # (SELECT Pow(2, max(value) -min(value))
- # FROM ProbeSetData
- # WHERE ProbeSetData.Id = ProbeSetXRef.dataId) < %s
- # """ % self.mescape(min(self.range_min, self.range_max),
- # max(self.range_min, self.range_max))
- #else:
- # # Deal with >, <, >=, and <=
- # self.where_clause = """ (SELECT Pow(2, max(value) -min(value))
- # FROM ProbeSetData
- # WHERE ProbeSetData.Id = ProbeSetXRef.dataId) > %s
- # """ % (escape(self.search_term[0]))
-
self.where_clause = self.get_where_clause()
self.query = self.compile_final_query(where_clause = self.where_clause)
@@ -791,10 +840,12 @@ class PositionSearch(DoSearch):
for search_key in ('POSITION', 'POS', 'MB'):
DoSearch.search_types[search_key] = "PositionSearch"
- def setup(self):
- self.search_term = [float(value) for value in self.search_term]
+ def get_where_clause(self):
+ self.search_term = [float(value) if is_number(value) else value for value in self.search_term]
self.chr, self.mb_min, self.mb_max = self.search_term[:3]
- self.where_clause = """ %s.Chr = '%s' and
+ self.get_chr()
+
+ where_clause = """ %s.Chr = %s and
%s.Mb > %s and
%s.Mb < %s """ % self.mescape(self.dataset.type,
self.chr,
@@ -803,29 +854,44 @@ class PositionSearch(DoSearch):
self.dataset.type,
max(self.mb_min, self.mb_max))
+
+ return where_clause
+
+ def get_chr(self):
+ try:
+ self.chr = int(self.chr)
+ except:
+ self.chr = int(self.chr.replace('chr', ''))
+
def run(self):
- self.setup()
+ self.get_where_clause()
self.query = self.compile_final_query(where_clause = self.where_clause)
return self.execute(self.query)
-class MrnaPositionSearch(MrnaAssaySearch, PositionSearch):
+class MrnaPositionSearch(PositionSearch, MrnaAssaySearch):
"""Searches for genes located within a specified range on a specified chromosome"""
+ for search_key in ('POSITION', 'POS', 'MB'):
+ DoSearch.search_types['ProbeSet_'+search_key] = "MrnaPositionSearch"
+
def run(self):
- self.setup()
+ self.where_clause = self.get_where_clause()
self.query = self.compile_final_query(where_clause = self.where_clause)
return self.execute(self.query)
-class GenotypePositionSearch(GenotypeSearch, PositionSearch):
+class GenotypePositionSearch(PositionSearch, GenotypeSearch):
"""Searches for genes located within a specified range on a specified chromosome"""
+ for search_key in ('POSITION', 'POS', 'MB'):
+ DoSearch.search_types['Geno_'+search_key] = "GenotypePositionSearch"
+
def run(self):
- self.setup()
+ self.where_clause = self.get_where_clause()
self.query = self.compile_final_query(where_clause = self.where_clause)
return self.execute(self.query)
@@ -833,6 +899,8 @@ class GenotypePositionSearch(GenotypeSearch, PositionSearch):
class PvalueSearch(MrnaAssaySearch):
"""Searches for traits with a permutationed p-value between low and high"""
+ DoSearch.search_types['ProbeSet_PVALUE'] = "PvalueSearch"
+
def run(self):
self.search_term = [float(value) for value in self.search_term]
@@ -863,7 +931,7 @@ class PvalueSearch(MrnaAssaySearch):
class AuthorSearch(PhenotypeSearch):
"""Searches for phenotype traits with specified author(s)"""
- DoSearch.search_types["NAME"] = "AuthorSearch"
+ DoSearch.search_types["Publish_NAME"] = "AuthorSearch"
def run(self):
@@ -875,6 +943,12 @@ class AuthorSearch(PhenotypeSearch):
return self.execute(self.query)
+def is_number(s):
+ try:
+ float(s)
+ return True
+ except ValueError:
+ return False
if __name__ == "__main__":
### Usually this will be used as a library, but call it from the command line for testing
diff --git a/wqflask/wqflask/docs.py b/wqflask/wqflask/docs.py
index 07b0b81a..a8363a1f 100755
--- a/wqflask/wqflask/docs.py
+++ b/wqflask/wqflask/docs.py
@@ -8,9 +8,9 @@ class Docs(object):
sql = """
SELECT Docs.title, Docs.content
FROM Docs
- WHERE Docs.entry LIKE '%s'
+ WHERE Docs.entry LIKE %s
"""
- result = g.db.execute(sql % (entry)).fetchone()
+ result = g.db.execute(sql, str(entry)).fetchone()
self.entry = entry
self.title = result[0]
self.content = result[1]
diff --git a/wqflask/wqflask/gsearch.py b/wqflask/wqflask/gsearch.py
new file mode 100755
index 00000000..3d693a4c
--- /dev/null
+++ b/wqflask/wqflask/gsearch.py
@@ -0,0 +1,92 @@
+from __future__ import absolute_import, print_function, division
+
+from flask import Flask, g
+from base.data_set import create_dataset
+from base.trait import GeneralTrait
+from dbFunction import webqtlDatabaseFunction
+
+class GSearch(object):
+
+ def __init__(self, kw):
+ self.type = kw['type']
+ self.terms = kw['terms']
+ if self.type == "gene":
+ sql = """
+ SELECT
+ Species.`Name` AS species_name,
+ InbredSet.`Name` AS inbredset_name,
+ Tissue.`Name` AS tissue_name,
+ ProbeSetFreeze.Name AS probesetfreeze_name,
+ ProbeSet.Name AS probeset_name,
+ ProbeSet.Symbol AS probeset_symbol,
+ ProbeSet.`description` AS probeset_description,
+ ProbeSet.Chr AS chr,
+ ProbeSet.Mb AS mb,
+ ProbeSetXRef.Mean AS mean,
+ ProbeSetXRef.LRS AS lrs,
+ ProbeSetXRef.`Locus` AS locus,
+ ProbeSetXRef.`pValue` AS pvalue,
+ ProbeSetXRef.`additive` AS additive
+ FROM Species, InbredSet, ProbeSetXRef, ProbeSet, ProbeFreeze, ProbeSetFreeze, Tissue
+ WHERE InbredSet.`SpeciesId`=Species.`Id`
+ AND ProbeFreeze.InbredSetId=InbredSet.`Id`
+ AND ProbeFreeze.`TissueId`=Tissue.`Id`
+ AND ProbeSetFreeze.ProbeFreezeId=ProbeFreeze.Id
+ AND ( MATCH (ProbeSet.Name,ProbeSet.description,ProbeSet.symbol,alias,GenbankId, UniGeneId, Probe_Target_Description) AGAINST ('%s' IN BOOLEAN MODE) )
+ AND ProbeSet.Id = ProbeSetXRef.ProbeSetId
+ AND ProbeSetXRef.ProbeSetFreezeId=ProbeSetFreeze.Id
+ AND ProbeSetFreeze.public > 0
+ ORDER BY species_name, inbredset_name, tissue_name, probesetfreeze_name, probeset_name
+ LIMIT 1000
+ """ % (self.terms)
+ re = g.db.execute(sql).fetchall()
+ self.trait_list = []
+ for line in re:
+ dataset = create_dataset(line[3], "ProbeSet")
+ trait_id = line[4]
+ this_trait = GeneralTrait(dataset=dataset, name=trait_id, get_qtl_info=True)
+ self.trait_list.append(this_trait)
+ species = webqtlDatabaseFunction.retrieve_species(dataset.group.name)
+ dataset.get_trait_info([this_trait], species)
+
+ elif self.type == "phenotype":
+ sql = """
+ SELECT
+ Species.`Name`,
+ InbredSet.`Name`,
+ PublishFreeze.`Name`,
+ PublishXRef.`Id`,
+ Phenotype.`Post_publication_description`,
+ Publication.`Authors`,
+ Publication.`Year`,
+ PublishXRef.`LRS`,
+ PublishXRef.`Locus`,
+ PublishXRef.`additive`
+ FROM Species,InbredSet,PublishFreeze,PublishXRef,Phenotype,Publication
+ WHERE PublishXRef.`InbredSetId`=InbredSet.`Id`
+ AND PublishFreeze.`InbredSetId`=InbredSet.`Id`
+ AND InbredSet.`SpeciesId`=Species.`Id`
+ AND PublishXRef.`PhenotypeId`=Phenotype.`Id`
+ AND PublishXRef.`PublicationId`=Publication.`Id`
+ AND (Phenotype.Post_publication_description REGEXP "[[:<:]]%s[[:>:]]"
+ OR Phenotype.Pre_publication_description REGEXP "[[:<:]]%s[[:>:]]"
+ OR Phenotype.Pre_publication_abbreviation REGEXP "[[:<:]]%s[[:>:]]"
+ OR Phenotype.Post_publication_abbreviation REGEXP "[[:<:]]%s[[:>:]]"
+ OR Phenotype.Lab_code REGEXP "[[:<:]]%s[[:>:]]"
+ OR Publication.PubMed_ID REGEXP "[[:<:]]%s[[:>:]]"
+ OR Publication.Abstract REGEXP "[[:<:]]%s[[:>:]]"
+ OR Publication.Title REGEXP "[[:<:]]%s[[:>:]]"
+ OR Publication.Authors REGEXP "[[:<:]]%s[[:>:]]"
+ OR PublishXRef.Id REGEXP "[[:<:]]%s[[:>:]]")
+ ORDER BY Species.`Name`, InbredSet.`Name`, PublishXRef.`Id`
+ LIMIT 1000
+ """ % (self.terms, self.terms, self.terms, self.terms, self.terms, self.terms, self.terms, self.terms, self.terms, self.terms)
+ re = g.db.execute(sql).fetchall()
+ self.trait_list = []
+ for line in re:
+ dataset = create_dataset(line[2], "Publish")
+ trait_id = line[3]
+ this_trait = GeneralTrait(dataset=dataset, name=trait_id, get_qtl_info=True)
+ self.trait_list.append(this_trait)
+ species = webqtlDatabaseFunction.retrieve_species(dataset.group.name)
+ dataset.get_trait_info([this_trait], species)
diff --git a/wqflask/wqflask/heatmap/heatmap.py b/wqflask/wqflask/heatmap/heatmap.py
index 9b6b1b69..035736fd 100644
--- a/wqflask/wqflask/heatmap/heatmap.py
+++ b/wqflask/wqflask/heatmap/heatmap.py
@@ -1,317 +1,318 @@
-from __future__ import absolute_import, print_function, division
-
-import sys
-sys.path.append(".")
-
-import gc
-import string
-import cPickle
-import os
-import datetime
-import time
-import pp
-import math
-import collections
-import resource
-
-import scipy
-import numpy as np
-from scipy import linalg
-
-from pprint import pformat as pf
-
-from htmlgen import HTMLgen2 as HT
-import reaper
-
-from base.trait import GeneralTrait
-from base import data_set
-from base import species
-from base import webqtlConfig
-from utility import webqtlUtil
-from wqflask.my_pylmm.data import prep_data
-from wqflask.my_pylmm.pyLMM import lmm
-from wqflask.my_pylmm.pyLMM import input
-from utility import helper_functions
-from utility import Plot, Bunch
-from utility import temp_data
-
-from MySQLdb import escape_string as escape
-
-import cPickle as pickle
-import simplejson as json
-
-from pprint import pformat as pf
-
-from redis import Redis
-Redis = Redis()
-
-from flask import Flask, g
-
-class Heatmap(object):
-
- def __init__(self, start_vars, temp_uuid):
-
- trait_db_list = [trait.strip() for trait in start_vars['trait_list'].split(',')]
-
- helper_functions.get_trait_db_obs(self, trait_db_list)
-
- self.temp_uuid = temp_uuid
- self.num_permutations = 5000
- self.dataset = self.trait_list[0][1]
-
- self.json_data = {} #The dictionary that will be used to create the json object that contains all the data needed to create the figure
-
- self.all_sample_list = []
- self.traits = []
-
- chrnames = []
- self.species = species.TheSpecies(dataset=self.trait_list[0][1])
- for key in self.species.chromosomes.chromosomes.keys():
- chrnames.append([self.species.chromosomes.chromosomes[key].name, self.species.chromosomes.chromosomes[key].mb_length])
-
- for trait_db in self.trait_list:
-
- this_trait = trait_db[0]
- self.traits.append(this_trait.name)
- this_sample_data = this_trait.data
-
- for sample in this_sample_data:
- if sample not in self.all_sample_list:
- self.all_sample_list.append(sample)
-
- self.sample_data = []
- for trait_db in self.trait_list:
- this_trait = trait_db[0]
- this_sample_data = this_trait.data
-
- #self.sample_data[this_trait.name] = []
- this_trait_vals = []
- for sample in self.all_sample_list:
- if sample in this_sample_data:
- this_trait_vals.append(this_sample_data[sample].value)
- #self.sample_data[this_trait.name].append(this_sample_data[sample].value)
- else:
- this_trait_vals.append('')
- #self.sample_data[this_trait.name].append('')
- self.sample_data.append(this_trait_vals)
-
- self.gen_reaper_results()
- #self.gen_pylmm_results()
-
- #chrnames = []
- lodnames = []
- chr_pos = []
- pos = []
- markernames = []
-
- for trait in self.trait_results.keys():
- lodnames.append(trait)
-
- for marker in self.dataset.group.markers.markers:
- #if marker['chr'] not in chrnames:
- # chr_ob = [marker['chr'], "filler"]
- # chrnames.append(chr_ob)
- chr_pos.append(marker['chr'])
- pos.append(marker['Mb'])
- markernames.append(marker['name'])
-
- self.json_data['chrnames'] = chrnames
- self.json_data['lodnames'] = lodnames
- self.json_data['chr'] = chr_pos
- self.json_data['pos'] = pos
- self.json_data['markernames'] = markernames
-
- for trait in self.trait_results:
- self.json_data[trait] = self.trait_results[trait]
-
- self.js_data = dict(
- json_data = self.json_data
- )
-
- print("self.js_data:", self.js_data)
-
-
- def gen_reaper_results(self):
- self.trait_results = {}
- for trait_db in self.trait_list:
- self.dataset.group.get_markers()
- this_trait = trait_db[0]
- #this_db = trait_db[1]
- genotype = self.dataset.group.read_genotype_file()
- samples, values, variances = this_trait.export_informative()
-
- trimmed_samples = []
- trimmed_values = []
- for i in range(0, len(samples)):
- if samples[i] in self.dataset.group.samplelist:
- trimmed_samples.append(samples[i])
- trimmed_values.append(values[i])
-
- self.lrs_array = genotype.permutation(strains = trimmed_samples,
- trait = trimmed_values,
- nperm= self.num_permutations)
-
- #self.suggestive = self.lrs_array[int(self.num_permutations*0.37-1)]
- #self.significant = self.lrs_array[int(self.num_permutations*0.95-1)]
-
- reaper_results = genotype.regression(strains = trimmed_samples,
- trait = trimmed_values)
-
-
- lrs_values = [float(qtl.lrs) for qtl in reaper_results]
- print("lrs_values:", lrs_values)
- #self.dataset.group.markers.add_pvalues(p_values)
-
- self.trait_results[this_trait.name] = []
- for qtl in reaper_results:
- if qtl.additive > 0:
- self.trait_results[this_trait.name].append(-float(qtl.lrs))
- else:
- self.trait_results[this_trait.name].append(float(qtl.lrs))
- #for lrs in lrs_values:
- # if
- # self.trait_results[this_trait.name].append(lrs)
-
-
- #this_db_samples = self.dataset.group.samplelist
- #this_sample_data = this_trait.data
- ##print("this_sample_data", this_sample_data)
- #this_trait_vals = []
- #for index, sample in enumerate(this_db_samples):
- # if sample in this_sample_data:
- # sample_value = this_sample_data[sample].value
- # this_trait_vals.append(sample_value)
- # else:
- # this_trait_vals.append("x")
-
- #pheno_vector = np.array([val == "x" and np.nan or float(val) for val in this_trait_vals])
-
- #key = "pylmm:input:" + str(self.temp_uuid)
- #print("key is:", pf(key))
-
- #genotype_data = [marker['genotypes'] for marker in self.dataset.group.markers.markers]
-
- #no_val_samples = self.identify_empty_samples(this_trait_vals)
- #trimmed_genotype_data = self.trim_genotypes(genotype_data, no_val_samples)
-
- #genotype_matrix = np.array(trimmed_genotype_data).T
-
- #print("genotype_matrix:", str(genotype_matrix.tolist()))
- #print("pheno_vector:", str(pheno_vector.tolist()))
-
- #params = dict(pheno_vector = pheno_vector.tolist(),
- # genotype_matrix = genotype_matrix.tolist(),
- # restricted_max_likelihood = True,
- # refit = False,
- # temp_uuid = str(self.temp_uuid),
- #
- # # meta data
- # timestamp = datetime.datetime.now().isoformat(),
- # )
- #
- #json_params = json.dumps(params)
- ##print("json_params:", json_params)
- #Redis.set(key, json_params)
- #Redis.expire(key, 60*60)
- #print("before printing command")
- #
- #command = 'python /home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/lmm.py --key {} --species {}'.format(key,
- # "other")
- #print("command is:", command)
- #print("after printing command")
- #
- #os.system(command)
- #
- #json_results = Redis.blpop("pylmm:results:" + str(self.temp_uuid), 45*60)
-
- def gen_pylmm_results(self):
- self.trait_results = {}
- for trait_db in self.trait_list:
- this_trait = trait_db[0]
- #this_db = trait_db[1]
- self.dataset.group.get_markers()
-
- this_db_samples = self.dataset.group.samplelist
- this_sample_data = this_trait.data
- #print("this_sample_data", this_sample_data)
- this_trait_vals = []
- for index, sample in enumerate(this_db_samples):
- if sample in this_sample_data:
- sample_value = this_sample_data[sample].value
- this_trait_vals.append(sample_value)
- else:
- this_trait_vals.append("x")
-
- pheno_vector = np.array([val == "x" and np.nan or float(val) for val in this_trait_vals])
-
- key = "pylmm:input:" + str(self.temp_uuid)
- #print("key is:", pf(key))
-
- genotype_data = [marker['genotypes'] for marker in self.dataset.group.markers.markers]
-
- no_val_samples = self.identify_empty_samples(this_trait_vals)
- trimmed_genotype_data = self.trim_genotypes(genotype_data, no_val_samples)
-
- genotype_matrix = np.array(trimmed_genotype_data).T
-
- #print("genotype_matrix:", str(genotype_matrix.tolist()))
- #print("pheno_vector:", str(pheno_vector.tolist()))
-
- params = dict(pheno_vector = pheno_vector.tolist(),
- genotype_matrix = genotype_matrix.tolist(),
- restricted_max_likelihood = True,
- refit = False,
- temp_uuid = str(self.temp_uuid),
-
- # meta data
- timestamp = datetime.datetime.now().isoformat(),
- )
-
- json_params = json.dumps(params)
- #print("json_params:", json_params)
- Redis.set(key, json_params)
- Redis.expire(key, 60*60)
- print("before printing command")
-
- command = 'python /home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/lmm.py --key {} --species {}'.format(key,
- "other")
- print("command is:", command)
- print("after printing command")
-
- os.system(command)
-
- json_results = Redis.blpop("pylmm:results:" + str(self.temp_uuid), 45*60)
- results = json.loads(json_results[1])
- p_values = [float(result) for result in results['p_values']]
- #print("p_values:", p_values)
- self.dataset.group.markers.add_pvalues(p_values)
-
- self.trait_results[this_trait.name] = []
- for marker in self.dataset.group.markers.markers:
- self.trait_results[this_trait.name].append(marker['lod_score'])
-
-
- def identify_empty_samples(self, values):
- no_val_samples = []
- for sample_count, val in enumerate(values):
- if val == "x":
- no_val_samples.append(sample_count)
- return no_val_samples
-
- def trim_genotypes(self, genotype_data, no_value_samples):
- trimmed_genotype_data = []
- for marker in genotype_data:
- new_genotypes = []
- for item_count, genotype in enumerate(marker):
- if item_count in no_value_samples:
- continue
- try:
- genotype = float(genotype)
- except ValueError:
- genotype = np.nan
- pass
- new_genotypes.append(genotype)
- trimmed_genotype_data.append(new_genotypes)
- return trimmed_genotype_data
-
- \ No newline at end of file
+from __future__ import absolute_import, print_function, division
+
+import sys
+sys.path.append(".")
+
+import gc
+import string
+import cPickle
+import os
+import datetime
+import time
+import pp
+import math
+import collections
+import resource
+
+import scipy
+import numpy as np
+from scipy import linalg
+
+from pprint import pformat as pf
+
+from htmlgen import HTMLgen2 as HT
+import reaper
+
+from base.trait import GeneralTrait
+from base import data_set
+from base import species
+from base import webqtlConfig
+from utility import webqtlUtil
+from wqflask.my_pylmm.data import prep_data
+# from wqflask.my_pylmm.pyLMM import lmm
+# from wqflask.my_pylmm.pyLMM import input
+from utility import helper_functions
+from utility import Plot, Bunch
+from utility import temp_data
+
+from MySQLdb import escape_string as escape
+
+import cPickle as pickle
+import simplejson as json
+
+from pprint import pformat as pf
+
+from redis import Redis
+Redis = Redis()
+
+from flask import Flask, g
+
+class Heatmap(object):
+
+ def __init__(self, start_vars, temp_uuid):
+
+ trait_db_list = [trait.strip() for trait in start_vars['trait_list'].split(',')]
+
+ helper_functions.get_trait_db_obs(self, trait_db_list)
+
+ self.temp_uuid = temp_uuid
+ self.num_permutations = 5000
+ self.dataset = self.trait_list[0][1]
+
+ self.json_data = {} #The dictionary that will be used to create the json object that contains all the data needed to create the figure
+
+ self.all_sample_list = []
+ self.traits = []
+
+ chrnames = []
+ self.species = species.TheSpecies(dataset=self.trait_list[0][1])
+ for key in self.species.chromosomes.chromosomes.keys():
+ chrnames.append([self.species.chromosomes.chromosomes[key].name, self.species.chromosomes.chromosomes[key].mb_length])
+
+ for trait_db in self.trait_list:
+
+ this_trait = trait_db[0]
+ self.traits.append(this_trait.name)
+ this_sample_data = this_trait.data
+
+ for sample in this_sample_data:
+ if sample not in self.all_sample_list:
+ self.all_sample_list.append(sample)
+
+ self.sample_data = []
+ for trait_db in self.trait_list:
+ this_trait = trait_db[0]
+ this_sample_data = this_trait.data
+
+ #self.sample_data[this_trait.name] = []
+ this_trait_vals = []
+ for sample in self.all_sample_list:
+ if sample in this_sample_data:
+ this_trait_vals.append(this_sample_data[sample].value)
+ #self.sample_data[this_trait.name].append(this_sample_data[sample].value)
+ else:
+ this_trait_vals.append('')
+ #self.sample_data[this_trait.name].append('')
+ self.sample_data.append(this_trait_vals)
+
+ self.gen_reaper_results()
+ #self.gen_pylmm_results()
+
+ #chrnames = []
+ lodnames = []
+ chr_pos = []
+ pos = []
+ markernames = []
+
+ for trait in self.trait_results.keys():
+ lodnames.append(trait)
+
+ for marker in self.dataset.group.markers.markers:
+ #if marker['chr'] not in chrnames:
+ # chr_ob = [marker['chr'], "filler"]
+ # chrnames.append(chr_ob)
+ chr_pos.append(marker['chr'])
+ pos.append(marker['Mb'])
+ markernames.append(marker['name'])
+
+ self.json_data['chrnames'] = chrnames
+ self.json_data['lodnames'] = lodnames
+ self.json_data['chr'] = chr_pos
+ self.json_data['pos'] = pos
+ self.json_data['markernames'] = markernames
+
+ for trait in self.trait_results:
+ self.json_data[trait] = self.trait_results[trait]
+
+ self.js_data = dict(
+ json_data = self.json_data
+ )
+
+ print("self.js_data:", self.js_data)
+
+
+ def gen_reaper_results(self):
+ self.trait_results = {}
+ for trait_db in self.trait_list:
+ self.dataset.group.get_markers()
+ this_trait = trait_db[0]
+ #this_db = trait_db[1]
+ genotype = self.dataset.group.read_genotype_file()
+ samples, values, variances = this_trait.export_informative()
+
+ trimmed_samples = []
+ trimmed_values = []
+ for i in range(0, len(samples)):
+ if samples[i] in self.dataset.group.samplelist:
+ trimmed_samples.append(samples[i])
+ trimmed_values.append(values[i])
+
+ self.lrs_array = genotype.permutation(strains = trimmed_samples,
+ trait = trimmed_values,
+ nperm= self.num_permutations)
+
+ #self.suggestive = self.lrs_array[int(self.num_permutations*0.37-1)]
+ #self.significant = self.lrs_array[int(self.num_permutations*0.95-1)]
+
+ reaper_results = genotype.regression(strains = trimmed_samples,
+ trait = trimmed_values)
+
+
+ lrs_values = [float(qtl.lrs) for qtl in reaper_results]
+ print("lrs_values:", lrs_values)
+ #self.dataset.group.markers.add_pvalues(p_values)
+
+ self.trait_results[this_trait.name] = []
+ for qtl in reaper_results:
+ if qtl.additive > 0:
+ self.trait_results[this_trait.name].append(-float(qtl.lrs))
+ else:
+ self.trait_results[this_trait.name].append(float(qtl.lrs))
+ #for lrs in lrs_values:
+ # if
+ # self.trait_results[this_trait.name].append(lrs)
+
+
+ #this_db_samples = self.dataset.group.samplelist
+ #this_sample_data = this_trait.data
+ ##print("this_sample_data", this_sample_data)
+ #this_trait_vals = []
+ #for index, sample in enumerate(this_db_samples):
+ # if sample in this_sample_data:
+ # sample_value = this_sample_data[sample].value
+ # this_trait_vals.append(sample_value)
+ # else:
+ # this_trait_vals.append("x")
+
+ #pheno_vector = np.array([val == "x" and np.nan or float(val) for val in this_trait_vals])
+
+ #key = "pylmm:input:" + str(self.temp_uuid)
+ #print("key is:", pf(key))
+
+ #genotype_data = [marker['genotypes'] for marker in self.dataset.group.markers.markers]
+
+ #no_val_samples = self.identify_empty_samples(this_trait_vals)
+ #trimmed_genotype_data = self.trim_genotypes(genotype_data, no_val_samples)
+
+ #genotype_matrix = np.array(trimmed_genotype_data).T
+
+ #print("genotype_matrix:", str(genotype_matrix.tolist()))
+ #print("pheno_vector:", str(pheno_vector.tolist()))
+
+ #params = dict(pheno_vector = pheno_vector.tolist(),
+ # genotype_matrix = genotype_matrix.tolist(),
+ # restricted_max_likelihood = True,
+ # refit = False,
+ # temp_uuid = str(self.temp_uuid),
+ #
+ # # meta data
+ # timestamp = datetime.datetime.now().isoformat(),
+ # )
+ #
+ #json_params = json.dumps(params)
+ ##print("json_params:", json_params)
+ #Redis.set(key, json_params)
+ #Redis.expire(key, 60*60)
+ #print("before printing command")
+ #
+ #command = 'python /home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/lmm.py --key {} --species {}'.format(key,
+ # "other")
+ #print("command is:", command)
+ #print("after printing command")
+ #
+ #os.system(command)
+ #
+ #json_results = Redis.blpop("pylmm:results:" + str(self.temp_uuid), 45*60)
+
+ def gen_pylmm_results(self):
+ # This function is NOT used. If it is, we should use a shared function with marker_regression.py
+ self.trait_results = {}
+ for trait_db in self.trait_list:
+ this_trait = trait_db[0]
+ #this_db = trait_db[1]
+ self.dataset.group.get_markers()
+
+ this_db_samples = self.dataset.group.samplelist
+ this_sample_data = this_trait.data
+ #print("this_sample_data", this_sample_data)
+ this_trait_vals = []
+ for index, sample in enumerate(this_db_samples):
+ if sample in this_sample_data:
+ sample_value = this_sample_data[sample].value
+ this_trait_vals.append(sample_value)
+ else:
+ this_trait_vals.append("x")
+
+ pheno_vector = np.array([val == "x" and np.nan or float(val) for val in this_trait_vals])
+
+ key = "pylmm:input:" + str(self.temp_uuid)
+ #print("key is:", pf(key))
+
+ genotype_data = [marker['genotypes'] for marker in self.dataset.group.markers.markers]
+
+ no_val_samples = self.identify_empty_samples(this_trait_vals)
+ trimmed_genotype_data = self.trim_genotypes(genotype_data, no_val_samples)
+
+ genotype_matrix = np.array(trimmed_genotype_data).T
+
+ #print("genotype_matrix:", str(genotype_matrix.tolist()))
+ #print("pheno_vector:", str(pheno_vector.tolist()))
+
+ params = dict(pheno_vector = pheno_vector.tolist(),
+ genotype_matrix = genotype_matrix.tolist(),
+ restricted_max_likelihood = True,
+ refit = False,
+ temp_uuid = str(self.temp_uuid),
+
+ # meta data
+ timestamp = datetime.datetime.now().isoformat(),
+ )
+
+ json_params = json.dumps(params)
+ #print("json_params:", json_params)
+ Redis.set(key, json_params)
+ Redis.expire(key, 60*60)
+ print("before printing command")
+
+ command = 'python /home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/lmm.py --key {} --species {}'.format(key,
+ "other")
+ print("command is:", command)
+ print("after printing command")
+
+ os.system(command)
+
+ json_results = Redis.blpop("pylmm:results:" + str(self.temp_uuid), 45*60)
+ results = json.loads(json_results[1])
+ p_values = [float(result) for result in results['p_values']]
+ #print("p_values:", p_values)
+ self.dataset.group.markers.add_pvalues(p_values)
+
+ self.trait_results[this_trait.name] = []
+ for marker in self.dataset.group.markers.markers:
+ self.trait_results[this_trait.name].append(marker['lod_score'])
+
+
+ def identify_empty_samples(self, values):
+ no_val_samples = []
+ for sample_count, val in enumerate(values):
+ if val == "x":
+ no_val_samples.append(sample_count)
+ return no_val_samples
+
+ def trim_genotypes(self, genotype_data, no_value_samples):
+ trimmed_genotype_data = []
+ for marker in genotype_data:
+ new_genotypes = []
+ for item_count, genotype in enumerate(marker):
+ if item_count in no_value_samples:
+ continue
+ try:
+ genotype = float(genotype)
+ except ValueError:
+ genotype = np.nan
+ pass
+ new_genotypes.append(genotype)
+ trimmed_genotype_data.append(new_genotypes)
+ return trimmed_genotype_data
+
+
diff --git a/wqflask/wqflask/interval_mapping/interval_mapping.py b/wqflask/wqflask/interval_mapping/interval_mapping.py
index 5eb901f7..46aac86c 100755
--- a/wqflask/wqflask/interval_mapping/interval_mapping.py
+++ b/wqflask/wqflask/interval_mapping/interval_mapping.py
@@ -24,9 +24,6 @@ from base import data_set
from base import species
from base import webqtlConfig
from utility import webqtlUtil
-from wqflask.my_pylmm.data import prep_data
-from wqflask.my_pylmm.pyLMM import lmm
-from wqflask.my_pylmm.pyLMM import input
from utility import helper_functions
from utility import Plot, Bunch
from utility import temp_data
@@ -56,14 +53,12 @@ class IntervalMapping(object):
self.set_options(start_vars)
+ self.score_type = "LRS"
+ self.cutoff = 3
+
self.json_data = {}
-
- #if self.method == "qtl_reaper":
self.json_data['lodnames'] = ['lod.hk']
self.gen_reaper_results(tempdata)
- #else:
- # self.gen_pylmm_results(tempdata)
- #self.gen_qtl_results(tempdata)
#Get chromosome lengths for drawing the interval map plot
chromosome_mb_lengths = {}
@@ -73,48 +68,39 @@ class IntervalMapping(object):
chromosome_mb_lengths[key] = self.species.chromosomes.chromosomes[key].mb_length
- #print("self.qtl_results:", self.qtl_results)
-
print("JSON DATA:", self.json_data)
- #os.chdir(webqtlConfig.TMPDIR)
json_filename = webqtlUtil.genRandStr(prefix="intmap_")
json.dumps(self.json_data, webqtlConfig.TMPDIR + json_filename)
-
+
self.js_data = dict(
+ result_score_type = self.score_type,
manhattan_plot = self.manhattan_plot,
- additive = self.additive,
chromosomes = chromosome_mb_lengths,
qtl_results = self.qtl_results,
json_data = self.json_data
- #lrs_lod = self.lrs_lod,
)
def set_options(self, start_vars):
"""Sets various options (physical/genetic mapping, # permutations, which chromosome"""
- #self.plot_scale = start_vars['scale']
- #if self.plotScale == 'physic' and not fd.genotype.Mbmap:
- # self.plotScale = 'morgan'
- #self.method = start_vars['mapping_method']
- self.num_permutations = int(start_vars['num_perm'])
- #self.do_bootstrap = start_vars['do_bootstrap']
- #self.selected_chr = start_vars['chromosome']
+ if start_vars['num_perm'] == "":
+ self.num_permutations = 0
+ else:
+ self.num_permutations = int(start_vars['num_perm'])
if start_vars['manhattan_plot'] == "true":
self.manhattan_plot = True
else:
self.manhattan_plot = False
- if start_vars['display_additive'] == "yes":
- self.additive = True
- else:
- self.additive = False
+ #ZS: Commenting this out until we can fix the issue with positive/negative additive effects being colored properly
+ #if start_vars['display_additive'] == "yes":
+ # self.additive = True
+ #else:
+ self.additive = False
if 'control_locus' in start_vars:
self.control_locus = start_vars['control_locus']
else:
self.control_locus = None
- #self.weighted_regression = start_vars['weighted']
- #self.lrs_lod = start_vars['lrs_lod']
-
def gen_qtl_results(self, tempdata):
"""Generates qtl results for plotting interval map"""
@@ -134,7 +120,7 @@ class IntervalMapping(object):
#if self.weighted_regression:
# self.lrs_array = self.genotype.permutation(strains = trimmed_samples,
# trait = trimmed_values,
- # variance = _vars,
+ # variance = variances,
# nperm=self.num_permutations)
#else:
self.lrs_array = genotype.permutation(strains = trimmed_samples,
@@ -171,20 +157,14 @@ class IntervalMapping(object):
self.json_data['chr'] = []
self.json_data['pos'] = []
self.json_data['lod.hk'] = []
- self.json_data['additive'] = []
self.json_data['markernames'] = []
for qtl in reaper_results:
reaper_locus = qtl.locus
- #if reaper_locus.chr == "20":
- # print("changing to X")
- # self.json_data['chr'].append("X")
- #else:
- # self.json_data['chr'].append(reaper_locus.chr)
- ##self.json_data['chr'].append(reaper_locus.chr)
self.json_data['pos'].append(reaper_locus.Mb)
self.json_data['lod.hk'].append(qtl.lrs)
self.json_data['markernames'].append(reaper_locus.name)
if self.additive:
+ self.json_data['additive'] = []
self.json_data['additive'].append(qtl.additive)
locus = {"name":reaper_locus.name, "chr":reaper_locus.chr, "cM":reaper_locus.cM, "Mb":reaper_locus.Mb}
qtl = {"lrs": qtl.lrs, "locus": locus, "additive": qtl.additive}
@@ -225,8 +205,9 @@ class IntervalMapping(object):
self.json_data['chr'] = []
self.json_data['pos'] = []
self.json_data['lod.hk'] = []
- self.json_data['additive'] = []
self.json_data['markernames'] = []
+ if self.additive:
+ self.json_data['additive'] = []
#Need to convert the QTL objects that qtl reaper returns into a json serializable dictionary
self.qtl_results = []
@@ -240,65 +221,8 @@ class IntervalMapping(object):
self.json_data['additive'].append(qtl.additive)
locus = {"name":reaper_locus.name, "chr":reaper_locus.chr, "cM":reaper_locus.cM, "Mb":reaper_locus.Mb}
qtl = {"lrs_value": qtl.lrs, "chr":reaper_locus.chr, "Mb":reaper_locus.Mb,
- "cM":reaper_locus.cM, "name":reaper_locus.name, "additive":qtl.additive}
+ "cM":reaper_locus.cM, "name":reaper_locus.name, "additive":qtl.additive, "dominance":qtl.dominance}
self.qtl_results.append(qtl)
-
- def gen_pylmm_results(self, tempdata):
- print("USING PYLMM")
- self.dataset.group.get_markers()
-
- pheno_vector = np.array([val == "x" and np.nan or float(val) for val in self.vals])
- if self.dataset.group.species == "human":
- p_values, t_stats = self.gen_human_results(pheno_vector, tempdata)
- else:
- genotype_data = [marker['genotypes'] for marker in self.dataset.group.markers.markers]
-
- no_val_samples = self.identify_empty_samples()
- trimmed_genotype_data = self.trim_genotypes(genotype_data, no_val_samples)
-
- genotype_matrix = np.array(trimmed_genotype_data).T
-
- t_stats, p_values = lmm.run(
- pheno_vector,
- genotype_matrix,
- restricted_max_likelihood=True,
- refit=False,
- temp_data=tempdata
- )
-
- print("p_values:", p_values)
- self.dataset.group.markers.add_pvalues(p_values)
- self.qtl_results = self.dataset.group.markers.markers
-
- def gen_qtl_results_2(self, tempdata):
- """Generates qtl results for plotting interval map"""
-
- self.dataset.group.get_markers()
- self.dataset.read_genotype_file()
-
- pheno_vector = np.array([val == "x" and np.nan or float(val) for val in self.vals])
-
- #if self.dataset.group.species == "human":
- # p_values, t_stats = self.gen_human_results(pheno_vector, tempdata)
- #else:
- genotype_data = [marker['genotypes'] for marker in self.dataset.group.markers.markers]
-
- no_val_samples = self.identify_empty_samples()
- trimmed_genotype_data = self.trim_genotypes(genotype_data, no_val_samples)
-
- genotype_matrix = np.array(trimmed_genotype_data).T
-
- t_stats, p_values = lmm.run(
- pheno_vector,
- genotype_matrix,
- restricted_max_likelihood=True,
- refit=False,
- temp_data=tempdata
- )
-
- self.dataset.group.markers.add_pvalues(p_values)
-
- self.qtl_results = self.dataset.group.markers.markers
def identify_empty_samples(self):
diff --git a/wqflask/wqflask/marker_regression/gemma_mapping.py b/wqflask/wqflask/marker_regression/gemma_mapping.py
new file mode 100644
index 00000000..b1ab780c
--- /dev/null
+++ b/wqflask/wqflask/marker_regression/gemma_mapping.py
@@ -0,0 +1,44 @@
+import os
+
+from base import webqtlConfig
+
+def run_gemma(this_dataset, samples, vals):
+ """Generates p-values for each marker using GEMMA"""
+
+ print("INSIDE GEMMA_MAPPING")
+
+ gen_pheno_txt_file(this_dataset, samples, vals)
+
+ os.chdir("{}gemma".format(webqtlConfig.HTMLPATH))
+
+ gemma_command = './gemma -bfile %s -k output_%s.cXX.txt -lmm 1 -o output/%s_output' % (this_dataset.group.name,
+ this_dataset.group.name,
+ this_dataset.group.name)
+ print("gemma_command:" + gemma_command)
+
+ os.system(gemma_command)
+
+ included_markers, p_values = parse_gemma_output(this_dataset)
+
+ return included_markers, p_values
+
+def gen_pheno_txt_file(this_dataset, samples, vals):
+ """Generates phenotype file for GEMMA"""
+
+ with open("{}gemma/{}.fam".format(webqtlConfig.HTMLPATH, this_dataset.group.name), "w") as outfile:
+ for i, sample in enumerate(samples):
+ outfile.write(str(sample) + " " + str(sample) + " 0 0 0 " + str(vals[i]) + "\n")
+
+def parse_gemma_output(this_dataset):
+ included_markers = []
+ p_values = []
+ with open("{}gemma/output/{}_output.assoc.txt".format(webqtlConfig.HTMLPATH, this_dataset.group.name)) as output_file:
+ for line in output_file:
+ if line.startswith("chr"):
+ continue
+ else:
+ included_markers.append(line.split("\t")[1])
+ p_values.append(float(line.split("\t")[10]))
+
+ print("p_values: ", p_values)
+ return included_markers, p_values \ No newline at end of file
diff --git a/wqflask/wqflask/marker_regression/marker_regression.py b/wqflask/wqflask/marker_regression/marker_regression.py
index 7708356b..b33efc1f 100755
--- a/wqflask/wqflask/marker_regression/marker_regression.py
+++ b/wqflask/wqflask/marker_regression/marker_regression.py
@@ -31,15 +31,18 @@ from base import data_set
from base import species
from base import webqtlConfig
from utility import webqtlUtil
-from wqflask.my_pylmm.data import prep_data
-from wqflask.my_pylmm.pyLMM import lmm
-from wqflask.my_pylmm.pyLMM import input
+#from wqflask.marker_regression import qtl_reaper_mapping
+#from wqflask.marker_regression import plink_mapping
+from wqflask.marker_regression import gemma_mapping
+#from wqflask.marker_regression import rqtl_mapping
from utility import helper_functions
from utility import Plot, Bunch
from utility import temp_data
-
from utility.benchmark import Bench
+from utility.tools import pylmm_command, plink_command
+PYLMM_PATH,PYLMM_COMMAND = pylmm_command()
+PLINK_PATH,PLINK_COMMAND = plink_command()
class MarkerRegression(object):
@@ -70,97 +73,132 @@ class MarkerRegression(object):
self.suggestive = ""
self.significant = ""
self.pair_scan = False # Initializing this since it is checked in views to determine which template to use
+ self.score_type = "LRS" #ZS: LRS or LOD
self.dataset.group.get_markers()
if self.mapping_method == "gemma":
- qtl_results = self.run_gemma()
+ self.score_type = "LOD"
+ included_markers, p_values = gemma_mapping.run_gemma(self.dataset, self.samples, self.vals)
+ self.dataset.group.get_specified_markers(markers = included_markers)
+ self.dataset.group.markers.add_pvalues(p_values)
+ results = self.dataset.group.markers.markers
elif self.mapping_method == "rqtl_plink":
- qtl_results = self.run_rqtl_plink()
+ results = self.run_rqtl_plink()
elif self.mapping_method == "rqtl_geno":
+ self.score_type = "LOD"
if start_vars['num_perm'] == "":
self.num_perm = 0
else:
self.num_perm = start_vars['num_perm']
self.control = start_vars['control_marker']
+ self.do_control = start_vars['do_control']
print("StartVars:", start_vars)
self.method = start_vars['mapmethod_rqtl_geno']
self.model = start_vars['mapmodel_rqtl_geno']
if start_vars['pair_scan'] == "true":
self.pair_scan = True
- print("pair scan:", self.pair_scan)
- print("DOING RQTL GENO")
- qtl_results = self.run_rqtl_geno()
- print("qtl_results:", qtl_results)
+ results = self.run_rqtl_geno()
+ print("qtl_results:", results)
elif self.mapping_method == "plink":
- qtl_results = self.run_plink()
- #print("qtl_results:", pf(qtl_results))
+ results = self.run_plink()
+ #print("qtl_results:", pf(results))
elif self.mapping_method == "pylmm":
print("RUNNING PYLMM")
self.num_perm = start_vars['num_perm']
if self.num_perm != "":
if int(self.num_perm) > 0:
self.run_permutations(str(temp_uuid))
- qtl_results = self.gen_data(str(temp_uuid))
+ results = self.gen_data(str(temp_uuid))
else:
print("RUNNING NOTHING")
- self.lod_cutoff = 2
- self.filtered_markers = []
- highest_chr = 1 #This is needed in order to convert the highest chr to X/Y
- for marker in qtl_results:
- if marker['chr'] > 0 or marker['chr'] == "X" or marker['chr'] == "X/Y":
- if marker['chr'] > highest_chr or marker['chr'] == "X" or marker['chr'] == "X/Y":
- highest_chr = marker['chr']
- if 'lod_score' in marker:
- self.filtered_markers.append(marker)
-
- self.json_data['chr'] = []
- self.json_data['pos'] = []
- self.json_data['lod.hk'] = []
- self.json_data['markernames'] = []
-
- self.json_data['suggestive'] = self.suggestive
- self.json_data['significant'] = self.significant
-
- #Need to convert the QTL objects that qtl reaper returns into a json serializable dictionary
- self.qtl_results = []
- for qtl in self.filtered_markers:
- print("lod score is:", qtl['lod_score'])
- if qtl['chr'] == highest_chr and highest_chr != "X" and highest_chr != "X/Y":
- print("changing to X")
- self.json_data['chr'].append("X")
- else:
- self.json_data['chr'].append(str(qtl['chr']))
- self.json_data['pos'].append(qtl['Mb'])
- self.json_data['lod.hk'].append(str(qtl['lod_score']))
- self.json_data['markernames'].append(qtl['name'])
-
- #Get chromosome lengths for drawing the interval map plot
- chromosome_mb_lengths = {}
- self.json_data['chrnames'] = []
- for key in self.species.chromosomes.chromosomes.keys():
- self.json_data['chrnames'].append([self.species.chromosomes.chromosomes[key].name, self.species.chromosomes.chromosomes[key].mb_length])
- chromosome_mb_lengths[key] = self.species.chromosomes.chromosomes[key].mb_length
-
- print("json_data:", self.json_data)
-
-
- self.js_data = dict(
- json_data = self.json_data,
- this_trait = self.this_trait.name,
- data_set = self.dataset.name,
- maf = self.maf,
- manhattan_plot = self.manhattan_plot,
- chromosomes = chromosome_mb_lengths,
- qtl_results = self.filtered_markers,
- )
+ if self.pair_scan == True:
+ self.qtl_results = []
+ highest_chr = 1 #This is needed in order to convert the highest chr to X/Y
+ for marker in results:
+ if marker['chr1'] > 0 or marker['chr1'] == "X" or marker['chr1'] == "X/Y":
+ if marker['chr1'] > highest_chr or marker['chr1'] == "X" or marker['chr1'] == "X/Y":
+ highest_chr = marker['chr1']
+ if 'lod_score' in marker:
+ self.qtl_results.append(marker)
+
+ for qtl in enumerate(self.qtl_results):
+ self.json_data['chr1'].append(str(qtl['chr1']))
+ self.json_data['chr2'].append(str(qtl['chr2']))
+ self.json_data['Mb'].append(qtl['Mb'])
+ self.json_data['markernames'].append(qtl['name'])
+
+ self.js_data = dict(
+ json_data = self.json_data,
+ this_trait = self.this_trait.name,
+ data_set = self.dataset.name,
+ maf = self.maf,
+ manhattan_plot = self.manhattan_plot,
+ qtl_results = self.qtl_results,
+ )
+
+ else:
+ self.cutoff = 2
+ self.qtl_results = []
+ highest_chr = 1 #This is needed in order to convert the highest chr to X/Y
+ for marker in results:
+ if marker['chr'] > 0 or marker['chr'] == "X" or marker['chr'] == "X/Y":
+ if marker['chr'] > highest_chr or marker['chr'] == "X" or marker['chr'] == "X/Y":
+ highest_chr = marker['chr']
+ if 'lod_score' in marker:
+ self.qtl_results.append(marker)
+
+ self.json_data['chr'] = []
+ self.json_data['pos'] = []
+ self.json_data['lod.hk'] = []
+ self.json_data['markernames'] = []
+
+ self.json_data['suggestive'] = self.suggestive
+ self.json_data['significant'] = self.significant
+
+ #Need to convert the QTL objects that qtl reaper returns into a json serializable dictionary
+ for index, qtl in enumerate(self.qtl_results):
+ if index<40:
+ print("lod score is:", qtl['lod_score'])
+ if qtl['chr'] == highest_chr and highest_chr != "X" and highest_chr != "X/Y":
+ print("changing to X")
+ self.json_data['chr'].append("X")
+ else:
+ self.json_data['chr'].append(str(qtl['chr']))
+ self.json_data['pos'].append(qtl['Mb'])
+ if 'lrs_value' in qtl:
+ self.json_data['lod.hk'].append(str(qtl['lrs_value']))
+ else:
+ self.json_data['lod.hk'].append(str(qtl['lod_score']))
+ self.json_data['markernames'].append(qtl['name'])
+
+ #Get chromosome lengths for drawing the interval map plot
+ chromosome_mb_lengths = {}
+ self.json_data['chrnames'] = []
+ for key in self.species.chromosomes.chromosomes.keys():
+ self.json_data['chrnames'].append([self.species.chromosomes.chromosomes[key].name, self.species.chromosomes.chromosomes[key].mb_length])
+ chromosome_mb_lengths[key] = self.species.chromosomes.chromosomes[key].mb_length
+
+ # print("json_data:", self.json_data)
+
+
+ self.js_data = dict(
+ result_score_type = self.score_type,
+ json_data = self.json_data,
+ this_trait = self.this_trait.name,
+ data_set = self.dataset.name,
+ maf = self.maf,
+ manhattan_plot = self.manhattan_plot,
+ chromosomes = chromosome_mb_lengths,
+ qtl_results = self.qtl_results,
+ )
+
def run_gemma(self):
"""Generates p-values for each marker using GEMMA"""
- #filename = webqtlUtil.genRandStr("{}_{}_".format(self.dataset.group.name, self.this_trait.name))
self.gen_pheno_txt_file()
os.chdir("/home/zas1024/gene/web/gemma")
@@ -272,7 +310,7 @@ class MarkerRegression(object):
""")
def run_rqtl_geno(self):
- print("Calling R/qtl from python")
+ print("Calling R/qtl")
self.geno_to_rqtl_function()
@@ -315,7 +353,7 @@ class MarkerRegression(object):
covar = self.create_covariates(cross_object) # Create the additive covariate matrix
if self.pair_scan:
- if(r_sum(covar)[0] > 0): # If sum(covar) > 0 we have a covariate matrix
+ if self.do_control == "true": # If sum(covar) > 0 we have a covariate matrix
print("Using covariate"); result_data_frame = scantwo(cross_object, pheno = "the_pheno", addcovar = covar, model=self.model, method=self.method, n_cluster = 16)
else:
print("No covariates"); result_data_frame = scantwo(cross_object, pheno = "the_pheno", model=self.model, method=self.method, n_cluster = 16)
@@ -330,13 +368,13 @@ class MarkerRegression(object):
return self.process_pair_scan_results(result_data_frame)
else:
- if(r_sum(covar)[0] > 0):
+ if self.do_control == "true":
print("Using covariate"); result_data_frame = scanone(cross_object, pheno = "the_pheno", addcovar = covar, model=self.model, method=self.method)
else:
print("No covariates"); result_data_frame = scanone(cross_object, pheno = "the_pheno", model=self.model, method=self.method)
if int(self.num_perm) > 0: # Do permutation (if requested by user)
- if(r_sum(covar)[0] > 0):
+ if self.do_control == "true":
perm_data_frame = scanone(cross_object, pheno_col = "the_pheno", addcovar = covar, n_perm = int(self.num_perm), model=self.model, method=self.method)
else:
perm_data_frame = scanone(cross_object, pheno_col = "the_pheno", n_perm = int(self.num_perm), model=self.model, method=self.method)
@@ -381,9 +419,23 @@ class MarkerRegression(object):
return pheno_as_string
def process_pair_scan_results(self, result):
- results = []
+ pair_scan_results = []
- return results
+ result = result[1]
+ output = [tuple([result[j][i] for j in range(result.ncol)]) for i in range(result.nrow)]
+ print("R/qtl scantwo output:", output)
+
+ for i, line in enumerate(result.iter_row()):
+ marker = {}
+ marker['name'] = result.rownames[i]
+ marker['chr1'] = output[i][0]
+ marker['Mb'] = output[i][1]
+ marker['chr2'] = int(output[i][2])
+ pair_scan_results.append(marker)
+
+ print("pair_scan_results:", pair_scan_results)
+
+ return pair_scan_results
def process_rqtl_results(self, result): # TODO: how to make this a one liner and not copy the stuff in a loop
qtl_results = []
@@ -414,29 +466,16 @@ class MarkerRegression(object):
def run_plink(self):
-
- os.chdir("/home/zas1024/plink")
-
plink_output_filename = webqtlUtil.genRandStr("%s_%s_"%(self.dataset.group.name, self.this_trait.name))
self.gen_pheno_txt_file_plink(pheno_filename = plink_output_filename)
- plink_command = './plink --noweb --ped %s.ped --no-fid --no-parents --no-sex --no-pheno --map %s.map --pheno %s/%s.txt --pheno-name %s --maf %s --missing-phenotype -9999 --out %s%s --assoc ' % (self.dataset.group.name, self.dataset.group.name, webqtlConfig.TMPDIR, plink_output_filename, self.this_trait.name, self.maf, webqtlConfig.TMPDIR, plink_output_filename)
-
+ plink_command = PLINK_COMMAND + ' --noweb --ped %s/%s.ped --no-fid --no-parents --no-sex --no-pheno --map %s/%s.map --pheno %s%s.txt --pheno-name %s --maf %s --missing-phenotype -9999 --out %s%s --assoc ' % (PLINK_PATH, self.dataset.group.name, PLINK_PATH, self.dataset.group.name, webqtlConfig.TMPDIR, plink_output_filename, self.this_trait.name, self.maf, webqtlConfig.TMPDIR, plink_output_filename)
+ print("plink_command:", plink_command)
+
os.system(plink_command)
count, p_values = self.parse_plink_output(plink_output_filename)
- #gemma_command = './gemma -bfile %s -k output_%s.cXX.txt -lmm 1 -o %s_output' % (
- # self.dataset.group.name,
- # self.dataset.group.name,
- # self.dataset.group.name)
- #print("gemma_command:" + gemma_command)
- #
- #os.system(gemma_command)
- #
- #included_markers, p_values = self.parse_gemma_output()
- #
- #self.dataset.group.get_specified_markers(markers = included_markers)
#for marker in self.dataset.group.markers.markers:
# if marker['name'] not in included_markers:
@@ -523,10 +562,7 @@ class MarkerRegression(object):
# get strain name from ped file in order
def get_samples_from_ped_file(self):
-
- os.chdir("/home/zas1024/plink")
-
- ped_file= open("{}.ped".format(self.dataset.group.name),"r")
+ ped_file= open("{}/{}.ped".format(PLINK_PATH, self.dataset.group.name),"r")
line = ped_file.readline()
sample_list=[]
@@ -655,8 +691,7 @@ class MarkerRegression(object):
Redis.set(key, json_params)
Redis.expire(key, 60*60)
- command = 'python /home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/lmm.py --key {} --species {}'.format(key,
- "other")
+ command = PYLMM_COMMAND+' --key {} --species {}'.format(key,"other")
os.system(command)
@@ -713,8 +748,8 @@ class MarkerRegression(object):
# "refit": False,
# "temp_data": tempdata}
- print("genotype_matrix:", str(genotype_matrix.tolist()))
- print("pheno_vector:", str(pheno_vector.tolist()))
+ # print("genotype_matrix:", str(genotype_matrix.tolist()))
+ # print("pheno_vector:", str(pheno_vector.tolist()))
params = dict(pheno_vector = pheno_vector.tolist(),
genotype_matrix = genotype_matrix.tolist(),
@@ -732,7 +767,7 @@ class MarkerRegression(object):
Redis.expire(key, 60*60)
print("before printing command")
- command = 'python /home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/lmm.py --key {} --species {}'.format(key,
+ command = PYLMM_COMMAND + ' --key {} --species {}'.format(key,
"other")
print("command is:", command)
print("after printing command")
@@ -745,7 +780,7 @@ class MarkerRegression(object):
json_results = Redis.blpop("pylmm:results:" + temp_uuid, 45*60)
results = json.loads(json_results[1])
p_values = [float(result) for result in results['p_values']]
- print("p_values:", p_values)
+ print("p_values:", p_values[:10])
#p_values = self.trim_results(p_values)
t_stats = results['t_stats']
@@ -806,7 +841,7 @@ class MarkerRegression(object):
print("Before creating the command")
- command = 'python /home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/lmm.py --key {} --species {}'.format(key,
+ command = PYLMM_COMMAND+' --key {} --species {}'.format(key,
"human")
print("command is:", command)
diff --git a/wqflask/wqflask/marker_regression/marker_regression_old.py b/wqflask/wqflask/marker_regression/marker_regression_old.py
deleted file mode 100644
index 36331250..00000000
--- a/wqflask/wqflask/marker_regression/marker_regression_old.py
+++ /dev/null
@@ -1,576 +0,0 @@
-from __future__ import absolute_import, print_function, division
-
-from base.trait import GeneralTrait
-from base import data_set #import create_dataset
-
-from pprint import pformat as pf
-
-import string
-import sys
-import datetime
-import os
-import collections
-import uuid
-
-import numpy as np
-from scipy import linalg
-
-import cPickle as pickle
-
-import simplejson as json
-
-from redis import Redis
-Redis = Redis()
-
-from flask import Flask, g
-
-from base.trait import GeneralTrait
-from base import data_set
-from base import species
-from base import webqtlConfig
-from utility import webqtlUtil
-from wqflask.my_pylmm.data import prep_data
-from wqflask.my_pylmm.pyLMM import lmm
-from wqflask.my_pylmm.pyLMM import input
-from utility import helper_functions
-from utility import Plot, Bunch
-from utility import temp_data
-
-from utility.benchmark import Bench
-
-
-class MarkerRegression(object):
-
- def __init__(self, start_vars, temp_uuid):
-
- helper_functions.get_species_dataset_trait(self, start_vars)
-
- #tempdata = temp_data.TempData(temp_uuid)
-
- self.samples = [] # Want only ones with values
- self.vals = []
-
- for sample in self.dataset.group.samplelist:
- value = start_vars['value:' + sample]
- self.samples.append(str(sample))
- self.vals.append(value)
-
- self.mapping_method = start_vars['method']
- self.maf = start_vars['maf'] # Minor allele frequency
- print("self.maf:", self.maf)
-
- self.dataset.group.get_markers()
- if self.mapping_method == "gemma":
- qtl_results = self.run_gemma()
- elif self.mapping_method == "plink":
- qtl_results = self.run_plink()
- #print("qtl_results:", pf(qtl_results))
- elif self.mapping_method == "pylmm":
- print("RUNNING PYLMM")
- #self.qtl_results = self.gen_data(tempdata)
- qtl_results = self.gen_data(str(temp_uuid))
- else:
- print("RUNNING NOTHING")
-
- self.lod_cutoff = 2
- self.filtered_markers = []
- for marker in qtl_results:
- if marker['chr'] > 0:
- self.filtered_markers.append(marker)
-
- #Get chromosome lengths for drawing the manhattan plot
- chromosome_mb_lengths = {}
- for key in self.species.chromosomes.chromosomes.keys():
- chromosome_mb_lengths[key] = self.species.chromosomes.chromosomes[key].mb_length
-
- self.js_data = dict(
- this_trait = self.this_trait.name,
- data_set = self.dataset.name,
- maf = self.maf,
- chromosomes = chromosome_mb_lengths,
- qtl_results = self.filtered_markers,
- )
-
- def run_gemma(self):
- """Generates p-values for each marker using GEMMA"""
-
- #filename = webqtlUtil.genRandStr("{}_{}_".format(self.dataset.group.name, self.this_trait.name))
- self.gen_pheno_txt_file()
-
- os.chdir("/home/zas1024/gene/web/gemma")
-
- gemma_command = './gemma -bfile %s -k output_%s.cXX.txt -lmm 1 -o %s_output' % (
- self.dataset.group.name,
- self.dataset.group.name,
- self.dataset.group.name)
- print("gemma_command:" + gemma_command)
-
- os.system(gemma_command)
-
- included_markers, p_values = self.parse_gemma_output()
-
- self.dataset.group.get_specified_markers(markers = included_markers)
-
- #for marker in self.dataset.group.markers.markers:
- # if marker['name'] not in included_markers:
- # print("marker:", marker)
- # self.dataset.group.markers.markers.remove(marker)
- # #del self.dataset.group.markers.markers[marker]
-
- self.dataset.group.markers.add_pvalues(p_values)
-
- return self.dataset.group.markers.markers
-
-
- def parse_gemma_output(self):
- included_markers = []
- p_values = []
- with open("/home/zas1024/gene/web/gemma/output/{}_output.assoc.txt".format(self.dataset.group.name)) as output_file:
- for line in output_file:
- if line.startswith("chr"):
- continue
- else:
- included_markers.append(line.split("\t")[1])
- p_values.append(float(line.split("\t")[10]))
- #p_values[line.split("\t")[1]] = float(line.split("\t")[10])
- print("p_values: ", p_values)
- return included_markers, p_values
-
- def gen_pheno_txt_file(self):
- """Generates phenotype file for GEMMA"""
-
- #with open("/home/zas1024/gene/web/gemma/tmp_pheno/{}.txt".format(filename), "w") as outfile:
- # for sample, i in enumerate(self.samples):
- # print("sample:" + str(i))
- # print("self.vals[i]:" + str(self.vals[sample]))
- # outfile.write(str(i) + "\t" + str(self.vals[sample]) + "\n")
-
- with open("/home/zas1024/gene/web/gemma/{}.fam".format(self.dataset.group.name), "w") as outfile:
- for i, sample in enumerate(self.samples):
- outfile.write(str(sample) + " " + str(sample) + " 0 0 0 " + str(self.vals[i]) + "\n")
-
- #def gen_plink_for_gemma(self, filename):
- #
- # make_bed = "/home/zas1024/plink/plink --file /home/zas1024/plink/%s --noweb --no-fid --no-parents --no-sex --no-pheno --pheno %s%s.txt --out %s%s --make-bed" % (webqtlConfig.HTMLPATH,
- # webqtlConfig.HTMLPATH,
- # self.dataset.group.name,
- # webqtlConfig.TMPDIR,
- # filename,
- # webqtlConfig.TMPDIR,
- # filename)
- #
- #
-
- def run_plink(self):
-
- os.chdir("/home/zas1024/plink")
-
- plink_output_filename = webqtlUtil.genRandStr("%s_%s_"%(self.dataset.group.name, self.this_trait.name))
-
- self.gen_pheno_txt_file_plink(pheno_filename = plink_output_filename)
-
- plink_command = './plink --noweb --ped %s.ped --no-fid --no-parents --no-sex --no-pheno --map %s.map --pheno %s/%s.txt --pheno-name %s --maf %s --missing-phenotype -9999 --out %s%s --assoc ' % (self.dataset.group.name, self.dataset.group.name, webqtlConfig.TMPDIR, plink_output_filename, self.this_trait.name, self.maf, webqtlConfig.TMPDIR, plink_output_filename)
-
- os.system(plink_command)
-
- count, p_values = self.parse_plink_output(plink_output_filename)
- #gemma_command = './gemma -bfile %s -k output_%s.cXX.txt -lmm 1 -o %s_output' % (
- # self.dataset.group.name,
- # self.dataset.group.name,
- # self.dataset.group.name)
- #print("gemma_command:" + gemma_command)
- #
- #os.system(gemma_command)
- #
- #included_markers, p_values = self.parse_gemma_output()
- #
- #self.dataset.group.get_specified_markers(markers = included_markers)
-
- #for marker in self.dataset.group.markers.markers:
- # if marker['name'] not in included_markers:
- # print("marker:", marker)
- # self.dataset.group.markers.markers.remove(marker)
- # #del self.dataset.group.markers.markers[marker]
-
- print("p_values:", pf(p_values))
-
- self.dataset.group.markers.add_pvalues(p_values)
-
- return self.dataset.group.markers.markers
-
-
- def gen_pheno_txt_file_plink(self, pheno_filename = ''):
- ped_sample_list = self.get_samples_from_ped_file()
- output_file = open("%s%s.txt" % (webqtlConfig.TMPDIR, pheno_filename), "wb")
- header = 'FID\tIID\t%s\n' % self.this_trait.name
- output_file.write(header)
-
- new_value_list = []
-
- #if valueDict does not include some strain, value will be set to -9999 as missing value
- for i, sample in enumerate(ped_sample_list):
- try:
- value = self.vals[i]
- value = str(value).replace('value=','')
- value = value.strip()
- except:
- value = -9999
-
- new_value_list.append(value)
-
-
- new_line = ''
- for i, sample in enumerate(ped_sample_list):
- j = i+1
- value = new_value_list[i]
- new_line += '%s\t%s\t%s\n'%(sample, sample, value)
-
- if j%1000 == 0:
- output_file.write(newLine)
- new_line = ''
-
- if new_line:
- output_file.write(new_line)
-
- output_file.close()
-
- # get strain name from ped file in order
- def get_samples_from_ped_file(self):
-
- os.chdir("/home/zas1024/plink")
-
- ped_file= open("{}.ped".format(self.dataset.group.name),"r")
- line = ped_file.readline()
- sample_list=[]
-
- while line:
- lineList = string.split(string.strip(line), '\t')
- lineList = map(string.strip, lineList)
-
- sample_name = lineList[0]
- sample_list.append(sample_name)
-
- line = ped_file.readline()
-
- return sample_list
-
- ################################################################
- # Generate Chr list, Chr OrderId and Retrieve Length Information
- ################################################################
- #def getChrNameOrderIdLength(self,RISet=''):
- # try:
- # query = """
- # Select
- # Chr_Length.Name,Chr_Length.OrderId,Length from Chr_Length, InbredSet
- # where
- # Chr_Length.SpeciesId = InbredSet.SpeciesId AND
- # InbredSet.Name = '%s'
- # Order by OrderId
- # """ % (self.dataset.group.name)
- # results =g.db.execute(query).fetchall()
- # ChrList=[]
- # ChrLengthMbList=[]
- # ChrNameOrderIdDict={}
- # ChrOrderIdNameDict={}
- #
- # for item in results:
- # ChrList.append(item[0])
- # ChrNameOrderIdDict[item[0]]=item[1] # key is chr name, value is orderId
- # ChrOrderIdNameDict[item[1]]=item[0] # key is orderId, value is chr name
- # ChrLengthMbList.append(item[2])
- #
- # except:
- # ChrList=[]
- # ChrNameOrderIdDict={}
- # ChrLengthMbList=[]
- #
- # return ChrList,ChrNameOrderIdDict,ChrOrderIdNameDict,ChrLengthMbList
-
-
- def parse_plink_output(self, output_filename):
- plink_results={}
-
- threshold_p_value = 0.01
-
- result_fp = open("%s%s.qassoc"% (webqtlConfig.TMPDIR, output_filename), "rb")
-
- header_line = result_fp.readline()# read header line
- line = result_fp.readline()
-
- value_list = [] # initialize value list, this list will include snp, bp and pvalue info
- p_value_dict = {}
- count = 0
-
- while line:
- #convert line from str to list
- line_list = self.build_line_list(line=line)
-
- # only keep the records whose chromosome name is in db
- if self.species.chromosomes.chromosomes.has_key(int(line_list[0])) and line_list[-1] and line_list[-1].strip()!='NA':
-
- chr_name = self.species.chromosomes.chromosomes[int(line_list[0])]
- snp = line_list[1]
- BP = line_list[2]
- p_value = float(line_list[-1])
- if threshold_p_value >= 0 and threshold_p_value <= 1:
- if p_value < threshold_p_value:
- p_value_dict[snp] = p_value
-
- if plink_results.has_key(chr_name):
- value_list = plink_results[chr_name]
-
- # pvalue range is [0,1]
- if threshold_p_value >=0 and threshold_p_value <= 1:
- if p_value < threshold_p_value:
- value_list.append((snp, BP, p_value))
- count += 1
-
- plink_results[chr_name] = value_list
- value_list = []
- else:
- if threshold_p_value >= 0 and threshold_p_value <= 1:
- if p_value < threshold_p_value:
- value_list.append((snp, BP, p_value))
- count += 1
-
- if value_list:
- plink_results[chr_name] = value_list
-
- value_list=[]
-
- line = result_fp.readline()
- else:
- line = result_fp.readline()
-
- #if p_value_list:
- # min_p_value = min(p_value_list)
- #else:
- # min_p_value = 0
-
- return count, p_value_dict
-
- ######################################################
- # input: line: str,one line read from file
- # function: convert line from str to list;
- # output: lineList list
- #######################################################
- def build_line_list(self, line=None):
-
- line_list = string.split(string.strip(line),' ')# irregular number of whitespaces between columns
- line_list = [item for item in line_list if item <>'']
- line_list = map(string.strip, line_list)
-
- return line_list
-
- #def gen_data(self, tempdata):
- def gen_data(self, temp_uuid):
- """Generates p-values for each marker"""
-
- pheno_vector = np.array([val == "x" and np.nan or float(val) for val in self.vals])
-
- #lmm_uuid = str(uuid.uuid4())
-
- key = "pylmm:input:" + temp_uuid
- print("key is:", pf(key))
- #with Bench("Loading cache"):
- # result = Redis.get(key)
-
- if self.dataset.group.species == "human":
- p_values, t_stats = self.gen_human_results(pheno_vector, key, temp_uuid)
- #p_values = self.trim_results(p_values)
-
- else:
- print("NOW CWD IS:", os.getcwd())
- genotype_data = [marker['genotypes'] for marker in self.dataset.group.markers.markers]
-
- no_val_samples = self.identify_empty_samples()
- trimmed_genotype_data = self.trim_genotypes(genotype_data, no_val_samples)
-
- genotype_matrix = np.array(trimmed_genotype_data).T
-
- #print("pheno_vector: ", pf(pheno_vector))
- #print("genotype_matrix: ", pf(genotype_matrix))
- #print("genotype_matrix.shape: ", pf(genotype_matrix.shape))
-
- #params = {"pheno_vector": pheno_vector,
- # "genotype_matrix": genotype_matrix,
- # "restricted_max_likelihood": True,
- # "refit": False,
- # "temp_data": tempdata}
-
- params = dict(pheno_vector = pheno_vector.tolist(),
- genotype_matrix = genotype_matrix.tolist(),
- restricted_max_likelihood = True,
- refit = False,
- temp_uuid = temp_uuid,
-
- # meta data
- timestamp = datetime.datetime.now().isoformat(),
- )
-
- json_params = json.dumps(params)
- #print("json_params:", json_params)
- Redis.set(key, json_params)
- Redis.expire(key, 60*60)
- print("before printing command")
-
- command = 'python /home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/lmm.py --key {} --species {}'.format(key,
- "other")
- print("command is:", command)
- print("after printing command")
-
- os.system(command)
-
- #t_stats, p_values = lmm.run(key)
- #lmm.run(key)
-
- json_results = Redis.blpop("pylmm:results:" + temp_uuid, 45*60)
- results = json.loads(json_results[1])
- p_values = [float(result) for result in results['p_values']]
- print("p_values:", p_values)
- #p_values = self.trim_results(p_values)
- t_stats = results['t_stats']
-
- #t_stats, p_values = lmm.run(
- # pheno_vector,
- # genotype_matrix,
- # restricted_max_likelihood=True,
- # refit=False,
- # temp_data=tempdata
- #)
- #print("p_values:", p_values)
-
- self.dataset.group.markers.add_pvalues(p_values)
-
- #self.get_lod_score_cutoff()
-
- return self.dataset.group.markers.markers
-
- def trim_results(self, p_values):
- print("len_p_values:", len(p_values))
- if len(p_values) > 500:
- p_values.sort(reverse=True)
- trimmed_values = p_values[:500]
-
- return trimmed_values
-
- #def gen_human_results(self, pheno_vector, tempdata):
- def gen_human_results(self, pheno_vector, key, temp_uuid):
- file_base = os.path.join(webqtlConfig.PYLMM_PATH, self.dataset.group.name)
-
- plink_input = input.plink(file_base, type='b')
- input_file_name = os.path.join(webqtlConfig.SNP_PATH, self.dataset.group.name + ".snps.gz")
-
- pheno_vector = pheno_vector.reshape((len(pheno_vector), 1))
- covariate_matrix = np.ones((pheno_vector.shape[0],1))
- kinship_matrix = np.fromfile(open(file_base + '.kin','r'),sep=" ")
- kinship_matrix.resize((len(plink_input.indivs),len(plink_input.indivs)))
-
- print("Before creating params")
-
- params = dict(pheno_vector = pheno_vector.tolist(),
- covariate_matrix = covariate_matrix.tolist(),
- input_file_name = input_file_name,
- kinship_matrix = kinship_matrix.tolist(),
- refit = False,
- temp_uuid = temp_uuid,
-
- # meta data
- timestamp = datetime.datetime.now().isoformat(),
- )
-
- print("After creating params")
-
- json_params = json.dumps(params)
- Redis.set(key, json_params)
- Redis.expire(key, 60*60)
-
- print("Before creating the command")
-
- command = 'python /home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/lmm.py --key {} --species {}'.format(key,
- "human")
-
- print("command is:", command)
-
- os.system(command)
-
- json_results = Redis.blpop("pylmm:results:" + temp_uuid, 45*60)
- results = json.loads(json_results[1])
- t_stats = results['t_stats']
- p_values = results['p_values']
-
-
- #p_values, t_stats = lmm.run_human(key)
-
- #p_values, t_stats = lmm.run_human(
- # pheno_vector,
- # covariate_matrix,
- # input_file_name,
- # kinship_matrix,
- # loading_progress=tempdata
- # )
-
- return p_values, t_stats
-
- def get_lod_score_cutoff(self):
- print("INSIDE GET LOD CUTOFF")
- high_qtl_count = 0
- for marker in self.dataset.group.markers.markers:
- if marker['lod_score'] > 1:
- high_qtl_count += 1
-
- if high_qtl_count > 1000:
- return 1
- else:
- return 0
-
- def identify_empty_samples(self):
- no_val_samples = []
- for sample_count, val in enumerate(self.vals):
- if val == "x":
- no_val_samples.append(sample_count)
- return no_val_samples
-
- def trim_genotypes(self, genotype_data, no_value_samples):
- trimmed_genotype_data = []
- for marker in genotype_data:
- new_genotypes = []
- for item_count, genotype in enumerate(marker):
- if item_count in no_value_samples:
- continue
- try:
- genotype = float(genotype)
- except ValueError:
- genotype = np.nan
- pass
- new_genotypes.append(genotype)
- trimmed_genotype_data.append(new_genotypes)
- return trimmed_genotype_data
-
-def create_snp_iterator_file(group):
- plink_file_base = os.path.join(webqtlConfig.PYLMM_PATH, group)
- plink_input = input.plink(plink_file_base, type='b')
-
- data = dict(plink_input = list(plink_input),
- numSNPs = plink_input.numSNPs)
-
- #input_dict = {}
- #
- #input_dict['plink_input'] = list(plink_input)
- #input_dict['numSNPs'] = plink_input.numSNPs
- #
-
- snp_file_base = os.path.join(webqtlConfig.SNP_PATH, group + ".snps.gz")
-
- with gzip.open(snp_file_base, "wb") as fh:
- pickle.dump(data, fh, pickle.HIGHEST_PROTOCOL)
-
-#if __name__ == '__main__':
-# import cPickle as pickle
-# import gzip
-# create_snp_iterator_file("HLC")
-
-if __name__ == '__main__':
- import cPickle as pickle
- import gzip
- create_snp_iterator_file("HLC")
diff --git a/wqflask/wqflask/model.py b/wqflask/wqflask/model.py
index fa8c1aab..5ea32e1f 100755
--- a/wqflask/wqflask/model.py
+++ b/wqflask/wqflask/model.py
@@ -172,8 +172,11 @@ class UserCollection(Base):
@property
def num_members(self):
- print("members are:", json.loads(self.members))
- return len(json.loads(self.members))
+ try:
+ return len(json.loads(self.members))
+ except:
+ return 0
+
#@property
#def display_num_members(self):
@@ -194,4 +197,4 @@ def display_collapsible(number):
def user_uuid():
"""Unique cookie for a user"""
user_uuid = request.cookies.get('user_uuid')
- \ No newline at end of file
+
diff --git a/wqflask/wqflask/my_pylmm/README.md b/wqflask/wqflask/my_pylmm/README.md
index f6b0e72d..b844c845 100644
--- a/wqflask/wqflask/my_pylmm/README.md
+++ b/wqflask/wqflask/my_pylmm/README.md
@@ -1,21 +1,37 @@
-# RELEASE NOTES
-
-## 0.50-gn2-pre1 release
-
-This is the first test release of multi-core pylmm into GN2. Both
-kinship calculation and GWAS have been made multi-threaded by
-introducing the Python multiprocessing module. Note that only
-run_other has been updated to use the new routines (so human is still
-handled the old way). I have taken care that we can still run both
-old-style and new-style LMM (through passing the 'new_code'
-boolean). This could be an option in the web server for users to
-select and test for any unexpected differences (of which there should
-be none, naturally ;).
-
-The current version can handle missing phenotypes, but as they are
-removed there is no way for GN2 to know what SNPs the P-values belong
-to. A future version will pass a SNP index to allow for missing
-phenotypes.
+# Genenetwork2/pylmm RELEASE NOTES
+
+## 0.51-gn2 (April 19, 2015)
+
+- Improved GN2 integration
+- Less matrix transposes
+- Able to run pylmm standalone without Redis again (still requires
+ the modules)
+
+## 0.50-gn2 (April 2nd, 2015)
+
+- Replaced the GN2 genotype normalization
+
+## 0.50-gn2-pre2 (March 18, 2015)
+
+- Added abstractions for progress meter and info/debug statements;
+ Redis perc_complete is now updated through a lambda
+
+## 0.50-gn2-pre1 (release, March 17, 2015)
+
+- This is the first test release of multi-core pylmm into GN2. Both
+ kinship calculation and GWAS have been made multi-threaded by
+ introducing the Python multiprocessing module. Note that only
+ run_other has been updated to use the new routines (so human is
+ still handled the old way). I have taken care that we can still run
+ both old-style and new-style LMM (through passing the 'new_code'
+ boolean). This could be an option in the web server for users to
+ select and test for any unexpected differences (of which there
+ should be none, naturally ;).
+
+- The current version can handle missing phenotypes, but as they are
+ removed there is no way for GN2 to know what SNPs the P-values
+ belong to. A future version will pass a SNP index to allow for
+ missing phenotypes.
\ No newline at end of file
diff --git a/wqflask/wqflask/my_pylmm/data/genofile_parser.py b/wqflask/wqflask/my_pylmm/data/genofile_parser.py
index 1f4760a9..9191f345 100755
--- a/wqflask/wqflask/my_pylmm/data/genofile_parser.py
+++ b/wqflask/wqflask/my_pylmm/data/genofile_parser.py
@@ -78,26 +78,19 @@ class ConvertGenoFile(object):
# self.process_snps_file()
- #def process_row(self, row):
- # counter = 0
- # for char in row:
- # if char
- # counter += 1
-
-
def process_csv(self):
for row_count, row in enumerate(self.process_rows()):
- #self.latest_row_pos = row_count
-
- row_items = row.split()
+ row_items = row.split("\t")
this_marker = Marker()
this_marker.name = row_items[1]
this_marker.chr = row_items[0]
- #this_marker.cM = row_items[2]
if self.cm_exists and self.mb_exists:
- #print("cm and mb exists")
- this_marker.Mb = row_items[2]
+ this_marker.cM = row_items[2]
+ this_marker.Mb = row_items[3]
+ genotypes = row_items[4:]
+ elif self.cm_exists:
+ this_marker.cM = row_items[2]
genotypes = row_items[3:]
elif self.mb_exists:
this_marker.Mb = row_items[2]
@@ -190,13 +183,13 @@ class ConvertGenoFile(object):
if __name__=="__main__":
- Old_Geno_Directory = """/home/zas1024/gene/web/genotypes/"""
- New_Geno_Directory = """/home/zas1024/gene/web/new_genotypes/"""
- #Input_File = """/home/zas1024/gene/web/genotypes/BXD.geno"""
+ Old_Geno_Directory = """/home/zas1024/gene/genotype_files/genotypes/"""
+ New_Geno_Directory = """/home/zas1024/gene/genotype_files/new_genotypes/"""
+ #Input_File = """/home/zas1024/gene/genotype_files/genotypes/BXD.geno"""
#Output_File = """/home/zas1024/gene/wqflask/wqflask/pylmm/data/bxd.snps"""
- convertob = ConvertGenoFile("/home/zas1024/gene/web/genotypes/HSNIH.geno", "/home/zas1024/gene/web/new_genotypes/HSNIH.json")
- convertob.convert()
- #ConvertGenoFile.process_all(Old_Geno_Directory, New_Geno_Directory)
+ #convertob = ConvertGenoFile("/home/zas1024/gene/genotype_files/genotypes/SRxSHRSPF2.geno", "/home/zas1024/gene/genotype_files/new_genotypes/SRxSHRSPF2.json")
+ #convertob.convert()
+ ConvertGenoFile.process_all(Old_Geno_Directory, New_Geno_Directory)
#ConvertGenoFiles(Geno_Directory)
#process_csv(Input_File, Output_File) \ No newline at end of file
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/__init__.py b/wqflask/wqflask/my_pylmm/pyLMM/__init__.py
deleted file mode 100644
index c40c3221..00000000
--- a/wqflask/wqflask/my_pylmm/pyLMM/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-PYLMM_VERSION="0.50-gn2-pre1"
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/convertlmm.py b/wqflask/wqflask/my_pylmm/pyLMM/convertlmm.py
deleted file mode 100644
index 3b6b5d70..00000000
--- a/wqflask/wqflask/my_pylmm/pyLMM/convertlmm.py
+++ /dev/null
@@ -1,178 +0,0 @@
-# This is a converter for common LMM formats, so as to keep complexity
-# outside the main routines.
-
-# Copyright (C) 2015 Pjotr Prins (pjotr.prins@thebird.nl)
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as
-# published by the Free Software Foundation, either version 3 of the
-# License, or (at your option) any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-
-# You should have received a copy of the GNU Affero General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-from __future__ import print_function
-from optparse import OptionParser
-import sys
-import os
-import numpy as np
-# from lmm import LMM, run_other
-# import input
-import plink
-
-usage = """
-python convertlmm.py [--plink] [--prefix out_basename] [--kinship kfile] [--pheno pname] [--geno gname]
-
- Convert files for runlmm.py processing. Writes to stdout by default.
-
- try --help for more information
-"""
-
-# if len(args) == 0:
-# print usage
-# sys.exit(1)
-
-option_parser = OptionParser(usage=usage)
-option_parser.add_option("--kinship", dest="kinship",
- help="Parse a kinship file. This is an nxn plain text file and can be computed with the pylmmKinship program")
-option_parser.add_option("--pheno", dest="pheno",
- help="Parse a phenotype file (use with --plink only)")
-option_parser.add_option("--geno", dest="geno",
- help="Parse a genotype file (use with --plink only)")
-option_parser.add_option("--plink", dest="plink", action="store_true", default=False,
- help="Parse PLINK style")
-# option_parser.add_option("--kinship",action="store_false", dest="kinship", default=True,
-# help="Parse a kinship file. This is an nxn plain text file and can be computed with the pylmmKinship program.")
-option_parser.add_option("--prefix", dest="prefix",
- help="Output prefix for output file(s)")
-option_parser.add_option("-q", "--quiet",
- action="store_false", dest="verbose", default=True,
- help="don't print status messages to stdout")
-option_parser.add_option("-v", "--verbose",
- action="store_true", dest="verbose", default=False,
- help="Print extra info")
-
-(options, args) = option_parser.parse_args()
-
-writer = None
-num_inds = None
-snp_names = []
-ind_names = []
-
-def msg(s):
- sys.stderr.write("INFO: ")
- sys.stderr.write(s)
- sys.stderr.write("\n")
-
-def wr(s):
- if writer:
- writer.write(s)
- else:
- sys.stdout.write(s)
-
-def wrln(s):
- wr(s)
- wr("\n")
-
-
-if options.pheno:
- if not options.plink:
- raise Exception("Use --plink switch")
- # Because plink does not track size we need to read the whole thing first
- msg("Converting pheno "+options.pheno)
- phenos = []
- count = 0
- count_pheno = None
- for line in open(options.pheno,'r'):
- count += 1
- list = line.split()
- pcount = len(list)-2
- assert(pcount > 0)
- if count_pheno == None:
- count_pheno = pcount
- assert(count_pheno == pcount)
- row = [list[0]]+list[2:]
- phenos.append(row)
-
- writer = None
- if options.prefix:
- writer = open(options.prefix+".pheno","w")
- wrln("# Phenotype format version 1.0")
- wrln("# Individuals = "+str(count))
- wrln("# Phenotypes = "+str(count_pheno))
- for i in range(count_pheno):
- wr("\t"+str(i+1))
- wr("\n")
- for i in range(count):
- wr("\t".join(phenos[i]))
- wr("\n")
- num_inds = count
- msg(str(count)+" pheno lines written")
-
-if options.kinship:
- is_header = True
- count = 0
- msg("Converting kinship "+options.kinship)
- writer = None
- if options.prefix:
- writer = open(options.prefix+".kin","w")
- for line in open(options.kinship,'r'):
- count += 1
- if is_header:
- size = len(line.split())
- wrln("# Kinship format version 1.0")
- wrln("# Size="+str(size))
- for i in range(size):
- wr("\t"+str(i+1))
- wr("\n")
- is_header = False
- wr(str(count))
- wr("\t")
- wr("\t".join(line.split()))
- wr("\n")
- num_inds = count
- msg(str(count)+" kinship lines written")
-
-if options.geno:
- msg("Converting geno "+options.geno+'.bed')
- if not options.plink:
- raise Exception("Use --plink switch")
- if not num_inds:
- raise Exception("Can not figure out the number of individuals, use --pheno or --kinship")
- bim_snps = plink.readbim(options.geno+'.bim')
- num_snps = len(bim_snps)
- writer = None
- if options.prefix:
- writer = open(options.prefix+".geno","w")
- wrln("# Genotype format version 1.0")
- wrln("# Individuals = "+str(num_inds))
- wrln("# SNPs = "+str(num_snps))
- wrln("# Encoding = HAB")
- for i in range(num_inds):
- wr("\t"+str(i+1))
- wr("\n")
-
- m = []
- def out(i,x):
- # wr(str(i)+"\t")
- # wr("\t".join(x))
- # wr("\n")
- m.append(x)
-
- snps = plink.readbed(options.geno+'.bed',num_inds, ('A','H','B','-'), out)
-
- msg("Write transposed genotype matrix")
- for g in range(num_snps):
- wr(bim_snps[g][1]+"\t")
- for i in range(num_inds):
- wr(m[g][i])
- wr("\n")
-
- msg(str(count)+" geno lines written (with "+str(snps)+" snps)")
-
-msg("Converting done")
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/genotype.py b/wqflask/wqflask/my_pylmm/pyLMM/genotype.py
deleted file mode 100644
index 315fd824..00000000
--- a/wqflask/wqflask/my_pylmm/pyLMM/genotype.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# Genotype routines
-
-# Copyright (C) 2013 Nicholas A. Furlotte (nick.furlotte@gmail.com)
-# Copyright (C) 2015 Pjotr Prins (pjotr.prins@thebird.nl)
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as
-# published by the Free Software Foundation, either version 3 of the
-# License, or (at your option) any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-
-# You should have received a copy of the GNU Affero General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-import numpy as np
-from collections import Counter
-import operator
-
-def replace_missing_with_MAF(snp_g):
- """
- Replace the missing genotype with the minor allele frequency (MAF)
- in the snp row. It is rather slow!
- """
- cnt = Counter(snp_g)
- tuples = sorted(cnt.items(), key=operator.itemgetter(1))
- l2 = [t for t in tuples if not np.isnan(t[0])]
- maf = l2[0][0]
- res = np.array([maf if np.isnan(snp) else snp for snp in snp_g])
- return res
-
-def normalize(ind_g):
- """
- Run for every SNP list (for one individual) and return
- normalized SNP genotype values with missing data filled in
- """
- g1 = np.copy(ind_g) # avoid side effects
- x = True - np.isnan(ind_g) # Matrix of True/False
- m = ind_g[x].mean() # Global mean value
- s = np.sqrt(ind_g[x].var()) # Global stddev
- g1[np.isnan(ind_g)] = m # Plug-in mean values for missing data
- if s == 0:
- g1 = g1 - m # Subtract the mean
- else:
- g1 = (g1 - m) / s # Normalize the deviation
- return g1
-
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/gwas.py b/wqflask/wqflask/my_pylmm/pyLMM/gwas.py
deleted file mode 100644
index b901c0e2..00000000
--- a/wqflask/wqflask/my_pylmm/pyLMM/gwas.py
+++ /dev/null
@@ -1,173 +0,0 @@
-# pylmm-based GWAS calculation
-#
-# Copyright (C) 2013 Nicholas A. Furlotte (nick.furlotte@gmail.com)
-# Copyright (C) 2015 Pjotr Prins (pjotr.prins@thebird.nl)
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as
-# published by the Free Software Foundation, either version 3 of the
-# License, or (at your option) any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-
-# You should have received a copy of the GNU Affero General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-#!/usr/bin/python
-
-import pdb
-import time
-import sys
-# from utility import temp_data
-import lmm2
-
-import os
-import numpy as np
-import input
-from optmatrix import matrix_initialize
-from lmm2 import LMM2
-
-import multiprocessing as mp # Multiprocessing is part of the Python stdlib
-import Queue
-
-def formatResult(id,beta,betaSD,ts,ps):
- return "\t".join([str(x) for x in [id,beta,betaSD,ts,ps]]) + "\n"
-
-def compute_snp(j,n,snp_ids,lmm2,REML,q = None):
- # print("COMPUTE SNP",j,snp_ids,"\n")
- result = []
- for snp_id in snp_ids:
- snp,id = snp_id
- x = snp.reshape((n,1)) # all the SNPs
- # print "X=",x
- # if refit:
- # L.fit(X=snp,REML=REML)
- ts,ps,beta,betaVar = lmm2.association(x,REML=REML,returnBeta=True)
- # result.append(formatResult(id,beta,np.sqrt(betaVar).sum(),ts,ps))
- result.append( (ts,ps) )
- if not q:
- q = compute_snp.q
- q.put([j,result])
- return j
- # PS.append(ps)
- # TS.append(ts)
- # return len(result)
- # compute.q.put(result)
- # return None
-
-def f_init(q):
- compute_snp.q = q
-
-def gwas(Y,G,K,restricted_max_likelihood=True,refit=False,verbose=True):
- """
- Execute a GWAS. The G matrix should be n inds (cols) x m snps (rows)
- """
- matrix_initialize()
- cpu_num = mp.cpu_count()
- numThreads = None # for now use all available threads
- kfile2 = False
- reml = restricted_max_likelihood
-
- sys.stderr.write(str(G.shape)+"\n")
- n = G.shape[1] # inds
- inds = n
- m = G.shape[0] # snps
- snps = m
- sys.stderr.write(str(m)+" SNPs\n")
- # print "***** GWAS: G",G.shape,G
- assert snps>inds, "snps should be larger than inds (snps=%d,inds=%d)" % (snps,inds)
-
- # CREATE LMM object for association
- # if not kfile2: L = LMM(Y,K,Kva,Kve,X0,verbose=verbose)
- # else: L = LMM_withK2(Y,K,Kva,Kve,X0,verbose=verbose,K2=K2)
-
- lmm2 = LMM2(Y,K) # ,Kva,Kve,X0,verbose=verbose)
- if not refit:
- if verbose: sys.stderr.write("Computing fit for null model\n")
- lmm2.fit() # follow GN model in run_other
- if verbose: sys.stderr.write("\t heritability=%0.3f, sigma=%0.3f\n" % (lmm2.optH,lmm2.optSigma))
-
- # outFile = "test.out"
- # out = open(outFile,'w')
- out = sys.stderr
-
- def outputResult(id,beta,betaSD,ts,ps):
- out.write(formatResult(id,beta,betaSD,ts,ps))
- def printOutHead(): out.write("\t".join(["SNP_ID","BETA","BETA_SD","F_STAT","P_VALUE"]) + "\n")
-
- # printOutHead()
- res = []
-
- # Set up the pool
- # mp.set_start_method('spawn')
- q = mp.Queue()
- p = mp.Pool(numThreads, f_init, [q])
- collect = []
-
- # Buffers for pvalues and t-stats
- # PS = []
- # TS = []
- count = 0
- job = 0
- jobs_running = 0
- for snp in G:
- snp_id = (snp,'SNPID')
- count += 1
- if count % 1000 == 0:
- job += 1
- if verbose:
- sys.stderr.write("Job %d At SNP %d\n" % (job,count))
- if numThreads == 1:
- print "Running on 1 THREAD"
- compute_snp(job,n,collect,lmm2,reml,q)
- collect = []
- j,lst = q.get()
- if verbose:
- sys.stderr.write("Job "+str(j)+" finished\n")
- res.append((j,lst))
- else:
- p.apply_async(compute_snp,(job,n,collect,lmm2,reml))
- jobs_running += 1
- collect = []
- while jobs_running > cpu_num:
- try:
- j,lst = q.get_nowait()
- if verbose:
- sys.stderr.write("Job "+str(j)+" finished\n")
- res.append((j,lst))
- jobs_running -= 1
- except Queue.Empty:
- time.sleep(0.1)
- pass
- if jobs_running > cpu_num*2:
- time.sleep(1.0)
- else:
- break
-
- collect.append(snp_id)
-
- if numThreads==1 or count<1000 or len(collect)>0:
- job += 1
- print "Collect final batch size %i job %i @%i: " % (len(collect), job, count)
- compute_snp(job,n,collect,lmm2,reml,q)
- collect = []
- j,lst = q.get()
- res.append((j,lst))
- print "count=",count," running=",jobs_running," collect=",len(collect)
- for job in range(jobs_running):
- j,lst = q.get(True,15) # time out
- if verbose:
- sys.stderr.write("Job "+str(j)+" finished\n")
- res.append((j,lst))
-
- print "Before sort",[res1[0] for res1 in res]
- res = sorted(res,key=lambda x: x[0])
- # if verbose:
- # print "res=",res[0][0:10]
- print "After sort",[res1[0] for res1 in res]
- print [len(res1[1]) for res1 in res]
- ts = [item[0] for j,res1 in res for item in res1]
- ps = [item[1] for j,res1 in res for item in res1]
- return ts,ps
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/input.py b/wqflask/wqflask/my_pylmm/pyLMM/input.py
deleted file mode 100644
index 7063fedf..00000000
--- a/wqflask/wqflask/my_pylmm/pyLMM/input.py
+++ /dev/null
@@ -1,267 +0,0 @@
-# pylmm is a python-based linear mixed-model solver with applications to GWAS
-
-# Copyright (C) 2013 Nicholas A. Furlotte (nick.furlotte@gmail.com)
-
-#The program is free for academic use. Please contact Nick Furlotte
-#<nick.furlotte@gmail.com> if you are interested in using the software for
-#commercial purposes.
-
-#The software must not be modified and distributed without prior
-#permission of the author.
-
-#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-#LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-#A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-#CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-#EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-#PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-#PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-#LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-#NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-#SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import os
-import sys
-import numpy as np
-import struct
-import pdb
-
-class plink:
- def __init__(self,fbase,kFile=None,phenoFile=None,type='b',normGenotype=True,readKFile=False):
- self.fbase = fbase
- self.type = type
- self.indivs = self.getIndivs(self.fbase,type)
- self.kFile = kFile
- self.phenos = None
- self.normGenotype = normGenotype
- self.phenoFile = phenoFile
- # Originally I was using the fastLMM style that has indiv IDs embedded.
- # NOW I want to use this module to just read SNPs so I'm allowing
- # the programmer to turn off the kinship reading.
- self.readKFile = readKFile
-
- if self.kFile:
- self.K = self.readKinship(self.kFile)
- elif os.path.isfile("%s.kin" % fbase):
- self.kFile = "%s.kin" %fbase
- if self.readKFile:
- self.K = self.readKinship(self.kFile)
- else:
- self.kFile = None
- self.K = None
-
- self.getPhenos(self.phenoFile)
-
- self.fhandle = None
- self.snpFileHandle = None
-
- def __del__(self):
- if self.fhandle: self.fhandle.close()
- if self.snpFileHandle: self.snpFileHandle.close()
-
- def getSNPIterator(self):
- if not self.type == 'b':
- sys.stderr.write("Have only implemented this for binary plink files (bed)\n")
- return
-
- # get the number of snps
- file = self.fbase + '.bim'
- i = 0
- f = open(file,'r')
- for line in f: i += 1
- f.close()
- self.numSNPs = i
- self.have_read = 0
- self.snpFileHandle = open(file,'r')
-
- self.BytestoRead = self.N / 4 + (self.N % 4 and 1 or 0)
- self._formatStr = 'c'*self.BytestoRead
-
- file = self.fbase + '.bed'
- self.fhandle = open(file,'rb')
-
- magicNumber = self.fhandle.read(2)
- order = self.fhandle.read(1)
- if not order == '\x01':
- sys.stderr.write("This is not in SNP major order - you did not handle this case\n")
- raise StopIteration
-
- return self
-
- def __iter__(self):
- return self.getSNPIterator()
-
- def next(self):
- if self.have_read == self.numSNPs:
- raise StopIteration
- X = self.fhandle.read(self.BytestoRead)
- XX = [bin(ord(x)) for x in struct.unpack(self._formatStr,X)]
- self.have_read += 1
- return self.formatBinaryGenotypes(XX,self.normGenotype),self.snpFileHandle.readline().strip().split()[1]
-
- def formatBinaryGenotypes(self,X,norm=True):
- D = { \
- '00': 0.0, \
- '10': 0.5, \
- '11': 1.0, \
- '01': np.nan \
- }
-
- D_tped = { \
- '00': '1 1', \
- '10': '1 2', \
- '11': '2 2', \
- '01': '0 0' \
- }
-
- #D = D_tped
-
- G = []
- for x in X:
- if not len(x) == 10:
- xx = x[2:]
- x = '0b' + '0'*(8 - len(xx)) + xx
- a,b,c,d = (x[8:],x[6:8],x[4:6],x[2:4])
- L = [D[y] for y in [a,b,c,d]]
- G += L
- # only take the leading values because whatever is left should be null
- G = G[:self.N]
- G = np.array(G)
- if norm:
- G = self.normalizeGenotype(G)
- return G
-
- def normalizeGenotype(self,G):
- # print "Before",G
- # print G.shape
- print "call input.normalizeGenotype"
- raise "This should not be used"
- x = True - np.isnan(G)
- m = G[x].mean()
- s = np.sqrt(G[x].var())
- G[np.isnan(G)] = m
- if s == 0: G = G - m
- else: G = (G - m) / s
- # print "After",G
- return G
-
- def getPhenos(self,phenoFile=None):
- if not phenoFile:
- self.phenoFile = phenoFile = self.fbase+".phenos"
- if not os.path.isfile(phenoFile):
- sys.stderr.write("Could not find phenotype file: %s\n" % (phenoFile))
- return
- f = open(phenoFile,'r')
- keys = []
- P = []
- for line in f:
- v = line.strip().split()
- keys.append((v[0],v[1]))
- P.append([(x == 'NA' or x == '-9') and np.nan or float(x) for x in v[2:]])
- f.close()
- P = np.array(P)
-
- # reorder to match self.indivs
- D = {}
- L = []
- for i in range(len(keys)):
- D[keys[i]] = i
- for i in range(len(self.indivs)):
- if not D.has_key(self.indivs[i]):
- continue
- L.append(D[self.indivs[i]])
- P = P[L,:]
-
- self.phenos = P
- return P
-
- def getIndivs(self,base,type='b'):
- if type == 't':
- famFile = "%s.tfam" % base
- else:
- famFile = "%s.fam" % base
- keys = []
- i = 0
- f = open(famFile,'r')
- for line in f:
- v = line.strip().split()
- famId = v[0]
- indivId = v[1]
- k = (famId.strip(),indivId.strip())
- keys.append(k)
- i += 1
- f.close()
-
- self.N = len(keys)
- sys.stderr.write("Read %d individuals from %s\n" % (self.N, famFile))
-
- return keys
-
- def readKinship(self,kFile):
- # Assume the fastLMM style
- # This will read in the kinship matrix and then reorder it
- # according to self.indivs - additionally throwing out individuals
- # that are not in both sets
- if self.indivs == None or len(self.indivs) == 0:
- sys.stderr.write("Did not read any individuals so can't load kinship\n")
- return
-
- sys.stderr.write("Reading kinship matrix from %s\n" % (kFile) )
-
- f = open(kFile,'r')
- # read indivs
- v = f.readline().strip().split("\t")[1:]
- keys = [tuple(y.split()) for y in v]
- D = {}
- for i in range(len(keys)): D[keys[i]] = i
-
- # read matrix
- K = []
- for line in f:
- K.append([float(x) for x in line.strip().split("\t")[1:]])
- f.close()
- K = np.array(K)
-
- # reorder to match self.indivs
- L = []
- KK = []
- X = []
- for i in range(len(self.indivs)):
- if not D.has_key(self.indivs[i]):
- X.append(self.indivs[i])
- else:
- KK.append(self.indivs[i])
- L.append(D[self.indivs[i]])
- K = K[L,:][:,L]
- self.indivs = KK
- self.indivs_removed = X
- if len(self.indivs_removed):
- sys.stderr.write("Removed %d individuals that did not appear in Kinship\n" % (len(self.indivs_removed)))
- return K
-
- def getCovariates(self,covFile=None):
- if not os.path.isfile(covFile):
- sys.stderr.write("Could not find covariate file: %s\n" % (phenoFile))
- return
- f = open(covFile,'r')
- keys = []
- P = []
- for line in f:
- v = line.strip().split()
- keys.append((v[0],v[1]))
- P.append([x == 'NA' and np.nan or float(x) for x in v[2:]])
- f.close()
- P = np.array(P)
-
- # reorder to match self.indivs
- D = {}
- L = []
- for i in range(len(keys)):
- D[keys[i]] = i
- for i in range(len(self.indivs)):
- if not D.has_key(self.indivs[i]): continue
- L.append(D[self.indivs[i]])
- P = P[L,:]
-
- return P
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/kinship.py b/wqflask/wqflask/my_pylmm/pyLMM/kinship.py
deleted file mode 100644
index 0c43587e..00000000
--- a/wqflask/wqflask/my_pylmm/pyLMM/kinship.py
+++ /dev/null
@@ -1,177 +0,0 @@
-# pylmm kinship calculation
-#
-# Copyright (C) 2013 Nicholas A. Furlotte (nick.furlotte@gmail.com)
-# Copyright (C) 2015 Pjotr Prins (pjotr.prins@thebird.nl)
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as
-# published by the Free Software Foundation, either version 3 of the
-# License, or (at your option) any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-
-# You should have received a copy of the GNU Affero General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-# env PYTHONPATH=$pylmm_lib_path:./lib python $pylmm_lib_path/runlmm.py --pheno test.pheno --geno test9000.geno kinship --test
-
-import sys
-import os
-import numpy as np
-from scipy import linalg
-import multiprocessing as mp # Multiprocessing is part of the Python stdlib
-import Queue
-import time
-
-from optmatrix import matrix_initialize, matrixMultT
-
-def kinship_full(G):
- """
- Calculate the Kinship matrix using a full dot multiplication
- """
- print G.shape
- m = G.shape[0] # snps
- n = G.shape[1] # inds
- sys.stderr.write(str(m)+" SNPs\n")
- assert m>n, "n should be larger than m (snps>inds)"
- m = np.dot(G.T,G)
- m = m/G.shape[0]
- return m
-
-def compute_W(job,G,n,snps,compute_size):
- """
- Read 1000 SNPs at a time into matrix and return the result
- """
- m = compute_size
- W = np.ones((n,m)) * np.nan # W matrix has dimensions individuals x SNPs (initially all NaNs)
- for j in range(0,compute_size):
- pos = job*m + j # real position
- if pos >= snps:
- W = W[:,range(0,j)]
- break
- snp = G[job*compute_size+j]
- if snp.var() == 0:
- continue
- W[:,j] = snp # set row to list of SNPs
- return W
-
-def compute_matrixMult(job,W,q = None):
- """
- Compute Kinship(W)*j
-
- For every set of SNPs matrixMult is used to multiply matrices T(W)*W
- """
- res = matrixMultT(W)
- if not q: q=compute_matrixMult.q
- q.put([job,res])
- return job
-
-def f_init(q):
- compute_matrixMult.q = q
-
-# Calculate the kinship matrix from G (SNPs as rows!), returns K
-#
-def kinship(G,computeSize=1000,numThreads=None,useBLAS=False,verbose=True):
- numThreads = None
- if numThreads:
- numThreads = int(numThreads)
- matrix_initialize(useBLAS)
-
- sys.stderr.write(str(G.shape)+"\n")
- n = G.shape[1] # inds
- inds = n
- m = G.shape[0] # snps
- snps = m
- sys.stderr.write(str(m)+" SNPs\n")
- assert snps>inds, "snps should be larger than inds (%i snps, %i inds)" % (snps,inds)
-
- q = mp.Queue()
- p = mp.Pool(numThreads, f_init, [q])
- cpu_num = mp.cpu_count()
- print "CPU cores:",cpu_num
- print snps,computeSize
- iterations = snps/computeSize+1
- # if testing:
- # iterations = 8
- # jobs = range(0,8) # range(0,iterations)
-
- results = []
-
- K = np.zeros((n,n)) # The Kinship matrix has dimension individuals x individuals
-
- completed = 0
- for job in range(iterations):
- if verbose:
- sys.stderr.write("Processing job %d first %d SNPs\n" % (job, ((job+1)*computeSize)))
- W = compute_W(job,G,n,snps,computeSize)
- if numThreads == 1:
- # Single-core
- compute_matrixMult(job,W,q)
- j,x = q.get()
- if verbose: sys.stderr.write("Job "+str(j)+" finished\n")
- K_j = x
- # print j,K_j[:,0]
- K = K + K_j
- else:
- # Multi-core
- results.append(p.apply_async(compute_matrixMult, (job,W)))
- # Do we have a result?
- while (len(results)-completed>cpu_num*2):
- time.sleep(0.1)
- try:
- j,x = q.get_nowait()
- if verbose: sys.stderr.write("Job "+str(j)+" finished\n")
- K_j = x
- # print j,K_j[:,0]
- K = K + K_j
- completed += 1
- except Queue.Empty:
- pass
-
- if numThreads == None or numThreads > 1:
- # results contains the growing result set
- for job in range(len(results)-completed):
- j,x = q.get(True,15)
- if verbose: sys.stderr.write("Job "+str(j)+" finished\n")
- K_j = x
- # print j,K_j[:,0]
- K = K + K_j
- completed += 1
-
- K = K / float(snps)
-
- # outFile = 'runtest.kin'
- # if verbose: sys.stderr.write("Saving Kinship file to %s\n" % outFile)
- # np.savetxt(outFile,K)
-
- # if saveKvaKve:
- # if verbose: sys.stderr.write("Obtaining Eigendecomposition\n")
- # Kva,Kve = linalg.eigh(K)
- # if verbose: sys.stderr.write("Saving eigendecomposition to %s.[kva | kve]\n" % outFile)
- # np.savetxt(outFile+".kva",Kva)
- # np.savetxt(outFile+".kve",Kve)
- return K
-
-def kvakve(K, verbose=True):
- """
- Obtain eigendecomposition for K and return Kva,Kve where Kva is cleaned
- of small values < 1e-6 (notably smaller than zero)
- """
- if verbose: sys.stderr.write("Obtaining eigendecomposition for %dx%d matrix\n" % (K.shape[0],K.shape[1]) )
-
- Kva,Kve = linalg.eigh(K)
- if verbose:
- print("Kva is: ", Kva.shape, Kva)
- print("Kve is: ", Kve.shape, Kve)
-
- if sum(Kva < 1e-6):
- if verbose: sys.stderr.write("Cleaning %d eigen values (Kva<0)\n" % (sum(Kva < 0)))
- Kva[Kva < 1e-6] = 1e-6
- return Kva,Kve
-
-
-
-
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/lmm.py b/wqflask/wqflask/my_pylmm/pyLMM/lmm.py
deleted file mode 100644
index 53689071..00000000
--- a/wqflask/wqflask/my_pylmm/pyLMM/lmm.py
+++ /dev/null
@@ -1,900 +0,0 @@
-# pylmm is a python-based linear mixed-model solver with applications to GWAS
-
-# Copyright (C) 2013 Nicholas A. Furlotte (nick.furlotte@gmail.com)
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as
-# published by the Free Software Foundation, either version 3 of the
-# License, or (at your option) any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-
-# You should have received a copy of the GNU Affero General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-from __future__ import absolute_import, print_function, division
-
-import sys
-import time
-import argparse
-import uuid
-
-import numpy as np
-from scipy import linalg
-from scipy import optimize
-from scipy import stats
-import pdb
-
-import simplejson as json
-
-import gzip
-import zlib
-import datetime
-import cPickle as pickle
-import simplejson as json
-
-from pprint import pformat as pf
-
-from redis import Redis
-Redis = Redis()
-
-import sys
-sys.path.append("/home/zas1024/gene/wqflask/")
-
-has_gn2=True
-
-from utility.benchmark import Bench
-from utility import temp_data
-
-sys.path.append("/home/zas1024/gene/wqflask/wqflask/my_pylmm/pyLMM/")
-
-from kinship import kinship, kinship_full, kvakve
-import genotype
-import phenotype
-import gwas
-
-try:
- from wqflask.my_pylmm.pyLMM import chunks
-except ImportError:
- print("WARNING: Standalone version missing the Genenetwork2 environment\n")
- has_gn2=False
- pass
-
-#np.seterr('raise')
-
-#def run_human(pheno_vector,
-# covariate_matrix,
-# plink_input_file,
-# kinship_matrix,
-# refit=False,
-# loading_progress=None):
-
-def run_human(pheno_vector,
- covariate_matrix,
- plink_input_file,
- kinship_matrix,
- refit=False,
- tempdata=None):
-
- v = np.isnan(pheno_vector)
- keep = True - v
- keep = keep.reshape((len(keep),))
-
- identifier = str(uuid.uuid4())
-
- #print("pheno_vector: ", pf(pheno_vector))
- #print("kinship_matrix: ", pf(kinship_matrix))
- #print("kinship_matrix.shape: ", pf(kinship_matrix.shape))
-
- #lmm_vars = pickle.dumps(dict(
- # pheno_vector = pheno_vector,
- # covariate_matrix = covariate_matrix,
- # kinship_matrix = kinship_matrix
- #))
- #Redis.hset(identifier, "lmm_vars", lmm_vars)
- #Redis.expire(identifier, 60*60)
-
- if v.sum():
- pheno_vector = pheno_vector[keep]
- print("pheno_vector shape is now: ", pf(pheno_vector.shape))
- covariate_matrix = covariate_matrix[keep,:]
- print("kinship_matrix shape is: ", pf(kinship_matrix.shape))
- print("keep is: ", pf(keep.shape))
- kinship_matrix = kinship_matrix[keep,:][:,keep]
-
- print("kinship_matrix:", pf(kinship_matrix))
-
- n = kinship_matrix.shape[0]
- print("n is:", n)
- lmm_ob = LMM(pheno_vector,
- kinship_matrix,
- covariate_matrix)
- lmm_ob.fit()
-
-
- # Buffers for pvalues and t-stats
- p_values = []
- t_stats = []
-
- #print("input_file: ", plink_input_file)
-
- with Bench("Opening and loading pickle file"):
- with gzip.open(plink_input_file, "rb") as input_file:
- data = pickle.load(input_file)
-
- plink_input = data['plink_input']
-
- #plink_input.getSNPIterator()
- with Bench("Calculating numSNPs"):
- total_snps = data['numSNPs']
-
- with Bench("snp iterator loop"):
- count = 0
-
- with Bench("Create list of inputs"):
- inputs = list(plink_input)
-
- with Bench("Divide into chunks"):
- results = chunks.divide_into_chunks(inputs, 64)
-
- result_store = []
-
- key = "plink_inputs"
-
- # Todo: Delete below line when done testing
- Redis.delete(key)
-
- timestamp = datetime.datetime.utcnow().isoformat()
-
- # Pickle chunks of input SNPs (from Plink interator) and compress them
- #print("Starting adding loop")
- for part, result in enumerate(results):
- #data = pickle.dumps(result, pickle.HIGHEST_PROTOCOL)
- holder = pickle.dumps(dict(
- identifier = identifier,
- part = part,
- timestamp = timestamp,
- result = result
- ), pickle.HIGHEST_PROTOCOL)
-
- #print("Adding:", part)
- Redis.rpush(key, zlib.compress(holder))
- #print("End adding loop")
- #print("***** Added to {} queue *****".format(key))
- for snp, this_id in plink_input:
- #with Bench("part before association"):
- #if count > 1000:
- # break
- count += 1
-
- percent_complete = (float(count) / total_snps) * 100
- #print("percent_complete: ", percent_complete)
- tempdata.store("percent_complete", percent_complete)
-
- #with Bench("actual association"):
- ps, ts = human_association(snp,
- n,
- keep,
- lmm_ob,
- pheno_vector,
- covariate_matrix,
- kinship_matrix,
- refit)
-
- #with Bench("after association"):
- p_values.append(ps)
- t_stats.append(ts)
-
- return p_values, t_stats
-
-
-#class HumanAssociation(object):
-# def __init__(self):
-#
-
-def human_association(snp,
- n,
- keep,
- lmm_ob,
- pheno_vector,
- covariate_matrix,
- kinship_matrix,
- refit):
-
- x = snp[keep].reshape((n,1))
- #x[[1,50,100,200,3000],:] = np.nan
- v = np.isnan(x).reshape((-1,))
-
- # Check SNPs for missing values
- if v.sum():
- keeps = True - v
- xs = x[keeps,:]
- # If no variation at this snp or all genotypes missing
- if keeps.sum() <= 1 or xs.var() <= 1e-6:
- return np.nan, np.nan
- #p_values.append(np.nan)
- #t_stats.append(np.nan)
- #continue
-
- # Its ok to center the genotype - I used options.normalizeGenotype to
- # force the removal of missing genotypes as opposed to replacing them with MAF.
-
- #if not options.normalizeGenotype:
- # xs = (xs - xs.mean()) / np.sqrt(xs.var())
-
- filtered_pheno = pheno_vector[keeps]
- filtered_covariate_matrix = covariate_matrix[keeps,:]
-
- print("kinship_matrix shape is: ", pf(kinship_matrix.shape))
- print("keeps is: ", pf(keeps.shape))
- filtered_kinship_matrix = kinship_matrix[keeps,:][:,keeps]
- filtered_lmm_ob = lmm.LMM(filtered_pheno,filtered_kinship_matrix,X0=filtered_covariate_matrix)
- if refit:
- filtered_lmm_ob.fit(X=xs)
- else:
- #try:
- filtered_lmm_ob.fit()
- #except: pdb.set_trace()
- ts,ps,beta,betaVar = Ls.association(xs,returnBeta=True)
- else:
- if x.var() == 0:
- return np.nan, np.nan
- #p_values.append(np.nan)
- #t_stats.append(np.nan)
- #continue
- if refit:
- lmm_ob.fit(X=x)
- ts, ps, beta, betaVar = lmm_ob.association(x)
- return ps, ts
-
-
-#def run(pheno_vector,
-# genotype_matrix,
-# restricted_max_likelihood=True,
-# refit=False,
-# temp_data=None):
-
-def run_other_old(pheno_vector,
- genotype_matrix,
- restricted_max_likelihood=True,
- refit=False,
- tempdata=None # <---- can not be None
- ):
-
- """Takes the phenotype vector and genotype matrix and returns a set of p-values and t-statistics
-
- restricted_max_likelihood -- whether to use restricted max likelihood; True or False
- refit -- whether to refit the variance component for each marker
- temp_data -- TempData object that stores the progress for each major step of the
- calculations ("calculate_kinship" and "GWAS" take the majority of time)
-
- """
-
- print("Running the original LMM engine in run_other (old)")
- print("REML=",restricted_max_likelihood," REFIT=",refit)
- with Bench("Calculate Kinship"):
- kinship_matrix,genotype_matrix = calculate_kinship(genotype_matrix, tempdata)
-
- print("kinship_matrix: ", pf(kinship_matrix))
- print("kinship_matrix.shape: ", pf(kinship_matrix.shape))
-
- # with Bench("Create LMM object"):
- # lmm_ob = LMM(pheno_vector, kinship_matrix)
-
- # with Bench("LMM_ob fitting"):
- # lmm_ob.fit()
-
- print("run_other_old genotype_matrix: ", genotype_matrix.shape)
- print(genotype_matrix)
-
- with Bench("Doing GWAS"):
- t_stats, p_values = GWAS(pheno_vector,
- genotype_matrix,
- kinship_matrix,
- restricted_max_likelihood=True,
- refit=False,
- temp_data=tempdata)
- Bench().report()
- return p_values, t_stats
-
-def run_other_new(pheno_vector,
- genotype_matrix,
- restricted_max_likelihood=True,
- refit=False,
- tempdata=None # <---- can not be None
- ):
-
- """Takes the phenotype vector and genotype matrix and returns a set of p-values and t-statistics
-
- restricted_max_likelihood -- whether to use restricted max likelihood; True or False
- refit -- whether to refit the variance component for each marker
- temp_data -- TempData object that stores the progress for each major step of the
- calculations ("calculate_kinship" and "GWAS" take the majority of time)
-
- """
-
- print("Running the new LMM2 engine in run_other_new")
- print("REML=",restricted_max_likelihood," REFIT=",refit)
-
- # Adjust phenotypes
- Y,G,keep = phenotype.remove_missing(pheno_vector,genotype_matrix,verbose=True)
- print("Removed missing phenotypes",Y.shape)
-
- # if options.maf_normalization:
- # G = np.apply_along_axis( genotype.replace_missing_with_MAF, axis=0, arr=g )
- # print "MAF replacements: \n",G
- # if not options.skip_genotype_normalization:
- # G = np.apply_along_axis( genotype.normalize, axis=1, arr=G)
-
- with Bench("Calculate Kinship"):
- K,G = calculate_kinship(G, tempdata)
-
- print("kinship_matrix: ", pf(K))
- print("kinship_matrix.shape: ", pf(K.shape))
-
- # with Bench("Create LMM object"):
- # lmm_ob = lmm2.LMM2(Y,K)
- # with Bench("LMM_ob fitting"):
- # lmm_ob.fit()
-
- print("run_other_new genotype_matrix: ", G.shape)
- print(G)
-
- with Bench("Doing GWAS"):
- t_stats, p_values = gwas.gwas(Y,
- G.T,
- K,
- restricted_max_likelihood=True,
- refit=False,verbose=True)
- Bench().report()
- return p_values, t_stats
-
-# def matrixMult(A,B):
-# return np.dot(A,B)
-
-def matrixMult(A,B):
-
- # If there is no fblas then we will revert to np.dot()
-
- try:
- linalg.fblas
- except AttributeError:
- return np.dot(A,B)
-
- #print("A is:", pf(A.shape))
- #print("B is:", pf(B.shape))
-
- # If the matrices are in Fortran order then the computations will be faster
- # when using dgemm. Otherwise, the function will copy the matrix and that takes time.
- if not A.flags['F_CONTIGUOUS']:
- AA = A.T
- transA = True
- else:
- AA = A
- transA = False
-
- if not B.flags['F_CONTIGUOUS']:
- BB = B.T
- transB = True
- else:
- BB = B
- transB = False
-
- return linalg.fblas.dgemm(alpha=1.,a=AA,b=BB,trans_a=transA,trans_b=transB)
-
-
-def calculate_kinship_new(genotype_matrix, temp_data=None):
- """
- Call the new kinship calculation where genotype_matrix contains
- inds (columns) by snps (rows).
- """
- print("call genotype.normalize")
- G = np.apply_along_axis( genotype.normalize, axis=0, arr=genotype_matrix)
- print("call calculate_kinship_new")
- return kinship(G.T),G # G gets transposed, we'll turn this into an iterator (FIXME)
-
-def calculate_kinship_old(genotype_matrix, temp_data=None):
- """
- genotype_matrix is an n x m matrix encoding SNP minor alleles.
-
- This function takes a matrix oF SNPs, imputes missing values with the maf,
- normalizes the resulting vectors and returns the RRM matrix.
-
- """
- print("call calculate_kinship_old")
- n = genotype_matrix.shape[0]
- m = genotype_matrix.shape[1]
- print("genotype 2D matrix n (inds) is:", n)
- print("genotype 2D matrix m (snps) is:", m)
- assert m>n, "n should be larger than m (snps>inds)"
- keep = []
- for counter in range(m):
- #print("type of genotype_matrix[:,counter]:", pf(genotype_matrix[:,counter]))
- #Checks if any values in column are not numbers
- not_number = np.isnan(genotype_matrix[:,counter])
-
- #Gets vector of values for column (no values in vector if not all values in col are numbers)
- marker_values = genotype_matrix[True - not_number, counter]
- #print("marker_values is:", pf(marker_values))
-
- #Gets mean of values in vector
- values_mean = marker_values.mean()
-
- genotype_matrix[not_number,counter] = values_mean
- vr = genotype_matrix[:,counter].var()
- if vr == 0:
- continue
- keep.append(counter)
- genotype_matrix[:,counter] = (genotype_matrix[:,counter] - values_mean) / np.sqrt(vr)
-
- percent_complete = int(round((counter/m)*45))
- if temp_data != None:
- temp_data.store("percent_complete", percent_complete)
-
- genotype_matrix = genotype_matrix[:,keep]
- print("After kinship (old) genotype_matrix: ", pf(genotype_matrix))
- kinship_matrix = np.dot(genotype_matrix, genotype_matrix.T) * 1.0/float(m)
- return kinship_matrix,genotype_matrix
-
-calculate_kinship = calculate_kinship_new # alias
-
-def GWAS(pheno_vector,
- genotype_matrix,
- kinship_matrix,
- kinship_eigen_vals=None,
- kinship_eigen_vectors=None,
- covariate_matrix=None,
- restricted_max_likelihood=True,
- refit=False,
- temp_data=None):
- """
- Performs a basic GWAS scan using the LMM. This function
- uses the LMM module to assess association at each SNP and
- does some simple cleanup, such as removing missing individuals
- per SNP and re-computing the eigen-decomp
-
- pheno_vector - n x 1 phenotype vector
- genotype_matrix - n x m SNP matrix
- kinship_matrix - n x n kinship matrix
- kinship_eigen_vals, kinship_eigen_vectors = linalg.eigh(K) - or the eigen vectors and values for K
- covariate_matrix - n x q covariate matrix
- restricted_max_likelihood - use restricted maximum likelihood
- refit - refit the variance component for each SNP
-
- """
- if kinship_eigen_vals == None:
- kinship_eigen_vals = []
- if kinship_eigen_vectors == None:
- kinship_eigen_vectors = []
-
- n = genotype_matrix.shape[0]
- m = genotype_matrix.shape[1]
-
- if covariate_matrix == None:
- covariate_matrix = np.ones((n,1))
-
- # Remove missing values in pheno_vector and adjust associated parameters
- v = np.isnan(pheno_vector)
- if v.sum():
- keep = True - v
- print(pheno_vector.shape,pheno_vector)
- print(keep.shape,keep)
- pheno_vector = pheno_vector[keep]
- #genotype_matrix = genotype_matrix[keep,:]
- #covariate_matrix = covariate_matrix[keep,:]
- #kinship_matrix = kinship_matrix[keep,:][:,keep]
- kinship_eigen_vals = []
- kinship_eigen_vectors = []
-
- lmm_ob = LMM(pheno_vector,
- kinship_matrix,
- kinship_eigen_vals,
- kinship_eigen_vectors,
- covariate_matrix)
- if not refit:
- lmm_ob.fit()
-
- p_values = []
- t_statistics = []
-
- n = genotype_matrix.shape[0]
- m = genotype_matrix.shape[1]
-
- for counter in range(m):
- x = genotype_matrix[:,counter].reshape((n, 1))
- v = np.isnan(x).reshape((-1,))
- if v.sum():
- keep = True - v
- xs = x[keep,:]
- if xs.var() == 0:
- p_values.append(0)
- t_statistics.append(np.nan)
- continue
-
- print(genotype_matrix.shape,pheno_vector.shape,keep.shape)
-
- pheno_vector = pheno_vector[keep]
- covariate_matrix = covariate_matrix[keep,:]
- kinship_matrix = kinship_matrix[keep,:][:,keep]
- lmm_ob_2 = LMM(pheno_vector,
- kinship_matrix,
- X0=covariate_matrix)
- if refit:
- lmm_ob_2.fit(X=xs)
- else:
- lmm_ob_2.fit()
- ts, ps, beta, betaVar = lmm_ob_2.association(xs, REML=restricted_max_likelihood)
- else:
- if x.var() == 0:
- p_values.append(0)
- t_statistics.append(np.nan)
- continue
-
- if refit:
- lmm_ob.fit(X=x)
- ts, ps, beta, betaVar = lmm_ob.association(x, REML=restricted_max_likelihood)
-
- percent_complete = 45 + int(round((counter/m)*55))
- temp_data.store("percent_complete", percent_complete)
-
- p_values.append(ps)
- t_statistics.append(ts)
-
- return t_statistics, p_values
-
-
-class LMM:
-
- """
- This is a simple version of EMMA/fastLMM.
- The main purpose of this module is to take a phenotype vector (Y), a set of covariates (X) and a kinship matrix (K)
- and to optimize this model by finding the maximum-likelihood estimates for the model parameters.
- There are three model parameters: heritability (h), covariate coefficients (beta) and the total
- phenotypic variance (sigma).
- Heritability as defined here is the proportion of the total variance (sigma) that is attributed to
- the kinship matrix.
-
- For simplicity, we assume that everything being input is a numpy array.
- If this is not the case, the module may throw an error as conversion from list to numpy array
- is not done consistently.
-
- """
- def __init__(self,Y,K,Kva=[],Kve=[],X0=None,verbose=True):
-
- """
- The constructor takes a phenotype vector or array of size n.
- It takes a kinship matrix of size n x n. Kva and Kve can be computed as Kva,Kve = linalg.eigh(K) and cached.
- If they are not provided, the constructor will calculate them.
- X0 is an optional covariate matrix of size n x q, where there are q covariates.
- When this parameter is not provided, the constructor will set X0 to an n x 1 matrix of all ones to represent a mean effect.
- """
-
- if X0 == None: X0 = np.ones(len(Y)).reshape(len(Y),1)
- self.verbose = verbose
-
- #x = Y != -9
- x = True - np.isnan(Y)
- #pdb.set_trace()
- if not x.sum() == len(Y):
- print("Removing %d missing values from Y\n" % ((True - x).sum()))
- if self.verbose: sys.stderr.write("Removing %d missing values from Y\n" % ((True - x).sum()))
- Y = Y[x]
- print("x: ", len(x))
- print("K: ", K.shape)
- #K = K[x,:][:,x]
- X0 = X0[x,:]
- Kva = []
- Kve = []
- self.nonmissing = x
-
- print("this K is:", K.shape, pf(K))
-
- if len(Kva) == 0 or len(Kve) == 0:
- # if self.verbose: sys.stderr.write("Obtaining eigendecomposition for %dx%d matrix\n" % (K.shape[0],K.shape[1]) )
- begin = time.time()
- # Kva,Kve = linalg.eigh(K)
- Kva,Kve = kvakve(K)
- end = time.time()
- if self.verbose: sys.stderr.write("Total time: %0.3f\n" % (end - begin))
- print("sum(Kva),sum(Kve)=",sum(Kva),sum(Kve))
-
- self.K = K
- self.Kva = Kva
- self.Kve = Kve
- print("self.Kva is: ", self.Kva.shape, pf(self.Kva))
- print("self.Kve is: ", self.Kve.shape, pf(self.Kve))
- self.Y = Y
- self.X0 = X0
- self.N = self.K.shape[0]
-
- # ----> Below moved to kinship.kvakve(K)
- # if sum(self.Kva < 1e-6):
- # if self.verbose: sys.stderr.write("Cleaning %d eigen values\n" % (sum(self.Kva < 0)))
- # self.Kva[self.Kva < 1e-6] = 1e-6
-
- self.transform()
-
- def transform(self):
-
- """
- Computes a transformation on the phenotype vector and the covariate matrix.
- The transformation is obtained by left multiplying each parameter by the transpose of the
- eigenvector matrix of K (the kinship).
- """
-
- self.Yt = matrixMult(self.Kve.T, self.Y)
- self.X0t = matrixMult(self.Kve.T, self.X0)
- self.X0t_stack = np.hstack([self.X0t, np.ones((self.N,1))])
- self.q = self.X0t.shape[1]
-
- def getMLSoln(self,h,X):
-
- """
- Obtains the maximum-likelihood estimates for the covariate coefficients (beta),
- the total variance of the trait (sigma) and also passes intermediates that can
- be utilized in other functions. The input parameter h is a value between 0 and 1 and represents
- the heritability or the proportion of the total variance attributed to genetics. The X is the
- covariate matrix.
- """
-
- S = 1.0/(h*self.Kva + (1.0 - h))
- Xt = X.T*S
- XX = matrixMult(Xt,X)
- XX_i = linalg.inv(XX)
- beta = matrixMult(matrixMult(XX_i,Xt),self.Yt)
- Yt = self.Yt - matrixMult(X,beta)
- Q = np.dot(Yt.T*S,Yt)
- sigma = Q * 1.0 / (float(self.N) - float(X.shape[1]))
- return beta,sigma,Q,XX_i,XX
-
- def LL_brent(self,h,X=None,REML=False):
- #brent will not be bounded by the specified bracket.
- # I return a large number if we encounter h < 0 to avoid errors in LL computation during the search.
- if h < 0: return 1e6
- return -self.LL(h,X,stack=False,REML=REML)[0]
-
- def LL(self,h,X=None,stack=True,REML=False):
-
- """
- Computes the log-likelihood for a given heritability (h). If X==None, then the
- default X0t will be used. If X is set and stack=True, then X0t will be matrix concatenated with
- the input X. If stack is false, then X is used in place of X0t in the LL calculation.
- REML is computed by adding additional terms to the standard LL and can be computed by setting REML=True.
- """
-
- if X == None:
- X = self.X0t
- elif stack:
- self.X0t_stack[:,(self.q)] = matrixMult(self.Kve.T,X)[:,0]
- X = self.X0t_stack
-
- n = float(self.N)
- q = float(X.shape[1])
- beta,sigma,Q,XX_i,XX = self.getMLSoln(h,X)
- LL = n*np.log(2*np.pi) + np.log(h*self.Kva + (1.0-h)).sum() + n + n*np.log(1.0/n * Q)
- LL = -0.5 * LL
-
- if REML:
- LL_REML_part = q*np.log(2.0*np.pi*sigma) + np.log(linalg.det(matrixMult(X.T,X))) - np.log(linalg.det(XX))
- LL = LL + 0.5*LL_REML_part
-
- return LL,beta,sigma,XX_i
-
- def getMax(self,H, X=None,REML=False):
-
- """
- Helper functions for .fit(...).
- This function takes a set of LLs computed over a grid and finds possible regions
- containing a maximum. Within these regions, a Brent search is performed to find the
- optimum.
-
- """
- n = len(self.LLs)
- HOpt = []
- for i in range(1,n-2):
- if self.LLs[i-1] < self.LLs[i] and self.LLs[i] > self.LLs[i+1]:
- HOpt.append(optimize.brent(self.LL_brent,args=(X,REML),brack=(H[i-1],H[i+1])))
- if np.isnan(HOpt[-1][0]):
- HOpt[-1][0] = [self.LLs[i-1]]
-
- if len(HOpt) > 1:
- if self.verbose:
- sys.stderr.write("NOTE: Found multiple optima. Returning first...\n")
- return HOpt[0]
- elif len(HOpt) == 1:
- return HOpt[0]
- elif self.LLs[0] > self.LLs[n-1]:
- return H[0]
- else:
- return H[n-1]
-
- def fit(self,X=None,ngrids=100,REML=True):
-
- """
- Finds the maximum-likelihood solution for the heritability (h) given the current parameters.
- X can be passed and will transformed and concatenated to X0t. Otherwise, X0t is used as
- the covariate matrix.
-
- This function calculates the LLs over a grid and then uses .getMax(...) to find the optimum.
- Given this optimum, the function computes the LL and associated ML solutions.
- """
-
- if X == None:
- X = self.X0t
- else:
- #X = np.hstack([self.X0t,matrixMult(self.Kve.T, X)])
- self.X0t_stack[:,(self.q)] = matrixMult(self.Kve.T,X)[:,0]
- X = self.X0t_stack
-
- H = np.array(range(ngrids)) / float(ngrids)
- L = np.array([self.LL(h,X,stack=False,REML=REML)[0] for h in H])
- self.LLs = L
-
- hmax = self.getMax(H,X,REML)
- L,beta,sigma,betaSTDERR = self.LL(hmax,X,stack=False,REML=REML)
-
- self.H = H
- self.optH = hmax
- self.optLL = L
- self.optBeta = beta
- self.optSigma = sigma
-
- return hmax,beta,sigma,L
-
- def association(self,X, h = None, stack=True,REML=True, returnBeta=True):
-
- """
- Calculates association statitics for the SNPs encoded in the vector X of size n.
- If h == None, the optimal h stored in optH is used.
-
- """
- if stack:
- #X = np.hstack([self.X0t,matrixMult(self.Kve.T, X)])
- self.X0t_stack[:,(self.q)] = matrixMult(self.Kve.T,X)[:,0]
- X = self.X0t_stack
-
- if h == None:
- h = self.optH
-
- L,beta,sigma,betaVAR = self.LL(h,X,stack=False,REML=REML)
- q = len(beta)
- ts,ps = self.tstat(beta[q-1],betaVAR[q-1,q-1],sigma,q)
-
- if returnBeta:
- return ts,ps,beta[q-1].sum(),betaVAR[q-1,q-1].sum()*sigma
- return ts,ps
-
- def tstat(self,beta,var,sigma,q):
-
- """
- Calculates a t-statistic and associated p-value given the estimate of beta and its standard error.
- This is actually an F-test, but when only one hypothesis is being performed, it reduces to a t-test.
- """
-
- ts = beta / np.sqrt(var * sigma)
- ps = 2.0*(1.0 - stats.t.cdf(np.abs(ts), self.N-q))
- if not len(ts) == 1 or not len(ps) == 1:
- print("ts=",ts)
- print("ps=",ps)
- raise Exception("Something bad happened :(")
- return ts.sum(),ps.sum()
-
- def plotFit(self,color='b-',title=''):
-
- """
- Simple function to visualize the likelihood space. It takes the LLs
- calcualted over a grid and normalizes them by subtracting off the mean and exponentiating.
- The resulting "probabilities" are normalized to one and plotted against heritability.
- This can be seen as an approximation to the posterior distribuiton of heritability.
-
- For diagnostic purposes this lets you see if there is one distinct maximum or multiple
- and what the variance of the parameter looks like.
- """
- import matplotlib.pyplot as pl
-
- mx = self.LLs.max()
- p = np.exp(self.LLs - mx)
- p = p/p.sum()
-
- pl.plot(self.H,p,color)
- pl.xlabel("Heritability")
- pl.ylabel("Probability of data")
- pl.title(title)
-
-
-def gn2_redis(key,species,new_code=True):
- """
- Invoke pylmm using Redis as a container. new_code runs the new
- version
- """
- json_params = Redis.get(key)
-
- params = json.loads(json_params)
-
- tempdata = temp_data.TempData(params['temp_uuid'])
-
-
- print('pheno', np.array(params['pheno_vector']))
-
- if species == "human" :
- print('kinship', np.array(params['kinship_matrix']))
- ps, ts = run_human(pheno_vector = np.array(params['pheno_vector']),
- covariate_matrix = np.array(params['covariate_matrix']),
- plink_input_file = params['input_file_name'],
- kinship_matrix = np.array(params['kinship_matrix']),
- refit = params['refit'],
- tempdata = tempdata)
- else:
- geno = np.array(params['genotype_matrix'])
- print('geno', geno.shape, geno)
-
- if new_code:
- ps, ts = run_other_new(pheno_vector = np.array(params['pheno_vector']),
- genotype_matrix = geno,
- restricted_max_likelihood = params['restricted_max_likelihood'],
- refit = params['refit'],
- tempdata = tempdata)
- else:
- ps, ts = run_other_old(pheno_vector = np.array(params['pheno_vector']),
- genotype_matrix = geno,
- restricted_max_likelihood = params['restricted_max_likelihood'],
- refit = params['refit'],
- tempdata = tempdata)
-
- results_key = "pylmm:results:" + params['temp_uuid']
-
- json_results = json.dumps(dict(p_values = ps,
- t_stats = ts))
-
- #Pushing json_results into a list where it is the only item because blpop needs a list
- Redis.rpush(results_key, json_results)
- Redis.expire(results_key, 60*60)
- return ps, ts
-
-# This is the main function used by Genenetwork2 (with environment)
-def gn2_main():
- parser = argparse.ArgumentParser(description='Run pyLMM')
- parser.add_argument('-k', '--key')
- parser.add_argument('-s', '--species')
-
- opts = parser.parse_args()
-
- key = opts.key
- species = opts.species
-
- gn2_redis(key,species)
-
-def gn2_load_redis(key,species,kinship,pheno,geno,new_code=True):
- print("Loading Redis from parsed data")
- if kinship == None:
- k = None
- else:
- k = kinship.tolist()
- params = dict(pheno_vector = pheno.tolist(),
- genotype_matrix = geno.tolist(),
- kinship_matrix= k,
- restricted_max_likelihood = True,
- refit = False,
- temp_uuid = "testrun_temp_uuid",
-
- # meta data
- timestamp = datetime.datetime.now().isoformat(),
- )
-
- json_params = json.dumps(params)
- Redis.set(key, json_params)
- Redis.expire(key, 60*60)
-
- return gn2_redis(key,species,new_code)
-
-if __name__ == '__main__':
- print("WARNING: Calling pylmm from lmm.py will become OBSOLETE, use runlmm.py instead!")
- if has_gn2:
- gn2_main()
- else:
- print("Run from runlmm.py instead")
-
-
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/lmm2.py b/wqflask/wqflask/my_pylmm/pyLMM/lmm2.py
deleted file mode 100644
index d4b3ac82..00000000
--- a/wqflask/wqflask/my_pylmm/pyLMM/lmm2.py
+++ /dev/null
@@ -1,410 +0,0 @@
-# pylmm is a python-based linear mixed-model solver with applications to GWAS
-
-# Copyright (C) 2013,2014 Nicholas A. Furlotte (nick.furlotte@gmail.com)
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as
-# published by the Free Software Foundation, either version 3 of the
-# License, or (at your option) any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-
-# You should have received a copy of the GNU Affero General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-import sys
-import time
-import numpy as np
-from scipy.linalg import eigh, inv, det
-import scipy.stats as stats # t-tests
-from scipy import optimize
-from optmatrix import matrixMult
-import kinship
-
-def calculateKinship(W,center=False):
- """
- W is an n x m matrix encoding SNP minor alleles.
-
- This function takes a matrix oF SNPs, imputes missing values with the maf,
- normalizes the resulting vectors and returns the RRM matrix.
- """
- n = W.shape[0]
- m = W.shape[1]
- keep = []
- for i in range(m):
- mn = W[True - np.isnan(W[:,i]),i].mean()
- W[np.isnan(W[:,i]),i] = mn
- vr = W[:,i].var()
- if vr == 0: continue
-
- keep.append(i)
- W[:,i] = (W[:,i] - mn) / np.sqrt(vr)
-
- W = W[:,keep]
- K = matrixMult(W,W.T) * 1.0/float(m)
- if center:
- P = np.diag(np.repeat(1,n)) - 1/float(n) * np.ones((n,n))
- S = np.trace(matrixMult(matrixMult(P,K),P))
- K_n = (n - 1)*K / S
- return K_n
- return K
-
-def GWAS(Y, X, K, Kva=[], Kve=[], X0=None, REML=True, refit=False):
- """
-
- Performs a basic GWAS scan using the LMM. This function
- uses the LMM module to assess association at each SNP and
- does some simple cleanup, such as removing missing individuals
- per SNP and re-computing the eigen-decomp
-
- Y - n x 1 phenotype vector
- X - n x m SNP matrix (genotype matrix)
- K - n x n kinship matrix
- Kva,Kve = linalg.eigh(K) - or the eigen vectors and values for K
- X0 - n x q covariate matrix
- REML - use restricted maximum likelihood
- refit - refit the variance component for each SNP
-
- """
- n = X.shape[0]
- m = X.shape[1]
- prins("Initialize GWAS")
- print("genotype matrix n is:", n)
- print("genotype matrix m is:", m)
-
- if X0 == None:
- X0 = np.ones((n,1))
-
- # Remove missing values in Y and adjust associated parameters
- v = np.isnan(Y)
- if v.sum():
- keep = True - v
- keep = keep.reshape((-1,))
- Y = Y[keep]
- X = X[keep,:]
- X0 = X0[keep,:]
- K = K[keep,:][:,keep]
- Kva = []
- Kve = []
-
- if len(Y) == 0:
- return np.ones(m)*np.nan,np.ones(m)*np.nan
-
- L = LMM(Y,K,Kva,Kve,X0)
- if not refit: L.fit()
-
- PS = []
- TS = []
-
- n = X.shape[0]
- m = X.shape[1]
-
- for i in range(m):
- x = X[:,i].reshape((n,1))
- v = np.isnan(x).reshape((-1,))
- if v.sum():
- keep = True - v
- xs = x[keep,:]
- if xs.var() == 0:
- PS.append(np.nan)
- TS.append(np.nan)
- continue
-
- Ys = Y[keep]
- X0s = X0[keep,:]
- Ks = K[keep,:][:,keep]
- Ls = LMM(Ys,Ks,X0=X0s)
- if refit:
- Ls.fit(X=xs)
- else:
- Ls.fit()
- ts,ps = Ls.association(xs,REML=REML)
- else:
- if x.var() == 0:
- PS.append(np.nan)
- TS.append(np.nan)
- continue
-
- if refit:
- L.fit(X=x)
- ts,ps = L.association(x,REML=REML)
-
- PS.append(ps)
- TS.append(ts)
-
- return TS,PS
-
-class LMM2:
-
- """
- This is a simple version of EMMA/fastLMM.
- The main purpose of this module is to take a phenotype vector (Y), a set of covariates (X) and a kinship matrix (K)
- and to optimize this model by finding the maximum-likelihood estimates for the model parameters.
- There are three model parameters: heritability (h), covariate coefficients (beta) and the total
- phenotypic variance (sigma).
- Heritability as defined here is the proportion of the total variance (sigma) that is attributed to
- the kinship matrix.
-
- For simplicity, we assume that everything being input is a numpy array.
- If this is not the case, the module may throw an error as conversion from list to numpy array
- is not done consistently.
-
- """
- def __init__(self,Y,K,Kva=[],Kve=[],X0=None,verbose=False):
-
- """
- The constructor takes a phenotype vector or array Y of size n.
- It takes a kinship matrix K of size n x n. Kva and Kve can be computed as Kva,Kve = linalg.eigh(K) and cached.
- If they are not provided, the constructor will calculate them.
- X0 is an optional covariate matrix of size n x q, where there are q covariates.
- When this parameter is not provided, the constructor will set X0 to an n x 1 matrix of all ones to represent a mean effect.
- """
-
- if X0 == None:
- X0 = np.ones(len(Y)).reshape(len(Y),1)
- self.verbose = verbose
-
- x = True - np.isnan(Y)
- x = x.reshape(-1,)
- if not x.sum() == len(Y):
- if self.verbose: sys.stderr.write("Removing %d missing values from Y\n" % ((True - x).sum()))
- Y = Y[x]
- K = K[x,:][:,x]
- X0 = X0[x,:]
- Kva = []
- Kve = []
- self.nonmissing = x
-
- print("this K is:", K.shape, K)
-
- if len(Kva) == 0 or len(Kve) == 0:
- # if self.verbose: sys.stderr.write("Obtaining eigendecomposition for %dx%d matrix\n" % (K.shape[0],K.shape[1]) )
- begin = time.time()
- # Kva,Kve = linalg.eigh(K)
- Kva,Kve = kinship.kvakve(K)
- end = time.time()
- if self.verbose: sys.stderr.write("Total time: %0.3f\n" % (end - begin))
- print("sum(Kva),sum(Kve)=",sum(Kva),sum(Kve))
-
- self.K = K
- self.Kva = Kva
- self.Kve = Kve
- self.N = self.K.shape[0]
- self.Y = Y.reshape((self.N,1))
- self.X0 = X0
-
- if sum(self.Kva < 1e-6):
- if self.verbose: sys.stderr.write("Cleaning %d eigen values\n" % (sum(self.Kva < 0)))
- self.Kva[self.Kva < 1e-6] = 1e-6
-
- self.transform()
-
- def transform(self):
-
- """
- Computes a transformation on the phenotype vector and the covariate matrix.
- The transformation is obtained by left multiplying each parameter by the transpose of the
- eigenvector matrix of K (the kinship).
- """
-
- self.Yt = matrixMult(self.Kve.T, self.Y)
- self.X0t = matrixMult(self.Kve.T, self.X0)
- self.X0t_stack = np.hstack([self.X0t, np.ones((self.N,1))])
- self.q = self.X0t.shape[1]
-
- def getMLSoln(self,h,X):
-
- """
- Obtains the maximum-likelihood estimates for the covariate coefficients (beta),
- the total variance of the trait (sigma) and also passes intermediates that can
- be utilized in other functions. The input parameter h is a value between 0 and 1 and represents
- the heritability or the proportion of the total variance attributed to genetics. The X is the
- covariate matrix.
- """
-
- S = 1.0/(h*self.Kva + (1.0 - h))
- Xt = X.T*S
- XX = matrixMult(Xt,X)
- XX_i = inv(XX)
- beta = matrixMult(matrixMult(XX_i,Xt),self.Yt)
- Yt = self.Yt - matrixMult(X,beta)
- Q = np.dot(Yt.T*S,Yt)
- sigma = Q * 1.0 / (float(self.N) - float(X.shape[1]))
- return beta,sigma,Q,XX_i,XX
-
- def LL_brent(self,h,X=None,REML=False):
- #brent will not be bounded by the specified bracket.
- # I return a large number if we encounter h < 0 to avoid errors in LL computation during the search.
- if h < 0: return 1e6
- return -self.LL(h,X,stack=False,REML=REML)[0]
-
- def LL(self,h,X=None,stack=True,REML=False):
-
- """
- Computes the log-likelihood for a given heritability (h). If X==None, then the
- default X0t will be used. If X is set and stack=True, then X0t will be matrix concatenated with
- the input X. If stack is false, then X is used in place of X0t in the LL calculation.
- REML is computed by adding additional terms to the standard LL and can be computed by setting REML=True.
- """
-
- if X == None: X = self.X0t
- elif stack:
- self.X0t_stack[:,(self.q)] = matrixMult(self.Kve.T,X)[:,0]
- X = self.X0t_stack
-
- n = float(self.N)
- q = float(X.shape[1])
- beta,sigma,Q,XX_i,XX = self.getMLSoln(h,X)
- LL = n*np.log(2*np.pi) + np.log(h*self.Kva + (1.0-h)).sum() + n + n*np.log(1.0/n * Q)
- LL = -0.5 * LL
-
- if REML:
- LL_REML_part = q*np.log(2.0*np.pi*sigma) + np.log(det(matrixMult(X.T,X))) - np.log(det(XX))
- LL = LL + 0.5*LL_REML_part
-
-
- LL = LL.sum()
- return LL,beta,sigma,XX_i
-
- def getMax(self,H, X=None,REML=False):
-
- """
- Helper functions for .fit(...).
- This function takes a set of LLs computed over a grid and finds possible regions
- containing a maximum. Within these regions, a Brent search is performed to find the
- optimum.
-
- """
- n = len(self.LLs)
- HOpt = []
- for i in range(1,n-2):
- if self.LLs[i-1] < self.LLs[i] and self.LLs[i] > self.LLs[i+1]:
- HOpt.append(optimize.brent(self.LL_brent,args=(X,REML),brack=(H[i-1],H[i+1])))
- if np.isnan(HOpt[-1]): HOpt[-1] = H[i-1]
- #if np.isnan(HOpt[-1]): HOpt[-1] = self.LLs[i-1]
- #if np.isnan(HOpt[-1][0]): HOpt[-1][0] = [self.LLs[i-1]]
-
- if len(HOpt) > 1:
- if self.verbose: sys.stderr.write("NOTE: Found multiple optima. Returning first...\n")
- return HOpt[0]
- elif len(HOpt) == 1: return HOpt[0]
- elif self.LLs[0] > self.LLs[n-1]: return H[0]
- else: return H[n-1]
-
-
- def fit(self,X=None,ngrids=100,REML=True):
-
- """
- Finds the maximum-likelihood solution for the heritability (h) given the current parameters.
- X can be passed and will transformed and concatenated to X0t. Otherwise, X0t is used as
- the covariate matrix.
-
- This function calculates the LLs over a grid and then uses .getMax(...) to find the optimum.
- Given this optimum, the function computes the LL and associated ML solutions.
- """
-
- if X == None: X = self.X0t
- else:
- #X = np.hstack([self.X0t,matrixMult(self.Kve.T, X)])
- self.X0t_stack[:,(self.q)] = matrixMult(self.Kve.T,X)[:,0]
- X = self.X0t_stack
-
- H = np.array(range(ngrids)) / float(ngrids)
- L = np.array([self.LL(h,X,stack=False,REML=REML)[0] for h in H])
- self.LLs = L
-
- hmax = self.getMax(H,X,REML)
- L,beta,sigma,betaSTDERR = self.LL(hmax,X,stack=False,REML=REML)
-
- self.H = H
- self.optH = hmax.sum()
- self.optLL = L
- self.optBeta = beta
- self.optSigma = sigma.sum()
-
- return hmax,beta,sigma,L
-
- def association(self,X,h=None,stack=True,REML=True,returnBeta=False):
- """
- Calculates association statitics for the SNPs encoded in the vector X of size n.
- If h == None, the optimal h stored in optH is used.
-
- """
- if False:
- print "X=",X
- print "h=",h
- print "q=",self.q
- print "self.Kve=",self.Kve
- print "X0t_stack=",self.X0t_stack.shape,self.X0t_stack
-
- if stack:
- # X = np.hstack([self.X0t,matrixMult(self.Kve.T, X)])
- m = matrixMult(self.Kve.T,X)
- # print "m=",m
- m = m[:,0]
- self.X0t_stack[:,(self.q)] = m
- X = self.X0t_stack
-
- if h == None: h = self.optH
-
- L,beta,sigma,betaVAR = self.LL(h,X,stack=False,REML=REML)
- q = len(beta)
- ts,ps = self.tstat(beta[q-1],betaVAR[q-1,q-1],sigma,q)
-
- if returnBeta: return ts,ps,beta[q-1].sum(),betaVAR[q-1,q-1].sum()*sigma
- return ts,ps
-
- def tstat(self,beta,var,sigma,q,log=False):
-
- """
- Calculates a t-statistic and associated p-value given the estimate of beta and its standard error.
- This is actually an F-test, but when only one hypothesis is being performed, it reduces to a t-test.
- """
-
- ts = beta / np.sqrt(var * sigma)
- #ps = 2.0*(1.0 - stats.t.cdf(np.abs(ts), self.N-q))
- # sf == survival function - this is more accurate -- could also use logsf if the precision is not good enough
- if log:
- ps = 2.0 + (stats.t.logsf(np.abs(ts), self.N-q))
- else:
- ps = 2.0*(stats.t.sf(np.abs(ts), self.N-q))
- if not len(ts) == 1 or not len(ps) == 1:
- raise Exception("Something bad happened :(")
- return ts.sum(),ps.sum()
-
- def plotFit(self,color='b-',title=''):
-
- """
- Simple function to visualize the likelihood space. It takes the LLs
- calcualted over a grid and normalizes them by subtracting off the mean and exponentiating.
- The resulting "probabilities" are normalized to one and plotted against heritability.
- This can be seen as an approximation to the posterior distribuiton of heritability.
-
- For diagnostic purposes this lets you see if there is one distinct maximum or multiple
- and what the variance of the parameter looks like.
- """
- import matplotlib.pyplot as pl
-
- mx = self.LLs.max()
- p = np.exp(self.LLs - mx)
- p = p/p.sum()
-
- pl.plot(self.H,p,color)
- pl.xlabel("Heritability")
- pl.ylabel("Probability of data")
- pl.title(title)
-
- def meanAndVar(self):
-
- mx = self.LLs.max()
- p = np.exp(self.LLs - mx)
- p = p/p.sum()
-
- mn = (self.H * p).sum()
- vx = ((self.H - mn)**2 * p).sum()
-
- return mn,vx
-
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/optmatrix.py b/wqflask/wqflask/my_pylmm/pyLMM/optmatrix.py
deleted file mode 100644
index 5c71db6a..00000000
--- a/wqflask/wqflask/my_pylmm/pyLMM/optmatrix.py
+++ /dev/null
@@ -1,55 +0,0 @@
-import sys
-import time
-import numpy as np
-from numpy.distutils.system_info import get_info;
-from scipy import linalg
-from scipy import optimize
-from scipy import stats
-
-useNumpy = None
-hasBLAS = None
-
-def matrix_initialize(useBLAS=True):
- global useNumpy # module based variable
- if useBLAS and useNumpy == None:
- print get_info('blas_opt')
- try:
- linalg.fblas
- sys.stderr.write("INFO: using linalg.fblas\n")
- useNumpy = False
- hasBLAS = True
- except AttributeError:
- sys.stderr.write("WARNING: linalg.fblas not found, using numpy.dot instead!\n")
- useNumpy = True
- else:
- sys.stderr.write("INFO: using numpy.dot\n")
- useNumpy=True
-
-def matrixMult(A,B):
- global useNumpy # module based variable
-
- if useNumpy:
- return np.dot(A,B)
-
- # If the matrices are in Fortran order then the computations will be faster
- # when using dgemm. Otherwise, the function will copy the matrix and that takes time.
- if not A.flags['F_CONTIGUOUS']:
- AA = A.T
- transA = True
- else:
- AA = A
- transA = False
-
- if not B.flags['F_CONTIGUOUS']:
- BB = B.T
- transB = True
- else:
- BB = B
- transB = False
-
- return linalg.fblas.dgemm(alpha=1.,a=AA,b=BB,trans_a=transA,trans_b=transB)
-
-def matrixMultT(M):
- # res = np.dot(W,W.T)
- # return linalg.fblas.dgemm(alpha=1.,a=M.T,b=M.T,trans_a=True,trans_b=False)
- return matrixMult(M,M.T)
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/phenotype.py b/wqflask/wqflask/my_pylmm/pyLMM/phenotype.py
deleted file mode 100644
index 682ba371..00000000
--- a/wqflask/wqflask/my_pylmm/pyLMM/phenotype.py
+++ /dev/null
@@ -1,40 +0,0 @@
-# Phenotype routines
-
-# Copyright (C) 2013 Nicholas A. Furlotte (nick.furlotte@gmail.com)
-# Copyright (C) 2015 Pjotr Prins (pjotr.prins@thebird.nl)
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as
-# published by the Free Software Foundation, either version 3 of the
-# License, or (at your option) any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-
-# You should have received a copy of the GNU Affero General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-import sys
-import numpy as np
-
-def remove_missing(y,g,verbose=False):
- """
- Remove missing data from matrices, make sure the genotype data has
- individuals as rows
- """
- assert(y!=None)
- assert(y.shape[0] == g.shape[0])
-
- y1 = y
- g1 = g
- v = np.isnan(y)
- keep = True - v
- if v.sum():
- if verbose:
- sys.stderr.write("runlmm.py: Cleaning the phenotype vector and genotype matrix by removing %d individuals...\n" % (v.sum()))
- y1 = y[keep]
- g1 = g[keep,:]
- return y1,g1,keep
-
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/plink.py b/wqflask/wqflask/my_pylmm/pyLMM/plink.py
deleted file mode 100644
index 7bd2df91..00000000
--- a/wqflask/wqflask/my_pylmm/pyLMM/plink.py
+++ /dev/null
@@ -1,107 +0,0 @@
-# Plink module
-#
-# Copyright (C) 2015 Pjotr Prins (pjotr.prins@thebird.nl)
-# Some of the BED file parsing came from pylmm:
-# Copyright (C) 2013 Nicholas A. Furlotte (nick.furlotte@gmail.com)
-
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as
-# published by the Free Software Foundation, either version 3 of the
-# License, or (at your option) any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-
-# You should have received a copy of the GNU Affero General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-# According to the PLINK information
-
-# Parse a textual BIM file and return the contents as a list of tuples
-#
-# Extended variant information file accompanying a .bed binary genotype table.
-#
-# A text file with no header line, and one line per variant with the following six fields:
-#
-# Chromosome code (either an integer, or 'X'/'Y'/'XY'/'MT'; '0' indicates unknown) or name
-# Variant identifier
-# Position in morgans or centimorgans (safe to use dummy value of '0')
-# Base-pair coordinate (normally 1-based, but 0 ok; limited to 231-2)
-# Allele 1 (corresponding to clear bits in .bed; usually minor)
-# Allele 2 (corresponding to set bits in .bed; usually major)
-#
-# Allele codes can contain more than one character. Variants with negative bp coordinates are ignored by PLINK. Example
-#
-# 1 mm37-1-3125499 0 3125499 1 2
-# 1 mm37-1-3125701 0 3125701 1 2
-# 1 mm37-1-3187481 0 3187481 1 2
-
-import struct
-# import numpy as np
-
-def readbim(fn):
- res = []
- for line in open(fn):
- list = line.split()
- if len([True for e in list if e == 'nan']) == 0:
- res.append( (list[0],list[1],int(list[2]),int(list[3]),int(list[4]),int(list[5])) )
- else:
- res.append( (list[0],list[1],list[2],float('nan'),float('nan'),float('nan')) )
- return res
-
-# .bed (PLINK binary biallelic genotype table)
-#
-# Primary representation of genotype calls at biallelic variants. Must
-# be accompanied by .bim and .fam files. Basically contains num SNP
-# blocks containing IND (compressed 4 IND into a byte)
-#
-# Since it is a biallelic format it supports for every individual
-# whether the first allele is homozygous (b00), the second allele is
-# homozygous (b11), it is heterozygous (b10) or that it is missing
-# (b01).
-
-# http://pngu.mgh.harvard.edu/~purcell/plink2/formats.html#bed
-# http://pngu.mgh.harvard.edu/~purcell/plink2/formats.html#fam
-# http://pngu.mgh.harvard.edu/~purcell/plink2/formats.html#bim
-
-def readbed(fn,inds,encoding,func=None):
-
- # For every SNP block fetch the individual genotypes using values
- # 0.0 and 1.0 for homozygous and 0.5 for heterozygous alleles
- def fetchGenotypes(X):
- # D = { \
- # '00': 0.0, \
- # '10': 0.5, \
- # '11': 1.0, \
- # '01': float('nan') \
- # }
-
- Didx = { '00': 0, '10': 1, '11': 2, '01': 3 }
- G = []
- for x in X:
- if not len(x) == 10:
- xx = x[2:]
- x = '0b' + '0'*(8 - len(xx)) + xx
- a,b,c,d = (x[8:],x[6:8],x[4:6],x[2:4])
- L = [encoding[Didx[y]] for y in [a,b,c,d]]
- G += L
- G = G[:inds]
- # G = np.array(G)
- return G
-
- bytes = inds / 4 + (inds % 4 and 1 or 0)
- format = 'c'*bytes
- count = 0
- with open(fn,'rb') as f:
- magic = f.read(3)
- assert( ":".join("{:02x}".format(ord(c)) for c in magic) == "6c:1b:01")
- while True:
- count += 1
- X = f.read(bytes)
- if not X:
- return(count-1)
- XX = [bin(ord(x)) for x in struct.unpack(format,X)]
- xs = fetchGenotypes(XX)
- func(count,xs)
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/runlmm.py b/wqflask/wqflask/my_pylmm/pyLMM/runlmm.py
deleted file mode 100644
index 324c4f2c..00000000
--- a/wqflask/wqflask/my_pylmm/pyLMM/runlmm.py
+++ /dev/null
@@ -1,212 +0,0 @@
-# This is the LMM runner that calls the possible methods using command line
-# switches. It acts as a multiplexer where all the invocation complexity
-# is kept outside the main LMM routines.
-#
-# Copyright (C) 2015 Pjotr Prins (pjotr.prins@thebird.nl)
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as
-# published by the Free Software Foundation, either version 3 of the
-# License, or (at your option) any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-
-# You should have received a copy of the GNU Affero General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-from optparse import OptionParser
-import sys
-import tsvreader
-import numpy as np
-from lmm import gn2_load_redis, calculate_kinship_old
-from kinship import kinship, kinship_full
-import genotype
-import phenotype
-
-usage = """
-python runlmm.py [options] command
-
- runlmm.py processing multiplexer reads standardised input formats
- and calls the different routines (writes to stdout)
-
- Current commands are:
-
- parse : only parse input files
- redis : use Redis to call into GN2
- kinship : calculate (new) kinship matrix
-
- try --help for more information
-"""
-
-
-parser = OptionParser(usage=usage)
-# parser.add_option("-f", "--file", dest="input file",
-# help="In", metavar="FILE")
-parser.add_option("--kinship",dest="kinship",
- help="Kinship file format 1.0")
-parser.add_option("--pheno",dest="pheno",
- help="Phenotype file format 1.0")
-parser.add_option("--geno",dest="geno",
- help="Genotype file format 1.0")
-parser.add_option("--maf-normalization",
- action="store_true", dest="maf_normalization", default=False,
- help="Apply MAF genotype normalization")
-parser.add_option("--genotype-normalization",
- action="store_true", dest="genotype_normalization", default=False,
- help="Force genotype normalization")
-parser.add_option("--remove-missing-phenotypes",
- action="store_true", dest="remove_missing_phenotypes", default=False,
- help="Remove missing phenotypes")
-parser.add_option("-q", "--quiet",
- action="store_false", dest="verbose", default=True,
- help="don't print status messages to stdout")
-parser.add_option("--blas", action="store_true", default=False, dest="useBLAS", help="Use BLAS instead of numpy matrix multiplication")
-parser.add_option("-t", "--threads",
- type="int", dest="numThreads",
- help="Threads to use")
-parser.add_option("--saveKvaKve",
- action="store_true", dest="saveKvaKve", default=False,
- help="Testing mode")
-parser.add_option("--test",
- action="store_true", dest="testing", default=False,
- help="Testing mode")
-parser.add_option("--test-kinship",
- action="store_true", dest="test_kinship", default=False,
- help="Testing mode for Kinship calculation")
-
-(options, args) = parser.parse_args()
-
-if len(args) != 1:
- print usage
- sys.exit(1)
-
-cmd = args[0]
-print "Command: ",cmd
-
-k = None
-y = None
-g = None
-
-if options.kinship:
- k = tsvreader.kinship(options.kinship)
- print k.shape
-
-if options.pheno:
- y = tsvreader.pheno(options.pheno)
- print y.shape
-
-if options.geno:
- g = tsvreader.geno(options.geno)
- print g.shape
-
-if cmd == 'redis_new':
- # The main difference between redis_new and redis is that missing
- # phenotypes are handled by the first
- Y = y
- G = g
- print "Original G",G.shape, "\n", G
-
- gt = G.T
- G = None
- ps, ts = gn2_load_redis('testrun','other',k,Y,gt,new_code=True)
- print np.array(ps)
- print len(ps),sum(ps)
- # Test results
- p1 = round(ps[0],4)
- p2 = round(ps[-1],4)
- sys.stderr.write(options.geno+"\n")
- if options.geno == 'data/small.geno':
- assert p1==0.0708, "p1=%f" % p1
- assert p2==0.1417, "p2=%f" % p2
- if options.geno == 'data/small_na.geno':
- assert p1==0.0897, "p1=%f" % p1
- assert p2==0.0405, "p2=%f" % p2
- if options.geno == 'data/test8000.geno':
- # assert p1==0.8984, "p1=%f" % p1
- # assert p2==0.9621, "p2=%f" % p2
- assert round(sum(ps)) == 4070
- assert len(ps) == 8000
-elif cmd == 'redis':
- # Emulating the redis setup of GN2
- G = g
- print "Original G",G.shape, "\n", G
- if y != None and options.remove_missing_phenotypes:
- gnt = np.array(g).T
- Y,g,keep = phenotype.remove_missing(y,g.T,options.verbose)
- G = g.T
- print "Removed missing phenotypes",G.shape, "\n", G
- else:
- Y = y
- if options.maf_normalization:
- G = np.apply_along_axis( genotype.replace_missing_with_MAF, axis=0, arr=g )
- print "MAF replacements: \n",G
- if options.genotype_normalization:
- G = np.apply_along_axis( genotype.normalize, axis=1, arr=G)
- g = None
- gnt = None
-
- gt = G.T
- G = None
- ps, ts = gn2_load_redis('testrun','other',k,Y,gt, new_code=False)
- print np.array(ps)
- print len(ps),sum(ps)
- # Test results 4070.02346579
- p1 = round(ps[0],4)
- p2 = round(ps[-1],4)
- sys.stderr.write(options.geno+"\n")
- if options.geno == 'data/small.geno':
- assert p1==0.0708, "p1=%f" % p1
- assert p2==0.1417, "p2=%f" % p2
- if options.geno == 'data/small_na.geno':
- assert p1==0.0897, "p1=%f" % p1
- assert p2==0.0405, "p2=%f" % p2
- if options.geno == 'data/test8000.geno':
- assert round(sum(ps)) == 4070
- assert len(ps) == 8000
-elif cmd == 'kinship':
- G = g
- print "Original G",G.shape, "\n", G
- if y != None and options.remove_missing_phenotypes:
- gnt = np.array(g).T
- Y,g = phenotype.remove_missing(y,g.T,options.verbose)
- G = g.T
- print "Removed missing phenotypes",G.shape, "\n", G
- if options.maf_normalization:
- G = np.apply_along_axis( genotype.replace_missing_with_MAF, axis=0, arr=g )
- print "MAF replacements: \n",G
- if options.genotype_normalization:
- G = np.apply_along_axis( genotype.normalize, axis=1, arr=G)
- g = None
- gnt = None
-
- if options.test_kinship:
- K = kinship_full(np.copy(G))
- print "Genotype",G.shape, "\n", G
- print "first Kinship method",K.shape,"\n",K
- k1 = round(K[0][0],4)
- K2,G = calculate_kinship_old(np.copy(G).T,temp_data=None)
- print "Genotype",G.shape, "\n", G
- print "GN2 Kinship method",K2.shape,"\n",K2
- k2 = round(K2[0][0],4)
-
- print "Genotype",G.shape, "\n", G
- K3 = kinship(G.T)
- print "third Kinship method",K3.shape,"\n",K3
- sys.stderr.write(options.geno+"\n")
- k3 = round(K3[0][0],4)
- if options.geno == 'data/small.geno':
- assert k1==0.8, "k1=%f" % k1
- assert k2==0.7939, "k2=%f" % k2
- assert k3==0.7939, "k3=%f" % k3
- if options.geno == 'data/small_na.geno':
- assert k1==0.8333, "k1=%f" % k1
- assert k2==0.7172, "k2=%f" % k2
- assert k3==0.7172, "k3=%f" % k3
- if options.geno == 'data/test8000.geno':
- assert k3==1.4352, "k3=%f" % k3
-
-else:
- print "Doing nothing"
diff --git a/wqflask/wqflask/my_pylmm/pyLMM/tsvreader.py b/wqflask/wqflask/my_pylmm/pyLMM/tsvreader.py
deleted file mode 100644
index b4027fa3..00000000
--- a/wqflask/wqflask/my_pylmm/pyLMM/tsvreader.py
+++ /dev/null
@@ -1,76 +0,0 @@
-# Standard file readers
-#
-# Copyright (C) 2015 Pjotr Prins (pjotr.prins@thebird.nl)
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as
-# published by the Free Software Foundation, either version 3 of the
-# License, or (at your option) any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-
-# You should have received a copy of the GNU Affero General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-import sys
-import os
-import numpy as np
-import csv
-
-def kinship(fn):
- K1 = []
- print fn
- with open(fn,'r') as tsvin:
- assert(tsvin.readline().strip() == "# Kinship format version 1.0")
- tsvin.readline()
- tsvin.readline()
- tsv = csv.reader(tsvin, delimiter='\t')
- for row in tsv:
- ns = np.genfromtxt(row[1:])
- K1.append(ns) # <--- slow
- K = np.array(K1)
- return K
-
-def pheno(fn):
- Y1 = []
- print fn
- with open(fn,'r') as tsvin:
- assert(tsvin.readline().strip() == "# Phenotype format version 1.0")
- tsvin.readline()
- tsvin.readline()
- tsvin.readline()
- tsv = csv.reader(tsvin, delimiter='\t')
- for row in tsv:
- ns = np.genfromtxt(row[1:])
- Y1.append(ns) # <--- slow
- Y = np.array(Y1)
- return Y
-
-def geno(fn):
- G1 = []
- hab_mapper = {'A':0,'H':1,'B':2,'-':3}
- pylmm_mapper = [ 0.0, 0.5, 1.0, float('nan') ]
-
- print fn
- with open(fn,'r') as tsvin:
- assert(tsvin.readline().strip() == "# Genotype format version 1.0")
- tsvin.readline()
- tsvin.readline()
- tsvin.readline()
- tsvin.readline()
- tsv = csv.reader(tsvin, delimiter='\t')
- for row in tsv:
- # print(row)
- id = row[0]
- gs = list(row[1])
- # print id,gs
- gs2 = [pylmm_mapper[hab_mapper[g]] for g in gs]
- # print id,gs2
- # ns = np.genfromtxt(row[1:])
- G1.append(gs2) # <--- slow
- G = np.array(G1)
- return G
-
diff --git a/wqflask/wqflask/search_results.py b/wqflask/wqflask/search_results.py
index df1edb13..12ea44d8 100755
--- a/wqflask/wqflask/search_results.py
+++ b/wqflask/wqflask/search_results.py
@@ -77,10 +77,15 @@ class SearchResultPage(object):
self.trait_type = kw['trait_type']
self.quick_search()
else:
- self.results = []
print("kw is:", kw)
- #self.quick_search = False
- self.search_terms = kw['search_terms']
+ if kw['search_terms_or']:
+ self.and_or = "or"
+ self.search_terms = kw['search_terms_or']
+ else:
+ self.and_or = "and"
+ self.search_terms = kw['search_terms_and']
+ self.search_term_exists = True
+ self.results = []
if kw['type'] == "Phenotypes":
dataset_type = "Publish"
elif kw['type'] == "Genotypes":
@@ -114,8 +119,7 @@ class SearchResultPage(object):
print("foo locals are:", locals())
trait_id = result[0]
- this_trait = GeneralTrait(dataset=self.dataset, name=trait_id)
- this_trait.retrieve_info(get_qtl_info=True)
+ this_trait = GeneralTrait(dataset=self.dataset, name=trait_id, get_qtl_info=True)
self.trait_list.append(this_trait)
self.dataset.get_trait_info(self.trait_list, species)
@@ -222,60 +226,61 @@ class SearchResultPage(object):
if len(self.search_terms) > 1:
combined_from_clause = ""
combined_where_clause = ""
+ previous_from_clauses = [] #The same table can't be referenced twice in the from clause
for i, a_search in enumerate(self.search_terms):
- print("[kodak] item is:", pf(a_search))
- search_term = a_search['search_term']
- search_operator = a_search['separator']
- if a_search['key']:
- search_type = a_search['key'].upper()
+ the_search = self.get_search_ob(a_search)
+ if the_search != None:
+ get_from_clause = getattr(the_search, "get_from_clause", None)
+ if callable(get_from_clause):
+ from_clause = the_search.get_from_clause()
+ if from_clause in previous_from_clauses:
+ pass
+ else:
+ previous_from_clauses.append(from_clause)
+ combined_from_clause += from_clause
+ where_clause = the_search.get_where_clause()
+ combined_where_clause += "(" + where_clause + ")"
+ if (i+1) < len(self.search_terms):
+ if self.and_or == "and":
+ combined_where_clause += "AND"
+ else:
+ combined_where_clause += "OR"
else:
- # We fall back to the dataset type as the key to get the right object
- search_type = self.dataset.type
-
- print("search_type is:", pf(search_type))
-
- search_ob = do_search.DoSearch.get_search(search_type)
- search_class = getattr(do_search, search_ob)
- the_search = search_class(search_term,
- search_operator,
- self.dataset,
- )
-
- #search_query = the_search.get_final_query()
-
- get_from_clause = getattr(the_search, "get_from_clause", None)
- if callable(get_from_clause):
- from_clause = the_search.get_from_clause()
- combined_from_clause += from_clause
- where_clause = the_search.get_where_clause()
- combined_where_clause += "(" + where_clause + ")"
- if (i+1) < len(self.search_terms):
- combined_where_clause += "AND"
-
- results = the_search.run_combined(combined_from_clause, combined_where_clause)
- self.results.extend(results)
-
+ self.search_term_exists = False
+ if self.search_term_exists:
+ combined_where_clause = "(" + combined_where_clause + ")"
+ final_query = the_search.compile_final_query(combined_from_clause, combined_where_clause)
+ results = the_search.execute(final_query)
+ self.results.extend(results)
else:
for a_search in self.search_terms:
- print("[kodak] item is:", pf(a_search))
- search_term = a_search['search_term']
- search_operator = a_search['separator']
- if a_search['key']:
- search_type = a_search['key'].upper()
+ the_search = self.get_search_ob(a_search)
+ if the_search != None:
+ self.results.extend(the_search.run())
else:
- # We fall back to the dataset type as the key to get the right object
- search_type = self.dataset.type
-
- print("search_type is:", pf(search_type))
-
- search_ob = do_search.DoSearch.get_search(search_type)
- search_class = getattr(do_search, search_ob)
- print("search_class is: ", pf(search_class))
- the_search = search_class(search_term,
- search_operator,
- self.dataset,
- )
- self.results.extend(the_search.run())
- #print("in the search results are:", self.results)
-
- self.header_fields = the_search.header_fields
+ self.search_term_exists = False
+
+ if the_search != None:
+ self.header_fields = the_search.header_fields
+
+ def get_search_ob(self, a_search):
+ print("[kodak] item is:", pf(a_search))
+ search_term = a_search['search_term']
+ search_operator = a_search['separator']
+ search_type = {}
+ search_type['dataset_type'] = self.dataset.type
+ if a_search['key']:
+ search_type['key'] = a_search['key'].upper()
+ print("search_type is:", pf(search_type))
+
+ search_ob = do_search.DoSearch.get_search(search_type)
+ if search_ob:
+ search_class = getattr(do_search, search_ob)
+ print("search_class is: ", pf(search_class))
+ the_search = search_class(search_term,
+ search_operator,
+ self.dataset,
+ )
+ return the_search
+ else:
+ return None
diff --git a/wqflask/wqflask/show_trait/SampleList.py b/wqflask/wqflask/show_trait/SampleList.py
index d196e722..367bd2dd 100755
--- a/wqflask/wqflask/show_trait/SampleList.py
+++ b/wqflask/wqflask/show_trait/SampleList.py
@@ -10,6 +10,8 @@ import numpy as np
from scipy import stats
from pprint import pformat as pf
+import itertools
+
class SampleList(object):
def __init__(self,
dataset,
@@ -24,11 +26,14 @@ class SampleList(object):
self.header = header
self.sample_list = [] # The actual list
+ self.sample_attribute_values = {}
self.get_attributes()
-
print("camera: attributes are:", pf(self.attributes))
+ if self.this_trait and self.dataset and self.dataset.type == 'ProbeSet':
+ self.get_extra_attribute_values()
+
for counter, sample_name in enumerate(sample_names, 1):
sample_name = sample_name.replace("_2nd_", "")
@@ -55,15 +60,14 @@ class SampleList(object):
sample.this_id = "Other_" + str(counter)
#### For extra attribute columns; currently only used by several datasets - Zach
- if self.this_trait and self.dataset and self.dataset.type == 'ProbeSet':
- sample.extra_attributes = self.get_extra_attribute_values(sample_name)
+ if self.sample_attribute_values:
+ sample.extra_attributes = self.sample_attribute_values.get(sample_name, {})
print("sample.extra_attributes is", pf(sample.extra_attributes))
self.sample_list.append(sample)
print("self.attributes is", pf(self.attributes))
- self.get_z_scores()
self.do_outliers()
#do_outliers(the_samples)
print("*the_samples are [%i]: %s" % (len(self.sample_list), pf(self.sample_list)))
@@ -74,50 +78,6 @@ class SampleList(object):
def __repr__(self):
return "<SampleList> --> %s" % (pf(self.__dict__))
- #def get_z_scores(self):
- # values = [sample.value for sample in self.sample_list if sample.value != None]
- # dataX = values[:]
- # dataX.sort(webqtlUtil.cmpOrder)
- # dataY=webqtlUtil.U(len(dataX))
- # z_scores=map(webqtlUtil.inverseCumul, dataY)
- #
- # print("self.sample_list:", [sample for sample in self.sample_list if sample.value != None])
- # print("z_scores:", len(z_scores))
- # for i, sample in enumerate([sample for sample in self.sample_list if sample.value != None]):
- # print("sample is:", sample)
- # sample.z_score = z_scores[i]
-
-
- #def get_z_scores(self):
- # values = [sample.value for sample in self.sample_list if sample.value != None]
- # z_scores = z_score(values)
- #
- # print("self.sample_list:", [sample for sample in self.sample_list if sample.value != None])
- # print("z_scores:", len(z_scores))
- # for i, sample in enumerate([sample for sample in self.sample_list if sample.value != None]):
- # print("sample is:", sample)
- # sample.z_score = z_scores[i]
-
-
- def get_z_scores(self):
-
-
- values = [sample.value for sample in self.sample_list if sample.value != None]
- numpy_array = np.array(values)
- prob_plot = stats.probplot(numpy_array)[0]
- print("prob_plot:", prob_plot)
-
- values = prob_plot[1]
- z_scores = prob_plot[0]
- print("z_scores:", z_scores)
-
-
- print("self.sample_list:", [sample for sample in self.sample_list if sample.value != None])
- for i, sample in enumerate([sample for sample in self.sample_list if sample.value != None]):
- print("sample is:", sample)
- sample.z_score = z_scores[i]
- sample.prob_plot_value = values[i]
-
def do_outliers(self):
values = [sample.value for sample in self.sample_list if sample.value != None]
upper_bound, lower_bound = Plot.find_outliers(values)
@@ -131,75 +91,54 @@ class SampleList(object):
else:
sample.outlier = False
-
def get_attributes(self):
"""Finds which extra attributes apply to this dataset"""
-
- #ZS: Id and name values for this trait's extra attributes
- case_attributes = g.db.execute('''SELECT CaseAttribute.Id, CaseAttribute.Name
- FROM CaseAttribute, CaseAttributeXRef
- WHERE CaseAttributeXRef.ProbeSetFreezeId = %s AND
- CaseAttribute.Id = CaseAttributeXRef.CaseAttributeId
- group by CaseAttributeXRef.CaseAttributeId''',
- (str(self.dataset.id),))
+ # Get attribute names and distinct values for each attribute
+ results = g.db.execute('''
+ SELECT DISTINCT CaseAttribute.Id, CaseAttribute.Name, CaseAttributeXRef.Value
+ FROM CaseAttribute, CaseAttributeXRef
+ WHERE CaseAttributeXRef.CaseAttributeId = CaseAttribute.Id
+ AND CaseAttributeXRef.ProbeSetFreezeId = %s
+ ORDER BY CaseAttribute.Name''', (str(self.dataset.id),))
self.attributes = {}
- for key, value in case_attributes.fetchall():
- print("radish: %s - %s" % (key, value))
+ for attr, values in itertools.groupby(results.fetchall(), lambda row: (row.Id, row.Name)):
+ key, name = attr
+ print("radish: %s - %s" % (key, name))
self.attributes[key] = Bunch()
- self.attributes[key].name = value
-
- attribute_values = g.db.execute('''SELECT DISTINCT CaseAttributeXRef.Value
- FROM CaseAttribute, CaseAttributeXRef
- WHERE CaseAttribute.Name = %s AND
- CaseAttributeXRef.CaseAttributeId = CaseAttribute.Id''', (value,))
-
- self.attributes[key].distinct_values = [item[0] for item in attribute_values.fetchall()]
+ self.attributes[key].name = name
+ self.attributes[key].distinct_values = [item.Value for item in values]
self.attributes[key].distinct_values.sort(key=natural_sort_key)
-
- def get_extra_attribute_values(self, sample_name):
-
- attribute_values = {}
-
+ def get_extra_attribute_values(self):
if self.attributes:
+ results = g.db.execute('''
+ SELECT Strain.Name AS SampleName, CaseAttributeId AS Id, CaseAttributeXRef.Value
+ FROM Strain, StrainXRef, InbredSet, CaseAttributeXRef
+ WHERE StrainXRef.StrainId = Strain.Id
+ AND InbredSet.Id = StrainXRef.InbredSetId
+ AND CaseAttributeXRef.StrainId = Strain.Id
+ AND InbredSet.Name = %s
+ AND CaseAttributeXRef.ProbeSetFreezeId = %s
+ ORDER BY SampleName''',
+ (self.dataset.group.name, self.this_trait.dataset.id))
+
+ for sample_name, items in itertools.groupby(results.fetchall(), lambda row: row.SampleName):
+ attribute_values = {}
+ for item in items:
+ attribute_value = item.Value
+
+ #ZS: If it's an int, turn it into one for sorting
+ #(for example, 101 would be lower than 80 if they're strings instead of ints)
+ try:
+ attribute_value = int(attribute_value)
+ except ValueError:
+ pass
+
+ attribute_values[self.attributes[item.Id].name] = attribute_value
+ self.sample_attribute_values[sample_name] = attribute_values
- #ZS: Get StrainId value for the next query
- result = g.db.execute("""SELECT Strain.Id
- FROM Strain, StrainXRef, InbredSet
- WHERE Strain.Name = %s and
- StrainXRef.StrainId = Strain.Id and
- InbredSet.Id = StrainXRef.InbredSetId and
- InbredSet.Name = %s""", (sample_name,
- self.dataset.group.name))
-
- sample_id = result.fetchone().Id
-
- for attribute in self.attributes:
-
- #ZS: Add extra case attribute values (if any)
- result = g.db.execute("""SELECT Value
- FROM CaseAttributeXRef
- WHERE ProbeSetFreezeId = %s AND
- StrainId = %s AND
- CaseAttributeId = %s
- group by CaseAttributeXRef.CaseAttributeId""", (
- self.this_trait.dataset.id, sample_id, str(attribute)))
-
- attribute_value = result.fetchone().Value #Trait-specific attributes, if any
-
- #ZS: If it's an int, turn it into one for sorting
- #(for example, 101 would be lower than 80 if they're strings instead of ints)
- try:
- attribute_value = int(attribute_value)
- except ValueError:
- pass
-
- attribute_values[self.attributes[attribute].name] = attribute_value
-
- return attribute_values
-
def se_exists(self):
"""Returns true if SE values exist for any samples, otherwise false"""
@@ -243,4 +182,4 @@ def natural_sort_key(x):
x = int(x)
except ValueError:
pass
- return x \ No newline at end of file
+ return x
diff --git a/wqflask/wqflask/show_trait/show_trait.py b/wqflask/wqflask/show_trait/show_trait.py
index 929f5abb..850c99a7 100755
--- a/wqflask/wqflask/show_trait/show_trait.py
+++ b/wqflask/wqflask/show_trait/show_trait.py
@@ -16,6 +16,7 @@ from base import webqtlConfig
from base import webqtlCaseData
from wqflask.show_trait.SampleList import SampleList
from utility import webqtlUtil, Plot, Bunch, helper_functions
+from utility.tools import pylmm_command, plink_command
from base.trait import GeneralTrait
from base import data_set
from dbFunction import webqtlDatabaseFunction
@@ -23,6 +24,9 @@ from basicStatistics import BasicStatisticsFunctions
from pprint import pformat as pf
+PYLMM_PATH,PYLMM_COMMAND = pylmm_command()
+PLINK_PATH,PLINK_COMMAND = plink_command()
+
###############################################
#
# Todo: Put in security to ensure that user has permission to access confidential data sets
@@ -98,11 +102,13 @@ class ShowTrait(object):
print("self.dataset.type:", self.dataset.type)
if hasattr(self.this_trait, 'locus_chr') and self.this_trait.locus_chr != "" and self.dataset.type != "Geno" and self.dataset.type != "Publish":
- self.nearest_marker1 = get_nearest_marker(self.this_trait, self.dataset)[0]
- self.nearest_marker2 = get_nearest_marker(self.this_trait, self.dataset)[1]
+ self.nearest_marker = get_nearest_marker(self.this_trait, self.dataset)
+ #self.nearest_marker1 = get_nearest_marker(self.this_trait, self.dataset)[0]
+ #self.nearest_marker2 = get_nearest_marker(self.this_trait, self.dataset)[1]
else:
- self.nearest_marker1 = ""
- self.nearest_marker2 = ""
+ self.nearest_marker = ""
+ #self.nearest_marker1 = ""
+ #self.nearest_marker2 = ""
self.make_sample_lists(self.this_trait)
@@ -116,13 +122,16 @@ class ShowTrait(object):
hddn['mapping_display_all'] = True
hddn['suggestive'] = 0
hddn['num_perm'] = 0
- hddn['manhattan_plot'] = False
+ hddn['manhattan_plot'] = ""
if hasattr(self.this_trait, 'locus_chr') and self.this_trait.locus_chr != "" and self.dataset.type != "Geno" and self.dataset.type != "Publish":
- hddn['control_marker'] = self.nearest_marker1+","+self.nearest_marker2
+ hddn['control_marker'] = self.nearest_marker
+ #hddn['control_marker'] = self.nearest_marker1+","+self.nearest_marker2
else:
hddn['control_marker'] = ""
+ hddn['do_control'] = False
hddn['maf'] = 0.01
hddn['compare_traits'] = []
+ hddn['export_data'] = ""
# We'll need access to this_trait and hddn in the Jinja2 Template, so we put it inside self
self.hddn = hddn
@@ -130,30 +139,43 @@ class ShowTrait(object):
self.temp_uuid = uuid.uuid4()
self.sample_group_types = OrderedDict()
- self.sample_group_types['samples_primary'] = self.dataset.group.name + " Only"
- self.sample_group_types['samples_other'] = "Non-" + self.dataset.group.name
- self.sample_group_types['samples_all'] = "All Cases"
+ if len(self.sample_groups) > 1:
+ self.sample_group_types['samples_primary'] = self.dataset.group.name + " Only"
+ self.sample_group_types['samples_other'] = "Non-" + self.dataset.group.name
+ self.sample_group_types['samples_all'] = "All Cases"
+ else:
+ self.sample_group_types['samples_primary'] = self.dataset.group.name
sample_lists = [group.sample_list for group in self.sample_groups]
print("sample_lists is:", pf(sample_lists))
- probability_plot_data = []
- sample_vals = []
- sample_z_scores = []
- for sample_list in sample_lists:
- for sample in sample_list:
- sample_vals.append(sample.prob_plot_value)
- sample_z_scores.append(sample.z_score)
- probability_plot_data.append(sample_z_scores)
- probability_plot_data.append(sample_vals)
+ self.get_mapping_methods()
-
js_data = dict(sample_group_types = self.sample_group_types,
sample_lists = sample_lists,
- probability_plot_data = probability_plot_data,
attribute_names = self.sample_groups[0].attributes,
temp_uuid = self.temp_uuid)
self.js_data = js_data
+ def get_mapping_methods(self):
+ '''Only display mapping methods when the dataset group's genotype file exists'''
+ def check_plink_gemma():
+ if (os.path.isfile(PLINK_PATH+"/"+self.dataset.group.name+".bed") and
+ os.path.isfile(PLINK_PATH+"/"+self.dataset.group.name+".map")):
+
+ return True
+ else:
+ return False
+
+ def check_pylmm_rqtl():
+ if os.path.isfile(webqtlConfig.GENODIR+self.dataset.group.name+".geno"):
+ return True
+ else:
+ return False
+
+ self.use_plink_gemma = check_plink_gemma()
+ self.use_pylmm_rqtl = check_pylmm_rqtl()
+
+
def read_data(self, include_f1=False):
'''read user input data or from trait data and analysis form'''
@@ -236,7 +258,7 @@ class ShowTrait(object):
def dispTraitInformation(self, args, title1Body, hddn, this_trait):
- _Species = webqtlDatabaseFunction.retrieve_species(group=self.dataset.group.name)
+ self.species_name = webqtlDatabaseFunction.retrieve_species(group=self.dataset.group.name)
#tbl = HT.TableLite(cellpadding=2, Class="collap", style="margin-left:20px;", width="840", valign="top", id="target1")
@@ -283,13 +305,13 @@ class ShowTrait(object):
# else:
# pass
- g.db.execute("SELECT Name FROM InbredSet WHERE Name=%s", self.dataset.group.name)
+ result = g.db.execute("SELECT Name FROM InbredSet WHERE Name=%s", self.dataset.group.name)
if this_trait:
addSelectionButton = HT.Href(url="#redirect", onClick="addRmvSelection('%s', document.getElementsByName('%s')[0], 'addToSelection');" % (self.dataset.group.name, 'dataInput'))
addSelectionButton_img = HT.Image("/images/add_icon.jpg", name="addselect", alt="Add To Collection", title="Add To Collection", style="border:none;")
#addSelectionButton.append(addSelectionButton_img)
addSelectionText = "Add"
- elif self.cursor.fetchall():
+ elif result.fetchall():
addSelectionButton = HT.Href(url="#redirect", onClick="dataEditingFunc(document.getElementsByName('%s')[0], 'addRecord');" % ('dataInput'))
addSelectionButton_img = HT.Image("/images/add_icon.jpg", name="", alt="Add To Collection", title="Add To Collection", style="border:none;")
#addSelectionButton.append(addSelectionButton_img)
@@ -310,7 +332,7 @@ class ShowTrait(object):
#XZ: Gene Symbol
if this_trait.symbol:
#XZ: Show SNP Browser only for mouse
- if _Species == 'mouse':
+ if self.species_name == 'mouse':
geneName = g.db.execute("SELECT geneSymbol FROM GeneList WHERE geneSymbol = %s", this_trait.symbol).fetchone()
if geneName:
snpurl = os.path.join(webqtlConfig.CGIDIR, "main.py?FormID=SnpBrowserResultPage&submitStatus=1&diffAlleles=True&customStrain=True") + "&geneName=%s" % geneName[0]
@@ -333,8 +355,8 @@ class ShowTrait(object):
#XZ: display similar traits in other selected datasets
if this_trait and this_trait.dataset and this_trait.dataset.type=="ProbeSet" and this_trait.symbol:
- if _Species in ("mouse", "rat", "human"):
- similarUrl = "%s?cmd=sch&gene=%s&alias=1&species=%s" % (os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), this_trait.symbol, _Species)
+ if self.species_name in ("mouse", "rat", "human"):
+ similarUrl = "%s?cmd=sch&gene=%s&alias=1&species=%s" % (os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), this_trait.symbol, self.species_name)
similarButton = HT.Href(url="#redirect", onClick="openNewWin('%s')" % similarUrl)
similarButton_img = HT.Image("/images/find_icon.jpg", name="similar", alt=" Find similar expression data ", title=" Find similar expression data ", style="border:none;")
similarText = "Find"
@@ -368,45 +390,46 @@ class ShowTrait(object):
blatsequence = ''
for seqt in seqs:
if int(seqt[1][-1]) % 2 == 1:
- blatsequence += string.strip(seqt[0])
+ blatsequence += string.strip(seqt[0])## NEEDED FOR UCSC GENOME BROWSER LINK
#--------Hongqiang add this part in order to not only blat ProbeSet, but also blat Probe
blatsequence = '%3E'+this_trait.name+'%0A'+blatsequence+'%0A'
#XZ, 06/03/2009: ProbeSet name is not unique among platforms. We should use ProbeSet Id instead.
- self.cursor.execute("""SELECT Probe.Sequence, Probe.Name
+ query = """SELECT Probe.Sequence, Probe.Name
FROM Probe, ProbeSet, ProbeSetFreeze, ProbeSetXRef
WHERE ProbeSetXRef.ProbeSetFreezeId = ProbeSetFreeze.Id AND
ProbeSetXRef.ProbeSetId = ProbeSet.Id AND
- ProbeSetFreeze.Name = '%s' AND
- ProbeSet.Name = '%s' AND
- Probe.ProbeSetId = ProbeSet.Id order by Probe.SerialOrder""" % (this_trait.dataset.name, this_trait.name) )
+ ProbeSetFreeze.Name = '{}' AND
+ ProbeSet.Name = '{}' AND
+ Probe.ProbeSetId = ProbeSet.Id order by Probe.SerialOrder""".format(this_trait.dataset.name, this_trait.name)
+
+ seqs = g.db.execute(query).fetchall()
- seqs = self.cursor.fetchall()
for seqt in seqs:
if int(seqt[1][-1]) %2 == 1:
blatsequence += '%3EProbe_'+string.strip(seqt[1])+'%0A'+string.strip(seqt[0])+'%0A'
#XZ: Pay attention to the parameter of version (rn, mm, hg). They need to be changed if necessary.
- if _Species == "rat":
- UCSC_BLAT_URL = webqtlConfig.UCSC_BLAT % ('rat', 'rn3', blatsequence)
- UTHSC_BLAT_URL = ""
- elif _Species == "mouse":
- UCSC_BLAT_URL = webqtlConfig.UCSC_BLAT % ('mouse', 'mm9', blatsequence)
- UTHSC_BLAT_URL = webqtlConfig.UTHSC_BLAT % ('mouse', 'mm9', blatsequence)
- elif _Species == "human":
- UCSC_BLAT_URL = webqtlConfig.UCSC_BLAT % ('human', 'hg19', blatsequence)
- UTHSC_BLAT_URL = ""
+ if self.species_name == "rat":
+ self.UCSC_BLAT_URL = webqtlConfig.UCSC_BLAT % ('rat', 'rn3', blatsequence)
+ self.UTHSC_BLAT_URL = ""
+ elif self.species_name == "mouse":
+ self.UCSC_BLAT_URL = webqtlConfig.UCSC_BLAT % ('mouse', 'mm9', blatsequence)
+ self.UTHSC_BLAT_URL = webqtlConfig.UTHSC_BLAT % ('mouse', 'mm9', blatsequence)
+ elif self.species_name == "human":
+ self.UCSC_BLAT_URL = webqtlConfig.UCSC_BLAT % ('human', 'hg19', blatsequence)
+ self.UTHSC_BLAT_URL = ""
else:
- UCSC_BLAT_URL = ""
- UTHSC_BLAT_URL = ""
+ self.UCSC_BLAT_URL = ""
+ self.UTHSC_BLAT_URL = ""
- if UCSC_BLAT_URL:
+ if self.UCSC_BLAT_URL != "":
verifyButton = HT.Href(url="#", onClick="javascript:openNewWin('%s'); return false;" % UCSC_BLAT_URL)
verifyButtonImg = HT.Image("/images/verify_icon.jpg", name="verify", alt=" Check probe locations at UCSC ",
title=" Check probe locations at UCSC ", style="border:none;")
verifyButton.append(verifyButtonImg)
verifyText = 'Verify'
- if UTHSC_BLAT_URL:
+ if self.UTHSC_BLAT_URL != "":
rnaseqButton = HT.Href(url="#", onClick="javascript:openNewWin('%s'); return false;" % UTHSC_BLAT_URL)
rnaseqButtonImg = HT.Image("/images/rnaseq_icon.jpg", name="rnaseq", alt=" View probes, SNPs, and RNA-seq at UTHSC ",
title=" View probes, SNPs, and RNA-seq at UTHSC ", style="border:none;")
@@ -426,6 +449,7 @@ class ShowTrait(object):
#query database for number of probes associated with trait; if count > 0, set probe tool button and text
probeResult = g.db.execute(query).fetchone()
if probeResult[0] > 0:
+ self.show_probes = "True"
probeurl = "%s?FormID=showProbeInfo&database=%s&ProbeSetID=%s&CellID=%s&group=%s&incparentsf1=ON" \
% (os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), this_trait.dataset, this_trait.name, this_trait.cellid, self.dataset.group.name)
probeButton = HT.Href(url="#", onClick="javascript:openNewWin('%s'); return false;" % probeurl)
@@ -433,7 +457,7 @@ class ShowTrait(object):
#probeButton.append(probeButton_img)
probeText = "Probes"
- this_trait.species = _Species # We need this in the template, so we tuck it into this_trait
+ this_trait.species = self.species_name # We need this in the template, so we tuck it into this_trait
this_trait.database = this_trait.get_database()
#XZ: ID links
@@ -469,62 +493,35 @@ class ShowTrait(object):
#XZ: Resource Links:
if this_trait.symbol:
- linkStyle = "background:#dddddd;padding:2"
- tSpan = HT.Span(style="font-family:verdana,serif;font-size:13px")
-
#XZ,12/26/2008: Gene symbol may contain single quotation mark.
#For example, Affymetrix, mouse430v2, 1440338_at, the symbol is 2'-Pde (geneid 211948)
#I debug this by using double quotation marks.
- if _Species == "rat":
-
- #XZ, 7/16/2009: The url for SymAtlas (renamed as BioGPS) has changed. We don't need this any more
- #symatlas_species = "Rattus norvegicus"
-
- #self.cursor.execute("SELECT kgID, chromosome,txStart,txEnd FROM GeneList_rn33 WHERE geneSymbol = '%s'" % this_trait.symbol)
- self.cursor.execute('SELECT kgID, chromosome,txStart,txEnd FROM GeneList_rn33 WHERE geneSymbol = "%s"' % this_trait.symbol)
- try:
- kgId, chr, txst, txen = self.cursor.fetchall()[0]
+ if self.species_name == "rat":
+ result = g.db.execute("SELECT kgID, chromosome,txStart,txEnd FROM GeneList_rn33 WHERE geneSymbol = %s", (this_trait.symbol)).fetchone()
+ if result != None:
+ kgId, chr, txst, txen = result[0], result[1], result[2], result[3]
if chr and txst and txen and kgId:
txst = int(txst*1000000)
txen = int(txen*1000000)
- #tSpan.append(HT.Span(HT.Href(text= 'UCSC',target="mainFrame",\
- # title= 'Info from UCSC Genome Browser', url = webqtlConfig.UCSC_REFSEQ % ('rn3',kgId,chr,txst,txen),Class="fs14 fwn"), style=linkStyle)
- # , "&nbsp;"*2)
- except:
- pass
- if _Species == "mouse":
-
- #XZ, 7/16/2009: The url for SymAtlas (renamed as BioGPS) has changed. We don't need this any more
- #symatlas_species = "Mus musculus"
-
- #self.cursor.execute("SELECT chromosome,txStart,txEnd FROM GeneList WHERE geneSymbol = '%s'" % this_trait.symbol)
- #try:
+ if self.species_name == "mouse":
print("this_trait.symbol:", this_trait.symbol)
result = g.db.execute("SELECT chromosome,txStart,txEnd FROM GeneList WHERE geneSymbol = %s", (this_trait.symbol)).fetchone()
if result != None:
this_chr, txst, txen = result[0], result[1], result[2]
- #this_chr, txst, txen = g.db.execute("SELECT chromosome,txStart,txEnd FROM GeneList WHERE geneSymbol = %s", (this_trait.symbol)).fetchone()
if this_chr and txst and txen and this_trait.refseq_transcriptid :
txst = int(txst*1000000)
txen = int(txen*1000000)
- #tSpan.append(HT.Span(HT.Href(text= 'UCSC',target="mainFrame",\
- # title= 'Info from UCSC Genome Browser', url = webqtlConfig.UCSC_REFSEQ % ('mm9',
- # this_trait.refseq_transcriptid,
- # this_chr,
- # txst,
- # txen),
- # Class="fs14 fwn"), style=linkStyle)
- # , "&nbsp;"*2)
+ ## NEEDED FOR UCSC GENOME BROWSER LINK
#XZ, 7/16/2009: The url for SymAtlas (renamed as BioGPS) has changed. We don't need this any more
#tSpan.append(HT.Span(HT.Href(text= 'SymAtlas',target="mainFrame",\
# url="http://symatlas.gnf.org/SymAtlas/bioentry?querytext=%s&query=14&species=%s&type=Expression" \
# % (this_trait.symbol,symatlas_species),Class="fs14 fwn", \
# title="Expression across many tissues and cell types"), style=linkStyle), "&nbsp;"*2)
- if this_trait.geneid and (_Species == "mouse" or _Species == "rat" or _Species == "human"):
+ if this_trait.geneid and (self.species_name == "mouse" or self.species_name == "rat" or self.species_name == "human"):
#tSpan.append(HT.Span(HT.Href(text= 'BioGPS',target="mainFrame",\
# url="http://biogps.gnf.org/?org=%s#goto=genereport&id=%s" \
- # % (_Species, this_trait.geneid),Class="fs14 fwn", \
+ # % (self.species_name, this_trait.geneid),Class="fs14 fwn", \
# title="Expression across many tissues and cell types"), style=linkStyle), "&nbsp;"*2)
pass
#tSpan.append(HT.Span(HT.Href(text= 'STRING',target="mainFrame",\
@@ -534,13 +531,13 @@ class ShowTrait(object):
if this_trait.symbol:
#ZS: The "species scientific" converts the plain English species names we're using to their scientific names, which are needed for PANTHER's input
#We should probably use the scientific name along with the English name (if not instead of) elsewhere as well, given potential non-English speaking users
- if _Species == "mouse":
+ if self.species_name == "mouse":
species_scientific = "Mus%20musculus"
- elif _Species == "rat":
+ elif self.species_name == "rat":
species_scientific = "Rattus%20norvegicus"
- elif _Species == "human":
+ elif self.species_name == "human":
species_scientific = "Homo%20sapiens"
- elif _Species == "drosophila":
+ elif self.species_name == "drosophila":
species_scientific = "Drosophila%20melanogaster"
else:
species_scientific = "all"
@@ -556,7 +553,7 @@ class ShowTrait(object):
# url="http://bind.ca/?textquery=%s" \
# % this_trait.symbol,Class="fs14 fwn", \
# title="Protein interactions"), style=linkStyle), "&nbsp;"*2)
- #if this_trait.geneid and (_Species == "mouse" or _Species == "rat" or _Species == "human"):
+ #if this_trait.geneid and (self.species_name == "mouse" or self.species_name == "rat" or self.species_name == "human"):
# tSpan.append(HT.Span(HT.Href(text= 'Gemma',target="mainFrame",\
# url="http://www.chibi.ubc.ca/Gemma/gene/showGene.html?ncbiid=%s" \
# % this_trait.geneid, Class="fs14 fwn", \
@@ -565,19 +562,19 @@ class ShowTrait(object):
# url="http://lily.uthsc.edu:8080/20091027_GNInterfaces/20091027_redirectSynDB.jsp?query=%s" \
# % this_trait.symbol, Class="fs14 fwn", \
# title="Brain synapse database"), style=linkStyle), "&nbsp;"*2)
- #if _Species == "mouse":
+ #if self.species_name == "mouse":
# tSpan.append(HT.Span(HT.Href(text= 'ABA',target="mainFrame",\
# url="http://mouse.brain-map.org/brain/%s.html" \
# % this_trait.symbol, Class="fs14 fwn", \
# title="Allen Brain Atlas"), style=linkStyle), "&nbsp;"*2)
if this_trait.geneid:
- #if _Species == "mouse":
+ #if self.species_name == "mouse":
# tSpan.append(HT.Span(HT.Href(text= 'ABA',target="mainFrame",\
# url="http://www.brain-map.org/search.do?queryText=egeneid=%s" \
# % this_trait.geneid, Class="fs14 fwn", \
# title="Allen Brain Atlas"), style=linkStyle), "&nbsp;"*2)
- if _Species == "human":
+ if self.species_name == "human":
#tSpan.append(HT.Span(HT.Href(text= 'ABA',target="mainFrame",\
# url="http://humancortex.alleninstitute.org/has/human/imageseries/search/1.html?searchSym=t&searchAlt=t&searchName=t&gene_term=&entrez_term=%s" \
# % this_trait.geneid, Class="fs14 fwn", \
@@ -680,13 +677,13 @@ class ShowTrait(object):
location = "not available"
#if this_trait.sequence and len(this_trait.sequence) > 100:
- # if _Species == "rat":
+ # if self.species_name == "rat":
# UCSC_BLAT_URL = webqtlConfig.UCSC_BLAT % ('rat', 'rn3', this_trait.sequence)
# UTHSC_BLAT_URL = webqtlConfig.UTHSC_BLAT % ('rat', 'rn3', this_trait.sequence)
- # elif _Species == "mouse":
+ # elif self.species_name == "mouse":
# UCSC_BLAT_URL = webqtlConfig.UCSC_BLAT % ('mouse', 'mm9', this_trait.sequence)
# UTHSC_BLAT_URL = webqtlConfig.UTHSC_BLAT % ('mouse', 'mm9', this_trait.sequence)
- # elif _Species == "human":
+ # elif self.species_name == "human":
# UCSC_BLAT_URL = webqtlConfig.UCSC_BLAT % ('human', 'hg19', blatsequence)
# UTHSC_BLAT_URL = webqtlConfig.UTHSC_BLAT % ('human', 'hg19', this_trait.sequence)
# else:
@@ -914,40 +911,7 @@ class ShowTrait(object):
this_group = 'BXD'
if this_group:
-
- dataset_menu = []
- print("[tape4] webqtlConfig.PUBLICTHRESH:", webqtlConfig.PUBLICTHRESH)
- print("[tape4] type webqtlConfig.PUBLICTHRESH:", type(webqtlConfig.PUBLICTHRESH))
- results = g.db.execute("""SELECT PublishFreeze.FullName,PublishFreeze.Name FROM
- PublishFreeze,InbredSet WHERE PublishFreeze.InbredSetId = InbredSet.Id
- and InbredSet.Name = %s and PublishFreeze.public > %s""",
- (this_group, webqtlConfig.PUBLICTHRESH))
- for item in results.fetchall():
- dataset_menu.append(dict(tissue=None,
- datasets=[item]))
-
- results = g.db.execute("""SELECT GenoFreeze.FullName,GenoFreeze.Name FROM GenoFreeze,
- InbredSet WHERE GenoFreeze.InbredSetId = InbredSet.Id and InbredSet.Name =
- %s and GenoFreeze.public > %s""",
- (this_group, webqtlConfig.PUBLICTHRESH))
- for item in results.fetchall():
- dataset_menu.append(dict(tissue=None,
- datasets=[item]))
-
- #03/09/2009: Xiaodong changed the SQL query to order by Name as requested by Rob.
- tissues = g.db.execute("SELECT Id, Name FROM Tissue order by Name")
- for item in tissues.fetchall():
- tissue_id, tissue_name = item
- data_sets = g.db.execute('''SELECT ProbeSetFreeze.FullName,ProbeSetFreeze.Name FROM ProbeSetFreeze, ProbeFreeze,
- InbredSet WHERE ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id and ProbeFreeze.TissueId = %s and
- ProbeSetFreeze.public > %s and ProbeFreeze.InbredSetId = InbredSet.Id and InbredSet.Name like %s
- order by ProbeSetFreeze.CreateTime desc, ProbeSetFreeze.AvgId ''',
- (tissue_id, webqtlConfig.PUBLICTHRESH, "%" + this_group + "%"))
- dataset_sub_menu = [item for item in data_sets.fetchall() if item]
- if dataset_sub_menu:
- dataset_menu.append(dict(tissue=tissue_name,
- datasets=dataset_sub_menu))
-
+ dataset_menu = self.dataset.group.datasets()
dataset_menu_selected = None
if len(dataset_menu):
if this_trait and this_trait.dataset:
@@ -965,7 +929,7 @@ class ShowTrait(object):
def build_mapping_tools(self, this_trait):
- _Species = webqtlDatabaseFunction.retrieveSpecies(cursor=self.cursor, group=fd.group)
+ #_Species = webqtlDatabaseFunction.retrieveSpecies(cursor=self.cursor, group=fd.group)
this_group = fd.group
if this_group[:3] == 'BXD':
@@ -1217,18 +1181,9 @@ class ShowTrait(object):
def make_sample_lists(self, this_trait):
- if self.dataset.group.parlist:
- all_samples_ordered = (self.dataset.group.parlist +
- self.dataset.group.f1list +
- self.dataset.group.samplelist)
- elif self.dataset.group.f1list:
- all_samples_ordered = self.dataset.group.f1list + self.dataset.group.samplelist
- else:
- all_samples_ordered = self.dataset.group.samplelist
-
- this_trait_samples = set(this_trait.data.keys())
+ all_samples_ordered = self.dataset.group.all_samples_ordered()
- primary_sample_names = all_samples_ordered
+ primary_sample_names = list(all_samples_ordered)
print("self.dataset.group", pf(self.dataset.group.__dict__))
print("-*- primary_samplelist is:", pf(primary_sample_names))
@@ -1239,14 +1194,10 @@ class ShowTrait(object):
all_samples_ordered.append(sample)
other_sample_names.append(sample)
- other_sample_names, all_samples_ordered = get_samplelist_from_trait_data(this_trait,
- all_samples_ordered)
-
-
print("species:", self.dataset.group.species)
if self.dataset.group.species == "human":
primary_sample_names += other_sample_names
-
+
primary_samples = SampleList(dataset = self.dataset,
sample_names=primary_sample_names,
this_trait=this_trait,
@@ -1282,36 +1233,29 @@ class ShowTrait(object):
# print("hjs")
self.dataset.group.allsamples = all_samples_ordered
-
-def get_samplelist_from_trait_data(this_trait, all_samples_ordered):
- other_sample_names = []
- for sample in this_trait.data.keys():
- if sample not in all_samples_ordered:
- all_samples_ordered.append(sample)
- other_sample_names.append(sample)
-
- return other_sample_names, all_samples_ordered
-
def get_nearest_marker(this_trait, this_db):
this_chr = this_trait.locus_chr
print("this_chr:", this_chr)
this_mb = this_trait.locus_mb
print("this_mb:", this_mb)
+ #One option is to take flanking markers, another is to take the two (or one) closest
query = """SELECT Geno.Name
FROM Geno, GenoXRef, GenoFreeze
WHERE Geno.Chr = '{}' AND
GenoXRef.GenoId = Geno.Id AND
GenoFreeze.Id = GenoXRef.GenoFreezeId AND
GenoFreeze.Name = '{}'
- ORDER BY ABS( Geno.Mb - {}) LIMIT 2""".format(this_chr, this_db.group.name+"Geno", this_mb)
+ ORDER BY ABS( Geno.Mb - {}) LIMIT 1""".format(this_chr, this_db.group.name+"Geno", this_mb)
print("query:", query)
result = g.db.execute(query).fetchall()
print("result:", result)
if result == []:
- return "", ""
+ return ""
+ #return "", ""
else:
- return result[0][0], result[1][0]
+ return result[0][0]
+ #return result[0][0], result[1][0]
diff --git a/wqflask/wqflask/static/new/css/bar_chart.css b/wqflask/wqflask/static/new/css/bar_chart.css
index 78d31eee..20730c2f 100755
--- a/wqflask/wqflask/static/new/css/bar_chart.css
+++ b/wqflask/wqflask/static/new/css/bar_chart.css
@@ -1,15 +1,23 @@
-.barchart .axis path,
-.barchart .axis line {
- fill: none;
- stroke: #000;
- shape-rendering: crispEdges;
-}
-
-.bar {
- fill: steelblue;
- shape-rendering: crispEdges;
-}
-/*
-.x.axis path {
- display: none;
-}*/ \ No newline at end of file
+.barchart .axis path,
+.barchart .axis line {
+ fill: none;
+ stroke: #000;
+ shape-rendering: crispEdges;
+}
+
+.bar {
+ fill: steelblue;
+ shape-rendering: crispEdges;
+}
+
+#legend-left, #legend-right {
+ font-size: 20px;
+}
+
+.nvd3 .nv-group {
+ fill-opacity: .9 !important;
+}
+
+.nvtooltip table td.legend-color-guide div {
+ display: none;
+} \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/css/charts.css b/wqflask/wqflask/static/new/css/charts.css
index 5f2d4d23..0ce88c15 100644
--- a/wqflask/wqflask/static/new/css/charts.css
+++ b/wqflask/wqflask/static/new/css/charts.css
@@ -25,4 +25,4 @@ p {
p#caption {
margin-left: 100px;
width: 500px;
-}
+} \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/css/prob_plot.css b/wqflask/wqflask/static/new/css/prob_plot.css
new file mode 100644
index 00000000..2a1f8f53
--- /dev/null
+++ b/wqflask/wqflask/static/new/css/prob_plot.css
@@ -0,0 +1,3 @@
+#prob_plot_title {
+ text-align: center;
+} \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/css/scatter-matrix.css b/wqflask/wqflask/static/new/css/scatter-matrix.css
index 147903be..58150b26 100644
--- a/wqflask/wqflask/static/new/css/scatter-matrix.css
+++ b/wqflask/wqflask/static/new/css/scatter-matrix.css
@@ -1,9 +1,9 @@
#scatter-matrix { font-size: 14px; }
-.axis { shape-rendering: crispEdges; }
-.axis line { stroke: #ddd; stroke-width: 1px; }
-.axis path { display: none; }
-.axis text { font-size: 0.8em; }
+#scatter-matrix .axis { shape-rendering: crispEdges; }
+#scatter-matrix .axis line { stroke: #ddd; stroke-width: 1px; }
+#scatter-matrix .axis path { display: none; }
+#scatter-matrix .axis text { font-size: 0.8em; }
rect.extent { fill: #000; fill-opacity: .125; stroke: #fff; }
rect.frame { fill: #fff; fill-opacity: .7; stroke: #aaa; }
diff --git a/wqflask/wqflask/static/new/css/show_trait.css b/wqflask/wqflask/static/new/css/show_trait.css
index 9fc82a85..1e9fd4df 100644
--- a/wqflask/wqflask/static/new/css/show_trait.css
+++ b/wqflask/wqflask/static/new/css/show_trait.css
@@ -4,4 +4,8 @@ tr .outlier {
#bar_chart_container {
overflow-x:scroll;
+}
+
+div.sample_group {
+ overflow: auto; # needed because it contains float dataTable wrapper
} \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/javascript/bar_chart.coffee b/wqflask/wqflask/static/new/javascript/bar_chart.coffee
index c83de64e..7558de80 100755
--- a/wqflask/wqflask/static/new/javascript/bar_chart.coffee
+++ b/wqflask/wqflask/static/new/javascript/bar_chart.coffee
@@ -1,191 +1,159 @@
root = exports ? this
class Bar_Chart
- constructor: (@sample_list) ->
+ constructor: (sample_lists) ->
+ @sample_lists = {}
+ l1 = @sample_lists['samples_primary'] = sample_lists[0] or []
+ l2 = @sample_lists['samples_other'] = sample_lists[1] or []
+
+ l1_names = (x.name for x in l1)
+ l3 = l1.concat((x for x in l2 when x.name not in l1_names))
+ @sample_lists['samples_all'] = l3
+ longest_sample_name_len = d3.max(sample.name.length for sample in l3)
+ @margin = {
+ top: 20,
+ right: 20,
+ bottom: longest_sample_name_len * 6,
+ left: 40
+ }
+
+ @attributes = (key for key of sample_lists[0][0]["extra_attributes"])
+ @sample_attr_vals = (@extra(s) for s in @sample_lists['samples_all']\
+ when s.value != null)
+ @get_distinct_attr_vals()
+ @get_attr_color_dict(@distinct_attr_vals)
+ @attribute_name = "None"
+
@sort_by = "name"
- @get_samples()
- console.log("sample names:", @sample_names)
- if @sample_attr_vals.length > 0
- @get_distinct_attr_vals()
- @get_attr_color_dict(@distinct_attr_vals)
-
- #Used to calculate the bottom margin so sample names aren't cut off
- longest_sample_name = d3.max(sample.length for sample in @sample_names)
-
- @margin = {top: 20, right: 20, bottom: longest_sample_name * 7, left: 40}
- @plot_width = @sample_vals.length * 20 - @margin.left - @margin.right
- @range = @sample_vals.length * 20
- @plot_height = 500 - @margin.top - @margin.bottom
-
- @x_buffer = @plot_width/20
- @y_buffer = @plot_height/20
-
- @y_min = d3.min(@sample_vals)
- @y_max = d3.max(@sample_vals) * 1.1
-
- @svg = @create_svg()
-
- @plot_height -= @y_buffer
- @create_scales()
- @create_graph()
+ @chart = null
+
+ @select_attribute_box = $ "#color_attribute"
d3.select("#color_attribute").on("change", =>
- @attribute = $("#color_attribute").val()
- console.log("attr_color_dict:", @attr_color_dict)
- #if $("#update_bar_chart").html() == 'Sort By Name'
- if @sort_by = "name"
- @svg.selectAll(".bar")
- .data(@sorted_samples())
- .transition()
- .duration(1000)
- .style("fill", (d) =>
- if @attribute == "None"
- return "steelblue"
- else
- return @attr_color_dict[@attribute][d[2][@attribute]]
- )
- .select("title")
- .text((d) =>
- return d[1]
- )
- else
- @svg.selectAll(".bar")
- .data(@samples)
- .transition()
- .duration(1000)
- .style("fill", (d) =>
- if @attribute == "None"
- return "steelblue"
- else
- return @attr_color_dict[@attribute][d[2][@attribute]]
- )
- @draw_legend()
- @add_legend(@attribute, @distinct_attr_vals[@attribute])
+ @attribute_name = @select_attribute_box.val()
+ @rebuild_bar_graph()
)
$(".sort_by_value").on("click", =>
console.log("sorting by value")
@sort_by = "value"
- if @attributes.length > 0
- @attribute = $("#color_attribute").val()
- #sortItems = (a, b) ->
- # return a[1] - b[1]
- @rebuild_bar_graph(@sorted_samples())
- #@svg.selectAll(".bar")
- # .data(@sorted_samples())
- # .transition()
- # .duration(1000)
- # .attr("y", (d) =>
- # return @y_scale(d[1])
- # )
- # .attr("height", (d) =>
- # return @plot_height - @y_scale(d[1])
- # )
- # .select("title")
- # .text((d) =>
- # return d[1]
- # )
- # #.style("fill", (d) =>
- # # if @attributes.length > 0
- # # return @attr_color_dict[attribute][d[2][attribute]]
- # # else
- # # return "steelblue"
- # #)
- #sorted_sample_names = (sample[0] for sample in @sorted_samples())
- #x_scale = d3.scale.ordinal()
- # .domain(sorted_sample_names)
- # .rangeBands([0, @plot_width], .1)
- #$('.x.axis').remove()
- #@add_x_axis(x_scale)
+ @rebuild_bar_graph()
)
-
+
$(".sort_by_name").on("click", =>
console.log("sorting by name")
@sort_by = "name"
- if @attributes.length > 0
- @attribute = $("#color_attribute").val()
- @rebuild_bar_graph(@samples)
- #@svg.selectAll(".bar")
- # .data(@samples)
- # .transition()
- # .duration(1000)
- # .attr("y", (d) =>
- # return @y_scale(d[1])
- # )
- # .attr("height", (d) =>
- # return @plot_height - @y_scale(d[1])
- # )
- # .select("title")
- # .text((d) =>
- # return d[1]
- # )
- # .style("fill", (d) =>
- # if @attributes.length > 0
- # return @attr_color_dict[attribute][d[2][attribute]]
- # else
- # return "steelblue"
- # )
- #x_scale = d3.scale.ordinal()
- # .domain(@sample_names)
- # .rangeBands([0, @plot_width], .1)
- #$('.x.axis').remove()
- #@add_x_axis(x_scale)
+ @rebuild_bar_graph()
)
d3.select("#color_by_trait").on("click", =>
@open_trait_selection()
)
- rebuild_bar_graph: (samples) ->
- console.log("samples:", samples)
- @svg.selectAll(".bar")
- .data(samples)
- .transition()
- .duration(1000)
- .style("fill", (d) =>
- if @attributes.length == 0 and @trait_color_dict?
- console.log("SAMPLE:", d[0])
- console.log("CHECKING:", @trait_color_dict[d[0]])
- #return "steelblue"
- return @trait_color_dict[d[0]]
- else if @attributes.length > 0 and @attribute != "None"
- console.log("@attribute:", @attribute)
- console.log("d[2]", d[2])
- console.log("the_color:", @attr_color_dict[@attribute][d[2][@attribute]])
- return @attr_color_dict[@attribute][d[2][@attribute]]
- else
- return "steelblue"
- )
- .attr("y", (d) =>
- return @y_scale(d[1])
- )
- .attr("height", (d) =>
- return @plot_height - @y_scale(d[1])
+ value: (sample) ->
+ @value_dict[sample.name].value
+
+ variance: (sample) ->
+ @value_dict[sample.name].variance
+
+ extra: (sample) ->
+ attr_vals = {}
+ for attribute in @attributes
+ attr_vals[attribute] = sample["extra_attributes"][attribute]
+ attr_vals
+
+ # takes a dict: name -> value and rebuilds the graph
+ redraw: (samples_dict, selected_group) ->
+ @value_dict = samples_dict[selected_group]
+ @raw_data = (x for x in @sample_lists[selected_group] when\
+ x.name of @value_dict and @value(x) != null)
+ @rebuild_bar_graph()
+
+ rebuild_bar_graph: ->
+ raw_data = @raw_data.slice()
+ if @sort_by == 'value'
+ raw_data = raw_data.sort((x, y) => @value(x) - @value(y))
+ console.log("raw_data: ", raw_data)
+
+ h = 600
+ container = $("#bar_chart_container")
+ container.height(h + @margin.top + @margin.bottom)
+ if @chart is null
+ @chart = nv.models.multiBarChart()
+ .height(h)
+ .errorBarColor(=> 'red')
+ .reduceXTicks(false)
+ .staggerLabels(false)
+ .showControls(false)
+ .showLegend(false)
+
+ # show value, sd, and attributes in tooltip
+ @chart.multibar.dispatch.on('elementMouseover.tooltip',
+ (evt) =>
+ evt.value = @chart.x()(evt.data);
+ evt['series'] = [{
+ key: 'Value',
+ value: evt.data.y,
+ color: evt.color
+ }];
+ if evt.data.yErr
+ evt['series'].push({key: 'SE', value: evt.data.yErr})
+ if evt.data.attr
+ for k, v of evt.data.attr
+ evt['series'].push({key: k, value: v})
+ @chart.tooltip.data(evt).hidden(false);
)
- .select("title")
- .text((d) =>
- return d[1]
+
+ @chart.tooltip.valueFormatter((d, i) -> d)
+
+ nv.addGraph(() =>
+ @remove_legend()
+ values = ({x: s.name, y: @value(s), yErr: @variance(s) or 0,\
+ attr: s.extra_attributes}\
+ for s in raw_data)
+
+ if @attribute_name != "None"
+ @color_dict = @attr_color_dict[@attribute_name]
+ @chart.barColor((d) => @color_dict[d.attr[@attribute_name]])
+ @add_legend()
+ else
+ @chart.barColor(=> 'steelblue')
+
+ @chart.width(raw_data.length * 20)
+ @chart.yDomain([0.9 * _.min((d.y - 1.5 * d.yErr for d in values)),
+ 1.05 * _.max((d.y + 1.5 * d.yErr for d in values))])
+ console.log("values: ", values)
+ d3.select("#bar_chart_container svg")
+ .datum([{values: values}])
+ .style('width', raw_data.length * 20 + 'px')
+ .transition().duration(1000)
+ .call(@chart)
+
+ d3.select("#bar_chart_container .nv-x")
+ .selectAll('.tick text')
+ .style("font-size", "12px")
+ .style("text-anchor", "end")
+ .attr("dx", "-.8em")
+ .attr("dy", "-.3em")
+ .attr("transform", (d) =>
+ return "rotate(-90)"
+ )
+
+ return @chart
)
- #.style("fill", (d) =>
- # return @trait_color_dict[d[0]]
- # #return @attr_color_dict["collection_trait"][trimmed_samples[d[0]]]
- #)
- sample_names = (sample[0] for sample in samples)
- console.log("sample_names2:", sample_names)
- x_scale = d3.scale.ordinal()
- .domain(sample_names)
- .rangeRoundBands([0, @range], 0.1, 0)
- $('.bar_chart').find('.x.axis').remove()
- @add_x_axis(x_scale)
get_attr_color_dict: (vals) ->
@attr_color_dict = {}
+ @is_discrete = {}
+ @minimum_values = {}
+ @maximum_values = {}
console.log("vals:", vals)
for own key, distinct_vals of vals
@min_val = d3.min(distinct_vals)
@max_val = d3.max(distinct_vals)
this_color_dict = {}
- if distinct_vals.length < 10
+ discrete = distinct_vals.length < 10
+ if discrete
color = d3.scale.category10()
for value, i in distinct_vals
this_color_dict[value] = color(i)
@@ -200,8 +168,7 @@ class Bar_Chart
return true
)
color_range = d3.scale.linear()
- .domain([min_val,
- max_val])
+ .domain([@min_val, @max_val])
.range([0,255])
for value, i in distinct_vals
console.log("color_range(value):", parseInt(color_range(value)))
@@ -209,79 +176,12 @@ class Bar_Chart
#this_color_dict[value] = d3.rgb("lightblue").darker(color_range(parseInt(value)))
#this_color_dict[value] = "rgb(0, 0, " + color_range(parseInt(value)) + ")"
@attr_color_dict[key] = this_color_dict
-
-
-
- draw_legend: () ->
- $('#legend-left').html(@min_val)
- $('#legend-right').html(@max_val)
- svg_html = '<svg height="10" width="90"> \
- <rect x="0" width="15" height="10" style="fill: rgb(0, 0, 0);"></rect> \
- <rect x="15" width="15" height="10" style="fill: rgb(50, 0, 0);"></rect> \
- <rect x="30" width="15" height="10" style="fill: rgb(100, 0, 0);"></rect> \
- <rect x="45" width="15" height="10" style="fill: rgb(150, 0, 0);"></rect> \
- <rect x="60" width="15" height="10" style="fill: rgb(200, 0, 0);"></rect> \
- <rect x="75" width="15" height="10" style="fill: rgb(255, 0, 0);"></rect> \
- </svg>'
- console.log("svg_html:", svg_html)
- $('#legend-colors').html(svg_html)
-
- get_trait_color_dict: (samples, vals) ->
- @trait_color_dict = {}
- console.log("vals:", vals)
- for own key, distinct_vals of vals
- this_color_dict = {}
- @min_val = d3.min(distinct_vals)
- @max_val = d3.max(distinct_vals)
- if distinct_vals.length < 10
- color = d3.scale.category10()
- for value, i in distinct_vals
- this_color_dict[value] = color(i)
- else
- console.log("distinct_values:", distinct_vals)
- #Check whether all values are numbers, and if they are get a corresponding
- #color gradient
- if _.every(distinct_vals, (d) =>
- if isNaN(d)
- return false
- else
- return true
- )
- color_range = d3.scale.linear()
- .domain([d3.min(distinct_vals),
- d3.max(distinct_vals)])
- .range([0,255])
- for value, i in distinct_vals
- console.log("color_range(value):", parseInt(color_range(value)))
- this_color_dict[value] = d3.rgb(parseInt(color_range(value)),0, 0)
- for own sample, value of samples
- @trait_color_dict[sample] = this_color_dict[value]
-
- convert_into_colors: (values) ->
- color_range = d3.scale.linear()
- .domain([d3.min(values),
- d3.max(values)])
- .range([0,255])
- for value, i in values
- console.log("color_range(value):", color_range(parseInt(value)))
- this_color_dict[value] = d3.rgb(color_range(parseInt(value)),0, 0)
- #this_color_dict[value] = d3.rgb("lightblue").darker(color_range(parseInt(value)))
-
- get_samples: () ->
- @sample_names = (sample.name for sample in @sample_list when sample.value != null)
- @sample_vals = (sample.value for sample in @sample_list when sample.value != null)
- @attributes = (key for key of @sample_list[0]["extra_attributes"])
- console.log("attributes:", @attributes)
- @sample_attr_vals = []
- if @attributes.length > 0
- for sample in @sample_list
- attr_vals = {}
- for attribute in @attributes
- attr_vals[attribute] = sample["extra_attributes"][attribute]
- @sample_attr_vals.push(attr_vals)
- @samples = _.zip(@sample_names, @sample_vals, @sample_attr_vals)
+ @is_discrete[key] = discrete
+ @minimum_values[key] = @min_val
+ @maximum_values[key] = @max_val
get_distinct_attr_vals: () ->
+ # FIXME: this has quadratic behaviour, may cause issues with many samples and continuous attributes
@distinct_attr_vals = {}
for sample in @sample_attr_vals
for attribute of sample
@@ -290,134 +190,45 @@ class Bar_Chart
if sample[attribute] not in @distinct_attr_vals[attribute]
@distinct_attr_vals[attribute].push(sample[attribute])
#console.log("distinct_attr_vals:", @distinct_attr_vals)
-
- create_svg: () ->
- svg = d3.select("#bar_chart")
- .append("svg")
- .attr("class", "bar_chart")
- .attr("width", @plot_width + @margin.left + @margin.right)
- .attr("height", @plot_height + @margin.top + @margin.bottom)
- .append("g")
- .attr("transform", "translate(" + @margin.left + "," + @margin.top + ")")
-
- return svg
-
- create_scales: () ->
- @x_scale = d3.scale.ordinal()
- .domain(@sample_names)
- .rangeRoundBands([0, @range], 0.1, 0)
-
- @y_scale = d3.scale.linear()
- .domain([@y_min * 0.75, @y_max])
- .range([@plot_height, @y_buffer])
-
- create_graph: () ->
-
- #@add_border()
- @add_x_axis(@x_scale)
- @add_y_axis()
-
- @add_bars()
-
- add_x_axis: (scale) ->
- xAxis = d3.svg.axis()
- .scale(scale)
- .orient("bottom");
-
- @svg.append("g")
- .attr("class", "x axis")
- .attr("transform", "translate(0," + @plot_height + ")")
- .call(xAxis)
- .selectAll("text")
- .style("text-anchor", "end")
- .style("font-size", "12px")
- .attr("dx", "-.8em")
- .attr("dy", "-.3em")
- .attr("transform", (d) =>
- return "rotate(-90)"
- )
- add_y_axis: () ->
- yAxis = d3.svg.axis()
- .scale(@y_scale)
- .orient("left")
- .ticks(5)
-
- @svg.append("g")
- .attr("class", "y axis")
- .call(yAxis)
- .append("text")
- .attr("transform", "rotate(-90)")
- .attr("y", 6)
- .attr("dy", ".71em")
- .style("text-anchor", "end")
-
- add_bars: () ->
- @svg.selectAll(".bar")
- .data(@samples)
- .enter().append("rect")
- .style("fill", "steelblue")
- .attr("class", "bar")
- .attr("x", (d) =>
- return @x_scale(d[0])
- )
- .attr("width", @x_scale.rangeBand())
- .attr("y", (d) =>
- return @y_scale(d[1])
- )
- .attr("height", (d) =>
- return @plot_height - @y_scale(d[1])
- )
- .append("svg:title")
- .text((d) =>
- return d[1]
+ add_legend: =>
+ if @is_discrete[@attribute_name]
+ @add_legend_discrete()
+ else
+ @add_legend_continuous()
+
+ remove_legend: =>
+ $(".legend").remove()
+ $("#legend-left,#legend-right,#legend-colors").empty()
+
+ add_legend_continuous: =>
+ $('#legend-left').html(@minimum_values[@attribute_name])
+ $('#legend-right').html(@maximum_values[@attribute_name])
+ svg_html = '<svg height="15" width="120"> \
+ <rect x="0" width="20" height="15" style="fill: rgb(0, 0, 0);"></rect> \
+ <rect x="20" width="20" height="15" style="fill: rgb(50, 0, 0);"></rect> \
+ <rect x="40" width="20" height="15" style="fill: rgb(100, 0, 0);"></rect> \
+ <rect x="60" width="20" height="15" style="fill: rgb(150, 0, 0);"></rect> \
+ <rect x="80" width="20" height="15" style="fill: rgb(200, 0, 0);"></rect> \
+ <rect x="100" width="20" height="15" style="fill: rgb(255, 0, 0);"></rect> \
+ </svg>'
+ console.log("svg_html:", svg_html)
+ $('#legend-colors').html(svg_html)
+
+ add_legend_discrete: =>
+ legend_span = d3.select('#bar_chart_legend')
+ .append('div').style('word-wrap', 'break-word')
+ .attr('class', 'legend').selectAll('span')
+ .data(@distinct_attr_vals[@attribute_name])
+ .enter().append('span').style({'word-wrap': 'normal', 'display': 'inline-block'})
+
+ legend_span.append('span')
+ .style("background-color", (d) =>
+ return @attr_color_dict[@attribute_name][d]
)
-
-
- sorted_samples: () ->
- #if @sample_attr_vals.length > 0
- sample_list = _.zip(@sample_names, @sample_vals, @sample_attr_vals)
- #else
- # sample_list = _.zip(@sample_names, @sample_vals)
- sorted = _.sortBy(sample_list, (sample) =>
- return sample[1]
- )
- console.log("sorted:", sorted)
- return sorted
-
- add_legend: (attribute, distinct_vals) ->
- legend = @svg.append("g")
- .attr("class", "legend")
- .attr("height", 100)
- .attr("width", 100)
- .attr('transform', 'translate(-20,50)')
-
- legend_rect = legend.selectAll('rect')
- .data(distinct_vals)
- .enter()
- .append("rect")
- .attr("x", @plot_width - 65)
- .attr("width", 10)
- .attr("height", 10)
- .attr("y", (d, i) =>
- return i * 20
- )
- .style("fill", (d) =>
- console.log("TEST:", @attr_color_dict[attribute][d])
- return @attr_color_dict[attribute][d]
- )
-
- legend_text = legend.selectAll('text')
- .data(distinct_vals)
- .enter()
- .append("text")
- .attr("x", @plot_width - 52)
- .attr("y", (d, i) =>
- return i*20 + 9
- )
- .text((d) =>
- return d
- )
+ .style({'display': 'inline-block', 'width': '15px', 'height': '15px',\
+ 'margin': '0px 5px 0px 15px'})
+ legend_span.append('span').text((d) => return d).style('font-size', '20px')
open_trait_selection: () ->
$('#collections_holder').load('/collections/list?color_by_trait #collections_list', =>
@@ -432,7 +243,7 @@ class Bar_Chart
# console.log("contents:", $(element).contents())
# $(element).contents().unwrap()
)
-
+
color_by_trait: (trait_sample_data) ->
console.log("BXD1:", trait_sample_data["BXD1"])
console.log("trait_sample_data:", trait_sample_data)
@@ -443,34 +254,7 @@ class Bar_Chart
@get_trait_color_dict(trimmed_samples, distinct_values)
console.log("TRAIT_COLOR_DICT:", @trait_color_dict)
console.log("SAMPLES:", @samples)
- if @sort_by = "value"
- @svg.selectAll(".bar")
- .data(@samples)
- .transition()
- .duration(1000)
- .style("fill", (d) =>
- console.log("this color:", @trait_color_dict[d[0]])
- return @trait_color_dict[d[0]]
- )
- .select("title")
- .text((d) =>
- return d[1]
- )
- @draw_legend()
- else
- @svg.selectAll(".bar")
- .data(@sorted_samples())
- .transition()
- .duration(1000)
- .style("fill", (d) =>
- console.log("this color:", @trait_color_dict[d[0]])
- return @trait_color_dict[d[0]]
- )
- .select("title")
- .text((d) =>
- return d[1]
- )
- @draw_legend()
+ # TODO
trim_values: (trait_sample_data) ->
trimmed_samples = {}
@@ -488,4 +272,4 @@ class Bar_Chart
#for sample in samples
# if samples[sample] in distinct_values
-root.Bar_Chart = Bar_Chart \ No newline at end of file
+root.Bar_Chart = Bar_Chart
diff --git a/wqflask/wqflask/static/new/javascript/bar_chart.js b/wqflask/wqflask/static/new/javascript/bar_chart.js
index f5ed544b..7ec35148 100755
--- a/wqflask/wqflask/static/new/javascript/bar_chart.js
+++ b/wqflask/wqflask/static/new/javascript/bar_chart.js
@@ -1,494 +1,487 @@
-// Generated by CoffeeScript 1.8.0
-var Bar_Chart, root,
- __hasProp = {}.hasOwnProperty,
- __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
+// Generated by CoffeeScript 1.9.2
+(function() {
+ var Bar_Chart, root,
+ bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
+ indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
+ hasProp = {}.hasOwnProperty;
-root = typeof exports !== "undefined" && exports !== null ? exports : this;
+ root = typeof exports !== "undefined" && exports !== null ? exports : this;
-Bar_Chart = (function() {
- function Bar_Chart(sample_list) {
- var longest_sample_name, sample;
- this.sample_list = sample_list;
- this.sort_by = "name";
- this.get_samples();
- console.log("sample names:", this.sample_names);
- if (this.sample_attr_vals.length > 0) {
- this.get_distinct_attr_vals();
- this.get_attr_color_dict(this.distinct_attr_vals);
- }
- longest_sample_name = d3.max((function() {
- var _i, _len, _ref, _results;
- _ref = this.sample_names;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- sample = _ref[_i];
- _results.push(sample.length);
- }
- return _results;
- }).call(this));
- this.margin = {
- top: 20,
- right: 20,
- bottom: longest_sample_name * 7,
- left: 40
- };
- this.plot_width = this.sample_vals.length * 20 - this.margin.left - this.margin.right;
- this.range = this.sample_vals.length * 20;
- this.plot_height = 500 - this.margin.top - this.margin.bottom;
- this.x_buffer = this.plot_width / 20;
- this.y_buffer = this.plot_height / 20;
- this.y_min = d3.min(this.sample_vals);
- this.y_max = d3.max(this.sample_vals) * 1.1;
- this.svg = this.create_svg();
- this.plot_height -= this.y_buffer;
- this.create_scales();
- this.create_graph();
- d3.select("#color_attribute").on("change", (function(_this) {
- return function() {
- _this.attribute = $("#color_attribute").val();
- console.log("attr_color_dict:", _this.attr_color_dict);
- if (_this.sort_by = "name") {
- _this.svg.selectAll(".bar").data(_this.sorted_samples()).transition().duration(1000).style("fill", function(d) {
- if (_this.attribute === "None") {
- return "steelblue";
- } else {
- return _this.attr_color_dict[_this.attribute][d[2][_this.attribute]];
- }
- }).select("title").text(function(d) {
- return d[1];
- });
- } else {
- _this.svg.selectAll(".bar").data(_this.samples).transition().duration(1000).style("fill", function(d) {
- if (_this.attribute === "None") {
- return "steelblue";
- } else {
- return _this.attr_color_dict[_this.attribute][d[2][_this.attribute]];
- }
- });
+ Bar_Chart = (function() {
+ function Bar_Chart(sample_lists) {
+ this.add_legend_discrete = bind(this.add_legend_discrete, this);
+ this.add_legend_continuous = bind(this.add_legend_continuous, this);
+ this.remove_legend = bind(this.remove_legend, this);
+ this.add_legend = bind(this.add_legend, this);
+ var key, l1, l1_names, l2, l3, longest_sample_name_len, s, sample, x;
+ this.sample_lists = {};
+ l1 = this.sample_lists['samples_primary'] = sample_lists[0] || [];
+ l2 = this.sample_lists['samples_other'] = sample_lists[1] || [];
+ l1_names = (function() {
+ var j, len, results;
+ results = [];
+ for (j = 0, len = l1.length; j < len; j++) {
+ x = l1[j];
+ results.push(x.name);
}
- _this.draw_legend();
- return _this.add_legend(_this.attribute, _this.distinct_attr_vals[_this.attribute]);
- };
- })(this));
- $(".sort_by_value").on("click", (function(_this) {
- return function() {
- console.log("sorting by value");
- _this.sort_by = "value";
- if (_this.attributes.length > 0) {
- _this.attribute = $("#color_attribute").val();
+ return results;
+ })();
+ l3 = l1.concat((function() {
+ var j, len, ref, results;
+ results = [];
+ for (j = 0, len = l2.length; j < len; j++) {
+ x = l2[j];
+ if (ref = x.name, indexOf.call(l1_names, ref) < 0) {
+ results.push(x);
+ }
}
- return _this.rebuild_bar_graph(_this.sorted_samples());
- };
- })(this));
- $(".sort_by_name").on("click", (function(_this) {
- return function() {
- console.log("sorting by name");
- _this.sort_by = "name";
- if (_this.attributes.length > 0) {
- _this.attribute = $("#color_attribute").val();
+ return results;
+ })());
+ this.sample_lists['samples_all'] = l3;
+ longest_sample_name_len = d3.max((function() {
+ var j, len, results;
+ results = [];
+ for (j = 0, len = l3.length; j < len; j++) {
+ sample = l3[j];
+ results.push(sample.name.length);
}
- return _this.rebuild_bar_graph(_this.samples);
- };
- })(this));
- d3.select("#color_by_trait").on("click", (function(_this) {
- return function() {
- return _this.open_trait_selection();
+ return results;
+ })());
+ this.margin = {
+ top: 20,
+ right: 20,
+ bottom: longest_sample_name_len * 6,
+ left: 40
};
- })(this));
- }
-
- Bar_Chart.prototype.rebuild_bar_graph = function(samples) {
- var sample, sample_names, x_scale;
- console.log("samples:", samples);
- this.svg.selectAll(".bar").data(samples).transition().duration(1000).style("fill", (function(_this) {
- return function(d) {
- if (_this.attributes.length === 0 && (_this.trait_color_dict != null)) {
- console.log("SAMPLE:", d[0]);
- console.log("CHECKING:", _this.trait_color_dict[d[0]]);
- return _this.trait_color_dict[d[0]];
- } else if (_this.attributes.length > 0 && _this.attribute !== "None") {
- console.log("@attribute:", _this.attribute);
- console.log("d[2]", d[2]);
- console.log("the_color:", _this.attr_color_dict[_this.attribute][d[2][_this.attribute]]);
- return _this.attr_color_dict[_this.attribute][d[2][_this.attribute]];
- } else {
- return "steelblue";
+ this.attributes = (function() {
+ var results;
+ results = [];
+ for (key in sample_lists[0][0]["extra_attributes"]) {
+ results.push(key);
}
- };
- })(this)).attr("y", (function(_this) {
- return function(d) {
- return _this.y_scale(d[1]);
- };
- })(this)).attr("height", (function(_this) {
- return function(d) {
- return _this.plot_height - _this.y_scale(d[1]);
- };
- })(this)).select("title").text((function(_this) {
- return function(d) {
- return d[1];
- };
- })(this));
- sample_names = (function() {
- var _i, _len, _results;
- _results = [];
- for (_i = 0, _len = samples.length; _i < _len; _i++) {
- sample = samples[_i];
- _results.push(sample[0]);
- }
- return _results;
- })();
- console.log("sample_names2:", sample_names);
- x_scale = d3.scale.ordinal().domain(sample_names).rangeRoundBands([0, this.range], 0.1, 0);
- $('.bar_chart').find('.x.axis').remove();
- return this.add_x_axis(x_scale);
- };
-
- Bar_Chart.prototype.get_attr_color_dict = function(vals) {
- var color, color_range, distinct_vals, i, key, this_color_dict, value, _i, _j, _len, _len1, _results;
- this.attr_color_dict = {};
- console.log("vals:", vals);
- _results = [];
- for (key in vals) {
- if (!__hasProp.call(vals, key)) continue;
- distinct_vals = vals[key];
- this.min_val = d3.min(distinct_vals);
- this.max_val = d3.max(distinct_vals);
- this_color_dict = {};
- if (distinct_vals.length < 10) {
- color = d3.scale.category10();
- for (i = _i = 0, _len = distinct_vals.length; _i < _len; i = ++_i) {
- value = distinct_vals[i];
- this_color_dict[value] = color(i);
- }
- } else {
- console.log("distinct_values:", distinct_vals);
- if (_.every(distinct_vals, (function(_this) {
- return function(d) {
- if (isNaN(d)) {
- return false;
- } else {
- return true;
- }
- };
- })(this))) {
- color_range = d3.scale.linear().domain([min_val, max_val]).range([0, 255]);
- for (i = _j = 0, _len1 = distinct_vals.length; _j < _len1; i = ++_j) {
- value = distinct_vals[i];
- console.log("color_range(value):", parseInt(color_range(value)));
- this_color_dict[value] = d3.rgb(parseInt(color_range(value)), 0, 0);
+ return results;
+ })();
+ this.sample_attr_vals = (function() {
+ var j, len, ref, results;
+ ref = this.sample_lists['samples_all'];
+ results = [];
+ for (j = 0, len = ref.length; j < len; j++) {
+ s = ref[j];
+ if (s.value !== null) {
+ results.push(this.extra(s));
}
}
- }
- _results.push(this.attr_color_dict[key] = this_color_dict);
+ return results;
+ }).call(this);
+ this.get_distinct_attr_vals();
+ this.get_attr_color_dict(this.distinct_attr_vals);
+ this.attribute_name = "None";
+ this.sort_by = "name";
+ this.chart = null;
+ this.select_attribute_box = $("#color_attribute");
+ d3.select("#color_attribute").on("change", (function(_this) {
+ return function() {
+ _this.attribute_name = _this.select_attribute_box.val();
+ return _this.rebuild_bar_graph();
+ };
+ })(this));
+ $(".sort_by_value").on("click", (function(_this) {
+ return function() {
+ console.log("sorting by value");
+ _this.sort_by = "value";
+ return _this.rebuild_bar_graph();
+ };
+ })(this));
+ $(".sort_by_name").on("click", (function(_this) {
+ return function() {
+ console.log("sorting by name");
+ _this.sort_by = "name";
+ return _this.rebuild_bar_graph();
+ };
+ })(this));
+ d3.select("#color_by_trait").on("click", (function(_this) {
+ return function() {
+ return _this.open_trait_selection();
+ };
+ })(this));
}
- return _results;
- };
-
- Bar_Chart.prototype.draw_legend = function() {
- var svg_html;
- $('#legend-left').html(this.min_val);
- $('#legend-right').html(this.max_val);
- svg_html = '<svg height="10" width="90"> <rect x="0" width="15" height="10" style="fill: rgb(0, 0, 0);"></rect> <rect x="15" width="15" height="10" style="fill: rgb(50, 0, 0);"></rect> <rect x="30" width="15" height="10" style="fill: rgb(100, 0, 0);"></rect> <rect x="45" width="15" height="10" style="fill: rgb(150, 0, 0);"></rect> <rect x="60" width="15" height="10" style="fill: rgb(200, 0, 0);"></rect> <rect x="75" width="15" height="10" style="fill: rgb(255, 0, 0);"></rect> </svg>';
- console.log("svg_html:", svg_html);
- return $('#legend-colors').html(svg_html);
- };
- Bar_Chart.prototype.get_trait_color_dict = function(samples, vals) {
- var color, color_range, distinct_vals, i, key, sample, this_color_dict, value, _i, _j, _len, _len1, _results;
- this.trait_color_dict = {};
- console.log("vals:", vals);
- for (key in vals) {
- if (!__hasProp.call(vals, key)) continue;
- distinct_vals = vals[key];
- this_color_dict = {};
- this.min_val = d3.min(distinct_vals);
- this.max_val = d3.max(distinct_vals);
- if (distinct_vals.length < 10) {
- color = d3.scale.category10();
- for (i = _i = 0, _len = distinct_vals.length; _i < _len; i = ++_i) {
- value = distinct_vals[i];
- this_color_dict[value] = color(i);
- }
- } else {
- console.log("distinct_values:", distinct_vals);
- if (_.every(distinct_vals, (function(_this) {
- return function(d) {
- if (isNaN(d)) {
- return false;
- } else {
- return true;
- }
- };
- })(this))) {
- color_range = d3.scale.linear().domain([d3.min(distinct_vals), d3.max(distinct_vals)]).range([0, 255]);
- for (i = _j = 0, _len1 = distinct_vals.length; _j < _len1; i = ++_j) {
- value = distinct_vals[i];
- console.log("color_range(value):", parseInt(color_range(value)));
- this_color_dict[value] = d3.rgb(parseInt(color_range(value)), 0, 0);
- }
- }
- }
- }
- _results = [];
- for (sample in samples) {
- if (!__hasProp.call(samples, sample)) continue;
- value = samples[sample];
- _results.push(this.trait_color_dict[sample] = this_color_dict[value]);
- }
- return _results;
- };
+ Bar_Chart.prototype.value = function(sample) {
+ return this.value_dict[sample.name].value;
+ };
- Bar_Chart.prototype.convert_into_colors = function(values) {
- var color_range, i, value, _i, _len, _results;
- color_range = d3.scale.linear().domain([d3.min(values), d3.max(values)]).range([0, 255]);
- _results = [];
- for (i = _i = 0, _len = values.length; _i < _len; i = ++_i) {
- value = values[i];
- console.log("color_range(value):", color_range(parseInt(value)));
- _results.push(this_color_dict[value] = d3.rgb(color_range(parseInt(value)), 0, 0));
- }
- return _results;
- };
+ Bar_Chart.prototype.variance = function(sample) {
+ return this.value_dict[sample.name].variance;
+ };
- Bar_Chart.prototype.get_samples = function() {
- var attr_vals, attribute, key, sample, _i, _j, _len, _len1, _ref, _ref1;
- this.sample_names = (function() {
- var _i, _len, _ref, _results;
- _ref = this.sample_list;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- sample = _ref[_i];
- if (sample.value !== null) {
- _results.push(sample.name);
- }
+ Bar_Chart.prototype.extra = function(sample) {
+ var attr_vals, attribute, j, len, ref;
+ attr_vals = {};
+ ref = this.attributes;
+ for (j = 0, len = ref.length; j < len; j++) {
+ attribute = ref[j];
+ attr_vals[attribute] = sample["extra_attributes"][attribute];
}
- return _results;
- }).call(this);
- this.sample_vals = (function() {
- var _i, _len, _ref, _results;
- _ref = this.sample_list;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- sample = _ref[_i];
- if (sample.value !== null) {
- _results.push(sample.value);
+ return attr_vals;
+ };
+
+ Bar_Chart.prototype.redraw = function(samples_dict, selected_group) {
+ var x;
+ this.value_dict = samples_dict[selected_group];
+ this.raw_data = (function() {
+ var j, len, ref, results;
+ ref = this.sample_lists[selected_group];
+ results = [];
+ for (j = 0, len = ref.length; j < len; j++) {
+ x = ref[j];
+ if (x.name in this.value_dict && this.value(x) !== null) {
+ results.push(x);
+ }
}
+ return results;
+ }).call(this);
+ return this.rebuild_bar_graph();
+ };
+
+ Bar_Chart.prototype.rebuild_bar_graph = function() {
+ var container, h, raw_data;
+ raw_data = this.raw_data.slice();
+ if (this.sort_by === 'value') {
+ raw_data = raw_data.sort((function(_this) {
+ return function(x, y) {
+ return _this.value(x) - _this.value(y);
+ };
+ })(this));
}
- return _results;
- }).call(this);
- this.attributes = (function() {
- var _results;
- _results = [];
- for (key in this.sample_list[0]["extra_attributes"]) {
- _results.push(key);
- }
- return _results;
- }).call(this);
- console.log("attributes:", this.attributes);
- this.sample_attr_vals = [];
- if (this.attributes.length > 0) {
- _ref = this.sample_list;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- sample = _ref[_i];
- attr_vals = {};
- _ref1 = this.attributes;
- for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
- attribute = _ref1[_j];
- attr_vals[attribute] = sample["extra_attributes"][attribute];
- }
- this.sample_attr_vals.push(attr_vals);
+ console.log("raw_data: ", raw_data);
+ h = 600;
+ container = $("#bar_chart_container");
+ container.height(h + this.margin.top + this.margin.bottom);
+ if (this.chart === null) {
+ this.chart = nv.models.multiBarChart().height(h).errorBarColor((function(_this) {
+ return function() {
+ return 'red';
+ };
+ })(this)).reduceXTicks(false).staggerLabels(false).showControls(false).showLegend(false);
+ this.chart.multibar.dispatch.on('elementMouseover.tooltip', (function(_this) {
+ return function(evt) {
+ var k, ref, v;
+ evt.value = _this.chart.x()(evt.data);
+ evt['series'] = [
+ {
+ key: 'Value',
+ value: evt.data.y,
+ color: evt.color
+ }
+ ];
+ if (evt.data.yErr) {
+ evt['series'].push({
+ key: 'SE',
+ value: evt.data.yErr
+ });
+ }
+ if (evt.data.attr) {
+ ref = evt.data.attr;
+ for (k in ref) {
+ v = ref[k];
+ evt['series'].push({
+ key: k,
+ value: v
+ });
+ }
+ }
+ return _this.chart.tooltip.data(evt).hidden(false);
+ };
+ })(this));
+ this.chart.tooltip.valueFormatter(function(d, i) {
+ return d;
+ });
}
- }
- return this.samples = _.zip(this.sample_names, this.sample_vals, this.sample_attr_vals);
- };
+ return nv.addGraph((function(_this) {
+ return function() {
+ var d, s, values;
+ _this.remove_legend();
+ values = (function() {
+ var j, len, results;
+ results = [];
+ for (j = 0, len = raw_data.length; j < len; j++) {
+ s = raw_data[j];
+ results.push({
+ x: s.name,
+ y: this.value(s),
+ yErr: this.variance(s) || 0,
+ attr: s.extra_attributes
+ });
+ }
+ return results;
+ }).call(_this);
+ if (_this.attribute_name !== "None") {
+ _this.color_dict = _this.attr_color_dict[_this.attribute_name];
+ _this.chart.barColor(function(d) {
+ return _this.color_dict[d.attr[_this.attribute_name]];
+ });
+ _this.add_legend();
+ } else if (typeof _this.trait_color_dict !== 'undefined') {
+ _this.color_dict = _this.trait_color_dict;
+ _this.chart.barColor(function(d) {
+ return _this.color_dict[d['x']];
+ });
+ } else {
+ _this.chart.barColor(function() {
+ return 'steelblue';
+ });
+ }
+ _this.chart.width(raw_data.length * 20);
+ //User should be able to change Y domain, but should still have good default
+ _this.chart.yDomain([
+ 0.95 * _.min((function() { // ZS: Decreasing this constant decreases the min Y axis value
+ var j, len, results;
+ results = [];
+ for (j = 0, len = values.length; j < len; j++) {
+ d = values[j];
+ results.push(d.y - 0.5 * d.yErr); //ZS: the 0.5 was originally 1.5
+ }
+ return results;
+ })()), 1.05 * _.max((function() { // ZS: Decreasing this constant decreases the max Y axis value
+ var j, len, results;
+ results = [];
+ for (j = 0, len = values.length; j < len; j++) {
+ d = values[j];
+ results.push(d.y + 0.5 * d.yErr); // //ZS: the 0.5 was originally 1.5
+ }
+ return results;
+ })())
+ ]);
+ console.log("values: ", values);
+ d3.select("#bar_chart_container svg").datum([
+ {
+ values: values
+ }
+ ]).style('width', raw_data.length * 20 + 'px').transition().duration(1000).call(_this.chart);
+ d3.select("#bar_chart_container .nv-x").selectAll('.tick text').style("font-size", "12px").style("text-anchor", "end").attr("dx", "-.8em").attr("dy", "-.3em").attr("transform", function(d) {
+ return "rotate(-90)";
+ });
+ return _this.chart;
+ };
+ })(this));
+ };
- Bar_Chart.prototype.get_distinct_attr_vals = function() {
- var attribute, sample, _i, _len, _ref, _results;
- this.distinct_attr_vals = {};
- _ref = this.sample_attr_vals;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- sample = _ref[_i];
- _results.push((function() {
- var _ref1, _results1;
- _results1 = [];
- for (attribute in sample) {
- if (!this.distinct_attr_vals[attribute]) {
- this.distinct_attr_vals[attribute] = [];
+ Bar_Chart.prototype.get_attr_color_dict = function(vals) {
+ var color, color_range, discrete, distinct_vals, i, j, key, l, len, len1, results, this_color_dict, value;
+ this.attr_color_dict = {};
+ this.is_discrete = {};
+ this.minimum_values = {};
+ this.maximum_values = {};
+ console.log("vals:", vals);
+ results = [];
+ for (key in vals) {
+ if (!hasProp.call(vals, key)) continue;
+ distinct_vals = vals[key];
+ this.min_val = d3.min(distinct_vals);
+ this.max_val = d3.max(distinct_vals);
+ this_color_dict = {};
+ discrete = distinct_vals.length < 10;
+ if (discrete) {
+ color = d3.scale.category10();
+ for (i = j = 0, len = distinct_vals.length; j < len; i = ++j) {
+ value = distinct_vals[i];
+ this_color_dict[value] = color(i);
}
- if (_ref1 = sample[attribute], __indexOf.call(this.distinct_attr_vals[attribute], _ref1) < 0) {
- _results1.push(this.distinct_attr_vals[attribute].push(sample[attribute]));
- } else {
- _results1.push(void 0);
+ } else {
+ console.log("distinct_values:", distinct_vals);
+ if (_.every(distinct_vals, (function(_this) {
+ return function(d) {
+ if (isNaN(d)) {
+ return false;
+ } else {
+ return true;
+ }
+ };
+ })(this))) {
+ color_range = d3.scale.linear().domain([this.min_val, this.max_val]).range([0, 255]);
+ for (i = l = 0, len1 = distinct_vals.length; l < len1; i = ++l) {
+ value = distinct_vals[i];
+ console.log("color_range(value):", parseInt(color_range(value)));
+ this_color_dict[value] = d3.rgb(parseInt(color_range(value)), 0, 0);
+ }
}
}
- return _results1;
- }).call(this));
- }
- return _results;
- };
-
- Bar_Chart.prototype.create_svg = function() {
- var svg;
- svg = d3.select("#bar_chart").append("svg").attr("class", "bar_chart").attr("width", this.plot_width + this.margin.left + this.margin.right).attr("height", this.plot_height + this.margin.top + this.margin.bottom).append("g").attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");
- return svg;
- };
-
- Bar_Chart.prototype.create_scales = function() {
- this.x_scale = d3.scale.ordinal().domain(this.sample_names).rangeRoundBands([0, this.range], 0.1, 0);
- return this.y_scale = d3.scale.linear().domain([this.y_min * 0.75, this.y_max]).range([this.plot_height, this.y_buffer]);
- };
-
- Bar_Chart.prototype.create_graph = function() {
- this.add_x_axis(this.x_scale);
- this.add_y_axis();
- return this.add_bars();
- };
-
- Bar_Chart.prototype.add_x_axis = function(scale) {
- var xAxis;
- xAxis = d3.svg.axis().scale(scale).orient("bottom");
- return this.svg.append("g").attr("class", "x axis").attr("transform", "translate(0," + this.plot_height + ")").call(xAxis).selectAll("text").style("text-anchor", "end").style("font-size", "12px").attr("dx", "-.8em").attr("dy", "-.3em").attr("transform", (function(_this) {
- return function(d) {
- return "rotate(-90)";
- };
- })(this));
- };
-
- Bar_Chart.prototype.add_y_axis = function() {
- var yAxis;
- yAxis = d3.svg.axis().scale(this.y_scale).orient("left").ticks(5);
- return this.svg.append("g").attr("class", "y axis").call(yAxis).append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy", ".71em").style("text-anchor", "end");
- };
+ this.attr_color_dict[key] = this_color_dict;
+ this.is_discrete[key] = discrete;
+ this.minimum_values[key] = this.min_val;
+ results.push(this.maximum_values[key] = this.max_val);
+ }
+ return results;
+ };
- Bar_Chart.prototype.add_bars = function() {
- return this.svg.selectAll(".bar").data(this.samples).enter().append("rect").style("fill", "steelblue").attr("class", "bar").attr("x", (function(_this) {
- return function(d) {
- return _this.x_scale(d[0]);
- };
- })(this)).attr("width", this.x_scale.rangeBand()).attr("y", (function(_this) {
- return function(d) {
- return _this.y_scale(d[1]);
- };
- })(this)).attr("height", (function(_this) {
- return function(d) {
- return _this.plot_height - _this.y_scale(d[1]);
- };
- })(this)).append("svg:title").text((function(_this) {
- return function(d) {
- return d[1];
- };
- })(this));
- };
+ Bar_Chart.prototype.get_distinct_attr_vals = function() {
+ var attribute, j, len, ref, results, sample;
+ this.distinct_attr_vals = {};
+ ref = this.sample_attr_vals;
+ results = [];
+ for (j = 0, len = ref.length; j < len; j++) {
+ sample = ref[j];
+ results.push((function() {
+ var ref1, results1;
+ results1 = [];
+ for (attribute in sample) {
+ if (!this.distinct_attr_vals[attribute]) {
+ this.distinct_attr_vals[attribute] = [];
+ }
+ if (ref1 = sample[attribute], indexOf.call(this.distinct_attr_vals[attribute], ref1) < 0) {
+ results1.push(this.distinct_attr_vals[attribute].push(sample[attribute]));
+ } else {
+ results1.push(void 0);
+ }
+ }
+ return results1;
+ }).call(this));
+ }
+ return results;
+ };
- Bar_Chart.prototype.sorted_samples = function() {
- var sample_list, sorted;
- sample_list = _.zip(this.sample_names, this.sample_vals, this.sample_attr_vals);
- sorted = _.sortBy(sample_list, (function(_this) {
- return function(sample) {
- return sample[1];
- };
- })(this));
- console.log("sorted:", sorted);
- return sorted;
- };
+ Bar_Chart.prototype.add_legend = function() {
+ if (this.is_discrete[this.attribute_name]) {
+ return this.add_legend_discrete();
+ } else {
+ return this.add_legend_continuous();
+ }
+ };
- Bar_Chart.prototype.add_legend = function(attribute, distinct_vals) {
- var legend, legend_rect, legend_text;
- legend = this.svg.append("g").attr("class", "legend").attr("height", 100).attr("width", 100).attr('transform', 'translate(-20,50)');
- legend_rect = legend.selectAll('rect').data(distinct_vals).enter().append("rect").attr("x", this.plot_width - 65).attr("width", 10).attr("height", 10).attr("y", (function(_this) {
- return function(d, i) {
- return i * 20;
- };
- })(this)).style("fill", (function(_this) {
- return function(d) {
- console.log("TEST:", _this.attr_color_dict[attribute][d]);
- return _this.attr_color_dict[attribute][d];
- };
- })(this));
- return legend_text = legend.selectAll('text').data(distinct_vals).enter().append("text").attr("x", this.plot_width - 52).attr("y", (function(_this) {
- return function(d, i) {
- return i * 20 + 9;
- };
- })(this)).text((function(_this) {
- return function(d) {
- return d;
- };
- })(this));
- };
+ Bar_Chart.prototype.remove_legend = function() {
+ $(".legend").remove();
+ return $("#legend-left,#legend-right,#legend-colors").empty();
+ };
- Bar_Chart.prototype.open_trait_selection = function() {
- return $('#collections_holder').load('/collections/list?color_by_trait #collections_list', (function(_this) {
- return function() {
- $.colorbox({
- inline: true,
- href: "#collections_holder"
- });
- return $('a.collection_name').attr('onClick', 'return false');
- };
- })(this));
- };
+ Bar_Chart.prototype.add_legend_continuous = function() {
+ var svg_html;
+ $('#legend-left').html(this.minimum_values[this.attribute_name]);
+ $('#legend-right').html(this.maximum_values[this.attribute_name]);
+ svg_html = '<svg height="15" width="120"> <rect x="0" width="20" height="15" style="fill: rgb(0, 0, 0);"></rect> <rect x="20" width="20" height="15" style="fill: rgb(50, 0, 0);"></rect> <rect x="40" width="20" height="15" style="fill: rgb(100, 0, 0);"></rect> <rect x="60" width="20" height="15" style="fill: rgb(150, 0, 0);"></rect> <rect x="80" width="20" height="15" style="fill: rgb(200, 0, 0);"></rect> <rect x="100" width="20" height="15" style="fill: rgb(255, 0, 0);"></rect> </svg>';
+ console.log("svg_html:", svg_html);
+ return $('#legend-colors').html(svg_html);
+ };
- Bar_Chart.prototype.color_by_trait = function(trait_sample_data) {
- var distinct_values, trimmed_samples;
- console.log("BXD1:", trait_sample_data["BXD1"]);
- console.log("trait_sample_data:", trait_sample_data);
- trimmed_samples = this.trim_values(trait_sample_data);
- distinct_values = {};
- distinct_values["collection_trait"] = this.get_distinct_values(trimmed_samples);
- this.get_trait_color_dict(trimmed_samples, distinct_values);
- console.log("TRAIT_COLOR_DICT:", this.trait_color_dict);
- console.log("SAMPLES:", this.samples);
- if (this.sort_by = "value") {
- this.svg.selectAll(".bar").data(this.samples).transition().duration(1000).style("fill", (function(_this) {
+ Bar_Chart.prototype.add_legend_discrete = function() {
+ var legend_span;
+ legend_span = d3.select('#bar_chart_legend').append('div').style('word-wrap', 'break-word').attr('class', 'legend').selectAll('span').data(this.distinct_attr_vals[this.attribute_name]).enter().append('span').style({
+ 'word-wrap': 'normal',
+ 'display': 'inline-block'
+ });
+ legend_span.append('span').style("background-color", (function(_this) {
return function(d) {
- console.log("this color:", _this.trait_color_dict[d[0]]);
- return _this.trait_color_dict[d[0]];
+ return _this.attr_color_dict[_this.attribute_name][d];
};
- })(this)).select("title").text((function(_this) {
+ })(this)).style({
+ 'display': 'inline-block',
+ 'width': '15px',
+ 'height': '15px',
+ 'margin': '0px 5px 0px 15px'
+ });
+ return legend_span.append('span').text((function(_this) {
return function(d) {
- return d[1];
+ return d;
};
- })(this));
- return this.draw_legend();
- } else {
- this.svg.selectAll(".bar").data(this.sorted_samples()).transition().duration(1000).style("fill", (function(_this) {
- return function(d) {
- console.log("this color:", _this.trait_color_dict[d[0]]);
- return _this.trait_color_dict[d[0]];
- };
- })(this)).select("title").text((function(_this) {
- return function(d) {
- return d[1];
+ })(this)).style('font-size', '20px');
+ };
+
+ Bar_Chart.prototype.open_trait_selection = function() {
+ return $('#collections_holder').load('/collections/list?color_by_trait #collections_list', (function(_this) {
+ return function() {
+ $.colorbox({
+ inline: true,
+ href: "#collections_holder"
+ });
+ return $('a.collection_name').attr('onClick', 'return false');
};
})(this));
- return this.draw_legend();
- }
- };
+ };
- Bar_Chart.prototype.trim_values = function(trait_sample_data) {
- var sample, trimmed_samples, _i, _len, _ref;
- trimmed_samples = {};
- _ref = this.sample_names;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- sample = _ref[_i];
- if (sample in trait_sample_data) {
- trimmed_samples[sample] = trait_sample_data[sample];
+ Bar_Chart.prototype.color_by_trait = function(trait_sample_data) {
+ var distinct_values, trimmed_samples;
+ console.log("BXD1:", trait_sample_data["BXD1"]);
+ console.log("trait_sample_data:", trait_sample_data);
+ trimmed_samples = this.trim_values(trait_sample_data);
+ distinct_values = {};
+ distinct_values["collection_trait"] = this.get_distinct_values(trimmed_samples);
+ this.trait_color_dict = this.get_trait_color_dict(trimmed_samples, distinct_values);
+ console.log("TRAIT_COLOR_DICT:", this.trait_color_dict);
+ return this.rebuild_bar_graph();
+ //return console.log("SAMPLES:", this.samples);
+ };
+
+ Bar_Chart.prototype.trim_values = function(trait_sample_data) {
+ var j, len, ref, sample, trimmed_samples;
+ trimmed_samples = {};
+ ref = this.sample_lists['samples_all'];
+ for (j = 0, len = ref.length; j < len; j++) {
+ sample = ref[j]['name'];
+ if (sample in trait_sample_data) {
+ trimmed_samples[sample] = trait_sample_data[sample];
+ }
}
- }
- console.log("trimmed_samples:", trimmed_samples);
- return trimmed_samples;
- };
+ console.log("trimmed_samples:", trimmed_samples);
+ return trimmed_samples;
+ };
+
+ Bar_Chart.prototype.get_distinct_values = function(samples) {
+ var distinct_values;
+ distinct_values = _.uniq(_.values(samples));
+ console.log("distinct_values:", distinct_values);
+ return distinct_values;
+ };
+
+ Bar_Chart.prototype.get_trait_color_dict = function(samples, vals) {
+ var color, color_range, distinct_vals, i, j, k, key, len, len1, results, sample, this_color_dict, value;
+ trait_color_dict = {};
+ console.log("vals:", vals);
+ for (key in vals) {
+ if (!hasProp.call(vals, key)) continue;
+ distinct_vals = vals[key];
+ this_color_dict = {};
+ this.min_val = d3.min(distinct_vals);
+ this.max_val = d3.max(distinct_vals);
+ if (distinct_vals.length < 10) {
+ color = d3.scale.category10();
+ for (i = j = 0, len = distinct_vals.length; j < len; i = ++j) {
+ value = distinct_vals[i];
+ this_color_dict[value] = color(i);
+ }
+ } else {
+ console.log("distinct_values:", distinct_vals);
+ if (_.every(distinct_vals, (function(_this) {
+ return function(d) {
+ if (isNaN(d)) {
+ return false;
+ } else {
+ return true;
+ }
+ };
+ })(this))) {
+ color_range = d3.scale.linear().domain([d3.min(distinct_vals), d3.max(distinct_vals)]).range([0, 255]);
+ for (i = k = 0, len1 = distinct_vals.length; k < len1; i = ++k) {
+ value = distinct_vals[i];
+ //console.log("color_range(value):", parseInt(color_range(value)));
+ this_color_dict[value] = d3.rgb(parseInt(color_range(value)), 0, 0);
+ }
+ }
+ }
+ }
+ results = [];
+ console.log("SAMPLES:", samples)
+ for (sample in samples) {
+ if (!hasProp.call(samples, sample)) continue;
+ value = samples[sample];
+ trait_color_dict[sample] = this_color_dict[value];
+ //results.push(this.trait_color_dict[sample] = this_color_dict[value]);
+ }
+ return trait_color_dict;
+ };
- Bar_Chart.prototype.get_distinct_values = function(samples) {
- var distinct_values;
- distinct_values = _.uniq(_.values(samples));
- console.log("distinct_values:", distinct_values);
- return distinct_values;
- };
+ return Bar_Chart;
- return Bar_Chart;
+ })();
-})();
+ root.Bar_Chart = Bar_Chart;
-root.Bar_Chart = Bar_Chart;
+}).call(this);
diff --git a/wqflask/wqflask/static/new/javascript/chr_lod_chart.coffee b/wqflask/wqflask/static/new/javascript/chr_lod_chart.coffee
index 321957b3..e00694be 100644
--- a/wqflask/wqflask/static/new/javascript/chr_lod_chart.coffee
+++ b/wqflask/wqflask/static/new/javascript/chr_lod_chart.coffee
@@ -193,18 +193,7 @@ class Chr_Lod_Chart
.attr("fill", "black")
add_back_button: () ->
- @svg.append("text")
- .attr("class", "back")
- .text("Return to full view")
- .attr("x", @x_buffer*2)
- .attr("y", @y_buffer/2)
- .attr("dx", "0em")
- .attr("text-anchor", "middle")
- .attr("font-family", "sans-serif")
- .attr("font-size", "18px")
- .attr("cursor", "pointer")
- .attr("fill", "black")
- .on("click", @return_to_full_view)
+ $("#return_to_full_view").show().click => @return_to_full_view()
add_path: () ->
line_function = d3.svg.line()
@@ -281,9 +270,10 @@ class Chr_Lod_Chart
)
return_to_full_view: () ->
+ $("#return_to_full_view").hide()
$('#topchart').remove()
$('#chart_container').append('<div class="qtlcharts" id="topchart"></div>')
- create_manhattan_plot()
+ create_lod_chart()
show_marker_in_table: (marker_info) ->
console.log("in show_marker_in_table")
diff --git a/wqflask/wqflask/static/new/javascript/chr_lod_chart.js b/wqflask/wqflask/static/new/javascript/chr_lod_chart.js
index 95dbb4e2..616a89f6 100644
--- a/wqflask/wqflask/static/new/javascript/chr_lod_chart.js
+++ b/wqflask/wqflask/static/new/javascript/chr_lod_chart.js
@@ -1,4 +1,4 @@
-// Generated by CoffeeScript 1.8.0
+// Generated by CoffeeScript 1.9.2
var Chr_Lod_Chart;
Chr_Lod_Chart = (function() {
@@ -38,28 +38,28 @@ Chr_Lod_Chart = (function() {
}
Chr_Lod_Chart.prototype.get_max_chr = function() {
- var key, _results;
+ var key, results;
this.max_chr = 0;
- _results = [];
+ results = [];
for (key in js_data.chromosomes) {
console.log("key is:", key);
if (parseInt(key) > this.max_chr) {
- _results.push(this.max_chr = parseInt(key));
+ results.push(this.max_chr = parseInt(key));
} else {
- _results.push(void 0);
+ results.push(void 0);
}
}
- return _results;
+ return results;
};
Chr_Lod_Chart.prototype.filter_qtl_results = function() {
- var result, this_chr, _i, _len, _ref, _results;
+ var i, len, ref, result, results, this_chr;
this.these_results = [];
this_chr = 100;
- _ref = this.qtl_results;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- result = _ref[_i];
+ ref = this.qtl_results;
+ results = [];
+ for (i = 0, len = ref.length; i < len; i++) {
+ result = ref[i];
if (result.chr === "X") {
this_chr = this.max_chr;
} else {
@@ -71,20 +71,20 @@ Chr_Lod_Chart = (function() {
break;
}
if (parseInt(this_chr) === parseInt(this.chr[0])) {
- _results.push(this.these_results.push(result));
+ results.push(this.these_results.push(result));
} else {
- _results.push(void 0);
+ results.push(void 0);
}
}
- return _results;
+ return results;
};
Chr_Lod_Chart.prototype.get_qtl_count = function() {
- var high_qtl_count, result, _i, _len, _ref;
+ var high_qtl_count, i, len, ref, result;
high_qtl_count = 0;
- _ref = this.these_results;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- result = _ref[_i];
+ ref = this.these_results;
+ for (i = 0, len = ref.length; i < len; i++) {
+ result = ref[i];
if (result.lod_score > 1) {
high_qtl_count += 1;
}
@@ -94,16 +94,23 @@ Chr_Lod_Chart = (function() {
};
Chr_Lod_Chart.prototype.create_coordinates = function() {
- var result, _i, _len, _ref, _results;
- _ref = this.these_results;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- result = _ref[_i];
+ var i, len, ref, result, results;
+ ref = this.these_results;
+ console.log("THESE_RESULTS:", ref)
+ results = [];
+ for (i = 0, len = ref.length; i < len; i++) {
+ result = ref[i];
this.x_coords.push(parseFloat(result.Mb));
- this.y_coords.push(result.lod_score);
- _results.push(this.marker_names.push(result.name));
+ if (js_data.result_score_type == "LOD") {
+ this.y_coords.push(result.lod_score);
+ }
+ else {
+ console.log("LRS VALUE:", result['lrs_value'])
+ this.y_coords.push(result['lrs_value']);
+ }
+ results.push(this.marker_names.push(result.name));
}
- return _results;
+ return results;
};
Chr_Lod_Chart.prototype.create_svg = function() {
@@ -189,7 +196,11 @@ Chr_Lod_Chart = (function() {
};
Chr_Lod_Chart.prototype.add_back_button = function() {
- return this.svg.append("text").attr("class", "back").text("Return to full view").attr("x", this.x_buffer * 2).attr("y", this.y_buffer / 2).attr("dx", "0em").attr("text-anchor", "middle").attr("font-family", "sans-serif").attr("font-size", "18px").attr("cursor", "pointer").attr("fill", "black").on("click", this.return_to_full_view);
+ return $("#return_to_full_view").show().click((function(_this) {
+ return function() {
+ return _this.return_to_full_view();
+ };
+ })(this));
};
Chr_Lod_Chart.prototype.add_path = function() {
@@ -253,9 +264,10 @@ Chr_Lod_Chart = (function() {
};
Chr_Lod_Chart.prototype.return_to_full_view = function() {
+ $("#return_to_full_view").hide();
$('#topchart').remove();
$('#chart_container').append('<div class="qtlcharts" id="topchart"></div>');
- return create_manhattan_plot();
+ return create_lod_chart();
};
Chr_Lod_Chart.prototype.show_marker_in_table = function(marker_info) {
diff --git a/wqflask/wqflask/static/new/javascript/corr_matrix.js b/wqflask/wqflask/static/new/javascript/corr_matrix.js
index df0bef9d..ad0fc8b8 100644
--- a/wqflask/wqflask/static/new/javascript/corr_matrix.js
+++ b/wqflask/wqflask/static/new/javascript/corr_matrix.js
@@ -31,7 +31,7 @@ iplotCorr = function(data, chartOpts) {
ncorrX = data.cols.length;
ncorrY = data.rows.length;
corXscale = d3.scale.ordinal().domain(d3.range(ncorrX)).rangeBands([0, width]);
- corYscale = d3.scale.ordinal().domain(d3.range(ncorrY)).rangeBands([height, 0]);
+ corYscale = d3.scale.ordinal().domain(d3.range(ncorrY)).rangeBands([0, height]);
corZscale = d3.scale.linear().domain(zlim).range(corcolors);
pixel_width = corXscale(1) - corXscale(0);
pixel_height = corYscale(0) - corYscale(1);
@@ -44,12 +44,16 @@ iplotCorr = function(data, chartOpts) {
value: data.corr[i][j]
});
}
+ corrplot.append("text").attr("class", "corrlabel_y").attr("y", corYscale(i) - pixel_height / 2).attr("x", -margin.left * 0.1).text(data["var"][data.rows[i]]).attr("dominant-baseline", "middle").attr("text-anchor", "end");
+ //corrplot.append("text").attr("class", "corrlabel_x").attr("x", corXscale(i) + pixel_width / 2).attr("y", height + margin.bottom * 0.2).text(data["var"][data.cols[i]]).attr("dominant-baseline", "middle").attr("text-anchor", "middle");
+
}
scatterplot.append("rect").attr("height", height).attr("width", width).attr("fill", rectcolor).attr("stroke", "black").attr("stroke-width", 1).attr("pointer-events", "none");
corr_tip = d3.tip().attr('class', 'd3-tip').html(function(d) {
return d3.format(".2f")(d.value);
}).direction('e').offset([0, 10]);
corrplot.call(corr_tip);
+
cells = corrplot.selectAll("empty").data(corr).enter().append("rect").attr("class", "cell").attr("x", function(d) {
return corXscale(d.col);
}).attr("y", function(d) {
@@ -59,11 +63,12 @@ iplotCorr = function(data, chartOpts) {
}).attr("stroke", "none").attr("stroke-width", 2).on("mouseover", function(d) {
d3.select(this).attr("stroke", "black");
corr_tip.show(d);
- corrplot.append("text").attr("class", "corrlabel").attr("x", corXscale(d.col) + pixel_width / 2).attr("y", height + margin.bottom * 0.2).text(data["var"][data.cols[d.col]]).attr("dominant-baseline", "middle").attr("text-anchor", "middle");
- return corrplot.append("text").attr("class", "corrlabel").attr("y", corYscale(d.row) + pixel_height / 2).attr("x", -margin.left * 0.1).text(data["var"][data.rows[d.row]]).attr("dominant-baseline", "middle").attr("text-anchor", "end");
+ //corrplot.append("text").attr("class", "corrlabel").attr("x", corXscale(d.col) + pixel_width / 2).attr("y", height + margin.bottom * 0.2).text(data["var"][data.cols[d.col]]).attr("dominant-baseline", "middle").attr("text-anchor", "middle");
+ //return corrplot.append("text").attr("class", "corrlabel_x").attr("y", corYscale(d.row) + pixel_height / 2).attr("x", -margin.left * 0.1).text(data["var"][data.rows[d.row]]).attr("dominant-baseline", "middle").attr("text-anchor", "end");
+ return corrplot.append("text").attr("class", "corrlabel_x").attr("x", corXscale(d.col) + pixel_width / 2).attr("y", height + margin.bottom * 0.2).text(data["var"][data.cols[d.col]]).attr("dominant-baseline", "middle").attr("text-anchor", "middle");
}).on("mouseout", function(d) {
corr_tip.hide(d);
- d3.selectAll("text.corrlabel").remove();
+ d3.selectAll("text.corrlabel_x").remove();
return d3.select(this).attr("stroke", "none");
}).on("click", function(d) {
return drawScatter(d.col, d.row);
@@ -135,7 +140,7 @@ iplotCorr = function(data, chartOpts) {
var x, y;
x = data.dat[data.cols[i]][d];
y = data.dat[data.rows[j]][d];
- if ((x != null) && (y != null)) {
+ if ((x != "") && (y != "")) {
return 3;
} else {
return null;
diff --git a/wqflask/wqflask/static/new/javascript/create_corr_matrix.js b/wqflask/wqflask/static/new/javascript/create_corr_matrix.js
index df84b85a..adb91295 100644
--- a/wqflask/wqflask/static/new/javascript/create_corr_matrix.js
+++ b/wqflask/wqflask/static/new/javascript/create_corr_matrix.js
@@ -42,3 +42,19 @@ get_data = function() {
data.rows = js_data.rows;
return data;
};
+
+
+var neg_color_scale = chroma.scale(['#FF0000', 'white']).domain([-1, -0.4]);
+var pos_color_scale = chroma.scale(['white', 'aqua']).domain([0.4, 1])
+$('.corr_cell').each( function () {
+ corr_value = parseFloat($(this).find('span.corr_value').text())
+ if (corr_value >= 0.5){
+ $(this).css('background-color', pos_color_scale(parseFloat(corr_value)))
+ }
+ else if (corr_value <= -0.5) {
+ $(this).css('background-color', neg_color_scale(parseFloat(corr_value)))
+ }
+ else {
+ $(this).css('background-color', 'white')
+ }
+}); \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/javascript/create_lodchart.coffee b/wqflask/wqflask/static/new/javascript/create_lodchart.coffee
index 76be5490..472ec12d 100644
--- a/wqflask/wqflask/static/new/javascript/create_lodchart.coffee
+++ b/wqflask/wqflask/static/new/javascript/create_lodchart.coffee
@@ -1,4 +1,4 @@
-create_manhattan_plot = ->
+create_lod_chart = ->
h = 500
w = 1200
margin = {left:60, top:40, right:40, bottom: 40, inner:5}
@@ -18,7 +18,7 @@ create_manhattan_plot = ->
.height(h)
.width(w)
.margin(margin)
- .ylab("LOD score")
+ .ylab(js_data.result_score_type + " score")
.manhattanPlot(js_data.manhattan_plot)
#.additive(additive)
@@ -44,44 +44,11 @@ create_manhattan_plot = ->
d3.select(this)
.transition().duration(500).attr("r", r*3)
.transition().duration(500).attr("r", r)
-
-create_manhattan_plot()
-$("#export").click =>
- #Get d3 SVG element
- svg = $("#topchart").find("svg")[0]
-
- #Extract SVG text string
- svg_xml = (new XMLSerializer).serializeToString(svg)
- console.log("svg_xml:", svg_xml)
-
- #Set filename
- filename = "manhattan_plot_" + js_data.this_trait
-
- #Make a form with the SVG data
- form = $("#exportform")
- form.find("#data").val(svg_xml)
- form.find("#filename").val(filename)
- form.submit()
-
-$("#export_pdf").click =>
-
- #$('#topchart').remove()
- #$('#chart_container').append('<div class="qtlcharts" id="topchart"></div>')
- #create_interval_map()
-
- #Get d3 SVG element
- svg = $("#topchart").find("svg")[0]
-
- #Extract SVG text string
- svg_xml = (new XMLSerializer).serializeToString(svg)
- console.log("svg_xml:", svg_xml)
-
- #Set filename
- filename = "manhattan_plot_" + js_data.this_trait
+$ ->
+ #window.setTimeout ( ->
+ # console.log(js_data)
+ #), 1000
+ #window.setTimeout(create_lod_chart(), 1000)
+ root.create_lod_chart = create_lod_chart
- #Make a form with the SVG data
- form = $("#exportpdfform")
- form.find("#data").val(svg_xml)
- form.find("#filename").val(filename)
- form.submit()
diff --git a/wqflask/wqflask/static/new/javascript/create_lodchart.js b/wqflask/wqflask/static/new/javascript/create_lodchart.js
index f61f05bd..b8fcf1f8 100644
--- a/wqflask/wqflask/static/new/javascript/create_lodchart.js
+++ b/wqflask/wqflask/static/new/javascript/create_lodchart.js
@@ -1,73 +1,45 @@
-// Generated by CoffeeScript 1.8.0
-var create_manhattan_plot;
+// Generated by CoffeeScript 1.9.2
+(function() {
+ var create_lod_chart;
-create_manhattan_plot = function() {
- var additive, chrrect, data, h, halfh, margin, mychart, totalh, totalw, w;
- h = 500;
- w = 1200;
- margin = {
- left: 60,
- top: 40,
- right: 40,
- bottom: 40,
- inner: 5
- };
- halfh = h + margin.top + margin.bottom;
- totalh = halfh * 2;
- totalw = w + margin.left + margin.right;
- if ('additive' in js_data) {
- additive = js_data.additive;
- } else {
- additive = false;
- }
- console.log("js_data:", js_data);
- mychart = lodchart().lodvarname("lod.hk").height(h).width(w).margin(margin).ylab("LOD score").manhattanPlot(js_data.manhattan_plot);
- data = js_data.json_data;
- d3.select("div#topchart").datum(data).call(mychart);
- chrrect = mychart.chrSelect();
- chrrect.on("mouseover", function() {
- return d3.select(this).attr("fill", "#E9CFEC");
- }).on("mouseout", function(d, i) {
- return d3.select(this).attr("fill", function() {
- if (i % 2) {
- return "#F1F1F9";
- }
- return "#FBFBFF";
+ create_lod_chart = function() {
+ var chrrect, data, h, halfh, margin, mychart, totalh, totalw, w;
+ h = 500;
+ w = 1200;
+ margin = {
+ left: 60,
+ top: 40,
+ right: 40,
+ bottom: 40,
+ inner: 5
+ };
+ halfh = h + margin.top + margin.bottom;
+ totalh = halfh * 2;
+ totalw = w + margin.left + margin.right;
+ //console.log("js_data:", js_data);
+ mychart = lodchart().lodvarname("lod.hk").height(h).width(w).margin(margin).ylab(js_data.result_score_type + " score").manhattanPlot(js_data.manhattan_plot);
+ data = js_data.json_data;
+ d3.select("div#topchart").datum(data).call(mychart);
+ chrrect = mychart.chrSelect();
+ chrrect.on("mouseover", function() {
+ return d3.select(this).attr("fill", "#E9CFEC");
+ }).on("mouseout", function(d, i) {
+ return d3.select(this).attr("fill", function() {
+ if (i % 2) {
+ return "#F1F1F9";
+ }
+ return "#FBFBFF";
+ });
+ });
+ return mychart.markerSelect().on("click", function(d) {
+ var r;
+ r = d3.select(this).attr("r");
+ return d3.select(this).transition().duration(500).attr("r", r * 3).transition().duration(500).attr("r", r);
});
- });
- return mychart.markerSelect().on("click", function(d) {
- var r;
- r = d3.select(this).attr("r");
- return d3.select(this).transition().duration(500).attr("r", r * 3).transition().duration(500).attr("r", r);
- });
-};
-
-create_manhattan_plot();
-
-$("#export").click((function(_this) {
- return function() {
- var filename, form, svg, svg_xml;
- svg = $("#topchart").find("svg")[0];
- svg_xml = (new XMLSerializer).serializeToString(svg);
- console.log("svg_xml:", svg_xml);
- filename = "manhattan_plot_" + js_data.this_trait;
- form = $("#exportform");
- form.find("#data").val(svg_xml);
- form.find("#filename").val(filename);
- return form.submit();
};
-})(this));
-$("#export_pdf").click((function(_this) {
- return function() {
- var filename, form, svg, svg_xml;
- svg = $("#topchart").find("svg")[0];
- svg_xml = (new XMLSerializer).serializeToString(svg);
- console.log("svg_xml:", svg_xml);
- filename = "manhattan_plot_" + js_data.this_trait;
- form = $("#exportpdfform");
- form.find("#data").val(svg_xml);
- form.find("#filename").val(filename);
- return form.submit();
- };
-})(this));
+ $(function() {
+ return root.create_lod_chart = create_lod_chart;
+ });
+
+}).call(this);
diff --git a/wqflask/wqflask/static/new/javascript/dataset_menu_structure.json b/wqflask/wqflask/static/new/javascript/dataset_menu_structure.json
index fabf3998..e790c9c0 100755
--- a/wqflask/wqflask/static/new/javascript/dataset_menu_structure.json
+++ b/wqflask/wqflask/static/new/javascript/dataset_menu_structure.json
@@ -56,12 +56,6 @@
},
"barley": {
"QSM": {
- "Genotypes": [
- [
- "QSMGeno",
- "QSM Genotypes"
- ]
- ],
"Leaf mRNA": [
[
"B1LI0809R",
@@ -79,12 +73,6 @@
"B1MI0809R",
"Barley1 Leaf MOCK TTKS (Aug09) RMA"
]
- ],
- "Phenotypes": [
- [
- "QSMPublish",
- "QSM Published Phenotypes"
- ]
]
},
"SXM": {
@@ -114,12 +102,12 @@
"Barley1 Leaf MAS 5.0 SCRI (Dec06)"
],
[
- "B30_K_1206_Rn",
- "Barley1 Leaf gcRMAn SCRI (Dec06)"
- ],
- [
"B30_K_1206_R",
"Barley1 Leaf gcRMA SCRI (Dec06)"
+ ],
+ [
+ "B30_K_1206_Rn",
+ "Barley1 Leaf gcRMAn SCRI (Dec06)"
]
],
"Phenotypes": [
@@ -132,18 +120,6 @@
},
"drosophila": {
"DGRP": {
- "Genotypes": [
- [
- "DGRPGeno",
- "DGRP Genotypes"
- ]
- ],
- "Phenotypes": [
- [
- "DGRPPublish",
- "DGRP Published Phenotypes"
- ]
- ],
"Whole Body mRNA": [
[
"NCSU_DrosWB_LC_RMA_0111",
@@ -152,18 +128,6 @@
]
},
"Oregon-R_x_2b3": {
- "Genotypes": [
- [
- "Oregon-R_x_2b3Geno",
- "Oregon-R_x_2b3 Genotypes"
- ]
- ],
- "Phenotypes": [
- [
- "Oregon-R_x_2b3Publish",
- "Oregon-R_x_2b3 Published Phenotypes"
- ]
- ],
"Whole Body mRNA": [
[
"UAB_DrosWB_LC_RMA_1009",
@@ -195,18 +159,6 @@
"GSE5281_RMA0709",
"GSE5281 Human Brain Best 102 Liang (Jul09) RMA"
]
- ],
- "Genotypes": [
- [
- "AD-cases-controlsGeno",
- "AD-cases-controls Genotypes"
- ]
- ],
- "Phenotypes": [
- [
- "AD-cases-controlsPublish",
- "AD-cases-controls Published Phenotypes"
- ]
]
},
"AD-cases-controls-Myers": {
@@ -229,12 +181,6 @@
"AD-cases-controls-MyersGeno",
"AD-cases-controls-Myers Genotypes"
]
- ],
- "Phenotypes": [
- [
- "AD-cases-controls-MyersPublish",
- "AD-cases-controls-Myers Published Phenotypes"
- ]
]
},
"Aging-Brain-UCI": {
@@ -244,24 +190,12 @@
"GSE11882 UCI Human Entorhinal Cortex Affy U133 Plus2 (Sep13) RMA"
]
],
- "Genotypes": [
- [
- "Aging-Brain-UCIGeno",
- "Aging-Brain-UCI Genotypes"
- ]
- ],
"Hippocampus mRNA": [
[
"UCI_HC_0913",
"GSE11882 UCI Human Hippocampus Affy U133 Plus2 (Sep13) RMA"
]
],
- "Phenotypes": [
- [
- "Aging-Brain-UCIPublish",
- "Aging-Brain-UCI Published Phenotypes"
- ]
- ],
"Postcentral Gyrus mRNA": [
[
"UCI_PCG_0913",
@@ -282,18 +216,6 @@
"GSE15745 NIH Human Brain Cerebellum ILM humanRef-8 v2.0 (May10) RankInv"
]
],
- "Genotypes": [
- [
- "Brain-Normal-NIH-GibbsGeno",
- "Brain-Normal-NIH-Gibbs Genotypes"
- ]
- ],
- "Phenotypes": [
- [
- "Brain-Normal-NIH-GibbsPublish",
- "Brain-Normal-NIH-Gibbs Published Phenotypes"
- ]
- ],
"Pons mRNA": [
[
"GSE15745-GPL6104_Po0510",
@@ -314,12 +236,6 @@
]
},
"CANDLE": {
- "Genotypes": [
- [
- "CANDLEGeno",
- "CANDLE Genotypes"
- ]
- ],
"Methylation": [
[
"CANDLE_Meth27_0313",
@@ -344,12 +260,6 @@
]
},
"CEPH-2004": {
- "Genotypes": [
- [
- "CEPH-2004Geno",
- "CEPH-2004 Genotypes"
- ]
- ],
"Lymphoblast B-cell mRNA": [
[
"UT_CEPH_RankInv0909",
@@ -359,12 +269,6 @@
"Human_1008",
"Monks CEPH B-cells Agilent (Dec04) Log10Ratio"
]
- ],
- "Phenotypes": [
- [
- "CEPH-2004Publish",
- "CEPH-2004 Published Phenotypes"
- ]
]
},
"GTEx": {
@@ -558,12 +462,6 @@
"GTEx Human Frontal Cortex (Apr14) RPKM"
]
],
- "Genotypes": [
- [
- "GTExGeno",
- "GTEx Genotypes"
- ]
- ],
"Heart - Atrial Appendage mRNA": [
[
"GTEx_log2_HeartAt_0314",
@@ -684,12 +582,6 @@
"GTEx Human Pancreas (Apr14) RPKM"
]
],
- "Phenotypes": [
- [
- "GTExPublish",
- "GTEx Published Phenotypes"
- ]
- ],
"Pituitary Gland mRNA": [
[
"GTEx_log2_Pitui_0314",
@@ -870,18 +762,6 @@
"HBTRC-MLC Human Cerebellum Agilent HD (Jun11) mlratio"
]
],
- "Genotypes": [
- [
- "HBGeno",
- "HB Genotypes"
- ]
- ],
- "Phenotypes": [
- [
- "HBPublish",
- "HB Published Phenotypes"
- ]
- ],
"Prefrontal Cortex mRNA": [
[
"HBTRC-MLPFC_0611",
@@ -920,12 +800,6 @@
]
},
"HCP": {
- "Genotypes": [
- [
- "HCPGeno",
- "HCP Genotypes"
- ]
- ],
"Phenotypes": [
[
"HCPPublish",
@@ -934,12 +808,6 @@
]
},
"HLC": {
- "Genotypes": [
- [
- "HLCGeno",
- "HLC Genotypes"
- ]
- ],
"Liver mRNA": [
[
"HLC_0311",
@@ -962,12 +830,6 @@
]
},
"HLT": {
- "Genotypes": [
- [
- "HLTGeno",
- "HLT Genotypes"
- ]
- ],
"Lung mRNA": [
[
"GSE23546HLT0613",
@@ -985,12 +847,6 @@
"GRNG-GSE23545HLT0613",
"GRNG/GSE23545 Whole-Genome GXD Non-Tumorous Human Lung Tissues Affy HuRSTA array (Jun11) RMA"
]
- ],
- "Phenotypes": [
- [
- "HLTPublish",
- "HLT Published Phenotypes"
- ]
]
},
"HSB": {
@@ -1012,12 +868,6 @@
"Human Dorsolateral Prefrontal Cortex Affy Hu-Exon 1.0 ST (Jul11) Quantile"
]
],
- "Genotypes": [
- [
- "HSBGeno",
- "HSB Genotypes"
- ]
- ],
"Hippocampus mRNA": [
[
"KIN_YSM_HIP_0711",
@@ -1048,12 +898,6 @@
"Human Orbital Prefrontal Cortex Affy Hu-Exon 1.0 ST (Jul11) Quantile"
]
],
- "Phenotypes": [
- [
- "HSBPublish",
- "HSB Published Phenotypes"
- ]
- ],
"Posterior Inferior Parietal Cortex mRNA": [
[
"KIN_YSM_IPC_0711",
@@ -1118,12 +962,6 @@
"INIA Macaca fasicularis Brain (Jan10) RMA **"
]
],
- "Genotypes": [
- [
- "Macaca-fasicularisGeno",
- "Macaca-fasicularis Genotypes"
- ]
- ],
"Hippocampus mRNA": [
[
"INIA_MacFas_Hc_RMA_0110",
@@ -1136,12 +974,6 @@
"INIA Macaca fasicularis Nucleus Accumbens (Jan10) RMA **"
]
],
- "Phenotypes": [
- [
- "Macaca-fasicularisPublish",
- "Macaca-fasicularis Published Phenotypes"
- ]
- ],
"Prefrontal Cortex mRNA": [
[
"INIA_MacFas_Pf_RMA_0110",
@@ -1164,18 +996,12 @@
"NCI Mammary LMT miRNA v2 (Apr09) RMA"
],
[
- "MA_M_0704_R",
- "NCI Mammary mRNA M430 (July04) RMA"
- ],
- [
"MA_M_0704_M",
"NCI Mammary mRNA M430 (July04) MAS5"
- ]
- ],
- "Phenotypes": [
+ ],
[
- "AKXDPublish",
- "AKXD Published Phenotypes"
+ "MA_M_0704_R",
+ "NCI Mammary mRNA M430 (July04) RMA"
]
]
},
@@ -1226,12 +1052,12 @@
],
"Liver mRNA": [
[
- "LVF2_M_0704_R",
- "(B6 x BTBR)F2-ob/ob Liver mRNA M430 (Jul04) RMA"
- ],
- [
"LVF2_M_0704_M",
"(B6 x BTBR)F2-ob/ob Liver mRNA M430 (Jul04) MAS5"
+ ],
+ [
+ "LVF2_M_0704_R",
+ "(B6 x BTBR)F2-ob/ob Liver mRNA M430 (Jul04) RMA"
]
],
"Phenotypes": [
@@ -1244,10 +1070,6 @@
"B6D2F2": {
"Brain mRNA": [
[
- "BRF2_M_0805_M",
- "OHSU/VA B6D2F2 Brain mRNA M430 (Aug05) MAS5"
- ],
- [
"BRF2_M_0805_P",
"OHSU/VA B6D2F2 Brain mRNA M430 (Aug05) PDNN"
],
@@ -1256,16 +1078,20 @@
"OHSU/VA B6D2F2 Brain mRNA M430 (Aug05) RMA"
],
[
- "BRF2_M_0304_P",
- "OHSU/VA B6D2F2 Brain mRNA M430A (Mar04) PDNN"
+ "BRF2_M_0805_M",
+ "OHSU/VA B6D2F2 Brain mRNA M430 (Aug05) MAS5"
],
[
- "BRF2_M_0304_R",
- "OHSU/VA B6D2F2 Brain mRNA M430A (Mar04) RMA"
+ "BRF2_M_0304_P",
+ "OHSU/VA B6D2F2 Brain mRNA M430A (Mar04) PDNN"
],
[
"BRF2_M_0304_M",
"OHSU/VA B6D2F2 Brain mRNA M430A (Mar04) MAS5"
+ ],
+ [
+ "BRF2_M_0304_R",
+ "OHSU/VA B6D2F2 Brain mRNA M430A (Mar04) RMA"
]
],
"Genotypes": [
@@ -1273,12 +1099,6 @@
"B6D2F2Geno",
"B6D2F2 Genotypes"
]
- ],
- "Phenotypes": [
- [
- "B6D2F2Publish",
- "B6D2F2 Published Phenotypes"
- ]
]
},
"B6D2F2-PSU": {
@@ -1305,32 +1125,14 @@
"PSU-B6D2F2_M2000812",
"PSU B6D2F2 Muscle Affy Mouse Genome 430 2.0 (Aug12) RMA Males Aged 200 **"
]
- ],
- "Phenotypes": [
- [
- "B6D2F2-PSUPublish",
- "B6D2F2-PSU Published Phenotypes"
- ]
]
},
"B6D2RI": {
- "Genotypes": [
- [
- "B6D2RIGeno",
- "B6D2RI Genotypes"
- ]
- ],
"Hippocampus mRNA": [
[
"UTHSC_B6D2RI_H_0912",
"UTHSC B6D2RI Aged Hippocampus Affy Mouse Gene 1.0 ST (Sep12) RMA **"
]
- ],
- "Phenotypes": [
- [
- "B6D2RIPublish",
- "B6D2RI Published Phenotypes"
- ]
]
},
"BDF2-1999": {
@@ -1345,12 +1147,6 @@
"UCLA_BDF2_LIVER_1999",
"UCLA BDF2 Liver (1999) mlratio"
]
- ],
- "Phenotypes": [
- [
- "BDF2-1999Publish",
- "BDF2-1999 Published Phenotypes"
- ]
]
},
"BDF2-2005": {
@@ -1360,52 +1156,46 @@
"BDF2-2005 Genotypes"
]
],
- "Phenotypes": [
- [
- "BDF2-2005Publish",
- "BDF2-2005 Published Phenotypes"
- ]
- ],
"Striatum mRNA": [
[
- "SA_M2_0905_R",
- "OHSU/VA B6D2F2 Striatum M430v2 (Sep05) RMA"
- ],
- [
"SA_M2_0905_M",
"OHSU/VA B6D2F2 Striatum M430v2 (Sep05) MAS5"
],
[
"SA_M2_0905_P",
"OHSU/VA B6D2F2 Striatum M430v2 (Sep05) PDNN"
+ ],
+ [
+ "SA_M2_0905_R",
+ "OHSU/VA B6D2F2 Striatum M430v2 (Sep05) RMA"
]
]
},
"BHF2": {
"Adipose mRNA": [
[
- "UCLA_BHF2_ADIPOSE_MALE",
- "UCLA BHF2 Adipose Male mlratio"
- ],
- [
"UCLA_BHF2_ADIPOSE_FEMALE",
"UCLA BHF2 Adipose Female mlratio"
],
[
+ "UCLA_BHF2_ADIPOSE_MALE",
+ "UCLA BHF2 Adipose Male mlratio"
+ ],
+ [
"UCLA_BHF2_ADIPOSE_0605",
"UCLA BHF2 Adipose (June05) mlratio"
]
],
"Brain mRNA": [
[
- "UCLA_BHF2_BRAIN_MALE",
- "UCLA BHF2 Brain Male mlratio"
- ],
- [
"UCLA_BHF2_BRAIN_FEMALE",
"UCLA BHF2 Brain Female mlratio"
],
[
+ "UCLA_BHF2_BRAIN_MALE",
+ "UCLA BHF2 Brain Male mlratio"
+ ],
+ [
"UCLA_BHF2_BRAIN_0605",
"UCLA BHF2 Brain (June05) mlratio"
]
@@ -1418,37 +1208,31 @@
],
"Liver mRNA": [
[
- "UCLA_BHF2_LIVER_MALE",
- "UCLA BHF2 Liver Male mlratio"
- ],
- [
"UCLA_BHF2_LIVER_FEMALE",
"UCLA BHF2 Liver Female mlratio"
],
[
+ "UCLA_BHF2_LIVER_MALE",
+ "UCLA BHF2 Liver Male mlratio"
+ ],
+ [
"UCLA_BHF2_LIVER_0605",
"UCLA BHF2 Liver (June05) mlratio"
]
],
"Muscle mRNA": [
[
- "UCLA_BHF2_MUSCLE_MALE",
- "UCLA BHF2 Muscle Male mlratio **"
- ],
- [
"UCLA_BHF2_MUSCLE_FEMALE",
"UCLA BHF2 Muscle Female mlratio **"
],
[
+ "UCLA_BHF2_MUSCLE_MALE",
+ "UCLA BHF2 Muscle Male mlratio **"
+ ],
+ [
"UCLA_BHF2_MUSCLE_0605",
"UCLA BHF2 Muscle (June05) mlratio **"
]
- ],
- "Phenotypes": [
- [
- "BHF2Publish",
- "BHF2 Published Phenotypes"
- ]
]
},
"BHHBF2": {
@@ -1513,12 +1297,6 @@
"UCLA_BHHBF2_MUSCLE_FEMALE",
"UCLA BHHBF2 Muscle Female Only"
]
- ],
- "Phenotypes": [
- [
- "BHHBF2Publish",
- "BHHBF2 Published Phenotypes"
- ]
]
},
"BXD": {
@@ -1604,14 +1382,14 @@
"UTHSC Mouse BXD Whole Brain RNA Sequence (Nov12) RPKM Trimmed 2.0"
],
[
- "UTHSC_BXD_WB_RNASeq1112",
- "UTHSC Mouse BXD Whole Brain RNA Sequence (Nov12) RPKM Untrimmed"
- ],
- [
"UTHSC_BXD_WB_RNASeqtrim1_1112",
"UTHSC Mouse BXD Whole Brain RNA Sequence (Nov12) RPKM Trimmed 1.0"
],
[
+ "UTHSC_BXD_WB_RNASeq1112",
+ "UTHSC Mouse BXD Whole Brain RNA Sequence (Nov12) RPKM Untrimmed"
+ ],
+ [
"UTHSC_BXD_WB_RNASeqEx1112",
"UTHSC Mouse BXD Whole Brain RNA Sequence Exon Level (Nov12) RPKM"
],
@@ -1624,6 +1402,10 @@
"UTHSC Brain mRNA U74Av2 (Nov05) PDNN"
],
[
+ "BR_U_0805_P",
+ "UTHSC Brain mRNA U74Av2 (Aug05) PDNN"
+ ],
+ [
"BR_U_0805_M",
"UTHSC Brain mRNA U74Av2 (Aug05) MAS5"
],
@@ -1632,10 +1414,6 @@
"UTHSC Brain mRNA U74Av2 (Aug05) RMA"
],
[
- "BR_U_0805_P",
- "UTHSC Brain mRNA U74Av2 (Aug05) PDNN"
- ],
- [
"CB_M_0204_P",
"INIA Brain mRNA M430 (Feb04) PDNN"
]
@@ -1746,10 +1524,6 @@
"Eye M430v2 WT Gpnmb (Sep08) RMA **"
],
[
- "Eye_M2_0908_R_MT",
- "Eye M430v2 Mutant Tyrp1 (Sep08) RMA **"
- ],
- [
"Eye_M2_0908_WTWT",
"Eye M430v2 WT WT (Sep08) RMA **"
],
@@ -1758,6 +1532,10 @@
"Eye M430v2 WT Tyrp1 (Sep08) RMA **"
],
[
+ "Eye_M2_0908_R_MT",
+ "Eye M430v2 Mutant Tyrp1 (Sep08) RMA **"
+ ],
+ [
"DBA2J-ONH-1212",
"Howell et al. 2011, DBA/2J Glaucoma Optic Nerve Head M430 2.0 (Dec12) RMA"
],
@@ -1962,12 +1740,12 @@
"Mouse Kidney M430v2 Sex Balanced (Aug06) PDNN"
],
[
- "MA_M2_0706_P",
- "Mouse Kidney M430v2 (Jul06) PDNN"
- ],
- [
"MA_M2_0706_R",
"Mouse Kidney M430v2 (Jul06) RMA"
+ ],
+ [
+ "MA_M2_0706_P",
+ "Mouse Kidney M430v2 (Jul06) PDNN"
]
],
"Leucocytes mRNA": [
@@ -1988,14 +1766,14 @@
],
"Liver Proteome": [
[
- "EPFLETHZBXDprotHFD0514",
- "EPFL/ETHZ BXD Liver, Soluble Proteins HFD (May14) SWATH **"
- ],
- [
"EPFLETHZBXDprotCD0514",
"EPFL/ETHZ BXD Liver, Soluble Proteins CD (May14) SWATH **"
],
[
+ "EPFLETHZBXDprotHFD0514",
+ "EPFL/ETHZ BXD Liver, Soluble Proteins HFD (May14) SWATH **"
+ ],
+ [
"EPFLBXDprotHFDRPN0214",
"EPFL/LISP BXD Liver, Soluble Proteins HFD (Feb14) SRM **"
],
@@ -2132,14 +1910,14 @@
],
"Neocortex mRNA": [
[
- "DevNeocortex_ILM6.2P14RInv_1111",
- "BIDMC/UTHSC Dev Neocortex P14 ILMv6.2 (Nov11) RankInv"
- ],
- [
"DevNeocortex_ILM6.2P3RInv_1111",
"BIDMC/UTHSC Dev Neocortex P3 ILMv6.2 (Nov11) RankInv"
],
[
+ "DevNeocortex_ILM6.2P14RInv_1111",
+ "BIDMC/UTHSC Dev Neocortex P14 ILMv6.2 (Nov11) RankInv"
+ ],
+ [
"HQFNeoc_1210v2_RankInv",
"HQF BXD Neocortex ILM6v1.1 (Dec10v2) RankInv"
],
@@ -2152,12 +1930,12 @@
"HQF BXD Neocortex ILM6v1.1 (Feb08) RankInv"
],
[
- "DevNeocortex_ILM6.2P3RInv_1110",
- "BIDMC/UTHSC Dev Neocortex P3 ILMv6.2 (Nov10) RankInv"
- ],
- [
"DevNeocortex_ILM6.2P14RInv_1110",
"BIDMC/UTHSC Dev Neocortex P14 ILMv6.2 (Nov10) RankInv"
+ ],
+ [
+ "DevNeocortex_ILM6.2P3RInv_1110",
+ "BIDMC/UTHSC Dev Neocortex P3 ILMv6.2 (Nov10) RankInv"
]
],
"Nucleus Accumbens mRNA": [
@@ -2256,14 +2034,14 @@
"ONC HEI Retina (April 2012) RankInv"
],
[
- "DoDTATRCRetMoGene2_1313",
- "DoD TATRC Retina Affy MoGene 2.0 ST (Dec13) RMA"
- ],
- [
"DoDTATRCRetExMoGene2_1313",
"DoD TATRC Retina Affy MoGene 2.0 ST (Dec13) RMA Exon Level"
],
[
+ "DoDTATRCRetMoGene2_1313",
+ "DoD TATRC Retina Affy MoGene 2.0 ST (Dec13) RMA"
+ ],
+ [
"ONCRetMoGene2_0413",
"DoD TATRC Retina Affy MoGene 2.0 ST (Oct13) RMA **"
],
@@ -2284,12 +2062,12 @@
"B6D2 ONC Retina (April 2012) RankInv **"
],
[
- "HEIONCvsCRetILM6_0911",
- "HEI ONC vs Control Retina Illumina V6.2 (Sep11) RankInv **"
- ],
- [
"G2HEIONCRetILM6_0911",
"G2 HEI ONC Retina Illumina V6.2 (Sep11) RankInv **"
+ ],
+ [
+ "HEIONCvsCRetILM6_0911",
+ "HEI ONC vs Control Retina Illumina V6.2 (Sep11) RankInv **"
]
],
"Spleen mRNA": [
@@ -2376,12 +2154,12 @@
"BIDMC/UTHSC Dev Striatum P14 ILMv6.2 (Nov11) RankInv **"
],
[
- "DevStriatum_ILM6.2P14RInv_1110",
- "BIDMC/UTHSC Dev Striatum P14 ILMv6.2 (Nov10) RankInv **"
- ],
- [
"DevStriatum_ILM6.2P3RInv_1110",
"BIDMC/UTHSC Dev Striatum P3 ILMv6.2 (Nov10) RankInv **"
+ ],
+ [
+ "DevStriatum_ILM6.2P14RInv_1110",
+ "BIDMC/UTHSC Dev Striatum P14 ILMv6.2 (Nov10) RankInv **"
]
],
"T Cell (helper) mRNA": [
@@ -2404,16 +2182,16 @@
],
"Ventral Tegmental Area mRNA": [
[
- "VCUEtOH_0609_R",
- "VCU BXD VTA EtOH M430 2.0 (Jun09) RMA **"
- ],
- [
"VCUSal_0609_R",
"VCU BXD VTA Sal M430 2.0 (Jun09) RMA **"
],
[
"VCUEtvsSal_0609_R",
"VCU BXD VTA Et vs Sal M430 2.0 (Jun09) Sscore **"
+ ],
+ [
+ "VCUEtOH_0609_R",
+ "VCU BXD VTA EtOH M430 2.0 (Jun09) RMA **"
]
]
},
@@ -2550,12 +2328,12 @@
],
"Hippocampus mRNA": [
[
- "HC_M2CB_1205_R",
- "Hippocampus Consortium M430v2 CXB (Dec05) RMA"
- ],
- [
"HC_M2CB_1205_P",
"Hippocampus Consortium M430v2 CXB (Dec05) PDNN"
+ ],
+ [
+ "HC_M2CB_1205_R",
+ "Hippocampus Consortium M430v2 CXB (Dec05) RMA"
]
],
"Phenotypes": [
@@ -2572,12 +2350,6 @@
]
},
"HS": {
- "Genotypes": [
- [
- "HSGeno",
- "HS Genotypes"
- ]
- ],
"Hippocampus mRNA": [
[
"OXUKHS_ILMHipp_RI0510",
@@ -2604,18 +2376,6 @@
]
},
"HS-CC": {
- "Genotypes": [
- [
- "HS-CCGeno",
- "HS-CC Genotypes"
- ]
- ],
- "Phenotypes": [
- [
- "HS-CCPublish",
- "HS-CC Published Phenotypes"
- ]
- ],
"Striatum mRNA": [
[
"OHSU_HS-CC_ILMStr_0211",
@@ -2660,14 +2420,6 @@
"Hippocampus Illumina (May07) RankInv"
],
[
- "Illum_LXS_Hipp_NON_1008",
- "Hippocampus Illumina NON (Oct08) RankInv beta"
- ],
- [
- "Illum_LXS_Hipp_RSE_1008",
- "Hippocampus Illumina RSE (Oct08) RankInv beta"
- ],
- [
"Illum_LXS_Hipp_NOE_1008",
"Hippocampus Illumina NOE (Oct08) RankInv beta"
],
@@ -2678,6 +2430,14 @@
[
"Illum_LXS_Hipp_NOS_1008",
"Hippocampus Illumina NOS (Oct08) RankInv beta"
+ ],
+ [
+ "Illum_LXS_Hipp_NON_1008",
+ "Hippocampus Illumina NON (Oct08) RankInv beta"
+ ],
+ [
+ "Illum_LXS_Hipp_RSE_1008",
+ "Hippocampus Illumina RSE (Oct08) RankInv beta"
]
],
"Phenotypes": [
@@ -2688,16 +2448,16 @@
],
"Prefrontal Cortex mRNA": [
[
- "VCUEtOH_0806_R",
- "VCU LXS PFC EtOH M430A 2.0 (Aug06) RMA **"
- ],
- [
"VCUSal_0806_R",
"VCU LXS PFC Sal M430A 2.0 (Aug06) RMA"
],
[
"VCUEt_vs_Sal_0806_R",
"VCU LXS PFC Et vs Sal M430A 2.0 (Aug06) Sscore **"
+ ],
+ [
+ "VCUEtOH_0806_R",
+ "VCU LXS PFC EtOH M430A 2.0 (Aug06) RMA **"
]
]
},
@@ -2736,12 +2496,12 @@
],
"Hippocampus mRNA": [
[
- "UMUTAffyExon_0209_RMA_MDP",
- "UMUTAffy Hippocampus Exon (Feb09) RMA MDP"
- ],
- [
"HC_M2_0606_MDP",
"Hippocampus Consortium M430v2 (Jun06) RMA MDP"
+ ],
+ [
+ "UMUTAffyExon_0209_RMA_MDP",
+ "UMUTAffy Hippocampus Exon (Feb09) RMA MDP"
]
],
"Liver mRNA": [
@@ -2774,12 +2534,6 @@
]
},
"NZBXFVB-N2": {
- "Genotypes": [
- [
- "NZBXFVB-N2Geno",
- "NZBXFVB-N2 Genotypes"
- ]
- ],
"Mammary Tumors mRNA": [
[
"NCI_Mam_Tum_RMA_0409",
@@ -2799,12 +2553,6 @@
"SOTNOT-OHSUGeno",
"SOTNOT-OHSU Genotypes"
]
- ],
- "Phenotypes": [
- [
- "SOTNOT-OHSUPublish",
- "SOTNOT-OHSU Published Phenotypes"
- ]
]
},
"Scripps-2013": {
@@ -2817,29 +2565,11 @@
"ScrBXDACC4GEx0513",
"Scripps BXD ACC 4 Groups Affy Mouse Gene 1.0 ST (May13) RMA Exon Level **"
]
- ],
- "Genotypes": [
- [
- "Scripps-2013Geno",
- "Scripps-2013 Genotypes"
- ]
- ],
- "Phenotypes": [
- [
- "Scripps-2013Publish",
- "Scripps-2013 Published Phenotypes"
- ]
]
}
},
"rat": {
"HSNIH": {
- "Genotypes": [
- [
- "HSNIHGeno",
- "HSNIH Genotypes"
- ]
- ],
"Phenotypes": [
[
"HSNIHPublish",
@@ -2915,18 +2645,6 @@
"UIOWA_Eye_RMA_0906",
"UIOWA Eye mRNA RAE230v2 (Sep06) RMA"
]
- ],
- "Genotypes": [
- [
- "SRxSHRSPF2Geno",
- "SRxSHRSPF2 Genotypes"
- ]
- ],
- "Phenotypes": [
- [
- "SRxSHRSPF2Publish",
- "SRxSHRSPF2 Published Phenotypes"
- ]
]
}
},
@@ -2946,12 +2664,6 @@
]
},
"J12XJ58F2": {
- "Genotypes": [
- [
- "J12XJ58F2Geno",
- "J12XJ58F2 Genotypes"
- ]
- ],
"Phenotypes": [
[
"J12XJ58F2Publish",
@@ -2962,12 +2674,6 @@
},
"tomato": {
"LXP": {
- "Genotypes": [
- [
- "LXPGeno",
- "LXP Genotypes"
- ]
- ],
"Phenotypes": [
[
"LXPPublish",
@@ -3285,14 +2991,6 @@
"barley": {
"QSM": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Leaf mRNA",
"Leaf mRNA"
]
@@ -3319,28 +3017,12 @@
"drosophila": {
"DGRP": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Whole Body mRNA",
"Whole Body mRNA"
]
],
"Oregon-R_x_2b3": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Whole Body mRNA",
"Whole Body mRNA"
]
@@ -3349,24 +3031,12 @@
"human": {
"AD-cases-controls": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Brain mRNA",
"Brain mRNA"
]
],
"AD-cases-controls-Myers": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
"Genotypes",
"Genotypes"
],
@@ -3377,14 +3047,6 @@
],
"Aging-Brain-UCI": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Entorhinal Cortex mRNA",
"Entorhinal Cortex mRNA"
],
@@ -3403,14 +3065,6 @@
],
"Brain-Normal-NIH-Gibbs": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Cerebellum mRNA",
"Cerebellum mRNA"
],
@@ -3433,10 +3087,6 @@
"Phenotypes"
],
[
- "Genotypes",
- "Genotypes"
- ],
- [
"Methylation",
"Methylation"
],
@@ -3447,28 +3097,12 @@
],
"CEPH-2004": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Lymphoblast B-cell mRNA",
"Lymphoblast B-cell mRNA"
]
],
"GTEx": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Adrenal Gland mRNA",
"Adrenal Gland mRNA"
],
@@ -3659,14 +3293,6 @@
],
"HB": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Cerebellum mRNA",
"Cerebellum mRNA"
],
@@ -3683,10 +3309,6 @@
[
"Phenotypes",
"Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
]
],
"HLC": [
@@ -3695,38 +3317,18 @@
"Phenotypes"
],
[
- "Genotypes",
- "Genotypes"
- ],
- [
"Liver mRNA",
"Liver mRNA"
]
],
"HLT": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Lung mRNA",
"Lung mRNA"
]
],
"HSB": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Amygdala mRNA",
"Amygdala mRNA"
],
@@ -3795,14 +3397,6 @@
"macaque monkey": {
"Macaca-fasicularis": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Amygdala mRNA",
"Amygdala mRNA"
],
@@ -3827,10 +3421,6 @@
"mouse": {
"AKXD": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
"Genotypes",
"Genotypes"
],
@@ -3881,10 +3471,6 @@
],
"B6D2F2": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
"Genotypes",
"Genotypes"
],
@@ -3895,10 +3481,6 @@
],
"B6D2F2-PSU": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
"Genotypes",
"Genotypes"
],
@@ -3909,24 +3491,12 @@
],
"B6D2RI": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Hippocampus mRNA",
"Hippocampus mRNA"
]
],
"BDF2-1999": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
"Genotypes",
"Genotypes"
],
@@ -3937,10 +3507,6 @@
],
"BDF2-2005": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
"Genotypes",
"Genotypes"
],
@@ -3951,10 +3517,6 @@
],
"BHF2": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
"Genotypes",
"Genotypes"
],
@@ -3977,10 +3539,6 @@
],
"BHHBF2": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
"Genotypes",
"Genotypes"
],
@@ -4233,10 +3791,6 @@
"Phenotypes"
],
[
- "Genotypes",
- "Genotypes"
- ],
- [
"Hippocampus mRNA",
"Hippocampus mRNA"
],
@@ -4251,14 +3805,6 @@
],
"HS-CC": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Striatum mRNA",
"Striatum mRNA"
]
@@ -4323,34 +3869,18 @@
"Phenotypes"
],
[
- "Genotypes",
- "Genotypes"
- ],
- [
"Mammary Tumors mRNA",
"Mammary Tumors mRNA"
]
],
"SOTNOT-OHSU": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
"Genotypes",
"Genotypes"
]
],
"Scripps-2013": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Anterior Cingulate Cortex mRNA",
"Anterior Cingulate Cortex mRNA"
]
@@ -4361,10 +3891,6 @@
[
"Phenotypes",
"Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
]
],
"HXBBXH": [
@@ -4403,14 +3929,6 @@
],
"SRxSHRSPF2": [
[
- "Phenotypes",
- "Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
- ],
- [
"Eye mRNA",
"Eye mRNA"
]
@@ -4431,10 +3949,6 @@
[
"Phenotypes",
"Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
]
]
},
@@ -4443,10 +3957,6 @@
[
"Phenotypes",
"Phenotypes"
- ],
- [
- "Genotypes",
- "Genotypes"
]
]
}
diff --git a/wqflask/wqflask/static/new/javascript/dataset_select_menu.js b/wqflask/wqflask/static/new/javascript/dataset_select_menu.js
index 5bd54359..f91504be 100644
--- a/wqflask/wqflask/static/new/javascript/dataset_select_menu.js
+++ b/wqflask/wqflask/static/new/javascript/dataset_select_menu.js
@@ -94,6 +94,7 @@ $(function() {
$('#dataset_info').click(dataset_info);
make_default = function() {
var holder, item, jholder, _i, _len, _ref;
+ alert("The current settings are now your default.")
holder = {};
_ref = ['species', 'group', 'type', 'dataset'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
@@ -134,10 +135,12 @@ $(function() {
return _results;
};
check_search_term = function() {
- var search_term;
- search_term = $('#tfor').val();
- console.log("search_term:", search_term);
- if (search_term === "") {
+ var or_search_term, and_search_term;
+ or_search_term = $('#or_search').val();
+ and_search_term = $('#and_search').val();
+ console.log("or_search_term:", or_search_term);
+ console.log("and_search_term:", and_search_term);
+ if (or_search_term === "" && and_search_term === "") {
alert("Please enter one or more search terms or search equations.");
return false;
}
diff --git a/wqflask/wqflask/static/new/javascript/draw_probability_plot.coffee b/wqflask/wqflask/static/new/javascript/draw_probability_plot.coffee
index a2345dcb..09ab3bc4 100644
--- a/wqflask/wqflask/static/new/javascript/draw_probability_plot.coffee
+++ b/wqflask/wqflask/static/new/javascript/draw_probability_plot.coffee
@@ -1,35 +1,94 @@
-# illustration of use of the scatterplot function
-
-h = 400
-w = 500
-margin = {left:60, top:40, right:40, bottom: 40, inner:5}
-halfh = (h+margin.top+margin.bottom)
-totalh = halfh*2
-halfw = (w+margin.left+margin.right)
-totalw = halfw*2
-
-# Example 1: simplest use
-#d3.json "data.json", (data) ->
-mychart = scatterplot().xvar(0)
- .yvar(1)
- .height(h)
- .width(w)
- .margin(margin)
-
-data = js_data.probability_plot_data
-#indID = js_data.indIDs
-#slope = js_data.slope
-#intercept = js_data.intercept
-
-console.log("THE DATA IS:", data)
-
-d3.select("div#prob_plot")
- .datum({data:data})
- .call(mychart)
-
-# animate points
-mychart.pointsSelect()
- .on "mouseover", (d) ->
- d3.select(this).attr("r", mychart.pointsize()*3)
- .on "mouseout", (d) ->
- d3.select(this).attr("r", mychart.pointsize())
+root = exports ? this
+
+# calculations here use the same formulae as scipy.stats.probplot
+get_z_scores = (n) ->
+ # order statistic medians (Filliben's approximation)
+ osm_uniform = new Array(n)
+ osm_uniform[n - 1] = Math.pow(0.5, 1.0 / n)
+ osm_uniform[0] = 1 - osm_uniform[n - 1]
+ for i in [1 .. (n - 2)]
+ osm_uniform[i] = (i + 1 - 0.3175) / (n + 0.365)
+
+ return (jStat.normal.inv(x, 0, 1) for x in osm_uniform)
+
+# samples is {'samples_primary': {'name1': value1, ...},
+# 'samples_other': {'nameN': valueN, ...},
+# 'samples_all': {'name1': value1, ...}}
+redraw_prob_plot = (samples, sample_group) ->
+ h = 600
+ w = 600
+ margin = {left:60, top:40, right:40, bottom: 40, inner:5}
+ totalh = h + margin.top + margin.bottom
+ totalw = w + margin.left + margin.right
+
+ container = $("#prob_plot_container")
+ container.width(totalw)
+ container.height(totalh)
+
+ nv.addGraph(() =>
+ chart = nv.models.scatterChart()
+ .width(w)
+ .height(h)
+ .showLegend(true)
+ .color(d3.scale.category10().range())
+
+ # size settings are quite counter-intuitive in NVD3!
+ chart.pointRange([50,50]) # (50 is the area, not radius)
+
+ chart.legend.updateState(false)
+
+ chart.xAxis
+ .axisLabel("Theoretical quantiles")
+ .tickFormat(d3.format('.02f'))
+
+ chart.yAxis
+ .axisLabel("Sample quantiles")
+ .tickFormat(d3.format('.02f'))
+
+ chart.tooltipContent((obj) =>
+ return '<b style="font-size: 20px">' + obj.point.name + '</b>'
+ )
+
+ all_samples = samples[sample_group]
+ names = (x for x in _.keys(all_samples) when all_samples[x] != null)
+ sorted_names = names.sort((x, y) => all_samples[x].value - all_samples[y].value)
+ sorted_values = (all_samples[x].value for x in sorted_names)
+ sw_result = ShapiroWilkW(sorted_values)
+ W = sw_result.w.toFixed(3)
+ pvalue = sw_result.p.toFixed(3)
+ pvalue_str = if pvalue > 0.05 then\
+ pvalue.toString()\
+ else\
+ "<span style='color:red'>"+pvalue+"</span>"
+ test_str = "Shapiro-Wilk test statistic is #{W} (p = #{pvalue_str})"
+
+ z_scores = get_z_scores(sorted_values.length)
+ slope = jStat.stdev(sorted_values)
+ intercept = jStat.mean(sorted_values)
+
+ make_data = (group_name) ->
+ return {
+ key: js_data.sample_group_types[group_name],
+ slope: slope,
+ intercept: intercept,
+ values: ({x: z_score, y: value, name: sample}\
+ for [z_score, value, sample] in\
+ _.zip(get_z_scores(sorted_values.length),
+ sorted_values,
+ sorted_names)\
+ when sample of samples[group_name])
+ }
+
+ data = [make_data('samples_primary'), make_data('samples_other')]
+ console.log("THE DATA IS:", data)
+ d3.select("#prob_plot_container svg")
+ .datum(data)
+ .call(chart)
+
+ $("#prob_plot_title").html("<h3>Normal probability plot</h3>"+test_str)
+ $("#prob_plot_container .nv-legendWrap").toggle(sample_group == "samples_all")
+
+ return chart
+ )
+
+root.redraw_prob_plot_impl = redraw_prob_plot
diff --git a/wqflask/wqflask/static/new/javascript/draw_probability_plot.js b/wqflask/wqflask/static/new/javascript/draw_probability_plot.js
index f2bf09e6..3eb6295f 100644
--- a/wqflask/wqflask/static/new/javascript/draw_probability_plot.js
+++ b/wqflask/wqflask/static/new/javascript/draw_probability_plot.js
@@ -1,38 +1,122 @@
-// Generated by CoffeeScript 1.8.0
-var data, h, halfh, halfw, margin, mychart, totalh, totalw, w;
+// Generated by CoffeeScript 1.9.2
+(function() {
+ var get_z_scores, redraw_prob_plot, root;
-h = 400;
+ root = typeof exports !== "undefined" && exports !== null ? exports : this;
-w = 500;
+ get_z_scores = function(n) {
+ var i, j, osm_uniform, ref, x;
+ osm_uniform = new Array(n);
+ osm_uniform[n - 1] = Math.pow(0.5, 1.0 / n);
+ osm_uniform[0] = 1 - osm_uniform[n - 1];
+ for (i = j = 1, ref = n - 2; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) {
+ osm_uniform[i] = (i + 1 - 0.3175) / (n + 0.365);
+ }
+ return (function() {
+ var k, len, results;
+ results = [];
+ for (k = 0, len = osm_uniform.length; k < len; k++) {
+ x = osm_uniform[k];
+ results.push(jStat.normal.inv(x, 0, 1));
+ }
+ return results;
+ })();
+ };
-margin = {
- left: 60,
- top: 40,
- right: 40,
- bottom: 40,
- inner: 5
-};
+ redraw_prob_plot = function(samples, sample_group) {
+ var container, h, margin, totalh, totalw, w;
+ h = 600;
+ w = 600;
+ margin = {
+ left: 60,
+ top: 40,
+ right: 40,
+ bottom: 40,
+ inner: 5
+ };
+ totalh = h + margin.top + margin.bottom;
+ totalw = w + margin.left + margin.right;
+ container = $("#prob_plot_container");
+ container.width(totalw);
+ container.height(totalh);
+ return nv.addGraph((function(_this) {
+ return function() {
+ var W, all_samples, chart, data, intercept, make_data, names, pvalue, pvalue_str, slope, sorted_names, sorted_values, sw_result, test_str, x, z_scores;
+ chart = nv.models.scatterChart().width(w).height(h).showLegend(true).color(d3.scale.category10().range());
+ chart.pointRange([50, 50]);
+ chart.legend.updateState(false);
+ chart.xAxis.axisLabel("Theoretical quantiles").tickFormat(d3.format('.02f'));
+ chart.yAxis.axisLabel("Sample quantiles").tickFormat(d3.format('.02f'));
+ chart.tooltipContent(function(obj) {
+ return '<b style="font-size: 20px">' + obj.point.name + '</b>';
+ });
+ all_samples = samples[sample_group];
+ names = (function() {
+ var j, len, ref, results;
+ ref = _.keys(all_samples);
+ results = [];
+ for (j = 0, len = ref.length; j < len; j++) {
+ x = ref[j];
+ if (all_samples[x] !== null) {
+ results.push(x);
+ }
+ }
+ return results;
+ })();
+ sorted_names = names.sort(function(x, y) {
+ return all_samples[x].value - all_samples[y].value;
+ });
+ sorted_values = (function() {
+ var j, len, results;
+ results = [];
+ for (j = 0, len = sorted_names.length; j < len; j++) {
+ x = sorted_names[j];
+ results.push(all_samples[x].value);
+ }
+ return results;
+ })();
+ sw_result = ShapiroWilkW(sorted_values);
+ W = sw_result.w.toFixed(3);
+ pvalue = sw_result.p.toFixed(3);
+ pvalue_str = pvalue > 0.05 ? pvalue.toString() : "<span style='color:red'>" + pvalue + "</span>";
+ test_str = "Shapiro-Wilk test statistic is " + W + " (p = " + pvalue_str + ")";
+ z_scores = get_z_scores(sorted_values.length);
+ slope = jStat.stdev(sorted_values);
+ intercept = jStat.mean(sorted_values);
+ make_data = function(group_name) {
+ var sample, value, z_score;
+ return {
+ key: js_data.sample_group_types[group_name],
+ slope: slope,
+ intercept: intercept,
+ values: (function() {
+ var j, len, ref, ref1, results;
+ ref = _.zip(get_z_scores(sorted_values.length), sorted_values, sorted_names);
+ results = [];
+ for (j = 0, len = ref.length; j < len; j++) {
+ ref1 = ref[j], z_score = ref1[0], value = ref1[1], sample = ref1[2];
+ if (sample in samples[group_name]) {
+ results.push({
+ x: z_score,
+ y: value,
+ name: sample
+ });
+ }
+ }
+ return results;
+ })()
+ };
+ };
+ data = [make_data('samples_primary'), make_data('samples_other')];
+ console.log("THE DATA IS:", data);
+ d3.select("#prob_plot_container svg").datum(data).call(chart);
+ $("#prob_plot_title").html("<h3>Normal probability plot</h3>" + test_str);
+ $("#prob_plot_container .nv-legendWrap").toggle(sample_group === "samples_all");
+ return chart;
+ };
+ })(this));
+ };
-halfh = h + margin.top + margin.bottom;
+ root.redraw_prob_plot_impl = redraw_prob_plot;
-totalh = halfh * 2;
-
-halfw = w + margin.left + margin.right;
-
-totalw = halfw * 2;
-
-mychart = scatterplot().xvar(0).yvar(1).height(h).width(w).margin(margin);
-
-data = js_data.probability_plot_data;
-
-console.log("THE DATA IS:", data);
-
-d3.select("div#prob_plot").datum({
- data: data
-}).call(mychart);
-
-mychart.pointsSelect().on("mouseover", function(d) {
- return d3.select(this).attr("r", mychart.pointsize() * 3);
-}).on("mouseout", function(d) {
- return d3.select(this).attr("r", mychart.pointsize());
-});
+}).call(this);
diff --git a/wqflask/wqflask/static/new/javascript/histogram.coffee b/wqflask/wqflask/static/new/javascript/histogram.coffee
index 98f89ac6..68d9b5a2 100755
--- a/wqflask/wqflask/static/new/javascript/histogram.coffee
+++ b/wqflask/wqflask/static/new/javascript/histogram.coffee
@@ -4,7 +4,6 @@ class Histogram
constructor: (@sample_list, @sample_group) ->
@sort_by = "name"
@format_count = d3.format(",.0f") #a formatter for counts
- @get_sample_vals()
@margin = {top: 10, right: 30, bottom: 30, left: 30}
@plot_width = 960 - @margin.left - @margin.right
@@ -12,21 +11,25 @@ class Histogram
@x_buffer = @plot_width/20
@y_buffer = @plot_height/20
+ @plot_height -= @y_buffer
+
+ @get_sample_vals(@sample_list)
+ @redraw(@sample_vals)
+ redraw: (@sample_vals) ->
@y_min = d3.min(@sample_vals)
@y_max = d3.max(@sample_vals) * 1.1
-
- @plot_height -= @y_buffer
+
@create_x_scale()
@get_histogram_data()
@create_y_scale()
+ $("#histogram").empty()
@svg = @create_svg()
-
@create_graph()
- get_sample_vals: () ->
- @sample_vals = (sample.value for sample in @sample_list when sample.value != null)
+ get_sample_vals: (sample_list) ->
+ @sample_vals = (sample.value for sample in sample_list when sample.value != null)
create_svg: () ->
svg = d3.select("#histogram")
@@ -53,8 +56,9 @@ class Histogram
get_histogram_data: () ->
console.log("sample_vals:", @sample_vals)
+ n_bins = Math.sqrt(@sample_vals.length)
@histogram_data = d3.layout.histogram()
- .bins(@x_scale.ticks(20))(@sample_vals)
+ .bins(@x_scale.ticks(n_bins))(@sample_vals)
console.log("histogram_data:", @histogram_data[0])
create_y_scale: () ->
@@ -112,17 +116,20 @@ class Histogram
.attr("class", "bar")
.attr("transform", (d) =>
return "translate(" + @x_scale(d.x) + "," + @y_scale(d.y) + ")")
+
+ rect_width = @x_scale(@histogram_data[0].x + @histogram_data[0].dx) -
+ @x_scale(@histogram_data[0].x)
bar.append("rect")
.attr("x", 1)
- .attr("width", @x_scale(@histogram_data[0].x + @histogram_data[0].dx) - 1)
+ .attr("width", rect_width - 1)
.attr("height", (d) =>
return @plot_height - @y_scale(d.y)
)
bar.append("text")
.attr("dy", ".75em")
.attr("y", 6)
- .attr("x", @x_scale(@histogram_data[0].dx)/2)
+ .attr("x", rect_width / 2)
.attr("text-anchor", "middle")
.style("fill", "#fff")
.text((d) =>
@@ -131,4 +138,4 @@ class Histogram
return @format_count(d.y)
)
-root.Histogram = Histogram \ No newline at end of file
+root.Histogram = Histogram
diff --git a/wqflask/wqflask/static/new/javascript/histogram.js b/wqflask/wqflask/static/new/javascript/histogram.js
index 561a3068..d26d0c03 100755
--- a/wqflask/wqflask/static/new/javascript/histogram.js
+++ b/wqflask/wqflask/static/new/javascript/histogram.js
@@ -1,124 +1,135 @@
-// Generated by CoffeeScript 1.8.0
-var Histogram, root;
-
-root = typeof exports !== "undefined" && exports !== null ? exports : this;
-
-Histogram = (function() {
- function Histogram(sample_list, sample_group) {
- this.sample_list = sample_list;
- this.sample_group = sample_group;
- this.sort_by = "name";
- this.format_count = d3.format(",.0f");
- this.get_sample_vals();
- this.margin = {
- top: 10,
- right: 30,
- bottom: 30,
- left: 30
+// Generated by CoffeeScript 1.9.2
+(function() {
+ var Histogram, root;
+
+ root = typeof exports !== "undefined" && exports !== null ? exports : this;
+
+ Histogram = (function() {
+ function Histogram(sample_list1, sample_group) {
+ this.sample_list = sample_list1;
+ this.sample_group = sample_group;
+ this.sort_by = "name";
+ this.format_count = d3.format(",.0f");
+ this.margin = {
+ top: 10,
+ right: 30,
+ bottom: 30,
+ left: 30
+ };
+ this.plot_width = 960 - this.margin.left - this.margin.right;
+ this.plot_height = 500 - this.margin.top - this.margin.bottom;
+ this.x_buffer = this.plot_width / 20;
+ this.y_buffer = this.plot_height / 20;
+ this.plot_height -= this.y_buffer;
+ this.get_sample_vals(this.sample_list);
+ this.redraw(this.sample_vals);
+ }
+
+ Histogram.prototype.redraw = function(sample_vals) {
+ this.sample_vals = sample_vals;
+ this.y_min = d3.min(this.sample_vals);
+ this.y_max = d3.max(this.sample_vals) * 1.1;
+ this.create_x_scale();
+ this.get_histogram_data();
+ this.create_y_scale();
+ $("#histogram").empty();
+ this.svg = this.create_svg();
+ return this.create_graph();
};
- this.plot_width = 960 - this.margin.left - this.margin.right;
- this.plot_height = 500 - this.margin.top - this.margin.bottom;
- this.x_buffer = this.plot_width / 20;
- this.y_buffer = this.plot_height / 20;
- this.y_min = d3.min(this.sample_vals);
- this.y_max = d3.max(this.sample_vals) * 1.1;
- this.plot_height -= this.y_buffer;
- this.create_x_scale();
- this.get_histogram_data();
- this.create_y_scale();
- this.svg = this.create_svg();
- this.create_graph();
- }
-
- Histogram.prototype.get_sample_vals = function() {
- var sample;
- return this.sample_vals = (function() {
- var _i, _len, _ref, _results;
- _ref = this.sample_list;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- sample = _ref[_i];
- if (sample.value !== null) {
- _results.push(sample.value);
+
+ Histogram.prototype.get_sample_vals = function(sample_list) {
+ var sample;
+ return this.sample_vals = (function() {
+ var i, len, results;
+ results = [];
+ for (i = 0, len = sample_list.length; i < len; i++) {
+ sample = sample_list[i];
+ if (sample.value !== null) {
+ results.push(sample.value);
+ }
}
- }
- return _results;
- }).call(this);
- };
-
- Histogram.prototype.create_svg = function() {
- var svg;
- svg = d3.select("#histogram").append("svg").attr("class", "histogram").attr("width", this.plot_width + this.margin.left + this.margin.right).attr("height", this.plot_height + this.margin.top + this.margin.bottom).append("g").attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");
- return svg;
- };
-
- Histogram.prototype.create_x_scale = function() {
- var x0;
- console.log("min/max:", d3.min(this.sample_vals) + "," + d3.max(this.sample_vals));
- x0 = Math.max(-d3.min(this.sample_vals), d3.max(this.sample_vals));
- return this.x_scale = d3.scale.linear().domain([d3.min(this.sample_vals), d3.max(this.sample_vals)]).range([0, this.plot_width]).nice();
- };
-
- Histogram.prototype.get_histogram_data = function() {
- console.log("sample_vals:", this.sample_vals);
- this.histogram_data = d3.layout.histogram().bins(this.x_scale.ticks(20))(this.sample_vals);
- return console.log("histogram_data:", this.histogram_data[0]);
- };
-
- Histogram.prototype.create_y_scale = function() {
- return this.y_scale = d3.scale.linear().domain([
- 0, d3.max(this.histogram_data, (function(_this) {
+ return results;
+ })();
+ };
+
+ Histogram.prototype.create_svg = function() {
+ var svg;
+ svg = d3.select("#histogram").append("svg").attr("class", "histogram").attr("width", this.plot_width + this.margin.left + this.margin.right).attr("height", this.plot_height + this.margin.top + this.margin.bottom).append("g").attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");
+ return svg;
+ };
+
+ Histogram.prototype.create_x_scale = function() {
+ var x0;
+ console.log("min/max:", d3.min(this.sample_vals) + "," + d3.max(this.sample_vals));
+ x0 = Math.max(-d3.min(this.sample_vals), d3.max(this.sample_vals));
+ return this.x_scale = d3.scale.linear().domain([d3.min(this.sample_vals), d3.max(this.sample_vals)]).range([0, this.plot_width]).nice();
+ };
+
+ Histogram.prototype.get_histogram_data = function() {
+ var n_bins;
+ console.log("sample_vals:", this.sample_vals);
+ n_bins = 2*Math.sqrt(this.sample_vals.length); //Was originally just the square root, but increased to 2*; ideally would be a GUI for changing this
+ this.histogram_data = d3.layout.histogram().bins(this.x_scale.ticks(n_bins))(this.sample_vals);
+ return console.log("histogram_data:", this.histogram_data[0]);
+ };
+
+ Histogram.prototype.create_y_scale = function() {
+ return this.y_scale = d3.scale.linear().domain([
+ 0, d3.max(this.histogram_data, (function(_this) {
+ return function(d) {
+ return d.y;
+ };
+ })(this))
+ ]).range([this.plot_height, 0]);
+ };
+
+ Histogram.prototype.create_graph = function() {
+ this.add_x_axis();
+ this.add_y_axis();
+ return this.add_bars();
+ };
+
+ Histogram.prototype.add_x_axis = function() {
+ var x_axis;
+ x_axis = d3.svg.axis().scale(this.x_scale).orient("bottom");
+ return this.svg.append("g").attr("class", "x axis").attr("transform", "translate(0," + this.plot_height + ")").call(x_axis);
+ };
+
+ Histogram.prototype.add_y_axis = function() {
+ var yAxis;
+ yAxis = d3.svg.axis().scale(this.y_scale).orient("left").ticks(5);
+ return this.svg.append("g").attr("class", "y axis").call(yAxis).append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy", ".71em").style("text-anchor", "end");
+ };
+
+ Histogram.prototype.add_bars = function() {
+ var bar, rect_width;
+ console.log("bar_width:", this.x_scale(this.histogram_data[0].dx));
+ bar = this.svg.selectAll(".bar").data(this.histogram_data).enter().append("g").attr("class", "bar").attr("transform", (function(_this) {
return function(d) {
- return d.y;
+ return "translate(" + _this.x_scale(d.x) + "," + _this.y_scale(d.y) + ")";
};
- })(this))
- ]).range([this.plot_height, 0]);
- };
-
- Histogram.prototype.create_graph = function() {
- this.add_x_axis();
- this.add_y_axis();
- return this.add_bars();
- };
-
- Histogram.prototype.add_x_axis = function() {
- var x_axis;
- x_axis = d3.svg.axis().scale(this.x_scale).orient("bottom");
- return this.svg.append("g").attr("class", "x axis").attr("transform", "translate(0," + this.plot_height + ")").call(x_axis);
- };
-
- Histogram.prototype.add_y_axis = function() {
- var yAxis;
- yAxis = d3.svg.axis().scale(this.y_scale).orient("left").ticks(5);
- return this.svg.append("g").attr("class", "y axis").call(yAxis).append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy", ".71em").style("text-anchor", "end");
- };
-
- Histogram.prototype.add_bars = function() {
- var bar;
- console.log("bar_width:", this.x_scale(this.histogram_data[0].dx));
- bar = this.svg.selectAll(".bar").data(this.histogram_data).enter().append("g").attr("class", "bar").attr("transform", (function(_this) {
- return function(d) {
- return "translate(" + _this.x_scale(d.x) + "," + _this.y_scale(d.y) + ")";
- };
- })(this));
- bar.append("rect").attr("x", 1).attr("width", this.x_scale(this.histogram_data[0].x + this.histogram_data[0].dx) - 1).attr("height", (function(_this) {
- return function(d) {
- return _this.plot_height - _this.y_scale(d.y);
- };
- })(this));
- return bar.append("text").attr("dy", ".75em").attr("y", 6).attr("x", this.x_scale(this.histogram_data[0].dx) / 2).attr("text-anchor", "middle").style("fill", "#fff").text((function(_this) {
- return function(d) {
- var bar_height;
- bar_height = _this.plot_height - _this.y_scale(d.y);
- if (bar_height > 20) {
- return _this.format_count(d.y);
- }
- };
- })(this));
- };
+ })(this));
+ rect_width = this.x_scale(this.histogram_data[0].x + this.histogram_data[0].dx) - this.x_scale(this.histogram_data[0].x);
+ bar.append("rect").attr("x", 1).attr("width", rect_width - 1).attr("height", (function(_this) {
+ return function(d) {
+ return _this.plot_height - _this.y_scale(d.y);
+ };
+ })(this));
+ return bar.append("text").attr("dy", ".75em").attr("y", 6).attr("x", rect_width / 2).attr("text-anchor", "middle").style("fill", "#fff").text((function(_this) {
+ return function(d) {
+ var bar_height;
+ bar_height = _this.plot_height - _this.y_scale(d.y);
+ if (bar_height > 20) {
+ return _this.format_count(d.y);
+ }
+ };
+ })(this));
+ };
+
+ return Histogram;
- return Histogram;
+ })();
-})();
+ root.Histogram = Histogram;
-root.Histogram = Histogram;
+}).call(this);
diff --git a/wqflask/wqflask/static/new/javascript/lod_chart.coffee b/wqflask/wqflask/static/new/javascript/lod_chart.coffee
index b0f4b2f5..55ffdce0 100644
--- a/wqflask/wqflask/static/new/javascript/lod_chart.coffee
+++ b/wqflask/wqflask/static/new/javascript/lod_chart.coffee
@@ -1,514 +1,517 @@
-lodchart = () ->
- width = 800
- height = 500
- margin = {left:60, top:40, right:40, bottom: 40, inner:5}
- axispos = {xtitle:25, ytitle:30, xlabel:5, ylabel:5}
- titlepos = 20
- manhattanPlot = false
- additive = false
- ylim = null
- additive_ylim = null
- nyticks = 5
- yticks = null
- additive_yticks = null
- chrGap = 8
- darkrect = "#F1F1F9"
- lightrect = "#FBFBFF"
- lodlinecolor = "darkslateblue"
- additivelinecolor = "red"
- linewidth = 2
- suggestivecolor = "gainsboro"
- significantcolor = "#EBC7C7"
- pointcolor = "#E9CFEC" # pink
- pointsize = 0 # default = no visible points at markers
- pointstroke = "black"
- title = ""
- xlab = "Chromosome"
- ylab = "LRS score"
- additive_ylab = "Additive Effect"
- rotate_ylab = null
- yscale = d3.scale.linear()
- additive_yscale = d3.scale.linear()
- xscale = null
- pad4heatmap = false
- lodcurve = null
- lodvarname = null
- markerSelect = null
- chrSelect = null
- pointsAtMarkers = true
-
-
- ## the main function
- chart = (selection) ->
- selection.each (data) ->
-
- #console.log("data:", data)
-
- if manhattanPlot == true
- pointcolor = "darkslateblue"
- pointsize = 2
-
- lodvarname = lodvarname ? data.lodnames[0]
- data[lodvarname] = (Math.abs(x) for x in data[lodvarname]) # take absolute values
- ylim = ylim ? [0, d3.max(data[lodvarname])]
- if additive
- data['additive'] = (Math.abs(x) for x in data['additive'])
- additive_ylim = additive_ylim ? [0, d3.max(data['additive'])]
-
- lodvarnum = data.lodnames.indexOf(lodvarname)
-
- # Select the svg element, if it exists.
- svg = d3.select(this).selectAll("svg").data([data])
-
- # Otherwise, create the skeletal chart.
- gEnter = svg.enter().append("svg").append("g")
-
- # Update the outer dimensions.
- svg.attr("width", width+margin.left+margin.right)
- .attr("height", height+margin.top+margin.bottom)
-
- # Update the inner dimensions.
- g = svg.select("g")
-
- # box
- g.append("rect")
- .attr("x", margin.left)
- .attr("y", margin.top)
- .attr("height", height)
- .attr("width", width)
- .attr("fill", darkrect)
- .attr("stroke", "none")
-
- yscale.domain(ylim)
- .range([height+margin.top, margin.top+margin.inner])
-
- # if yticks not provided, use nyticks to choose pretty ones
- yticks = yticks ? yscale.ticks(nyticks)
-
- #if data['additive'].length > 0
- if additive
- additive_yscale.domain(additive_ylim)
- .range([height+margin.top, margin.top+margin.inner + height/2])
-
- additive_yticks = additive_yticks ? additive_yscale.ticks(nyticks)
-
- # reorganize lod,pos by chromosomes
- reorgLodData(data, lodvarname)
-
- # add chromosome scales (for x-axis)
- data = chrscales(data, width, chrGap, margin.left, pad4heatmap)
- xscale = data.xscale
-
- # chr rectangles
- chrSelect =
- g.append("g").attr("class", "chrRect")
- .selectAll("empty")
- .data(data.chrnames)
- .enter()
- .append("rect")
- .attr("id", (d) -> "chrrect#{d[0]}")
- .attr("x", (d,i) ->
- return data.chrStart[i] if i==0 and pad4heatmap
- data.chrStart[i]-chrGap/2)
- .attr("width", (d,i) ->
- return data.chrEnd[i] - data.chrStart[i]+chrGap/2 if (i==0 or i+1 == data.chrnames.length) and pad4heatmap
- data.chrEnd[i] - data.chrStart[i]+chrGap)
- .attr("y", margin.top)
- .attr("height", height)
- .attr("fill", (d,i) ->
- return darkrect if i % 2
- lightrect)
- .attr("stroke", "none")
- .on("click", (d) ->
- console.log("d is:", d)
- redraw_plot(d)
- )
-
- # x-axis labels
- xaxis = g.append("g").attr("class", "x axis")
- xaxis.selectAll("empty")
- .data(data.chrnames)
- .enter()
- .append("text")
- .text((d) -> d[0])
- .attr("x", (d,i) -> (data.chrStart[i]+data.chrEnd[i])/2)
- .attr("y", margin.top+height+axispos.xlabel)
- .attr("dominant-baseline", "hanging")
- .attr("text-anchor", "middle")
- .attr("cursor", "pointer")
- .on("click", (d) ->
- redraw_plot(d)
- )
-
- xaxis.append("text").attr("class", "title")
- .attr("y", margin.top+height+axispos.xtitle)
- .attr("x", margin.left+width/2)
- .attr("fill", "slateblue")
- .text(xlab)
-
-
- redraw_plot = (chr_ob) ->
- #console.log("chr_name is:", chr_ob[0])
- #console.log("chr_length is:", chr_ob[1])
- $('#topchart').remove()
- $('#chart_container').append('<div class="qtlcharts" id="topchart"></div>')
- chr_plot = new Chr_Lod_Chart(600, 1200, chr_ob, manhattanPlot)
-
- # y-axis
- rotate_ylab = rotate_ylab ? (ylab.length > 1)
- yaxis = g.append("g").attr("class", "y axis")
- yaxis.selectAll("empty")
- .data(yticks)
- .enter()
- .append("line")
- .attr("y1", (d) -> yscale(d))
- .attr("y2", (d) -> yscale(d))
- .attr("x1", margin.left)
- .attr("x2", margin.left+7)
- .attr("fill", "none")
- .attr("stroke", "white")
- .attr("stroke-width", 1)
- .style("pointer-events", "none")
-
- yaxis.selectAll("empty")
- .data(yticks)
- .enter()
- .append("text")
- .attr("y", (d) -> yscale(d))
- .attr("x", margin.left-axispos.ylabel)
- .attr("fill", "blue")
- .attr("dominant-baseline", "middle")
- .attr("text-anchor", "end")
- .text((d) -> formatAxis(yticks)(d))
-
- yaxis.append("text").attr("class", "title")
- .attr("y", margin.top+height/2)
- .attr("x", margin.left-axispos.ytitle)
- .text(ylab)
- .attr("transform", if rotate_ylab then "rotate(270,#{margin.left-axispos.ytitle},#{margin.top+height/2})" else "")
- .attr("text-anchor", "middle")
- .attr("fill", "slateblue")
-
- #if data['additive'].length > 0
- if additive
- rotate_additive_ylab = rotate_additive_ylab ? (additive_ylab.length > 1)
- additive_yaxis = g.append("g").attr("class", "y axis")
- additive_yaxis.selectAll("empty")
- .data(additive_yticks)
- .enter()
- .append("line")
- .attr("y1", (d) -> additive_yscale(d))
- .attr("y2", (d) -> additive_yscale(d))
- .attr("x1", margin.left + width)
- .attr("x2", margin.left + width - 7)
- .attr("fill", "none")
- .attr("stroke", "white")
- .attr("stroke-width", 1)
- .style("pointer-events", "none")
-
- additive_yaxis.selectAll("empty")
- .data(additive_yticks)
- .enter()
- .append("text")
- .attr("y", (d) -> additive_yscale(d))
- .attr("x", (d) -> margin.left + width + axispos.ylabel + 20)
- .attr("fill", "green")
- .attr("dominant-baseline", "middle")
- .attr("text-anchor", "end")
- .text((d) -> formatAxis(additive_yticks)(d))
-
- additive_yaxis.append("text").attr("class", "title")
- .attr("y", margin.top+1.5*height)
- .attr("x", margin.left + width + axispos.ytitle)
- .text(additive_ylab)
- .attr("transform", if rotate_additive_ylab then "rotate(270,#{margin.left + width + axispos.ytitle}, #{margin.top+height*1.5})" else "")
- .attr("text-anchor", "middle")
- .attr("fill", "green")
-
- if 'suggestive' of data
- suggestive_bar = g.append("g").attr("class", "suggestive")
- suggestive_bar.selectAll("empty")
- .data([data.suggestive])
- .enter()
- .append("line")
- .attr("y1", (d) -> yscale(d))
- .attr("y2", (d) -> yscale(d))
- .attr("x1", margin.left)
- .attr("x2", margin.left+width)
- .attr("fill", "none")
- .attr("stroke", suggestivecolor)
- .attr("stroke-width", 5)
- .style("pointer-events", "none")
-
- suggestive_bar = g.append("g").attr("class", "significant")
- suggestive_bar.selectAll("empty")
- .data([data.significant])
- .enter()
- .append("line")
- .attr("y1", (d) -> yscale(d))
- .attr("y2", (d) -> yscale(d))
- .attr("x1", margin.left)
- .attr("x2", margin.left+width)
- .attr("fill", "none")
- .attr("stroke", significantcolor)
- .attr("stroke-width", 5)
- .style("pointer-events", "none")
-
- if manhattanPlot == false
- # lod curves by chr
- lodcurve = (chr, lodcolumn) ->
- d3.svg.line()
- .x((d) -> xscale[chr](d))
- .y((d,i) -> yscale(data.lodByChr[chr][i][lodcolumn]))
-
- if additive
- additivecurve = (chr, lodcolumn) ->
- d3.svg.line()
- .x((d) -> xscale[chr](d))
- .y((d,i) -> additive_yscale(data.additiveByChr[chr][i][lodcolumn]))
-
- curves = g.append("g").attr("id", "curves")
-
- for chr in data.chrnames
- curves.append("path")
- .datum(data.posByChr[chr[0]])
- .attr("d", lodcurve(chr[0], lodvarnum))
- .attr("stroke", lodlinecolor)
- .attr("fill", "none")
- .attr("stroke-width", linewidth)
- .style("pointer-events", "none")
-
- if additive
- for chr in data.chrnames
- curves.append("path")
- .datum(data.posByChr[chr[0]])
- .attr("d", additivecurve(chr[0], lodvarnum))
- .attr("stroke", additivelinecolor)
- .attr("fill", "none")
- .attr("stroke-width", 1)
- .style("pointer-events", "none")
-
- # points at markers
- console.log("before pointsize")
- if pointsize > 0
- console.log("pointsize > 0 !!!")
- markerpoints = g.append("g").attr("id", "markerpoints_visible")
- markerpoints.selectAll("empty")
- .data(data.markers)
- .enter()
- .append("circle")
- .attr("cx", (d) -> xscale[d.chr](d.pos))
- .attr("cy", (d) -> yscale(d.lod))
- .attr("r", pointsize)
- .attr("fill", pointcolor)
- .attr("stroke", pointstroke)
- .attr("pointer-events", "hidden")
-
- # title
- titlegrp = g.append("g").attr("class", "title")
- .append("text")
- .attr("x", margin.left+width/2)
- .attr("y", margin.top-titlepos)
- .text(title)
-
- # another box around edge
- g.append("rect")
- .attr("x", margin.left)
- .attr("y", margin.top)
- .attr("height", height)
- .attr("width", () ->
- return(data.chrEnd[-1..][0]-margin.left) if pad4heatmap
- data.chrEnd[-1..][0]-margin.left+chrGap/2)
- .attr("fill", "none")
- .attr("stroke", "black")
- .attr("stroke-width", "none")
-
- if pointsAtMarkers
- # these hidden points are what gets selected...a bit larger
- hiddenpoints = g.append("g").attr("id", "markerpoints_hidden")
-
- markertip = d3.tip()
- .attr('class', 'd3-tip')
- .html((d) ->
- [d.name, " LRS = #{d3.format('.2f')(d.lod)}"])
- .direction("e")
- .offset([0,10])
- svg.call(markertip)
-
- markerSelect =
- hiddenpoints.selectAll("empty")
- .data(data.markers)
- .enter()
- .append("circle")
- .attr("cx", (d) -> xscale[d.chr](d.pos))
- .attr("cy", (d) -> yscale(d.lod))
- .attr("id", (d) -> d.name)
- .attr("r", d3.max([pointsize*2, 3]))
- .attr("opacity", 0)
- .attr("fill", pointcolor)
- .attr("stroke", pointstroke)
- .attr("stroke-width", "1")
- .on "mouseover.paneltip", (d) ->
- d3.select(this).attr("opacity", 1)
- markertip.show(d)
- .on "mouseout.paneltip", ->
- d3.select(this).attr("opacity", 0)
- .call(markertip.hide)
-
- ## configuration parameters
- chart.width = (value) ->
- return width unless arguments.length
- width = value
- chart
-
- chart.height = (value) ->
- return height unless arguments.length
- height = value
- chart
-
- chart.margin = (value) ->
- return margin unless arguments.length
- margin = value
- chart
-
- chart.titlepos = (value) ->
- return titlepos unless arguments.length
- titlepos
- chart
-
- chart.axispos = (value) ->
- return axispos unless arguments.length
- axispos = value
- chart
-
- chart.manhattanPlot = (value) ->
- return manhattanPlot unless arguments.length
- manhattanPlot = value
- chart
-
- chart.ylim = (value) ->
- return ylim unless arguments.length
- ylim = value
- chart
-
- #if data['additive'].length > 0
- chart.additive_ylim = (value) ->
- return additive_ylim unless arguments.length
- additive_ylim = value
- chart
-
- chart.nyticks = (value) ->
- return nyticks unless arguments.length
- nyticks = value
- chart
-
- chart.yticks = (value) ->
- return yticks unless arguments.length
- yticks = value
- chart
-
- chart.chrGap = (value) ->
- return chrGap unless arguments.length
- chrGap = value
- chart
-
- chart.darkrect = (value) ->
- return darkrect unless arguments.length
- darkrect = value
- chart
-
- chart.lightrect = (value) ->
- return lightrect unless arguments.length
- lightrect = value
- chart
-
- chart.linecolor = (value) ->
- return linecolor unless arguments.length
- linecolor = value
- chart
-
- chart.linewidth = (value) ->
- return linewidth unless arguments.length
- linewidth = value
- chart
-
- chart.pointcolor = (value) ->
- return pointcolor unless arguments.length
- pointcolor = value
- chart
-
- chart.pointsize = (value) ->
- return pointsize unless arguments.length
- pointsize = value
- chart
-
- chart.pointstroke = (value) ->
- return pointstroke unless arguments.length
- pointstroke = value
- chart
-
- chart.title = (value) ->
- return title unless arguments.length
- title = value
- chart
-
- chart.xlab = (value) ->
- return xlab unless arguments.length
- xlab = value
- chart
-
- chart.ylab = (value) ->
- return ylab unless arguments.length
- ylab = value
- chart
-
- chart.rotate_ylab = (value) ->
- return rotate_ylab if !arguments.length
- rotate_ylab = value
- chart
-
- chart.lodvarname = (value) ->
- return lodvarname unless arguments.length
- lodvarname = value
- chart
-
- chart.pad4heatmap = (value) ->
- return pad4heatmap unless arguments.length
- pad4heatmap = value
- chart
-
- chart.pointsAtMarkers = (value) ->
- return pointsAtMarkers unless arguments.length
- pointsAtMarkers = value
- chart
-
- chart.yscale = () ->
- return yscale
-
- chart.additive = () ->
- return additive
-
- #if data['additive'].length > 0
- chart.additive_yscale = () ->
- return additive_yscale
-
- chart.xscale = () ->
- return xscale
-
- if manhattanPlot == false
- chart.lodcurve = () ->
- return lodcurve
-
- #if data['additive'].length > 0
- chart.additivecurve = () ->
- return additivecurve
-
- chart.markerSelect = () ->
- return markerSelect
-
- chart.chrSelect = () ->
- return chrSelect
-
- # return the chart function
- chart
-
+lodchart = () ->
+ width = 800
+ height = 500
+ margin = {left:60, top:40, right:40, bottom: 40, inner:5}
+ axispos = {xtitle:25, ytitle:30, xlabel:5, ylabel:5}
+ titlepos = 20
+ manhattanPlot = false
+ additive = false
+ ylim = null
+ additive_ylim = null
+ nyticks = 5
+ yticks = null
+ additive_yticks = null
+ chrGap = 8
+ darkrect = "#F1F1F9"
+ lightrect = "#FBFBFF"
+ lodlinecolor = "darkslateblue"
+ additivelinecolor = "red"
+ linewidth = 2
+ suggestivecolor = "gainsboro"
+ significantcolor = "#EBC7C7"
+ pointcolor = "#E9CFEC" # pink
+ pointsize = 0 # default = no visible points at markers
+ pointstroke = "black"
+ title = ""
+ xlab = "Chromosome"
+ ylab = "LRS score"
+ additive_ylab = "Additive Effect"
+ rotate_ylab = null
+ yscale = d3.scale.linear()
+ additive_yscale = d3.scale.linear()
+ xscale = null
+ pad4heatmap = false
+ lodcurve = null
+ lodvarname = null
+ markerSelect = null
+ chrSelect = null
+ pointsAtMarkers = true
+
+
+ ## the main function
+ chart = (selection) ->
+ selection.each (data) ->
+
+ #console.log("data:", data)
+
+ if manhattanPlot == true
+ pointcolor = "darkslateblue"
+ pointsize = 2
+
+ lodvarname = lodvarname ? data.lodnames[0]
+ data[lodvarname] = (Math.abs(x) for x in data[lodvarname]) # take absolute values
+ ylim = ylim ? [0, d3.max(data[lodvarname])]
+ if additive
+ data['additive'] = (Math.abs(x) for x in data['additive'])
+ additive_ylim = additive_ylim ? [0, d3.max(data['additive'])]
+
+ lodvarnum = data.lodnames.indexOf(lodvarname)
+
+ # Select the svg element, if it exists.
+ svg = d3.select(this).selectAll("svg").data([data])
+
+ # Otherwise, create the skeletal chart.
+ gEnter = svg.enter().append("svg").append("g")
+
+ # Update the outer dimensions.
+ svg.attr("width", width+margin.left+margin.right)
+ .attr("height", height+margin.top+margin.bottom)
+
+ # Update the inner dimensions.
+ g = svg.select("g")
+
+ # box
+ g.append("rect")
+ .attr("x", margin.left)
+ .attr("y", margin.top)
+ .attr("height", height)
+ .attr("width", width)
+ .attr("fill", darkrect)
+ .attr("stroke", "none")
+
+ yscale.domain(ylim)
+ .range([height+margin.top, margin.top+margin.inner])
+
+ # if yticks not provided, use nyticks to choose pretty ones
+ yticks = yticks ? yscale.ticks(nyticks)
+
+ #if data['additive'].length > 0
+ if additive
+ additive_yscale.domain(additive_ylim)
+ .range([height+margin.top, margin.top+margin.inner + height/2])
+
+ additive_yticks = additive_yticks ? additive_yscale.ticks(nyticks)
+
+ # reorganize lod,pos by chromosomes
+ reorgLodData(data, lodvarname)
+
+ # add chromosome scales (for x-axis)
+ data = chrscales(data, width, chrGap, margin.left, pad4heatmap)
+ xscale = data.xscale
+
+ # chr rectangles
+ chrSelect =
+ g.append("g").attr("class", "chrRect")
+ .selectAll("empty")
+ .data(data.chrnames)
+ .enter()
+ .append("rect")
+ .attr("id", (d) -> "chrrect#{d[0]}")
+ .attr("x", (d,i) ->
+ return data.chrStart[i] if i==0 and pad4heatmap
+ data.chrStart[i]-chrGap/2)
+ .attr("width", (d,i) ->
+ return data.chrEnd[i] - data.chrStart[i]+chrGap/2 if (i==0 or i+1 == data.chrnames.length) and pad4heatmap
+ data.chrEnd[i] - data.chrStart[i]+chrGap)
+ .attr("y", margin.top)
+ .attr("height", height)
+ .attr("fill", (d,i) ->
+ return darkrect if i % 2
+
+ lightrect)
+ .attr("stroke", "none")
+ .on("click", (d) ->
+ console.log("d is:", d)
+ redraw_plot(d)
+ )
+
+ # x-axis labels
+ xaxis = g.append("g").attr("class", "x axis")
+ xaxis.selectAll("empty")
+ .data(data.chrnames)
+ .enter()
+ .append("text")
+ .text((d) -> d[0])
+ .attr("x", (d,i) -> (data.chrStart[i]+data.chrEnd[i])/2)
+ .attr("y", margin.top+height+axispos.xlabel)
+ .attr("dominant-baseline", "hanging")
+ .attr("text-anchor", "middle")
+ .attr("cursor", "pointer")
+ .on("click", (d) ->
+ redraw_plot(d)
+ )
+
+ xaxis.append("text").attr("class", "title")
+ .attr("y", margin.top+height+axispos.xtitle)
+ .attr("x", margin.left+width/2)
+ .attr("fill", "slateblue")
+ .text(xlab)
+
+
+ redraw_plot = (chr_ob) ->
+ #console.log("chr_name is:", chr_ob[0])
+ #console.log("chr_length is:", chr_ob[1])
+ $('#topchart').remove()
+ $('#chart_container').append('<div class="qtlcharts" id="topchart"></div>')
+ chr_plot = new Chr_Lod_Chart(600, 1200, chr_ob, manhattanPlot)
+
+ # y-axis
+ rotate_ylab = rotate_ylab ? (ylab.length > 1)
+ yaxis = g.append("g").attr("class", "y axis")
+ yaxis.selectAll("empty")
+ .data(yticks)
+ .enter()
+ .append("line")
+ .attr("y1", (d) -> yscale(d))
+ .attr("y2", (d) -> yscale(d))
+ .attr("x1", margin.left)
+ .attr("x2", margin.left+7)
+ .attr("fill", "none")
+ .attr("stroke", "white")
+ .attr("stroke-width", 1)
+ .style("pointer-events", "none")
+
+ yaxis.selectAll("empty")
+ .data(yticks)
+ .enter()
+ .append("text")
+ .attr("y", (d) -> yscale(d))
+ .attr("x", margin.left-axispos.ylabel)
+ .attr("fill", "blue")
+ .attr("dominant-baseline", "middle")
+ .attr("text-anchor", "end")
+ .text((d) -> formatAxis(yticks)(d))
+
+ yaxis.append("text").attr("class", "title")
+ .attr("y", margin.top+height/2)
+ .attr("x", margin.left-axispos.ytitle)
+ .text(ylab)
+ .attr("transform", if rotate_ylab then "rotate(270,#{margin.left-axispos.ytitle},#{margin.top+height/2})" else "")
+ .attr("text-anchor", "middle")
+ .attr("fill", "slateblue")
+
+ #if data['additive'].length > 0
+ if additive
+ rotate_additive_ylab = rotate_additive_ylab ? (additive_ylab.length > 1)
+ additive_yaxis = g.append("g").attr("class", "y axis")
+ additive_yaxis.selectAll("empty")
+ .data(additive_yticks)
+ .enter()
+ .append("line")
+ .attr("y1", (d) -> additive_yscale(d))
+ .attr("y2", (d) -> additive_yscale(d))
+ .attr("x1", margin.left + width)
+ .attr("x2", margin.left + width - 7)
+ .attr("fill", "none")
+ .attr("stroke", "white")
+ .attr("stroke-width", 1)
+ .style("pointer-events", "none")
+
+ additive_yaxis.selectAll("empty")
+ .data(additive_yticks)
+ .enter()
+ .append("text")
+ .attr("y", (d) -> additive_yscale(d))
+ .attr("x", (d) -> margin.left + width + axispos.ylabel + 20)
+ .attr("fill", "green")
+ .attr("dominant-baseline", "middle")
+ .attr("text-anchor", "end")
+ .text((d) -> formatAxis(additive_yticks)(d))
+
+ additive_yaxis.append("text").attr("class", "title")
+ .attr("y", margin.top+1.5*height)
+ .attr("x", margin.left + width + axispos.ytitle)
+ .text(additive_ylab)
+ .attr("transform", if rotate_additive_ylab then "rotate(270,#{margin.left + width + axispos.ytitle}, #{margin.top+height*1.5})" else "")
+ .attr("text-anchor", "middle")
+ .attr("fill", "green")
+
+ if 'suggestive' of data
+ suggestive_bar = g.append("g").attr("class", "suggestive")
+ suggestive_bar.selectAll("empty")
+ .data([data.suggestive])
+ .enter()
+ .append("line")
+ .attr("y1", (d) -> yscale(d))
+ .attr("y2", (d) -> yscale(d))
+ .attr("x1", margin.left)
+ .attr("x2", margin.left+width)
+ .attr("fill", "none")
+ .attr("stroke", suggestivecolor)
+ .attr("stroke-width", 5)
+ .style("pointer-events", "none")
+
+ suggestive_bar = g.append("g").attr("class", "significant")
+ suggestive_bar.selectAll("empty")
+ .data([data.significant])
+ .enter()
+ .append("line")
+ .attr("y1", (d) -> yscale(d))
+ .attr("y2", (d) -> yscale(d))
+ .attr("x1", margin.left)
+ .attr("x2", margin.left+width)
+ .attr("fill", "none")
+ .attr("stroke", significantcolor)
+ .attr("stroke-width", 5)
+ .style("pointer-events", "none")
+
+ if manhattanPlot == false
+ # lod curves by chr
+ lodcurve = (chr, lodcolumn) ->
+ d3.svg.line()
+ .x((d) -> xscale[chr](d))
+ .y((d,i) -> yscale(data.lodByChr[chr][i][lodcolumn]))
+
+ if additive
+ additivecurve = (chr, lodcolumn) ->
+ d3.svg.line()
+ .x((d) -> xscale[chr](d))
+ .y((d,i) -> additive_yscale(data.additiveByChr[chr][i][lodcolumn]))
+
+ curves = g.append("g").attr("id", "curves")
+
+ for chr in data.chrnames
+ if chr.indexOf(data['chr'])
+ curves.append("path")
+ .datum(data.posByChr[chr[0]])
+ .attr("d", lodcurve(chr[0], lodvarnum))
+ .attr("stroke", lodlinecolor)
+ .attr("fill", "none")
+ .attr("stroke-width", linewidth)
+ .style("pointer-events", "none")
+
+ if additive
+ for chr in data.chrnames
+ if chr.indexOf(data['chr'])
+ curves.append("path")
+ .datum(data.posByChr[chr[0]])
+ .attr("d", additivecurve(chr[0], lodvarnum))
+ .attr("stroke", additivelinecolor)
+ .attr("fill", "none")
+ .attr("stroke-width", 1)
+ .style("pointer-events", "none")
+
+ # points at markers
+ console.log("before pointsize")
+ if pointsize > 0
+ console.log("pointsize > 0 !!!")
+ markerpoints = g.append("g").attr("id", "markerpoints_visible")
+ markerpoints.selectAll("empty")
+ .data(data.markers)
+ .enter()
+ .append("circle")
+ .attr("cx", (d) -> xscale[d.chr](d.pos))
+ .attr("cy", (d) -> yscale(d.lod))
+ .attr("r", pointsize)
+ .attr("fill", pointcolor)
+ .attr("stroke", pointstroke)
+ .attr("pointer-events", "hidden")
+
+ # title
+ titlegrp = g.append("g").attr("class", "title")
+ .append("text")
+ .attr("x", margin.left+width/2)
+ .attr("y", margin.top-titlepos)
+ .text(title)
+
+ # another box around edge
+ g.append("rect")
+ .attr("x", margin.left)
+ .attr("y", margin.top)
+ .attr("height", height)
+ .attr("width", () ->
+ return(data.chrEnd[-1..][0]-margin.left) if pad4heatmap
+ data.chrEnd[-1..][0]-margin.left+chrGap/2)
+ .attr("fill", "none")
+ .attr("stroke", "black")
+ .attr("stroke-width", "none")
+
+ if pointsAtMarkers
+ # these hidden points are what gets selected...a bit larger
+ hiddenpoints = g.append("g").attr("id", "markerpoints_hidden")
+
+ markertip = d3.tip()
+ .attr('class', 'd3-tip')
+ .html((d) ->
+ [d.name, " LRS = #{d3.format('.2f')(d.lod)}"])
+ .direction("e")
+ .offset([0,10])
+ svg.call(markertip)
+
+ markerSelect =
+ hiddenpoints.selectAll("empty")
+ .data(data.markers)
+ .enter()
+ .append("circle")
+ .attr("cx", (d) -> xscale[d.chr](d.pos))
+ .attr("cy", (d) -> yscale(d.lod))
+ .attr("id", (d) -> d.name)
+ .attr("r", d3.max([pointsize*2, 3]))
+ .attr("opacity", 0)
+ .attr("fill", pointcolor)
+ .attr("stroke", pointstroke)
+ .attr("stroke-width", "1")
+ .on "mouseover.paneltip", (d) ->
+ d3.select(this).attr("opacity", 1)
+ markertip.show(d)
+ .on "mouseout.paneltip", ->
+ d3.select(this).attr("opacity", 0)
+ .call(markertip.hide)
+
+ ## configuration parameters
+ chart.width = (value) ->
+ return width unless arguments.length
+ width = value
+ chart
+
+ chart.height = (value) ->
+ return height unless arguments.length
+ height = value
+ chart
+
+ chart.margin = (value) ->
+ return margin unless arguments.length
+ margin = value
+ chart
+
+ chart.titlepos = (value) ->
+ return titlepos unless arguments.length
+ titlepos
+ chart
+
+ chart.axispos = (value) ->
+ return axispos unless arguments.length
+ axispos = value
+ chart
+
+ chart.manhattanPlot = (value) ->
+ return manhattanPlot unless arguments.length
+ manhattanPlot = value
+ chart
+
+ chart.ylim = (value) ->
+ return ylim unless arguments.length
+ ylim = value
+ chart
+
+ #if data['additive'].length > 0
+ chart.additive_ylim = (value) ->
+ return additive_ylim unless arguments.length
+ additive_ylim = value
+ chart
+
+ chart.nyticks = (value) ->
+ return nyticks unless arguments.length
+ nyticks = value
+ chart
+
+ chart.yticks = (value) ->
+ return yticks unless arguments.length
+ yticks = value
+ chart
+
+ chart.chrGap = (value) ->
+ return chrGap unless arguments.length
+ chrGap = value
+ chart
+
+ chart.darkrect = (value) ->
+ return darkrect unless arguments.length
+ darkrect = value
+ chart
+
+ chart.lightrect = (value) ->
+ return lightrect unless arguments.length
+ lightrect = value
+ chart
+
+ chart.linecolor = (value) ->
+ return linecolor unless arguments.length
+ linecolor = value
+ chart
+
+ chart.linewidth = (value) ->
+ return linewidth unless arguments.length
+ linewidth = value
+ chart
+
+ chart.pointcolor = (value) ->
+ return pointcolor unless arguments.length
+ pointcolor = value
+ chart
+
+ chart.pointsize = (value) ->
+ return pointsize unless arguments.length
+ pointsize = value
+ chart
+
+ chart.pointstroke = (value) ->
+ return pointstroke unless arguments.length
+ pointstroke = value
+ chart
+
+ chart.title = (value) ->
+ return title unless arguments.length
+ title = value
+ chart
+
+ chart.xlab = (value) ->
+ return xlab unless arguments.length
+ xlab = value
+ chart
+
+ chart.ylab = (value) ->
+ return ylab unless arguments.length
+ ylab = value
+ chart
+
+ chart.rotate_ylab = (value) ->
+ return rotate_ylab if !arguments.length
+ rotate_ylab = value
+ chart
+
+ chart.lodvarname = (value) ->
+ return lodvarname unless arguments.length
+ lodvarname = value
+ chart
+
+ chart.pad4heatmap = (value) ->
+ return pad4heatmap unless arguments.length
+ pad4heatmap = value
+ chart
+
+ chart.pointsAtMarkers = (value) ->
+ return pointsAtMarkers unless arguments.length
+ pointsAtMarkers = value
+ chart
+
+ chart.yscale = () ->
+ return yscale
+
+ chart.additive = () ->
+ return additive
+
+ #if data['additive'].length > 0
+ chart.additive_yscale = () ->
+ return additive_yscale
+
+ chart.xscale = () ->
+ return xscale
+
+ if manhattanPlot == false
+ chart.lodcurve = () ->
+ return lodcurve
+
+ #if data['additive'].length > 0
+ chart.additivecurve = () ->
+ return additivecurve
+
+ chart.markerSelect = () ->
+ return markerSelect
+
+ chart.chrSelect = () ->
+ return chrSelect
+
+ # return the chart function
+ chart
+
diff --git a/wqflask/wqflask/static/new/javascript/lod_chart.js b/wqflask/wqflask/static/new/javascript/lod_chart.js
index 92289bfe..d0d39fe6 100644
--- a/wqflask/wqflask/static/new/javascript/lod_chart.js
+++ b/wqflask/wqflask/static/new/javascript/lod_chart.js
@@ -1,4 +1,4 @@
-// Generated by CoffeeScript 1.8.0
+// Generated by CoffeeScript 1.9.2
var lodchart;
lodchart = function() {
@@ -20,7 +20,6 @@ lodchart = function() {
};
titlepos = 20;
manhattanPlot = false;
- additive = false;
ylim = null;
additive_ylim = null;
nyticks = 5;
@@ -30,7 +29,8 @@ lodchart = function() {
darkrect = "#F1F1F9";
lightrect = "#FBFBFF";
lodlinecolor = "darkslateblue";
- additivelinecolor = "red";
+ additivelinecolor_plus = "red";
+ additivelinecolor_negative = "green";
linewidth = 2;
suggestivecolor = "gainsboro";
significantcolor = "#EBC7C7";
@@ -53,33 +53,34 @@ lodchart = function() {
pointsAtMarkers = true;
chart = function(selection) {
return selection.each(function(data) {
- var additive_yaxis, additivecurve, chr, curves, g, gEnter, hiddenpoints, lodvarnum, markerpoints, markertip, redraw_plot, rotate_additive_ylab, suggestive_bar, svg, titlegrp, x, xaxis, yaxis, _i, _j, _len, _len1, _ref, _ref1;
+ var additive_yaxis, additivecurve, chr, curves, g, gEnter, hiddenpoints, j, k, len, len1, lodvarnum, markerpoints, markertip, redraw_plot, ref, ref1, rotate_additive_ylab, suggestive_bar, svg, titlegrp, x, xaxis, yaxis;
if (manhattanPlot === true) {
pointcolor = "darkslateblue";
pointsize = 2;
}
lodvarname = lodvarname != null ? lodvarname : data.lodnames[0];
data[lodvarname] = (function() {
- var _i, _len, _ref, _results;
- _ref = data[lodvarname];
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- x = _ref[_i];
- _results.push(Math.abs(x));
+ var j, len, ref, results;
+ ref = data[lodvarname];
+ results = [];
+ for (j = 0, len = ref.length; j < len; j++) {
+ x = ref[j];
+ results.push(Math.abs(x));
}
- return _results;
+ return results;
})();
ylim = ylim != null ? ylim : [0, d3.max(data[lodvarname])];
- if (additive) {
+
+ if ('additive' in data) {
data['additive'] = (function() {
- var _i, _len, _ref, _results;
- _ref = data['additive'];
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- x = _ref[_i];
- _results.push(Math.abs(x));
+ var j, len, ref, results;
+ ref = data['additive'];
+ results = [];
+ for (j = 0, len = ref.length; j < len; j++) {
+ x = ref[j];
+ results.push(x);
}
- return _results;
+ return results;
})();
additive_ylim = additive_ylim != null ? additive_ylim : [0, d3.max(data['additive'])];
}
@@ -91,7 +92,7 @@ lodchart = function() {
g.append("rect").attr("x", margin.left).attr("y", margin.top).attr("height", height).attr("width", width).attr("fill", darkrect).attr("stroke", "none");
yscale.domain(ylim).range([height + margin.top, margin.top + margin.inner]);
yticks = yticks != null ? yticks : yscale.ticks(nyticks);
- if (additive) {
+ if ('additive' in data) {
additive_yscale.domain(additive_ylim).range([height + margin.top, margin.top + margin.inner + height / 2]);
additive_yticks = additive_yticks != null ? additive_yticks : additive_yscale.ticks(nyticks);
}
@@ -147,7 +148,7 @@ lodchart = function() {
return formatAxis(yticks)(d);
});
yaxis.append("text").attr("class", "title").attr("y", margin.top + height / 2).attr("x", margin.left - axispos.ytitle).text(ylab).attr("transform", rotate_ylab ? "rotate(270," + (margin.left - axispos.ytitle) + "," + (margin.top + height / 2) + ")" : "").attr("text-anchor", "middle").attr("fill", "slateblue");
- if (additive) {
+ if ('additive' in data) {
rotate_additive_ylab = rotate_additive_ylab != null ? rotate_additive_ylab : additive_ylab.length > 1;
additive_yaxis = g.append("g").attr("class", "y axis");
additive_yaxis.selectAll("empty").data(additive_yticks).enter().append("line").attr("y1", function(d) {
@@ -186,26 +187,41 @@ lodchart = function() {
return yscale(data.lodByChr[chr][i][lodcolumn]);
});
};
- if (additive) {
+ if ('additive' in data) {
additivecurve = function(chr, lodcolumn) {
- return d3.svg.line().x(function(d) {
+ if (data.additiveByChr[chr][0] < 0) {
+ pos_neg = "negative"
+ }
+ else {
+ pos_neg = "positive"
+ }
+ return [pos_neg, d3.svg.line().x(function(d) {
return xscale[chr](d);
}).y(function(d, i) {
- return additive_yscale(data.additiveByChr[chr][i][lodcolumn]);
- });
+ return additive_yscale(Math.abs(data.additiveByChr[chr][i]));
+ })];
};
}
curves = g.append("g").attr("id", "curves");
- _ref = data.chrnames;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- chr = _ref[_i];
- curves.append("path").datum(data.posByChr[chr[0]]).attr("d", lodcurve(chr[0], lodvarnum)).attr("stroke", lodlinecolor).attr("fill", "none").attr("stroke-width", linewidth).style("pointer-events", "none");
+ ref = data.chrnames;
+ for (j = 0, len = ref.length; j < len; j++) {
+ chr = ref[j];
+ if (chr.indexOf(data['chr'])) {
+ curves.append("path").datum(data.posByChr[chr[0]]).attr("d", lodcurve(chr[0], lodvarnum)).attr("stroke", lodlinecolor).attr("fill", "none").attr("stroke-width", linewidth).style("pointer-events", "none");
+ }
}
- if (additive) {
- _ref1 = data.chrnames;
- for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
- chr = _ref1[_j];
- curves.append("path").datum(data.posByChr[chr[0]]).attr("d", additivecurve(chr[0], lodvarnum)).attr("stroke", additivelinecolor).attr("fill", "none").attr("stroke-width", 1).style("pointer-events", "none");
+ if ('additive' in data) {
+ ref1 = data.chrnames;
+ for (k = 0, len1 = ref1.length; k < len1; k++) {
+ chr = ref1[k];
+ if (chr.indexOf(data['chr'])) {
+ if (additivecurve(chr[0], lodvarnum)[0] == "negative") {
+ curves.append("path").datum(data.posByChr[chr[0]]).attr("d", additivecurve(chr[0], lodvarnum)[1]).attr("stroke", additivelinecolor_negative).attr("fill", "none").attr("stroke-width", 1).style("pointer-events", "none");
+ }
+ else {
+ curves.append("path").datum(data.posByChr[chr[0]]).attr("d", additivecurve(chr[0], lodvarnum)[1]).attr("stroke", additivelinecolor_plus).attr("fill", "none").attr("stroke-width", 1).style("pointer-events", "none");
+ }
+ }
}
}
}
@@ -426,9 +442,6 @@ lodchart = function() {
chart.yscale = function() {
return yscale;
};
- chart.additive = function() {
- return additive;
- };
chart.additive_yscale = function() {
return additive_yscale;
};
@@ -450,4 +463,4 @@ lodchart = function() {
return chrSelect;
};
return chart;
-};
+}; \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/javascript/panelutil.coffee b/wqflask/wqflask/static/new/javascript/panelutil.coffee
index a3bc0b44..f7b51457 100644
--- a/wqflask/wqflask/static/new/javascript/panelutil.coffee
+++ b/wqflask/wqflask/static/new/javascript/panelutil.coffee
@@ -30,16 +30,15 @@ reorgLodData = (data, lodvarname=null) ->
data.lodByChr = {}
for chr,i in data.chrnames
- #console.log("chr:", chr)
- data.posByChr[chr[0]] = []
- data.lodByChr[chr[0]] = []
- for pos, j in data.pos
- if data.chr[j].toString() == chr[0]
- #console.log(data.chr[j] + " AND " + chr[0])
- data.posByChr[chr[0]].push(pos)
- data.lodnames = [data.lodnames] unless Array.isArray(data.lodnames)
- lodval = (data[lodcolumn][j] for lodcolumn in data.lodnames)
- data.lodByChr[chr[0]].push(lodval)
+ if data.chr.indexOf(chr[0])
+ data.posByChr[chr[0]] = []
+ data.lodByChr[chr[0]] = []
+ for pos, j in data.pos
+ if data.chr[j].toString() == chr[0]
+ data.posByChr[chr[0]].push(pos)
+ data.lodnames = [data.lodnames] unless Array.isArray(data.lodnames)
+ lodval = (data[lodcolumn][j] for lodcolumn in data.lodnames)
+ data.lodByChr[chr[0]].push(lodval)
#console.log("data.posByChr:", data.posByChr)
diff --git a/wqflask/wqflask/static/new/javascript/panelutil.js b/wqflask/wqflask/static/new/javascript/panelutil.js
index 3a180e60..113512b4 100644
--- a/wqflask/wqflask/static/new/javascript/panelutil.js
+++ b/wqflask/wqflask/static/new/javascript/panelutil.js
@@ -47,12 +47,19 @@ reorgLodData = function(data, lodvarname) {
}
data.posByChr = {};
data.lodByChr = {};
+ if ('additive' in data){
+ data.additiveByChr = {};
+ }
_ref = data.chrnames;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
chr = _ref[i];
data.posByChr[chr[0]] = [];
data.lodByChr[chr[0]] = [];
+ if ('additive' in data){
+ data.additiveByChr[chr[0]] = [];
+ }
_ref1 = data.pos;
+
for (j = _j = 0, _len1 = _ref1.length; _j < _len1; j = ++_j) {
pos = _ref1[j];
if (data.chr[j].toString() === chr[0]) {
@@ -71,6 +78,12 @@ reorgLodData = function(data, lodvarname) {
return _results;
})();
data.lodByChr[chr[0]].push(lodval);
+
+ if ('additive' in data){
+ addval = data['additive'][j]
+ data.additiveByChr[chr[0]].push(addval);
+ }
+
}
}
}
@@ -106,10 +119,13 @@ chrscales = function(data, width, chrGap, leftMargin, pad4heatmap) {
if (d > maxd) {
maxd = d;
}
- rng = d3.extent(data.posByChr[chr[0]]);
- chrStart.push(rng[0]);
- chrEnd.push(rng[1]);
- L = rng[1] - rng[0];
+ //rng = d3.extent(data.posByChr[chr[0]]);
+ //chrStart.push(rng[0]);
+ //chrEnd.push(rng[1]);
+ //L = rng[1] - rng[0];
+ chrStart.push(0);
+ chrEnd.push(chr[1]);
+ L = chr[1]
chrLength.push(L);
totalChrLength += L;
}
@@ -436,4 +452,4 @@ abs = function(x) {
return x;
}
return Math.abs(x);
-};
+}; \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/javascript/probability_plot.coffee b/wqflask/wqflask/static/new/javascript/probability_plot.coffee
deleted file mode 100644
index c1f26941..00000000
--- a/wqflask/wqflask/static/new/javascript/probability_plot.coffee
+++ /dev/null
@@ -1,424 +0,0 @@
-probability_plot = () ->
- width = 800
- height = 600
- margin = {left:60, top:40, right:40, bottom: 40, inner:5}
- axispos = {xtitle:25, ytitle:45, xlabel:5, ylabel:5}
- titlepos = 20
- xNA = {handle:true, force:false, width:15, gap:10}
- yNA = {handle:true, force:false, width:15, gap:10}
- xlim = null
- ylim = null
- nxticks = 5
- xticks = null
- nyticks = 5
- yticks = null
- rectcolor = d3.rgb(230, 230, 230)
- pointcolor = null
- pointstroke = "black"
- pointsize = 3 # default = no visible points at markers
- title = "Correlation Scatterplot"
- xlab = "X"
- ylab = "Y"
- rotate_ylab = null
- yscale = d3.scale.linear()
- xscale = d3.scale.linear()
- xvar = 0
- yvar = 1
- pointsSelect = null
- dataByInd = false
-
- ## the main function
- chart = (selection) ->
- selection.each (data) ->
-
- if dataByInd
- x = data.data.map (d) -> d[xvar]
- y = data.data.map (d) -> d[yvar]
- else # reorganize data
- x = data.data[xvar]
- y = data.data[yvar]
-
- console.log("x:", x)
- console.log("y:", y)
-
- # grab indID if it's there
- # if no indID, create a vector of them
- indID = data?.indID ? null
- indID = indID ? [1..x.length]
-
- console.log("indID:", indID)
-
- # groups of colors
- group = data?.group ? (1 for i in x)
- ngroup = d3.max(group)
- group = (g-1 for g in group) # changed from (1,2,3,...) to (0,1,2,...)
-
- # colors of the points in the different groups
- pointcolor = pointcolor ? selectGroupColors(ngroup, "dark")
- pointcolor = expand2vector(pointcolor, ngroup)
-
- # if all (x,y) not null
- xNA.handle = false if x.every (v) -> (v?) and !xNA.force
- yNA.handle = false if y.every (v) -> (v?) and !yNA.force
- if xNA.handle
- paneloffset = xNA.width + xNA.gap
- panelwidth = width - paneloffset
- else
- paneloffset = 0
- panelwidth = width
- if yNA.handle
- panelheight = height - (yNA.width + yNA.gap)
- else
- panelheight = height
-
- xlim = xlim ? d3.extent(x)
- ylim = ylim ? d3.extent(y)
-
- # I'll replace missing values something smaller than what's observed
- na_value = d3.min(x.concat y) - 100
-
- # Select the svg element, if it exists.
- svg = d3.select(this).selectAll("svg").data([data])
-
- # Otherwise, create the skeletal chart.
- gEnter = svg.enter().append("svg").append("g")
-
- # Update the outer dimensions.
- svg.attr("width", width+margin.left+margin.right)
- .attr("height", height+margin.top+margin.bottom)
-
- g = svg.select("g")
-
- # box
- g.append("rect")
- .attr("x", paneloffset+margin.left)
- .attr("y", margin.top)
- .attr("height", panelheight)
- .attr("width", panelwidth)
- .attr("fill", rectcolor)
- .attr("stroke", "none")
- if xNA.handle
- g.append("rect")
- .attr("x", margin.left)
- .attr("y", margin.top)
- .attr("height", panelheight)
- .attr("width", xNA.width)
- .attr("fill", rectcolor)
- .attr("stroke", "none")
- if xNA.handle and yNA.handle
- g.append("rect")
- .attr("x", margin.left)
- .attr("y", margin.top+height - yNA.width)
- .attr("height", yNA.width)
- .attr("width", xNA.width)
- .attr("fill", rectcolor)
- .attr("stroke", "none")
- if yNA.handle
- g.append("rect")
- .attr("x", margin.left+paneloffset)
- .attr("y", margin.top+height-yNA.width)
- .attr("height", yNA.width)
- .attr("width", panelwidth)
- .attr("fill", rectcolor)
- .attr("stroke", "none")
-
- # simple scales (ignore NA business)
- xrange = [margin.left+paneloffset+margin.inner, margin.left+paneloffset+panelwidth-margin.inner]
- yrange = [margin.top+panelheight-margin.inner, margin.top+margin.inner]
- xscale.domain(xlim).range(xrange)
- yscale.domain(ylim).range(yrange)
- xs = d3.scale.linear().domain(xlim).range(xrange)
- ys = d3.scale.linear().domain(ylim).range(yrange)
-
- # "polylinear" scales to handle missing values
- if xNA.handle
- xscale.domain([na_value].concat xlim)
- .range([margin.left + xNA.width/2].concat xrange)
- x = x.map (e) -> if e? then e else na_value
- if yNA.handle
- yscale.domain([na_value].concat ylim)
- .range([height+margin.top-yNA.width/2].concat yrange)
- y = y.map (e) -> if e? then e else na_value
-
- # if yticks not provided, use nyticks to choose pretty ones
- yticks = yticks ? ys.ticks(nyticks)
- xticks = xticks ? xs.ticks(nxticks)
-
- # title
- titlegrp = g.append("g").attr("class", "title")
- .append("text")
- .attr("x", margin.left + width/2)
- .attr("y", margin.top - titlepos)
- .text(title)
-
- # x-axis
- xaxis = g.append("g").attr("class", "x axis")
- xaxis.selectAll("empty")
- .data(xticks)
- .enter()
- .append("line")
- .attr("x1", (d) -> xscale(d))
- .attr("x2", (d) -> xscale(d))
- .attr("y1", margin.top)
- .attr("y2", margin.top+height)
- .attr("fill", "none")
- .attr("stroke", "white")
- .attr("stroke-width", 1)
- .style("pointer-events", "none")
- xaxis.selectAll("empty")
- .data(xticks)
- .enter()
- .append("text")
- .attr("x", (d) -> xscale(d))
- .attr("y", margin.top+height+axispos.xlabel)
- .text((d) -> formatAxis(xticks)(d))
- xaxis.append("text").attr("class", "title")
- .attr("x", margin.left+width/2)
- .attr("y", margin.top+height+axispos.xtitle)
- .text(xlab)
- if xNA.handle
- xaxis.append("text")
- .attr("x", margin.left+xNA.width/2)
- .attr("y", margin.top+height+axispos.xlabel)
- .text("N/A")
-
- # y-axis
- rotate_ylab = rotate_ylab ? (ylab.length > 1)
- yaxis = g.append("g").attr("class", "y axis")
- yaxis.selectAll("empty")
- .data(yticks)
- .enter()
- .append("line")
- .attr("y1", (d) -> yscale(d))
- .attr("y2", (d) -> yscale(d))
- .attr("x1", margin.left)
- .attr("x2", margin.left+width)
- .attr("fill", "none")
- .attr("stroke", "white")
- .attr("stroke-width", 1)
- .style("pointer-events", "none")
- yaxis.selectAll("empty")
- .data(yticks)
- .enter()
- .append("text")
- .attr("y", (d) -> yscale(d))
- .attr("x", margin.left-axispos.ylabel)
- .text((d) -> formatAxis(yticks)(d))
- yaxis.append("text").attr("class", "title")
- .attr("y", margin.top+height/2)
- .attr("x", margin.left-axispos.ytitle)
- .text(ylab)
- .attr("transform", if rotate_ylab then "rotate(270,#{margin.left-axispos.ytitle},#{margin.top+height/2})" else "")
- if yNA.handle
- yaxis.append("text")
- .attr("x", margin.left-axispos.ylabel)
- .attr("y", margin.top+height-yNA.width/2)
- .text("N/A")
-
- indtip = d3.tip()
- .attr('class', 'd3-tip')
- .html((d,i) -> indID[i])
- .direction('e')
- .offset([0,10])
- svg.call(indtip)
-
- #g.append("line")
- # .attr("x1")
- #
- #g.append("line")
- # .attr("x1", xscale(minx))
- # .attr("x2", xscale(maxx*0.995))
- # .attr("y2", yscale(slope*maxx*0.995+intercept))
- # .style("stroke", "black")
- # .style("stroke-width", 2);
-
- points = g.append("g").attr("id", "points")
- pointsSelect =
- points.selectAll("empty")
- .data(d3.range(x.length))
- .enter()
- .append("circle")
- .attr("cx", (d,i) -> xscale(x[i]))
- .attr("cy", (d,i) -> yscale(y[i]))
- .attr("class", (d,i) -> "pt#{i}")
- .attr("r", pointsize)
- .attr("fill", (d,i) -> pointcolor[group[i]])
- .attr("stroke", pointstroke)
- .attr("stroke-width", "1")
- .attr("opacity", (d,i) ->
- return 1 if (x[i]? or xNA.handle) and (y[i]? or yNA.handle)
- return 0)
- .on("mouseover.paneltip", indtip.show)
- .on("mouseout.paneltip", indtip.hide)
-
- # box
- g.append("rect")
- .attr("x", margin.left+paneloffset)
- .attr("y", margin.top)
- .attr("height", panelheight)
- .attr("width", panelwidth)
- .attr("fill", "none")
- .attr("stroke", "black")
- .attr("stroke-width", "none")
- if xNA.handle
- g.append("rect")
- .attr("x", margin.left)
- .attr("y", margin.top)
- .attr("height", panelheight)
- .attr("width", xNA.width)
- .attr("fill", "none")
- .attr("stroke", "black")
- .attr("stroke-width", "none")
- if xNA.handle and yNA.handle
- g.append("rect")
- .attr("x", margin.left)
- .attr("y", margin.top+height - yNA.width)
- .attr("height", yNA.width)
- .attr("width", xNA.width)
- .attr("fill", "none")
- .attr("stroke", "black")
- .attr("stroke-width", "none")
- if yNA.handle
- g.append("rect")
- .attr("x", margin.left+paneloffset)
- .attr("y", margin.top+height-yNA.width)
- .attr("height", yNA.width)
- .attr("width", panelwidth)
- .attr("fill", "none")
- .attr("stroke", "black")
- .attr("stroke-width", "none")
-
- ## configuration parameters
- chart.width = (value) ->
- return width if !arguments.length
- width = value
- chart
-
- chart.height = (value) ->
- return height if !arguments.length
- height = value
- chart
-
- chart.margin = (value) ->
- return margin if !arguments.length
- margin = value
- chart
-
- chart.axispos = (value) ->
- return axispos if !arguments.length
- axispos = value
- chart
-
- chart.titlepos = (value) ->
- return titlepos if !arguments.length
- titlepos
- chart
-
- chart.xlim = (value) ->
- return xlim if !arguments.length
- xlim = value
- chart
-
- chart.nxticks = (value) ->
- return nxticks if !arguments.length
- nxticks = value
- chart
-
- chart.xticks = (value) ->
- return xticks if !arguments.length
- xticks = value
- chart
-
- chart.ylim = (value) ->
- return ylim if !arguments.length
- ylim = value
- chart
-
- chart.nyticks = (value) ->
- return nyticks if !arguments.length
- nyticks = value
- chart
-
- chart.yticks = (value) ->
- return yticks if !arguments.length
- yticks = value
- chart
-
- chart.rectcolor = (value) ->
- return rectcolor if !arguments.length
- rectcolor = value
- chart
-
- chart.pointcolor = (value) ->
- return pointcolor if !arguments.length
- pointcolor = value
- chart
-
- chart.pointsize = (value) ->
- return pointsize if !arguments.length
- pointsize = value
- chart
-
- chart.pointstroke = (value) ->
- return pointstroke if !arguments.length
- pointstroke = value
- chart
-
- chart.dataByInd = (value) ->
- return dataByInd if !arguments.length
- dataByInd = value
- chart
-
- chart.title = (value) ->
- return title if !arguments.length
- title = value
- chart
-
- chart.xlab = (value) ->
- return xlab if !arguments.length
- xlab = value
- chart
-
- chart.ylab = (value) ->
- return ylab if !arguments.length
- ylab = value
- chart
-
- chart.rotate_ylab = (value) ->
- return rotate_ylab if !arguments.length
- rotate_ylab = value
- chart
-
- chart.xvar = (value) ->
- return xvar if !arguments.length
- xvar = value
- chart
-
- chart.yvar = (value) ->
- return yvar if !arguments.length
- yvar = value
- chart
-
- chart.xNA = (value) ->
- return xNA if !arguments.length
- xNA = value
- chart
-
- chart.yNA = (value) ->
- return yNA if !arguments.length
- yNA = value
- chart
-
- chart.yscale = () ->
- return yscale
-
- chart.xscale = () ->
- return xscale
-
- chart.pointsSelect = () ->
- return pointsSelect
-
- # return the chart function
- chart
-
-probability_plot() \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/javascript/probability_plot.js b/wqflask/wqflask/static/new/javascript/probability_plot.js
deleted file mode 100644
index af0f787b..00000000
--- a/wqflask/wqflask/static/new/javascript/probability_plot.js
+++ /dev/null
@@ -1,408 +0,0 @@
-// Generated by CoffeeScript 1.8.0
-var probability_plot;
-
-probability_plot = function() {
- var axispos, chart, dataByInd, height, margin, nxticks, nyticks, pointcolor, pointsSelect, pointsize, pointstroke, rectcolor, rotate_ylab, title, titlepos, width, xNA, xlab, xlim, xscale, xticks, xvar, yNA, ylab, ylim, yscale, yticks, yvar;
- width = 800;
- height = 600;
- margin = {
- left: 60,
- top: 40,
- right: 40,
- bottom: 40,
- inner: 5
- };
- axispos = {
- xtitle: 25,
- ytitle: 45,
- xlabel: 5,
- ylabel: 5
- };
- titlepos = 20;
- xNA = {
- handle: true,
- force: false,
- width: 15,
- gap: 10
- };
- yNA = {
- handle: true,
- force: false,
- width: 15,
- gap: 10
- };
- xlim = null;
- ylim = null;
- nxticks = 5;
- xticks = null;
- nyticks = 5;
- yticks = null;
- rectcolor = d3.rgb(230, 230, 230);
- pointcolor = null;
- pointstroke = "black";
- pointsize = 3;
- title = "Correlation Scatterplot";
- xlab = "X";
- ylab = "Y";
- rotate_ylab = null;
- yscale = d3.scale.linear();
- xscale = d3.scale.linear();
- xvar = 0;
- yvar = 1;
- pointsSelect = null;
- dataByInd = false;
- chart = function(selection) {
- return selection.each(function(data) {
- var g, gEnter, group, i, indID, indtip, na_value, ngroup, panelheight, paneloffset, panelwidth, points, svg, titlegrp, x, xaxis, xrange, xs, y, yaxis, yrange, ys, _i, _ref, _ref1, _ref2, _results;
- if (dataByInd) {
- x = data.data.map(function(d) {
- return d[xvar];
- });
- y = data.data.map(function(d) {
- return d[yvar];
- });
- } else {
- x = data.data[xvar];
- y = data.data[yvar];
- }
- console.log("x:", x);
- console.log("y:", y);
- indID = (_ref = data != null ? data.indID : void 0) != null ? _ref : null;
- indID = indID != null ? indID : (function() {
- _results = [];
- for (var _i = 1, _ref1 = x.length; 1 <= _ref1 ? _i <= _ref1 : _i >= _ref1; 1 <= _ref1 ? _i++ : _i--){ _results.push(_i); }
- return _results;
- }).apply(this);
- console.log("indID:", indID);
- group = (_ref2 = data != null ? data.group : void 0) != null ? _ref2 : (function() {
- var _j, _len, _results1;
- _results1 = [];
- for (_j = 0, _len = x.length; _j < _len; _j++) {
- i = x[_j];
- _results1.push(1);
- }
- return _results1;
- })();
- ngroup = d3.max(group);
- group = (function() {
- var _j, _len, _results1;
- _results1 = [];
- for (_j = 0, _len = group.length; _j < _len; _j++) {
- g = group[_j];
- _results1.push(g - 1);
- }
- return _results1;
- })();
- pointcolor = pointcolor != null ? pointcolor : selectGroupColors(ngroup, "dark");
- pointcolor = expand2vector(pointcolor, ngroup);
- if (x.every(function(v) {
- return (v != null) && !xNA.force;
- })) {
- xNA.handle = false;
- }
- if (y.every(function(v) {
- return (v != null) && !yNA.force;
- })) {
- yNA.handle = false;
- }
- if (xNA.handle) {
- paneloffset = xNA.width + xNA.gap;
- panelwidth = width - paneloffset;
- } else {
- paneloffset = 0;
- panelwidth = width;
- }
- if (yNA.handle) {
- panelheight = height - (yNA.width + yNA.gap);
- } else {
- panelheight = height;
- }
- xlim = xlim != null ? xlim : d3.extent(x);
- ylim = ylim != null ? ylim : d3.extent(y);
- na_value = d3.min(x.concat(y)) - 100;
- svg = d3.select(this).selectAll("svg").data([data]);
- gEnter = svg.enter().append("svg").append("g");
- svg.attr("width", width + margin.left + margin.right).attr("height", height + margin.top + margin.bottom);
- g = svg.select("g");
- g.append("rect").attr("x", paneloffset + margin.left).attr("y", margin.top).attr("height", panelheight).attr("width", panelwidth).attr("fill", rectcolor).attr("stroke", "none");
- if (xNA.handle) {
- g.append("rect").attr("x", margin.left).attr("y", margin.top).attr("height", panelheight).attr("width", xNA.width).attr("fill", rectcolor).attr("stroke", "none");
- }
- if (xNA.handle && yNA.handle) {
- g.append("rect").attr("x", margin.left).attr("y", margin.top + height - yNA.width).attr("height", yNA.width).attr("width", xNA.width).attr("fill", rectcolor).attr("stroke", "none");
- }
- if (yNA.handle) {
- g.append("rect").attr("x", margin.left + paneloffset).attr("y", margin.top + height - yNA.width).attr("height", yNA.width).attr("width", panelwidth).attr("fill", rectcolor).attr("stroke", "none");
- }
- xrange = [margin.left + paneloffset + margin.inner, margin.left + paneloffset + panelwidth - margin.inner];
- yrange = [margin.top + panelheight - margin.inner, margin.top + margin.inner];
- xscale.domain(xlim).range(xrange);
- yscale.domain(ylim).range(yrange);
- xs = d3.scale.linear().domain(xlim).range(xrange);
- ys = d3.scale.linear().domain(ylim).range(yrange);
- if (xNA.handle) {
- xscale.domain([na_value].concat(xlim)).range([margin.left + xNA.width / 2].concat(xrange));
- x = x.map(function(e) {
- if (e != null) {
- return e;
- } else {
- return na_value;
- }
- });
- }
- if (yNA.handle) {
- yscale.domain([na_value].concat(ylim)).range([height + margin.top - yNA.width / 2].concat(yrange));
- y = y.map(function(e) {
- if (e != null) {
- return e;
- } else {
- return na_value;
- }
- });
- }
- yticks = yticks != null ? yticks : ys.ticks(nyticks);
- xticks = xticks != null ? xticks : xs.ticks(nxticks);
- titlegrp = g.append("g").attr("class", "title").append("text").attr("x", margin.left + width / 2).attr("y", margin.top - titlepos).text(title);
- xaxis = g.append("g").attr("class", "x axis");
- xaxis.selectAll("empty").data(xticks).enter().append("line").attr("x1", function(d) {
- return xscale(d);
- }).attr("x2", function(d) {
- return xscale(d);
- }).attr("y1", margin.top).attr("y2", margin.top + height).attr("fill", "none").attr("stroke", "white").attr("stroke-width", 1).style("pointer-events", "none");
- xaxis.selectAll("empty").data(xticks).enter().append("text").attr("x", function(d) {
- return xscale(d);
- }).attr("y", margin.top + height + axispos.xlabel).text(function(d) {
- return formatAxis(xticks)(d);
- });
- xaxis.append("text").attr("class", "title").attr("x", margin.left + width / 2).attr("y", margin.top + height + axispos.xtitle).text(xlab);
- if (xNA.handle) {
- xaxis.append("text").attr("x", margin.left + xNA.width / 2).attr("y", margin.top + height + axispos.xlabel).text("N/A");
- }
- rotate_ylab = rotate_ylab != null ? rotate_ylab : ylab.length > 1;
- yaxis = g.append("g").attr("class", "y axis");
- yaxis.selectAll("empty").data(yticks).enter().append("line").attr("y1", function(d) {
- return yscale(d);
- }).attr("y2", function(d) {
- return yscale(d);
- }).attr("x1", margin.left).attr("x2", margin.left + width).attr("fill", "none").attr("stroke", "white").attr("stroke-width", 1).style("pointer-events", "none");
- yaxis.selectAll("empty").data(yticks).enter().append("text").attr("y", function(d) {
- return yscale(d);
- }).attr("x", margin.left - axispos.ylabel).text(function(d) {
- return formatAxis(yticks)(d);
- });
- yaxis.append("text").attr("class", "title").attr("y", margin.top + height / 2).attr("x", margin.left - axispos.ytitle).text(ylab).attr("transform", rotate_ylab ? "rotate(270," + (margin.left - axispos.ytitle) + "," + (margin.top + height / 2) + ")" : "");
- if (yNA.handle) {
- yaxis.append("text").attr("x", margin.left - axispos.ylabel).attr("y", margin.top + height - yNA.width / 2).text("N/A");
- }
- indtip = d3.tip().attr('class', 'd3-tip').html(function(d, i) {
- return indID[i];
- }).direction('e').offset([0, 10]);
- svg.call(indtip);
- points = g.append("g").attr("id", "points");
- pointsSelect = points.selectAll("empty").data(d3.range(x.length)).enter().append("circle").attr("cx", function(d, i) {
- return xscale(x[i]);
- }).attr("cy", function(d, i) {
- return yscale(y[i]);
- }).attr("class", function(d, i) {
- return "pt" + i;
- }).attr("r", pointsize).attr("fill", function(d, i) {
- return pointcolor[group[i]];
- }).attr("stroke", pointstroke).attr("stroke-width", "1").attr("opacity", function(d, i) {
- if (((x[i] != null) || xNA.handle) && ((y[i] != null) || yNA.handle)) {
- return 1;
- }
- return 0;
- }).on("mouseover.paneltip", indtip.show).on("mouseout.paneltip", indtip.hide);
- g.append("rect").attr("x", margin.left + paneloffset).attr("y", margin.top).attr("height", panelheight).attr("width", panelwidth).attr("fill", "none").attr("stroke", "black").attr("stroke-width", "none");
- if (xNA.handle) {
- g.append("rect").attr("x", margin.left).attr("y", margin.top).attr("height", panelheight).attr("width", xNA.width).attr("fill", "none").attr("stroke", "black").attr("stroke-width", "none");
- }
- if (xNA.handle && yNA.handle) {
- g.append("rect").attr("x", margin.left).attr("y", margin.top + height - yNA.width).attr("height", yNA.width).attr("width", xNA.width).attr("fill", "none").attr("stroke", "black").attr("stroke-width", "none");
- }
- if (yNA.handle) {
- return g.append("rect").attr("x", margin.left + paneloffset).attr("y", margin.top + height - yNA.width).attr("height", yNA.width).attr("width", panelwidth).attr("fill", "none").attr("stroke", "black").attr("stroke-width", "none");
- }
- });
- };
- chart.width = function(value) {
- if (!arguments.length) {
- return width;
- }
- width = value;
- return chart;
- };
- chart.height = function(value) {
- if (!arguments.length) {
- return height;
- }
- height = value;
- return chart;
- };
- chart.margin = function(value) {
- if (!arguments.length) {
- return margin;
- }
- margin = value;
- return chart;
- };
- chart.axispos = function(value) {
- if (!arguments.length) {
- return axispos;
- }
- axispos = value;
- return chart;
- };
- chart.titlepos = function(value) {
- if (!arguments.length) {
- return titlepos;
- }
- titlepos;
- return chart;
- };
- chart.xlim = function(value) {
- if (!arguments.length) {
- return xlim;
- }
- xlim = value;
- return chart;
- };
- chart.nxticks = function(value) {
- if (!arguments.length) {
- return nxticks;
- }
- nxticks = value;
- return chart;
- };
- chart.xticks = function(value) {
- if (!arguments.length) {
- return xticks;
- }
- xticks = value;
- return chart;
- };
- chart.ylim = function(value) {
- if (!arguments.length) {
- return ylim;
- }
- ylim = value;
- return chart;
- };
- chart.nyticks = function(value) {
- if (!arguments.length) {
- return nyticks;
- }
- nyticks = value;
- return chart;
- };
- chart.yticks = function(value) {
- if (!arguments.length) {
- return yticks;
- }
- yticks = value;
- return chart;
- };
- chart.rectcolor = function(value) {
- if (!arguments.length) {
- return rectcolor;
- }
- rectcolor = value;
- return chart;
- };
- chart.pointcolor = function(value) {
- if (!arguments.length) {
- return pointcolor;
- }
- pointcolor = value;
- return chart;
- };
- chart.pointsize = function(value) {
- if (!arguments.length) {
- return pointsize;
- }
- pointsize = value;
- return chart;
- };
- chart.pointstroke = function(value) {
- if (!arguments.length) {
- return pointstroke;
- }
- pointstroke = value;
- return chart;
- };
- chart.dataByInd = function(value) {
- if (!arguments.length) {
- return dataByInd;
- }
- dataByInd = value;
- return chart;
- };
- chart.title = function(value) {
- if (!arguments.length) {
- return title;
- }
- title = value;
- return chart;
- };
- chart.xlab = function(value) {
- if (!arguments.length) {
- return xlab;
- }
- xlab = value;
- return chart;
- };
- chart.ylab = function(value) {
- if (!arguments.length) {
- return ylab;
- }
- ylab = value;
- return chart;
- };
- chart.rotate_ylab = function(value) {
- if (!arguments.length) {
- return rotate_ylab;
- }
- rotate_ylab = value;
- return chart;
- };
- chart.xvar = function(value) {
- if (!arguments.length) {
- return xvar;
- }
- xvar = value;
- return chart;
- };
- chart.yvar = function(value) {
- if (!arguments.length) {
- return yvar;
- }
- yvar = value;
- return chart;
- };
- chart.xNA = function(value) {
- if (!arguments.length) {
- return xNA;
- }
- xNA = value;
- return chart;
- };
- chart.yNA = function(value) {
- if (!arguments.length) {
- return yNA;
- }
- yNA = value;
- return chart;
- };
- chart.yscale = function() {
- return yscale;
- };
- chart.xscale = function() {
- return xscale;
- };
- chart.pointsSelect = function() {
- return pointsSelect;
- };
- return chart;
-};
-
-probability_plot();
diff --git a/wqflask/wqflask/static/new/javascript/scatterplot.coffee b/wqflask/wqflask/static/new/javascript/scatterplot.coffee
index 6a96e50f..008ab925 100644
--- a/wqflask/wqflask/static/new/javascript/scatterplot.coffee
+++ b/wqflask/wqflask/static/new/javascript/scatterplot.coffee
@@ -427,4 +427,4 @@ scatterplot = () ->
# return the chart function
chart
-root.scatterplot = scatterplot \ No newline at end of file
+root.scatterplot = scatterplot
diff --git a/wqflask/wqflask/static/new/javascript/search_results.coffee b/wqflask/wqflask/static/new/javascript/search_results.coffee
index c4e6b1a2..e0cfc61a 100755
--- a/wqflask/wqflask/static/new/javascript/search_results.coffee
+++ b/wqflask/wqflask/static/new/javascript/search_results.coffee
@@ -15,8 +15,7 @@ $ ->
$(".trait_checkbox").trigger('click')
add = ->
- traits = $("#trait_table input:checked").map(->
- return $(this).val()).get()
+ traits = $("#trait_table input:checked").map(-> return $(this).val()).get()
console.log("checked length is:", traits.length)
console.log("checked is:", traits)
$.colorbox({href:"/collections/add?traits=#{traits}"})
diff --git a/wqflask/wqflask/static/new/javascript/search_results.js b/wqflask/wqflask/static/new/javascript/search_results.js
index ba2ebb4f..25381996 100755
--- a/wqflask/wqflask/static/new/javascript/search_results.js
+++ b/wqflask/wqflask/static/new/javascript/search_results.js
@@ -1,17 +1,94 @@
-// Generated by CoffeeScript 1.8.0
$(function() {
var add, change_buttons, checked_traits, deselect_all, invert, remove, removed_traits, select_all;
+
checked_traits = null;
select_all = function() {
console.log("selected_all");
- return $(".trait_checkbox").prop('checked', true);
+ $(".trait_checkbox").each(function() {
+ $(this).prop('checked', true);
+ if (!$(this).closest('tr').hasClass('selected')) {
+ $(this).closest('tr').addClass('selected')
+ }
+ });
};
+
deselect_all = function() {
- return $(".trait_checkbox").prop('checked', false);
+ $(".trait_checkbox").each(function() {
+ $(this).prop('checked', false);
+ if ($(this).closest('tr').hasClass('selected')) {
+ $(this).closest('tr').removeClass('selected')
+ }
+ });
};
+
invert = function() {
- return $(".trait_checkbox").trigger('click');
+ $(".trait_checkbox").each(function() {
+ if ($(this).prop('checked') == true) {
+ $(this).prop('checked', false)
+ }
+ else {
+ $(this).prop('checked', true)
+ }
+
+ if ($(this).closest('tr').hasClass('selected')) {
+ $(this).closest('tr').removeClass('selected')
+ }
+ else {
+ $(this).closest('tr').addClass('selected')
+ }
+ });
};
+
+ $('#searchbox').keyup(function(){
+ $('#trait_table').DataTable().search($(this).val()).draw();
+ });
+
+ $('#select_top').keyup(function(){
+ num_rows = $(this).val()
+ if (num_rows = parseInt(num_rows)){
+ i = 0
+ $('#trait_table > tbody > tr').each(function(){
+ if (i < num_rows) {
+ $(this).find('.trait_checkbox').prop("checked", true)
+ if (!$(this).closest('tr').hasClass('selected')) {
+ $(this).closest('tr').addClass('selected')
+ }
+ }
+ else {
+ if ($(this).closest('tr').hasClass('selected')) {
+ $(this).closest('tr').removeClass('selected')
+ $(this).find('.trait_checkbox').prop("checked", false)
+ }
+ }
+ i += 1
+ });
+ }
+ else {
+ $('#trait_table > tbody > tr').each(function(){
+ $(this).closest('tr').removeClass('selected')
+ $(this).find('.trait_checkbox').prop("checked", false)
+ });
+ }
+ change_buttons();
+ });
+
+ $('.trait_checkbox:checkbox').change(function() {
+ console.log("CHANGED")
+ change_buttons()
+
+ if ($(this).is(":checked")) {
+ if (!$(this).closest('tr').hasClass('selected')) {
+ $(this).closest('tr').addClass('selected')
+ }
+ }
+ else {
+ if ($(this).closest('tr').hasClass('selected')) {
+ $(this).closest('tr').removeClass('selected')
+ }
+ }
+
+ });
+
add = function() {
var traits;
traits = $("#trait_table input:checked").map(function() {
@@ -28,7 +105,7 @@ $(function() {
return checked_traits.closest("tr").fadeOut();
};
change_buttons = function() {
- var button, buttons, item, num_checked, text, _i, _j, _k, _l, _len, _len1, _len2, _len3, _results, _results1;
+ var button, buttons, item, num_checked, text, _i, _j, _k, _l, _len, _len2, _len3, _len4, _results, _results2;
buttons = ["#add", "#remove"];
num_checked = $('.trait_checkbox:checked').length;
console.log("num_checked is:", num_checked);
@@ -38,31 +115,13 @@ $(function() {
$(button).prop("disabled", true);
}
} else {
- for (_j = 0, _len1 = buttons.length; _j < _len1; _j++) {
+ for (_j = 0, _len2 = buttons.length; _j < _len2; _j++) {
button = buttons[_j];
$(button).prop("disabled", false);
}
}
- if (num_checked > 1) {
- console.log("in loop");
- _results = [];
- for (_k = 0, _len2 = buttons.length; _k < _len2; _k++) {
- item = buttons[_k];
- console.log(" processing item:", item);
- _results.push(text = $(item).html());
- }
- return _results;
- } else {
- console.log("in loop");
- _results1 = [];
- for (_l = 0, _len3 = buttons.length; _l < _len3; _l++) {
- item = buttons[_l];
- console.log(" processing item:", item);
- _results1.push(text = $(item).html());
- }
- return _results1;
- }
};
+
remove = function() {
var traits, uc_id;
checked_traits = $("#trait_table input:checked");
@@ -88,6 +147,5 @@ $(function() {
$("#invert").click(invert);
$("#add").click(add);
$("#remove").click(remove);
- $('.trait_checkbox').click(change_buttons);
- return $('.btn').click(change_buttons);
-});
+ $('.trait_checkbox, .btn').click(change_buttons);
+}); \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/javascript/show_trait.coffee b/wqflask/wqflask/static/new/javascript/show_trait.coffee
index d05ccbf7..91aa15ba 100755
--- a/wqflask/wqflask/static/new/javascript/show_trait.coffee
+++ b/wqflask/wqflask/static/new/javascript/show_trait.coffee
@@ -61,38 +61,16 @@ Stat_Table_Rows = [
]
$ ->
- sample_lists = js_data.sample_lists
- sample_group_types = js_data.sample_group_types
- #if $("#update_bar_chart").length
- # $("#update_bar_chart.btn-group").button()
- root.bar_chart = new Bar_Chart(sample_lists[0])
- root.histogram = new Histogram(sample_lists[0])
- new Box_Plot(sample_lists[0])
+ add = ->
+ trait = $("input[name=trait_hmac]").val()
+ console.log("trait is:", trait)
+ $.colorbox({href:"/collections/add?traits=#{trait}"})
- $('.bar_chart_samples_group').change ->
- $('#bar_chart').remove()
- $('#bar_chart_container').append('<div id="bar_chart"></div>')
- group = $(this).val()
- if group == "samples_primary"
- root.bar_chart = new Bar_Chart(sample_lists[0])
- else if group == "samples_other"
- root.bar_chart = new Bar_Chart(sample_lists[1])
- else if group == "samples_all"
- all_samples = sample_lists[0].concat sample_lists[1]
- root.bar_chart = new Bar_Chart(all_samples)
-
- $('.box_plot_samples_group').change ->
- $('#box_plot').remove()
- $('#box_plot_container').append('<div id="box_plot"></div>')
- group = $(this).val()
- if group == "samples_primary"
- new Box_Plot(sample_lists[0])
- else if group == "samples_other"
- new Box_Plot(sample_lists[1])
- else if group == "samples_all"
- all_samples = sample_lists[0].concat sample_lists[1]
- new Box_Plot(all_samples)
+ $('#add_to_collection').click(add)
+
+ sample_lists = js_data.sample_lists
+ sample_group_types = js_data.sample_group_types
d3.select("#select_compare_trait").on("click", =>
$('.scatter-matrix-container').remove()
@@ -126,7 +104,7 @@ $ ->
$("#stats_tabs" + selected).show()
- change_stats_value = (sample_sets, category, value_type, decimal_places)->
+ change_stats_value = (sample_sets, category, value_type, decimal_places, effects) ->
id = "#" + process_id(category, value_type)
console.log("the_id:", id)
in_box = $(id).html
@@ -145,7 +123,10 @@ $ ->
console.log("*-* current_value:", current_value)
if the_value != current_value
console.log("object:", $(id).html(the_value))
- $(id).html(the_value).effect("highlight")
+ if effects
+ $(id).html(the_value).effect("highlight")
+ else
+ $(id).html(the_value)
# We go ahead and always change the title value if we have it
if title_value
@@ -153,11 +134,20 @@ $ ->
update_stat_values = (sample_sets)->
+ show_effects = $(".tab-pane.active").attr("id") == "stats_tab"
for category in ['samples_primary', 'samples_other', 'samples_all']
for row in Stat_Table_Rows
console.log("Calling change_stats_value")
- change_stats_value(sample_sets, category, row.vn, row.digits)
+ change_stats_value(sample_sets, category, row.vn, row.digits, show_effects)
+
+ redraw_histogram = ->
+ root.histogram.redraw((x.value for x in _.values(root.selected_samples[root.histogram_group])))
+
+ redraw_bar_chart = ->
+ root.bar_chart.redraw(root.selected_samples, root.bar_chart_group)
+ redraw_prob_plot = ->
+ root.redraw_prob_plot_impl(root.selected_samples, root.prob_plot_group)
make_table = ->
header = "<thead><tr><th>&nbsp;</th>"
@@ -213,6 +203,11 @@ $ ->
samples_other: new Stats([])
samples_all: new Stats([])
+ root.selected_samples = # maps: sample name -> value
+ samples_primary: {}
+ samples_other: {}
+ samples_all: {}
+
console.log("at beginning:", sample_sets)
tables = ['samples_primary', 'samples_other']
@@ -222,24 +217,43 @@ $ ->
name = $(row).find('.edit_sample_sample_name').html()
name = $.trim(name)
real_value = $(row).find('.edit_sample_value').val()
- console.log("real_value:", real_value)
+ #console.log("real_value:", real_value)
checkbox = $(row).find(".edit_sample_checkbox")
- checked = $(checkbox).attr('checked')
+ checked = $(checkbox).prop('checked')
if checked and is_number(real_value) and real_value != ""
- console.log("in the iffy if")
+ #console.log("in the iffy if")
real_value = parseFloat(real_value)
sample_sets[table].add_value(real_value)
- console.log("checking name of:", name)
+
+ real_variance = $(row).find('.edit_sample_se').val()
+ if (is_number(real_variance))
+ real_variance = parseFloat(real_variance)
+ else
+ real_variance = null
+ real_dict = {value: real_value, variance: real_variance}
+ root.selected_samples[table][name] = real_dict
+
+ #console.log("checking name of:", name)
if not (name of already_seen)
- console.log("haven't seen")
+ #console.log("haven't seen")
sample_sets['samples_all'].add_value(real_value)
+ root.selected_samples['samples_all'][name] = real_dict
already_seen[name] = true
console.log("towards end:", sample_sets)
update_stat_values(sample_sets)
+ console.log("redrawing histogram")
+ redraw_histogram()
+
+ console.log("redrawing bar chart")
+ redraw_bar_chart()
+
+ console.log("redrawing probability plot")
+ redraw_prob_plot()
+
show_hide_outliers = ->
console.log("FOOBAR in beginning of show_hide_outliers")
label = $('#show_hide_outliers').val()
@@ -377,11 +391,9 @@ $ ->
##Get Sample Data From Table Code
- get_sample_table_data = ->
- samples = {}
- primary_samples = []
- other_samples = []
- $('#sortable1').find('.value_se').each (_index, element) =>
+ get_sample_table_data = (table_name) ->
+ samples = []
+ $('#' + table_name).find('.value_se').each (_index, element) =>
row_data = {}
row_data.name = $.trim($(element).find('.column_name-Sample').text())
row_data.value = $(element).find('.edit_sample_value').val()
@@ -391,10 +403,7 @@ $ ->
row_data[attribute_info.name] = $.trim($(element).find(
'.column_name-'+attribute_info.name.replace(" ", "_")).text())
console.log("row_data is:", row_data)
- primary_samples.push(row_data)
- console.log("primary_samples is:", primary_samples)
- samples.primary_samples = primary_samples
- samples.other_samples = other_samples
+ samples.push(row_data)
return samples
##End Get Sample Data from Table Code
@@ -402,7 +411,9 @@ $ ->
##Export Sample Table Data Code
export_sample_table_data = ->
- sample_data = get_sample_table_data()
+ sample_data = {}
+ sample_data.primary_samples = get_sample_table_data('samples_primary')
+ sample_data.other_samples = get_sample_table_data('samples_other')
console.log("sample_data is:", sample_data)
json_sample_data = JSON.stringify(sample_data)
console.log("json_sample_data is:", json_sample_data)
@@ -429,11 +440,37 @@ $ ->
console.log("after registering block_outliers")
_.mixin(_.str.exports()); # Add string fuctions directly to underscore
- $('#edit_sample_lists').change(edit_data_change)
- console.log("loaded")
- #console.log("basic_table is:", basic_table)
- # Add back following two lines later
+
+ root.histogram_group = 'samples_primary'
+ root.histogram = new Histogram(sample_lists[0])
+ $('.histogram_samples_group').val(root.histogram_group)
+ $('.histogram_samples_group').change ->
+ root.histogram_group = $(this).val()
+ redraw_histogram()
+
+ root.bar_chart_group = 'samples_primary'
+ root.bar_chart = new Bar_Chart(sample_lists)
+ $('.bar_chart_samples_group').val(root.bar_chart_group)
+ $('.bar_chart_samples_group').change ->
+ root.bar_chart_group = $(this).val()
+ redraw_bar_chart()
+
+ root.prob_plot_group = 'samples_primary'
+ $('.prob_plot_samples_group').val(root.prob_plot_group)
+ $('.prob_plot_samples_group').change ->
+ root.prob_plot_group = $(this).val()
+ redraw_prob_plot()
+
make_table()
edit_data_change() # Set the values at the beginning
+
+ $('#edit_sample_lists').change(edit_data_change)
+
+ # bind additional handlers for pushing data updates
+ $('#block_by_index').click(edit_data_change)
+ $('#exclude_group').click(edit_data_change)
+ $('#block_outliers').click(edit_data_change)
+ $('#reset').click(edit_data_change)
+
#$("#all-mean").html('foobar8')
console.log("end")
diff --git a/wqflask/wqflask/static/new/javascript/show_trait.js b/wqflask/wqflask/static/new/javascript/show_trait.js
index 159dafcb..1dd54e3a 100755
--- a/wqflask/wqflask/static/new/javascript/show_trait.js
+++ b/wqflask/wqflask/static/new/javascript/show_trait.js
@@ -1,469 +1,508 @@
// Generated by CoffeeScript 1.8.0
-var Stat_Table_Rows, is_number,
- __hasProp = {}.hasOwnProperty,
- __slice = [].slice;
+(function() {
+ var Stat_Table_Rows, is_number,
+ __hasProp = {}.hasOwnProperty,
+ __slice = [].slice;
-console.log("start_b");
+ console.log("start_b");
-is_number = function(o) {
- return !isNaN((o - 0) && o !== null);
-};
-
-Stat_Table_Rows = [
- {
- vn: "n_of_samples",
- pretty: "N of Samples",
- digits: 0
- }, {
- vn: "mean",
- pretty: "Mean",
- digits: 2
- }, {
- vn: "median",
- pretty: "Median",
- digits: 2
- }, {
- vn: "std_error",
- pretty: "Standard Error (SE)",
- digits: 2
- }, {
- vn: "std_dev",
- pretty: "Standard Deviation (SD)",
- digits: 2
- }, {
- vn: "min",
- pretty: "Minimum",
- digits: 2
- }, {
- vn: "max",
- pretty: "Maximum",
- digits: 2
- }, {
- vn: "range",
- pretty: "Range (log2)",
- digits: 2
- }, {
- vn: "range_fold",
- pretty: "Range (fold)",
- digits: 2
- }, {
- vn: "interquartile",
- pretty: "Interquartile Range",
- url: "/glossary.html#Interquartile",
- digits: 2
- }
-];
+ is_number = function(o) {
+ return !isNaN((o - 0) && o !== null);
+ };
-$(function() {
- var block_by_attribute_value, block_by_index, block_outliers, change_stats_value, create_value_dropdown, edit_data_change, export_sample_table_data, get_sample_table_data, hide_no_value, hide_tabs, make_table, on_corr_method_change, open_trait_selection, populate_sample_attributes_values_dropdown, process_id, reset_samples_table, sample_group_types, sample_lists, show_hide_outliers, stats_mdp_change, update_stat_values;
- sample_lists = js_data.sample_lists;
- sample_group_types = js_data.sample_group_types;
- root.bar_chart = new Bar_Chart(sample_lists[0]);
- root.histogram = new Histogram(sample_lists[0]);
- new Box_Plot(sample_lists[0]);
- $('.bar_chart_samples_group').change(function() {
- var all_samples, group;
- $('#bar_chart').remove();
- $('#bar_chart_container').append('<div id="bar_chart"></div>');
- group = $(this).val();
- if (group === "samples_primary") {
- return root.bar_chart = new Bar_Chart(sample_lists[0]);
- } else if (group === "samples_other") {
- return root.bar_chart = new Bar_Chart(sample_lists[1]);
- } else if (group === "samples_all") {
- all_samples = sample_lists[0].concat(sample_lists[1]);
- return root.bar_chart = new Bar_Chart(all_samples);
- }
- });
- $('.box_plot_samples_group').change(function() {
- var all_samples, group;
- $('#box_plot').remove();
- $('#box_plot_container').append('<div id="box_plot"></div>');
- group = $(this).val();
- if (group === "samples_primary") {
- return new Box_Plot(sample_lists[0]);
- } else if (group === "samples_other") {
- return new Box_Plot(sample_lists[1]);
- } else if (group === "samples_all") {
- all_samples = sample_lists[0].concat(sample_lists[1]);
- return new Box_Plot(all_samples);
+ Stat_Table_Rows = [
+ {
+ vn: "n_of_samples",
+ pretty: "N of Samples",
+ digits: 0
+ }, {
+ vn: "mean",
+ pretty: "Mean",
+ digits: 2
+ }, {
+ vn: "median",
+ pretty: "Median",
+ digits: 2
+ }, {
+ vn: "std_error",
+ pretty: "Standard Error (SE)",
+ digits: 2
+ }, {
+ vn: "std_dev",
+ pretty: "Standard Deviation (SD)",
+ digits: 2
+ }, {
+ vn: "min",
+ pretty: "Minimum",
+ digits: 2
+ }, {
+ vn: "max",
+ pretty: "Maximum",
+ digits: 2
+ }, {
+ vn: "range",
+ pretty: "Range (log2)",
+ digits: 2
+ }, {
+ vn: "range_fold",
+ pretty: "Range (fold)",
+ digits: 2
+ }, {
+ vn: "interquartile",
+ pretty: "Interquartile Range",
+ url: "/glossary.html#Interquartile",
+ digits: 2
}
- });
- d3.select("#select_compare_trait").on("click", (function(_this) {
- return function() {
- $('.scatter-matrix-container').remove();
- return open_trait_selection();
- };
- })(this));
- d3.select("#clear_compare_trait").on("click", (function(_this) {
- return function() {
- return $('.scatter-matrix-container').remove();
+ ];
+
+ $(function() {
+ var add, block_by_attribute_value, block_by_index, block_outliers, change_stats_value, create_value_dropdown, edit_data_change, export_sample_table_data, get_sample_table_data, hide_no_value, hide_tabs, make_table, on_corr_method_change, open_trait_selection, populate_sample_attributes_values_dropdown, process_id, redraw_bar_chart, redraw_histogram, redraw_prob_plot, reset_samples_table, sample_group_types, sample_lists, show_hide_outliers, stats_mdp_change, update_stat_values;
+ add = function() {
+ var trait;
+ trait = $("input[name=trait_hmac]").val();
+ console.log("trait is:", trait);
+ return $.colorbox({
+ href: "/collections/add?traits=" + trait
+ });
};
- })(this));
- open_trait_selection = function() {
- return $('#collections_holder').load('/collections/list?color_by_trait #collections_list', (function(_this) {
+ $('#add_to_collection').click(add);
+ sample_lists = js_data.sample_lists;
+ sample_group_types = js_data.sample_group_types;
+ d3.select("#select_compare_trait").on("click", (function(_this) {
return function() {
- $.colorbox({
- inline: true,
- href: "#collections_holder"
- });
- return $('a.collection_name').attr('onClick', 'return false');
+ $('.scatter-matrix-container').remove();
+ return open_trait_selection();
};
})(this));
- };
- hide_tabs = function(start) {
- var x, _i, _results;
- _results = [];
- for (x = _i = start; start <= 10 ? _i <= 10 : _i >= 10; x = start <= 10 ? ++_i : --_i) {
- _results.push($("#stats_tabs" + x).hide());
- }
- return _results;
- };
- stats_mdp_change = function() {
- var selected;
- selected = $(this).val();
- hide_tabs(0);
- return $("#stats_tabs" + selected).show();
- };
- change_stats_value = function(sample_sets, category, value_type, decimal_places) {
- var current_value, id, in_box, the_value, title_value;
- id = "#" + process_id(category, value_type);
- console.log("the_id:", id);
- in_box = $(id).html;
- current_value = parseFloat($(in_box)).toFixed(decimal_places);
- the_value = sample_sets[category][value_type]();
- console.log("After running sample_sets, the_value is:", the_value);
- if (decimal_places > 0) {
- title_value = the_value.toFixed(decimal_places * 2);
- the_value = the_value.toFixed(decimal_places);
- } else {
- title_value = null;
- }
- console.log("*-* the_value:", the_value);
- console.log("*-* current_value:", current_value);
- if (the_value !== current_value) {
- console.log("object:", $(id).html(the_value));
- $(id).html(the_value).effect("highlight");
- }
- if (title_value) {
- return $(id).attr('title', title_value);
- }
- };
- update_stat_values = function(sample_sets) {
- var category, row, _i, _len, _ref, _results;
- _ref = ['samples_primary', 'samples_other', 'samples_all'];
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- category = _ref[_i];
- _results.push((function() {
- var _j, _len1, _results1;
- _results1 = [];
- for (_j = 0, _len1 = Stat_Table_Rows.length; _j < _len1; _j++) {
- row = Stat_Table_Rows[_j];
- console.log("Calling change_stats_value");
- _results1.push(change_stats_value(sample_sets, category, row.vn, row.digits));
- }
- return _results1;
- })());
- }
- return _results;
- };
- make_table = function() {
- var header, key, row, row_line, table, the_id, the_rows, value, _i, _len, _ref, _ref1;
- header = "<thead><tr><th>&nbsp;</th>";
- console.log("js_data.sample_group_types:", js_data.sample_group_types);
- _ref = js_data.sample_group_types;
- for (key in _ref) {
- if (!__hasProp.call(_ref, key)) continue;
- value = _ref[key];
- console.log("aa key:", key);
- console.log("aa value:", value);
- the_id = process_id("column", key);
- header += "<th id=\"" + the_id + "\">" + value + "</th>";
- }
- header += "</thead>";
- console.log("windex header is:", header);
- the_rows = "<tbody>";
- for (_i = 0, _len = Stat_Table_Rows.length; _i < _len; _i++) {
- row = Stat_Table_Rows[_i];
- console.log("rowing");
- row_line = "<tr>";
- if (row.url != null) {
- row_line += "<td id=\"" + row.vn + "\"><a href=\"" + row.url + "\">" + row.pretty + "</a></td>";
+ d3.select("#clear_compare_trait").on("click", (function(_this) {
+ return function() {
+ return $('.scatter-matrix-container').remove();
+ };
+ })(this));
+ open_trait_selection = function() {
+ return $('#collections_holder').load('/collections/list?color_by_trait #collections_list', (function(_this) {
+ return function() {
+ $.colorbox({
+ inline: true,
+ href: "#collections_holder"
+ });
+ return $('a.collection_name').attr('onClick', 'return false');
+ };
+ })(this));
+ };
+ hide_tabs = function(start) {
+ var x, _i, _results;
+ _results = [];
+ for (x = _i = start; start <= 10 ? _i <= 10 : _i >= 10; x = start <= 10 ? ++_i : --_i) {
+ _results.push($("#stats_tabs" + x).hide());
+ }
+ return _results;
+ };
+ stats_mdp_change = function() {
+ var selected;
+ selected = $(this).val();
+ hide_tabs(0);
+ return $("#stats_tabs" + selected).show();
+ };
+ change_stats_value = function(sample_sets, category, value_type, decimal_places, effects) {
+ var current_value, id, in_box, the_value, title_value;
+ id = "#" + process_id(category, value_type);
+ console.log("the_id:", id);
+ in_box = $(id).html;
+ current_value = parseFloat($(in_box)).toFixed(decimal_places);
+ the_value = sample_sets[category][value_type]();
+ console.log("After running sample_sets, the_value is:", the_value);
+ if (decimal_places > 0) {
+ title_value = the_value.toFixed(decimal_places * 2);
+ the_value = the_value.toFixed(decimal_places);
} else {
- row_line += "<td id=\"" + row.vn + "\">" + row.pretty + "</td>";
+ title_value = null;
}
- console.log("box - js_data.sample_group_types:", js_data.sample_group_types);
- _ref1 = js_data.sample_group_types;
- for (key in _ref1) {
- if (!__hasProp.call(_ref1, key)) continue;
- value = _ref1[key];
- console.log("apple key:", key);
- the_id = process_id(key, row.vn);
- console.log("the_id:", the_id);
- row_line += "<td id=\"" + the_id + "\">foo</td>";
+ console.log("*-* the_value:", the_value);
+ console.log("*-* current_value:", current_value);
+ if (the_value !== current_value) {
+ console.log("object:", $(id).html(the_value));
+ if (effects) {
+ $(id).html(the_value).effect("highlight");
+ } else {
+ $(id).html(the_value);
+ }
}
- row_line += "</tr>";
- console.log("row line:", row_line);
- the_rows += row_line;
- }
- the_rows += "</tbody>";
- table = header + the_rows;
- console.log("table is:", table);
- return $("#stats_table").append(table);
- };
- process_id = function() {
- var processed, value, values, _i, _len;
- values = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
-
- /* Make an id or a class valid javascript by, for example, eliminating spaces */
- processed = "";
- for (_i = 0, _len = values.length; _i < _len; _i++) {
- value = values[_i];
- console.log("value:", value);
- value = value.replace(" ", "_");
- if (processed.length) {
- processed += "-";
+ if (title_value) {
+ return $(id).attr('title', title_value);
}
- processed += value;
- }
- return processed;
- };
- edit_data_change = function() {
- var already_seen, checkbox, checked, name, real_value, row, rows, sample_sets, table, tables, _i, _j, _len, _len1;
- already_seen = {};
- sample_sets = {
- samples_primary: new Stats([]),
- samples_other: new Stats([]),
- samples_all: new Stats([])
};
- console.log("at beginning:", sample_sets);
- tables = ['samples_primary', 'samples_other'];
- for (_i = 0, _len = tables.length; _i < _len; _i++) {
- table = tables[_i];
- rows = $("#" + table).find('tr');
- for (_j = 0, _len1 = rows.length; _j < _len1; _j++) {
- row = rows[_j];
- name = $(row).find('.edit_sample_sample_name').html();
- name = $.trim(name);
- real_value = $(row).find('.edit_sample_value').val();
- console.log("real_value:", real_value);
- checkbox = $(row).find(".edit_sample_checkbox");
- checked = $(checkbox).attr('checked');
- if (checked && is_number(real_value) && real_value !== "") {
- console.log("in the iffy if");
- real_value = parseFloat(real_value);
- sample_sets[table].add_value(real_value);
- console.log("checking name of:", name);
- if (!(name in already_seen)) {
- console.log("haven't seen");
- sample_sets['samples_all'].add_value(real_value);
- already_seen[name] = true;
+ update_stat_values = function(sample_sets) {
+ var category, row, show_effects, _i, _len, _ref, _results;
+ show_effects = $(".tab-pane.active").attr("id") === "stats_tab";
+ _ref = ['samples_primary', 'samples_other', 'samples_all'];
+ _results = [];
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ category = _ref[_i];
+ _results.push((function() {
+ var _j, _len1, _results1;
+ _results1 = [];
+ for (_j = 0, _len1 = Stat_Table_Rows.length; _j < _len1; _j++) {
+ row = Stat_Table_Rows[_j];
+ console.log("Calling change_stats_value");
+ _results1.push(change_stats_value(sample_sets, category, row.vn, row.digits, show_effects));
}
+ return _results1;
+ })());
+ }
+ return _results;
+ };
+ redraw_histogram = function() {
+ var x;
+ return root.histogram.redraw((function() {
+ var _i, _len, _ref, _results;
+ _ref = _.values(root.selected_samples[root.histogram_group]);
+ _results = [];
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ x = _ref[_i];
+ _results.push(x.value);
}
+ return _results;
+ })());
+ };
+ redraw_bar_chart = function() {
+ return root.bar_chart.redraw(root.selected_samples, root.bar_chart_group);
+ };
+ redraw_prob_plot = function() {
+ return root.redraw_prob_plot_impl(root.selected_samples, root.prob_plot_group);
+ };
+ make_table = function() {
+ var header, key, row, row_line, table, the_id, the_rows, value, _i, _len, _ref, _ref1;
+ header = "<thead><tr><th>&nbsp;</th>";
+ console.log("js_data.sample_group_types:", js_data.sample_group_types);
+ _ref = js_data.sample_group_types;
+ for (key in _ref) {
+ if (!__hasProp.call(_ref, key)) continue;
+ value = _ref[key];
+ the_id = process_id("column", key);
+ header += "<th id=\"" + the_id + "\">" + value + "</th>";
}
- }
- console.log("towards end:", sample_sets);
- return update_stat_values(sample_sets);
- };
- show_hide_outliers = function() {
- var label;
- console.log("FOOBAR in beginning of show_hide_outliers");
- label = $('#show_hide_outliers').val();
- console.log("lable is:", label);
- if (label === "Hide Outliers") {
- return $('#show_hide_outliers').val("Show Outliers");
- } else if (label === "Show Outliers") {
- console.log("Found Show Outliers");
- $('#show_hide_outliers').val("Hide Outliers");
- return console.log("Should be now Hide Outliers");
- }
- };
- on_corr_method_change = function() {
- var corr_method;
- console.log("in beginning of on_corr_method_change");
- corr_method = $('select[name=corr_method]').val();
- console.log("corr_method is:", corr_method);
- $('.correlation_desc').hide();
- $('#' + corr_method + "_r_desc").show().effect("highlight");
- if (corr_method === "lit") {
- return $("#corr_sample_method_options").hide();
- } else {
- return $("#corr_sample_method_options").show();
- }
- };
- $('select[name=corr_method]').change(on_corr_method_change);
- create_value_dropdown = function(value) {
- return "<option val=" + value + ">" + value + "</option>";
- };
- populate_sample_attributes_values_dropdown = function() {
- var attribute_info, key, sample_attributes, selected_attribute, value, _i, _len, _ref, _ref1, _results;
- console.log("in beginning of psavd");
- $('#attribute_values').empty();
- sample_attributes = {};
- _ref = js_data.attribute_names;
- for (key in _ref) {
- if (!__hasProp.call(_ref, key)) continue;
- attribute_info = _ref[key];
- sample_attributes[attribute_info.name] = attribute_info.distinct_values;
- }
- console.log("[visa] attributes is:", sample_attributes);
- selected_attribute = $('#exclude_menu').val().replace("_", " ");
- console.log("selected_attribute is:", selected_attribute);
- _ref1 = sample_attributes[selected_attribute];
- _results = [];
- for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
- value = _ref1[_i];
- _results.push($(create_value_dropdown(value)).appendTo($('#attribute_values')));
- }
- return _results;
- };
- if (js_data.attribute_names.length > 0) {
- populate_sample_attributes_values_dropdown();
- }
- $('#exclude_menu').change(populate_sample_attributes_values_dropdown);
- block_by_attribute_value = function() {
- var attribute_name, cell_class, exclude_by_value;
- attribute_name = $('#exclude_menu').val();
- exclude_by_value = $('#attribute_values').val();
- cell_class = ".column_name-" + attribute_name;
- return $(cell_class).each((function(_this) {
- return function(index, element) {
- var row;
- if ($.trim($(element).text()) === exclude_by_value) {
- row = $(element).parent('tr');
- return $(row).find(".trait_value_input").val("x");
+ header += "</thead>";
+ the_rows = "<tbody>";
+ for (_i = 0, _len = Stat_Table_Rows.length; _i < _len; _i++) {
+ row = Stat_Table_Rows[_i];
+ console.log("rowing");
+ row_line = "<tr>";
+ if (row.url != null) {
+ row_line += "<td id=\"" + row.vn + "\"><a href=\"" + row.url + "\">" + row.pretty + "</a></td>";
+ } else {
+ row_line += "<td id=\"" + row.vn + "\">" + row.pretty + "</td>";
}
+ console.log("box - js_data.sample_group_types:", js_data.sample_group_types);
+ _ref1 = js_data.sample_group_types;
+ for (key in _ref1) {
+ if (!__hasProp.call(_ref1, key)) continue;
+ value = _ref1[key];
+ the_id = process_id(key, row.vn);
+ row_line += "<td id=\"" + the_id + "\">foo</td>";
+ }
+ row_line += "</tr>";
+ console.log("row line:", row_line);
+ the_rows += row_line;
+ }
+ the_rows += "</tbody>";
+ table = header + the_rows;
+ console.log("table is:", table);
+ return $("#stats_table").append(table);
+ };
+ process_id = function() {
+ var processed, value, values, _i, _len;
+ values = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
+
+ /* Make an id or a class valid javascript by, for example, eliminating spaces */
+ processed = "";
+ for (_i = 0, _len = values.length; _i < _len; _i++) {
+ value = values[_i];
+ console.log("value:", value);
+ value = value.replace(" ", "_");
+ if (processed.length) {
+ processed += "-";
+ }
+ processed += value;
+ }
+ return processed;
+ };
+ edit_data_change = function() {
+ var already_seen, checkbox, checked, name, real_dict, real_value, real_variance, row, rows, sample_sets, table, tables, _i, _j, _len, _len1;
+ already_seen = {};
+ sample_sets = {
+ samples_primary: new Stats([]),
+ samples_other: new Stats([]),
+ samples_all: new Stats([])
};
- })(this));
- };
- $('#exclude_group').click(block_by_attribute_value);
- block_by_index = function() {
- var end_index, error, index, index_list, index_set, index_string, start_index, _i, _j, _k, _len, _len1, _ref, _results;
- index_string = $('#remove_samples_field').val();
- index_list = [];
- _ref = index_string.split(",");
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- index_set = _ref[_i];
- if (index_set.indexOf('-') !== -1) {
- try {
- start_index = parseInt(index_set.split("-")[0]);
- end_index = parseInt(index_set.split("-")[1]);
- for (index = _j = start_index; start_index <= end_index ? _j <= end_index : _j >= end_index; index = start_index <= end_index ? ++_j : --_j) {
- index_list.push(index);
+ root.selected_samples = {
+ samples_primary: {},
+ samples_other: {},
+ samples_all: {}
+ };
+ console.log("at beginning:", sample_sets);
+ tables = ['samples_primary', 'samples_other'];
+ for (_i = 0, _len = tables.length; _i < _len; _i++) {
+ table = tables[_i];
+ rows = $("#" + table).find('tr');
+ for (_j = 0, _len1 = rows.length; _j < _len1; _j++) {
+ row = rows[_j];
+ name = $(row).find('.edit_sample_sample_name').html();
+ name = $.trim(name);
+ real_value = $(row).find('.edit_sample_value').val();
+ checkbox = $(row).find(".edit_sample_checkbox");
+ checked = $(checkbox).prop('checked');
+ if (checked && is_number(real_value) && real_value !== "") {
+ real_value = parseFloat(real_value);
+ sample_sets[table].add_value(real_value);
+ real_variance = $(row).find('.edit_sample_se').val();
+ if (is_number(real_variance)) {
+ real_variance = parseFloat(real_variance);
+ } else {
+ real_variance = null;
+ }
+ real_dict = {
+ value: real_value,
+ variance: real_variance
+ };
+ root.selected_samples[table][name] = real_dict;
+ if (!(name in already_seen)) {
+ sample_sets['samples_all'].add_value(real_value);
+ root.selected_samples['samples_all'][name] = real_dict;
+ already_seen[name] = true;
+ }
}
- } catch (_error) {
- error = _error;
- alert("Syntax error");
}
- } else {
- index = parseInt(index_set);
- console.log("index:", index);
- index_list.push(index);
}
- }
- console.log("index_list:", index_list);
- _results = [];
- for (_k = 0, _len1 = index_list.length; _k < _len1; _k++) {
- index = index_list[_k];
- if ($('#block_group').val() === "primary") {
- console.log("block_group:", $('#block_group').val());
- console.log("row:", $('#Primary_' + index.toString()));
- _results.push($('#Primary_' + index.toString()).find('.trait_value_input').val("x"));
- } else if ($('#block_group').val() === "other") {
- console.log("block_group:", $('#block_group').val());
- console.log("row:", $('#Other_' + index.toString()));
- _results.push($('#Other_' + index.toString()).find('.trait_value_input').val("x"));
+ console.log("towards end:", sample_sets);
+ update_stat_values(sample_sets);
+ console.log("redrawing histogram");
+ redraw_histogram();
+ console.log("redrawing bar chart");
+ redraw_bar_chart();
+ console.log("redrawing probability plot");
+ return redraw_prob_plot();
+ };
+ show_hide_outliers = function() {
+ var label;
+ console.log("FOOBAR in beginning of show_hide_outliers");
+ label = $('#show_hide_outliers').val();
+ console.log("lable is:", label);
+ if (label === "Hide Outliers") {
+ return $('#show_hide_outliers').val("Show Outliers");
+ } else if (label === "Show Outliers") {
+ console.log("Found Show Outliers");
+ $('#show_hide_outliers').val("Hide Outliers");
+ return console.log("Should be now Hide Outliers");
+ }
+ };
+ on_corr_method_change = function() {
+ var corr_method;
+ console.log("in beginning of on_corr_method_change");
+ corr_method = $('select[name=corr_method]').val();
+ console.log("corr_method is:", corr_method);
+ $('.correlation_desc').hide();
+ $('#' + corr_method + "_r_desc").show().effect("highlight");
+ if (corr_method === "lit") {
+ return $("#corr_sample_method_options").hide();
} else {
- _results.push(void 0);
+ return $("#corr_sample_method_options").show();
+ }
+ };
+ $('select[name=corr_method]').change(on_corr_method_change);
+ create_value_dropdown = function(value) {
+ return "<option val=" + value + ">" + value + "</option>";
+ };
+ populate_sample_attributes_values_dropdown = function() {
+ var attribute_info, key, sample_attributes, selected_attribute, value, _i, _len, _ref, _ref1, _results;
+ console.log("in beginning of psavd");
+ $('#attribute_values').empty();
+ sample_attributes = {};
+ _ref = js_data.attribute_names;
+ for (key in _ref) {
+ if (!__hasProp.call(_ref, key)) continue;
+ attribute_info = _ref[key];
+ sample_attributes[attribute_info.name] = attribute_info.distinct_values;
}
+ console.log("[visa] attributes is:", sample_attributes);
+ selected_attribute = $('#exclude_menu').val().replace("_", " ");
+ console.log("selected_attribute is:", selected_attribute);
+ _ref1 = sample_attributes[selected_attribute];
+ _results = [];
+ for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
+ value = _ref1[_i];
+ _results.push($(create_value_dropdown(value)).appendTo($('#attribute_values')));
+ }
+ return _results;
+ };
+ if (js_data.attribute_names.length > 0) {
+ populate_sample_attributes_values_dropdown();
}
- return _results;
- };
- $('#block_by_index').click(block_by_index);
- hide_no_value = function() {
- return $('.value_se').each((function(_this) {
- return function(_index, element) {
- if ($(element).find('.trait_value_input').val() === 'x') {
- return $(element).hide();
- }
- };
- })(this));
- };
- $('#hide_no_value').click(hide_no_value);
- block_outliers = function() {
- return $('.outlier').each((function(_this) {
- return function(_index, element) {
- return $(element).find('.trait_value_input').val('x');
- };
- })(this));
- };
- $('#block_outliers').click(block_outliers);
- reset_samples_table = function() {
- return $('.trait_value_input').each((function(_this) {
- return function(_index, element) {
- console.log("value is:", $(element).val());
- $(element).val($(element).data('value'));
- console.log("data-value is:", $(element).data('value'));
- return $(element).parents('.value_se').show();
- };
- })(this));
- };
- $('#reset').click(reset_samples_table);
- get_sample_table_data = function() {
- var other_samples, primary_samples, samples;
- samples = {};
- primary_samples = [];
- other_samples = [];
- $('#sortable1').find('.value_se').each((function(_this) {
- return function(_index, element) {
- var attribute_info, key, row_data, _ref;
- row_data = {};
- row_data.name = $.trim($(element).find('.column_name-Sample').text());
- row_data.value = $(element).find('.edit_sample_value').val();
- if ($(element).find('.edit_sample_se').length !== -1) {
- row_data.se = $(element).find('.edit_sample_se').val();
+ $('#exclude_menu').change(populate_sample_attributes_values_dropdown);
+ block_by_attribute_value = function() {
+ var attribute_name, cell_class, exclude_by_value;
+ attribute_name = $('#exclude_menu').val();
+ exclude_by_value = $('#attribute_values').val();
+ cell_class = ".column_name-" + attribute_name;
+ return $(cell_class).each((function(_this) {
+ return function(index, element) {
+ var row;
+ if ($.trim($(element).text()) === exclude_by_value) {
+ row = $(element).parent('tr');
+ return $(row).find(".trait_value_input").val("x");
+ }
+ };
+ })(this));
+ };
+ $('#exclude_group').click(block_by_attribute_value);
+ block_by_index = function() {
+ var end_index, error, index, index_list, index_set, index_string, start_index, _i, _j, _k, _len, _len1, _ref, _results;
+ index_string = $('#remove_samples_field').val();
+ index_list = [];
+ _ref = index_string.split(",");
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ index_set = _ref[_i];
+ if (index_set.indexOf('-') !== -1) {
+ try {
+ start_index = parseInt(index_set.split("-")[0]);
+ end_index = parseInt(index_set.split("-")[1]);
+ for (index = _j = start_index; start_index <= end_index ? _j <= end_index : _j >= end_index; index = start_index <= end_index ? ++_j : --_j) {
+ index_list.push(index);
+ }
+ } catch (_error) {
+ error = _error;
+ alert("Syntax error");
+ }
+ } else {
+ index = parseInt(index_set);
+ console.log("index:", index);
+ index_list.push(index);
}
- _ref = js_data.attribute_names;
- for (key in _ref) {
- if (!__hasProp.call(_ref, key)) continue;
- attribute_info = _ref[key];
- row_data[attribute_info.name] = $.trim($(element).find('.column_name-' + attribute_info.name.replace(" ", "_")).text());
+ }
+ console.log("index_list:", index_list);
+ _results = [];
+ for (_k = 0, _len1 = index_list.length; _k < _len1; _k++) {
+ index = index_list[_k];
+ if ($('#block_group').val() === "primary") {
+ console.log("block_group:", $('#block_group').val());
+ console.log("row:", $('#Primary_' + index.toString()));
+ _results.push($('#Primary_' + index.toString()).find('.trait_value_input').val("x"));
+ } else if ($('#block_group').val() === "other") {
+ console.log("block_group:", $('#block_group').val());
+ console.log("row:", $('#Other_' + index.toString()));
+ _results.push($('#Other_' + index.toString()).find('.trait_value_input').val("x"));
+ } else {
+ _results.push(void 0);
}
- console.log("row_data is:", row_data);
- return primary_samples.push(row_data);
- };
- })(this));
- console.log("primary_samples is:", primary_samples);
- samples.primary_samples = primary_samples;
- samples.other_samples = other_samples;
- return samples;
- };
- export_sample_table_data = function() {
- var format, json_sample_data, sample_data;
- sample_data = get_sample_table_data();
- console.log("sample_data is:", sample_data);
- json_sample_data = JSON.stringify(sample_data);
- console.log("json_sample_data is:", json_sample_data);
- $('input[name=export_data]').val(json_sample_data);
- console.log("export_data is", $('input[name=export_data]').val());
- format = $('#export_format').val();
- if (format === "excel") {
- $('#trait_data_form').attr('action', '/export_trait_excel');
- } else {
- $('#trait_data_form').attr('action', '/export_trait_csv');
- }
- console.log("action is:", $('#trait_data_form').attr('action'));
- return $('#trait_data_form').submit();
- };
- $('#export').click(export_sample_table_data);
- console.log("before registering block_outliers");
- $('#block_outliers').click(block_outliers);
- console.log("after registering block_outliers");
- _.mixin(_.str.exports());
- $('#edit_sample_lists').change(edit_data_change);
- console.log("loaded");
- make_table();
- edit_data_change();
- return console.log("end");
-});
+ }
+ return _results;
+ };
+ $('#block_by_index').click(block_by_index);
+ hide_no_value = function() {
+ return $('.value_se').each((function(_this) {
+ return function(_index, element) {
+ if ($(element).find('.trait_value_input').val() === 'x') {
+ return $(element).hide();
+ }
+ };
+ })(this));
+ };
+ $('#hide_no_value').click(hide_no_value);
+ block_outliers = function() {
+ return $('.outlier').each((function(_this) {
+ return function(_index, element) {
+ return $(element).find('.trait_value_input').val('x');
+ };
+ })(this));
+ };
+ $('#block_outliers').click(block_outliers);
+ reset_samples_table = function() {
+ return $('.trait_value_input').each((function(_this) {
+ return function(_index, element) {
+ console.log("value is:", $(element).val());
+ $(element).val($(element).data('value'));
+ console.log("data-value is:", $(element).data('value'));
+ return $(element).parents('.value_se').show();
+ };
+ })(this));
+ };
+ $('#reset').click(reset_samples_table);
+ get_sample_table_data = function(table_name) {
+ var samples;
+ samples = [];
+ $('#' + table_name).find('.value_se').each((function(_this) {
+ return function(_index, element) {
+ var attribute_info, key, row_data, _ref;
+ row_data = {};
+ row_data.name = $.trim($(element).find('.column_name-Sample').text());
+ row_data.value = $(element).find('.edit_sample_value').val();
+ if ($(element).find('.edit_sample_se').length !== -1) {
+ row_data.se = $(element).find('.edit_sample_se').val();
+ }
+ _ref = js_data.attribute_names;
+ for (key in _ref) {
+ if (!__hasProp.call(_ref, key)) continue;
+ attribute_info = _ref[key];
+ row_data[attribute_info.name] = $.trim($(element).find('.column_name-' + attribute_info.name.replace(" ", "_")).text());
+ }
+ console.log("row_data is:", row_data);
+ return samples.push(row_data);
+ };
+ })(this));
+ return samples;
+ };
+ export_sample_table_data = function() {
+ var format, json_sample_data, sample_data;
+ sample_data = {};
+ sample_data.primary_samples = get_sample_table_data('samples_primary');
+ sample_data.other_samples = get_sample_table_data('samples_other');
+ console.log("sample_data is:", sample_data);
+ json_sample_data = JSON.stringify(sample_data);
+ console.log("json_sample_data is:", json_sample_data);
+ $('input[name=export_data]').val(json_sample_data);
+ console.log("export_data is", $('input[name=export_data]').val());
+ format = $('#export_format').val();
+ if (format === "excel") {
+ $('#trait_data_form').attr('action', '/export_trait_excel');
+ } else {
+ $('#trait_data_form').attr('action', '/export_trait_csv');
+ }
+ console.log("action is:", $('#trait_data_form').attr('action'));
+ return $('#trait_data_form').submit();
+ };
+ $('#export').click(export_sample_table_data);
+ console.log("before registering block_outliers");
+ $('#block_outliers').click(block_outliers);
+ console.log("after registering block_outliers");
+ _.mixin(_.str.exports());
+ root.histogram_group = 'samples_primary';
+ root.histogram = new Histogram(sample_lists[0]);
+ $('.histogram_samples_group').val(root.histogram_group);
+ $('.histogram_samples_group').change(function() {
+ root.histogram_group = $(this).val();
+ return redraw_histogram();
+ });
+ root.bar_chart_group = 'samples_primary';
+ root.bar_chart = new Bar_Chart(sample_lists);
+ $('.bar_chart_samples_group').val(root.bar_chart_group);
+ $('.bar_chart_samples_group').change(function() {
+ root.bar_chart_group = $(this).val();
+ return redraw_bar_chart();
+ });
+ root.prob_plot_group = 'samples_primary';
+ $('.prob_plot_samples_group').val(root.prob_plot_group);
+ $('.prob_plot_samples_group').change(function() {
+ root.prob_plot_group = $(this).val();
+ return redraw_prob_plot();
+ });
+ make_table();
+ edit_data_change();
+ $('#edit_sample_lists').change(edit_data_change);
+ $('#block_by_index').click(edit_data_change);
+ $('#exclude_group').click(edit_data_change);
+ $('#block_outliers').click(edit_data_change);
+ $('#reset').click(edit_data_change);
+ return console.log("end");
+ });
+
+}).call(this);
diff --git a/wqflask/wqflask/static/new/javascript/show_trait_mapping_tools.coffee b/wqflask/wqflask/static/new/javascript/show_trait_mapping_tools.coffee
index a87d3537..d14fb98c 100755
--- a/wqflask/wqflask/static/new/javascript/show_trait_mapping_tools.coffee
+++ b/wqflask/wqflask/static/new/javascript/show_trait_mapping_tools.coffee
@@ -63,10 +63,12 @@ do_ajax_post = (url, form_data) ->
console.log(xhr)
clearInterval(this.my_timer)
$('#progress_bar_container').modal('hide')
+ $('#static_progress_bar_container').modal('hide')
$("body").html("We got an error.")
success: (data) =>
clearInterval(this.my_timer)
$('#progress_bar_container').modal('hide')
+ $('#static_progress_bar_container').modal('hide')
open_mapping_results(data)
#$("body").html(data)
)
@@ -76,36 +78,49 @@ do_ajax_post = (url, form_data) ->
return false
open_mapping_results = (data) ->
+ #results_window = window.open("/mapping_results_container")
+ #results_window.onload = ->
+ # results_window.document.getElementById("mapping_results_container").innerHTML = data
+
$.colorbox(
- html: data
- href: "#mapping_results_holder"
- height: "80%"
- width: "80%"
- )
+ html: data
+ href: "#mapping_results_holder"
+ height: "90%"
+ width: "90%"
+ onComplete: =>
+ root.create_lod_chart()
+
+ #Set filename
+ filename = "lod_chart_" + js_data.this_trait
+
+ getSvgXml = ->
+ svg = $("#topchart").find("svg")[0]
+ (new XMLSerializer).serializeToString(svg)
+
+ $("#exportform > #export").click =>
+ svg_xml = getSvgXml()
+ form = $("#exportform")
+ form.find("#data").val(svg_xml)
+ form.find("#filename").val(filename)
+ form.submit()
+
+ $("#exportpdfform > #export_pdf").click =>
+ svg_xml = getSvgXml()
+ form = $("#exportpdfform")
+ form.find("#data").val(svg_xml)
+ form.find("#filename").val(filename)
+ form.submit()
+ )
+
+outlier_text = "One or more outliers exist in this data set. Please review values before mapping. \
+ Including outliers when mapping may lead to misleading results. \
+ We recommend <A HREF=\"http://en.wikipedia.org/wiki/Winsorising\">winsorising</A> the outliers \
+ or simply deleting them."
showalert = (message,alerttype) ->
$('#alert_placeholder').append('<div id="alertdiv" class="alert ' + alerttype + '"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>')
-$("#interval_mapping_compute").click(() =>
- showalert("One or more outliers exist in this data set. Please review values before mapping. \
- Including outliers when mapping may lead to misleading results. \
- We recommend <A HREF=\"http://en.wikipedia.org/wiki/Winsorising\">winsorising</A> the outliers \
- or simply deleting them.", "alert-success")
- console.log("In interval mapping")
- $("#progress_bar_container").modal()
- url = "/interval_mapping"
-
- $('input[name=method]').val("reaper")
- $('input[name=manhattan_plot]').val($('input[name=manhattan_plot_reaper]:checked').val())
- $('input[name=mapping_display_all]').val($('input[name=display_all_reaper]'))
- $('input[name=suggestive]').val($('input[name=suggestive_reaper]'))
- form_data = $('#trait_data_form').serialize()
- console.log("form_data is:", form_data)
-
- do_ajax_post(url, form_data)
-)
-
$('#suggestive').hide()
$('input[name=display_all]').change(() =>
@@ -116,8 +131,13 @@ $('input[name=display_all]').change(() =>
$('#suggestive').hide()
)
-$("#pylmm_compute").click(() =>
- $("#progress_bar_container").modal({show:true})
+$("#pylmm_mapping_compute").on("mouseover", =>
+ if ( $(".outlier").length and $(".outlier-alert").length < 1 )
+ showalert(outlier_text, "alert-success outlier-alert")
+)
+
+$("#pylmm_compute").on("click", =>
+ $("#progress_bar_container").modal()
url = "/marker_regression"
$('input[name=method]').val("pylmm")
$('input[name=num_perm]').val($('input[name=num_perm_pylmm]').val())
@@ -130,10 +150,9 @@ $("#pylmm_compute").click(() =>
# block_outliers()
do_ajax_post(url, form_data)
)
+
-
-
-$("#rqtl_geno_compute").click(() =>
+$("#rqtl_geno_compute").on("click", =>
$("#progress_bar_container").modal()
url = "/marker_regression"
$('input[name=method]').val("rqtl_geno")
@@ -150,12 +169,12 @@ $("#rqtl_geno_compute").click(() =>
)
-$("#plink_compute").click(() =>
+$("#plink_compute").on("click", =>
$("#static_progress_bar_container").modal()
url = "/marker_regression"
$('input[name=method]').val("plink")
- $('input[name=mapping_display_all]').val($('input[name=display_all_plink]').val())
- $('input[name=suggestive]').val($('input[name=suggestive_plink]').val())
+ #$('input[name=mapping_display_all]').val($('input[name=display_all_plink]').val())
+ #$('input[name=suggestive]').val($('input[name=suggestive_plink]').val())
$('input[name=maf]').val($('input[name=maf_plink]').val())
form_data = $('#trait_data_form').serialize()
console.log("form_data is:", form_data)
@@ -163,12 +182,13 @@ $("#plink_compute").click(() =>
do_ajax_post(url, form_data)
)
-$("#gemma_compute").click(() =>
+$("#gemma_compute").on("click", =>
+ console.log("RUNNING GEMMA")
$("#static_progress_bar_container").modal()
url = "/marker_regression"
$('input[name=method]').val("gemma")
- $('input[name=mapping_display_all]').val($('input[name=display_all_gemma]').val())
- $('input[name=suggestive]').val($('input[name=suggestive_gemma]').val())
+ #$('input[name=mapping_display_all]').val($('input[name=display_all_gemma]').val())
+ #$('input[name=suggestive]').val($('input[name=suggestive_gemma]').val())
$('input[name=maf]').val($('input[name=maf_gemma]').val())
form_data = $('#trait_data_form').serialize()
console.log("form_data is:", form_data)
@@ -176,6 +196,26 @@ $("#gemma_compute").click(() =>
do_ajax_post(url, form_data)
)
+$("#interval_mapping_compute").on("mouseover", =>
+ if ( $(".outlier").length and $(".outlier-alert").length < 1 )
+ showalert(outlier_text, "alert-success outlier-alert")
+)
+
+$("#interval_mapping_compute").on("click", =>
+ console.log("In interval mapping")
+ $("#progress_bar_container").modal()
+ url = "/interval_mapping"
+
+ $('input[name=method]').val("reaper")
+ $('input[name=manhattan_plot]').val($('input[name=manhattan_plot_reaper]:checked').val())
+ $('input[name=mapping_display_all]').val($('input[name=display_all_reaper]'))
+ $('input[name=suggestive]').val($('input[name=suggestive_reaper]'))
+ form_data = $('#trait_data_form').serialize()
+ console.log("form_data is:", form_data)
+
+ do_ajax_post(url, form_data)
+)
+
#$(".submit_special").click(submit_special)
composite_mapping_fields = ->
diff --git a/wqflask/wqflask/static/new/javascript/show_trait_mapping_tools.js b/wqflask/wqflask/static/new/javascript/show_trait_mapping_tools.js
index c8988cdc..2f26d6cb 100755
--- a/wqflask/wqflask/static/new/javascript/show_trait_mapping_tools.js
+++ b/wqflask/wqflask/static/new/javascript/show_trait_mapping_tools.js
@@ -1,224 +1,270 @@
// Generated by CoffeeScript 1.8.0
-var block_outliers, composite_mapping_fields, do_ajax_post, get_progress, mapping_method_fields, open_mapping_results, showalert, submit_special, toggle_enable_disable, update_time_remaining;
-
-submit_special = function() {
- var url;
- console.log("In submit_special");
- console.log("this is:", this);
- console.log("$(this) is:", $(this));
- url = $(this).data("url");
- console.log("url is:", url);
- $("#trait_data_form").attr("action", url);
- return $("#trait_data_form").submit();
-};
-
-update_time_remaining = function(percent_complete) {
- var minutes_remaining, now, period, total_seconds_remaining;
- now = new Date();
- period = now.getTime() - root.start_time;
- console.log("period is:", period);
- if (period > 8000) {
- total_seconds_remaining = (period / percent_complete * (100 - percent_complete)) / 1000;
- minutes_remaining = Math.round(total_seconds_remaining / 60);
- if (minutes_remaining < 3) {
- return $('#time_remaining').text(Math.round(total_seconds_remaining) + " seconds remaining");
- } else {
- return $('#time_remaining').text(minutes_remaining + " minutes remaining");
+(function() {
+ var block_outliers, composite_mapping_fields, do_ajax_post, get_progress, mapping_method_fields, open_mapping_results, outlier_text, showalert, submit_special, toggle_enable_disable, update_time_remaining;
+
+ submit_special = function() {
+ var url;
+ console.log("In submit_special");
+ console.log("this is:", this);
+ console.log("$(this) is:", $(this));
+ url = $(this).data("url");
+ console.log("url is:", url);
+ $("#trait_data_form").attr("action", url);
+ return $("#trait_data_form").submit();
+ };
+
+ update_time_remaining = function(percent_complete) {
+ var minutes_remaining, now, period, total_seconds_remaining;
+ now = new Date();
+ period = now.getTime() - root.start_time;
+ console.log("period is:", period);
+ if (period > 8000) {
+ total_seconds_remaining = (period / percent_complete * (100 - percent_complete)) / 1000;
+ minutes_remaining = Math.round(total_seconds_remaining / 60);
+ if (minutes_remaining < 3) {
+ return $('#time_remaining').text(Math.round(total_seconds_remaining) + " seconds remaining");
+ } else {
+ return $('#time_remaining').text(minutes_remaining + " minutes remaining");
+ }
}
- }
-};
-
-get_progress = function() {
- var params, params_str, temp_uuid, url;
- console.log("temp_uuid:", $("#temp_uuid").val());
- temp_uuid = $("#temp_uuid").val();
- params = {
- key: temp_uuid
};
- params_str = $.param(params);
- url = "/get_temp_data?" + params_str;
- console.log("url:", url);
- $.ajax({
- type: "GET",
- url: url,
- success: (function(_this) {
- return function(progress_data) {
- var percent_complete;
- percent_complete = progress_data['percent_complete'];
- console.log("in get_progress data:", progress_data);
- $('#marker_regression_progress').css("width", percent_complete + "%");
- if (root.start_time) {
- if (!isNaN(percent_complete)) {
- return update_time_remaining(percent_complete);
- }
- } else {
- return root.start_time = new Date().getTime();
- }
- };
- })(this)
- });
- return false;
-};
-block_outliers = function() {
- return $('.outlier').each((function(_this) {
- return function(_index, element) {
- return $(element).find('.trait_value_input').val('x');
+ get_progress = function() {
+ var params, params_str, temp_uuid, url;
+ console.log("temp_uuid:", $("#temp_uuid").val());
+ temp_uuid = $("#temp_uuid").val();
+ params = {
+ key: temp_uuid
};
- })(this));
-};
-
-do_ajax_post = function(url, form_data) {
- $.ajax({
- type: "POST",
- url: url,
- data: form_data,
- error: (function(_this) {
- return function(xhr, ajaxOptions, thrownError) {
- alert("Sorry, an error occurred");
- console.log(xhr);
- clearInterval(_this.my_timer);
- $('#progress_bar_container').modal('hide');
- return $("body").html("We got an error.");
- };
- })(this),
- success: (function(_this) {
- return function(data) {
- clearInterval(_this.my_timer);
- $('#progress_bar_container').modal('hide');
- return open_mapping_results(data);
- };
- })(this)
- });
- console.log("settingInterval");
- this.my_timer = setInterval(get_progress, 1000);
- return false;
-};
-
-open_mapping_results = function(data) {
- return $.colorbox({
- html: data,
- href: "#mapping_results_holder",
- height: "80%",
- width: "80%"
- });
-};
-
-showalert = function(message, alerttype) {
- return $('#alert_placeholder').append('<div id="alertdiv" class="alert ' + alerttype + '"><a class="close" data-dismiss="alert">�</a><span>' + message + '</span></div>');
-};
-
-$("#interval_mapping_compute").click((function(_this) {
- return function() {
- var form_data, url;
- showalert("One or more outliers exist in this data set. Please review values before mapping. Including outliers when mapping may lead to misleading results. We recommend <A HREF=\"http://en.wikipedia.org/wiki/Winsorising\">winsorising</A> the outliers or simply deleting them.", "alert-success");
- console.log("In interval mapping");
- $("#progress_bar_container").modal();
- url = "/interval_mapping";
- $('input[name=method]').val("reaper");
- $('input[name=manhattan_plot]').val($('input[name=manhattan_plot_reaper]:checked').val());
- $('input[name=mapping_display_all]').val($('input[name=display_all_reaper]'));
- $('input[name=suggestive]').val($('input[name=suggestive_reaper]'));
- form_data = $('#trait_data_form').serialize();
- console.log("form_data is:", form_data);
- return do_ajax_post(url, form_data);
+ params_str = $.param(params);
+ url = "/get_temp_data?" + params_str;
+ console.log("url:", url);
+ $.ajax({
+ type: "GET",
+ url: url,
+ success: (function(_this) {
+ return function(progress_data) {
+ var percent_complete;
+ percent_complete = progress_data['percent_complete'];
+ console.log("in get_progress data:", progress_data);
+ $('#marker_regression_progress').css("width", percent_complete + "%");
+ if (root.start_time) {
+ if (!isNaN(percent_complete)) {
+ return update_time_remaining(percent_complete);
+ }
+ } else {
+ return root.start_time = new Date().getTime();
+ }
+ };
+ })(this)
+ });
+ return false;
};
-})(this));
-$('#suggestive').hide();
-
-$('input[name=display_all]').change((function(_this) {
- return function() {
- console.log("check");
- if ($('input[name=display_all]:checked').val() === "False") {
- return $('#suggestive').show();
- } else {
- return $('#suggestive').hide();
- }
+ block_outliers = function() {
+ return $('.outlier').each((function(_this) {
+ return function(_index, element) {
+ return $(element).find('.trait_value_input').val('x');
+ };
+ })(this));
};
-})(this));
-$("#pylmm_compute").click((function(_this) {
- return function() {
- var form_data, url;
- $("#progress_bar_container").modal({
- show: true
+ do_ajax_post = function(url, form_data) {
+ $.ajax({
+ type: "POST",
+ url: url,
+ data: form_data,
+ error: (function(_this) {
+ return function(xhr, ajaxOptions, thrownError) {
+ alert("Sorry, an error occurred");
+ console.log(xhr);
+ clearInterval(_this.my_timer);
+ $('#progress_bar_container').modal('hide');
+ $('#static_progress_bar_container').modal('hide');
+ return $("body").html("We got an error.");
+ };
+ })(this),
+ success: (function(_this) {
+ return function(data) {
+ clearInterval(_this.my_timer);
+ $('#progress_bar_container').modal('hide');
+ $('#static_progress_bar_container').modal('hide');
+ return open_mapping_results(data);
+ };
+ })(this)
});
- url = "/marker_regression";
- $('input[name=method]').val("pylmm");
- $('input[name=num_perm]').val($('input[name=num_perm_pylmm]').val());
- $('input[name=manhattan_plot]').val($('input[name=manhattan_plot_pylmm]:checked').val());
- form_data = $('#trait_data_form').serialize();
- console.log("form_data is:", form_data);
- return do_ajax_post(url, form_data);
+ console.log("settingInterval");
+ this.my_timer = setInterval(get_progress, 1000);
+ return false;
};
-})(this));
-
-$("#rqtl_geno_compute").click((function(_this) {
- return function() {
- var form_data, url;
- $("#progress_bar_container").modal();
- url = "/marker_regression";
- $('input[name=method]').val("rqtl_geno");
- $('input[name=num_perm]').val($('input[name=num_perm_rqtl_geno]').val());
- $('input[name=manhattan_plot]').val($('input[name=manhattan_plot_rqtl]:checked').val());
- $('input[name=control_marker]').val($('input[name=control_rqtl_geno]').val());
- form_data = $('#trait_data_form').serialize();
- console.log("form_data is:", form_data);
- return do_ajax_post(url, form_data);
+
+ open_mapping_results = function(data) {
+ return $.colorbox({
+ html: data,
+ href: "#mapping_results_holder",
+ height: "90%",
+ width: "90%",
+ onComplete: (function(_this) {
+ return function() {
+ var filename, getSvgXml;
+ root.create_lod_chart();
+ filename = "lod_chart_" + js_data.this_trait;
+ getSvgXml = function() {
+ var svg;
+ svg = $("#topchart").find("svg")[0];
+ return (new XMLSerializer).serializeToString(svg);
+ };
+ $("#exportform > #export").click(function() {
+ var form, svg_xml;
+ svg_xml = getSvgXml();
+ form = $("#exportform");
+ form.find("#data").val(svg_xml);
+ form.find("#filename").val(filename);
+ return form.submit();
+ });
+ return $("#exportpdfform > #export_pdf").click(function() {
+ var form, svg_xml;
+ svg_xml = getSvgXml();
+ form = $("#exportpdfform");
+ form.find("#data").val(svg_xml);
+ form.find("#filename").val(filename);
+ return form.submit();
+ });
+ };
+ })(this)
+ });
};
-})(this));
-
-$("#plink_compute").click((function(_this) {
- return function() {
- var form_data, url;
- $("#static_progress_bar_container").modal();
- url = "/marker_regression";
- $('input[name=method]').val("plink");
- $('input[name=mapping_display_all]').val($('input[name=display_all_plink]').val());
- $('input[name=suggestive]').val($('input[name=suggestive_plink]').val());
- $('input[name=maf]').val($('input[name=maf_plink]').val());
- form_data = $('#trait_data_form').serialize();
- console.log("form_data is:", form_data);
- return do_ajax_post(url, form_data);
+
+ outlier_text = "One or more outliers exist in this data set. Please review values before mapping. Including outliers when mapping may lead to misleading results. We recommend <A HREF=\"http://en.wikipedia.org/wiki/Winsorising\">winsorising</A> the outliers or simply deleting them.";
+
+ showalert = function(message, alerttype) {
+ return $('#alert_placeholder').append('<div id="alertdiv" class="alert ' + alerttype + '"><a class="close" data-dismiss="alert">�</a><span>' + message + '</span></div>');
};
-})(this));
-
-$("#gemma_compute").click((function(_this) {
- return function() {
- var form_data, url;
- $("#static_progress_bar_container").modal();
- url = "/marker_regression";
- $('input[name=method]').val("gemma");
- $('input[name=mapping_display_all]').val($('input[name=display_all_gemma]').val());
- $('input[name=suggestive]').val($('input[name=suggestive_gemma]').val());
- $('input[name=maf]').val($('input[name=maf_gemma]').val());
- form_data = $('#trait_data_form').serialize();
- console.log("form_data is:", form_data);
- return do_ajax_post(url, form_data);
+
+ $('#suggestive').hide();
+
+ $('input[name=display_all]').change((function(_this) {
+ return function() {
+ console.log("check");
+ if ($('input[name=display_all]:checked').val() === "False") {
+ return $('#suggestive').show();
+ } else {
+ return $('#suggestive').hide();
+ }
+ };
+ })(this));
+
+ $("#pylmm_mapping_compute").on("mouseover", (function(_this) {
+ return function() {
+ if ($(".outlier").length && $(".outlier-alert").length < 1) {
+ return showalert(outlier_text, "alert-success outlier-alert");
+ }
+ };
+ })(this));
+
+ $("#pylmm_compute").on("click", (function(_this) {
+ return function() {
+ var form_data, url;
+ $("#progress_bar_container").modal();
+ url = "/marker_regression";
+ $('input[name=method]').val("pylmm");
+ $('input[name=num_perm]').val($('input[name=num_perm_pylmm]').val());
+ $('input[name=manhattan_plot]').val($('input[name=manhattan_plot_pylmm]:checked').val());
+ form_data = $('#trait_data_form').serialize();
+ console.log("form_data is:", form_data);
+ return do_ajax_post(url, form_data);
+ };
+ })(this));
+
+ $("#rqtl_geno_compute").on("click", (function(_this) {
+ return function() {
+ var form_data, url;
+ $("#progress_bar_container").modal();
+ url = "/marker_regression";
+ $('input[name=method]').val("rqtl_geno");
+ $('input[name=num_perm]').val($('input[name=num_perm_rqtl_geno]').val());
+ $('input[name=manhattan_plot]').val($('input[name=manhattan_plot_rqtl]:checked').val());
+ $('input[name=control_marker]').val($('input[name=control_rqtl_geno]').val());
+ $('input[name=do_control]').val($('input[name=do_control_rqtl]:checked').val());
+ form_data = $('#trait_data_form').serialize();
+ console.log("form_data is:", form_data);
+ return do_ajax_post(url, form_data);
+ };
+ })(this));
+
+ $("#plink_compute").on("click", (function(_this) {
+ return function() {
+ var form_data, url;
+ $("#static_progress_bar_container").modal();
+ url = "/marker_regression";
+ $('input[name=method]').val("plink");
+ $('input[name=maf]').val($('input[name=maf_plink]').val());
+ form_data = $('#trait_data_form').serialize();
+ console.log("form_data is:", form_data);
+ return do_ajax_post(url, form_data);
+ };
+ })(this));
+
+ $("#gemma_compute").on("click", (function(_this) {
+ return function() {
+ var form_data, url;
+ console.log("RUNNING GEMMA");
+ $("#static_progress_bar_container").modal();
+ url = "/marker_regression";
+ $('input[name=method]').val("gemma");
+ $('input[name=maf]').val($('input[name=maf_gemma]').val());
+ form_data = $('#trait_data_form').serialize();
+ console.log("form_data is:", form_data);
+ return do_ajax_post(url, form_data);
+ };
+ })(this));
+
+ $("#interval_mapping_compute").on("mouseover", (function(_this) {
+ return function() {
+ if ($(".outlier").length && $(".outlier-alert").length < 1) {
+ return showalert(outlier_text, "alert-success outlier-alert");
+ }
+ };
+ })(this));
+
+ $("#interval_mapping_compute").on("click", (function(_this) {
+ return function() {
+ var form_data, url;
+ console.log("In interval mapping");
+ $("#progress_bar_container").modal();
+ url = "/interval_mapping";
+ $('input[name=method]').val("reaper");
+ $('input[name=manhattan_plot]').val($('input[name=manhattan_plot_reaper]:checked').val());
+ $('input[name=mapping_display_all]').val($('input[name=display_all_reaper]'));
+ $('input[name=suggestive]').val($('input[name=suggestive_reaper]'));
+ form_data = $('#trait_data_form').serialize();
+ console.log("form_data is:", form_data);
+ return do_ajax_post(url, form_data);
+ };
+ })(this));
+
+ composite_mapping_fields = function() {
+ return $(".composite_fields").toggle();
};
-})(this));
-composite_mapping_fields = function() {
- return $(".composite_fields").toggle();
-};
+ mapping_method_fields = function() {
+ return $(".mapping_method_fields").toggle();
+ };
-mapping_method_fields = function() {
- return $(".mapping_method_fields").toggle();
-};
+ $("#use_composite_choice").change(composite_mapping_fields);
-$("#use_composite_choice").change(composite_mapping_fields);
+ $("#mapping_method_choice").change(mapping_method_fields);
-$("#mapping_method_choice").change(mapping_method_fields);
+ toggle_enable_disable = function(elem) {
+ return $(elem).prop("disabled", !$(elem).prop("disabled"));
+ };
-toggle_enable_disable = function(elem) {
- return $(elem).prop("disabled", !$(elem).prop("disabled"));
-};
+ $("#choose_closet_control").change(function() {
+ return toggle_enable_disable("#control_locus");
+ });
-$("#choose_closet_control").change(function() {
- return toggle_enable_disable("#control_locus");
-});
+ $("#display_all_lrs").change(function() {
+ return toggle_enable_disable("#suggestive_lrs");
+ });
-$("#display_all_lrs").change(function() {
- return toggle_enable_disable("#suggestive_lrs");
-});
+}).call(this);
diff --git a/wqflask/wqflask/static/new/js_external/chroma.js b/wqflask/wqflask/static/new/js_external/chroma.js
new file mode 100644
index 00000000..0976056b
--- /dev/null
+++ b/wqflask/wqflask/static/new/js_external/chroma.js
@@ -0,0 +1,2464 @@
+/**
+ * @license
+ *
+ * chroma.js - JavaScript library for color conversions
+ *
+ * Copyright (c) 2011-2015, Gregor Aisch
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * 3. The name Gregor Aisch may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+(function() {
+ var Color, DEG2RAD, LAB_CONSTANTS, PI, PITHIRD, RAD2DEG, TWOPI, _guess_formats, _guess_formats_sorted, _input, _interpolators, abs, atan2, bezier, blend, blend_f, brewer, burn, chroma, clip_rgb, cmyk2rgb, colors, cos, css2rgb, darken, dodge, each, floor, hex2rgb, hsi2rgb, hsl2css, hsl2rgb, hsv2rgb, interpolate, interpolate_hsx, interpolate_lab, interpolate_num, interpolate_rgb, lab2lch, lab2rgb, lab_xyz, lch2lab, lch2rgb, lighten, limit, log, luminance_x, m, max, multiply, normal, num2rgb, overlay, pow, rgb2cmyk, rgb2css, rgb2hex, rgb2hsi, rgb2hsl, rgb2hsv, rgb2lab, rgb2lch, rgb2luminance, rgb2num, rgb2temperature, rgb2xyz, rgb_xyz, rnd, root, round, screen, sin, sqrt, temperature2rgb, type, unpack, w3cx11, xyz_lab, xyz_rgb,
+ slice = [].slice;
+
+ type = (function() {
+
+ /*
+ for browser-safe type checking+
+ ported from jQuery's $.type
+ */
+ var classToType, len, name, o, ref;
+ classToType = {};
+ ref = "Boolean Number String Function Array Date RegExp Undefined Null".split(" ");
+ for (o = 0, len = ref.length; o < len; o++) {
+ name = ref[o];
+ classToType["[object " + name + "]"] = name.toLowerCase();
+ }
+ return function(obj) {
+ var strType;
+ strType = Object.prototype.toString.call(obj);
+ return classToType[strType] || "object";
+ };
+ })();
+
+ limit = function(x, min, max) {
+ if (min == null) {
+ min = 0;
+ }
+ if (max == null) {
+ max = 1;
+ }
+ if (x < min) {
+ x = min;
+ }
+ if (x > max) {
+ x = max;
+ }
+ return x;
+ };
+
+ unpack = function(args) {
+ if (args.length >= 3) {
+ return [].slice.call(args);
+ } else {
+ return args[0];
+ }
+ };
+
+ clip_rgb = function(rgb) {
+ var i;
+ for (i in rgb) {
+ if (i < 3) {
+ if (rgb[i] < 0) {
+ rgb[i] = 0;
+ }
+ if (rgb[i] > 255) {
+ rgb[i] = 255;
+ }
+ } else if (i === 3) {
+ if (rgb[i] < 0) {
+ rgb[i] = 0;
+ }
+ if (rgb[i] > 1) {
+ rgb[i] = 1;
+ }
+ }
+ }
+ return rgb;
+ };
+
+ PI = Math.PI, round = Math.round, cos = Math.cos, floor = Math.floor, pow = Math.pow, log = Math.log, sin = Math.sin, sqrt = Math.sqrt, atan2 = Math.atan2, max = Math.max, abs = Math.abs;
+
+ TWOPI = PI * 2;
+
+ PITHIRD = PI / 3;
+
+ DEG2RAD = PI / 180;
+
+ RAD2DEG = 180 / PI;
+
+ chroma = function() {
+ if (arguments[0] instanceof Color) {
+ return arguments[0];
+ }
+ return (function(func, args, ctor) {
+ ctor.prototype = func.prototype;
+ var child = new ctor, result = func.apply(child, args);
+ return Object(result) === result ? result : child;
+ })(Color, arguments, function(){});
+ };
+
+ _interpolators = [];
+
+ if ((typeof module !== "undefined" && module !== null) && (module.exports != null)) {
+ module.exports = chroma;
+ }
+
+ if (typeof define === 'function' && define.amd) {
+ define([], function() {
+ return chroma;
+ });
+ } else {
+ root = typeof exports !== "undefined" && exports !== null ? exports : this;
+ root.chroma = chroma;
+ }
+
+ chroma.version = '1.1.1';
+
+
+ /**
+ chroma.js
+
+ Copyright (c) 2011-2013, Gregor Aisch
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * The name Gregor Aisch may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ @source: https://github.com/gka/chroma.js
+ */
+
+ _input = {};
+
+ _guess_formats = [];
+
+ _guess_formats_sorted = false;
+
+ Color = (function() {
+ function Color() {
+ var arg, args, chk, len, len1, me, mode, o, w;
+ me = this;
+ args = [];
+ for (o = 0, len = arguments.length; o < len; o++) {
+ arg = arguments[o];
+ if (arg != null) {
+ args.push(arg);
+ }
+ }
+ mode = args[args.length - 1];
+ if (_input[mode] != null) {
+ me._rgb = clip_rgb(_input[mode](unpack(args.slice(0, -1))));
+ } else {
+ if (!_guess_formats_sorted) {
+ _guess_formats = _guess_formats.sort(function(a, b) {
+ return b.p - a.p;
+ });
+ _guess_formats_sorted = true;
+ }
+ for (w = 0, len1 = _guess_formats.length; w < len1; w++) {
+ chk = _guess_formats[w];
+ mode = chk.test.apply(chk, args);
+ if (mode) {
+ break;
+ }
+ }
+ if (mode) {
+ me._rgb = clip_rgb(_input[mode].apply(_input, args));
+ }
+ }
+ if (me._rgb == null) {
+ console.warn('unknown format: ' + args);
+ }
+ if (me._rgb == null) {
+ me._rgb = [0, 0, 0];
+ }
+ if (me._rgb.length === 3) {
+ me._rgb.push(1);
+ }
+ }
+
+ Color.prototype.alpha = function(alpha) {
+ if (arguments.length) {
+ this._rgb[3] = alpha;
+ return this;
+ }
+ return this._rgb[3];
+ };
+
+ Color.prototype.toString = function() {
+ return this.name();
+ };
+
+ return Color;
+
+ })();
+
+ chroma._input = _input;
+
+
+ /**
+ ColorBrewer colors for chroma.js
+
+ Copyright (c) 2002 Cynthia Brewer, Mark Harrower, and The
+ Pennsylvania State University.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software distributed
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations under the License.
+
+ @preserve
+ */
+
+ chroma.brewer = brewer = {
+ OrRd: ['#fff7ec', '#fee8c8', '#fdd49e', '#fdbb84', '#fc8d59', '#ef6548', '#d7301f', '#b30000', '#7f0000'],
+ PuBu: ['#fff7fb', '#ece7f2', '#d0d1e6', '#a6bddb', '#74a9cf', '#3690c0', '#0570b0', '#045a8d', '#023858'],
+ BuPu: ['#f7fcfd', '#e0ecf4', '#bfd3e6', '#9ebcda', '#8c96c6', '#8c6bb1', '#88419d', '#810f7c', '#4d004b'],
+ Oranges: ['#fff5eb', '#fee6ce', '#fdd0a2', '#fdae6b', '#fd8d3c', '#f16913', '#d94801', '#a63603', '#7f2704'],
+ BuGn: ['#f7fcfd', '#e5f5f9', '#ccece6', '#99d8c9', '#66c2a4', '#41ae76', '#238b45', '#006d2c', '#00441b'],
+ YlOrBr: ['#ffffe5', '#fff7bc', '#fee391', '#fec44f', '#fe9929', '#ec7014', '#cc4c02', '#993404', '#662506'],
+ YlGn: ['#ffffe5', '#f7fcb9', '#d9f0a3', '#addd8e', '#78c679', '#41ab5d', '#238443', '#006837', '#004529'],
+ Reds: ['#fff5f0', '#fee0d2', '#fcbba1', '#fc9272', '#fb6a4a', '#ef3b2c', '#cb181d', '#a50f15', '#67000d'],
+ RdPu: ['#fff7f3', '#fde0dd', '#fcc5c0', '#fa9fb5', '#f768a1', '#dd3497', '#ae017e', '#7a0177', '#49006a'],
+ Greens: ['#f7fcf5', '#e5f5e0', '#c7e9c0', '#a1d99b', '#74c476', '#41ab5d', '#238b45', '#006d2c', '#00441b'],
+ YlGnBu: ['#ffffd9', '#edf8b1', '#c7e9b4', '#7fcdbb', '#41b6c4', '#1d91c0', '#225ea8', '#253494', '#081d58'],
+ Purples: ['#fcfbfd', '#efedf5', '#dadaeb', '#bcbddc', '#9e9ac8', '#807dba', '#6a51a3', '#54278f', '#3f007d'],
+ GnBu: ['#f7fcf0', '#e0f3db', '#ccebc5', '#a8ddb5', '#7bccc4', '#4eb3d3', '#2b8cbe', '#0868ac', '#084081'],
+ Greys: ['#ffffff', '#f0f0f0', '#d9d9d9', '#bdbdbd', '#969696', '#737373', '#525252', '#252525', '#000000'],
+ YlOrRd: ['#ffffcc', '#ffeda0', '#fed976', '#feb24c', '#fd8d3c', '#fc4e2a', '#e31a1c', '#bd0026', '#800026'],
+ PuRd: ['#f7f4f9', '#e7e1ef', '#d4b9da', '#c994c7', '#df65b0', '#e7298a', '#ce1256', '#980043', '#67001f'],
+ Blues: ['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6', '#4292c6', '#2171b5', '#08519c', '#08306b'],
+ PuBuGn: ['#fff7fb', '#ece2f0', '#d0d1e6', '#a6bddb', '#67a9cf', '#3690c0', '#02818a', '#016c59', '#014636'],
+ Spectral: ['#9e0142', '#d53e4f', '#f46d43', '#fdae61', '#fee08b', '#ffffbf', '#e6f598', '#abdda4', '#66c2a5', '#3288bd', '#5e4fa2'],
+ RdYlGn: ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee08b', '#ffffbf', '#d9ef8b', '#a6d96a', '#66bd63', '#1a9850', '#006837'],
+ RdBu: ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#fddbc7', '#f7f7f7', '#d1e5f0', '#92c5de', '#4393c3', '#2166ac', '#053061'],
+ PiYG: ['#8e0152', '#c51b7d', '#de77ae', '#f1b6da', '#fde0ef', '#f7f7f7', '#e6f5d0', '#b8e186', '#7fbc41', '#4d9221', '#276419'],
+ PRGn: ['#40004b', '#762a83', '#9970ab', '#c2a5cf', '#e7d4e8', '#f7f7f7', '#d9f0d3', '#a6dba0', '#5aae61', '#1b7837', '#00441b'],
+ RdYlBu: ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee090', '#ffffbf', '#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695'],
+ BrBG: ['#543005', '#8c510a', '#bf812d', '#dfc27d', '#f6e8c3', '#f5f5f5', '#c7eae5', '#80cdc1', '#35978f', '#01665e', '#003c30'],
+ RdGy: ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#fddbc7', '#ffffff', '#e0e0e0', '#bababa', '#878787', '#4d4d4d', '#1a1a1a'],
+ PuOr: ['#7f3b08', '#b35806', '#e08214', '#fdb863', '#fee0b6', '#f7f7f7', '#d8daeb', '#b2abd2', '#8073ac', '#542788', '#2d004b'],
+ Set2: ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854', '#ffd92f', '#e5c494', '#b3b3b3'],
+ Accent: ['#7fc97f', '#beaed4', '#fdc086', '#ffff99', '#386cb0', '#f0027f', '#bf5b17', '#666666'],
+ Set1: ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33', '#a65628', '#f781bf', '#999999'],
+ Set3: ['#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd', '#ccebc5', '#ffed6f'],
+ Dark2: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02', '#a6761d', '#666666'],
+ Paired: ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99', '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#6a3d9a', '#ffff99', '#b15928'],
+ Pastel2: ['#b3e2cd', '#fdcdac', '#cbd5e8', '#f4cae4', '#e6f5c9', '#fff2ae', '#f1e2cc', '#cccccc'],
+ Pastel1: ['#fbb4ae', '#b3cde3', '#ccebc5', '#decbe4', '#fed9a6', '#ffffcc', '#e5d8bd', '#fddaec', '#f2f2f2']
+ };
+
+
+ /**
+ X11 color names
+
+ http://www.w3.org/TR/css3-color/#svg-color
+ */
+
+ w3cx11 = {
+ indigo: "#4b0082",
+ gold: "#ffd700",
+ hotpink: "#ff69b4",
+ firebrick: "#b22222",
+ indianred: "#cd5c5c",
+ yellow: "#ffff00",
+ mistyrose: "#ffe4e1",
+ darkolivegreen: "#556b2f",
+ olive: "#808000",
+ darkseagreen: "#8fbc8f",
+ pink: "#ffc0cb",
+ tomato: "#ff6347",
+ lightcoral: "#f08080",
+ orangered: "#ff4500",
+ navajowhite: "#ffdead",
+ lime: "#00ff00",
+ palegreen: "#98fb98",
+ darkslategrey: "#2f4f4f",
+ greenyellow: "#adff2f",
+ burlywood: "#deb887",
+ seashell: "#fff5ee",
+ mediumspringgreen: "#00fa9a",
+ fuchsia: "#ff00ff",
+ papayawhip: "#ffefd5",
+ blanchedalmond: "#ffebcd",
+ chartreuse: "#7fff00",
+ dimgray: "#696969",
+ black: "#000000",
+ peachpuff: "#ffdab9",
+ springgreen: "#00ff7f",
+ aquamarine: "#7fffd4",
+ white: "#ffffff",
+ orange: "#ffa500",
+ lightsalmon: "#ffa07a",
+ darkslategray: "#2f4f4f",
+ brown: "#a52a2a",
+ ivory: "#fffff0",
+ dodgerblue: "#1e90ff",
+ peru: "#cd853f",
+ lawngreen: "#7cfc00",
+ chocolate: "#d2691e",
+ crimson: "#dc143c",
+ forestgreen: "#228b22",
+ darkgrey: "#a9a9a9",
+ lightseagreen: "#20b2aa",
+ cyan: "#00ffff",
+ mintcream: "#f5fffa",
+ silver: "#c0c0c0",
+ antiquewhite: "#faebd7",
+ mediumorchid: "#ba55d3",
+ skyblue: "#87ceeb",
+ gray: "#808080",
+ darkturquoise: "#00ced1",
+ goldenrod: "#daa520",
+ darkgreen: "#006400",
+ floralwhite: "#fffaf0",
+ darkviolet: "#9400d3",
+ darkgray: "#a9a9a9",
+ moccasin: "#ffe4b5",
+ saddlebrown: "#8b4513",
+ grey: "#808080",
+ darkslateblue: "#483d8b",
+ lightskyblue: "#87cefa",
+ lightpink: "#ffb6c1",
+ mediumvioletred: "#c71585",
+ slategrey: "#708090",
+ red: "#ff0000",
+ deeppink: "#ff1493",
+ limegreen: "#32cd32",
+ darkmagenta: "#8b008b",
+ palegoldenrod: "#eee8aa",
+ plum: "#dda0dd",
+ turquoise: "#40e0d0",
+ lightgrey: "#d3d3d3",
+ lightgoldenrodyellow: "#fafad2",
+ darkgoldenrod: "#b8860b",
+ lavender: "#e6e6fa",
+ maroon: "#800000",
+ yellowgreen: "#9acd32",
+ sandybrown: "#f4a460",
+ thistle: "#d8bfd8",
+ violet: "#ee82ee",
+ navy: "#000080",
+ magenta: "#ff00ff",
+ dimgrey: "#696969",
+ tan: "#d2b48c",
+ rosybrown: "#bc8f8f",
+ olivedrab: "#6b8e23",
+ blue: "#0000ff",
+ lightblue: "#add8e6",
+ ghostwhite: "#f8f8ff",
+ honeydew: "#f0fff0",
+ cornflowerblue: "#6495ed",
+ slateblue: "#6a5acd",
+ linen: "#faf0e6",
+ darkblue: "#00008b",
+ powderblue: "#b0e0e6",
+ seagreen: "#2e8b57",
+ darkkhaki: "#bdb76b",
+ snow: "#fffafa",
+ sienna: "#a0522d",
+ mediumblue: "#0000cd",
+ royalblue: "#4169e1",
+ lightcyan: "#e0ffff",
+ green: "#008000",
+ mediumpurple: "#9370db",
+ midnightblue: "#191970",
+ cornsilk: "#fff8dc",
+ paleturquoise: "#afeeee",
+ bisque: "#ffe4c4",
+ slategray: "#708090",
+ darkcyan: "#008b8b",
+ khaki: "#f0e68c",
+ wheat: "#f5deb3",
+ teal: "#008080",
+ darkorchid: "#9932cc",
+ deepskyblue: "#00bfff",
+ salmon: "#fa8072",
+ darkred: "#8b0000",
+ steelblue: "#4682b4",
+ palevioletred: "#db7093",
+ lightslategray: "#778899",
+ aliceblue: "#f0f8ff",
+ lightslategrey: "#778899",
+ lightgreen: "#90ee90",
+ orchid: "#da70d6",
+ gainsboro: "#dcdcdc",
+ mediumseagreen: "#3cb371",
+ lightgray: "#d3d3d3",
+ mediumturquoise: "#48d1cc",
+ lemonchiffon: "#fffacd",
+ cadetblue: "#5f9ea0",
+ lightyellow: "#ffffe0",
+ lavenderblush: "#fff0f5",
+ coral: "#ff7f50",
+ purple: "#800080",
+ aqua: "#00ffff",
+ whitesmoke: "#f5f5f5",
+ mediumslateblue: "#7b68ee",
+ darkorange: "#ff8c00",
+ mediumaquamarine: "#66cdaa",
+ darksalmon: "#e9967a",
+ beige: "#f5f5dc",
+ blueviolet: "#8a2be2",
+ azure: "#f0ffff",
+ lightsteelblue: "#b0c4de",
+ oldlace: "#fdf5e6",
+ rebeccapurple: "#663399"
+ };
+
+ chroma.colors = colors = w3cx11;
+
+ lab2rgb = function() {
+ var a, args, b, g, l, r, x, y, z;
+ args = unpack(arguments);
+ l = args[0], a = args[1], b = args[2];
+ y = (l + 16) / 116;
+ x = isNaN(a) ? y : y + a / 500;
+ z = isNaN(b) ? y : y - b / 200;
+ y = LAB_CONSTANTS.Yn * lab_xyz(y);
+ x = LAB_CONSTANTS.Xn * lab_xyz(x);
+ z = LAB_CONSTANTS.Zn * lab_xyz(z);
+ r = xyz_rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z);
+ g = xyz_rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z);
+ b = xyz_rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z);
+ r = limit(r, 0, 255);
+ g = limit(g, 0, 255);
+ b = limit(b, 0, 255);
+ return [r, g, b, args.length > 3 ? args[3] : 1];
+ };
+
+ xyz_rgb = function(r) {
+ return round(255 * (r <= 0.00304 ? 12.92 * r : 1.055 * pow(r, 1 / 2.4) - 0.055));
+ };
+
+ lab_xyz = function(t) {
+ if (t > LAB_CONSTANTS.t1) {
+ return t * t * t;
+ } else {
+ return LAB_CONSTANTS.t2 * (t - LAB_CONSTANTS.t0);
+ }
+ };
+
+ LAB_CONSTANTS = {
+ Kn: 18,
+ Xn: 0.950470,
+ Yn: 1,
+ Zn: 1.088830,
+ t0: 0.137931034,
+ t1: 0.206896552,
+ t2: 0.12841855,
+ t3: 0.008856452
+ };
+
+ rgb2lab = function() {
+ var b, g, r, ref, ref1, x, y, z;
+ ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
+ ref1 = rgb2xyz(r, g, b), x = ref1[0], y = ref1[1], z = ref1[2];
+ return [116 * y - 16, 500 * (x - y), 200 * (y - z)];
+ };
+
+ rgb_xyz = function(r) {
+ if ((r /= 255) <= 0.04045) {
+ return r / 12.92;
+ } else {
+ return pow((r + 0.055) / 1.055, 2.4);
+ }
+ };
+
+ xyz_lab = function(t) {
+ if (t > LAB_CONSTANTS.t3) {
+ return pow(t, 1 / 3);
+ } else {
+ return t / LAB_CONSTANTS.t2 + LAB_CONSTANTS.t0;
+ }
+ };
+
+ rgb2xyz = function() {
+ var b, g, r, ref, x, y, z;
+ ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
+ r = rgb_xyz(r);
+ g = rgb_xyz(g);
+ b = rgb_xyz(b);
+ x = xyz_lab((0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / LAB_CONSTANTS.Xn);
+ y = xyz_lab((0.2126729 * r + 0.7151522 * g + 0.0721750 * b) / LAB_CONSTANTS.Yn);
+ z = xyz_lab((0.0193339 * r + 0.1191920 * g + 0.9503041 * b) / LAB_CONSTANTS.Zn);
+ return [x, y, z];
+ };
+
+ chroma.lab = function() {
+ return (function(func, args, ctor) {
+ ctor.prototype = func.prototype;
+ var child = new ctor, result = func.apply(child, args);
+ return Object(result) === result ? result : child;
+ })(Color, slice.call(arguments).concat(['lab']), function(){});
+ };
+
+ _input.lab = lab2rgb;
+
+ Color.prototype.lab = function() {
+ return rgb2lab(this._rgb);
+ };
+
+ bezier = function(colors) {
+ var I, I0, I1, c, lab0, lab1, lab2, lab3, ref, ref1, ref2;
+ colors = (function() {
+ var len, o, results;
+ results = [];
+ for (o = 0, len = colors.length; o < len; o++) {
+ c = colors[o];
+ results.push(chroma(c));
+ }
+ return results;
+ })();
+ if (colors.length === 2) {
+ ref = (function() {
+ var len, o, results;
+ results = [];
+ for (o = 0, len = colors.length; o < len; o++) {
+ c = colors[o];
+ results.push(c.lab());
+ }
+ return results;
+ })(), lab0 = ref[0], lab1 = ref[1];
+ I = function(t) {
+ var i, lab;
+ lab = (function() {
+ var o, results;
+ results = [];
+ for (i = o = 0; o <= 2; i = ++o) {
+ results.push(lab0[i] + t * (lab1[i] - lab0[i]));
+ }
+ return results;
+ })();
+ return chroma.lab.apply(chroma, lab);
+ };
+ } else if (colors.length === 3) {
+ ref1 = (function() {
+ var len, o, results;
+ results = [];
+ for (o = 0, len = colors.length; o < len; o++) {
+ c = colors[o];
+ results.push(c.lab());
+ }
+ return results;
+ })(), lab0 = ref1[0], lab1 = ref1[1], lab2 = ref1[2];
+ I = function(t) {
+ var i, lab;
+ lab = (function() {
+ var o, results;
+ results = [];
+ for (i = o = 0; o <= 2; i = ++o) {
+ results.push((1 - t) * (1 - t) * lab0[i] + 2 * (1 - t) * t * lab1[i] + t * t * lab2[i]);
+ }
+ return results;
+ })();
+ return chroma.lab.apply(chroma, lab);
+ };
+ } else if (colors.length === 4) {
+ ref2 = (function() {
+ var len, o, results;
+ results = [];
+ for (o = 0, len = colors.length; o < len; o++) {
+ c = colors[o];
+ results.push(c.lab());
+ }
+ return results;
+ })(), lab0 = ref2[0], lab1 = ref2[1], lab2 = ref2[2], lab3 = ref2[3];
+ I = function(t) {
+ var i, lab;
+ lab = (function() {
+ var o, results;
+ results = [];
+ for (i = o = 0; o <= 2; i = ++o) {
+ results.push((1 - t) * (1 - t) * (1 - t) * lab0[i] + 3 * (1 - t) * (1 - t) * t * lab1[i] + 3 * (1 - t) * t * t * lab2[i] + t * t * t * lab3[i]);
+ }
+ return results;
+ })();
+ return chroma.lab.apply(chroma, lab);
+ };
+ } else if (colors.length === 5) {
+ I0 = bezier(colors.slice(0, 3));
+ I1 = bezier(colors.slice(2, 5));
+ I = function(t) {
+ if (t < 0.5) {
+ return I0(t * 2);
+ } else {
+ return I1((t - 0.5) * 2);
+ }
+ };
+ }
+ return I;
+ };
+
+ chroma.bezier = function(colors) {
+ var f;
+ f = bezier(colors);
+ f.scale = function() {
+ return chroma.scale(f);
+ };
+ return f;
+ };
+
+
+ /*
+ chroma.js
+
+ Copyright (c) 2011-2013, Gregor Aisch
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * The name Gregor Aisch may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ @source: https://github.com/gka/chroma.js
+ */
+
+ chroma.cubehelix = function(start, rotations, hue, gamma, lightness) {
+ var dh, dl, f;
+ if (start == null) {
+ start = 300;
+ }
+ if (rotations == null) {
+ rotations = -1.5;
+ }
+ if (hue == null) {
+ hue = 1;
+ }
+ if (gamma == null) {
+ gamma = 1;
+ }
+ if (lightness == null) {
+ lightness = [0, 1];
+ }
+ dl = lightness[1] - lightness[0];
+ dh = 0;
+ f = function(fract) {
+ var a, amp, b, cos_a, g, h, l, r, sin_a;
+ a = TWOPI * ((start + 120) / 360 + rotations * fract);
+ l = pow(lightness[0] + dl * fract, gamma);
+ h = dh !== 0 ? hue[0] + fract * dh : hue;
+ amp = h * l * (1 - l) / 2;
+ cos_a = cos(a);
+ sin_a = sin(a);
+ r = l + amp * (-0.14861 * cos_a + 1.78277 * sin_a);
+ g = l + amp * (-0.29227 * cos_a - 0.90649 * sin_a);
+ b = l + amp * (+1.97294 * cos_a);
+ return chroma(clip_rgb([r * 255, g * 255, b * 255]));
+ };
+ f.start = function(s) {
+ if (s == null) {
+ return start;
+ }
+ start = s;
+ return f;
+ };
+ f.rotations = function(r) {
+ if (r == null) {
+ return rotations;
+ }
+ rotations = r;
+ return f;
+ };
+ f.gamma = function(g) {
+ if (g == null) {
+ return gamma;
+ }
+ gamma = g;
+ return f;
+ };
+ f.hue = function(h) {
+ if (h == null) {
+ return hue;
+ }
+ hue = h;
+ if (type(hue) === 'array') {
+ dh = hue[1] - hue[0];
+ if (dh === 0) {
+ hue = hue[1];
+ }
+ } else {
+ dh = 0;
+ }
+ return f;
+ };
+ f.lightness = function(h) {
+ if (h == null) {
+ return lightness;
+ }
+ lightness = h;
+ if (type(lightness) === 'array') {
+ dl = lightness[1] - lightness[0];
+ if (dl === 0) {
+ lightness = lightness[1];
+ }
+ } else {
+ dl = 0;
+ }
+ return f;
+ };
+ f.scale = function() {
+ return chroma.scale(f);
+ };
+ f.hue(hue);
+ return f;
+ };
+
+ chroma.random = function() {
+ var code, digits, i, o;
+ digits = '0123456789abcdef';
+ code = '#';
+ for (i = o = 0; o < 6; i = ++o) {
+ code += digits.charAt(floor(Math.random() * 16));
+ }
+ return new Color(code);
+ };
+
+ _input.rgb = function() {
+ var k, ref, results, v;
+ ref = unpack(arguments);
+ results = [];
+ for (k in ref) {
+ v = ref[k];
+ results.push(v);
+ }
+ return results;
+ };
+
+ chroma.rgb = function() {
+ return (function(func, args, ctor) {
+ ctor.prototype = func.prototype;
+ var child = new ctor, result = func.apply(child, args);
+ return Object(result) === result ? result : child;
+ })(Color, slice.call(arguments).concat(['rgb']), function(){});
+ };
+
+ Color.prototype.rgb = function() {
+ return this._rgb.slice(0, 3);
+ };
+
+ Color.prototype.rgba = function() {
+ return this._rgb;
+ };
+
+ _guess_formats.push({
+ p: 15,
+ test: function(n) {
+ var a;
+ a = unpack(arguments);
+ if (type(a) === 'array' && a.length === 3) {
+ return 'rgb';
+ }
+ if (a.length === 4 && type(a[3]) === "number" && a[3] >= 0 && a[3] <= 1) {
+ return 'rgb';
+ }
+ }
+ });
+
+ hex2rgb = function(hex) {
+ var a, b, g, r, rgb, u;
+ if (hex.match(/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/)) {
+ if (hex.length === 4 || hex.length === 7) {
+ hex = hex.substr(1);
+ }
+ if (hex.length === 3) {
+ hex = hex.split("");
+ hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
+ }
+ u = parseInt(hex, 16);
+ r = u >> 16;
+ g = u >> 8 & 0xFF;
+ b = u & 0xFF;
+ return [r, g, b, 1];
+ }
+ if (hex.match(/^#?([A-Fa-f0-9]{8})$/)) {
+ if (hex.length === 9) {
+ hex = hex.substr(1);
+ }
+ u = parseInt(hex, 16);
+ r = u >> 24 & 0xFF;
+ g = u >> 16 & 0xFF;
+ b = u >> 8 & 0xFF;
+ a = round((u & 0xFF) / 0xFF * 100) / 100;
+ return [r, g, b, a];
+ }
+ if ((_input.css != null) && (rgb = _input.css(hex))) {
+ return rgb;
+ }
+ throw "unknown color: " + hex;
+ };
+
+ rgb2hex = function(channels, mode) {
+ var a, b, g, hxa, r, str, u;
+ if (mode == null) {
+ mode = 'rgb';
+ }
+ r = channels[0], g = channels[1], b = channels[2], a = channels[3];
+ u = r << 16 | g << 8 | b;
+ str = "000000" + u.toString(16);
+ str = str.substr(str.length - 6);
+ hxa = '0' + round(a * 255).toString(16);
+ hxa = hxa.substr(hxa.length - 2);
+ return "#" + (function() {
+ switch (mode.toLowerCase()) {
+ case 'rgba':
+ return str + hxa;
+ case 'argb':
+ return hxa + str;
+ default:
+ return str;
+ }
+ })();
+ };
+
+ _input.hex = function(h) {
+ return hex2rgb(h);
+ };
+
+ chroma.hex = function() {
+ return (function(func, args, ctor) {
+ ctor.prototype = func.prototype;
+ var child = new ctor, result = func.apply(child, args);
+ return Object(result) === result ? result : child;
+ })(Color, slice.call(arguments).concat(['hex']), function(){});
+ };
+
+ Color.prototype.hex = function(mode) {
+ if (mode == null) {
+ mode = 'rgb';
+ }
+ return rgb2hex(this._rgb, mode);
+ };
+
+ _guess_formats.push({
+ p: 10,
+ test: function(n) {
+ if (arguments.length === 1 && type(n) === "string") {
+ return 'hex';
+ }
+ }
+ });
+
+ hsl2rgb = function() {
+ var args, b, c, g, h, i, l, o, r, ref, s, t1, t2, t3;
+ args = unpack(arguments);
+ h = args[0], s = args[1], l = args[2];
+ if (s === 0) {
+ r = g = b = l * 255;
+ } else {
+ t3 = [0, 0, 0];
+ c = [0, 0, 0];
+ t2 = l < 0.5 ? l * (1 + s) : l + s - l * s;
+ t1 = 2 * l - t2;
+ h /= 360;
+ t3[0] = h + 1 / 3;
+ t3[1] = h;
+ t3[2] = h - 1 / 3;
+ for (i = o = 0; o <= 2; i = ++o) {
+ if (t3[i] < 0) {
+ t3[i] += 1;
+ }
+ if (t3[i] > 1) {
+ t3[i] -= 1;
+ }
+ if (6 * t3[i] < 1) {
+ c[i] = t1 + (t2 - t1) * 6 * t3[i];
+ } else if (2 * t3[i] < 1) {
+ c[i] = t2;
+ } else if (3 * t3[i] < 2) {
+ c[i] = t1 + (t2 - t1) * ((2 / 3) - t3[i]) * 6;
+ } else {
+ c[i] = t1;
+ }
+ }
+ ref = [round(c[0] * 255), round(c[1] * 255), round(c[2] * 255)], r = ref[0], g = ref[1], b = ref[2];
+ }
+ if (args.length > 3) {
+ return [r, g, b, args[3]];
+ } else {
+ return [r, g, b];
+ }
+ };
+
+ rgb2hsl = function(r, g, b) {
+ var h, l, min, ref, s;
+ if (r !== void 0 && r.length >= 3) {
+ ref = r, r = ref[0], g = ref[1], b = ref[2];
+ }
+ r /= 255;
+ g /= 255;
+ b /= 255;
+ min = Math.min(r, g, b);
+ max = Math.max(r, g, b);
+ l = (max + min) / 2;
+ if (max === min) {
+ s = 0;
+ h = Number.NaN;
+ } else {
+ s = l < 0.5 ? (max - min) / (max + min) : (max - min) / (2 - max - min);
+ }
+ if (r === max) {
+ h = (g - b) / (max - min);
+ } else if (g === max) {
+ h = 2 + (b - r) / (max - min);
+ } else if (b === max) {
+ h = 4 + (r - g) / (max - min);
+ }
+ h *= 60;
+ if (h < 0) {
+ h += 360;
+ }
+ return [h, s, l];
+ };
+
+ chroma.hsl = function() {
+ return (function(func, args, ctor) {
+ ctor.prototype = func.prototype;
+ var child = new ctor, result = func.apply(child, args);
+ return Object(result) === result ? result : child;
+ })(Color, slice.call(arguments).concat(['hsl']), function(){});
+ };
+
+ _input.hsl = hsl2rgb;
+
+ Color.prototype.hsl = function() {
+ return rgb2hsl(this._rgb);
+ };
+
+ hsv2rgb = function() {
+ var args, b, f, g, h, i, p, q, r, ref, ref1, ref2, ref3, ref4, ref5, s, t, v;
+ args = unpack(arguments);
+ h = args[0], s = args[1], v = args[2];
+ v *= 255;
+ if (s === 0) {
+ r = g = b = v;
+ } else {
+ if (h === 360) {
+ h = 0;
+ }
+ if (h > 360) {
+ h -= 360;
+ }
+ if (h < 0) {
+ h += 360;
+ }
+ h /= 60;
+ i = floor(h);
+ f = h - i;
+ p = v * (1 - s);
+ q = v * (1 - s * f);
+ t = v * (1 - s * (1 - f));
+ switch (i) {
+ case 0:
+ ref = [v, t, p], r = ref[0], g = ref[1], b = ref[2];
+ break;
+ case 1:
+ ref1 = [q, v, p], r = ref1[0], g = ref1[1], b = ref1[2];
+ break;
+ case 2:
+ ref2 = [p, v, t], r = ref2[0], g = ref2[1], b = ref2[2];
+ break;
+ case 3:
+ ref3 = [p, q, v], r = ref3[0], g = ref3[1], b = ref3[2];
+ break;
+ case 4:
+ ref4 = [t, p, v], r = ref4[0], g = ref4[1], b = ref4[2];
+ break;
+ case 5:
+ ref5 = [v, p, q], r = ref5[0], g = ref5[1], b = ref5[2];
+ }
+ }
+ r = round(r);
+ g = round(g);
+ b = round(b);
+ return [r, g, b, args.length > 3 ? args[3] : 1];
+ };
+
+ rgb2hsv = function() {
+ var b, delta, g, h, min, r, ref, s, v;
+ ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
+ min = Math.min(r, g, b);
+ max = Math.max(r, g, b);
+ delta = max - min;
+ v = max / 255.0;
+ if (max === 0) {
+ h = Number.NaN;
+ s = 0;
+ } else {
+ s = delta / max;
+ if (r === max) {
+ h = (g - b) / delta;
+ }
+ if (g === max) {
+ h = 2 + (b - r) / delta;
+ }
+ if (b === max) {
+ h = 4 + (r - g) / delta;
+ }
+ h *= 60;
+ if (h < 0) {
+ h += 360;
+ }
+ }
+ return [h, s, v];
+ };
+
+ chroma.hsv = function() {
+ return (function(func, args, ctor) {
+ ctor.prototype = func.prototype;
+ var child = new ctor, result = func.apply(child, args);
+ return Object(result) === result ? result : child;
+ })(Color, slice.call(arguments).concat(['hsv']), function(){});
+ };
+
+ _input.hsv = hsv2rgb;
+
+ Color.prototype.hsv = function() {
+ return rgb2hsv(this._rgb);
+ };
+
+ num2rgb = function(num) {
+ var b, g, r;
+ if (type(num) === "number" && num >= 0 && num <= 0xFFFFFF) {
+ r = num >> 16;
+ g = (num >> 8) & 0xFF;
+ b = num & 0xFF;
+ return [r, g, b, 1];
+ }
+ console.warn("unknown num color: " + num);
+ return [0, 0, 0, 1];
+ };
+
+ rgb2num = function() {
+ var b, g, r, ref;
+ ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
+ return (r << 16) + (g << 8) + b;
+ };
+
+ chroma.num = function(num) {
+ return new Color(num, 'num');
+ };
+
+ Color.prototype.num = function(mode) {
+ if (mode == null) {
+ mode = 'rgb';
+ }
+ return rgb2num(this._rgb, mode);
+ };
+
+ _input.num = num2rgb;
+
+ _guess_formats.push({
+ p: 10,
+ test: function(n) {
+ if (arguments.length === 1 && type(n) === "number" && n >= 0 && n <= 0xFFFFFF) {
+ return 'num';
+ }
+ }
+ });
+
+ css2rgb = function(css) {
+ var aa, ab, hsl, i, m, o, rgb, w;
+ css = css.toLowerCase();
+ if ((chroma.colors != null) && chroma.colors[css]) {
+ return hex2rgb(chroma.colors[css]);
+ }
+ if (m = css.match(/rgb\(\s*(\-?\d+),\s*(\-?\d+)\s*,\s*(\-?\d+)\s*\)/)) {
+ rgb = m.slice(1, 4);
+ for (i = o = 0; o <= 2; i = ++o) {
+ rgb[i] = +rgb[i];
+ }
+ rgb[3] = 1;
+ } else if (m = css.match(/rgba\(\s*(\-?\d+),\s*(\-?\d+)\s*,\s*(\-?\d+)\s*,\s*([01]|[01]?\.\d+)\)/)) {
+ rgb = m.slice(1, 5);
+ for (i = w = 0; w <= 3; i = ++w) {
+ rgb[i] = +rgb[i];
+ }
+ } else if (m = css.match(/rgb\(\s*(\-?\d+(?:\.\d+)?)%,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*\)/)) {
+ rgb = m.slice(1, 4);
+ for (i = aa = 0; aa <= 2; i = ++aa) {
+ rgb[i] = round(rgb[i] * 2.55);
+ }
+ rgb[3] = 1;
+ } else if (m = css.match(/rgba\(\s*(\-?\d+(?:\.\d+)?)%,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)/)) {
+ rgb = m.slice(1, 5);
+ for (i = ab = 0; ab <= 2; i = ++ab) {
+ rgb[i] = round(rgb[i] * 2.55);
+ }
+ rgb[3] = +rgb[3];
+ } else if (m = css.match(/hsl\(\s*(\-?\d+(?:\.\d+)?),\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*\)/)) {
+ hsl = m.slice(1, 4);
+ hsl[1] *= 0.01;
+ hsl[2] *= 0.01;
+ rgb = hsl2rgb(hsl);
+ rgb[3] = 1;
+ } else if (m = css.match(/hsla\(\s*(\-?\d+(?:\.\d+)?),\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)/)) {
+ hsl = m.slice(1, 4);
+ hsl[1] *= 0.01;
+ hsl[2] *= 0.01;
+ rgb = hsl2rgb(hsl);
+ rgb[3] = +m[4];
+ }
+ return rgb;
+ };
+
+ rgb2css = function(rgba) {
+ var mode;
+ mode = rgba[3] < 1 ? 'rgba' : 'rgb';
+ if (mode === 'rgb') {
+ return mode + '(' + rgba.slice(0, 3).map(round).join(',') + ')';
+ } else if (mode === 'rgba') {
+ return mode + '(' + rgba.slice(0, 3).map(round).join(',') + ',' + rgba[3] + ')';
+ } else {
+
+ }
+ };
+
+ rnd = function(a) {
+ return round(a * 100) / 100;
+ };
+
+ hsl2css = function(hsl, alpha) {
+ var mode;
+ mode = alpha < 1 ? 'hsla' : 'hsl';
+ hsl[0] = rnd(hsl[0] || 0);
+ hsl[1] = rnd(hsl[1] * 100) + '%';
+ hsl[2] = rnd(hsl[2] * 100) + '%';
+ if (mode === 'hsla') {
+ hsl[3] = alpha;
+ }
+ return mode + '(' + hsl.join(',') + ')';
+ };
+
+ _input.css = function(h) {
+ return css2rgb(h);
+ };
+
+ chroma.css = function() {
+ return (function(func, args, ctor) {
+ ctor.prototype = func.prototype;
+ var child = new ctor, result = func.apply(child, args);
+ return Object(result) === result ? result : child;
+ })(Color, slice.call(arguments).concat(['css']), function(){});
+ };
+
+ Color.prototype.css = function(mode) {
+ if (mode == null) {
+ mode = 'rgb';
+ }
+ if (mode.slice(0, 3) === 'rgb') {
+ return rgb2css(this._rgb);
+ } else if (mode.slice(0, 3) === 'hsl') {
+ return hsl2css(this.hsl(), this.alpha());
+ }
+ };
+
+ _input.named = function(name) {
+ return hex2rgb(w3cx11[name]);
+ };
+
+ _guess_formats.push({
+ p: 20,
+ test: function(n) {
+ if (arguments.length === 1 && (w3cx11[n] != null)) {
+ return 'named';
+ }
+ }
+ });
+
+ Color.prototype.name = function(n) {
+ var h, k;
+ if (arguments.length) {
+ if (w3cx11[n]) {
+ this._rgb = hex2rgb(w3cx11[n]);
+ }
+ this._rgb[3] = 1;
+ this;
+ }
+ h = this.hex();
+ for (k in w3cx11) {
+ if (h === w3cx11[k]) {
+ return k;
+ }
+ }
+ return h;
+ };
+
+ lch2lab = function() {
+
+ /*
+ Convert from a qualitative parameter h and a quantitative parameter l to a 24-bit pixel.
+ These formulas were invented by David Dalrymple to obtain maximum contrast without going
+ out of gamut if the parameters are in the range 0-1.
+
+ A saturation multiplier was added by Gregor Aisch
+ */
+ var c, h, l, ref;
+ ref = unpack(arguments), l = ref[0], c = ref[1], h = ref[2];
+ h = h * DEG2RAD;
+ return [l, cos(h) * c, sin(h) * c];
+ };
+
+ lch2rgb = function() {
+ var L, a, args, b, c, g, h, l, r, ref, ref1;
+ args = unpack(arguments);
+ l = args[0], c = args[1], h = args[2];
+ ref = lch2lab(l, c, h), L = ref[0], a = ref[1], b = ref[2];
+ ref1 = lab2rgb(L, a, b), r = ref1[0], g = ref1[1], b = ref1[2];
+ return [limit(r, 0, 255), limit(g, 0, 255), limit(b, 0, 255), args.length > 3 ? args[3] : 1];
+ };
+
+ lab2lch = function() {
+ var a, b, c, h, l, ref;
+ ref = unpack(arguments), l = ref[0], a = ref[1], b = ref[2];
+ c = sqrt(a * a + b * b);
+ h = (atan2(b, a) * RAD2DEG + 360) % 360;
+ if (round(c * 10000) === 0) {
+ h = Number.NaN;
+ }
+ return [l, c, h];
+ };
+
+ rgb2lch = function() {
+ var a, b, g, l, r, ref, ref1;
+ ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
+ ref1 = rgb2lab(r, g, b), l = ref1[0], a = ref1[1], b = ref1[2];
+ return lab2lch(l, a, b);
+ };
+
+ chroma.lch = function() {
+ var args;
+ args = unpack(arguments);
+ return new Color(args, 'lch');
+ };
+
+ chroma.hcl = function() {
+ var args;
+ args = unpack(arguments);
+ return new Color(args, 'hcl');
+ };
+
+ _input.lch = lch2rgb;
+
+ _input.hcl = function() {
+ var c, h, l, ref;
+ ref = unpack(arguments), h = ref[0], c = ref[1], l = ref[2];
+ return lch2rgb([l, c, h]);
+ };
+
+ Color.prototype.lch = function() {
+ return rgb2lch(this._rgb);
+ };
+
+ Color.prototype.hcl = function() {
+ return rgb2lch(this._rgb).reverse();
+ };
+
+ rgb2cmyk = function(mode) {
+ var b, c, f, g, k, m, r, ref, y;
+ if (mode == null) {
+ mode = 'rgb';
+ }
+ ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
+ r = r / 255;
+ g = g / 255;
+ b = b / 255;
+ k = 1 - Math.max(r, Math.max(g, b));
+ f = k < 1 ? 1 / (1 - k) : 0;
+ c = (1 - r - k) * f;
+ m = (1 - g - k) * f;
+ y = (1 - b - k) * f;
+ return [c, m, y, k];
+ };
+
+ cmyk2rgb = function() {
+ var alpha, args, b, c, g, k, m, r, y;
+ args = unpack(arguments);
+ c = args[0], m = args[1], y = args[2], k = args[3];
+ alpha = args.length > 4 ? args[4] : 1;
+ if (k === 1) {
+ return [0, 0, 0, alpha];
+ }
+ r = c >= 1 ? 0 : round(255 * (1 - c) * (1 - k));
+ g = m >= 1 ? 0 : round(255 * (1 - m) * (1 - k));
+ b = y >= 1 ? 0 : round(255 * (1 - y) * (1 - k));
+ return [r, g, b, alpha];
+ };
+
+ _input.cmyk = function() {
+ return cmyk2rgb(unpack(arguments));
+ };
+
+ chroma.cmyk = function() {
+ return (function(func, args, ctor) {
+ ctor.prototype = func.prototype;
+ var child = new ctor, result = func.apply(child, args);
+ return Object(result) === result ? result : child;
+ })(Color, slice.call(arguments).concat(['cmyk']), function(){});
+ };
+
+ Color.prototype.cmyk = function() {
+ return rgb2cmyk(this._rgb);
+ };
+
+ _input.gl = function() {
+ var i, k, o, rgb, v;
+ rgb = (function() {
+ var ref, results;
+ ref = unpack(arguments);
+ results = [];
+ for (k in ref) {
+ v = ref[k];
+ results.push(v);
+ }
+ return results;
+ }).apply(this, arguments);
+ for (i = o = 0; o <= 2; i = ++o) {
+ rgb[i] *= 255;
+ }
+ return rgb;
+ };
+
+ chroma.gl = function() {
+ return (function(func, args, ctor) {
+ ctor.prototype = func.prototype;
+ var child = new ctor, result = func.apply(child, args);
+ return Object(result) === result ? result : child;
+ })(Color, slice.call(arguments).concat(['gl']), function(){});
+ };
+
+ Color.prototype.gl = function() {
+ var rgb;
+ rgb = this._rgb;
+ return [rgb[0] / 255, rgb[1] / 255, rgb[2] / 255, rgb[3]];
+ };
+
+ rgb2luminance = function(r, g, b) {
+ var ref;
+ ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
+ r = luminance_x(r);
+ g = luminance_x(g);
+ b = luminance_x(b);
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ };
+
+ luminance_x = function(x) {
+ x /= 255;
+ if (x <= 0.03928) {
+ return x / 12.92;
+ } else {
+ return pow((x + 0.055) / 1.055, 2.4);
+ }
+ };
+
+ _interpolators = [];
+
+ interpolate = function(col1, col2, f, m) {
+ var interpol, len, o, res;
+ if (f == null) {
+ f = 0.5;
+ }
+ if (m == null) {
+ m = 'rgb';
+ }
+
+ /*
+ interpolates between colors
+ f = 0 --> me
+ f = 1 --> col
+ */
+ if (type(col1) !== 'object') {
+ col1 = chroma(col1);
+ }
+ if (type(col2) !== 'object') {
+ col2 = chroma(col2);
+ }
+ for (o = 0, len = _interpolators.length; o < len; o++) {
+ interpol = _interpolators[o];
+ if (m === interpol[0]) {
+ res = interpol[1](col1, col2, f, m);
+ break;
+ }
+ }
+ if (res == null) {
+ throw "color mode " + m + " is not supported";
+ }
+ res.alpha(col1.alpha() + f * (col2.alpha() - col1.alpha()));
+ return res;
+ };
+
+ chroma.interpolate = interpolate;
+
+ Color.prototype.interpolate = function(col2, f, m) {
+ return interpolate(this, col2, f, m);
+ };
+
+ chroma.mix = interpolate;
+
+ Color.prototype.mix = Color.prototype.interpolate;
+
+ interpolate_rgb = function(col1, col2, f, m) {
+ var xyz0, xyz1;
+ xyz0 = col1._rgb;
+ xyz1 = col2._rgb;
+ return new Color(xyz0[0] + f * (xyz1[0] - xyz0[0]), xyz0[1] + f * (xyz1[1] - xyz0[1]), xyz0[2] + f * (xyz1[2] - xyz0[2]), m);
+ };
+
+ _interpolators.push(['rgb', interpolate_rgb]);
+
+ Color.prototype.luminance = function(lum, mode) {
+ var cur_lum, eps, max_iter, test;
+ if (mode == null) {
+ mode = 'rgb';
+ }
+ if (!arguments.length) {
+ return rgb2luminance(this._rgb);
+ }
+ if (lum === 0) {
+ this._rgb = [0, 0, 0, this._rgb[3]];
+ } else if (lum === 1) {
+ this._rgb = [255, 255, 255, this._rgb[3]];
+ } else {
+ eps = 1e-7;
+ max_iter = 20;
+ test = function(l, h) {
+ var lm, m;
+ m = l.interpolate(h, 0.5, mode);
+ lm = m.luminance();
+ if (Math.abs(lum - lm) < eps || !max_iter--) {
+ return m;
+ }
+ if (lm > lum) {
+ return test(l, m);
+ }
+ return test(m, h);
+ };
+ cur_lum = rgb2luminance(this._rgb);
+ this._rgb = (cur_lum > lum ? test(chroma('black'), this) : test(this, chroma('white'))).rgba();
+ }
+ return this;
+ };
+
+ temperature2rgb = function(kelvin) {
+ var b, g, r, temp;
+ temp = kelvin / 100;
+ if (temp < 66) {
+ r = 255;
+ g = -155.25485562709179 - 0.44596950469579133 * (g = temp - 2) + 104.49216199393888 * log(g);
+ b = temp < 20 ? 0 : -254.76935184120902 + 0.8274096064007395 * (b = temp - 10) + 115.67994401066147 * log(b);
+ } else {
+ r = 351.97690566805693 + 0.114206453784165 * (r = temp - 55) - 40.25366309332127 * log(r);
+ g = 325.4494125711974 + 0.07943456536662342 * (g = temp - 50) - 28.0852963507957 * log(g);
+ b = 255;
+ }
+ return clip_rgb([r, g, b]);
+ };
+
+ rgb2temperature = function() {
+ var b, eps, g, maxTemp, minTemp, r, ref, rgb, temp;
+ ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
+ minTemp = 1000;
+ maxTemp = 40000;
+ eps = 0.4;
+ while (maxTemp - minTemp > eps) {
+ temp = (maxTemp + minTemp) * 0.5;
+ rgb = temperature2rgb(temp);
+ if ((rgb[2] / rgb[0]) >= (b / r)) {
+ maxTemp = temp;
+ } else {
+ minTemp = temp;
+ }
+ }
+ return round(temp);
+ };
+
+ chroma.temperature = chroma.kelvin = function() {
+ return (function(func, args, ctor) {
+ ctor.prototype = func.prototype;
+ var child = new ctor, result = func.apply(child, args);
+ return Object(result) === result ? result : child;
+ })(Color, slice.call(arguments).concat(['temperature']), function(){});
+ };
+
+ _input.temperature = _input.kelvin = _input.K = temperature2rgb;
+
+ Color.prototype.temperature = function() {
+ return rgb2temperature(this._rgb);
+ };
+
+ Color.prototype.kelvin = Color.prototype.temperature;
+
+ chroma.contrast = function(a, b) {
+ var l1, l2, ref, ref1;
+ if ((ref = type(a)) === 'string' || ref === 'number') {
+ a = new Color(a);
+ }
+ if ((ref1 = type(b)) === 'string' || ref1 === 'number') {
+ b = new Color(b);
+ }
+ l1 = a.luminance();
+ l2 = b.luminance();
+ if (l1 > l2) {
+ return (l1 + 0.05) / (l2 + 0.05);
+ } else {
+ return (l2 + 0.05) / (l1 + 0.05);
+ }
+ };
+
+ Color.prototype.get = function(modechan) {
+ var channel, i, me, mode, ref, src;
+ me = this;
+ ref = modechan.split('.'), mode = ref[0], channel = ref[1];
+ src = me[mode]();
+ if (channel) {
+ i = mode.indexOf(channel);
+ if (i > -1) {
+ return src[i];
+ } else {
+ return console.warn('unknown channel ' + channel + ' in mode ' + mode);
+ }
+ } else {
+ return src;
+ }
+ };
+
+ Color.prototype.set = function(modechan, value) {
+ var channel, i, me, mode, ref, src;
+ me = this;
+ ref = modechan.split('.'), mode = ref[0], channel = ref[1];
+ if (channel) {
+ src = me[mode]();
+ i = mode.indexOf(channel);
+ if (i > -1) {
+ if (type(value) === 'string') {
+ switch (value.charAt(0)) {
+ case '+':
+ src[i] += +value;
+ break;
+ case '-':
+ src[i] += +value;
+ break;
+ case '*':
+ src[i] *= +(value.substr(1));
+ break;
+ case '/':
+ src[i] /= +(value.substr(1));
+ break;
+ default:
+ src[i] = +value;
+ }
+ } else {
+ src[i] = value;
+ }
+ } else {
+ console.warn('unknown channel ' + channel + ' in mode ' + mode);
+ }
+ } else {
+ src = value;
+ }
+ me._rgb = chroma(src, mode).alpha(me.alpha())._rgb;
+ return me;
+ };
+
+ Color.prototype.darken = function(amount) {
+ var lab, me;
+ if (amount == null) {
+ amount = 1;
+ }
+ me = this;
+ lab = me.lab();
+ lab[0] -= LAB_CONSTANTS.Kn * amount;
+ return chroma.lab(lab).alpha(me.alpha());
+ };
+
+ Color.prototype.brighten = function(amount) {
+ if (amount == null) {
+ amount = 1;
+ }
+ return this.darken(-amount);
+ };
+
+ Color.prototype.darker = Color.prototype.darken;
+
+ Color.prototype.brighter = Color.prototype.brighten;
+
+ Color.prototype.saturate = function(amount) {
+ var lch, me;
+ if (amount == null) {
+ amount = 1;
+ }
+ me = this;
+ lch = me.lch();
+ lch[1] += amount * LAB_CONSTANTS.Kn;
+ if (lch[1] < 0) {
+ lch[1] = 0;
+ }
+ return chroma.lch(lch).alpha(me.alpha());
+ };
+
+ Color.prototype.desaturate = function(amount) {
+ if (amount == null) {
+ amount = 1;
+ }
+ return this.saturate(-amount);
+ };
+
+ Color.prototype.premultiply = function() {
+ var a, rgb;
+ rgb = this.rgb();
+ a = this.alpha();
+ return chroma(rgb[0] * a, rgb[1] * a, rgb[2] * a, a);
+ };
+
+ blend = function(bottom, top, mode) {
+ if (!blend[mode]) {
+ throw 'unknown blend mode ' + mode;
+ }
+ return blend[mode](bottom, top);
+ };
+
+ blend_f = function(f) {
+ return function(bottom, top) {
+ var c0, c1;
+ c0 = chroma(top).rgb();
+ c1 = chroma(bottom).rgb();
+ return chroma(f(c0, c1), 'rgb');
+ };
+ };
+
+ each = function(f) {
+ return function(c0, c1) {
+ var i, o, out;
+ out = [];
+ for (i = o = 0; o <= 3; i = ++o) {
+ out[i] = f(c0[i], c1[i]);
+ }
+ return out;
+ };
+ };
+
+ normal = function(a, b) {
+ return a;
+ };
+
+ multiply = function(a, b) {
+ return a * b / 255;
+ };
+
+ darken = function(a, b) {
+ if (a > b) {
+ return b;
+ } else {
+ return a;
+ }
+ };
+
+ lighten = function(a, b) {
+ if (a > b) {
+ return a;
+ } else {
+ return b;
+ }
+ };
+
+ screen = function(a, b) {
+ return 255 * (1 - (1 - a / 255) * (1 - b / 255));
+ };
+
+ overlay = function(a, b) {
+ if (b < 128) {
+ return 2 * a * b / 255;
+ } else {
+ return 255 * (1 - 2 * (1 - a / 255) * (1 - b / 255));
+ }
+ };
+
+ burn = function(a, b) {
+ return 255 * (1 - (1 - b / 255) / (a / 255));
+ };
+
+ dodge = function(a, b) {
+ if (a === 255) {
+ return 255;
+ }
+ a = 255 * (b / 255) / (1 - a / 255);
+ if (a > 255) {
+ return 255;
+ } else {
+ return a;
+ }
+ };
+
+ blend.normal = blend_f(each(normal));
+
+ blend.multiply = blend_f(each(multiply));
+
+ blend.screen = blend_f(each(screen));
+
+ blend.overlay = blend_f(each(overlay));
+
+ blend.darken = blend_f(each(darken));
+
+ blend.lighten = blend_f(each(lighten));
+
+ blend.dodge = blend_f(each(dodge));
+
+ blend.burn = blend_f(each(burn));
+
+ chroma.blend = blend;
+
+ chroma.analyze = function(data) {
+ var len, o, r, val;
+ r = {
+ min: Number.MAX_VALUE,
+ max: Number.MAX_VALUE * -1,
+ sum: 0,
+ values: [],
+ count: 0
+ };
+ for (o = 0, len = data.length; o < len; o++) {
+ val = data[o];
+ if ((val != null) && !isNaN(val)) {
+ r.values.push(val);
+ r.sum += val;
+ if (val < r.min) {
+ r.min = val;
+ }
+ if (val > r.max) {
+ r.max = val;
+ }
+ r.count += 1;
+ }
+ }
+ r.domain = [r.min, r.max];
+ r.limits = function(mode, num) {
+ return chroma.limits(r, mode, num);
+ };
+ return r;
+ };
+
+ chroma.scale = function(colors, positions) {
+ var _classes, _colorCache, _colors, _correctLightness, _domain, _fixed, _max, _min, _mode, _nacol, _out, _padding, _pos, _spread, classifyValue, f, getClass, getColor, resetCache, setColors, tmap;
+ _mode = 'rgb';
+ _nacol = chroma('#ccc');
+ _spread = 0;
+ _fixed = false;
+ _domain = [0, 1];
+ _pos = [];
+ _padding = [0, 0];
+ _classes = false;
+ _colors = [];
+ _out = false;
+ _min = 0;
+ _max = 1;
+ _correctLightness = false;
+ _colorCache = {};
+ setColors = function(colors) {
+ var c, col, o, ref, ref1, ref2, w;
+ if (colors == null) {
+ colors = ['#fff', '#000'];
+ }
+ if ((colors != null) && type(colors) === 'string' && (((ref = chroma.brewer) != null ? ref[colors] : void 0) != null)) {
+ colors = chroma.brewer[colors];
+ }
+ if (type(colors) === 'array') {
+ colors = colors.slice(0);
+ for (c = o = 0, ref1 = colors.length - 1; 0 <= ref1 ? o <= ref1 : o >= ref1; c = 0 <= ref1 ? ++o : --o) {
+ col = colors[c];
+ if (type(col) === "string") {
+ colors[c] = chroma(col);
+ }
+ }
+ _pos.length = 0;
+ for (c = w = 0, ref2 = colors.length - 1; 0 <= ref2 ? w <= ref2 : w >= ref2; c = 0 <= ref2 ? ++w : --w) {
+ _pos.push(c / (colors.length - 1));
+ }
+ }
+ resetCache();
+ return _colors = colors;
+ };
+ getClass = function(value) {
+ var i, n;
+ if (_classes != null) {
+ n = _classes.length - 1;
+ i = 0;
+ while (i < n && value >= _classes[i]) {
+ i++;
+ }
+ return i - 1;
+ }
+ return 0;
+ };
+ tmap = function(t) {
+ return t;
+ };
+ classifyValue = function(value) {
+ var i, maxc, minc, n, val;
+ val = value;
+ if (_classes.length > 2) {
+ n = _classes.length - 1;
+ i = getClass(value);
+ minc = _classes[0] + (_classes[1] - _classes[0]) * (0 + _spread * 0.5);
+ maxc = _classes[n - 1] + (_classes[n] - _classes[n - 1]) * (1 - _spread * 0.5);
+ val = _min + ((_classes[i] + (_classes[i + 1] - _classes[i]) * 0.5 - minc) / (maxc - minc)) * (_max - _min);
+ }
+ return val;
+ };
+ getColor = function(val, bypassMap) {
+ var c, col, i, k, o, p, ref, t;
+ if (bypassMap == null) {
+ bypassMap = false;
+ }
+ if (isNaN(val)) {
+ return _nacol;
+ }
+ if (!bypassMap) {
+ if (_classes && _classes.length > 2) {
+ c = getClass(val);
+ t = c / (_classes.length - 2);
+ t = _padding[0] + (t * (1 - _padding[0] - _padding[1]));
+ } else if (_max !== _min) {
+ t = (val - _min) / (_max - _min);
+ t = _padding[0] + (t * (1 - _padding[0] - _padding[1]));
+ t = Math.min(1, Math.max(0, t));
+ } else {
+ t = 1;
+ }
+ } else {
+ t = val;
+ }
+ if (!bypassMap) {
+ t = tmap(t);
+ }
+ k = Math.floor(t * 10000);
+ if (_colorCache[k]) {
+ col = _colorCache[k];
+ } else {
+ if (type(_colors) === 'array') {
+ for (i = o = 0, ref = _pos.length - 1; 0 <= ref ? o <= ref : o >= ref; i = 0 <= ref ? ++o : --o) {
+ p = _pos[i];
+ if (t <= p) {
+ col = _colors[i];
+ break;
+ }
+ if (t >= p && i === _pos.length - 1) {
+ col = _colors[i];
+ break;
+ }
+ if (t > p && t < _pos[i + 1]) {
+ t = (t - p) / (_pos[i + 1] - p);
+ col = chroma.interpolate(_colors[i], _colors[i + 1], t, _mode);
+ break;
+ }
+ }
+ } else if (type(_colors) === 'function') {
+ col = _colors(t);
+ }
+ _colorCache[k] = col;
+ }
+ return col;
+ };
+ resetCache = function() {
+ return _colorCache = {};
+ };
+ setColors(colors);
+ f = function(v) {
+ var c;
+ c = chroma(getColor(v));
+ if (_out && c[_out]) {
+ return c[_out]();
+ } else {
+ return c;
+ }
+ };
+ f.classes = function(classes) {
+ var d;
+ if (classes != null) {
+ if (type(classes) === 'array') {
+ _classes = classes;
+ _domain = [classes[0], classes[classes.length - 1]];
+ } else {
+ d = chroma.analyze(_domain);
+ if (classes === 0) {
+ _classes = [d.min, d.max];
+ } else {
+ _classes = chroma.limits(d, 'e', classes);
+ }
+ }
+ return f;
+ }
+ return _classes;
+ };
+ f.domain = function(domain) {
+ var c, d, k, len, o, ref, w;
+ if (!arguments.length) {
+ return _domain;
+ }
+ _min = domain[0];
+ _max = domain[domain.length - 1];
+ _pos = [];
+ k = _colors.length;
+ if (domain.length === k && _min !== _max) {
+ for (o = 0, len = domain.length; o < len; o++) {
+ d = domain[o];
+ _pos.push((d - _min) / (_max - _min));
+ }
+ } else {
+ for (c = w = 0, ref = k - 1; 0 <= ref ? w <= ref : w >= ref; c = 0 <= ref ? ++w : --w) {
+ _pos.push(c / (k - 1));
+ }
+ }
+ _domain = [_min, _max];
+ return f;
+ };
+ f.mode = function(_m) {
+ if (!arguments.length) {
+ return _mode;
+ }
+ _mode = _m;
+ resetCache();
+ return f;
+ };
+ f.range = function(colors, _pos) {
+ setColors(colors, _pos);
+ return f;
+ };
+ f.out = function(_o) {
+ _out = _o;
+ return f;
+ };
+ f.spread = function(val) {
+ if (!arguments.length) {
+ return _spread;
+ }
+ _spread = val;
+ return f;
+ };
+ f.correctLightness = function(v) {
+ if (v == null) {
+ v = true;
+ }
+ _correctLightness = v;
+ resetCache();
+ if (_correctLightness) {
+ tmap = function(t) {
+ var L0, L1, L_actual, L_diff, L_ideal, max_iter, pol, t0, t1;
+ L0 = getColor(0, true).lab()[0];
+ L1 = getColor(1, true).lab()[0];
+ pol = L0 > L1;
+ L_actual = getColor(t, true).lab()[0];
+ L_ideal = L0 + (L1 - L0) * t;
+ L_diff = L_actual - L_ideal;
+ t0 = 0;
+ t1 = 1;
+ max_iter = 20;
+ while (Math.abs(L_diff) > 1e-2 && max_iter-- > 0) {
+ (function() {
+ if (pol) {
+ L_diff *= -1;
+ }
+ if (L_diff < 0) {
+ t0 = t;
+ t += (t1 - t) * 0.5;
+ } else {
+ t1 = t;
+ t += (t0 - t) * 0.5;
+ }
+ L_actual = getColor(t, true).lab()[0];
+ return L_diff = L_actual - L_ideal;
+ })();
+ }
+ return t;
+ };
+ } else {
+ tmap = function(t) {
+ return t;
+ };
+ }
+ return f;
+ };
+ f.padding = function(p) {
+ if (p != null) {
+ if (type(p) === 'number') {
+ p = [p, p];
+ }
+ _padding = p;
+ return f;
+ } else {
+ return _padding;
+ }
+ };
+ f.colors = function() {
+ var dd, dm, i, numColors, o, out, ref, results, samples, w;
+ numColors = 0;
+ out = 'hex';
+ if (arguments.length === 1) {
+ if (type(arguments[0]) === 'string') {
+ out = arguments[0];
+ } else {
+ numColors = arguments[0];
+ }
+ }
+ if (arguments.length === 2) {
+ numColors = arguments[0], out = arguments[1];
+ }
+ if (numColors) {
+ dm = _domain[0];
+ dd = _domain[1] - dm;
+ return (function() {
+ results = [];
+ for (var o = 0; 0 <= numColors ? o < numColors : o > numColors; 0 <= numColors ? o++ : o--){ results.push(o); }
+ return results;
+ }).apply(this).map(function(i) {
+ return f(dm + i / (numColors - 1) * dd)[out]();
+ });
+ }
+ colors = [];
+ samples = [];
+ if (_classes && _classes.length > 2) {
+ for (i = w = 1, ref = _classes.length; 1 <= ref ? w < ref : w > ref; i = 1 <= ref ? ++w : --w) {
+ samples.push((_classes[i - 1] + _classes[i]) * 0.5);
+ }
+ } else {
+ samples = _domain;
+ }
+ return samples.map(function(v) {
+ return f(v)[out]();
+ });
+ };
+ return f;
+ };
+
+ if (chroma.scales == null) {
+ chroma.scales = {};
+ }
+
+ chroma.scales.cool = function() {
+ return chroma.scale([chroma.hsl(180, 1, .9), chroma.hsl(250, .7, .4)]);
+ };
+
+ chroma.scales.hot = function() {
+ return chroma.scale(['#000', '#f00', '#ff0', '#fff'], [0, .25, .75, 1]).mode('rgb');
+ };
+
+ chroma.analyze = function(data, key, filter) {
+ var add, k, len, o, r, val, visit;
+ r = {
+ min: Number.MAX_VALUE,
+ max: Number.MAX_VALUE * -1,
+ sum: 0,
+ values: [],
+ count: 0
+ };
+ if (filter == null) {
+ filter = function() {
+ return true;
+ };
+ }
+ add = function(val) {
+ if ((val != null) && !isNaN(val)) {
+ r.values.push(val);
+ r.sum += val;
+ if (val < r.min) {
+ r.min = val;
+ }
+ if (val > r.max) {
+ r.max = val;
+ }
+ r.count += 1;
+ }
+ };
+ visit = function(val, k) {
+ if (filter(val, k)) {
+ if ((key != null) && type(key) === 'function') {
+ return add(key(val));
+ } else if ((key != null) && type(key) === 'string' || type(key) === 'number') {
+ return add(val[key]);
+ } else {
+ return add(val);
+ }
+ }
+ };
+ if (type(data) === 'array') {
+ for (o = 0, len = data.length; o < len; o++) {
+ val = data[o];
+ visit(val);
+ }
+ } else {
+ for (k in data) {
+ val = data[k];
+ visit(val, k);
+ }
+ }
+ r.domain = [r.min, r.max];
+ r.limits = function(mode, num) {
+ return chroma.limits(r, mode, num);
+ };
+ return r;
+ };
+
+ chroma.limits = function(data, mode, num) {
+ var aa, ab, ac, ad, ae, af, ag, ah, ai, aj, ak, al, am, assignments, best, centroids, cluster, clusterSizes, dist, i, j, kClusters, limits, max_log, min, min_log, mindist, n, nb_iters, newCentroids, o, p, pb, pr, ref, ref1, ref10, ref11, ref12, ref13, ref14, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, repeat, sum, tmpKMeansBreaks, value, values, w;
+ if (mode == null) {
+ mode = 'equal';
+ }
+ if (num == null) {
+ num = 7;
+ }
+ if (type(data) === 'array') {
+ data = chroma.analyze(data);
+ }
+ min = data.min;
+ max = data.max;
+ sum = data.sum;
+ values = data.values.sort(function(a, b) {
+ return a - b;
+ });
+ limits = [];
+ if (mode.substr(0, 1) === 'c') {
+ limits.push(min);
+ limits.push(max);
+ }
+ if (mode.substr(0, 1) === 'e') {
+ limits.push(min);
+ for (i = o = 1, ref = num - 1; 1 <= ref ? o <= ref : o >= ref; i = 1 <= ref ? ++o : --o) {
+ limits.push(min + (i / num) * (max - min));
+ }
+ limits.push(max);
+ } else if (mode.substr(0, 1) === 'l') {
+ if (min <= 0) {
+ throw 'Logarithmic scales are only possible for values > 0';
+ }
+ min_log = Math.LOG10E * log(min);
+ max_log = Math.LOG10E * log(max);
+ limits.push(min);
+ for (i = w = 1, ref1 = num - 1; 1 <= ref1 ? w <= ref1 : w >= ref1; i = 1 <= ref1 ? ++w : --w) {
+ limits.push(pow(10, min_log + (i / num) * (max_log - min_log)));
+ }
+ limits.push(max);
+ } else if (mode.substr(0, 1) === 'q') {
+ limits.push(min);
+ for (i = aa = 1, ref2 = num - 1; 1 <= ref2 ? aa <= ref2 : aa >= ref2; i = 1 <= ref2 ? ++aa : --aa) {
+ p = values.length * i / num;
+ pb = floor(p);
+ if (pb === p) {
+ limits.push(values[pb]);
+ } else {
+ pr = p - pb;
+ limits.push(values[pb] * pr + values[pb + 1] * (1 - pr));
+ }
+ }
+ limits.push(max);
+ } else if (mode.substr(0, 1) === 'k') {
+
+ /*
+ implementation based on
+ http://code.google.com/p/figue/source/browse/trunk/figue.js#336
+ simplified for 1-d input values
+ */
+ n = values.length;
+ assignments = new Array(n);
+ clusterSizes = new Array(num);
+ repeat = true;
+ nb_iters = 0;
+ centroids = null;
+ centroids = [];
+ centroids.push(min);
+ for (i = ab = 1, ref3 = num - 1; 1 <= ref3 ? ab <= ref3 : ab >= ref3; i = 1 <= ref3 ? ++ab : --ab) {
+ centroids.push(min + (i / num) * (max - min));
+ }
+ centroids.push(max);
+ while (repeat) {
+ for (j = ac = 0, ref4 = num - 1; 0 <= ref4 ? ac <= ref4 : ac >= ref4; j = 0 <= ref4 ? ++ac : --ac) {
+ clusterSizes[j] = 0;
+ }
+ for (i = ad = 0, ref5 = n - 1; 0 <= ref5 ? ad <= ref5 : ad >= ref5; i = 0 <= ref5 ? ++ad : --ad) {
+ value = values[i];
+ mindist = Number.MAX_VALUE;
+ for (j = ae = 0, ref6 = num - 1; 0 <= ref6 ? ae <= ref6 : ae >= ref6; j = 0 <= ref6 ? ++ae : --ae) {
+ dist = abs(centroids[j] - value);
+ if (dist < mindist) {
+ mindist = dist;
+ best = j;
+ }
+ }
+ clusterSizes[best]++;
+ assignments[i] = best;
+ }
+ newCentroids = new Array(num);
+ for (j = af = 0, ref7 = num - 1; 0 <= ref7 ? af <= ref7 : af >= ref7; j = 0 <= ref7 ? ++af : --af) {
+ newCentroids[j] = null;
+ }
+ for (i = ag = 0, ref8 = n - 1; 0 <= ref8 ? ag <= ref8 : ag >= ref8; i = 0 <= ref8 ? ++ag : --ag) {
+ cluster = assignments[i];
+ if (newCentroids[cluster] === null) {
+ newCentroids[cluster] = values[i];
+ } else {
+ newCentroids[cluster] += values[i];
+ }
+ }
+ for (j = ah = 0, ref9 = num - 1; 0 <= ref9 ? ah <= ref9 : ah >= ref9; j = 0 <= ref9 ? ++ah : --ah) {
+ newCentroids[j] *= 1 / clusterSizes[j];
+ }
+ repeat = false;
+ for (j = ai = 0, ref10 = num - 1; 0 <= ref10 ? ai <= ref10 : ai >= ref10; j = 0 <= ref10 ? ++ai : --ai) {
+ if (newCentroids[j] !== centroids[i]) {
+ repeat = true;
+ break;
+ }
+ }
+ centroids = newCentroids;
+ nb_iters++;
+ if (nb_iters > 200) {
+ repeat = false;
+ }
+ }
+ kClusters = {};
+ for (j = aj = 0, ref11 = num - 1; 0 <= ref11 ? aj <= ref11 : aj >= ref11; j = 0 <= ref11 ? ++aj : --aj) {
+ kClusters[j] = [];
+ }
+ for (i = ak = 0, ref12 = n - 1; 0 <= ref12 ? ak <= ref12 : ak >= ref12; i = 0 <= ref12 ? ++ak : --ak) {
+ cluster = assignments[i];
+ kClusters[cluster].push(values[i]);
+ }
+ tmpKMeansBreaks = [];
+ for (j = al = 0, ref13 = num - 1; 0 <= ref13 ? al <= ref13 : al >= ref13; j = 0 <= ref13 ? ++al : --al) {
+ tmpKMeansBreaks.push(kClusters[j][0]);
+ tmpKMeansBreaks.push(kClusters[j][kClusters[j].length - 1]);
+ }
+ tmpKMeansBreaks = tmpKMeansBreaks.sort(function(a, b) {
+ return a - b;
+ });
+ limits.push(tmpKMeansBreaks[0]);
+ for (i = am = 1, ref14 = tmpKMeansBreaks.length - 1; am <= ref14; i = am += 2) {
+ if (!isNaN(tmpKMeansBreaks[i])) {
+ limits.push(tmpKMeansBreaks[i]);
+ }
+ }
+ }
+ return limits;
+ };
+
+ hsi2rgb = function(h, s, i) {
+
+ /*
+ borrowed from here:
+ http://hummer.stanford.edu/museinfo/doc/examples/humdrum/keyscape2/hsi2rgb.cpp
+ */
+ var args, b, g, r;
+ args = unpack(arguments);
+ h = args[0], s = args[1], i = args[2];
+ h /= 360;
+ if (h < 1 / 3) {
+ b = (1 - s) / 3;
+ r = (1 + s * cos(TWOPI * h) / cos(PITHIRD - TWOPI * h)) / 3;
+ g = 1 - (b + r);
+ } else if (h < 2 / 3) {
+ h -= 1 / 3;
+ r = (1 - s) / 3;
+ g = (1 + s * cos(TWOPI * h) / cos(PITHIRD - TWOPI * h)) / 3;
+ b = 1 - (r + g);
+ } else {
+ h -= 2 / 3;
+ g = (1 - s) / 3;
+ b = (1 + s * cos(TWOPI * h) / cos(PITHIRD - TWOPI * h)) / 3;
+ r = 1 - (g + b);
+ }
+ r = limit(i * r * 3);
+ g = limit(i * g * 3);
+ b = limit(i * b * 3);
+ return [r * 255, g * 255, b * 255, args.length > 3 ? args[3] : 1];
+ };
+
+ rgb2hsi = function() {
+
+ /*
+ borrowed from here:
+ http://hummer.stanford.edu/museinfo/doc/examples/humdrum/keyscape2/rgb2hsi.cpp
+ */
+ var b, g, h, i, min, r, ref, s;
+ ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
+ TWOPI = Math.PI * 2;
+ r /= 255;
+ g /= 255;
+ b /= 255;
+ min = Math.min(r, g, b);
+ i = (r + g + b) / 3;
+ s = 1 - min / i;
+ if (s === 0) {
+ h = 0;
+ } else {
+ h = ((r - g) + (r - b)) / 2;
+ h /= Math.sqrt((r - g) * (r - g) + (r - b) * (g - b));
+ h = Math.acos(h);
+ if (b > g) {
+ h = TWOPI - h;
+ }
+ h /= TWOPI;
+ }
+ return [h * 360, s, i];
+ };
+
+ chroma.hsi = function() {
+ return (function(func, args, ctor) {
+ ctor.prototype = func.prototype;
+ var child = new ctor, result = func.apply(child, args);
+ return Object(result) === result ? result : child;
+ })(Color, slice.call(arguments).concat(['hsi']), function(){});
+ };
+
+ _input.hsi = hsi2rgb;
+
+ Color.prototype.hsi = function() {
+ return rgb2hsi(this._rgb);
+ };
+
+ interpolate_hsx = function(col1, col2, f, m) {
+ var dh, hue, hue0, hue1, lbv, lbv0, lbv1, res, sat, sat0, sat1, xyz0, xyz1;
+ if (m === 'hsl') {
+ xyz0 = col1.hsl();
+ xyz1 = col2.hsl();
+ } else if (m === 'hsv') {
+ xyz0 = col1.hsv();
+ xyz1 = col2.hsv();
+ } else if (m === 'hsi') {
+ xyz0 = col1.hsi();
+ xyz1 = col2.hsi();
+ } else if (m === 'lch' || m === 'hcl') {
+ m = 'hcl';
+ xyz0 = col1.hcl();
+ xyz1 = col2.hcl();
+ }
+ if (m.substr(0, 1) === 'h') {
+ hue0 = xyz0[0], sat0 = xyz0[1], lbv0 = xyz0[2];
+ hue1 = xyz1[0], sat1 = xyz1[1], lbv1 = xyz1[2];
+ }
+ if (!isNaN(hue0) && !isNaN(hue1)) {
+ if (hue1 > hue0 && hue1 - hue0 > 180) {
+ dh = hue1 - (hue0 + 360);
+ } else if (hue1 < hue0 && hue0 - hue1 > 180) {
+ dh = hue1 + 360 - hue0;
+ } else {
+ dh = hue1 - hue0;
+ }
+ hue = hue0 + f * dh;
+ } else if (!isNaN(hue0)) {
+ hue = hue0;
+ if ((lbv1 === 1 || lbv1 === 0) && m !== 'hsv') {
+ sat = sat0;
+ }
+ } else if (!isNaN(hue1)) {
+ hue = hue1;
+ if ((lbv0 === 1 || lbv0 === 0) && m !== 'hsv') {
+ sat = sat1;
+ }
+ } else {
+ hue = Number.NaN;
+ }
+ if (sat == null) {
+ sat = sat0 + f * (sat1 - sat0);
+ }
+ lbv = lbv0 + f * (lbv1 - lbv0);
+ return res = chroma[m](hue, sat, lbv);
+ };
+
+ _interpolators = _interpolators.concat((function() {
+ var len, o, ref, results;
+ ref = ['hsv', 'hsl', 'hsi', 'hcl', 'lch'];
+ results = [];
+ for (o = 0, len = ref.length; o < len; o++) {
+ m = ref[o];
+ results.push([m, interpolate_hsx]);
+ }
+ return results;
+ })());
+
+ interpolate_num = function(col1, col2, f, m) {
+ var n1, n2;
+ n1 = col1.num();
+ n2 = col2.num();
+ return chroma.num(n1 + (n2 - n1) * f, 'num');
+ };
+
+ _interpolators.push(['num', interpolate_num]);
+
+ interpolate_lab = function(col1, col2, f, m) {
+ var res, xyz0, xyz1;
+ xyz0 = col1.lab();
+ xyz1 = col2.lab();
+ return res = new Color(xyz0[0] + f * (xyz1[0] - xyz0[0]), xyz0[1] + f * (xyz1[1] - xyz0[1]), xyz0[2] + f * (xyz1[2] - xyz0[2]), m);
+ };
+
+ _interpolators.push(['lab', interpolate_lab]);
+
+}).call(this); \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/js_external/jstat.min.js b/wqflask/wqflask/static/new/js_external/jstat.min.js
new file mode 100644
index 00000000..28de9c1a
--- /dev/null
+++ b/wqflask/wqflask/static/new/js_external/jstat.min.js
@@ -0,0 +1,2 @@
+this.j$=this.jStat=function(a,b){function f(b,c){var d=b>c?b:c;return a.pow(10,17-~~(a.log(d>0?d:-d)*a.LOG10E))}function h(a){return e.call(a)==="[object Function]"}function i(a){return typeof a=="number"&&a===a}function j(a){return c.apply([],a)}function k(){return new k._init(arguments)}function l(){return 0}function m(){return 1}function n(a,b){return a===b?1:0}var c=Array.prototype.concat,d=Array.prototype.slice,e=Object.prototype.toString,g=Array.isArray||function(b){return e.call(b)==="[object Array]"};k.fn=k.prototype,k._init=function(b){var c;if(g(b[0]))if(g(b[0][0])){h(b[1])&&(b[0]=k.map(b[0],b[1]));for(c=0;c<b[0].length;c++)this[c]=b[0][c];this.length=b[0].length}else this[0]=h(b[1])?k.map(b[0],b[1]):b[0],this.length=1;else if(i(b[0]))this[0]=k.seq.apply(null,b),this.length=1;else{if(b[0]instanceof k)return k(b[0].toArray());this[0]=[],this.length=1}return this},k._init.prototype=k.prototype,k._init.constructor=k,k.utils={calcRdx:f,isArray:g,isFunction:h,isNumber:i,toVector:j},k.extend=function(b){var c,d;if(arguments.length===1){for(d in b)k[d]=b[d];return this}for(c=1;c<arguments.length;c++)for(d in arguments[c])b[d]=arguments[c][d];return b},k.rows=function(b){return b.length||1},k.cols=function(b){return b[0].length||1},k.dimensions=function(b){return{rows:k.rows(b),cols:k.cols(b)}},k.row=function(b,c){return b[c]},k.col=function(b,c){var d=new Array(b.length);for(var e=0;e<b.length;e++)d[e]=[b[e][c]];return d},k.diag=function(b){var c=k.rows(b),d=new Array(c);for(var e=0;e<c;e++)d[e]=[b[e][e]];return d},k.antidiag=function(b){var c=k.rows(b)-1,d=new Array(c);for(var e=0;c>=0;c--,e++)d[e]=[b[e][c]];return d},k.transpose=function(b){var c=[],d,e,f,h,i;g(b[0])||(b=[b]),e=b.length,f=b[0].length;for(i=0;i<f;i++){d=new Array(e);for(h=0;h<e;h++)d[h]=b[h][i];c.push(d)}return c.length===1?c[0]:c},k.map=function(b,c,d){var e,f,h,i,j;g(b[0])||(b=[b]),f=b.length,h=b[0].length,i=d?b:new Array(f);for(e=0;e<f;e++){i[e]||(i[e]=new Array(h));for(j=0;j<h;j++)i[e][j]=c(b[e][j],e,j)}return i.length===1?i[0]:i},k.cumreduce=function(b,c,d){var e,f,h,i,j;g(b[0])||(b=[b]),f=b.length,h=b[0].length,i=d?b:new Array(f);for(e=0;e<f;e++){i[e]||(i[e]=new Array(h)),h>0&&(i[e][0]=b[e][0]);for(j=1;j<h;j++)i[e][j]=c(i[e][j-1],b[e][j])}return i.length===1?i[0]:i},k.alter=function(b,c){return k.map(b,c,!0)},k.create=function(b,c,d){var e=new Array(b),f,g;h(c)&&(d=c,c=b);for(f=0;f<b;f++){e[f]=new Array(c);for(g=0;g<c;g++)e[f][g]=d(f,g)}return e},k.zeros=function(b,c){return i(c)||(c=b),k.create(b,c,l)},k.ones=function(b,c){return i(c)||(c=b),k.create(b,c,m)},k.rand=function(c,d){return i(d)||(d=c),k.create(c,d,a.random)},k.identity=function(b,c){return i(c)||(c=b),k.create(b,c,n)},k.symmetric=function(b){var c=!0,d=b.length,e,f;if(b.length!==b[0].length)return!1;for(e=0;e<d;e++)for(f=0;f<d;f++)if(b[f][e]!==b[e][f])return!1;return!0},k.clear=function(b){return k.alter(b,l)},k.seq=function(b,c,d,e){h(e)||(e=!1);var g=[],i=f(b,c),j=(c*i-b*i)/((d-1)*i),k=b,l;for(l=0;k<=c;l++,k=(b*i+j*i*l)/i)g.push(e?e(k,l):k);return g};var o=k.prototype;return o.length=0,o.push=Array.prototype.push,o.sort=Array.prototype.sort,o.splice=Array.prototype.splice,o.slice=Array.prototype.slice,o.toArray=function(){return this.length>1?d.call(this):d.call(this)[0]},o.map=function(b,c){return k(k.map(this,b,c))},o.cumreduce=function(b,c){return k(k.cumreduce(this,b,c))},o.alter=function(b){return k.alter(this,b),this},function(a){for(var b=0;b<a.length;b++)(function(a){o[a]=function(b){var c=this,d;return b?(setTimeout(function(){b.call(c,o[a].call(c))}),this):(d=k[a](this),g(d)?k(d):d)}})(a[b])}("transpose clear symmetric rows cols dimensions diag antidiag".split(" ")),function(a){for(var b=0;b<a.length;b++)(function(a){o[a]=function(b,c){var d=this;return c?(setTimeout(function(){c.call(d,o[a].call(d,b))}),this):k(k[a](this,b))}})(a[b])}("row col".split(" ")),function(a){for(var b=0;b<a.length;b++)(function(a){o[a]=new Function("return jStat(jStat."+a+".apply(null, arguments));")})(a[b])}("create zeros ones rand identity".split(" ")),k}(Math),function(a,b){function d(a,b){return a-b}function e(a,c,d){return b.max(c,b.min(a,d))}var c=a.utils.isFunction;a.sum=function g(a){var g=0,b=a.length,c;while(--b>=0)g+=a[b];return g},a.sumsqrd=function(b){var c=0,d=b.length;while(--d>=0)c+=b[d]*b[d];return c},a.sumsqerr=function(c){var d=a.mean(c),e=0,f=c.length,g;while(--f>=0)g=c[f]-d,e+=g*g;return e},a.product=function(b){var c=1,d=b.length;while(--d>=0)c*=b[d];return c},a.min=function(b){var c=b[0],d=0;while(++d<b.length)b[d]<c&&(c=b[d]);return c},a.max=function(b){var c=b[0],d=0;while(++d<b.length)b[d]>c&&(c=b[d]);return c},a.mean=function(c){return a.sum(c)/c.length},a.meansqerr=function(c){return a.sumsqerr(c)/c.length},a.geomean=function(d){return b.pow(a.product(d),1/d.length)},a.median=function(b){var c=b.length,e=b.slice().sort(d);return c&1?e[c/2|0]:(e[c/2-1]+e[c/2])/2},a.cumsum=function(c){return a.cumreduce(c,function(a,b){return a+b})},a.cumprod=function(c){return a.cumreduce(c,function(a,b){return a*b})},a.diff=function(b){var c=[],d=b.length,e;for(e=1;e<d;e++)c.push(b[e]-b[e-1]);return c},a.mode=function(b){var c=b.length,e=b.slice().sort(d),f=1,g=0,h=0,i=[],j;for(j=0;j<c;j++)e[j]===e[j+1]?f++:(f>g?(i=[e[j]],g=f,h=0):f===g&&(i.push(e[j]),h++),f=1);return h===0?i[0]:i},a.range=function(c){return a.max(c)-a.min(c)},a.variance=function(c,d){return a.sumsqerr(c)/(c.length-(d?1:0))},a.stdev=function(d,e){return b.sqrt(a.variance(d,e))},a.meandev=function(d){var e=0,f=a.mean(d),g;for(g=d.length-1;g>=0;g--)e+=b.abs(d[g]-f);return e/d.length},a.meddev=function(d){var e=0,f=a.median(d),g;for(g=d.length-1;g>=0;g--)e+=b.abs(d[g]-f);return e/d.length},a.coeffvar=function(c){return a.stdev(c)/a.mean(c)},a.quartiles=function(c){var e=c.length,f=c.slice().sort(d);return[f[b.round(e/4)-1],f[b.round(e/2)-1],f[b.round(e*3/4)-1]]},a.quantiles=function(c,f,g,h){var i=c.slice().sort(d),j=[f.length],k=c.length,l,m,n,o,p,q;typeof g=="undefined"&&(g=3/8),typeof h=="undefined"&&(h=3/8);for(l=0;l<f.length;l++)m=f[l],n=g+m*(1-g-h),o=k*m+n,p=b.floor(e(o,1,k-1)),q=e(o-p,0,1),j[l]=(1-q)*i[p-1]+q*i[p];return j},a.percentileOfScore=function(b,c,d){var e=0,f=b.length,g=!1,h,i;d==="strict"&&(g=!0);for(i=0;i<f;i++)h=b[i],(g&&h<c||!g&&h<=c)&&e++;return e/f},a.histogram=function(d,e){var f=a.min(d),g=e||4,h=(a.max(d)-f)/g,i=d.length,e=[],j;for(j=0;j<g;j++)e[j]=0;for(j=0;j<i;j++)e[b.min(b.floor((d[j]-f)/h),g-1)]+=1;return e},a.covariance=function(c,d){var e=a.mean(c),f=a.mean(d),g=c.length,h=new Array(g),i;for(i=0;i<g;i++)h[i]=(c[i]-e)*(d[i]-f);return a.sum(h)/(g-1)},a.corrcoeff=function(c,d){return a.covariance(c,d)/a.stdev(c,1)/a.stdev(d,1)},a.stanMoment=function(d,e){var f=a.mean(d),g=a.stdev(d),h=d.length,j=0;for(i=0;i<h;i++)j+=b.pow((d[i]-f)/g,e);return j/d.length},a.skewness=function(c){return a.stanMoment(c,3)},a.kurtosis=function(c){return a.stanMoment(c,4)-3};var f=a.prototype;(function(b){for(var d=0;d<b.length;d++)(function(b){f[b]=function(d,e){var g=[],h=0,i=this;c(d)&&(e=d,d=!1);if(e)return setTimeout(function(){e.call(i,f[b].call(i,d))}),this;if(this.length>1){i=d===!0?this:this.transpose();for(;h<i.length;h++)g[h]=a[b](i[h]);return g}return a[b](this[0],d)}})(b[d])})("cumsum cumprod".split(" ")),function(b){for(var d=0;d<b.length;d++)(function(b){f[b]=function(d,e){var g=[],h=0,i=this;c(d)&&(e=d,d=!1);if(e)return setTimeout(function(){e.call(i,f[b].call(i,d))}),this;if(this.length>1){i=d===!0?this:this.transpose();for(;h<i.length;h++)g[h]=a[b](i[h]);return d===!0?a[b](a.utils.toVector(g)):g}return a[b](this[0],d)}})(b[d])}("sum sumsqrd sumsqerr product min max mean meansqerr geomean median diff mode range variance stdev meandev meddev coeffvar quartiles histogram skewness kurtosis".split(" ")),function(b){for(var d=0;d<b.length;d++)(function(b){f[b]=function(){var d=[],e=0,g=this,h=Array.prototype.slice.call(arguments);if(c(h[h.length-1])){var i=h[h.length-1],j=h.slice(0,h.length-1);return setTimeout(function(){i.call(g,f[b].apply(g,j))}),this}var i=undefined,k=function(d){return a[b].apply(g,[d].concat(h))};if(this.length>1){g=g.transpose();for(;e<g.length;e++)d[e]=k(g[e]);return d}return k(this[0])}})(b[d])}("quantiles percentileOfScore".split(" "))}(this.jStat,Math),function(a,b){a.gammaln=function(c){var d=0,e=[76.18009172947146,-86.50532032941678,24.01409824083091,-1.231739572450155,.001208650973866179,-0.000005395239384953],f=1.000000000190015,g,h,i;i=(h=g=c)+5.5,i-=(g+.5)*b.log(i);for(;d<6;d++)f+=e[d]/++h;return b.log(2.5066282746310007*f/g)-i},a.gammafn=function(c){var d=[-1.716185138865495,24.76565080557592,-379.80425647094563,629.3311553128184,866.9662027904133,-31451.272968848367,-36144.413418691176,66456.14382024054],e=[-30.8402300119739,315.35062697960416,-1015.1563674902192,-3107.771671572311,22538.11842098015,4755.846277527881,-134659.9598649693,-115132.2596755535],f=!1,g=0,h=0,i=0,j=c,k,l,m,n,o,p;if(j<=0){n=j%1+3.6e-16;if(n)f=(j&1?-1:1)*b.PI/b.sin(b.PI*n),j=1-j;else return Infinity}m=j,j<1?l=j++:l=(j-=g=(j|0)-1)-1;for(k=0;k<8;++k)i=(i+d[k])*l,h=h*l+e[k];n=i/h+1;if(m<j)n/=m;else if(m>j)for(k=0;k<g;++k)n*=j,j++;return f&&(n=f/n),n},a.gammap=function(c,d){return a.lowRegGamma(c,d)*a.gammafn(c)},a.lowRegGamma=function(d,e){var f=a.gammaln(d),g=d,h=1/d,i=h,j=e+1-d,k=1/1e-30,l=1/j,m=l,n=1,o=-~(b.log(d>=1?d:1/d)*8.5+d*.4+17),p,q;if(e<0||d<=0)return NaN;if(e<d+1){for(;n<=o;n++)h+=i*=e/++g;return h*b.exp(-e+d*b.log(e)-f)}for(;n<=o;n++)p=-n*(n-d),j+=2,l=p*l+j,k=j+p/k,l=1/l,m*=l*k;return 1-m*b.exp(-e+d*b.log(e)-f)},a.factorialln=function(c){return c<0?NaN:a.gammaln(c+1)},a.factorial=function(c){return c<0?NaN:a.gammafn(c+1)},a.combination=function(d,e){return d>170||e>170?b.exp(a.combinationln(d,e)):a.factorial(d)/a.factorial(e)/a.factorial(d-e)},a.combinationln=function(c,d){return a.factorialln(c)-a.factorialln(d)-a.factorialln(c-d)},a.permutation=function(c,d){return a.factorial(c)/a.factorial(c-d)},a.betafn=function(d,e){return d<=0||e<=0?undefined:d+e>170?b.exp(a.betaln(d,e)):a.gammafn(d)*a.gammafn(e)/a.gammafn(d+e)},a.betaln=function(c,d){return a.gammaln(c)+a.gammaln(d)-a.gammaln(c+d)},a.betacf=function(c,d,e){var f=1e-30,g=1,h=d+e,i=d+1,j=d-1,k=1,l=1-h*c/i,m,n,o,p;b.abs(l)<f&&(l=f),l=1/l,p=l;for(;g<=100;g++){m=2*g,n=g*(e-g)*c/((j+m)*(d+m)),l=1+n*l,b.abs(l)<f&&(l=f),k=1+n/k,b.abs(k)<f&&(k=f),l=1/l,p*=l*k,n=-(d+g)*(h+g)*c/((d+m)*(i+m)),l=1+n*l,b.abs(l)<f&&(l=f),k=1+n/k,b.abs(k)<f&&(k=f),l=1/l,o=l*k,p*=o;if(b.abs(o-1)<3e-7)break}return p},a.gammapinv=function(d,e){var f=0,g=e-1,h=1e-8,i=a.gammaln(e),j,k,l,m,n,o,p;if(d>=1)return b.max(100,e+100*b.sqrt(e));if(d<=0)return 0;e>1?(o=b.log(g),p=b.exp(g*(o-1)-i),n=d<.5?d:1-d,l=b.sqrt(-2*b.log(n)),j=(2.30753+l*.27061)/(1+l*(.99229+l*.04481))-l,d<.5&&(j=-j),j=b.max(.001,e*b.pow(1-1/(9*e)-j/(3*b.sqrt(e)),3))):(l=1-e*(.253+e*.12),d<l?j=b.pow(d/l,1/e):j=1-b.log(1-(d-l)/(1-l)));for(;f<12;f++){if(j<=0)return 0;k=a.lowRegGamma(e,j)-d,e>1?l=p*b.exp(-(j-g)+g*(b.log(j)-o)):l=b.exp(-j+g*b.log(j)-i),m=k/l,j-=l=m/(1-.5*b.min(1,m*((e-1)/j-1))),j<=0&&(j=.5*(j+l));if(b.abs(l)<h*j)break}return j},a.erf=function(c){var d=[-1.3026537197817094,.6419697923564902,.019476473204185836,-0.00956151478680863,-0.000946595344482036,.000366839497852761,42523324806907e-18,-0.000020278578112534,-0.000001624290004647,130365583558e-17,1.5626441722e-8,-8.5238095915e-8,6.529054439e-9,5.059343495e-9,-9.91364156e-10,-2.27365122e-10,9.6467911e-11,2.394038e-12,-6.886027e-12,8.94487e-13,3.13092e-13,-1.12708e-13,3.81e-16,7.106e-15,-1.523e-15,-9.4e-17,1.21e-16,-2.8e-17],e=d.length-1,f=!1,g=0,h=0,i,j,k,l;c<0&&(c=-c,f=!0),i=2/(2+c),j=4*i-2;for(;e>0;e--)k=g,g=j*g-h+d[e],h=k;return l=i*b.exp(-c*c+.5*(d[0]+j*g)-h),f?l-1:1-l},a.erfc=function(c){return 1-a.erf(c)},a.erfcinv=function(d){var e=0,f,g,h,i;if(d>=2)return-100;if(d<=0)return 100;i=d<1?d:2-d,h=b.sqrt(-2*b.log(i/2)),f=-0.70711*((2.30753+h*.27061)/(1+h*(.99229+h*.04481))-h);for(;e<2;e++)g=a.erfc(f)-i,f+=g/(1.1283791670955126*b.exp(-f*f)-f*g);return d<1?f:-f},a.ibetainv=function(d,e,f){var g=1e-8,h=e-1,i=f-1,j=0,k,l,m,n,o,p,q,r,s,t,u;if(d<=0)return 0;if(d>=1)return 1;e>=1&&f>=1?(m=d<.5?d:1-d,n=b.sqrt(-2*b.log(m)),q=(2.30753+n*.27061)/(1+n*(.99229+n*.04481))-n,d<.5&&(q=-q),r=(q*q-3)/6,s=2/(1/(2*e-1)+1/(2*f-1)),t=q*b.sqrt(r+s)/s-(1/(2*f-1)-1/(2*e-1))*(r+5/6-2/(3*s)),q=e/(e+f*b.exp(2*t))):(k=b.log(e/(e+f)),l=b.log(f/(e+f)),n=b.exp(e*k)/e,o=b.exp(f*l)/f,t=n+o,d<n/t?q=b.pow(e*t*d,1/e):q=1-b.pow(f*t*(1-d),1/f)),u=-a.gammaln(e)-a.gammaln(f)+a.gammaln(e+f);for(;j<10;j++){if(q===0||q===1)return q;p=a.ibeta(q,e,f)-d,n=b.exp(h*b.log(q)+i*b.log(1-q)+u),o=p/n,q-=n=o/(1-.5*b.min(1,o*(h/q-i/(1-q)))),q<=0&&(q=.5*(q+n)),q>=1&&(q=.5*(q+n+1));if(b.abs(n)<g*q&&j>0)break}return q},a.ibeta=function(d,e,f){var g=d===0||d===1?0:b.exp(a.gammaln(e+f)-a.gammaln(e)-a.gammaln(f)+e*b.log(d)+f*b.log(1-d));return d<0||d>1?!1:d<(e+1)/(e+f+2)?g*a.betacf(d,e,f)/e:1-g*a.betacf(1-d,f,e)/f},a.randn=function(d,e){var f,g,h,i,j,k;e||(e=d);if(d)return a.create(d,e,function(){return a.randn()});do f=b.random(),g=1.7156*(b.random()-.5),h=f-.449871,i=b.abs(g)+.386595,j=h*h+i*(.196*i-.25472*h);while(j>.27597&&(j>.27846||g*g>-4*b.log(f)*f*f));return g/f},a.randg=function(d,e,f){var g=d,h,i,j,k,l,m;f||(f=e),d||(d=1);if(e)return m=a.zeros(e,f),m.alter(function(){return a.randg(d)}),m;d<1&&(d+=1),h=d-1/3,i=1/b.sqrt(9*h);do{do l=a.randn(),k=1+i*l;while(k<=0);k=k*k*k,j=b.random()}while(j>1-.331*b.pow(l,4)&&b.log(j)>.5*l*l+h*(1-k+b.log(k)));if(d==g)return h*k;do j=b.random();while(j===0);return b.pow(j,1/g)*h*k},function(b){for(var c=0;c<b.length;c++)(function(b){a.fn[b]=function(){return a(a.map(this,function(c){return a[b](c)}))}})(b[c])}("gammaln gammafn factorial factorialln".split(" ")),function(b){for(var c=0;c<b.length;c++)(function(b){a.fn[b]=function(){return a(a[b].apply(null,arguments))}})(b[c])}("randn".split(" "))}(this.jStat,Math),function(a,b){(function(b){for(var c=0;c<b.length;c++)(function(b){a[b]=function(a,b,c){return this instanceof arguments.callee?(this._a=a,this._b=b,this._c=c,this):new arguments.callee(a,b,c)},a.fn[b]=function(c,d,e){var f=a[b](c,d,e);return f.data=this,f},a[b].prototype.sample=function(c){var d=this._a,e=this._b,f=this._c;return c?a.alter(c,function(){return a[b].sample(d,e,f)}):a[b].sample(d,e,f)},function(c){for(var d=0;d<c.length;d++)(function(c){a[b].prototype[c]=function(d){var e=this._a,f=this._b,g=this._c;return!d&&d!==0&&(d=this.data),typeof d!="number"?a.fn.map.call(d,function(d){return a[b][c](d,e,f,g)}):a[b][c](d,e,f,g)}})(c[d])}("pdf cdf inv".split(" ")),function(c){for(var d=0;d<c.length;d++)(function(c){a[b].prototype[c]=function(){return a[b][c](this._a,this._b,this._c)}})(c[d])}("mean median mode variance".split(" "))})(b[c])})("beta centralF cauchy chisquare exponential gamma invgamma kumaraswamy lognormal noncentralt normal pareto studentt weibull uniform binomial negbin hypgeom poisson triangular".split(" ")),a.extend(a.beta,{pdf:function(d,e,f){return d>1||d<0?0:e==1&&f==1?1:e<512||f<512?b.pow(d,e-1)*b.pow(1-d,f-1)/a.betafn(e,f):b.exp((e-1)*b.log(d)+(f-1)*b.log(1-d)-a.betaln(e,f))},cdf:function(c,d,e){return c>1||c<0?(c>1)*1:a.ibeta(c,d,e)},inv:function(c,d,e){return a.ibetainv(c,d,e)},mean:function(b,c){return b/(b+c)},median:function(b,c){throw new Error("median not yet implemented")},mode:function(b,c){return(b-1)/(b+c-2)},sample:function(c,d){var e=a.randg(c);return e/(e+a.randg(d))},variance:function(c,d){return c*d/(b.pow(c+d,2)*(c+d+1))}}),a.extend(a.centralF,{pdf:function(d,e,f){var g,h,i;return d<0?undefined:e<=2?e===1&&f===1?Infinity:e===2&&f===1?1:b.sqrt(b.pow(e*d,e)*b.pow(f,f)/b.pow(e*d+f,e+f))/(d*a.betafn(e/2,f/2)):(g=e*d/(f+d*e),h=f/(f+d*e),i=e*h/2,i*a.binomial.pdf((e-2)/2,(e+f-2)/2,g))},cdf:function(c,d,e){return a.ibeta(d*c/(d*c+e),d/2,e/2)},inv:function(c,d,e){return e/(d*(1/a.ibetainv(c,d/2,e/2)-1))},mean:function(b,c){return c>2?c/(c-2):undefined},mode:function(b,c){return b>2?c*(b-2)/(b*(c+2)):undefined},sample:function(c,d){var e=a.randg(c/2)*2,f=a.randg(d/2)*2;return e/c/(f/d)},variance:function(b,c){return c<=4?undefined:2*c*c*(b+c-2)/(b*(c-2)*(c-2)*(c-4))}}),a.extend(a.cauchy,{pdf:function(c,d,e){return e/(b.pow(c-d,2)+b.pow(e,2))/b.PI},cdf:function(c,d,e){return b.atan((c-d)/e)/b.PI+.5},inv:function(a,c,d){return c+d*b.tan(b.PI*(a-.5))},median:function(b,c){return b},mode:function(b,c){return b},sample:function(d,e){return a.randn()*b.sqrt(1/(2*a.randg(.5)))*e+d}}),a.extend(a.chisquare,{pdf:function(d,e){return d===0?0:b.exp((e/2-1)*b.log(d)-d/2-e/2*b.log(2)-a.gammaln(e/2))},cdf:function(c,d){return a.lowRegGamma(d/2,c/2)},inv:function(b,c){return 2*a.gammapinv(b,.5*c)},mean:function(a){return a},median:function(c){return c*b.pow(1-2/(9*c),3)},mode:function(b){return b-2>0?b-2:0},sample:function(c){return a.randg(c/2)*2},variance:function(b){return 2*b}}),a.extend(a.exponential,{pdf:function(c,d){return c<0?0:d*b.exp(-d*c)},cdf:function(c,d){return c<0?0:1-b.exp(-d*c)},inv:function(a,c){return-b.log(1-a)/c},mean:function(a){return 1/a},median:function(a){return 1/a*b.log(2)},mode:function(b){return 0},sample:function(c){return-1/c*b.log(b.random())},variance:function(a){return b.pow(a,-2)}}),a.extend(a.gamma,{pdf:function(d,e,f){return b.exp((e-1)*b.log(d)-d/f-a.gammaln(e)-e*b.log(f))},cdf:function(c,d,e){return a.lowRegGamma(d,c/e)},inv:function(b,c,d){return a.gammapinv(b,c)*d},mean:function(a,b){return a*b},mode:function(b,c){return b>1?(b-1)*c:undefined},sample:function(c,d){return a.randg(c)*d},variance:function(b,c){return b*c*c}}),a.extend(a.invgamma,{pdf:function(d,e,f){return b.exp(-(e+1)*b.log(d)-f/d-a.gammaln(e)+e*b.log(f))},cdf:function(c,d,e){return 1-a.lowRegGamma(d,e/c)},inv:function(b,c,d){return d/a.gammapinv(1-b,c)},mean:function(a,b){return a>1?b/(a-1):undefined},mode:function(b,c){return c/(b+1)},sample:function(c,d){return d/a.randg(c)},variance:function(b,c){return b<=2?undefined:c*c/((b-1)*(b-1)*(b-2))}}),a.extend(a.kumaraswamy,{pdf:function(c,d,e){return b.exp(b.log(d)+b.log(e)+(d-1)*b.log(c)+(e-1)*b.log(1-b.pow(c,d)))},cdf:function(c,d,e){return 1-b.pow(1-b.pow(c,d),e)},mean:function(b,c){return c*a.gammafn(1+1/b)*a.gammafn(c)/a.gammafn(1+1/b+c)},median:function(c,d){return b.pow(1-b.pow(2,-1/d),1/c)},mode:function(c,d){return c>=1&&d>=1&&c!==1&&d!==1?b.pow((c-1)/(c*d-1),1/c):undefined},variance:function(b,c){throw new Error("variance not yet implemented")}}),a.extend(a.lognormal,{pdf:function(c,d,e){return b.exp(-b.log(c)-.5*b.log(2*b.PI)-b.log(e)-b.pow(b.log(c)-d,2)/(2*e*e))},cdf:function(d,e,f){return.5+.5*a.erf((b.log(d)-e)/b.sqrt(2*f*f))},inv:function(c,d,e){return b.exp(-1.4142135623730951*e*a.erfcinv(2*c)+d)},mean:function(c,d){return b.exp(c+d*d/2)},median:function(c,d){return b.exp(c)},mode:function(c,d){return b.exp(c-d*d)},sample:function(d,e){return b.exp(a.randn()*e+d)},variance:function(c,d){return(b.exp(d*d)-1)*b.exp(2*c+d*d)}}),a.extend(a.noncentralt,{pdf:function(d,e,f){var g=1e-14;return b.abs(f)<g?a.studentt.pdf(d,e):b.abs(d)<g?b.exp(a.gammaln((e+1)/2)-f*f/2-.5*b.log(b.PI*e)-a.gammaln(e/2)):e/d*(a.noncentralt.cdf(d*b.sqrt(1+2/e),e+2,f)-a.noncentralt.cdf(d,e,f))},cdf:function(d,e,f){var g=1e-14,h=200;if(b.abs(f)<g)return a.studentt.cdf(d,e);var i=!1;d<0&&(i=!0,f=-f);var j=a.normal.cdf(-f,0,1),k=g+1,l=k,m=d*d/(d*d+e),n=0,o=b.exp(-f*f/2),p=b.exp(-f*f/2-.5*b.log(2)-a.gammaln(1.5))*f;while(n<h||l>g||k>g)l=k,n>0&&(o*=f*f/(2*n),p*=f*f/(2*(n+.5))),k=o*a.beta.cdf(m,n+.5,e/2)+p*a.beta.cdf(m,n+1,e/2),j+=.5*k,n++;return i?1-j:j}}),a.extend(a.normal,{pdf:function(c,d,e){return b.exp(-0.5*b.log(2*b.PI)-b.log(e)-b.pow(c-d,2)/(2*e*e))},cdf:function(d,e,f){return.5*(1+a.erf((d-e)/b.sqrt(2*f*f)))},inv:function(b,c,d){return-1.4142135623730951*d*a.erfcinv(2*b)+c},mean:function(a,b){return a},median:function(b,c){return b},mode:function(a,b){return a},sample:function(c,d){return a.randn()*d+c},variance:function(a,b){return b*b}}),a.extend(a.pareto,{pdf:function(c,d,e){return c<d?undefined:e*b.pow(d,e)/b.pow(c,e+1)},cdf:function(c,d,e){return 1-b.pow(d/c,e)},mean:function(c,d){return d<=1?undefined:d*b.pow(c,d)/(d-1)},median:function(c,d){return c*d*b.SQRT2},mode:function(b,c){return b},variance:function(a,c){return c<=2?undefined:a*a*c/(b.pow(c-1,2)*(c-2))}}),a.extend(a.studentt,{pdf:function(d,e){return e=e>1e+100?1e+100:e,1/(b.sqrt(e)*a.betafn(.5,e/2))*b.pow(1+d*d/e,-((e+1)/2))},cdf:function(d,e){var f=e/2;return a.ibeta((d+b.sqrt(d*d+e))/(2*b.sqrt(d*d+e)),f,f)},inv:function(c,d){var e=a.ibetainv(2*b.min(c,1-c),.5*d,.5);return e=b.sqrt(d*(1-e)/e),c>.5?e:-e},mean:function(b){return b>1?0:undefined},median:function(b){return 0},mode:function(b){return 0},sample:function(d){return a.randn()*b.sqrt(d/(2*a.randg(d/2)))},variance:function(b){return b>2?b/(b-2):b>1?Infinity:undefined}}),a.extend(a.weibull,{pdf:function(c,d,e){return c<0?0:e/d*b.pow(c/d,e-1)*b.exp(-b.pow(c/d,e))},cdf:function(c,d,e){return c<0?0:1-b.exp(-b.pow(c/d,e))},inv:function(a,c,d){return c*b.pow(-b.log(1-a),1/d)},mean:function(b,c){return b*a.gammafn(1+1/c)},median:function(c,d){return c*b.pow(b.log(2),1/d)},mode:function(c,d){return d<=1?undefined:c*b.pow((d-1)/d,1/d)},sample:function(c,d){return c*b.pow(-b.log(b.random()),1/d)},variance:function(d,e){return d*d*a.gammafn(1+2/e)-b.pow(this.mean(d,e),2)}}),a.extend(a.uniform,{pdf:function(b,c,d){return b<c||b>d?0:1/(d-c)},cdf:function(b,c,d){return b<c?0:b<d?(b-c)/(d-c):1},inv:function(a,b,c){return b+a*(c-b)},mean:function(b,c){return.5*(b+c)},median:function(c,d){return a.mean(c,d)},mode:function(b,c){throw new Error("mode is not yet implemented")},sample:function(c,d){return c/2+d/2+(d/2-c/2)*(2*b.random()-1)},variance:function(c,d){return b.pow(d-c,2)/12}}),a.extend(a.binomial,{pdf:function(d,e,f){return f===0||f===1?e*f===d?1:0:a.combination(e,d)*b.pow(f,d)*b.pow(1-f,e-d)},cdf:function(c,d,e){var f=[],g=0;if(c<0)return 0;if(c<d){for(;g<=c;g++)f[g]=a.binomial.pdf(g,d,e);return a.sum(f)}return 1}}),a.extend(a.negbin,{pdf:function(d,e,f){return d!==d|0?!1:d<0?0:a.combination(d+e-1,e-1)*b.pow(1-f,d)*b.pow(f,e)},cdf:function(c,d,e){var f=0,g=0;if(c<0)return 0;for(;g<=c;g++)f+=a.negbin.pdf(g,d,e);return f}}),a.extend(a.hypgeom,{pdf:function(d,e,f,g){if(d!==d|0)return!1;if(d<0||d<f-(e-g))return 0;if(d>g||d>f)return 0;if(f*2>e)return g*2>e?a.hypgeom.pdf(e-f-g+d,e,e-f,e-g):a.hypgeom.pdf(g-d,e,e-f,g);if(g*2>e)return a.hypgeom.pdf(f-d,e,f,e-g);if(f<g)return a.hypgeom.pdf(d,e,g,f);var h=1,i=0;for(var j=0;j<d;j++){while(h>1&&i<g)h*=1-f/(e-i),i++;h*=(g-j)*(f-j)/((j+1)*(e-f-g+j+1))}for(;i<g;i++)h*=1-f/(e-i);return b.min(1,b.max(0,h))},cdf:function(d,e,f,g){if(d<0||d<f-(e-g))return 0;if(d>=g||d>=f)return 1;if(f*2>e)return g*2>e?a.hypgeom.cdf(e-f-g+d,e,e-f,e-g):1-a.hypgeom.cdf(g-d-1,e,e-f,g);if(g*2>e)return 1-a.hypgeom.cdf(f-d-1,e,f,e-g);if(f<g)return a.hypgeom.cdf(d,e,g,f);var h=1,i=1,j=0;for(var k=0;k<d;k++){while(h>1&&j<g){var l=1-f/(e-j);i*=l,h*=l,j++}i*=(g-k)*(f-k)/((k+1)*(e-f-g+k+1)),h+=i}for(;j<g;j++)h*=1-f/(e-j);return b.min(1,b.max(0,h))}}),a.extend(a.poisson,{pdf:function(d,e){return b.pow(e,d)*b.exp(-e)/a.factorial(d)},cdf:function(c,d){var e=[],f=0;if(c<0)return 0;for(;f<=c;f++)e.push(a.poisson.pdf(f,d));return a.sum(e)},mean:function(a){return a},variance:function(a){return a},sample:function(c){var d=1,e=0,f=b.exp(-c);do e++,d*=b.random();while(d>f);return e-1}}),a.extend(a.triangular,{pdf:function(b,c,d,e){return d<=c||e<c||e>d?undefined:b<c||b>d?0:b<=e?e===c?1:2*(b-c)/((d-c)*(e-c)):e===d?1:2*(d-b)/((d-c)*(d-e))},cdf:function(c,d,e,f){return e<=d||f<d||f>e?undefined:c<d?0:c<=f?b.pow(c-d,2)/((e-d)*(f-d)):1-b.pow(e-c,2)/((e-d)*(e-f))},mean:function(b,c,d){return(b+c+d)/3},median:function(c,d,e){if(e<=(c+d)/2)return d-b.sqrt((d-c)*(d-e))/b.sqrt(2);if(e>(c+d)/2)return c+b.sqrt((d-c)*(e-c))/b.sqrt(2)},mode:function(b,c,d){return d},sample:function(c,d,e){var f=b.random();return f<(e-c)/(d-c)?c+b.sqrt(f*(d-c)*(e-c)):d-b.sqrt((1-f)*(d-c)*(d-e))},variance:function(b,c,d){return(b*b+c*c+d*d-b*c-b*d-c*d)/18}})}(this.jStat,Math),function(a,b){var d=Array.prototype.push,e=a.utils.isArray;a.extend({add:function(c,d){return e(d)?(e(d[0])||(d=[d]),a.map(c,function(a,b,c){return a+d[b][c]})):a.map(c,function(a){return a+d})},subtract:function(c,d){return e(d)?(e(d[0])||(d=[d]),a.map(c,function(a,b,c){return a-d[b][c]||0})):a.map(c,function(a){return a-d})},divide:function(c,d){return e(d)?(e(d[0])||(d=[d]),a.multiply(c,a.inv(d))):a.map(c,function(a){return a/d})},multiply:function(c,d){var f,g,h,i,j=c.length,k=c[0].length,l=a.zeros(j,h=e(d)?d[0].length:k),m=0;if(e(d)){for(;m<h;m++)for(f=0;f<j;f++){i=0;for(g=0;g<k;g++)i+=c[f][g]*d[g][m];l[f][m]=i}return j===1&&m===1?l[0][0]:l}return a.map(c,function(a){return a*d})},dot:function(c,d){e(c[0])||(c=[c]),e(d[0])||(d=[d]);var f=c[0].length===1&&c.length!==1?a.transpose(c):c,g=d[0].length===1&&d.length!==1?a.transpose(d):d,h=[],i=0,j=f.length,k=f[0].length,l,m;for(;i<j;i++){h[i]=[],l=0;for(m=0;m<k;m++)l+=f[i][m]*g[i][m];h[i]=l}return h.length===1?h[0]:h},pow:function(d,e){return a.map(d,function(a){return b.pow(a,e)})},exp:function(d){return a.map(d,function(a){return b.exp(a)})},log:function(d){return a.map(d,function(a){return b.log(a)})},abs:function(d){return a.map(d,function(a){return b.abs(a)})},norm:function(c,d){var f=0,g=0;isNaN(d)&&(d=2),e(c[0])&&(c=c[0]);for(;g<c.length;g++)f+=b.pow(b.abs(c[g]),d);return b.pow(f,1/d)},angle:function(d,e){return b.acos(a.dot(d,e)/(a.norm(d)*a.norm(e)))},aug:function(b,c){var e=b.slice(),f=0;for(;f<e.length;f++)d.apply(e[f],c[f]);return e},inv:function(c){var d=c.length,e=c[0].length,f=a.identity(d,e),g=a.gauss_jordan(c,f),h=[],i=0,j;for(;i<d;i++){h[i]=[];for(j=e;j<g[0].length;j++)h[i][j-e]=g[i][j]}return h},det:function(b){var c=b.length,d=c*2,e=new Array(d),f=c-1,g=d-1,h=f-c+1,i=g,j=0,k=0,l;if(c===2)return b[0][0]*b[1][1]-b[0][1]*b[1][0];for(;j<d;j++)e[j]=1;for(j=0;j<c;j++){for(l=0;l<c;l++)e[h<0?h+c:h]*=b[j][l],e[i<c?i+c:i]*=b[j][l],h++,i--;h=--f-c+1,i=--g}for(j=0;j<c;j++)k+=e[j];for(;j<d;j++)k-=e[j];return k},gauss_elimination:function(d,e){var f=0,g=0,h=d.length,i=d[0].length,j=1,k=0,l=[],m,n,o,p;d=a.aug(d,e),m=d[0].length;for(f=0;f<h;f++){n=d[f][f],g=f;for(p=f+1;p<i;p++)n<b.abs(d[p][f])&&(n=d[p][f],g=p);if(g!=f)for(p=0;p<m;p++)o=d[f][p],d[f][p]=d[g][p],d[g][p]=o;for(g=f+1;g<h;g++){j=d[g][f]/d[f][f];for(p=f;p<m;p++)d[g][p]=d[g][p]-j*d[f][p]}}for(f=h-1;f>=0;f--){k=0;for(g=f+1;g<=h-1;g++)k+=l[g]*d[f][g];l[f]=(d[f][m-1]-k)/d[f][f]}return l},gauss_jordan:function(e,f){var g=a.aug(e,f),h=g.length,i=g[0].length;for(var j=0;j<h;j++){var k=j;for(var l=j+1;l<h;l++)b.abs(g[l][j])>b.abs(g[k][j])&&(k=l);var m=g[j];g[j]=g[k],g[k]=m;for(var l=j+1;l<h;l++){c=g[l][j]/g[j][j];for(var n=j;n<i;n++)g[l][n]-=g[j][n]*c}}for(var j=h-1;j>=0;j--){c=g[j][j];for(var l=0;l<j;l++)for(var n=i-1;n>j-1;n--)g[l][n]-=g[j][n]*g[l][j]/c;g[j][j]/=c;for(var n=h;n<i;n++)g[j][n]/=c}return g},lu:function(b,c){throw new Error("lu not yet implemented")},cholesky:function(b,c){throw new Error("cholesky not yet implemented")},gauss_jacobi:function(d,e,f,g){var h=0,i=0,j=d.length,k=[],l=[],m=[],n,o,p,q;for(;h<j;h++){k[h]=[],l[h]=[],m[h]=[];for(i=0;i<j;i++)h>i?(k[h][i]=d[h][i],l[h][i]=m[h][i]=0):h<i?(l[h][i]=d[h][i],k[h][i]=m[h][i]=0):(m[h][i]=d[h][i],k[h][i]=l[h][i]=0)}p=a.multiply(a.multiply(a.inv(m),a.add(k,l)),-1),o=a.multiply(a.inv(m),e),n=f,q=a.add(a.multiply(p,f),o),h=2;while(b.abs(a.norm(a.subtract(q,n)))>g)n=q,q=a.add(a.multiply(p,n),o),h++;return q},gauss_seidel:function(d,e,f,g){var h=0,i=d.length,j=[],k=[],l=[],m,n,o,p,q;for(;h<i;h++){j[h]=[],k[h]=[],l[h]=[];for(m=0;m<i;m++)h>m?(j[h][m]=d[h][m],k[h][m]=l[h][m]=0):h<m?(k[h][m]=d[h][m],j[h][m]=l[h][m]=0):(l[h][m]=d[h][m],j[h][m]=k[h][m]=0)}p=a.multiply(a.multiply(a.inv(a.add(l,j)),k),-1),o=a.multiply(a.inv(a.add(l,j)),e),n=f,q=a.add(a.multiply(p,f),o),h=2;while(b.abs(a.norm(a.subtract(q,n)))>g)n=q,q=a.add(a.multiply(p,n),o),h+=1;return q},SOR:function(d,e,f,g,h){var i=0,j=d.length,k=[],l=[],m=[],n,o,p,q,r;for(;i<j;i++){k[i]=[],l[i]=[],m[i]=[];for(n=0;n<j;n++)i>n?(k[i][n]=d[i][n],l[i][n]=m[i][n]=0):i<n?(l[i][n]=d[i][n],k[i][n]=m[i][n]=0):(m[i][n]=d[i][n],k[i][n]=l[i][n]=0)}q=a.multiply(a.inv(a.add(m,a.multiply(k,h))),a.subtract(a.multiply(m,1-h),a.multiply(l,h))),p=a.multiply(a.multiply(a.inv(a.add(m,a.multiply(k,h))),e),h),o=f,r=a.add(a.multiply(q,f),p),i=2;while(b.abs(a.norm(a.subtract(r,o)))>g)o=r,r=a.add(a.multiply(q,o),p),i++;return r},householder:function(d){var e=d.length,f=d[0].length,g=0,h=[],i=[],j,k,l,m,n;for(;g<e-1;g++){j=0;for(m=g+1;m<f;m++)j+=d[m][g]*d[m][g];n=d[g+1][g]>0?-1:1,j=n*b.sqrt(j),k=b.sqrt((j*j-d[g+1][g]*j)/2),h=a.zeros(e,1),h[g+1][0]=(d[g+1][g]-j)/(2*k);for(l=g+2;l<e;l++)h[l][0]=d[l][g]/(2*k);i=a.subtract(a.identity(e,f),a.multiply(a.multiply(h,a.transpose(h)),2)),d=a.multiply(i,a.multiply(d,i))}return d},QR:function(d,e){var f=d.length,g=d[0].length,h=0,i=[],j=[],k=[],l,m,n,o,p,q;for(;h<f-1;h++){m=0;for(l=h+1;l<g;l++)m+=d[l][h]*d[l][h];p=d[h+1][h]>0?-1:1,m=p*b.sqrt(m),n=b.sqrt((m*m-d[h+1][h]*m)/2),i=a.zeros(f,1),i[h+1][0]=(d[h+1][h]-m)/(2*n);for(o=h+2;o<f;o++)i[o][0]=d[o][h]/(2*n);j=a.subtract(a.identity(f,g),a.multiply(a.multiply(i,a.transpose(i)),2)),d=a.multiply(j,d),e=a.multiply(j,e)}for(h=f-1;h>=0;h--){q=0;for(l=h+1;l<=g-1;l++)q=k[l]*d[h][l];k[h]=e[h][0]/d[h][h]}return k},jacobi:function(d){var e=1,f=0,g=d.length,h=a.identity(g,g),i=[],j,k,l,m,n,o,p,q;while(e===1){f++,o=d[0][1],m=0,n=1;for(k=0;k<g;k++)for(l=0;l<g;l++)k!=l&&o<b.abs(d[k][l])&&(o=b.abs(d[k][l]),m=k,n=l);d[m][m]===d[n][n]?p=d[m][n]>0?b.PI/4:-b.PI/4:p=b.atan(2*d[m][n]/(d[m][m]-d[n][n]))/2,q=a.identity(g,g),q[m][m]=b.cos(p),q[m][n]=-b.sin(p),q[n][m]=b.sin(p),q[n][n]=b.cos(p),h=a.multiply(h,q),j=a.multiply(a.multiply(a.inv(q),d),q),d=j,e=0;for(k=1;k<g;k++)for(l=1;l<g;l++)k!=l&&b.abs(d[k][l])>.001&&(e=1)}for(k=0;k<g;k++)i.push(d[k][k]);return[h,i]},rungekutta:function(b,c,d,e,f,g){var h,i,j,k,l;if(g===2)while(e<=d)h=c*b(e,f),i=c*b(e+c,f+h),j=f+(h+i)/2,f=j,e+=c;if(g===4)while(e<=d)h=c*b(e,f),i=c*b(e+c/2,f+h/2),k=c*b(e+c/2,f+i/2),l=c*b(e+c,f+k),j=f+(h+2*i+2*k+l)/6,f=j,e+=c;return f},romberg:function(c,d,e,f){var g=0,h=(e-d)/2,i=[],j=[],k=[],l,m,n,o,p,q;while(g<f/2){p=c(d);for(n=d,o=0;n<=e;n+=h,o++)i[o]=n;l=i.length;for(n=1;n<l-1;n++)p+=(n%2!==0?4:2)*c(i[n]);p=h/3*(p+c(e)),k[g]=p,h/=2,g++}m=k.length,l=1;while(m!==1){for(n=0;n<m-1;n++)j[n]=(b.pow(4,l)*k[n+1]-k[n])/(b.pow(4,l)-1);m=j.length,k=j,j=[],l++}return k},richardson:function(c,d,e,f){function g(a,b){var c=0,d=a.length,e;for(;c<d;c++)a[c]===b&&(e=c);return e}var h=c.length,i=b.abs(e-c[g(c,e)+1]),j=0,k=[],l=[],m,n,o,p,q;while(f>=i)m=g(c,e+f),n=g(c,e),k[j]=(d[m]-2*d[n]+d[2*n-m])/(f*f),f/=2,j++;p=k.length,o=1;while(p!=1){for(q=0;q<p-1;q++)l[q]=(b.pow(4,o)*k[q+1]-k[q])/(b.pow(4,o)-1);p=l.length,k=l,l=[],o++}return k},simpson:function(b,c,d,e){var f=(d-c)/e,g=b(c),h=[],i=c,j=0,k=1,l;for(;i<=d;i+=f,j++)h[j]=i;l=h.length;for(;k<l-1;k++)g+=(k%2!==0?4:2)*b(h[k]);return f/3*(g+b(d))},hermite:function(b,c,d,e){var f=b.length,g=0,h=0,i=[],j=[],k=[],l=[],m;for(;h<f;h++){i[h]=1;for(m=0;m<f;m++)h!=m&&(i[h]*=(e-b[m])/(b[h]-b[m]));j[h]=0;for(m=0;m<f;m++)h!=m&&(j[h]+=1/(b[h]-b[m]));k[h]=(1-2*(e-b[h])*j[h])*i[h]*i[h],l[h]=(e-b[h])*i[h]*i[h],g+=k[h]*c[h]+l[h]*d[h]}return g},lagrange:function(b,c,d){var e=0,f=0,g,h,i=b.length;for(;f<i;f++){h=c[f];for(g=0;g<i;g++)f!=g&&(h*=(d-b[g])/(b[f]-b[g]));e+=h}return e},cubic_spline:function(c,d,e){var f=c.length,g=0,h,i=[],j=[],k=[],l=[],m=[],n=[],o=[];for(;g<f-1;g++)m[g]=c[g+1]-c[g];k[0]=0;for(g=1;g<f-1;g++)k[g]=3/m[g]*(d[g+1]-d[g])-3/m[g-1]*(d[g]-d[g-1]);for(g=1;g<f-1;g++)i[g]=[],j[g]=[],i[g][g-1]=m[g-1],i[g][g]=2*(m[g-1]+m[g]),i[g][g+1]=m[g],j[g][0]=k[g];l=a.multiply(a.inv(i),j);for(h=0;h<f-1;h++)n[h]=(d[h+1]-d[h])/m[h]-m[h]*(l[h+1][0]+2*l[h][0])/3,o[h]=(l[h+1][0]-l[h][0])/(3*m[h]);for(h=0;h<f;h++)if(c[h]>e)break;return h-=1,d[h]+(e-c[h])*n[h]+a.sq(e-c[h])*l[h]+(e-c[h])*a.sq(e-c[h])*o[h]},gauss_quadrature:function(){throw new Error("gauss_quadrature not yet implemented")},PCA:function(c){var d=c.length,e=c[0].length,f=!1,g=0,h,i,j=[],k=[],l=[],m=[],n=[],o=[],p=[],q=[],r=[],s=[];for(g=0;g<d;g++)j[g]=a.sum(c[g])/e;for(g=0;g<e;g++){p[g]=[];for(h=0;h<d;h++)p[g][h]=c[h][g]-j[h]}p=a.transpose(p);for(g=0;g<d;g++){q[g]=[];for(h=0;h<d;h++)q[g][h]=a.dot([p[g]],[p[h]])/(e-1)}l=a.jacobi(q),r=l[0],k=l[1],s=a.transpose(r);for(g=0;g<k.length;g++)for(h=g;h<k.length;h++)k[g]<k[h]&&(i=k[g],k[g]=k[h],k[h]=i,m=s[g],s[g]=s[h],s[h]=m);o=a.transpose(p);for(g=0;g<d;g++){n[g]=[];for(h=0;h<o.length;h++)n[g][h]=a.dot([s[g]],[o[h]])}return[c,k,s,n]}}),function(b){for(var c=0;c<b.length;c++)(function(b){a.fn[b]=function(c,d){var e=this;return d?(setTimeout(function(){d.call(e,a.fn[b].call(e,c))},15),this):typeof a[b](this,c)=="number"?a[b](this,c):a(a[b](this,c))}})(b[c])}("add divide multiply subtract dot pow exp log abs norm angle".split
+(" "))}(this.jStat,Math),function(a,b){var c=[].slice,d=a.utils.isNumber;a.extend({zscore:function(){var e=c.call(arguments);return d(e[1])?(e[0]-e[1])/e[2]:(e[0]-a.mean(e[1]))/a.stdev(e[1],e[2])},ztest:function(){var f=c.call(arguments);if(f.length===4){if(d(f[1])){var g=a.zscore(f[0],f[1],f[2]);return f[3]===1?a.normal.cdf(-b.abs(g),0,1):a.normal.cdf(-b.abs(g),0,1)*2}var g=f[0];return f[2]===1?a.normal.cdf(-b.abs(g),0,1):a.normal.cdf(-b.abs(g),0,1)*2}var g=a.zscore(f[0],f[1],f[3]);return f[1]===1?a.normal.cdf(-b.abs(g),0,1):a.normal.cdf(-b.abs(g),0,1)*2}}),a.extend(a.fn,{zscore:function(b,c){return(b-this.mean())/this.stdev(c)},ztest:function(d,e,f){var g=b.abs(this.zscore(d,f));return e===1?a.normal.cdf(-g,0,1):a.normal.cdf(-g,0,1)*2}}),a.extend({tscore:function(){var e=c.call(arguments);return e.length===4?(e[0]-e[1])/(e[2]/b.sqrt(e[3])):(e[0]-a.mean(e[1]))/(a.stdev(e[1],!0)/b.sqrt(e[1].length))},ttest:function(){var f=c.call(arguments),g;return f.length===5?(g=b.abs(a.tscore(f[0],f[1],f[2],f[3])),f[4]===1?a.studentt.cdf(-g,f[3]-1):a.studentt.cdf(-g,f[3]-1)*2):d(f[1])?(g=b.abs(f[0]),f[2]==1?a.studentt.cdf(-g,f[1]-1):a.studentt.cdf(-g,f[1]-1)*2):(g=b.abs(a.tscore(f[0],f[1])),f[2]==1?a.studentt.cdf(-g,f[1].length-1):a.studentt.cdf(-g,f[1].length-1)*2)}}),a.extend(a.fn,{tscore:function(c){return(c-this.mean())/(this.stdev(!0)/b.sqrt(this.cols()))},ttest:function(d,e){return e===1?1-a.studentt.cdf(b.abs(this.tscore(d)),this.cols()-1):a.studentt.cdf(-b.abs(this.tscore(d)),this.cols()-1)*2}}),a.extend({anovafscore:function(){var e=c.call(arguments),f,g,h,i,j,k,l,m;if(e.length===1){j=new Array(e[0].length);for(l=0;l<e[0].length;l++)j[l]=e[0][l];e=j}if(e.length===2)return a.variance(e[0])/a.variance(e[1]);g=new Array;for(l=0;l<e.length;l++)g=g.concat(e[l]);h=a.mean(g),f=0;for(l=0;l<e.length;l++)f+=e[l].length*b.pow(a.mean(e[l])-h,2);f/=e.length-1,k=0;for(l=0;l<e.length;l++){i=a.mean(e[l]);for(m=0;m<e[l].length;m++)k+=b.pow(e[l][m]-i,2)}return k/=g.length-e.length,f/k},anovaftest:function(){var e=c.call(arguments),f,g,h,i;if(d(e[0]))return 1-a.centralF.cdf(e[0],e[1],e[2]);anovafscore=a.anovafscore(e),f=e.length-1,h=0;for(i=0;i<e.length;i++)h+=e[i].length;return g=h-f-1,1-a.centralF.cdf(anovafscore,f,g)},ftest:function(c,d,e){return 1-a.centralF.cdf(c,d,e)}}),a.extend(a.fn,{anovafscore:function(){return a.anovafscore(this.toArray())},anovaftes:function(){var c=0,d;for(d=0;d<this.length;d++)c+=this[d].length;return a.ftest(this.anovafscore(),this.length-1,c-this.length)}}),a.extend({normalci:function(){var e=c.call(arguments),f=new Array(2),g;return e.length===4?g=b.abs(a.normal.inv(e[1]/2,0,1)*e[2]/b.sqrt(e[3])):g=b.abs(a.normal.inv(e[1]/2,0,1)*a.stdev(e[2])/b.sqrt(e[2].length)),f[0]=e[0]-g,f[1]=e[0]+g,f},tci:function(){var e=c.call(arguments),f=new Array(2),g;return e.length===4?g=b.abs(a.studentt.inv(e[1]/2,e[3]-1)*e[2]/b.sqrt(e[3])):g=b.abs(a.studentt.inv(e[1]/2,e[2].length-1)*a.stdev(e[2],!0)/b.sqrt(e[2].length)),f[0]=e[0]-g,f[1]=e[0]+g,f},significant:function(b,c){return b<c}}),a.extend(a.fn,{normalci:function(c,d){return a.normalci(c,d,this.toArray())},tci:function(c,d){return a.tci(c,d,this.toArray())}})}(this.jStat,Math); \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/js_external/jszip.min.js b/wqflask/wqflask/static/new/js_external/jszip.min.js
new file mode 100644
index 00000000..a09f35b8
--- /dev/null
+++ b/wqflask/wqflask/static/new/js_external/jszip.min.js
@@ -0,0 +1,14 @@
+/*!
+
+JSZip - A Javascript class for generating and reading zip files
+<http://stuartk.com/jszip>
+
+(c) 2009-2014 Stuart Knightley <stuart [at] stuartk.com>
+Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
+
+JSZip uses the library pako released under the MIT license :
+https://github.com/nodeca/pako/blob/master/LICENSE
+*/
+!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;"undefined"!=typeof window?b=window:"undefined"!=typeof global?b=global:"undefined"!=typeof self&&(b=self),b.JSZip=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){"use strict";var d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";c.encode=function(a){for(var b,c,e,f,g,h,i,j="",k=0;k<a.length;)b=a.charCodeAt(k++),c=a.charCodeAt(k++),e=a.charCodeAt(k++),f=b>>2,g=(3&b)<<4|c>>4,h=(15&c)<<2|e>>6,i=63&e,isNaN(c)?h=i=64:isNaN(e)&&(i=64),j=j+d.charAt(f)+d.charAt(g)+d.charAt(h)+d.charAt(i);return j},c.decode=function(a){var b,c,e,f,g,h,i,j="",k=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");k<a.length;)f=d.indexOf(a.charAt(k++)),g=d.indexOf(a.charAt(k++)),h=d.indexOf(a.charAt(k++)),i=d.indexOf(a.charAt(k++)),b=f<<2|g>>4,c=(15&g)<<4|h>>2,e=(3&h)<<6|i,j+=String.fromCharCode(b),64!=h&&(j+=String.fromCharCode(c)),64!=i&&(j+=String.fromCharCode(e));return j}},{}],2:[function(a,b){"use strict";function c(){this.compressedSize=0,this.uncompressedSize=0,this.crc32=0,this.compressionMethod=null,this.compressedContent=null}c.prototype={getContent:function(){return null},getCompressedContent:function(){return null}},b.exports=c},{}],3:[function(a,b,c){"use strict";c.STORE={magic:"\x00\x00",compress:function(a){return a},uncompress:function(a){return a},compressInputType:null,uncompressInputType:null},c.DEFLATE=a("./flate")},{"./flate":8}],4:[function(a,b){"use strict";var c=a("./utils"),d=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];b.exports=function(a,b){if("undefined"==typeof a||!a.length)return 0;var e="string"!==c.getTypeOf(a);"undefined"==typeof b&&(b=0);var f=0,g=0,h=0;b=-1^b;for(var i=0,j=a.length;j>i;i++)h=e?a[i]:a.charCodeAt(i),g=255&(b^h),f=d[g],b=b>>>8^f;return-1^b}},{"./utils":21}],5:[function(a,b){"use strict";function c(){this.data=null,this.length=0,this.index=0}var d=a("./utils");c.prototype={checkOffset:function(a){this.checkIndex(this.index+a)},checkIndex:function(a){if(this.length<a||0>a)throw new Error("End of data reached (data length = "+this.length+", asked index = "+a+"). Corrupted zip ?")},setIndex:function(a){this.checkIndex(a),this.index=a},skip:function(a){this.setIndex(this.index+a)},byteAt:function(){},readInt:function(a){var b,c=0;for(this.checkOffset(a),b=this.index+a-1;b>=this.index;b--)c=(c<<8)+this.byteAt(b);return this.index+=a,c},readString:function(a){return d.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date((a>>25&127)+1980,(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1)}},b.exports=c},{"./utils":21}],6:[function(a,b,c){"use strict";c.base64=!1,c.binary=!1,c.dir=!1,c.createFolders=!1,c.date=null,c.compression=null,c.compressionOptions=null,c.comment=null,c.unixPermissions=null,c.dosPermissions=null},{}],7:[function(a,b,c){"use strict";var d=a("./utils");c.string2binary=function(a){return d.string2binary(a)},c.string2Uint8Array=function(a){return d.transformTo("uint8array",a)},c.uint8Array2String=function(a){return d.transformTo("string",a)},c.string2Blob=function(a){var b=d.transformTo("arraybuffer",a);return d.arrayBuffer2Blob(b)},c.arrayBuffer2Blob=function(a){return d.arrayBuffer2Blob(a)},c.transformTo=function(a,b){return d.transformTo(a,b)},c.getTypeOf=function(a){return d.getTypeOf(a)},c.checkSupport=function(a){return d.checkSupport(a)},c.MAX_VALUE_16BITS=d.MAX_VALUE_16BITS,c.MAX_VALUE_32BITS=d.MAX_VALUE_32BITS,c.pretty=function(a){return d.pretty(a)},c.findCompression=function(a){return d.findCompression(a)},c.isRegExp=function(a){return d.isRegExp(a)}},{"./utils":21}],8:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,e=a("pako");c.uncompressInputType=d?"uint8array":"array",c.compressInputType=d?"uint8array":"array",c.magic="\b\x00",c.compress=function(a,b){return e.deflateRaw(a,{level:b.level||-1})},c.uncompress=function(a){return e.inflateRaw(a)}},{pako:24}],9:[function(a,b){"use strict";function c(a,b){return this instanceof c?(this.files={},this.comment=null,this.root="",a&&this.load(a,b),void(this.clone=function(){var a=new c;for(var b in this)"function"!=typeof this[b]&&(a[b]=this[b]);return a})):new c(a,b)}var d=a("./base64");c.prototype=a("./object"),c.prototype.load=a("./load"),c.support=a("./support"),c.defaults=a("./defaults"),c.utils=a("./deprecatedPublicUtils"),c.base64={encode:function(a){return d.encode(a)},decode:function(a){return d.decode(a)}},c.compressions=a("./compressions"),b.exports=c},{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(a,b){"use strict";var c=a("./base64"),d=a("./zipEntries");b.exports=function(a,b){var e,f,g,h;for(b=b||{},b.base64&&(a=c.decode(a)),f=new d(a,b),e=f.files,g=0;g<e.length;g++)h=e[g],this.file(h.fileName,h.decompressed,{binary:!0,optimizedBinaryString:!0,date:h.date,dir:h.dir,comment:h.fileComment.length?h.fileComment:null,unixPermissions:h.unixPermissions,dosPermissions:h.dosPermissions,createFolders:b.createFolders});return f.zipComment.length&&(this.comment=f.zipComment),this}},{"./base64":1,"./zipEntries":22}],11:[function(a,b){(function(a){"use strict";b.exports=function(b,c){return new a(b,c)},b.exports.test=function(b){return a.isBuffer(b)}}).call(this,"undefined"!=typeof Buffer?Buffer:void 0)},{}],12:[function(a,b){"use strict";function c(a){this.data=a,this.length=this.data.length,this.index=0}var d=a("./uint8ArrayReader");c.prototype=new d,c.prototype.readData=function(a){this.checkOffset(a);var b=this.data.slice(this.index,this.index+a);return this.index+=a,b},b.exports=c},{"./uint8ArrayReader":18}],13:[function(a,b){"use strict";var c=a("./support"),d=a("./utils"),e=a("./crc32"),f=a("./signature"),g=a("./defaults"),h=a("./base64"),i=a("./compressions"),j=a("./compressedObject"),k=a("./nodeBuffer"),l=a("./utf8"),m=a("./stringWriter"),n=a("./uint8ArrayWriter"),o=function(a){if(a._data instanceof j&&(a._data=a._data.getContent(),a.options.binary=!0,a.options.base64=!1,"uint8array"===d.getTypeOf(a._data))){var b=a._data;a._data=new Uint8Array(b.length),0!==b.length&&a._data.set(b,0)}return a._data},p=function(a){var b=o(a),e=d.getTypeOf(b);return"string"===e?!a.options.binary&&c.nodebuffer?k(b,"utf-8"):a.asBinary():b},q=function(a){var b=o(this);return null===b||"undefined"==typeof b?"":(this.options.base64&&(b=h.decode(b)),b=a&&this.options.binary?D.utf8decode(b):d.transformTo("string",b),a||this.options.binary||(b=d.transformTo("string",D.utf8encode(b))),b)},r=function(a,b,c){this.name=a,this.dir=c.dir,this.date=c.date,this.comment=c.comment,this.unixPermissions=c.unixPermissions,this.dosPermissions=c.dosPermissions,this._data=b,this.options=c,this._initialMetadata={dir:c.dir,date:c.date}};r.prototype={asText:function(){return q.call(this,!0)},asBinary:function(){return q.call(this,!1)},asNodeBuffer:function(){var a=p(this);return d.transformTo("nodebuffer",a)},asUint8Array:function(){var a=p(this);return d.transformTo("uint8array",a)},asArrayBuffer:function(){return this.asUint8Array().buffer}};var s=function(a,b){var c,d="";for(c=0;b>c;c++)d+=String.fromCharCode(255&a),a>>>=8;return d},t=function(){var a,b,c={};for(a=0;a<arguments.length;a++)for(b in arguments[a])arguments[a].hasOwnProperty(b)&&"undefined"==typeof c[b]&&(c[b]=arguments[a][b]);return c},u=function(a){return a=a||{},a.base64!==!0||null!==a.binary&&void 0!==a.binary||(a.binary=!0),a=t(a,g),a.date=a.date||new Date,null!==a.compression&&(a.compression=a.compression.toUpperCase()),a},v=function(a,b,c){var e,f=d.getTypeOf(b);if(c=u(c),"string"==typeof c.unixPermissions&&(c.unixPermissions=parseInt(c.unixPermissions,8)),c.unixPermissions&&16384&c.unixPermissions&&(c.dir=!0),c.dosPermissions&&16&c.dosPermissions&&(c.dir=!0),c.dir&&(a=x(a)),c.createFolders&&(e=w(a))&&y.call(this,e,!0),c.dir||null===b||"undefined"==typeof b)c.base64=!1,c.binary=!1,b=null,f=null;else if("string"===f)c.binary&&!c.base64&&c.optimizedBinaryString!==!0&&(b=d.string2binary(b));else{if(c.base64=!1,c.binary=!0,!(f||b instanceof j))throw new Error("The data of '"+a+"' is in an unsupported format !");"arraybuffer"===f&&(b=d.transformTo("uint8array",b))}var g=new r(a,b,c);return this.files[a]=g,g},w=function(a){"/"==a.slice(-1)&&(a=a.substring(0,a.length-1));var b=a.lastIndexOf("/");return b>0?a.substring(0,b):""},x=function(a){return"/"!=a.slice(-1)&&(a+="/"),a},y=function(a,b){return b="undefined"!=typeof b?b:!1,a=x(a),this.files[a]||v.call(this,a,null,{dir:!0,createFolders:b}),this.files[a]},z=function(a,b,c){var f,g=new j;return a._data instanceof j?(g.uncompressedSize=a._data.uncompressedSize,g.crc32=a._data.crc32,0===g.uncompressedSize||a.dir?(b=i.STORE,g.compressedContent="",g.crc32=0):a._data.compressionMethod===b.magic?g.compressedContent=a._data.getCompressedContent():(f=a._data.getContent(),g.compressedContent=b.compress(d.transformTo(b.compressInputType,f),c))):(f=p(a),(!f||0===f.length||a.dir)&&(b=i.STORE,f=""),g.uncompressedSize=f.length,g.crc32=e(f),g.compressedContent=b.compress(d.transformTo(b.compressInputType,f),c)),g.compressedSize=g.compressedContent.length,g.compressionMethod=b.magic,g},A=function(a,b){var c=a;return a||(c=b?16893:33204),(65535&c)<<16},B=function(a){return 63&(a||0)},C=function(a,b,c,g,h){var i,j,k,m,n=(c.compressedContent,d.transformTo("string",l.utf8encode(b.name))),o=b.comment||"",p=d.transformTo("string",l.utf8encode(o)),q=n.length!==b.name.length,r=p.length!==o.length,t=b.options,u="",v="",w="";k=b._initialMetadata.dir!==b.dir?b.dir:t.dir,m=b._initialMetadata.date!==b.date?b.date:t.date;var x=0,y=0;k&&(x|=16),"UNIX"===h?(y=798,x|=A(b.unixPermissions,k)):(y=20,x|=B(b.dosPermissions,k)),i=m.getHours(),i<<=6,i|=m.getMinutes(),i<<=5,i|=m.getSeconds()/2,j=m.getFullYear()-1980,j<<=4,j|=m.getMonth()+1,j<<=5,j|=m.getDate(),q&&(v=s(1,1)+s(e(n),4)+n,u+="up"+s(v.length,2)+v),r&&(w=s(1,1)+s(this.crc32(p),4)+p,u+="uc"+s(w.length,2)+w);var z="";z+="\n\x00",z+=q||r?"\x00\b":"\x00\x00",z+=c.compressionMethod,z+=s(i,2),z+=s(j,2),z+=s(c.crc32,4),z+=s(c.compressedSize,4),z+=s(c.uncompressedSize,4),z+=s(n.length,2),z+=s(u.length,2);var C=f.LOCAL_FILE_HEADER+z+n+u,D=f.CENTRAL_FILE_HEADER+s(y,2)+z+s(p.length,2)+"\x00\x00\x00\x00"+s(x,4)+s(g,4)+n+u+p;return{fileRecord:C,dirRecord:D,compressedObject:c}},D={load:function(){throw new Error("Load method is not defined. Is the file jszip-load.js included ?")},filter:function(a){var b,c,d,e,f=[];for(b in this.files)this.files.hasOwnProperty(b)&&(d=this.files[b],e=new r(d.name,d._data,t(d.options)),c=b.slice(this.root.length,b.length),b.slice(0,this.root.length)===this.root&&a(c,e)&&f.push(e));return f},file:function(a,b,c){if(1===arguments.length){if(d.isRegExp(a)){var e=a;return this.filter(function(a,b){return!b.dir&&e.test(a)})}return this.filter(function(b,c){return!c.dir&&b===a})[0]||null}return a=this.root+a,v.call(this,a,b,c),this},folder:function(a){if(!a)return this;if(d.isRegExp(a))return this.filter(function(b,c){return c.dir&&a.test(b)});var b=this.root+a,c=y.call(this,b),e=this.clone();return e.root=c.name,e},remove:function(a){a=this.root+a;var b=this.files[a];if(b||("/"!=a.slice(-1)&&(a+="/"),b=this.files[a]),b&&!b.dir)delete this.files[a];else for(var c=this.filter(function(b,c){return c.name.slice(0,a.length)===a}),d=0;d<c.length;d++)delete this.files[c[d].name];return this},generate:function(a){a=t(a||{},{base64:!0,compression:"STORE",compressionOptions:null,type:"base64",platform:"DOS",comment:null,mimeType:"application/zip"}),d.checkSupport(a.type),("darwin"===a.platform||"freebsd"===a.platform||"linux"===a.platform||"sunos"===a.platform)&&(a.platform="UNIX"),"win32"===a.platform&&(a.platform="DOS");var b,c,e=[],g=0,j=0,k=d.transformTo("string",this.utf8encode(a.comment||this.comment||""));for(var l in this.files)if(this.files.hasOwnProperty(l)){var o=this.files[l],p=o.options.compression||a.compression.toUpperCase(),q=i[p];if(!q)throw new Error(p+" is not a valid compression method !");var r=o.options.compressionOptions||a.compressionOptions||{},u=z.call(this,o,q,r),v=C.call(this,l,o,u,g,a.platform);g+=v.fileRecord.length+u.compressedSize,j+=v.dirRecord.length,e.push(v)}var w="";w=f.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+s(e.length,2)+s(e.length,2)+s(j,4)+s(g,4)+s(k.length,2)+k;var x=a.type.toLowerCase();for(b="uint8array"===x||"arraybuffer"===x||"blob"===x||"nodebuffer"===x?new n(g+j+w.length):new m(g+j+w.length),c=0;c<e.length;c++)b.append(e[c].fileRecord),b.append(e[c].compressedObject.compressedContent);for(c=0;c<e.length;c++)b.append(e[c].dirRecord);b.append(w);var y=b.finalize();switch(a.type.toLowerCase()){case"uint8array":case"arraybuffer":case"nodebuffer":return d.transformTo(a.type.toLowerCase(),y);case"blob":return d.arrayBuffer2Blob(d.transformTo("arraybuffer",y),a.mimeType);case"base64":return a.base64?h.encode(y):y;default:return y}},crc32:function(a,b){return e(a,b)},utf8encode:function(a){return d.transformTo("string",l.utf8encode(a))},utf8decode:function(a){return l.utf8decode(a)}};b.exports=D},{"./base64":1,"./compressedObject":2,"./compressions":3,"./crc32":4,"./defaults":6,"./nodeBuffer":11,"./signature":14,"./stringWriter":16,"./support":17,"./uint8ArrayWriter":19,"./utf8":20,"./utils":21}],14:[function(a,b,c){"use strict";c.LOCAL_FILE_HEADER="PK",c.CENTRAL_FILE_HEADER="PK",c.CENTRAL_DIRECTORY_END="PK",c.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",c.ZIP64_CENTRAL_DIRECTORY_END="PK",c.DATA_DESCRIPTOR="PK\b"},{}],15:[function(a,b){"use strict";function c(a,b){this.data=a,b||(this.data=e.string2binary(this.data)),this.length=this.data.length,this.index=0}var d=a("./dataReader"),e=a("./utils");c.prototype=new d,c.prototype.byteAt=function(a){return this.data.charCodeAt(a)},c.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)},c.prototype.readData=function(a){this.checkOffset(a);var b=this.data.slice(this.index,this.index+a);return this.index+=a,b},b.exports=c},{"./dataReader":5,"./utils":21}],16:[function(a,b){"use strict";var c=a("./utils"),d=function(){this.data=[]};d.prototype={append:function(a){a=c.transformTo("string",a),this.data.push(a)},finalize:function(){return this.data.join("")}},b.exports=d},{"./utils":21}],17:[function(a,b,c){(function(a){"use strict";if(c.base64=!0,c.array=!0,c.string=!0,c.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,c.nodebuffer="undefined"!=typeof a,c.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)c.blob=!1;else{var b=new ArrayBuffer(0);try{c.blob=0===new Blob([b],{type:"application/zip"}).size}catch(d){try{var e=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder,f=new e;f.append(b),c.blob=0===f.getBlob("application/zip").size}catch(d){c.blob=!1}}}}).call(this,"undefined"!=typeof Buffer?Buffer:void 0)},{}],18:[function(a,b){"use strict";function c(a){a&&(this.data=a,this.length=this.data.length,this.index=0)}var d=a("./dataReader");c.prototype=new d,c.prototype.byteAt=function(a){return this.data[a]},c.prototype.lastIndexOfSignature=function(a){for(var b=a.charCodeAt(0),c=a.charCodeAt(1),d=a.charCodeAt(2),e=a.charCodeAt(3),f=this.length-4;f>=0;--f)if(this.data[f]===b&&this.data[f+1]===c&&this.data[f+2]===d&&this.data[f+3]===e)return f;return-1},c.prototype.readData=function(a){if(this.checkOffset(a),0===a)return new Uint8Array(0);var b=this.data.subarray(this.index,this.index+a);return this.index+=a,b},b.exports=c},{"./dataReader":5}],19:[function(a,b){"use strict";var c=a("./utils"),d=function(a){this.data=new Uint8Array(a),this.index=0};d.prototype={append:function(a){0!==a.length&&(a=c.transformTo("uint8array",a),this.data.set(a,this.index),this.index+=a.length)},finalize:function(){return this.data}},b.exports=d},{"./utils":21}],20:[function(a,b,c){"use strict";for(var d=a("./utils"),e=a("./support"),f=a("./nodeBuffer"),g=new Array(256),h=0;256>h;h++)g[h]=h>=252?6:h>=248?5:h>=240?4:h>=224?3:h>=192?2:1;g[254]=g[254]=1;var i=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=e.uint8array?new Uint8Array(i):new Array(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},j=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+g[a[c]]>b?c:b},k=function(a){var b,c,e,f,h=a.length,i=new Array(2*h);for(c=0,b=0;h>b;)if(e=a[b++],128>e)i[c++]=e;else if(f=g[e],f>4)i[c++]=65533,b+=f-1;else{for(e&=2===f?31:3===f?15:7;f>1&&h>b;)e=e<<6|63&a[b++],f--;f>1?i[c++]=65533:65536>e?i[c++]=e:(e-=65536,i[c++]=55296|e>>10&1023,i[c++]=56320|1023&e)}return i.length!==c&&(i.subarray?i=i.subarray(0,c):i.length=c),d.applyFromCharCode(i)};c.utf8encode=function(a){return e.nodebuffer?f(a,"utf-8"):i(a)},c.utf8decode=function(a){if(e.nodebuffer)return d.transformTo("nodebuffer",a).toString("utf-8");a=d.transformTo(e.uint8array?"uint8array":"array",a);for(var b=[],c=0,f=a.length,g=65536;f>c;){var h=j(a,Math.min(c+g,f));b.push(e.uint8array?k(a.subarray(c,h)):k(a.slice(c,h))),c=h}return b.join("")}},{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(a,b,c){"use strict";function d(a){return a}function e(a,b){for(var c=0;c<a.length;++c)b[c]=255&a.charCodeAt(c);return b}function f(a){var b=65536,d=[],e=a.length,f=c.getTypeOf(a),g=0,h=!0;try{switch(f){case"uint8array":String.fromCharCode.apply(null,new Uint8Array(0));break;case"nodebuffer":String.fromCharCode.apply(null,j(0))}}catch(i){h=!1}if(!h){for(var k="",l=0;l<a.length;l++)k+=String.fromCharCode(a[l]);return k}for(;e>g&&b>1;)try{d.push("array"===f||"nodebuffer"===f?String.fromCharCode.apply(null,a.slice(g,Math.min(g+b,e))):String.fromCharCode.apply(null,a.subarray(g,Math.min(g+b,e)))),g+=b}catch(i){b=Math.floor(b/2)}return d.join("")}function g(a,b){for(var c=0;c<a.length;c++)b[c]=a[c];return b}var h=a("./support"),i=a("./compressions"),j=a("./nodeBuffer");c.string2binary=function(a){for(var b="",c=0;c<a.length;c++)b+=String.fromCharCode(255&a.charCodeAt(c));return b},c.arrayBuffer2Blob=function(a,b){c.checkSupport("blob"),b=b||"application/zip";try{return new Blob([a],{type:b})}catch(d){try{var e=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder,f=new e;return f.append(a),f.getBlob(b)}catch(d){throw new Error("Bug : can't construct the Blob.")}}},c.applyFromCharCode=f;var k={};k.string={string:d,array:function(a){return e(a,new Array(a.length))},arraybuffer:function(a){return k.string.uint8array(a).buffer},uint8array:function(a){return e(a,new Uint8Array(a.length))},nodebuffer:function(a){return e(a,j(a.length))}},k.array={string:f,array:d,arraybuffer:function(a){return new Uint8Array(a).buffer},uint8array:function(a){return new Uint8Array(a)},nodebuffer:function(a){return j(a)}},k.arraybuffer={string:function(a){return f(new Uint8Array(a))},array:function(a){return g(new Uint8Array(a),new Array(a.byteLength))},arraybuffer:d,uint8array:function(a){return new Uint8Array(a)},nodebuffer:function(a){return j(new Uint8Array(a))}},k.uint8array={string:f,array:function(a){return g(a,new Array(a.length))},arraybuffer:function(a){return a.buffer},uint8array:d,nodebuffer:function(a){return j(a)}},k.nodebuffer={string:f,array:function(a){return g(a,new Array(a.length))},arraybuffer:function(a){return k.nodebuffer.uint8array(a).buffer},uint8array:function(a){return g(a,new Uint8Array(a.length))},nodebuffer:d},c.transformTo=function(a,b){if(b||(b=""),!a)return b;c.checkSupport(a);var d=c.getTypeOf(b),e=k[d][a](b);return e},c.getTypeOf=function(a){return"string"==typeof a?"string":"[object Array]"===Object.prototype.toString.call(a)?"array":h.nodebuffer&&j.test(a)?"nodebuffer":h.uint8array&&a instanceof Uint8Array?"uint8array":h.arraybuffer&&a instanceof ArrayBuffer?"arraybuffer":void 0},c.checkSupport=function(a){var b=h[a.toLowerCase()];if(!b)throw new Error(a+" is not supported by this browser")},c.MAX_VALUE_16BITS=65535,c.MAX_VALUE_32BITS=-1,c.pretty=function(a){var b,c,d="";for(c=0;c<(a||"").length;c++)b=a.charCodeAt(c),d+="\\x"+(16>b?"0":"")+b.toString(16).toUpperCase();return d},c.findCompression=function(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b].magic===a)return i[b];return null},c.isRegExp=function(a){return"[object RegExp]"===Object.prototype.toString.call(a)}},{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(a,b){"use strict";function c(a,b){this.files=[],this.loadOptions=b,a&&this.load(a)}var d=a("./stringReader"),e=a("./nodeBufferReader"),f=a("./uint8ArrayReader"),g=a("./utils"),h=a("./signature"),i=a("./zipEntry"),j=a("./support"),k=a("./object");c.prototype={checkSignature:function(a){var b=this.reader.readString(4);if(b!==a)throw new Error("Corrupted zip or bug : unexpected signature ("+g.pretty(b)+", expected "+g.pretty(a)+")")},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2),this.zipComment=this.reader.readString(this.zipCommentLength),this.zipComment=k.utf8decode(this.zipComment)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.versionMadeBy=this.reader.readString(2),this.versionNeeded=this.reader.readInt(2),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var a,b,c,d=this.zip64EndOfCentralSize-44,e=0;d>e;)a=this.reader.readInt(2),b=this.reader.readInt(4),c=this.reader.readString(b),this.zip64ExtensibleData[a]={id:a,length:b,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var a,b;for(a=0;a<this.files.length;a++)b=this.files[a],this.reader.setIndex(b.localHeaderOffset),this.checkSignature(h.LOCAL_FILE_HEADER),b.readLocalPart(this.reader),b.handleUTF8(),b.processAttributes()},readCentralDir:function(){var a;for(this.reader.setIndex(this.centralDirOffset);this.reader.readString(4)===h.CENTRAL_FILE_HEADER;)a=new i({zip64:this.zip64},this.loadOptions),a.readCentralPart(this.reader),this.files.push(a)},readEndOfCentral:function(){var a=this.reader.lastIndexOfSignature(h.CENTRAL_DIRECTORY_END);if(-1===a){var b=!0;try{this.reader.setIndex(0),this.checkSignature(h.LOCAL_FILE_HEADER),b=!1}catch(c){}throw new Error(b?"Can't find end of central directory : is this a zip file ? If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html":"Corrupted zip : can't find end of central directory")}if(this.reader.setIndex(a),this.checkSignature(h.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===g.MAX_VALUE_16BITS||this.diskWithCentralDirStart===g.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===g.MAX_VALUE_16BITS||this.centralDirRecords===g.MAX_VALUE_16BITS||this.centralDirSize===g.MAX_VALUE_32BITS||this.centralDirOffset===g.MAX_VALUE_32BITS){if(this.zip64=!0,a=this.reader.lastIndexOfSignature(h.ZIP64_CENTRAL_DIRECTORY_LOCATOR),-1===a)throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");this.reader.setIndex(a),this.checkSignature(h.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(h.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}},prepareReader:function(a){var b=g.getTypeOf(a);this.reader="string"!==b||j.uint8array?"nodebuffer"===b?new e(a):new f(g.transformTo("uint8array",a)):new d(a,this.loadOptions.optimizedBinaryString)},load:function(a){this.prepareReader(a),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},b.exports=c},{"./nodeBufferReader":12,"./object":13,"./signature":14,"./stringReader":15,"./support":17,"./uint8ArrayReader":18,"./utils":21,"./zipEntry":23}],23:[function(a,b){"use strict";function c(a,b){this.options=a,this.loadOptions=b}var d=a("./stringReader"),e=a("./utils"),f=a("./compressedObject"),g=a("./object"),h=0,i=3;c.prototype={isEncrypted:function(){return 1===(1&this.bitFlag)},useUTF8:function(){return 2048===(2048&this.bitFlag)},prepareCompressedContent:function(a,b,c){return function(){var d=a.index;a.setIndex(b);var e=a.readData(c);return a.setIndex(d),e}},prepareContent:function(a,b,c,d,f){return function(){var a=e.transformTo(d.uncompressInputType,this.getCompressedContent()),b=d.uncompress(a);if(b.length!==f)throw new Error("Bug : uncompressed data size mismatch");return b}},readLocalPart:function(a){var b,c;if(a.skip(22),this.fileNameLength=a.readInt(2),c=a.readInt(2),this.fileName=a.readString(this.fileNameLength),a.skip(c),-1==this.compressedSize||-1==this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory (compressedSize == -1 || uncompressedSize == -1)");if(b=e.findCompression(this.compressionMethod),null===b)throw new Error("Corrupted zip : compression "+e.pretty(this.compressionMethod)+" unknown (inner file : "+this.fileName+")");if(this.decompressed=new f,this.decompressed.compressedSize=this.compressedSize,this.decompressed.uncompressedSize=this.uncompressedSize,this.decompressed.crc32=this.crc32,this.decompressed.compressionMethod=this.compressionMethod,this.decompressed.getCompressedContent=this.prepareCompressedContent(a,a.index,this.compressedSize,b),this.decompressed.getContent=this.prepareContent(a,a.index,this.compressedSize,b,this.uncompressedSize),this.loadOptions.checkCRC32&&(this.decompressed=e.transformTo("string",this.decompressed.getContent()),g.crc32(this.decompressed)!==this.crc32))throw new Error("Corrupted zip : CRC32 mismatch")},readCentralPart:function(a){if(this.versionMadeBy=a.readInt(2),this.versionNeeded=a.readInt(2),this.bitFlag=a.readInt(2),this.compressionMethod=a.readString(2),this.date=a.readDate(),this.crc32=a.readInt(4),this.compressedSize=a.readInt(4),this.uncompressedSize=a.readInt(4),this.fileNameLength=a.readInt(2),this.extraFieldsLength=a.readInt(2),this.fileCommentLength=a.readInt(2),this.diskNumberStart=a.readInt(2),this.internalFileAttributes=a.readInt(2),this.externalFileAttributes=a.readInt(4),this.localHeaderOffset=a.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");this.fileName=a.readString(this.fileNameLength),this.readExtraFields(a),this.parseZIP64ExtraField(a),this.fileComment=a.readString(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var a=this.versionMadeBy>>8;this.dir=16&this.externalFileAttributes?!0:!1,a===h&&(this.dosPermissions=63&this.externalFileAttributes),a===i&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileName.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var a=new d(this.extraFields[1].value);this.uncompressedSize===e.MAX_VALUE_32BITS&&(this.uncompressedSize=a.readInt(8)),this.compressedSize===e.MAX_VALUE_32BITS&&(this.compressedSize=a.readInt(8)),this.localHeaderOffset===e.MAX_VALUE_32BITS&&(this.localHeaderOffset=a.readInt(8)),this.diskNumberStart===e.MAX_VALUE_32BITS&&(this.diskNumberStart=a.readInt(4))}},readExtraFields:function(a){var b,c,d,e=a.index;for(this.extraFields=this.extraFields||{};a.index<e+this.extraFieldsLength;)b=a.readInt(2),c=a.readInt(2),d=a.readString(c),this.extraFields[b]={id:b,length:c,value:d}},handleUTF8:function(){if(this.useUTF8())this.fileName=g.utf8decode(this.fileName),this.fileComment=g.utf8decode(this.fileComment);else{var a=this.findExtraFieldUnicodePath();null!==a&&(this.fileName=a);var b=this.findExtraFieldUnicodeComment();null!==b&&(this.fileComment=b)}},findExtraFieldUnicodePath:function(){var a=this.extraFields[28789];if(a){var b=new d(a.value);return 1!==b.readInt(1)?null:g.crc32(this.fileName)!==b.readInt(4)?null:g.utf8decode(b.readString(a.length-5))
+}return null},findExtraFieldUnicodeComment:function(){var a=this.extraFields[25461];if(a){var b=new d(a.value);return 1!==b.readInt(1)?null:g.crc32(this.fileComment)!==b.readInt(4)?null:g.utf8decode(b.readString(a.length-5))}return null}},b.exports=c},{"./compressedObject":2,"./object":13,"./stringReader":15,"./utils":21}],24:[function(a,b){"use strict";var c=a("./lib/utils/common").assign,d=a("./lib/deflate"),e=a("./lib/inflate"),f=a("./lib/zlib/constants"),g={};c(g,d,e,f),b.exports=g},{"./lib/deflate":25,"./lib/inflate":26,"./lib/utils/common":27,"./lib/zlib/constants":30}],25:[function(a,b,c){"use strict";function d(a,b){var c=new s(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}function f(a,b){return b=b||{},b.gzip=!0,d(a,b)}var g=a("./zlib/deflate.js"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=0,m=4,n=0,o=1,p=-1,q=0,r=8,s=function(a){this.options=h.assign({level:p,method:r,chunkSize:16384,windowBits:15,memLevel:8,strategy:q,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==n)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header)};s.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?m:l,e.input="string"==typeof a?i.string2buf(a):a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==o&&c!==n)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&d===m)&&this.onData("string"===this.options.to?i.buf2binstring(h.shrinkBuf(e.output,e.next_out)):h.shrinkBuf(e.output,e.next_out))}while((e.avail_in>0||0===e.avail_out)&&c!==o);return d===m?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===n):!0},s.prototype.onData=function(a){this.chunks.push(a)},s.prototype.onEnd=function(a){a===n&&(this.result="string"===this.options.to?this.chunks.join(""):h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=s,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(a,b,c){"use strict";function d(a,b){var c=new m(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=function(a){this.options=g.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};m.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,m=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,l.input="string"==typeof a?h.binstring2buf(a):a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new g.Buf8(m),l.next_out=0,l.avail_out=m),c=f.inflate(l,i.Z_NO_FLUSH),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&d===i.Z_FINISH)&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=m-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.shrinkBuf(l.output,l.next_out)))}while(l.avail_in>0&&c!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):!0},m.prototype.onData=function(a){this.chunks.push(a)},m.prototype.onEnd=function(a){a===i.Z_OK&&(this.result="string"===this.options.to?this.chunks.join(""):g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=m,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":27,"./utils/strings":28,"./zlib/constants":30,"./zlib/gzheader":33,"./zlib/inflate.js":35,"./zlib/messages":37,"./zlib/zstream":39}],27:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],28:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":27}],29:[function(a,b){"use strict";function c(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=c},{}],30:[function(a,b){b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],31:[function(a,b){"use strict";function c(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function d(a,b,c,d){var f=e,g=d+c;a=-1^a;for(var h=d;g>h;h++)a=a>>>8^f[255&(a^b[h])];return-1^a}var e=c();b.exports=d},{}],32:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(C.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){D._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-jb?a.strstart-(a.w_size-jb):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ib,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ib-(m-f),f=m-ib,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-jb)){C.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=hb)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+hb-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<hb)););}while(a.lookahead<jb&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===H)return sb;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return sb;if(a.strstart-a.block_start>=a.w_size-jb&&(h(a,!1),0===a.strm.avail_out))return sb}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ub:vb):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sb:sb}function o(a,b){for(var c,d;;){if(a.lookahead<jb){if(m(a),a.lookahead<jb&&b===H)return sb;if(0===a.lookahead)break}if(c=0,a.lookahead>=hb&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+hb-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-jb&&(a.match_length=l(a,c)),a.match_length>=hb)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-hb),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=hb){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+hb-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return sb}return a.insert=a.strstart<hb-1?a.strstart:hb-1,b===K?(h(a,!0),0===a.strm.avail_out?ub:vb):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sb:tb}function p(a,b){for(var c,d,e;;){if(a.lookahead<jb){if(m(a),a.lookahead<jb&&b===H)return sb;if(0===a.lookahead)break}if(c=0,a.lookahead>=hb&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+hb-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=hb-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-jb&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===S||a.match_length===hb&&a.strstart-a.match_start>4096)&&(a.match_length=hb-1)),a.prev_length>=hb&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-hb,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-hb),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+hb-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=hb-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return sb}else if(a.match_available){if(d=D._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return sb}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=D._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<hb-1?a.strstart:hb-1,b===K?(h(a,!0),0===a.strm.avail_out?ub:vb):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sb:tb}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ib){if(m(a),a.lookahead<=ib&&b===H)return sb;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=hb&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ib;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ib-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=hb?(c=D._tr_tally(a,1,a.match_length-hb),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sb}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ub:vb):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sb:tb}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sb;break}if(a.match_length=0,c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sb}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ub:vb):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sb:tb}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=hb-1,a.match_available=0,a.ins_h=0}function t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*fb),this.dyn_dtree=new C.Buf16(2*(2*db+1)),this.bl_tree=new C.Buf16(2*(2*eb+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(gb+1),this.heap=new C.Buf16(2*cb+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*cb+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?lb:qb,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+hb-1)/hb),i.window=new C.Buf8(2*i.w_size),i.head=new C.Buf16(i.hash_size),i.prev=new C.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new C.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===rb&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===lb)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=mb):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wb),h.status=qb);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=kb),m+=31-m%31,h.status=qb,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===mb)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=nb)}else h.status=nb;if(h.status===nb)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=ob)}else h.status=ob;if(h.status===ob)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pb)}else h.status=pb;if(h.status===pb&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=qb)):h.status=qb),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===rb&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==rb){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ub||o===vb)&&(h.status=rb),o===sb||o===ub)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===tb&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,M}return b!==K?M:h.wrap<=0?N:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==lb&&b!==mb&&b!==nb&&b!==ob&&b!==pb&&b!==qb&&b!==rb?d(a,O):(a.state=null,b===qb?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,ab=29,bb=256,cb=bb+1+ab,db=30,eb=19,fb=2*cb+1,gb=15,hb=3,ib=258,jb=ib+hb+1,kb=32,lb=42,mb=69,nb=73,ob=91,pb=103,qb=113,rb=666,sb=1,tb=2,ub=3,vb=4,wb=3,xb=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xb(0,0,0,0,n),new xb(4,4,8,4,o),new xb(4,5,16,8,o),new xb(4,6,32,32,o),new xb(4,4,16,16,p),new xb(8,16,32,32,p),new xb(8,16,128,128,p),new xb(8,32,128,256,p),new xb(32,128,258,1024,p),new xb(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(a,b){"use strict";function c(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=c},{}],34:[function(a,b){"use strict";var c=30,d=12;b.exports=function(a,b){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;e=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=e.dmax,l=e.wsize,m=e.whave,n=e.wnext,o=e.window,p=e.hold,q=e.bits,r=e.lencode,s=e.distcode,t=(1<<e.lenbits)-1,u=(1<<e.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){e.mode=d;break a}a.msg="invalid literal/length code",e.mode=c;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",e.mode=c;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",e.mode=c;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&e.sane){a.msg="invalid distance too far back",e.mode=c;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),e.hold=p,e.bits=q}},{}],35:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(ob),b.distcode=b.distdyn=new r.Buf32(pb),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,rb)}function k(a){if(sb){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sb=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,ob,pb,qb,rb,sb,tb,ub,vb,wb,xb,yb,zb,Ab=0,Bb=new r.Buf8(4),Cb=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xb=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Bb[0]=255&m,Bb[1]=m>>>8&255,c.check=t(c.check,Bb,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=lb;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=lb;break}if(m>>>=4,n-=4,wb=(15&m)+8,0===c.wbits)c.wbits=wb;else if(wb>c.wbits){a.msg="invalid window size",c.mode=lb;break}c.dmax=1<<wb,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=lb;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=lb;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Bb[0]=255&m,Bb[1]=m>>>8&255,c.check=t(c.check,Bb,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Bb[0]=255&m,Bb[1]=m>>>8&255,Bb[2]=m>>>16&255,Bb[3]=m>>>24&255,c.check=t(c.check,Bb,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Bb[0]=255&m,Bb[1]=m>>>8&255,c.check=t(c.check,Bb,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Bb[0]=255&m,Bb[1]=m>>>8&255,c.check=t(c.check,Bb,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wb=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wb)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wb=e[g+q++],c.head&&wb&&c.length<65536&&(c.head.name+=String.fromCharCode(wb));while(wb&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wb)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wb=e[g+q++],c.head&&wb&&c.length<65536&&(c.head.comment+=String.fromCharCode(wb));while(wb&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wb)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=lb;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ib;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=bb,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=lb}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=lb;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=lb;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Cb[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Cb[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,yb={bits:c.lenbits},xb=v(w,c.lens,0,19,c.lencode,0,c.work,yb),c.lenbits=yb.bits,xb){a.msg="invalid code lengths set",c.mode=lb;break}c.have=0,c.mode=ab;case ab:for(;c.have<c.nlen+c.ndist;){for(;Ab=c.lencode[m&(1<<c.lenbits)-1],qb=Ab>>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=qb);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sb)m>>>=qb,n-=qb,c.lens[c.have++]=sb;else{if(16===sb){for(zb=qb+2;zb>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qb,n-=qb,0===c.have){a.msg="invalid bit length repeat",c.mode=lb;break}wb=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sb){for(zb=qb+3;zb>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qb,n-=qb,wb=0,q=3+(7&m),m>>>=3,n-=3}else{for(zb=qb+7;zb>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qb,n-=qb,wb=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=lb;break}for(;q--;)c.lens[c.have++]=wb}}if(c.mode===lb)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=lb;break}if(c.lenbits=9,yb={bits:c.lenbits},xb=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,yb),c.lenbits=yb.bits,xb){a.msg="invalid literal/lengths set",c.mode=lb;break}if(c.distbits=6,c.distcode=c.distdyn,yb={bits:c.distbits},xb=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,yb),c.distbits=yb.bits,xb){a.msg="invalid distances set",c.mode=lb;break}if(c.mode=bb,b===B)break a;case bb:c.mode=cb;case cb:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);
+break}for(c.back=0;Ab=c.lencode[m&(1<<c.lenbits)-1],qb=Ab>>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=qb);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(rb&&0===(240&rb)){for(tb=qb,ub=rb,vb=sb;Ab=c.lencode[vb+((m&(1<<tb+ub)-1)>>tb)],qb=Ab>>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=tb+qb);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=tb,n-=tb,c.back+=tb}if(m>>>=qb,n-=qb,c.back+=qb,c.length=sb,0===rb){c.mode=hb;break}if(32&rb){c.back=-1,c.mode=V;break}if(64&rb){a.msg="invalid literal/length code",c.mode=lb;break}c.extra=15&rb,c.mode=db;case db:if(c.extra){for(zb=c.extra;zb>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=eb;case eb:for(;Ab=c.distcode[m&(1<<c.distbits)-1],qb=Ab>>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=qb);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&rb)){for(tb=qb,ub=rb,vb=sb;Ab=c.distcode[vb+((m&(1<<tb+ub)-1)>>tb)],qb=Ab>>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=tb+qb);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=tb,n-=tb,c.back+=tb}if(m>>>=qb,n-=qb,c.back+=qb,64&rb){a.msg="invalid distance code",c.mode=lb;break}c.offset=sb,c.extra=15&rb,c.mode=fb;case fb:if(c.extra){for(zb=c.extra;zb>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=lb;break}c.mode=gb;case gb:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=lb;break}q>c.wnext?(q-=c.wnext,ob=c.wsize-q):ob=c.wnext-q,q>c.length&&(q=c.length),pb=c.window}else pb=f,ob=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pb[ob++];while(--q);0===c.length&&(c.mode=cb);break;case hb:if(0===j)break a;f[h++]=c.length,j--,c.mode=cb;break;case ib:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=lb;break}m=0,n=0}c.mode=jb;case jb:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=lb;break}m=0,n=0}c.mode=kb;case kb:xb=D;break a;case lb:xb=G;break a;case mb:return H;case nb:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<lb&&(c.mode<ib||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=mb,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===bb||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xb===C&&(xb=I),xb)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,ab=19,bb=20,cb=21,db=22,eb=23,fb=24,gb=25,hb=26,ib=27,jb=28,kb=29,lb=30,mb=31,nb=32,ob=852,pb=592,qb=15,rb=qb,sb=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":27,"./adler32":29,"./crc32":31,"./inffast":34,"./inftrees":36}],36:[function(a,b){"use strict";var c=a("../utils/common"),d=15,e=852,f=592,g=0,h=1,i=2,j=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],k=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],l=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],m=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,n,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new c.Buf16(d+1),Q=new c.Buf16(d+1),R=null,S=0;for(D=0;d>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[n+E]]++;for(H=C,G=d;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;d>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===g||1!==G))return-1;for(Q[1]=0,D=1;d>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[n+E]&&(r[Q[b[n+E]]++]=E);if(a===g?(N=R=r,y=19):a===h?(N=j,O-=257,R=k,S-=257,y=256):(N=l,R=m,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===h&&L>e||a===i&&L>f)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[n+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===h&&L>e||a===i&&L>f)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":27}],37:[function(a,b){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],38:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a){return 256>a?gb[a]:gb[256+(a>>>7)]}function f(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function g(a,b,c){a.bi_valid>V-c?(a.bi_buf|=b<<a.bi_valid&65535,f(a,a.bi_buf),a.bi_buf=b>>V-a.bi_valid,a.bi_valid+=c-V):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function h(a,b,c){g(a,c[2*b],c[2*b+1])}function i(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function j(a){16===a.bi_valid?(f(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function k(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;U>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;T>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function l(a,b,c){var d,e,f=new Array(U+1),g=0;for(d=1;U>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=i(f[h]++,h))}}function m(){var a,b,c,d,e,f=new Array(U+1);for(c=0,d=0;O-1>d;d++)for(ib[d]=c,a=0;a<1<<_[d];a++)hb[c++]=d;for(hb[c-1]=d,e=0,d=0;16>d;d++)for(jb[d]=e,a=0;a<1<<ab[d];a++)gb[e++]=d;for(e>>=7;R>d;d++)for(jb[d]=e<<7,a=0;a<1<<ab[d]-7;a++)gb[256+e++]=d;for(b=0;U>=b;b++)f[b]=0;for(a=0;143>=a;)eb[2*a+1]=8,a++,f[8]++;for(;255>=a;)eb[2*a+1]=9,a++,f[9]++;for(;279>=a;)eb[2*a+1]=7,a++,f[7]++;for(;287>=a;)eb[2*a+1]=8,a++,f[8]++;for(l(eb,Q+1,f),a=0;R>a;a++)fb[2*a+1]=5,fb[2*a]=i(a,5);kb=new nb(eb,_,P+1,Q,U),lb=new nb(fb,ab,0,R,U),mb=new nb(new Array(0),bb,0,S,W)}function n(a){var b;for(b=0;Q>b;b++)a.dyn_ltree[2*b]=0;for(b=0;R>b;b++)a.dyn_dtree[2*b]=0;for(b=0;S>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*X]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function o(a){a.bi_valid>8?f(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function p(a,b,c,d){o(a),d&&(f(a,c),f(a,~c)),E.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function q(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function r(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&q(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!q(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function s(a,b,c){var d,f,i,j,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],f=a.pending_buf[a.l_buf+k],k++,0===d?h(a,f,b):(i=hb[f],h(a,i+P+1,b),j=_[i],0!==j&&(f-=ib[i],g(a,f,j)),d--,i=e(d),h(a,i,c),j=ab[i],0!==j&&(d-=jb[i],g(a,d,j)));while(k<a.last_lit);h(a,X,b)}function t(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=T,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)r(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],r(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,r(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],k(a,b),l(f,j,a.bl_count)}function u(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*Y]++):10>=h?a.bl_tree[2*Z]++:a.bl_tree[2*$]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function v(a,b,c){var d,e,f=-1,i=b[1],j=0,k=7,l=4;for(0===i&&(k=138,l=3),d=0;c>=d;d++)if(e=i,i=b[2*(d+1)+1],!(++j<k&&e===i)){if(l>j){do h(a,e,a.bl_tree);while(0!==--j)}else 0!==e?(e!==f&&(h(a,e,a.bl_tree),j--),h(a,Y,a.bl_tree),g(a,j-3,2)):10>=j?(h(a,Z,a.bl_tree),g(a,j-3,3)):(h(a,$,a.bl_tree),g(a,j-11,7));j=0,f=e,0===i?(k=138,l=3):e===i?(k=6,l=3):(k=7,l=4)}}function w(a){var b;for(u(a,a.dyn_ltree,a.l_desc.max_code),u(a,a.dyn_dtree,a.d_desc.max_code),t(a,a.bl_desc),b=S-1;b>=3&&0===a.bl_tree[2*cb[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function x(a,b,c,d){var e;for(g(a,b-257,5),g(a,c-1,5),g(a,d-4,4),e=0;d>e;e++)g(a,a.bl_tree[2*cb[e]+1],3);v(a,a.dyn_ltree,b-1),v(a,a.dyn_dtree,c-1)}function y(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return G;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return H;for(b=32;P>b;b++)if(0!==a.dyn_ltree[2*b])return H;return G}function z(a){pb||(m(),pb=!0),a.l_desc=new ob(a.dyn_ltree,kb),a.d_desc=new ob(a.dyn_dtree,lb),a.bl_desc=new ob(a.bl_tree,mb),a.bi_buf=0,a.bi_valid=0,n(a)}function A(a,b,c,d){g(a,(J<<1)+(d?1:0),3),p(a,b,c,!0)}function B(a){g(a,K<<1,3),h(a,X,eb),j(a)}function C(a,b,c,d){var e,f,h=0;a.level>0?(a.strm.data_type===I&&(a.strm.data_type=y(a)),t(a,a.l_desc),t(a,a.d_desc),h=w(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?A(a,b,c,d):a.strategy===F||f===e?(g(a,(K<<1)+(d?1:0),3),s(a,eb,fb)):(g(a,(L<<1)+(d?1:0),3),x(a,a.l_desc.max_code+1,a.d_desc.max_code+1,h+1),s(a,a.dyn_ltree,a.dyn_dtree)),n(a),d&&o(a)}function D(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(hb[c]+P+1)]++,a.dyn_dtree[2*e(b)]++),a.last_lit===a.lit_bufsize-1}var E=a("../utils/common"),F=4,G=0,H=1,I=2,J=0,K=1,L=2,M=3,N=258,O=29,P=256,Q=P+1+O,R=30,S=19,T=2*Q+1,U=15,V=16,W=7,X=256,Y=16,Z=17,$=18,_=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ab=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],bb=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],cb=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],db=512,eb=new Array(2*(Q+2));d(eb);var fb=new Array(2*R);d(fb);var gb=new Array(db);d(gb);var hb=new Array(N-M+1);d(hb);var ib=new Array(O);d(ib);var jb=new Array(R);d(jb);var kb,lb,mb,nb=function(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length},ob=function(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b},pb=!1;c._tr_init=z,c._tr_stored_block=A,c._tr_flush_block=C,c._tr_tally=D,c._tr_align=B},{"../utils/common":27}],39:[function(a,b){"use strict";function c(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=c},{}]},{},[9])(9)}); \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/js_external/shapiro-wilk.js b/wqflask/wqflask/static/new/js_external/shapiro-wilk.js
new file mode 100644
index 00000000..1084b9f5
--- /dev/null
+++ b/wqflask/wqflask/static/new/js_external/shapiro-wilk.js
@@ -0,0 +1,197 @@
+/*
+ * Ported from http://svn.r-project.org/R/trunk/src/library/stats/src/swilk.c
+ *
+ * R : A Computer Language for Statistical Data Analysis
+ * Copyright (C) 2000-12 The R Core Team.
+ *
+ * Based on Applied Statistics algorithms AS181, R94
+ * (C) Royal Statistical Society 1982, 1995
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, a copy is available at
+ * http://www.r-project.org/Licenses/
+ */
+
+function sign(x) {
+ if (x == 0)
+ return 0;
+ return x > 0 ? 1 : -1;
+}
+
+function ShapiroWilkW(x)
+{
+ function poly(cc, nord, x)
+ {
+ /* Algorithm AS 181.2 Appl. Statist. (1982) Vol. 31, No. 2
+ Calculates the algebraic polynomial of order nord-1 with array of coefficients cc.
+ Zero order coefficient is cc(1) = cc[0] */
+ var p;
+ var ret_val;
+
+ ret_val = cc[0];
+ if (nord > 1) {
+ p = x * cc[nord-1];
+ for (j = nord - 2; j > 0; j--)
+ p = (p + cc[j]) * x;
+ ret_val += p;
+ }
+ return ret_val;
+ }
+ x = x.sort(function (a, b) { return a - b; });
+ var n = x.length;
+ if (n < 3)
+ return undefined;
+ var nn2 = Math.floor(n / 2);
+ var a = new Array(Math.floor(nn2) + 1); /* 1-based */
+
+/* ALGORITHM AS R94 APPL. STATIST. (1995) vol.44, no.4, 547-551.
+
+ Calculates the Shapiro-Wilk W test and its significance level
+*/
+ var small = 1e-19;
+
+ /* polynomial coefficients */
+ var g = [ -2.273, 0.459 ];
+ var c1 = [ 0, 0.221157, -0.147981, -2.07119, 4.434685, -2.706056 ];
+ var c2 = [ 0, 0.042981, -0.293762, -1.752461, 5.682633, -3.582633 ];
+ var c3 = [ 0.544, -0.39978, 0.025054, -6.714e-4 ];
+ var c4 = [ 1.3822, -0.77857, 0.062767, -0.0020322 ];
+ var c5 = [ -1.5861, -0.31082, -0.083751, 0.0038915 ];
+ var c6 = [ -0.4803, -0.082676, 0.0030302 ];
+
+ /* Local variables */
+ var i, j, i1;
+
+ var ssassx, summ2, ssumm2, gamma, range;
+ var a1, a2, an, m, s, sa, xi, sx, xx, y, w1;
+ var fac, asa, an25, ssa, sax, rsn, ssx, xsx;
+
+ var pw = 1;
+ an = n;
+
+ if (n == 3)
+ a[1] = 0.70710678;/* = sqrt(1/2) */
+ else {
+ an25 = an + 0.25;
+ summ2 = 0.0;
+ for (i = 1; i <= nn2; i++) {
+ a[i] = jStat.normal.inv((i - 0.375) / an25, 0, 1); // p(X <= x),
+ var r__1 = a[i];
+ summ2 += r__1 * r__1;
+ }
+ summ2 *= 2;
+ ssumm2 = Math.sqrt(summ2);
+ rsn = 1 / Math.sqrt(an);
+ a1 = poly(c1, 6, rsn) - a[1] / ssumm2;
+
+ /* Normalize a[] */
+ if (n > 5) {
+ i1 = 3;
+ a2 = -a[2] / ssumm2 + poly(c2, 6, rsn);
+ fac = Math.sqrt((summ2 - 2 * (a[1] * a[1]) - 2 * (a[2] * a[2])) / (1 - 2 * (a1 * a1) - 2 * (a2 * a2)));
+ a[2] = a2;
+ } else {
+ i1 = 2;
+ fac = Math.sqrt((summ2 - 2 * (a[1] * a[1])) / ( 1 - 2 * (a1 * a1)));
+ }
+ a[1] = a1;
+ for (i = i1; i <= nn2; i++)
+ a[i] /= - fac;
+ }
+
+/* Check for zero range */
+
+ range = x[n - 1] - x[0];
+ if (range < small) {
+ console.log('range is too small!')
+ return undefined;
+ }
+
+
+/* Check for correct sort order on range - scaled X */
+
+ xx = x[0] / range;
+ sx = xx;
+ sa = -a[1];
+ for (i = 1, j = n - 1; i < n; j--) {
+ xi = x[i] / range;
+ if (xx - xi > small) {
+ console.log("xx - xi is too big.", xx - xi);
+ return undefined;
+ }
+ sx += xi;
+ i++;
+ if (i != j)
+ sa += sign(i - j) * a[Math.min(i, j)];
+ xx = xi;
+ }
+ if (n > 5000) {
+ console.log("n is too big!")
+ return undefined;
+ }
+
+
+/* Calculate W statistic as squared correlation
+ between data and coefficients */
+
+ sa /= n;
+ sx /= n;
+ ssa = ssx = sax = 0.;
+ for (i = 0, j = n - 1; i < n; i++, j--) {
+ if (i != j)
+ asa = sign(i - j) * a[1 + Math.min(i, j)] - sa;
+ else
+ asa = -sa;
+ xsx = x[i] / range - sx;
+ ssa += asa * asa;
+ ssx += xsx * xsx;
+ sax += asa * xsx;
+ }
+
+/* W1 equals (1-W) calculated to avoid excessive rounding error
+ for W very near 1 (a potential problem in very large samples) */
+
+ ssassx = Math.sqrt(ssa * ssx);
+ w1 = (ssassx - sax) * (ssassx + sax) / (ssa * ssx);
+ var w = 1 - w1;
+
+/* Calculate significance level for W */
+
+ if (n == 3) {/* exact P value : */
+ var pi6 = 1.90985931710274; /* = 6/pi */
+ var stqr = 1.04719755119660; /* = asin(sqrt(3/4)) */
+ pw = pi6 * (Math.asin(Math.sqrt(w)) - stqr);
+ if (pw < 0.)
+ pw = 0;
+ return w;
+ }
+ y = Math.log(w1);
+ xx = Math.log(an);
+ if (n <= 11) {
+ gamma = poly(g, 2, an);
+ if (y >= gamma) {
+ pw = 1e-99; /* an "obvious" value, was 'small' which was 1e-19f */
+ return w;
+ }
+ y = -Math.log(gamma - y);
+ m = poly(c3, 4, an);
+ s = Math.exp(poly(c4, 4, an));
+ } else { /* n >= 12 */
+ m = poly(c5, 4, xx);
+ s = Math.exp(poly(c6, 3, xx));
+ }
+
+ pw = 0.5 - 0.5 * jStat.erf((y - m) / Math.sqrt(2) / s)
+
+ return {w: w, p: pw};
+}
diff --git a/wqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables.css b/wqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables.css
index 7a674d3a..931ec6b3 100755
--- a/wqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables.css
+++ b/wqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables.css
@@ -1,224 +1,455 @@
-
/*
- * Table
+ * Table styles
*/
table.dataTable {
- margin: 0 auto;
- clear: both;
- width: 100%;
-}
-
-table.dataTable thead th {
- padding: 3px 18px 3px 10px;
- border-bottom: 1px solid black;
- font-weight: bold;
- cursor: pointer;
- *cursor: hand;
+ //width: 100%;
+ margin: 0 auto;
+ clear: both;
+ border-collapse: separate;
+ border-spacing: 0;
+ /*
+ * Header and footer styles
+ */
+ /*
+ * Body styles
+ */
}
-
+table.dataTable thead th,
table.dataTable tfoot th {
- padding: 3px 18px 3px 10px;
- border-top: 1px solid black;
- font-weight: bold;
+ font-weight: bold;
}
-
-table.dataTable td {
- padding: 3px 10px;
+table.dataTable thead th,
+table.dataTable thead td {
+ padding: 10px 18px;
+ border-bottom: 1px solid #111;
}
-
-table.dataTable td.center,
+table.dataTable thead th:active,
+table.dataTable thead td:active {
+ outline: none;
+}
+table.dataTable tfoot th,
+table.dataTable tfoot td {
+ padding: 10px 18px 6px 18px;
+ border-top: 1px solid #111;
+}
+table.dataTable thead .sorting,
+table.dataTable thead .sorting_asc,
+table.dataTable thead .sorting_desc {
+ cursor: pointer;
+ *cursor: hand;
+}
+table.dataTable thead .sorting,
+table.dataTable thead .sorting_asc,
+table.dataTable thead .sorting_desc,
+table.dataTable thead .sorting_asc_disabled,
+table.dataTable thead .sorting_desc_disabled {
+ background-repeat: no-repeat;
+ background-position: center right;
+}
+table.dataTable thead .sorting {
+ background-image: url("../images/sort_both.png");
+}
+table.dataTable thead .sorting_asc {
+ background-image: url("../images/sort_asc.png");
+}
+table.dataTable thead .sorting_desc {
+ background-image: url("../images/sort_desc.png");
+}
+table.dataTable thead .sorting_asc_disabled {
+ background-image: url("../images/sort_asc_disabled.png");
+}
+table.dataTable thead .sorting_desc_disabled {
+ background-image: url("../images/sort_desc_disabled.png");
+}
+table.dataTable tbody tr {
+ background-color: #ffffff;
+}
+table.dataTable tbody tr.selected {
+ background-color: #ffff99;
+}
+table.dataTable tbody th,
+table.dataTable tbody td {
+ padding: 8px 10px;
+}
+table.dataTable.row-border tbody th, table.dataTable.row-border tbody td, table.dataTable.display tbody th, table.dataTable.display tbody td {
+ border-top: 1px solid #ddd;
+}
+table.dataTable.row-border tbody tr:first-child th,
+table.dataTable.row-border tbody tr:first-child td, table.dataTable.display tbody tr:first-child th,
+table.dataTable.display tbody tr:first-child td {
+ border-top: none;
+}
+table.dataTable.cell-border tbody th, table.dataTable.cell-border tbody td {
+ border-top: 1px solid #ddd;
+ border-right: 1px solid #ddd;
+}
+table.dataTable.cell-border tbody tr th:first-child,
+table.dataTable.cell-border tbody tr td:first-child {
+ border-left: 1px solid #ddd;
+}
+table.dataTable.cell-border tbody tr:first-child th,
+table.dataTable.cell-border tbody tr:first-child td {
+ border-top: none;
+}
+table.dataTable.stripe tbody tr.odd, table.dataTable.display tbody tr.odd {
+ background-color: #f9f9f9;
+}
+table.dataTable.stripe tbody tr.odd.selected, table.dataTable.display tbody tr.odd.selected {
+ background-color: #abb9d3;
+}
+table.dataTable.hover tbody tr:hover, table.dataTable.display tbody tr:hover {
+ background-color: whitesmoke;
+}
+table.dataTable.hover tbody tr:hover.selected, table.dataTable.display tbody tr:hover.selected {
+ background-color: #a9b7d1;
+}
+table.dataTable.order-column tbody tr > .sorting_1,
+table.dataTable.order-column tbody tr > .sorting_2,
+table.dataTable.order-column tbody tr > .sorting_3, table.dataTable.display tbody tr > .sorting_1,
+table.dataTable.display tbody tr > .sorting_2,
+table.dataTable.display tbody tr > .sorting_3 {
+ background-color: #f9f9f9;
+}
+table.dataTable.order-column tbody tr.selected > .sorting_1,
+table.dataTable.order-column tbody tr.selected > .sorting_2,
+table.dataTable.order-column tbody tr.selected > .sorting_3, table.dataTable.display tbody tr.selected > .sorting_1,
+table.dataTable.display tbody tr.selected > .sorting_2,
+table.dataTable.display tbody tr.selected > .sorting_3 {
+ background-color: #acbad4;
+}
+table.dataTable.display tbody tr.odd > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd > .sorting_1 {
+ background-color: #f1f1f1;
+}
+table.dataTable.display tbody tr.odd > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd > .sorting_2 {
+ background-color: #f3f3f3;
+}
+table.dataTable.display tbody tr.odd > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd > .sorting_3 {
+ background-color: whitesmoke;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_1 {
+ background-color: #a6b3cd;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_2 {
+ background-color: #a7b5ce;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_3 {
+ background-color: #a9b6d0;
+}
+table.dataTable.display tbody tr.even > .sorting_1, table.dataTable.order-column.stripe tbody tr.even > .sorting_1 {
+ background-color: #f9f9f9;
+}
+table.dataTable.display tbody tr.even > .sorting_2, table.dataTable.order-column.stripe tbody tr.even > .sorting_2 {
+ background-color: #fbfbfb;
+}
+table.dataTable.display tbody tr.even > .sorting_3, table.dataTable.order-column.stripe tbody tr.even > .sorting_3 {
+ background-color: #fdfdfd;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_1 {
+ background-color: #acbad4;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_2 {
+ background-color: #adbbd6;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_3 {
+ background-color: #afbdd8;
+}
+table.dataTable.display tbody tr:hover > .sorting_1, table.dataTable.order-column.hover tbody tr:hover > .sorting_1 {
+ background-color: #eaeaea;
+}
+table.dataTable.display tbody tr:hover > .sorting_2, table.dataTable.order-column.hover tbody tr:hover > .sorting_2 {
+ background-color: #ebebeb;
+}
+table.dataTable.display tbody tr:hover > .sorting_3, table.dataTable.order-column.hover tbody tr:hover > .sorting_3 {
+ background-color: #eeeeee;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_1 {
+ background-color: #a1aec7;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_2, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_2 {
+ background-color: #a2afc8;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_3, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_3 {
+ background-color: #a4b2cb;
+}
+table.dataTable.no-footer {
+ border-bottom: 1px solid #111;
+}
+table.dataTable.nowrap th, table.dataTable.nowrap td {
+ white-space: nowrap;
+}
+table.dataTable.compact thead th,
+table.dataTable.compact thead td {
+ padding: 4px 17px 4px 4px;
+}
+table.dataTable.compact tfoot th,
+table.dataTable.compact tfoot td {
+ padding: 4px;
+}
+table.dataTable.compact tbody th,
+table.dataTable.compact tbody td {
+ padding: 4px;
+}
+table.dataTable th.dt-left,
+table.dataTable td.dt-left {
+ text-align: left;
+}
+table.dataTable th.dt-center,
+table.dataTable td.dt-center,
table.dataTable td.dataTables_empty {
- text-align: center;
+ text-align: center;
+}
+table.dataTable th.dt-right,
+table.dataTable td.dt-right {
+ text-align: right;
+}
+table.dataTable th.dt-justify,
+table.dataTable td.dt-justify {
+ text-align: justify;
+}
+table.dataTable th.dt-nowrap,
+table.dataTable td.dt-nowrap {
+ white-space: nowrap;
+}
+table.dataTable thead th.dt-head-left,
+table.dataTable thead td.dt-head-left,
+table.dataTable tfoot th.dt-head-left,
+table.dataTable tfoot td.dt-head-left {
+ text-align: left;
+}
+table.dataTable thead th.dt-head-center,
+table.dataTable thead td.dt-head-center,
+table.dataTable tfoot th.dt-head-center,
+table.dataTable tfoot td.dt-head-center {
+ text-align: center;
+}
+table.dataTable thead th.dt-head-right,
+table.dataTable thead td.dt-head-right,
+table.dataTable tfoot th.dt-head-right,
+table.dataTable tfoot td.dt-head-right {
+ text-align: right;
+}
+table.dataTable thead th.dt-head-justify,
+table.dataTable thead td.dt-head-justify,
+table.dataTable tfoot th.dt-head-justify,
+table.dataTable tfoot td.dt-head-justify {
+ text-align: justify;
+}
+table.dataTable thead th.dt-head-nowrap,
+table.dataTable thead td.dt-head-nowrap,
+table.dataTable tfoot th.dt-head-nowrap,
+table.dataTable tfoot td.dt-head-nowrap {
+ white-space: nowrap;
+}
+table.dataTable tbody th.dt-body-left,
+table.dataTable tbody td.dt-body-left {
+ text-align: left;
+}
+table.dataTable tbody th.dt-body-center,
+table.dataTable tbody td.dt-body-center {
+ text-align: center;
+}
+table.dataTable tbody th.dt-body-right,
+table.dataTable tbody td.dt-body-right {
+ text-align: right;
+}
+table.dataTable tbody th.dt-body-justify,
+table.dataTable tbody td.dt-body-justify {
+ text-align: justify;
+}
+table.dataTable tbody th.dt-body-nowrap,
+table.dataTable tbody td.dt-body-nowrap {
+ white-space: nowrap;
}
-table.dataTable tr.odd { background-color: #E2E4FF; }
-table.dataTable tr.even { background-color: white; }
-
-table.dataTable tr.odd td.sorting_1 { background-color: #D3D6FF; }
-table.dataTable tr.odd td.sorting_2 { background-color: #DADCFF; }
-table.dataTable tr.odd td.sorting_3 { background-color: #E0E2FF; }
-table.dataTable tr.even td.sorting_1 { background-color: #EAEBFF; }
-table.dataTable tr.even td.sorting_2 { background-color: #F2F3FF; }
-table.dataTable tr.even td.sorting_3 { background-color: #F9F9FF; }
-
-table.dataTable tr.outlier td{ background-color: #FFFF00; }
-
+table.dataTable,
+table.dataTable th,
+table.dataTable td {
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+}
/*
- * Table wrapper
+ * Control feature layout
*/
.dataTables_wrapper {
- position: relative;
- clear: both;
- float: left;
- *zoom: 1;
+ position: relative;
+ clear: both;
+ *zoom: 1;
+ zoom: 1;
}
-
-
-/*
- * Page length menu
- */
-.dataTables_length {
- float: left;
+.dataTables_wrapper .dataTables_length {
+ float: left;
}
-
-
-/*
- * Filter
- */
-.dataTables_filter {
- float: right;
- text-align: right;
+.dataTables_wrapper .dataTables_filter {
+ float: right;
+ text-align: right;
}
-
-
-/*
- * Table information
- */
-.dataTables_info {
- clear: both;
- float: left;
+.dataTables_wrapper .dataTables_filter input {
+ margin-left: 0.5em;
}
-
-
-/*
- * Pagination
- */
-.dataTables_paginate {
- float: right;
- text-align: right;
+.dataTables_wrapper .dataTables_info {
+ clear: both;
+ float: left;
+ padding-top: 0.755em;
}
-
-/* Two button pagination - previous / next */
-.paginate_disabled_previous,
-.paginate_enabled_previous,
-.paginate_disabled_next,
-.paginate_enabled_next {
- height: 19px;
- float: left;
- cursor: pointer;
- *cursor: hand;
- color: #111 !important;
-}
-.paginate_disabled_previous:hover,
-.paginate_enabled_previous:hover,
-.paginate_disabled_next:hover,
-.paginate_enabled_next:hover {
- text-decoration: none !important;
-}
-.paginate_disabled_previous:active,
-.paginate_enabled_previous:active,
-.paginate_disabled_next:active,
-.paginate_enabled_next:active {
- outline: none;
+.dataTables_wrapper .dataTables_paginate {
+ float: right;
+ text-align: right;
+ padding-top: 0.25em;
}
-
-.paginate_disabled_previous,
-.paginate_disabled_next {
- color: #666 !important;
+.dataTables_wrapper .dataTables_paginate .paginate_button {
+ box-sizing: border-box;
+ display: inline-block;
+ min-width: 1.5em;
+ padding: 0.5em 1em;
+ margin-left: 2px;
+ text-align: center;
+ text-decoration: none !important;
+ cursor: pointer;
+ *cursor: hand;
+ color: #333 !important;
+ border: 1px solid transparent;
}
-.paginate_disabled_previous,
-.paginate_enabled_previous {
- padding-left: 23px;
+.dataTables_wrapper .dataTables_paginate .paginate_button.current, .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover {
+ color: #333 !important;
+ border: 1px solid #cacaca;
+ background-color: white;
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, white), color-stop(100%, #dcdcdc));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(top, white 0%, #dcdcdc 100%);
+ /* Chrome10+,Safari5.1+ */
+ background: -moz-linear-gradient(top, white 0%, #dcdcdc 100%);
+ /* FF3.6+ */
+ background: -ms-linear-gradient(top, white 0%, #dcdcdc 100%);
+ /* IE10+ */
+ background: -o-linear-gradient(top, white 0%, #dcdcdc 100%);
+ /* Opera 11.10+ */
+ background: linear-gradient(to bottom, white 0%, #dcdcdc 100%);
+ /* W3C */
}
-.paginate_disabled_next,
-.paginate_enabled_next {
- padding-right: 23px;
- margin-left: 10px;
+.dataTables_wrapper .dataTables_paginate .paginate_button.disabled, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active {
+ cursor: default;
+ color: #666 !important;
+ border: 1px solid transparent;
+ background: transparent;
+ box-shadow: none;
}
-
-.paginate_enabled_previous { background: url('../images/back_enabled.png') no-repeat top left; }
-.paginate_enabled_previous:hover { background: url('../images/back_enabled_hover.png') no-repeat top left; }
-.paginate_disabled_previous { background: url('../images/back_disabled.png') no-repeat top left; }
-
-.paginate_enabled_next { background: url('../images/forward_enabled.png') no-repeat top right; }
-.paginate_enabled_next:hover { background: url('../images/forward_enabled_hover.png') no-repeat top right; }
-.paginate_disabled_next { background: url('../images/forward_disabled.png') no-repeat top right; }
-
-/* Full number pagination */
-.paging_full_numbers {
- height: 22px;
- line-height: 22px;
+.dataTables_wrapper .dataTables_paginate .paginate_button:hover {
+ color: white !important;
+ border: 1px solid #111;
+ background-color: #585858;
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #585858), color-stop(100%, #111));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(top, #585858 0%, #111 100%);
+ /* Chrome10+,Safari5.1+ */
+ background: -moz-linear-gradient(top, #585858 0%, #111 100%);
+ /* FF3.6+ */
+ background: -ms-linear-gradient(top, #585858 0%, #111 100%);
+ /* IE10+ */
+ background: -o-linear-gradient(top, #585858 0%, #111 100%);
+ /* Opera 11.10+ */
+ background: linear-gradient(to bottom, #585858 0%, #111 100%);
+ /* W3C */
}
-.paging_full_numbers a:active {
- outline: none
+.dataTables_wrapper .dataTables_paginate .paginate_button:active {
+ outline: none;
+ background-color: #2b2b2b;
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #2b2b2b), color-stop(100%, #0c0c0c));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
+ /* Chrome10+,Safari5.1+ */
+ background: -moz-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
+ /* FF3.6+ */
+ background: -ms-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
+ /* IE10+ */
+ background: -o-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
+ /* Opera 11.10+ */
+ background: linear-gradient(to bottom, #2b2b2b 0%, #0c0c0c 100%);
+ /* W3C */
+ box-shadow: inset 0 0 3px #111;
}
-.paging_full_numbers a:hover {
- text-decoration: none;
+.dataTables_wrapper .dataTables_paginate .ellipsis {
+ padding: 0 1em;
}
-
-.paging_full_numbers a.paginate_button,
-.paging_full_numbers a.paginate_active {
- border: 1px solid #aaa;
- -webkit-border-radius: 5px;
- -moz-border-radius: 5px;
- border-radius: 5px;
- padding: 2px 5px;
- margin: 0 3px;
- cursor: pointer;
- *cursor: hand;
- color: #333 !important;
+.dataTables_wrapper .dataTables_processing {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: 100%;
+ height: 40px;
+ margin-left: -50%;
+ margin-top: -25px;
+ padding-top: 20px;
+ text-align: center;
+ font-size: 1.2em;
+ background-color: white;
+ background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255, 255, 255, 0)), color-stop(25%, rgba(255, 255, 255, 0.9)), color-stop(75%, rgba(255, 255, 255, 0.9)), color-stop(100%, rgba(255, 255, 255, 0)));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ /* Chrome10+,Safari5.1+ */
+ background: -moz-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ /* FF3.6+ */
+ background: -ms-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ /* IE10+ */
+ background: -o-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ /* Opera 11.10+ */
+ background: linear-gradient(to right, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ /* W3C */
}
-
-.paging_full_numbers a.paginate_button {
- background-color: #ddd;
+.dataTables_wrapper .dataTables_length,
+.dataTables_wrapper .dataTables_filter,
+.dataTables_wrapper .dataTables_info,
+.dataTables_wrapper .dataTables_processing,
+.dataTables_wrapper .dataTables_paginate {
+ color: #333;
}
-
-.paging_full_numbers a.paginate_button:hover {
- background-color: #ccc;
- text-decoration: none !important;
+.dataTables_wrapper .dataTables_scroll {
+ clear: both;
}
-
-.paging_full_numbers a.paginate_active {
- background-color: #99B3FF;
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody {
+ *margin-top: -1px;
+ -webkit-overflow-scrolling: touch;
}
-
-
-/*
- * Processing indicator
- */
-.dataTables_processing {
- position: absolute;
- top: 50%;
- left: 50%;
- width: 250px;
- height: 30px;
- margin-left: -125px;
- margin-top: -15px;
- padding: 14px 0 2px 0;
- border: 1px solid #ddd;
- text-align: center;
- color: #999;
- font-size: 14px;
- background-color: white;
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody th > div.dataTables_sizing,
+.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody td > div.dataTables_sizing {
+ height: 0;
+ overflow: hidden;
+ margin: 0 !important;
+ padding: 0 !important;
}
-
-
-/*
- * Sorting
- */
-.sorting { background: url('../images/sort_both.png') no-repeat center right; }
-.sorting_asc { background: url('../images/sort_asc.png') no-repeat center right; }
-.sorting_desc { background: url('../images/sort_desc.png') no-repeat center right; }
-
-.sorting_asc_disabled { background: url('../images/sort_asc_disabled.png') no-repeat center right; }
-.sorting_desc_disabled { background: url('../images/sort_desc_disabled.png') no-repeat center right; }
-
-table.dataTable thead th:active,
-table.dataTable thead td:active {
- outline: none;
+.dataTables_wrapper.no-footer .dataTables_scrollBody {
+ border-bottom: 1px solid #111;
}
-
-
-/*
- * Scrolling
- */
-.dataTables_scroll {
- clear: both;
+.dataTables_wrapper.no-footer div.dataTables_scrollHead table,
+.dataTables_wrapper.no-footer div.dataTables_scrollBody table {
+ border-bottom: none;
}
-
-.dataTables_scrollBody {
- *margin-top: -1px;
- -webkit-overflow-scrolling: touch;
+.dataTables_wrapper:after {
+ visibility: hidden;
+ display: block;
+ content: "";
+ clear: both;
+ height: 0;
}
+@media screen and (max-width: 767px) {
+ .dataTables_wrapper .dataTables_info,
+ .dataTables_wrapper .dataTables_paginate {
+ float: none;
+ text-align: center;
+ }
+ .dataTables_wrapper .dataTables_paginate {
+ margin-top: 0.5em;
+ }
+}
+@media screen and (max-width: 640px) {
+ .dataTables_wrapper .dataTables_length,
+ .dataTables_wrapper .dataTables_filter {
+ float: none;
+ text-align: center;
+ }
+ .dataTables_wrapper .dataTables_filter {
+ margin-top: 0.5em;
+ }
+}
diff --git a/wqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables.min.css b/wqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables.min.css
new file mode 100644
index 00000000..2edb32f7
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables.min.css
@@ -0,0 +1 @@
+table.dataTable{width:100%;margin:0 auto;clear:both;border-collapse:separate;border-spacing:0}table.dataTable thead th,table.dataTable tfoot th{font-weight:bold}table.dataTable thead th,table.dataTable thead td{padding:10px 18px;border-bottom:1px solid #111}table.dataTable thead th:active,table.dataTable thead td:active{outline:none}table.dataTable tfoot th,table.dataTable tfoot td{padding:10px 18px 6px 18px;border-top:1px solid #111}table.dataTable thead .sorting,table.dataTable thead .sorting_asc,table.dataTable thead .sorting_desc{cursor:pointer;*cursor:hand}table.dataTable thead .sorting,table.dataTable thead .sorting_asc,table.dataTable thead .sorting_desc,table.dataTable thead .sorting_asc_disabled,table.dataTable thead .sorting_desc_disabled{background-repeat:no-repeat;background-position:center right}table.dataTable thead .sorting{background-image:url("../images/sort_both.png")}table.dataTable thead .sorting_asc{background-image:url("../images/sort_asc.png")}table.dataTable thead .sorting_desc{background-image:url("../images/sort_desc.png")}table.dataTable thead .sorting_asc_disabled{background-image:url("../images/sort_asc_disabled.png")}table.dataTable thead .sorting_desc_disabled{background-image:url("../images/sort_desc_disabled.png")}table.dataTable tbody tr{background-color:#fff}table.dataTable tbody tr.selected{background-color:#B0BED9}table.dataTable tbody th,table.dataTable tbody td{padding:8px 10px}table.dataTable.row-border tbody th,table.dataTable.row-border tbody td,table.dataTable.display tbody th,table.dataTable.display tbody td{border-top:1px solid #ddd}table.dataTable.row-border tbody tr:first-child th,table.dataTable.row-border tbody tr:first-child td,table.dataTable.display tbody tr:first-child th,table.dataTable.display tbody tr:first-child td{border-top:none}table.dataTable.cell-border tbody th,table.dataTable.cell-border tbody td{border-top:1px solid #ddd;border-right:1px solid #ddd}table.dataTable.cell-border tbody tr th:first-child,table.dataTable.cell-border tbody tr td:first-child{border-left:1px solid #ddd}table.dataTable.cell-border tbody tr:first-child th,table.dataTable.cell-border tbody tr:first-child td{border-top:none}table.dataTable.stripe tbody tr.odd,table.dataTable.display tbody tr.odd{background-color:#f9f9f9}table.dataTable.stripe tbody tr.odd.selected,table.dataTable.display tbody tr.odd.selected{background-color:#abb9d3}table.dataTable.hover tbody tr:hover,table.dataTable.display tbody tr:hover{background-color:#f5f5f5}table.dataTable.hover tbody tr:hover.selected,table.dataTable.display tbody tr:hover.selected{background-color:#a9b7d1}table.dataTable.order-column tbody tr>.sorting_1,table.dataTable.order-column tbody tr>.sorting_2,table.dataTable.order-column tbody tr>.sorting_3,table.dataTable.display tbody tr>.sorting_1,table.dataTable.display tbody tr>.sorting_2,table.dataTable.display tbody tr>.sorting_3{background-color:#f9f9f9}table.dataTable.order-column tbody tr.selected>.sorting_1,table.dataTable.order-column tbody tr.selected>.sorting_2,table.dataTable.order-column tbody tr.selected>.sorting_3,table.dataTable.display tbody tr.selected>.sorting_1,table.dataTable.display tbody tr.selected>.sorting_2,table.dataTable.display tbody tr.selected>.sorting_3{background-color:#acbad4}table.dataTable.display tbody tr.odd>.sorting_1,table.dataTable.order-column.stripe tbody tr.odd>.sorting_1{background-color:#f1f1f1}table.dataTable.display tbody tr.odd>.sorting_2,table.dataTable.order-column.stripe tbody tr.odd>.sorting_2{background-color:#f3f3f3}table.dataTable.display tbody tr.odd>.sorting_3,table.dataTable.order-column.stripe tbody tr.odd>.sorting_3{background-color:#f5f5f5}table.dataTable.display tbody tr.odd.selected>.sorting_1,table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_1{background-color:#a6b3cd}table.dataTable.display tbody tr.odd.selected>.sorting_2,table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_2{background-color:#a7b5ce}table.dataTable.display tbody tr.odd.selected>.sorting_3,table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_3{background-color:#a9b6d0}table.dataTable.display tbody tr.even>.sorting_1,table.dataTable.order-column.stripe tbody tr.even>.sorting_1{background-color:#f9f9f9}table.dataTable.display tbody tr.even>.sorting_2,table.dataTable.order-column.stripe tbody tr.even>.sorting_2{background-color:#fbfbfb}table.dataTable.display tbody tr.even>.sorting_3,table.dataTable.order-column.stripe tbody tr.even>.sorting_3{background-color:#fdfdfd}table.dataTable.display tbody tr.even.selected>.sorting_1,table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_1{background-color:#acbad4}table.dataTable.display tbody tr.even.selected>.sorting_2,table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_2{background-color:#adbbd6}table.dataTable.display tbody tr.even.selected>.sorting_3,table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_3{background-color:#afbdd8}table.dataTable.display tbody tr:hover>.sorting_1,table.dataTable.order-column.hover tbody tr:hover>.sorting_1{background-color:#eaeaea}table.dataTable.display tbody tr:hover>.sorting_2,table.dataTable.order-column.hover tbody tr:hover>.sorting_2{background-color:#ebebeb}table.dataTable.display tbody tr:hover>.sorting_3,table.dataTable.order-column.hover tbody tr:hover>.sorting_3{background-color:#eee}table.dataTable.display tbody tr:hover.selected>.sorting_1,table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_1{background-color:#a1aec7}table.dataTable.display tbody tr:hover.selected>.sorting_2,table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_2{background-color:#a2afc8}table.dataTable.display tbody tr:hover.selected>.sorting_3,table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_3{background-color:#a4b2cb}table.dataTable.no-footer{border-bottom:1px solid #111}table.dataTable.nowrap th,table.dataTable.nowrap td{white-space:nowrap}table.dataTable.compact thead th,table.dataTable.compact thead td{padding:4px 17px 4px 4px}table.dataTable.compact tfoot th,table.dataTable.compact tfoot td{padding:4px}table.dataTable.compact tbody th,table.dataTable.compact tbody td{padding:4px}table.dataTable th.dt-left,table.dataTable td.dt-left{text-align:left}table.dataTable th.dt-center,table.dataTable td.dt-center,table.dataTable td.dataTables_empty{text-align:center}table.dataTable th.dt-right,table.dataTable td.dt-right{text-align:right}table.dataTable th.dt-justify,table.dataTable td.dt-justify{text-align:justify}table.dataTable th.dt-nowrap,table.dataTable td.dt-nowrap{white-space:nowrap}table.dataTable thead th.dt-head-left,table.dataTable thead td.dt-head-left,table.dataTable tfoot th.dt-head-left,table.dataTable tfoot td.dt-head-left{text-align:left}table.dataTable thead th.dt-head-center,table.dataTable thead td.dt-head-center,table.dataTable tfoot th.dt-head-center,table.dataTable tfoot td.dt-head-center{text-align:center}table.dataTable thead th.dt-head-right,table.dataTable thead td.dt-head-right,table.dataTable tfoot th.dt-head-right,table.dataTable tfoot td.dt-head-right{text-align:right}table.dataTable thead th.dt-head-justify,table.dataTable thead td.dt-head-justify,table.dataTable tfoot th.dt-head-justify,table.dataTable tfoot td.dt-head-justify{text-align:justify}table.dataTable thead th.dt-head-nowrap,table.dataTable thead td.dt-head-nowrap,table.dataTable tfoot th.dt-head-nowrap,table.dataTable tfoot td.dt-head-nowrap{white-space:nowrap}table.dataTable tbody th.dt-body-left,table.dataTable tbody td.dt-body-left{text-align:left}table.dataTable tbody th.dt-body-center,table.dataTable tbody td.dt-body-center{text-align:center}table.dataTable tbody th.dt-body-right,table.dataTable tbody td.dt-body-right{text-align:right}table.dataTable tbody th.dt-body-justify,table.dataTable tbody td.dt-body-justify{text-align:justify}table.dataTable tbody th.dt-body-nowrap,table.dataTable tbody td.dt-body-nowrap{white-space:nowrap}table.dataTable,table.dataTable th,table.dataTable td{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}.dataTables_wrapper{position:relative;clear:both;*zoom:1;zoom:1}.dataTables_wrapper .dataTables_length{float:left}.dataTables_wrapper .dataTables_filter{float:right;text-align:right}.dataTables_wrapper .dataTables_filter input{margin-left:0.5em}.dataTables_wrapper .dataTables_info{clear:both;float:left;padding-top:0.755em}.dataTables_wrapper .dataTables_paginate{float:right;text-align:right;padding-top:0.25em}.dataTables_wrapper .dataTables_paginate .paginate_button{box-sizing:border-box;display:inline-block;min-width:1.5em;padding:0.5em 1em;margin-left:2px;text-align:center;text-decoration:none !important;cursor:pointer;*cursor:hand;color:#333 !important;border:1px solid transparent}.dataTables_wrapper .dataTables_paginate .paginate_button.current,.dataTables_wrapper .dataTables_paginate .paginate_button.current:hover{color:#333 !important;border:1px solid #cacaca;background-color:#fff;background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc));background:-webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:-moz-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:-ms-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:-o-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:linear-gradient(to bottom, #fff 0%, #dcdcdc 100%)}.dataTables_wrapper .dataTables_paginate .paginate_button.disabled,.dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover,.dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active{cursor:default;color:#666 !important;border:1px solid transparent;background:transparent;box-shadow:none}.dataTables_wrapper .dataTables_paginate .paginate_button:hover{color:white !important;border:1px solid #111;background-color:#585858;background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #585858), color-stop(100%, #111));background:-webkit-linear-gradient(top, #585858 0%, #111 100%);background:-moz-linear-gradient(top, #585858 0%, #111 100%);background:-ms-linear-gradient(top, #585858 0%, #111 100%);background:-o-linear-gradient(top, #585858 0%, #111 100%);background:linear-gradient(to bottom, #585858 0%, #111 100%)}.dataTables_wrapper .dataTables_paginate .paginate_button:active{outline:none;background-color:#2b2b2b;background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #2b2b2b), color-stop(100%, #0c0c0c));background:-webkit-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:-moz-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:-ms-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:-o-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:linear-gradient(to bottom, #2b2b2b 0%, #0c0c0c 100%);box-shadow:inset 0 0 3px #111}.dataTables_wrapper .dataTables_paginate .ellipsis{padding:0 1em}.dataTables_wrapper .dataTables_processing{position:absolute;top:50%;left:50%;width:100%;height:40px;margin-left:-50%;margin-top:-25px;padding-top:20px;text-align:center;font-size:1.2em;background-color:white;background:-webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255,255,255,0)), color-stop(25%, rgba(255,255,255,0.9)), color-stop(75%, rgba(255,255,255,0.9)), color-stop(100%, rgba(255,255,255,0)));background:-webkit-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:-moz-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:-ms-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:-o-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:linear-gradient(to right, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%)}.dataTables_wrapper .dataTables_length,.dataTables_wrapper .dataTables_filter,.dataTables_wrapper .dataTables_info,.dataTables_wrapper .dataTables_processing,.dataTables_wrapper .dataTables_paginate{color:#333}.dataTables_wrapper .dataTables_scroll{clear:both}.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody{*margin-top:-1px;-webkit-overflow-scrolling:touch}.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody th>div.dataTables_sizing,.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody td>div.dataTables_sizing{height:0;overflow:hidden;margin:0 !important;padding:0 !important}.dataTables_wrapper.no-footer .dataTables_scrollBody{border-bottom:1px solid #111}.dataTables_wrapper.no-footer div.dataTables_scrollHead table,.dataTables_wrapper.no-footer div.dataTables_scrollBody table{border-bottom:none}.dataTables_wrapper:after{visibility:hidden;display:block;content:"";clear:both;height:0}@media screen and (max-width: 767px){.dataTables_wrapper .dataTables_info,.dataTables_wrapper .dataTables_paginate{float:none;text-align:center}.dataTables_wrapper .dataTables_paginate{margin-top:0.5em}}@media screen and (max-width: 640px){.dataTables_wrapper .dataTables_length,.dataTables_wrapper .dataTables_filter{float:none;text-align:center}.dataTables_wrapper .dataTables_filter{margin-top:0.5em}}
diff --git a/wqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables_themeroller.css b/wqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables_themeroller.css
index cf1d4ed7..1426a44a 100755
--- a/wqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables_themeroller.css
+++ b/wqflask/wqflask/static/new/packages/DataTables/css/jquery.dataTables_themeroller.css
@@ -1,244 +1,416 @@
-
-
/*
- * Table
+ * Table styles
*/
table.dataTable {
- margin: 0 auto;
- clear: both;
- width: 100%;
- border-collapse: collapse;
-}
-
-table.dataTable thead th {
- padding: 3px 0px 3px 10px;
- cursor: pointer;
- *cursor: hand;
-}
-
+ width: 100%;
+ margin: 0 auto;
+ clear: both;
+ border-collapse: separate;
+ border-spacing: 0;
+ /*
+ * Header and footer styles
+ */
+ /*
+ * Body styles
+ */
+}
+table.dataTable thead th,
+table.dataTable thead td,
+table.dataTable tfoot th,
+table.dataTable tfoot td {
+ padding: 4px 10px;
+}
+table.dataTable thead th,
table.dataTable tfoot th {
- padding: 3px 10px;
-}
-
-table.dataTable td {
- padding: 3px 10px;
-}
-
-table.dataTable td.center,
-table.dataTable td.dataTables_empty {
- text-align: center;
+ font-weight: bold;
}
-
-table.dataTable tr.odd { background-color: #E2E4FF; }
-table.dataTable tr.even { background-color: white; }
-
-table.dataTable tr.odd td.sorting_1 { background-color: #D3D6FF; }
-table.dataTable tr.odd td.sorting_2 { background-color: #DADCFF; }
-table.dataTable tr.odd td.sorting_3 { background-color: #E0E2FF; }
-table.dataTable tr.even td.sorting_1 { background-color: #EAEBFF; }
-table.dataTable tr.even td.sorting_2 { background-color: #F2F3FF; }
-table.dataTable tr.even td.sorting_3 { background-color: #F9F9FF; }
-
-
-/*
- * Table wrapper
- */
-.dataTables_wrapper {
- position: relative;
- clear: both;
- *zoom: 1;
-}
-.dataTables_wrapper .ui-widget-header {
- font-weight: normal;
+table.dataTable thead th:active,
+table.dataTable thead td:active {
+ outline: none;
}
-.dataTables_wrapper .ui-toolbar {
- padding: 5px;
-}
-
-
-/*
- * Page length menu
- */
-.dataTables_length {
- float: left;
-}
-
-
-/*
- * Filter
- */
-.dataTables_filter {
- float: right;
- text-align: right;
-}
-
-
-/*
- * Table information
- */
-.dataTables_info {
- padding-top: 3px;
- clear: both;
- float: left;
-}
-
-
-/*
- * Pagination
- */
-.dataTables_paginate {
- float: right;
- text-align: right;
+table.dataTable thead .sorting_asc,
+table.dataTable thead .sorting_desc,
+table.dataTable thead .sorting {
+ cursor: pointer;
+ *cursor: hand;
}
-
-.dataTables_paginate .ui-button {
- margin-right: -0.1em !important;
+table.dataTable thead th div.DataTables_sort_wrapper {
+ position: relative;
+ padding-right: 10px;
}
-
-.paging_two_button .ui-button {
- float: left;
- cursor: pointer;
- * cursor: hand;
+table.dataTable thead th div.DataTables_sort_wrapper span {
+ position: absolute;
+ top: 50%;
+ margin-top: -8px;
+ right: -5px;
}
-
-.paging_full_numbers .ui-button {
- padding: 2px 6px;
- margin: 0;
- cursor: pointer;
- * cursor: hand;
- color: #333 !important;
+table.dataTable thead th.ui-state-default {
+ border-right-width: 0;
}
-
-/* Two button pagination - previous / next */
-.paginate_disabled_previous,
-.paginate_enabled_previous,
-.paginate_disabled_next,
-.paginate_enabled_next {
- height: 19px;
- float: left;
- cursor: pointer;
- *cursor: hand;
- color: #111 !important;
-}
-.paginate_disabled_previous:hover,
-.paginate_enabled_previous:hover,
-.paginate_disabled_next:hover,
-.paginate_enabled_next:hover {
- text-decoration: none !important;
-}
-.paginate_disabled_previous:active,
-.paginate_enabled_previous:active,
-.paginate_disabled_next:active,
-.paginate_enabled_next:active {
- outline: none;
+table.dataTable thead th.ui-state-default:last-child {
+ border-right-width: 1px;
}
-
-.paginate_disabled_previous,
-.paginate_disabled_next {
- color: #666 !important;
-}
-.paginate_disabled_previous,
-.paginate_enabled_previous {
- padding-left: 23px;
+table.dataTable tbody tr {
+ background-color: #ffffff;
}
-.paginate_disabled_next,
-.paginate_enabled_next {
- padding-right: 23px;
- margin-left: 10px;
+table.dataTable tbody tr.selected {
+ background-color: #B0BED9;
}
-
-.paginate_enabled_previous { background: url('../images/back_enabled.png') no-repeat top left; }
-.paginate_enabled_previous:hover { background: url('../images/back_enabled_hover.png') no-repeat top left; }
-.paginate_disabled_previous { background: url('../images/back_disabled.png') no-repeat top left; }
-
-.paginate_enabled_next { background: url('../images/forward_enabled.png') no-repeat top right; }
-.paginate_enabled_next:hover { background: url('../images/forward_enabled_hover.png') no-repeat top right; }
-.paginate_disabled_next { background: url('../images/forward_disabled.png') no-repeat top right; }
-
-/* Full number pagination */
-.paging_full_numbers a:active {
- outline: none
+table.dataTable tbody th,
+table.dataTable tbody td {
+ padding: 8px 10px;
}
-.paging_full_numbers a:hover {
- text-decoration: none;
-}
-
-.paging_full_numbers a.paginate_button,
-.paging_full_numbers a.paginate_active {
- border: 1px solid #aaa;
- -webkit-border-radius: 5px;
- -moz-border-radius: 5px;
- border-radius: 5px;
- padding: 2px 5px;
- margin: 0 3px;
- cursor: pointer;
- *cursor: hand;
- color: #333 !important;
-}
-
-.paging_full_numbers a.paginate_button {
- background-color: #ddd;
-}
-
-.paging_full_numbers a.paginate_button:hover {
- background-color: #ccc;
- text-decoration: none !important;
+table.dataTable th.center,
+table.dataTable td.center,
+table.dataTable td.dataTables_empty {
+ text-align: center;
}
-
-.paging_full_numbers a.paginate_active {
- background-color: #99B3FF;
+table.dataTable th.right,
+table.dataTable td.right {
+ text-align: right;
}
-
-
-/*
- * Processing indicator
- */
-.dataTables_processing {
- position: absolute;
- top: 50%;
- left: 50%;
- width: 250px;
- height: 30px;
- margin-left: -125px;
- margin-top: -15px;
- padding: 14px 0 2px 0;
- border: 1px solid #ddd;
- text-align: center;
- color: #999;
- font-size: 14px;
- background-color: white;
+table.dataTable.row-border tbody th, table.dataTable.row-border tbody td, table.dataTable.display tbody th, table.dataTable.display tbody td {
+ border-top: 1px solid #ddd;
+}
+table.dataTable.row-border tbody tr:first-child th,
+table.dataTable.row-border tbody tr:first-child td, table.dataTable.display tbody tr:first-child th,
+table.dataTable.display tbody tr:first-child td {
+ border-top: none;
+}
+table.dataTable.cell-border tbody th, table.dataTable.cell-border tbody td {
+ border-top: 1px solid #ddd;
+ border-right: 1px solid #ddd;
+}
+table.dataTable.cell-border tbody tr th:first-child,
+table.dataTable.cell-border tbody tr td:first-child {
+ border-left: 1px solid #ddd;
+}
+table.dataTable.cell-border tbody tr:first-child th,
+table.dataTable.cell-border tbody tr:first-child td {
+ border-top: none;
+}
+table.dataTable.stripe tbody tr.odd, table.dataTable.display tbody tr.odd {
+ background-color: #f9f9f9;
+}
+table.dataTable.stripe tbody tr.odd.selected, table.dataTable.display tbody tr.odd.selected {
+ background-color: #abb9d3;
+}
+table.dataTable.hover tbody tr:hover,
+table.dataTable.hover tbody tr.odd:hover,
+table.dataTable.hover tbody tr.even:hover, table.dataTable.display tbody tr:hover,
+table.dataTable.display tbody tr.odd:hover,
+table.dataTable.display tbody tr.even:hover {
+ background-color: whitesmoke;
+}
+table.dataTable.hover tbody tr:hover.selected,
+table.dataTable.hover tbody tr.odd:hover.selected,
+table.dataTable.hover tbody tr.even:hover.selected, table.dataTable.display tbody tr:hover.selected,
+table.dataTable.display tbody tr.odd:hover.selected,
+table.dataTable.display tbody tr.even:hover.selected {
+ background-color: #a9b7d1;
+}
+table.dataTable.order-column tbody tr > .sorting_1,
+table.dataTable.order-column tbody tr > .sorting_2,
+table.dataTable.order-column tbody tr > .sorting_3, table.dataTable.display tbody tr > .sorting_1,
+table.dataTable.display tbody tr > .sorting_2,
+table.dataTable.display tbody tr > .sorting_3 {
+ background-color: #f9f9f9;
+}
+table.dataTable.order-column tbody tr.selected > .sorting_1,
+table.dataTable.order-column tbody tr.selected > .sorting_2,
+table.dataTable.order-column tbody tr.selected > .sorting_3, table.dataTable.display tbody tr.selected > .sorting_1,
+table.dataTable.display tbody tr.selected > .sorting_2,
+table.dataTable.display tbody tr.selected > .sorting_3 {
+ background-color: #acbad4;
+}
+table.dataTable.display tbody tr.odd > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd > .sorting_1 {
+ background-color: #f1f1f1;
+}
+table.dataTable.display tbody tr.odd > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd > .sorting_2 {
+ background-color: #f3f3f3;
+}
+table.dataTable.display tbody tr.odd > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd > .sorting_3 {
+ background-color: whitesmoke;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_1 {
+ background-color: #a6b3cd;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_2 {
+ background-color: #a7b5ce;
+}
+table.dataTable.display tbody tr.odd.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_3 {
+ background-color: #a9b6d0;
+}
+table.dataTable.display tbody tr.even > .sorting_1, table.dataTable.order-column.stripe tbody tr.even > .sorting_1 {
+ background-color: #f9f9f9;
+}
+table.dataTable.display tbody tr.even > .sorting_2, table.dataTable.order-column.stripe tbody tr.even > .sorting_2 {
+ background-color: #fbfbfb;
+}
+table.dataTable.display tbody tr.even > .sorting_3, table.dataTable.order-column.stripe tbody tr.even > .sorting_3 {
+ background-color: #fdfdfd;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_1 {
+ background-color: #acbad4;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_2 {
+ background-color: #adbbd6;
+}
+table.dataTable.display tbody tr.even.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_3 {
+ background-color: #afbdd8;
+}
+table.dataTable.display tbody tr:hover > .sorting_1,
+table.dataTable.display tbody tr.odd:hover > .sorting_1,
+table.dataTable.display tbody tr.even:hover > .sorting_1, table.dataTable.order-column.hover tbody tr:hover > .sorting_1,
+table.dataTable.order-column.hover tbody tr.odd:hover > .sorting_1,
+table.dataTable.order-column.hover tbody tr.even:hover > .sorting_1 {
+ background-color: #eaeaea;
+}
+table.dataTable.display tbody tr:hover > .sorting_2,
+table.dataTable.display tbody tr.odd:hover > .sorting_2,
+table.dataTable.display tbody tr.even:hover > .sorting_2, table.dataTable.order-column.hover tbody tr:hover > .sorting_2,
+table.dataTable.order-column.hover tbody tr.odd:hover > .sorting_2,
+table.dataTable.order-column.hover tbody tr.even:hover > .sorting_2 {
+ background-color: #ebebeb;
+}
+table.dataTable.display tbody tr:hover > .sorting_3,
+table.dataTable.display tbody tr.odd:hover > .sorting_3,
+table.dataTable.display tbody tr.even:hover > .sorting_3, table.dataTable.order-column.hover tbody tr:hover > .sorting_3,
+table.dataTable.order-column.hover tbody tr.odd:hover > .sorting_3,
+table.dataTable.order-column.hover tbody tr.even:hover > .sorting_3 {
+ background-color: #eeeeee;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_1,
+table.dataTable.display tbody tr.odd:hover.selected > .sorting_1,
+table.dataTable.display tbody tr.even:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_1,
+table.dataTable.order-column.hover tbody tr.odd:hover.selected > .sorting_1,
+table.dataTable.order-column.hover tbody tr.even:hover.selected > .sorting_1 {
+ background-color: #a1aec7;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_2,
+table.dataTable.display tbody tr.odd:hover.selected > .sorting_2,
+table.dataTable.display tbody tr.even:hover.selected > .sorting_2, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_2,
+table.dataTable.order-column.hover tbody tr.odd:hover.selected > .sorting_2,
+table.dataTable.order-column.hover tbody tr.even:hover.selected > .sorting_2 {
+ background-color: #a2afc8;
+}
+table.dataTable.display tbody tr:hover.selected > .sorting_3,
+table.dataTable.display tbody tr.odd:hover.selected > .sorting_3,
+table.dataTable.display tbody tr.even:hover.selected > .sorting_3, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_3,
+table.dataTable.order-column.hover tbody tr.odd:hover.selected > .sorting_3,
+table.dataTable.order-column.hover tbody tr.even:hover.selected > .sorting_3 {
+ background-color: #a4b2cb;
+}
+table.dataTable.nowrap th, table.dataTable.nowrap td {
+ white-space: nowrap;
+}
+table.dataTable.compact thead th,
+table.dataTable.compact thead td {
+ padding: 5px 9px;
+}
+table.dataTable.compact tfoot th,
+table.dataTable.compact tfoot td {
+ padding: 5px 9px 3px 9px;
+}
+table.dataTable.compact tbody th,
+table.dataTable.compact tbody td {
+ padding: 4px 5px;
+}
+table.dataTable th.dt-left,
+table.dataTable td.dt-left {
+ text-align: left;
+}
+table.dataTable th.dt-center,
+table.dataTable td.dt-center,
+table.dataTable td.dataTables_empty {
+ text-align: center;
+}
+table.dataTable th.dt-right,
+table.dataTable td.dt-right {
+ text-align: right;
+}
+table.dataTable th.dt-justify,
+table.dataTable td.dt-justify {
+ text-align: justify;
+}
+table.dataTable th.dt-nowrap,
+table.dataTable td.dt-nowrap {
+ white-space: nowrap;
+}
+table.dataTable thead th.dt-head-left,
+table.dataTable thead td.dt-head-left,
+table.dataTable tfoot th.dt-head-left,
+table.dataTable tfoot td.dt-head-left {
+ text-align: left;
+}
+table.dataTable thead th.dt-head-center,
+table.dataTable thead td.dt-head-center,
+table.dataTable tfoot th.dt-head-center,
+table.dataTable tfoot td.dt-head-center {
+ text-align: center;
+}
+table.dataTable thead th.dt-head-right,
+table.dataTable thead td.dt-head-right,
+table.dataTable tfoot th.dt-head-right,
+table.dataTable tfoot td.dt-head-right {
+ text-align: right;
+}
+table.dataTable thead th.dt-head-justify,
+table.dataTable thead td.dt-head-justify,
+table.dataTable tfoot th.dt-head-justify,
+table.dataTable tfoot td.dt-head-justify {
+ text-align: justify;
+}
+table.dataTable thead th.dt-head-nowrap,
+table.dataTable thead td.dt-head-nowrap,
+table.dataTable tfoot th.dt-head-nowrap,
+table.dataTable tfoot td.dt-head-nowrap {
+ white-space: nowrap;
+}
+table.dataTable tbody th.dt-body-left,
+table.dataTable tbody td.dt-body-left {
+ text-align: left;
+}
+table.dataTable tbody th.dt-body-center,
+table.dataTable tbody td.dt-body-center {
+ text-align: center;
+}
+table.dataTable tbody th.dt-body-right,
+table.dataTable tbody td.dt-body-right {
+ text-align: right;
+}
+table.dataTable tbody th.dt-body-justify,
+table.dataTable tbody td.dt-body-justify {
+ text-align: justify;
+}
+table.dataTable tbody th.dt-body-nowrap,
+table.dataTable tbody td.dt-body-nowrap {
+ white-space: nowrap;
+}
+
+table.dataTable,
+table.dataTable th,
+table.dataTable td {
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
}
-
/*
- * Sorting
+ * Control feature layout
*/
-table.dataTable thead th div.DataTables_sort_wrapper {
- position: relative;
- padding-right: 20px;
-}
-
-table.dataTable thead th div.DataTables_sort_wrapper span {
- position: absolute;
- top: 50%;
- margin-top: -8px;
- right: 0;
-}
-
-table.dataTable th:active {
- outline: none;
+.dataTables_wrapper {
+ position: relative;
+ clear: both;
+ *zoom: 1;
+ zoom: 1;
+}
+.dataTables_wrapper .dataTables_length {
+ float: left;
+}
+.dataTables_wrapper .dataTables_filter {
+ float: right;
+ text-align: right;
+}
+.dataTables_wrapper .dataTables_filter input {
+ margin-left: 0.5em;
+}
+.dataTables_wrapper .dataTables_info {
+ clear: both;
+ float: left;
+ padding-top: 0.55em;
+}
+.dataTables_wrapper .dataTables_paginate {
+ float: right;
+ text-align: right;
+}
+.dataTables_wrapper .dataTables_paginate .fg-button {
+ box-sizing: border-box;
+ display: inline-block;
+ min-width: 1.5em;
+ padding: 0.5em;
+ margin-left: 2px;
+ text-align: center;
+ text-decoration: none !important;
+ cursor: pointer;
+ *cursor: hand;
+ color: #333 !important;
+ border: 1px solid transparent;
+}
+.dataTables_wrapper .dataTables_paginate .fg-button:active {
+ outline: none;
+}
+.dataTables_wrapper .dataTables_paginate .fg-button:first-child {
+ border-top-left-radius: 3px;
+ border-bottom-left-radius: 3px;
+}
+.dataTables_wrapper .dataTables_paginate .fg-button:last-child {
+ border-top-right-radius: 3px;
+ border-bottom-right-radius: 3px;
+}
+.dataTables_wrapper .dataTables_processing {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: 100%;
+ height: 40px;
+ margin-left: -50%;
+ margin-top: -25px;
+ padding-top: 20px;
+ text-align: center;
+ font-size: 1.2em;
+ background-color: white;
+ background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255, 255, 255, 0)), color-stop(25%, rgba(255, 255, 255, 0.9)), color-stop(75%, rgba(255, 255, 255, 0.9)), color-stop(100%, rgba(255, 255, 255, 0)));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ /* Chrome10+,Safari5.1+ */
+ background: -moz-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ /* FF3.6+ */
+ background: -ms-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ /* IE10+ */
+ background: -o-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ /* Opera 11.10+ */
+ background: linear-gradient(to right, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
+ /* W3C */
+}
+.dataTables_wrapper .dataTables_length,
+.dataTables_wrapper .dataTables_filter,
+.dataTables_wrapper .dataTables_info,
+.dataTables_wrapper .dataTables_processing,
+.dataTables_wrapper .dataTables_paginate {
+ color: #333;
+}
+.dataTables_wrapper .dataTables_scroll {
+ clear: both;
+}
+.dataTables_wrapper .dataTables_scrollBody {
+ *margin-top: -1px;
+ -webkit-overflow-scrolling: touch;
}
-
-
-/*
- * Scrolling
- */
-.dataTables_scroll {
- clear: both;
+.dataTables_wrapper .ui-widget-header {
+ font-weight: normal;
}
-
-.dataTables_scrollBody {
- *margin-top: -1px;
- -webkit-overflow-scrolling: touch;
+.dataTables_wrapper .ui-toolbar {
+ padding: 8px;
+}
+.dataTables_wrapper:after {
+ visibility: hidden;
+ display: block;
+ content: "";
+ clear: both;
+ height: 0;
+}
+
+@media screen and (max-width: 767px) {
+ .dataTables_wrapper .dataTables_length,
+ .dataTables_wrapper .dataTables_filter,
+ .dataTables_wrapper .dataTables_info,
+ .dataTables_wrapper .dataTables_paginate {
+ float: none;
+ text-align: center;
+ }
+ .dataTables_wrapper .dataTables_filter,
+ .dataTables_wrapper .dataTables_paginate {
+ margin-top: 0.5em;
+ }
}
-
diff --git a/wqflask/wqflask/static/new/packages/DataTables/extensions/buttons.bootstrap.css b/wqflask/wqflask/static/new/packages/DataTables/extensions/buttons.bootstrap.css
new file mode 100644
index 00000000..461dd2b0
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/DataTables/extensions/buttons.bootstrap.css
@@ -0,0 +1,89 @@
+div.dt-button-info {
+ position: fixed;
+ top: 50%;
+ left: 50%;
+ width: 400px;
+ margin-top: -100px;
+ margin-left: -200px;
+ background-color: white;
+ border: 2px solid #111;
+ box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.3);
+ border-radius: 3px;
+ text-align: center;
+ z-index: 21;
+}
+div.dt-button-info h2 {
+ padding: 0.5em;
+ margin: 0;
+ font-weight: normal;
+ border-bottom: 1px solid #ddd;
+ background-color: #f3f3f3;
+}
+div.dt-button-info > div {
+ padding: 1em;
+}
+
+ul.dt-button-collection.dropdown-menu {
+ display: block;
+ z-index: 2002;
+ -webkit-column-gap: 8px;
+ -moz-column-gap: 8px;
+ -ms-column-gap: 8px;
+ -o-column-gap: 8px;
+ column-gap: 8px;
+}
+ul.dt-button-collection.dropdown-menu.fixed {
+ position: fixed;
+ top: 50%;
+ left: 50%;
+ margin-left: -75px;
+}
+ul.dt-button-collection.dropdown-menu.fixed.two-column {
+ margin-left: -150px;
+}
+ul.dt-button-collection.dropdown-menu.fixed.three-column {
+ margin-left: -225px;
+}
+ul.dt-button-collection.dropdown-menu.fixed.four-column {
+ margin-left: -300px;
+}
+ul.dt-button-collection.dropdown-menu > * {
+ -webkit-column-break-inside: avoid;
+ break-inside: avoid;
+}
+ul.dt-button-collection.dropdown-menu.two-column {
+ width: 300px;
+ padding-bottom: 1px;
+ -webkit-column-count: 2;
+ -moz-column-count: 2;
+ -ms-column-count: 2;
+ -o-column-count: 2;
+ column-count: 2;
+}
+ul.dt-button-collection.dropdown-menu.three-column {
+ width: 450px;
+ padding-bottom: 1px;
+ -webkit-column-count: 3;
+ -moz-column-count: 3;
+ -ms-column-count: 3;
+ -o-column-count: 3;
+ column-count: 3;
+}
+ul.dt-button-collection.dropdown-menu.four-column {
+ width: 600px;
+ padding-bottom: 1px;
+ -webkit-column-count: 4;
+ -moz-column-count: 4;
+ -ms-column-count: 4;
+ -o-column-count: 4;
+ column-count: 4;
+}
+
+div.dt-button-background {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 2001;
+}
diff --git a/wqflask/wqflask/static/new/packages/DataTables/extensions/buttons.dataTables.css b/wqflask/wqflask/static/new/packages/DataTables/extensions/buttons.dataTables.css
new file mode 100644
index 00000000..15b6c263
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/DataTables/extensions/buttons.dataTables.css
@@ -0,0 +1,297 @@
+div.dt-button-info {
+ position: fixed;
+ top: 50%;
+ left: 50%;
+ width: 400px;
+ margin-top: -100px;
+ margin-left: -200px;
+ background-color: white;
+ border: 2px solid #111;
+ box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.3);
+ border-radius: 3px;
+ text-align: center;
+ z-index: 21;
+}
+div.dt-button-info h2 {
+ padding: 0.5em;
+ margin: 0;
+ font-weight: normal;
+ border-bottom: 1px solid #ddd;
+ background-color: #f3f3f3;
+}
+div.dt-button-info > div {
+ padding: 1em;
+}
+
+button.dt-button,
+div.dt-button,
+a.dt-button {
+ position: relative;
+ display: inline-block;
+ box-sizing: border-box;
+ margin-right: 0.333em;
+ padding: 0.5em 1em;
+ border: 1px solid #999;
+ border-radius: 2px;
+ cursor: pointer;
+ font-size: 0.88em;
+ color: black;
+ white-space: nowrap;
+ overflow: hidden;
+ background-color: #e9e9e9;
+ /* Fallback */
+ background-image: -webkit-linear-gradient(top, white 0%, #e9e9e9 100%);
+ /* Chrome 10+, Saf5.1+, iOS 5+ */
+ background-image: -moz-linear-gradient(top, white 0%, #e9e9e9 100%);
+ /* FF3.6 */
+ background-image: -ms-linear-gradient(top, white 0%, #e9e9e9 100%);
+ /* IE10 */
+ background-image: -o-linear-gradient(top, white 0%, #e9e9e9 100%);
+ /* Opera 11.10+ */
+ background-image: linear-gradient(top, white 0%, #e9e9e9 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='white', EndColorStr='#e9e9e9');
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+ user-select: none;
+ text-decoration: none;
+ outline: none;
+}
+button.dt-button.disabled,
+div.dt-button.disabled,
+a.dt-button.disabled {
+ color: #999;
+ border: 1px solid #d0d0d0;
+ cursor: default;
+ background-color: #f9f9f9;
+ /* Fallback */
+ background-image: -webkit-linear-gradient(top, #ffffff 0%, #f9f9f9 100%);
+ /* Chrome 10+, Saf5.1+, iOS 5+ */
+ background-image: -moz-linear-gradient(top, #ffffff 0%, #f9f9f9 100%);
+ /* FF3.6 */
+ background-image: -ms-linear-gradient(top, #ffffff 0%, #f9f9f9 100%);
+ /* IE10 */
+ background-image: -o-linear-gradient(top, #ffffff 0%, #f9f9f9 100%);
+ /* Opera 11.10+ */
+ background-image: linear-gradient(top, #ffffff 0%, #f9f9f9 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#ffffff', EndColorStr='#f9f9f9');
+}
+button.dt-button:active:not(.disabled), button.dt-button.active:not(.disabled),
+div.dt-button:active:not(.disabled),
+div.dt-button.active:not(.disabled),
+a.dt-button:active:not(.disabled),
+a.dt-button.active:not(.disabled) {
+ background-color: #e2e2e2;
+ /* Fallback */
+ background-image: -webkit-linear-gradient(top, #f3f3f3 0%, #e2e2e2 100%);
+ /* Chrome 10+, Saf5.1+, iOS 5+ */
+ background-image: -moz-linear-gradient(top, #f3f3f3 0%, #e2e2e2 100%);
+ /* FF3.6 */
+ background-image: -ms-linear-gradient(top, #f3f3f3 0%, #e2e2e2 100%);
+ /* IE10 */
+ background-image: -o-linear-gradient(top, #f3f3f3 0%, #e2e2e2 100%);
+ /* Opera 11.10+ */
+ background-image: linear-gradient(top, #f3f3f3 0%, #e2e2e2 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#f3f3f3', EndColorStr='#e2e2e2');
+ box-shadow: inset 1px 1px 3px #999999;
+}
+button.dt-button:active:not(.disabled):hover:not(.disabled), button.dt-button.active:not(.disabled):hover:not(.disabled),
+div.dt-button:active:not(.disabled):hover:not(.disabled),
+div.dt-button.active:not(.disabled):hover:not(.disabled),
+a.dt-button:active:not(.disabled):hover:not(.disabled),
+a.dt-button.active:not(.disabled):hover:not(.disabled) {
+ box-shadow: inset 1px 1px 3px #999999;
+ background-color: #cccccc;
+ /* Fallback */
+ background-image: -webkit-linear-gradient(top, #eaeaea 0%, #cccccc 100%);
+ /* Chrome 10+, Saf5.1+, iOS 5+ */
+ background-image: -moz-linear-gradient(top, #eaeaea 0%, #cccccc 100%);
+ /* FF3.6 */
+ background-image: -ms-linear-gradient(top, #eaeaea 0%, #cccccc 100%);
+ /* IE10 */
+ background-image: -o-linear-gradient(top, #eaeaea 0%, #cccccc 100%);
+ /* Opera 11.10+ */
+ background-image: linear-gradient(top, #eaeaea 0%, #cccccc 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#eaeaea', EndColorStr='#cccccc');
+}
+button.dt-button:hover,
+div.dt-button:hover,
+a.dt-button:hover {
+ text-decoration: none;
+}
+button.dt-button:hover:not(.disabled),
+div.dt-button:hover:not(.disabled),
+a.dt-button:hover:not(.disabled) {
+ border: 1px solid #666;
+ background-color: #e0e0e0;
+ /* Fallback */
+ background-image: -webkit-linear-gradient(top, #f9f9f9 0%, #e0e0e0 100%);
+ /* Chrome 10+, Saf5.1+, iOS 5+ */
+ background-image: -moz-linear-gradient(top, #f9f9f9 0%, #e0e0e0 100%);
+ /* FF3.6 */
+ background-image: -ms-linear-gradient(top, #f9f9f9 0%, #e0e0e0 100%);
+ /* IE10 */
+ background-image: -o-linear-gradient(top, #f9f9f9 0%, #e0e0e0 100%);
+ /* Opera 11.10+ */
+ background-image: linear-gradient(top, #f9f9f9 0%, #e0e0e0 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#f9f9f9', EndColorStr='#e0e0e0');
+}
+button.dt-button:focus:not(.disabled),
+div.dt-button:focus:not(.disabled),
+a.dt-button:focus:not(.disabled) {
+ border: 1px solid #426c9e;
+ text-shadow: 0 1px 0 #c4def1;
+ outline: none;
+ background-color: #79ace9;
+ /* Fallback */
+ background-image: -webkit-linear-gradient(top, #bddef4 0%, #79ace9 100%);
+ /* Chrome 10+, Saf5.1+, iOS 5+ */
+ background-image: -moz-linear-gradient(top, #bddef4 0%, #79ace9 100%);
+ /* FF3.6 */
+ background-image: -ms-linear-gradient(top, #bddef4 0%, #79ace9 100%);
+ /* IE10 */
+ background-image: -o-linear-gradient(top, #bddef4 0%, #79ace9 100%);
+ /* Opera 11.10+ */
+ background-image: linear-gradient(top, #bddef4 0%, #79ace9 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#bddef4', EndColorStr='#79ace9');
+}
+
+.dt-button embed {
+ outline: none;
+}
+
+div.dt-buttons {
+ position: relative;
+ float: left;
+}
+div.dt-buttons.buttons-right {
+ float: right;
+}
+
+div.dt-button-collection {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 150px;
+ margin-top: 3px;
+ padding: 8px 8px 4px 8px;
+ border: 1px solid #ccc;
+ border: 1px solid rgba(0, 0, 0, 0.4);
+ background-color: white;
+ overflow: hidden;
+ z-index: 2002;
+ border-radius: 5px;
+ box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.3);
+ z-index: 2002;
+ -webkit-column-gap: 8px;
+ -moz-column-gap: 8px;
+ -ms-column-gap: 8px;
+ -o-column-gap: 8px;
+ column-gap: 8px;
+}
+div.dt-button-collection button.dt-button,
+div.dt-button-collection div.dt-button,
+div.dt-button-collection a.dt-button {
+ position: relative;
+ left: 0;
+ right: 0;
+ display: block;
+ float: none;
+ margin-bottom: 4px;
+ margin-right: 0;
+}
+div.dt-button-collection button.dt-button:active:not(.disabled), div.dt-button-collection button.dt-button.active:not(.disabled),
+div.dt-button-collection div.dt-button:active:not(.disabled),
+div.dt-button-collection div.dt-button.active:not(.disabled),
+div.dt-button-collection a.dt-button:active:not(.disabled),
+div.dt-button-collection a.dt-button.active:not(.disabled) {
+ background-color: #dadada;
+ /* Fallback */
+ background-image: -webkit-linear-gradient(top, #f0f0f0 0%, #dadada 100%);
+ /* Chrome 10+, Saf5.1+, iOS 5+ */
+ background-image: -moz-linear-gradient(top, #f0f0f0 0%, #dadada 100%);
+ /* FF3.6 */
+ background-image: -ms-linear-gradient(top, #f0f0f0 0%, #dadada 100%);
+ /* IE10 */
+ background-image: -o-linear-gradient(top, #f0f0f0 0%, #dadada 100%);
+ /* Opera 11.10+ */
+ background-image: linear-gradient(top, #f0f0f0 0%, #dadada 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#f0f0f0', EndColorStr='#dadada');
+ box-shadow: inset 1px 1px 3px #666;
+}
+div.dt-button-collection.fixed {
+ position: fixed;
+ top: 50%;
+ left: 50%;
+ margin-left: -75px;
+}
+div.dt-button-collection.fixed.two-column {
+ margin-left: -150px;
+}
+div.dt-button-collection.fixed.three-column {
+ margin-left: -225px;
+}
+div.dt-button-collection.fixed.four-column {
+ margin-left: -300px;
+}
+div.dt-button-collection > * {
+ -webkit-column-break-inside: avoid;
+ break-inside: avoid;
+}
+div.dt-button-collection.two-column {
+ width: 300px;
+ padding-bottom: 1px;
+ -webkit-column-count: 2;
+ -moz-column-count: 2;
+ -ms-column-count: 2;
+ -o-column-count: 2;
+ column-count: 2;
+}
+div.dt-button-collection.three-column {
+ width: 450px;
+ padding-bottom: 1px;
+ -webkit-column-count: 3;
+ -moz-column-count: 3;
+ -ms-column-count: 3;
+ -o-column-count: 3;
+ column-count: 3;
+}
+div.dt-button-collection.four-column {
+ width: 600px;
+ padding-bottom: 1px;
+ -webkit-column-count: 4;
+ -moz-column-count: 4;
+ -ms-column-count: 4;
+ -o-column-count: 4;
+ column-count: 4;
+}
+
+div.dt-button-background {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: rgba(0, 0, 0, 0.7);
+ /* Fallback */
+ background: -ms-radial-gradient(center, ellipse farthest-corner, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.7) 100%);
+ /* IE10 Consumer Preview */
+ background: -moz-radial-gradient(center, ellipse farthest-corner, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.7) 100%);
+ /* Firefox */
+ background: -o-radial-gradient(center, ellipse farthest-corner, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.7) 100%);
+ /* Opera */
+ background: -webkit-gradient(radial, center center, 0, center center, 497, color-stop(0, rgba(0, 0, 0, 0.3)), color-stop(1, rgba(0, 0, 0, 0.7)));
+ /* Webkit (Safari/Chrome 10) */
+ background: -webkit-radial-gradient(center, ellipse farthest-corner, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.7) 100%);
+ /* Webkit (Chrome 11+) */
+ background: radial-gradient(ellipse farthest-corner at center, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.7) 100%);
+ /* W3C Markup, IE10 Release Preview */
+ z-index: 2001;
+}
+
+@media screen and (max-width: 640px) {
+ div.dt-buttons {
+ float: none !important;
+ text-align: center;
+ }
+}
diff --git a/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.colReorder.js b/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.colReorder.js
new file mode 100644
index 00000000..58e7656e
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.colReorder.js
@@ -0,0 +1,1372 @@
+/*! ColReorder 1.1.3
+ * ©2010-2014 SpryMedia Ltd - datatables.net/license
+ */
+
+/**
+ * @summary ColReorder
+ * @description Provide the ability to reorder columns in a DataTable
+ * @version 1.1.3
+ * @file dataTables.colReorder.js
+ * @author SpryMedia Ltd (www.sprymedia.co.uk)
+ * @contact www.sprymedia.co.uk/contact
+ * @copyright Copyright 2010-2014 SpryMedia Ltd.
+ *
+ * This source file is free software, available under the following license:
+ * MIT license - http://datatables.net/license/mit
+ *
+ * This source file is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
+ *
+ * For details please refer to: http://www.datatables.net
+ */
+
+(function(window, document, undefined) {
+
+
+/**
+ * Switch the key value pairing of an index array to be value key (i.e. the old value is now the
+ * key). For example consider [ 2, 0, 1 ] this would be returned as [ 1, 2, 0 ].
+ * @method fnInvertKeyValues
+ * @param array aIn Array to switch around
+ * @returns array
+ */
+function fnInvertKeyValues( aIn )
+{
+ var aRet=[];
+ for ( var i=0, iLen=aIn.length ; i<iLen ; i++ )
+ {
+ aRet[ aIn[i] ] = i;
+ }
+ return aRet;
+}
+
+
+/**
+ * Modify an array by switching the position of two elements
+ * @method fnArraySwitch
+ * @param array aArray Array to consider, will be modified by reference (i.e. no return)
+ * @param int iFrom From point
+ * @param int iTo Insert point
+ * @returns void
+ */
+function fnArraySwitch( aArray, iFrom, iTo )
+{
+ var mStore = aArray.splice( iFrom, 1 )[0];
+ aArray.splice( iTo, 0, mStore );
+}
+
+
+/**
+ * Switch the positions of nodes in a parent node (note this is specifically designed for
+ * table rows). Note this function considers all element nodes under the parent!
+ * @method fnDomSwitch
+ * @param string sTag Tag to consider
+ * @param int iFrom Element to move
+ * @param int Point to element the element to (before this point), can be null for append
+ * @returns void
+ */
+function fnDomSwitch( nParent, iFrom, iTo )
+{
+ var anTags = [];
+ for ( var i=0, iLen=nParent.childNodes.length ; i<iLen ; i++ )
+ {
+ if ( nParent.childNodes[i].nodeType == 1 )
+ {
+ anTags.push( nParent.childNodes[i] );
+ }
+ }
+ var nStore = anTags[ iFrom ];
+
+ if ( iTo !== null )
+ {
+ nParent.insertBefore( nStore, anTags[iTo] );
+ }
+ else
+ {
+ nParent.appendChild( nStore );
+ }
+}
+
+
+
+var factory = function( $, DataTable ) {
+"use strict";
+
+/**
+ * Plug-in for DataTables which will reorder the internal column structure by taking the column
+ * from one position (iFrom) and insert it into a given point (iTo).
+ * @method $.fn.dataTableExt.oApi.fnColReorder
+ * @param object oSettings DataTables settings object - automatically added by DataTables!
+ * @param int iFrom Take the column to be repositioned from this point
+ * @param int iTo and insert it into this point
+ * @returns void
+ */
+$.fn.dataTableExt.oApi.fnColReorder = function ( oSettings, iFrom, iTo )
+{
+ var v110 = $.fn.dataTable.Api ? true : false;
+ var i, iLen, j, jLen, iCols=oSettings.aoColumns.length, nTrs, oCol;
+ var attrMap = function ( obj, prop, mapping ) {
+ if ( ! obj[ prop ] ) {
+ return;
+ }
+
+ var a = obj[ prop ].split('.');
+ var num = a.shift();
+
+ if ( isNaN( num*1 ) ) {
+ return;
+ }
+
+ obj[ prop ] = mapping[ num*1 ]+'.'+a.join('.');
+ };
+
+ /* Sanity check in the input */
+ if ( iFrom == iTo )
+ {
+ /* Pointless reorder */
+ return;
+ }
+
+ if ( iFrom < 0 || iFrom >= iCols )
+ {
+ this.oApi._fnLog( oSettings, 1, "ColReorder 'from' index is out of bounds: "+iFrom );
+ return;
+ }
+
+ if ( iTo < 0 || iTo >= iCols )
+ {
+ this.oApi._fnLog( oSettings, 1, "ColReorder 'to' index is out of bounds: "+iTo );
+ return;
+ }
+
+ /*
+ * Calculate the new column array index, so we have a mapping between the old and new
+ */
+ var aiMapping = [];
+ for ( i=0, iLen=iCols ; i<iLen ; i++ )
+ {
+ aiMapping[i] = i;
+ }
+ fnArraySwitch( aiMapping, iFrom, iTo );
+ var aiInvertMapping = fnInvertKeyValues( aiMapping );
+
+
+ /*
+ * Convert all internal indexing to the new column order indexes
+ */
+ /* Sorting */
+ for ( i=0, iLen=oSettings.aaSorting.length ; i<iLen ; i++ )
+ {
+ oSettings.aaSorting[i][0] = aiInvertMapping[ oSettings.aaSorting[i][0] ];
+ }
+
+ /* Fixed sorting */
+ if ( oSettings.aaSortingFixed !== null )
+ {
+ for ( i=0, iLen=oSettings.aaSortingFixed.length ; i<iLen ; i++ )
+ {
+ oSettings.aaSortingFixed[i][0] = aiInvertMapping[ oSettings.aaSortingFixed[i][0] ];
+ }
+ }
+
+ /* Data column sorting (the column which the sort for a given column should take place on) */
+ for ( i=0, iLen=iCols ; i<iLen ; i++ )
+ {
+ oCol = oSettings.aoColumns[i];
+ for ( j=0, jLen=oCol.aDataSort.length ; j<jLen ; j++ )
+ {
+ oCol.aDataSort[j] = aiInvertMapping[ oCol.aDataSort[j] ];
+ }
+
+ // Update the column indexes
+ if ( v110 ) {
+ oCol.idx = aiInvertMapping[ oCol.idx ];
+ }
+ }
+
+ if ( v110 ) {
+ // Update 1.10 optimised sort class removal variable
+ $.each( oSettings.aLastSort, function (i, val) {
+ oSettings.aLastSort[i].src = aiInvertMapping[ val.src ];
+ } );
+ }
+
+ /* Update the Get and Set functions for each column */
+ for ( i=0, iLen=iCols ; i<iLen ; i++ )
+ {
+ oCol = oSettings.aoColumns[i];
+
+ if ( typeof oCol.mData == 'number' ) {
+ oCol.mData = aiInvertMapping[ oCol.mData ];
+
+ // regenerate the get / set functions
+ oSettings.oApi._fnColumnOptions( oSettings, i, {} );
+ }
+ else if ( $.isPlainObject( oCol.mData ) ) {
+ // HTML5 data sourced
+ attrMap( oCol.mData, '_', aiInvertMapping );
+ attrMap( oCol.mData, 'filter', aiInvertMapping );
+ attrMap( oCol.mData, 'sort', aiInvertMapping );
+ attrMap( oCol.mData, 'type', aiInvertMapping );
+
+ // regenerate the get / set functions
+ oSettings.oApi._fnColumnOptions( oSettings, i, {} );
+ }
+ }
+
+
+ /*
+ * Move the DOM elements
+ */
+ if ( oSettings.aoColumns[iFrom].bVisible )
+ {
+ /* Calculate the current visible index and the point to insert the node before. The insert
+ * before needs to take into account that there might not be an element to insert before,
+ * in which case it will be null, and an appendChild should be used
+ */
+ var iVisibleIndex = this.oApi._fnColumnIndexToVisible( oSettings, iFrom );
+ var iInsertBeforeIndex = null;
+
+ i = iTo < iFrom ? iTo : iTo + 1;
+ while ( iInsertBeforeIndex === null && i < iCols )
+ {
+ iInsertBeforeIndex = this.oApi._fnColumnIndexToVisible( oSettings, i );
+ i++;
+ }
+
+ /* Header */
+ nTrs = oSettings.nTHead.getElementsByTagName('tr');
+ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
+ {
+ fnDomSwitch( nTrs[i], iVisibleIndex, iInsertBeforeIndex );
+ }
+
+ /* Footer */
+ if ( oSettings.nTFoot !== null )
+ {
+ nTrs = oSettings.nTFoot.getElementsByTagName('tr');
+ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
+ {
+ fnDomSwitch( nTrs[i], iVisibleIndex, iInsertBeforeIndex );
+ }
+ }
+
+ /* Body */
+ for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ )
+ {
+ if ( oSettings.aoData[i].nTr !== null )
+ {
+ fnDomSwitch( oSettings.aoData[i].nTr, iVisibleIndex, iInsertBeforeIndex );
+ }
+ }
+ }
+
+ /*
+ * Move the internal array elements
+ */
+ /* Columns */
+ fnArraySwitch( oSettings.aoColumns, iFrom, iTo );
+
+ /* Search columns */
+ fnArraySwitch( oSettings.aoPreSearchCols, iFrom, iTo );
+
+ /* Array array - internal data anodes cache */
+ for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ )
+ {
+ var data = oSettings.aoData[i];
+
+ if ( v110 ) {
+ // DataTables 1.10+
+ if ( data.anCells ) {
+ fnArraySwitch( data.anCells, iFrom, iTo );
+ }
+
+ // For DOM sourced data, the invalidate will reread the cell into
+ // the data array, but for data sources as an array, they need to
+ // be flipped
+ if ( data.src !== 'dom' && $.isArray( data._aData ) ) {
+ fnArraySwitch( data._aData, iFrom, iTo );
+ }
+ }
+ else {
+ // DataTables 1.9-
+ if ( $.isArray( data._aData ) ) {
+ fnArraySwitch( data._aData, iFrom, iTo );
+ }
+ fnArraySwitch( data._anHidden, iFrom, iTo );
+ }
+ }
+
+ /* Reposition the header elements in the header layout array */
+ for ( i=0, iLen=oSettings.aoHeader.length ; i<iLen ; i++ )
+ {
+ fnArraySwitch( oSettings.aoHeader[i], iFrom, iTo );
+ }
+
+ if ( oSettings.aoFooter !== null )
+ {
+ for ( i=0, iLen=oSettings.aoFooter.length ; i<iLen ; i++ )
+ {
+ fnArraySwitch( oSettings.aoFooter[i], iFrom, iTo );
+ }
+ }
+
+ // In 1.10 we need to invalidate row cached data for sorting, filtering etc
+ if ( v110 ) {
+ var api = new $.fn.dataTable.Api( oSettings );
+ api.rows().invalidate();
+ }
+
+ /*
+ * Update DataTables' event handlers
+ */
+
+ /* Sort listener */
+ for ( i=0, iLen=iCols ; i<iLen ; i++ )
+ {
+ $(oSettings.aoColumns[i].nTh).off('click.DT');
+ this.oApi._fnSortAttachListener( oSettings, oSettings.aoColumns[i].nTh, i );
+ }
+
+
+ /* Fire an event so other plug-ins can update */
+ $(oSettings.oInstance).trigger( 'column-reorder', [ oSettings, {
+ "iFrom": iFrom,
+ "iTo": iTo,
+ "aiInvertMapping": aiInvertMapping
+ } ] );
+};
+
+
+/**
+ * ColReorder provides column visibility control for DataTables
+ * @class ColReorder
+ * @constructor
+ * @param {object} dt DataTables settings object
+ * @param {object} opts ColReorder options
+ */
+var ColReorder = function( dt, opts )
+{
+ var oDTSettings;
+
+ if ( $.fn.dataTable.Api ) {
+ oDTSettings = new $.fn.dataTable.Api( dt ).settings()[0];
+ }
+ // 1.9 compatibility
+ else if ( dt.fnSettings ) {
+ // DataTables object, convert to the settings object
+ oDTSettings = dt.fnSettings();
+ }
+ else if ( typeof dt === 'string' ) {
+ // jQuery selector
+ if ( $.fn.dataTable.fnIsDataTable( $(dt)[0] ) ) {
+ oDTSettings = $(dt).eq(0).dataTable().fnSettings();
+ }
+ }
+ else if ( dt.nodeName && dt.nodeName.toLowerCase() === 'table' ) {
+ // Table node
+ if ( $.fn.dataTable.fnIsDataTable( dt.nodeName ) ) {
+ oDTSettings = $(dt.nodeName).dataTable().fnSettings();
+ }
+ }
+ else if ( dt instanceof jQuery ) {
+ // jQuery object
+ if ( $.fn.dataTable.fnIsDataTable( dt[0] ) ) {
+ oDTSettings = dt.eq(0).dataTable().fnSettings();
+ }
+ }
+ else {
+ // DataTables settings object
+ oDTSettings = dt;
+ }
+
+ // Ensure that we can't initialise on the same table twice
+ if ( oDTSettings._colReorder ) {
+ throw "ColReorder already initialised on table #"+oDTSettings.nTable.id;
+ }
+
+ // Convert from camelCase to Hungarian, just as DataTables does
+ var camelToHungarian = $.fn.dataTable.camelToHungarian;
+ if ( camelToHungarian ) {
+ camelToHungarian( ColReorder.defaults, ColReorder.defaults, true );
+ camelToHungarian( ColReorder.defaults, opts || {} );
+ }
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Public class variables
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+ /**
+ * @namespace Settings object which contains customisable information for ColReorder instance
+ */
+ this.s = {
+ /**
+ * DataTables settings object
+ * @property dt
+ * @type Object
+ * @default null
+ */
+ "dt": null,
+
+ /**
+ * Initialisation object used for this instance
+ * @property init
+ * @type object
+ * @default {}
+ */
+ "init": $.extend( true, {}, ColReorder.defaults, opts ),
+
+ /**
+ * Number of columns to fix (not allow to be reordered)
+ * @property fixed
+ * @type int
+ * @default 0
+ */
+ "fixed": 0,
+
+ /**
+ * Number of columns to fix counting from right (not allow to be reordered)
+ * @property fixedRight
+ * @type int
+ * @default 0
+ */
+ "fixedRight": 0,
+
+ /**
+ * Callback function for once the reorder has been done
+ * @property reorderCallback
+ * @type function
+ * @default null
+ */
+ "reorderCallback": null,
+
+ /**
+ * @namespace Information used for the mouse drag
+ */
+ "mouse": {
+ "startX": -1,
+ "startY": -1,
+ "offsetX": -1,
+ "offsetY": -1,
+ "target": -1,
+ "targetIndex": -1,
+ "fromIndex": -1
+ },
+
+ /**
+ * Information which is used for positioning the insert cusor and knowing where to do the
+ * insert. Array of objects with the properties:
+ * x: x-axis position
+ * to: insert point
+ * @property aoTargets
+ * @type array
+ * @default []
+ */
+ "aoTargets": []
+ };
+
+
+ /**
+ * @namespace Common and useful DOM elements for the class instance
+ */
+ this.dom = {
+ /**
+ * Dragging element (the one the mouse is moving)
+ * @property drag
+ * @type element
+ * @default null
+ */
+ "drag": null,
+
+ /**
+ * The insert cursor
+ * @property pointer
+ * @type element
+ * @default null
+ */
+ "pointer": null
+ };
+
+
+ /* Constructor logic */
+ this.s.dt = oDTSettings;
+ this.s.dt._colReorder = this;
+ this._fnConstruct();
+
+ /* Add destroy callback */
+ oDTSettings.oApi._fnCallbackReg(oDTSettings, 'aoDestroyCallback', $.proxy(this._fnDestroy, this), 'ColReorder');
+
+ return this;
+};
+
+
+
+ColReorder.prototype = {
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Public methods
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+ /**
+ * Reset the column ordering to the original ordering that was detected on
+ * start up.
+ * @return {this} Returns `this` for chaining.
+ *
+ * @example
+ * // DataTables initialisation with ColReorder
+ * var table = $('#example').dataTable( {
+ * "sDom": 'Rlfrtip'
+ * } );
+ *
+ * // Add click event to a button to reset the ordering
+ * $('#resetOrdering').click( function (e) {
+ * e.preventDefault();
+ * $.fn.dataTable.ColReorder( table ).fnReset();
+ * } );
+ */
+ "fnReset": function ()
+ {
+ var a = [];
+ for ( var i=0, iLen=this.s.dt.aoColumns.length ; i<iLen ; i++ )
+ {
+ a.push( this.s.dt.aoColumns[i]._ColReorder_iOrigCol );
+ }
+
+ this._fnOrderColumns( a );
+
+ return this;
+ },
+
+ /**
+ * `Deprecated` - Get the current order of the columns, as an array.
+ * @return {array} Array of column identifiers
+ * @deprecated `fnOrder` should be used in preference to this method.
+ * `fnOrder` acts as a getter/setter.
+ */
+ "fnGetCurrentOrder": function ()
+ {
+ return this.fnOrder();
+ },
+
+ /**
+ * Get the current order of the columns, as an array. Note that the values
+ * given in the array are unique identifiers for each column. Currently
+ * these are the original ordering of the columns that was detected on
+ * start up, but this could potentially change in future.
+ * @return {array} Array of column identifiers
+ *
+ * @example
+ * // Get column ordering for the table
+ * var order = $.fn.dataTable.ColReorder( dataTable ).fnOrder();
+ *//**
+ * Set the order of the columns, from the positions identified in the
+ * ordering array given. Note that ColReorder takes a brute force approach
+ * to reordering, so it is possible multiple reordering events will occur
+ * before the final order is settled upon.
+ * @param {array} [set] Array of column identifiers in the new order. Note
+ * that every column must be included, uniquely, in this array.
+ * @return {this} Returns `this` for chaining.
+ *
+ * @example
+ * // Swap the first and second columns
+ * $.fn.dataTable.ColReorder( dataTable ).fnOrder( [1, 0, 2, 3, 4] );
+ *
+ * @example
+ * // Move the first column to the end for the table `#example`
+ * var curr = $.fn.dataTable.ColReorder( '#example' ).fnOrder();
+ * var first = curr.shift();
+ * curr.push( first );
+ * $.fn.dataTable.ColReorder( '#example' ).fnOrder( curr );
+ *
+ * @example
+ * // Reverse the table's order
+ * $.fn.dataTable.ColReorder( '#example' ).fnOrder(
+ * $.fn.dataTable.ColReorder( '#example' ).fnOrder().reverse()
+ * );
+ */
+ "fnOrder": function ( set )
+ {
+ if ( set === undefined )
+ {
+ var a = [];
+ for ( var i=0, iLen=this.s.dt.aoColumns.length ; i<iLen ; i++ )
+ {
+ a.push( this.s.dt.aoColumns[i]._ColReorder_iOrigCol );
+ }
+ return a;
+ }
+
+ this._fnOrderColumns( fnInvertKeyValues( set ) );
+
+ return this;
+ },
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Private methods (they are of course public in JS, but recommended as private)
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+ /**
+ * Constructor logic
+ * @method _fnConstruct
+ * @returns void
+ * @private
+ */
+ "_fnConstruct": function ()
+ {
+ var that = this;
+ var iLen = this.s.dt.aoColumns.length;
+ var i;
+
+ /* Columns discounted from reordering - counting left to right */
+ if ( this.s.init.iFixedColumns )
+ {
+ this.s.fixed = this.s.init.iFixedColumns;
+ }
+
+ /* Columns discounted from reordering - counting right to left */
+ this.s.fixedRight = this.s.init.iFixedColumnsRight ?
+ this.s.init.iFixedColumnsRight :
+ 0;
+
+ /* Drop callback initialisation option */
+ if ( this.s.init.fnReorderCallback )
+ {
+ this.s.reorderCallback = this.s.init.fnReorderCallback;
+ }
+
+ /* Add event handlers for the drag and drop, and also mark the original column order */
+ for ( i = 0; i < iLen; i++ )
+ {
+ if ( i > this.s.fixed-1 && i < iLen - this.s.fixedRight )
+ {
+ this._fnMouseListener( i, this.s.dt.aoColumns[i].nTh );
+ }
+
+ /* Mark the original column order for later reference */
+ this.s.dt.aoColumns[i]._ColReorder_iOrigCol = i;
+ }
+
+ /* State saving */
+ this.s.dt.oApi._fnCallbackReg( this.s.dt, 'aoStateSaveParams', function (oS, oData) {
+ that._fnStateSave.call( that, oData );
+ }, "ColReorder_State" );
+
+ /* An initial column order has been specified */
+ var aiOrder = null;
+ if ( this.s.init.aiOrder )
+ {
+ aiOrder = this.s.init.aiOrder.slice();
+ }
+
+ /* State loading, overrides the column order given */
+ if ( this.s.dt.oLoadedState && typeof this.s.dt.oLoadedState.ColReorder != 'undefined' &&
+ this.s.dt.oLoadedState.ColReorder.length == this.s.dt.aoColumns.length )
+ {
+ aiOrder = this.s.dt.oLoadedState.ColReorder;
+ }
+
+ /* If we have an order to apply - do so */
+ if ( aiOrder )
+ {
+ /* We might be called during or after the DataTables initialisation. If before, then we need
+ * to wait until the draw is done, if after, then do what we need to do right away
+ */
+ if ( !that.s.dt._bInitComplete )
+ {
+ var bDone = false;
+ this.s.dt.aoDrawCallback.push( {
+ "fn": function () {
+ if ( !that.s.dt._bInitComplete && !bDone )
+ {
+ bDone = true;
+ var resort = fnInvertKeyValues( aiOrder );
+ that._fnOrderColumns.call( that, resort );
+ }
+ },
+ "sName": "ColReorder_Pre"
+ } );
+ }
+ else
+ {
+ var resort = fnInvertKeyValues( aiOrder );
+ that._fnOrderColumns.call( that, resort );
+ }
+ }
+ else {
+ this._fnSetColumnIndexes();
+ }
+ },
+
+
+ /**
+ * Set the column order from an array
+ * @method _fnOrderColumns
+ * @param array a An array of integers which dictate the column order that should be applied
+ * @returns void
+ * @private
+ */
+ "_fnOrderColumns": function ( a )
+ {
+ if ( a.length != this.s.dt.aoColumns.length )
+ {
+ this.s.dt.oInstance.oApi._fnLog( this.s.dt, 1, "ColReorder - array reorder does not "+
+ "match known number of columns. Skipping." );
+ return;
+ }
+
+ for ( var i=0, iLen=a.length ; i<iLen ; i++ )
+ {
+ var currIndex = $.inArray( i, a );
+ if ( i != currIndex )
+ {
+ /* Reorder our switching array */
+ fnArraySwitch( a, currIndex, i );
+
+ /* Do the column reorder in the table */
+ this.s.dt.oInstance.fnColReorder( currIndex, i );
+ }
+ }
+
+ /* When scrolling we need to recalculate the column sizes to allow for the shift */
+ if ( this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "" )
+ {
+ this.s.dt.oInstance.fnAdjustColumnSizing( false );
+ }
+
+ /* Save the state */
+ this.s.dt.oInstance.oApi._fnSaveState( this.s.dt );
+
+ this._fnSetColumnIndexes();
+
+ if ( this.s.reorderCallback !== null )
+ {
+ this.s.reorderCallback.call( this );
+ }
+ },
+
+
+ /**
+ * Because we change the indexes of columns in the table, relative to their starting point
+ * we need to reorder the state columns to what they are at the starting point so we can
+ * then rearrange them again on state load!
+ * @method _fnStateSave
+ * @param object oState DataTables state
+ * @returns string JSON encoded cookie string for DataTables
+ * @private
+ */
+ "_fnStateSave": function ( oState )
+ {
+ var i, iLen, aCopy, iOrigColumn;
+ var oSettings = this.s.dt;
+ var columns = oSettings.aoColumns;
+
+ oState.ColReorder = [];
+
+ /* Sorting */
+ if ( oState.aaSorting ) {
+ // 1.10.0-
+ for ( i=0 ; i<oState.aaSorting.length ; i++ ) {
+ oState.aaSorting[i][0] = columns[ oState.aaSorting[i][0] ]._ColReorder_iOrigCol;
+ }
+
+ var aSearchCopy = $.extend( true, [], oState.aoSearchCols );
+
+ for ( i=0, iLen=columns.length ; i<iLen ; i++ )
+ {
+ iOrigColumn = columns[i]._ColReorder_iOrigCol;
+
+ /* Column filter */
+ oState.aoSearchCols[ iOrigColumn ] = aSearchCopy[i];
+
+ /* Visibility */
+ oState.abVisCols[ iOrigColumn ] = columns[i].bVisible;
+
+ /* Column reordering */
+ oState.ColReorder.push( iOrigColumn );
+ }
+ }
+ else if ( oState.order ) {
+ // 1.10.1+
+ for ( i=0 ; i<oState.order.length ; i++ ) {
+ oState.order[i][0] = columns[ oState.order[i][0] ]._ColReorder_iOrigCol;
+ }
+
+ var stateColumnsCopy = $.extend( true, [], oState.columns );
+
+ for ( i=0, iLen=columns.length ; i<iLen ; i++ )
+ {
+ iOrigColumn = columns[i]._ColReorder_iOrigCol;
+
+ /* Columns */
+ oState.columns[ iOrigColumn ] = stateColumnsCopy[i];
+
+ /* Column reordering */
+ oState.ColReorder.push( iOrigColumn );
+ }
+ }
+ },
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Mouse drop and drag
+ */
+
+ /**
+ * Add a mouse down listener to a particluar TH element
+ * @method _fnMouseListener
+ * @param int i Column index
+ * @param element nTh TH element clicked on
+ * @returns void
+ * @private
+ */
+ "_fnMouseListener": function ( i, nTh )
+ {
+ var that = this;
+ $(nTh).on( 'mousedown.ColReorder', function (e) {
+ e.preventDefault();
+ that._fnMouseDown.call( that, e, nTh );
+ } );
+ },
+
+
+ /**
+ * Mouse down on a TH element in the table header
+ * @method _fnMouseDown
+ * @param event e Mouse event
+ * @param element nTh TH element to be dragged
+ * @returns void
+ * @private
+ */
+ "_fnMouseDown": function ( e, nTh )
+ {
+ var that = this;
+
+ /* Store information about the mouse position */
+ var target = $(e.target).closest('th, td');
+ var offset = target.offset();
+ var idx = parseInt( $(nTh).attr('data-column-index'), 10 );
+
+ if ( idx === undefined ) {
+ return;
+ }
+
+ this.s.mouse.startX = e.pageX;
+ this.s.mouse.startY = e.pageY;
+ this.s.mouse.offsetX = e.pageX - offset.left;
+ this.s.mouse.offsetY = e.pageY - offset.top;
+ this.s.mouse.target = this.s.dt.aoColumns[ idx ].nTh;//target[0];
+ this.s.mouse.targetIndex = idx;
+ this.s.mouse.fromIndex = idx;
+
+ this._fnRegions();
+
+ /* Add event handlers to the document */
+ $(document)
+ .on( 'mousemove.ColReorder', function (e) {
+ that._fnMouseMove.call( that, e );
+ } )
+ .on( 'mouseup.ColReorder', function (e) {
+ that._fnMouseUp.call( that, e );
+ } );
+ },
+
+
+ /**
+ * Deal with a mouse move event while dragging a node
+ * @method _fnMouseMove
+ * @param event e Mouse event
+ * @returns void
+ * @private
+ */
+ "_fnMouseMove": function ( e )
+ {
+ var that = this;
+
+ if ( this.dom.drag === null )
+ {
+ /* Only create the drag element if the mouse has moved a specific distance from the start
+ * point - this allows the user to make small mouse movements when sorting and not have a
+ * possibly confusing drag element showing up
+ */
+ if ( Math.pow(
+ Math.pow(e.pageX - this.s.mouse.startX, 2) +
+ Math.pow(e.pageY - this.s.mouse.startY, 2), 0.5 ) < 5 )
+ {
+ return;
+ }
+ this._fnCreateDragNode();
+ }
+
+ /* Position the element - we respect where in the element the click occured */
+ this.dom.drag.css( {
+ left: e.pageX - this.s.mouse.offsetX,
+ top: e.pageY - this.s.mouse.offsetY
+ } );
+
+ /* Based on the current mouse position, calculate where the insert should go */
+ var bSet = false;
+ var lastToIndex = this.s.mouse.toIndex;
+
+ for ( var i=1, iLen=this.s.aoTargets.length ; i<iLen ; i++ )
+ {
+ if ( e.pageX < this.s.aoTargets[i-1].x + ((this.s.aoTargets[i].x-this.s.aoTargets[i-1].x)/2) )
+ {
+ this.dom.pointer.css( 'left', this.s.aoTargets[i-1].x );
+ this.s.mouse.toIndex = this.s.aoTargets[i-1].to;
+ bSet = true;
+ break;
+ }
+ }
+
+ // The insert element wasn't positioned in the array (less than
+ // operator), so we put it at the end
+ if ( !bSet )
+ {
+ this.dom.pointer.css( 'left', this.s.aoTargets[this.s.aoTargets.length-1].x );
+ this.s.mouse.toIndex = this.s.aoTargets[this.s.aoTargets.length-1].to;
+ }
+
+ // Perform reordering if realtime updating is on and the column has moved
+ if ( this.s.init.bRealtime && lastToIndex !== this.s.mouse.toIndex ) {
+ this.s.dt.oInstance.fnColReorder( this.s.mouse.fromIndex, this.s.mouse.toIndex );
+ this.s.mouse.fromIndex = this.s.mouse.toIndex;
+ this._fnRegions();
+ }
+ },
+
+
+ /**
+ * Finish off the mouse drag and insert the column where needed
+ * @method _fnMouseUp
+ * @param event e Mouse event
+ * @returns void
+ * @private
+ */
+ "_fnMouseUp": function ( e )
+ {
+ var that = this;
+
+ $(document).off( 'mousemove.ColReorder mouseup.ColReorder' );
+
+ if ( this.dom.drag !== null )
+ {
+ /* Remove the guide elements */
+ this.dom.drag.remove();
+ this.dom.pointer.remove();
+ this.dom.drag = null;
+ this.dom.pointer = null;
+
+ /* Actually do the reorder */
+ this.s.dt.oInstance.fnColReorder( this.s.mouse.fromIndex, this.s.mouse.toIndex );
+ this._fnSetColumnIndexes();
+
+ /* When scrolling we need to recalculate the column sizes to allow for the shift */
+ if ( this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "" )
+ {
+ this.s.dt.oInstance.fnAdjustColumnSizing( false );
+ }
+
+ /* Save the state */
+ this.s.dt.oInstance.oApi._fnSaveState( this.s.dt );
+
+ if ( this.s.reorderCallback !== null )
+ {
+ this.s.reorderCallback.call( this );
+ }
+ }
+ },
+
+
+ /**
+ * Calculate a cached array with the points of the column inserts, and the
+ * 'to' points
+ * @method _fnRegions
+ * @returns void
+ * @private
+ */
+ "_fnRegions": function ()
+ {
+ var aoColumns = this.s.dt.aoColumns;
+
+ this.s.aoTargets.splice( 0, this.s.aoTargets.length );
+
+ this.s.aoTargets.push( {
+ "x": $(this.s.dt.nTable).offset().left,
+ "to": 0
+ } );
+
+ var iToPoint = 0;
+ for ( var i=0, iLen=aoColumns.length ; i<iLen ; i++ )
+ {
+ /* For the column / header in question, we want it's position to remain the same if the
+ * position is just to it's immediate left or right, so we only incremement the counter for
+ * other columns
+ */
+ if ( i != this.s.mouse.fromIndex )
+ {
+ iToPoint++;
+ }
+
+ if ( aoColumns[i].bVisible )
+ {
+ this.s.aoTargets.push( {
+ "x": $(aoColumns[i].nTh).offset().left + $(aoColumns[i].nTh).outerWidth(),
+ "to": iToPoint
+ } );
+ }
+ }
+
+ /* Disallow columns for being reordered by drag and drop, counting right to left */
+ if ( this.s.fixedRight !== 0 )
+ {
+ this.s.aoTargets.splice( this.s.aoTargets.length - this.s.fixedRight );
+ }
+
+ /* Disallow columns for being reordered by drag and drop, counting left to right */
+ if ( this.s.fixed !== 0 )
+ {
+ this.s.aoTargets.splice( 0, this.s.fixed );
+ }
+ },
+
+
+ /**
+ * Copy the TH element that is being drags so the user has the idea that they are actually
+ * moving it around the page.
+ * @method _fnCreateDragNode
+ * @returns void
+ * @private
+ */
+ "_fnCreateDragNode": function ()
+ {
+ var scrolling = this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "";
+
+ var origCell = this.s.dt.aoColumns[ this.s.mouse.targetIndex ].nTh;
+ var origTr = origCell.parentNode;
+ var origThead = origTr.parentNode;
+ var origTable = origThead.parentNode;
+ var cloneCell = $(origCell).clone();
+
+ // This is a slightly odd combination of jQuery and DOM, but it is the
+ // fastest and least resource intensive way I could think of cloning
+ // the table with just a single header cell in it.
+ this.dom.drag = $(origTable.cloneNode(false))
+ .addClass( 'DTCR_clonedTable' )
+ .append(
+ $(origThead.cloneNode(false)).append(
+ $(origTr.cloneNode(false)).append(
+ cloneCell[0]
+ )
+ )
+ )
+ .css( {
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ width: $(origCell).outerWidth(),
+ height: $(origCell).outerHeight()
+ } )
+ .appendTo( 'body' );
+
+ this.dom.pointer = $('<div></div>')
+ .addClass( 'DTCR_pointer' )
+ .css( {
+ position: 'absolute',
+ top: scrolling ?
+ $('div.dataTables_scroll', this.s.dt.nTableWrapper).offset().top :
+ $(this.s.dt.nTable).offset().top,
+ height : scrolling ?
+ $('div.dataTables_scroll', this.s.dt.nTableWrapper).height() :
+ $(this.s.dt.nTable).height()
+ } )
+ .appendTo( 'body' );
+ },
+
+ /**
+ * Clean up ColReorder memory references and event handlers
+ * @method _fnDestroy
+ * @returns void
+ * @private
+ */
+ "_fnDestroy": function ()
+ {
+ var i, iLen;
+
+ for ( i=0, iLen=this.s.dt.aoDrawCallback.length ; i<iLen ; i++ )
+ {
+ if ( this.s.dt.aoDrawCallback[i].sName === 'ColReorder_Pre' )
+ {
+ this.s.dt.aoDrawCallback.splice( i, 1 );
+ break;
+ }
+ }
+
+ $(this.s.dt.nTHead).find( '*' ).off( '.ColReorder' );
+
+ $.each( this.s.dt.aoColumns, function (i, column) {
+ $(column.nTh).removeAttr('data-column-index');
+ } );
+
+ this.s.dt._colReorder = null;
+ this.s = null;
+ },
+
+
+ /**
+ * Add a data attribute to the column headers, so we know the index of
+ * the row to be reordered. This allows fast detection of the index, and
+ * for this plug-in to work with FixedHeader which clones the nodes.
+ * @private
+ */
+ "_fnSetColumnIndexes": function ()
+ {
+ $.each( this.s.dt.aoColumns, function (i, column) {
+ $(column.nTh).attr('data-column-index', i);
+ } );
+ }
+};
+
+
+
+
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Static parameters
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+
+/**
+ * ColReorder default settings for initialisation
+ * @namespace
+ * @static
+ */
+ColReorder.defaults = {
+ /**
+ * Predefined ordering for the columns that will be applied automatically
+ * on initialisation. If not specified then the order that the columns are
+ * found to be in the HTML is the order used.
+ * @type array
+ * @default null
+ * @static
+ * @example
+ * // Using the `oColReorder` option in the DataTables options object
+ * $('#example').dataTable( {
+ * "sDom": 'Rlfrtip',
+ * "oColReorder": {
+ * "aiOrder": [ 4, 3, 2, 1, 0 ]
+ * }
+ * } );
+ *
+ * @example
+ * // Using `new` constructor
+ * $('#example').dataTable()
+ *
+ * new $.fn.dataTable.ColReorder( '#example', {
+ * "aiOrder": [ 4, 3, 2, 1, 0 ]
+ * } );
+ */
+ aiOrder: null,
+
+ /**
+ * Redraw the table's column ordering as the end user draws the column
+ * (`true`) or wait until the mouse is released (`false` - default). Note
+ * that this will perform a redraw on each reordering, which involves an
+ * Ajax request each time if you are using server-side processing in
+ * DataTables.
+ * @type boolean
+ * @default false
+ * @static
+ * @example
+ * // Using the `oColReorder` option in the DataTables options object
+ * $('#example').dataTable( {
+ * "sDom": 'Rlfrtip',
+ * "oColReorder": {
+ * "bRealtime": true
+ * }
+ * } );
+ *
+ * @example
+ * // Using `new` constructor
+ * $('#example').dataTable()
+ *
+ * new $.fn.dataTable.ColReorder( '#example', {
+ * "bRealtime": true
+ * } );
+ */
+ bRealtime: false,
+
+ /**
+ * Indicate how many columns should be fixed in position (counting from the
+ * left). This will typically be 1 if used, but can be as high as you like.
+ * @type int
+ * @default 0
+ * @static
+ * @example
+ * // Using the `oColReorder` option in the DataTables options object
+ * $('#example').dataTable( {
+ * "sDom": 'Rlfrtip',
+ * "oColReorder": {
+ * "iFixedColumns": 1
+ * }
+ * } );
+ *
+ * @example
+ * // Using `new` constructor
+ * $('#example').dataTable()
+ *
+ * new $.fn.dataTable.ColReorder( '#example', {
+ * "iFixedColumns": 1
+ * } );
+ */
+ iFixedColumns: 0,
+
+ /**
+ * As `iFixedColumnsRight` but counting from the right.
+ * @type int
+ * @default 0
+ * @static
+ * @example
+ * // Using the `oColReorder` option in the DataTables options object
+ * $('#example').dataTable( {
+ * "sDom": 'Rlfrtip',
+ * "oColReorder": {
+ * "iFixedColumnsRight": 1
+ * }
+ * } );
+ *
+ * @example
+ * // Using `new` constructor
+ * $('#example').dataTable()
+ *
+ * new $.fn.dataTable.ColReorder( '#example', {
+ * "iFixedColumnsRight": 1
+ * } );
+ */
+ iFixedColumnsRight: 0,
+
+ /**
+ * Callback function that is fired when columns are reordered
+ * @type function():void
+ * @default null
+ * @static
+ * @example
+ * // Using the `oColReorder` option in the DataTables options object
+ * $('#example').dataTable( {
+ * "sDom": 'Rlfrtip',
+ * "oColReorder": {
+ * "fnReorderCallback": function () {
+ * alert( 'Columns reordered' );
+ * }
+ * }
+ * } );
+ *
+ * @example
+ * // Using `new` constructor
+ * $('#example').dataTable()
+ *
+ * new $.fn.dataTable.ColReorder( '#example', {
+ * "fnReorderCallback": function () {
+ * alert( 'Columns reordered' );
+ * }
+ * } );
+ */
+ fnReorderCallback: null
+};
+
+
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Constants
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+/**
+ * ColReorder version
+ * @constant version
+ * @type String
+ * @default As code
+ */
+ColReorder.version = "1.1.3";
+
+
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * DataTables interfaces
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+// Expose
+$.fn.dataTable.ColReorder = ColReorder;
+$.fn.DataTable.ColReorder = ColReorder;
+
+
+// Register a new feature with DataTables
+if ( typeof $.fn.dataTable == "function" &&
+ typeof $.fn.dataTableExt.fnVersionCheck == "function" &&
+ $.fn.dataTableExt.fnVersionCheck('1.9.3') )
+{
+ $.fn.dataTableExt.aoFeatures.push( {
+ "fnInit": function( settings ) {
+ var table = settings.oInstance;
+
+ if ( ! settings._colReorder ) {
+ var dtInit = settings.oInit;
+ var opts = dtInit.colReorder || dtInit.oColReorder || {};
+
+ new ColReorder( settings, opts );
+ }
+ else {
+ table.oApi._fnLog( settings, 1, "ColReorder attempted to initialise twice. Ignoring second" );
+ }
+
+ return null; /* No node for DataTables to insert */
+ },
+ "cFeature": "R",
+ "sFeature": "ColReorder"
+ } );
+}
+else {
+ alert( "Warning: ColReorder requires DataTables 1.9.3 or greater - www.datatables.net/download");
+}
+
+
+// API augmentation
+if ( $.fn.dataTable.Api ) {
+ $.fn.dataTable.Api.register( 'colReorder.reset()', function () {
+ return this.iterator( 'table', function ( ctx ) {
+ ctx._colReorder.fnReset();
+ } );
+ } );
+
+ $.fn.dataTable.Api.register( 'colReorder.order()', function ( set ) {
+ if ( set ) {
+ return this.iterator( 'table', function ( ctx ) {
+ ctx._colReorder.fnOrder( set );
+ } );
+ }
+
+ return this.context.length ?
+ this.context[0]._colReorder.fnOrder() :
+ null;
+ } );
+}
+
+return ColReorder;
+}; // /factory
+
+
+// Define as an AMD module if possible
+if ( typeof define === 'function' && define.amd ) {
+ define( ['jquery', 'datatables'], factory );
+}
+else if ( typeof exports === 'object' ) {
+ // Node/CommonJS
+ factory( require('jquery'), require('datatables') );
+}
+else if ( jQuery && !jQuery.fn.dataTable.ColReorder ) {
+ // Otherwise simply initialise as normal, stopping multiple evaluation
+ factory( jQuery, jQuery.fn.dataTable );
+}
+
+
+})(window, document); \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.colResize.js b/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.colResize.js
new file mode 100644
index 00000000..2712750a
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.colResize.js
@@ -0,0 +1,846 @@
+/*! ColResize 0.0.10
+ */
+
+/**
+ * @summary ColResize
+ * @description Provide the ability to resize columns in a DataTable
+ * @version 0.0.10
+ * @file dataTables.colResize.js
+ * @author Silvacom Ltd.
+ *
+ * For details please refer to: http://www.datatables.net
+ *
+ * Special thank to everyone who has contributed to this plug in
+ * - dykstrad
+ * - tdillan (for 0.0.3 and 0.0.5 bug fixes)
+ * - kylealonius (for 0.0.8 bug fix)
+ * - the86freak (for 0.0.9 bug fix)
+ */
+
+(function (window, document, undefined) {
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * DataTables plug-in API functions test
+ *
+ * This are required by ColResize in order to perform the tasks required, and also keep this
+ * code portable, to be used for other column resize projects with DataTables, if needed.
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+ var factory = function ($, DataTable) {
+ "use strict";
+
+ /**
+ * Plug-in for DataTables which will resize the columns depending on the handle clicked
+ * @method $.fn.dataTableExt.oApi.fnColResize
+ * @param object oSettings DataTables settings object - automatically added by DataTables!
+ * @param int iCol Take the column to be resized
+ * @returns void
+ */
+ $.fn.dataTableExt.oApi.fnColResize = function (oSettings, iCol) {
+ var v110 = $.fn.dataTable.Api ? true : false;
+
+ /*
+ * Update DataTables' event handlers
+ */
+
+ /* Fire an event so other plug-ins can update */
+ $(oSettings.oInstance).trigger('column-resize', [ oSettings, {
+ "iCol": iCol
+ } ]);
+ };
+
+ /**
+ * ColResize provides column resize control for DataTables
+ * @class ColResize
+ * @constructor
+ * @param {object} dt DataTables settings object
+ * @param {object} opts ColResize options
+ */
+ var ColResize = function (dt, opts) {
+ var oDTSettings;
+
+ if ($.fn.dataTable.Api) {
+ oDTSettings = new $.fn.dataTable.Api(dt).settings()[0];
+ }
+ // 1.9 compatibility
+ else if (dt.fnSettings) {
+ // DataTables object, convert to the settings object
+ oDTSettings = dt.fnSettings();
+ }
+ else if (typeof dt === 'string') {
+ // jQuery selector
+ if ($.fn.dataTable.fnIsDataTable($(dt)[0])) {
+ oDTSettings = $(dt).eq(0).dataTable().fnSettings();
+ }
+ }
+ else if (dt.nodeName && dt.nodeName.toLowerCase() === 'table') {
+ // Table node
+ if ($.fn.dataTable.fnIsDataTable(dt.nodeName)) {
+ oDTSettings = $(dt.nodeName).dataTable().fnSettings();
+ }
+ }
+ else if (dt instanceof jQuery) {
+ // jQuery object
+ if ($.fn.dataTable.fnIsDataTable(dt[0])) {
+ oDTSettings = dt.eq(0).dataTable().fnSettings();
+ }
+ }
+ else {
+ // DataTables settings object
+ oDTSettings = dt;
+ }
+
+ // Convert from camelCase to Hungarian, just as DataTables does
+ if ($.fn.dataTable.camelToHungarian) {
+ $.fn.dataTable.camelToHungarian(ColResize.defaults, opts || {});
+ }
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Public class variables
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+ /**
+ * @namespace Settings object which contains customizable information for ColResize instance
+ */
+ this.s = {
+ /**
+ * DataTables settings object
+ * @property dt
+ * @type Object
+ * @default null
+ */
+ "dt": null,
+
+ /**
+ * Initialisation object used for this instance
+ * @property init
+ * @type object
+ * @default {}
+ */
+ "init": $.extend(true, {}, ColResize.defaults, opts),
+
+ /**
+ * @namespace Information used for the mouse drag
+ */
+ "mouse": {
+ "startX": -1,
+ "startY": -1,
+ "targetIndex": -1,
+ "targetColumn": -1,
+ "neighbourIndex": -1,
+ "neighbourColumn": -1
+ },
+
+ /**
+ * Status variable keeping track of mouse down status
+ * @property isMousedown
+ * @type boolean
+ * @default false
+ */
+ "isMousedown": false
+ };
+
+
+ /**
+ * @namespace Common and useful DOM elements for the class instance
+ */
+ this.dom = {
+ /**
+ * Resizing element (the one the mouse is resizing)
+ * @property resize
+ * @type element
+ * @default null
+ */
+ "resizeCol": null,
+
+ /**
+ * Resizing element neighbour (the column next to the one the mouse is resizing)
+ * This is for fixed table resizing.
+ * @property resize
+ * @type element
+ * @default null
+ */
+ "resizeColNeighbour": null,
+
+ /**
+ * Array of events to be restored, used for overriding existing events from other plugins for a time.
+ * @property restoreEvents
+ * @type array
+ * @default []
+ */
+ "restoreEvents": []
+ };
+
+
+ /* Constructor logic */
+ this.s.dt = oDTSettings.oInstance.fnSettings();
+ this.s.dt._colResize = this;
+ this._fnConstruct();
+
+ /* Add destroy callback */
+ oDTSettings.oApi._fnCallbackReg(oDTSettings, 'aoDestroyCallback', $.proxy(this._fnDestroy, this), 'ColResize');
+
+ return this;
+ };
+
+
+ ColResize.prototype = {
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Public methods
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+ /**
+ * Reset the column widths to the original widths that was detected on
+ * start up.
+ * @return {this} Returns `this` for chaining.
+ *
+ * @example
+ * // DataTables initialisation with ColResize
+ * var table = $('#example').dataTable( {
+ * "sDom": 'Zlfrtip'
+ * } );
+ *
+ * // Add click event to a button to reset the ordering
+ * $('#resetOrdering').click( function (e) {
+ * e.preventDefault();
+ * $.fn.dataTable.ColResize( table ).fnReset();
+ * } );
+ */
+ "fnReset": function () {
+ var a = [];
+ for (var i = 0, iLen = this.s.dt.aoColumns.length; i < iLen; i++) {
+ this.s.dt.aoColumns[i].width = this.s.dt.aoColumns[i]._ColResize_iOrigWidth;
+ }
+
+ this.s.dt.adjust().draw();
+
+ return this;
+ },
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Private methods (they are of course public in JS, but recommended as private)
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+ /**
+ * Constructor logic
+ * @method _fnConstruct
+ * @returns void
+ * @private
+ */
+ "_fnConstruct": function () {
+ var that = this;
+ var iLen = that.s.dt.aoColumns.length;
+ var i;
+
+ that._fnSetupMouseListeners();
+
+ /* Add event handlers for the resize handles */
+ for (i = 0; i < iLen; i++) {
+ /* Mark the original column width for later reference */
+ this.s.dt.aoColumns[i]._ColResize_iOrigWidth = this.s.dt.aoColumns[i].width;
+ }
+
+ this._fnSetColumnIndexes();
+
+ /* State saving */
+ this.s.dt.oApi._fnCallbackReg( this.s.dt, 'aoStateSaveParams', function (oS, oData) {
+ that._fnStateSave.call(that, oData);
+ }, "ColResize_State" );
+
+ // State loading
+ this._fnStateLoad();
+ },
+
+ /**
+ * @method _fnStateSave
+ * @param object oState DataTables state
+ * @private
+ */
+ "_fnStateSave": function (oState) {
+ this.s.dt.aoColumns.forEach(function(col, index) {
+ oState.columns[index].width = col.sWidthOrig;
+ });
+ },
+
+ /**
+ * If state has been loaded, apply the saved widths to the columns
+ * @method _fnStateLoad
+ * @private
+ */
+ "_fnStateLoad": function() {
+ var that = this,
+ loadedState = this.s.dt.oLoadedState;
+ if (loadedState && loadedState.columns) {
+ var colStates = loadedState.columns,
+ currCols = this.s.dt.aoColumns;
+ // Only apply the saved widths if the number of columns is the same.
+ // Otherwise, we don't know if we're applying the width to the correct column.
+ if (colStates.length > 0 && colStates.length === currCols.length) {
+ colStates.forEach(function(state, index) {
+ var col = that.s.dt.aoColumns[index];
+ if (state.width) {
+ col.sWidthOrig = col.sWidth = state.width;
+ }
+ });
+ }
+ }
+ },
+
+ /**
+ * Remove events of type from obj add it to restoreEvents array to be restored at a later time
+ * @param until string flag when to restore the event
+ * @param obj Object to remove events from
+ * @param type type of event to remove
+ * @param namespace namespace of the event being removed
+ */
+ "_fnDelayEvents": function (until, obj, type, namespace) {
+ var that = this;
+ //Get the events for the object
+ var events = $._data($(obj).get(0), 'events');
+ $.each(events, function (i, o) {
+ //If the event type matches
+ if (i == type) {
+ //Loop through the possible many events with that type
+ $.each(o, function (k, v) {
+ //Somehow it is possible for the event to be undefined make sure it is defined first
+ if (v) {
+ if (namespace) {
+ //Add the event to the array of events to be restored later
+ that.dom.restoreEvents.push({"until": until, "obj": obj, "type": v.type, "namespace": v.namespace, "handler": v.handler});
+ //If the namespace matches
+ if (v.namespace == namespace) {
+ //Turn off/unbind the event
+ $(obj).off(type + "." + namespace);
+ }
+ } else {
+ //Add the event to the array of events to be restored later
+ that.dom.restoreEvents.push({"until": until, "obj": obj, "type": v.type, "namespace": null, "handler": v.handler});
+ //Turn off/unbind the event
+ $(obj).off(type);
+ }
+ }
+ });
+ }
+ });
+ },
+
+ /**
+ * Loop through restoreEvents array and restore the events on the elements provided
+ */
+ "_fnRestoreEvents": function (until) {
+ var that = this;
+ //Loop through the events to be restored
+ var i;
+ for (i = that.dom.restoreEvents.length; i--;) {
+ if (that.dom.restoreEvents[i].until == undefined || that.dom.restoreEvents[i].until == null || that.dom.restoreEvents[i].until == until) {
+ if (that.dom.restoreEvents[i].namespace) {
+ //Turn on the event for the object provided
+ $(that.dom.restoreEvents[i].obj).off(that.dom.restoreEvents[i].type + "." + that.dom.restoreEvents[i].namespace).on(that.dom.restoreEvents[i].type + "." + that.dom.restoreEvents[i].namespace, that.dom.restoreEvents[i].handler);
+ that.dom.restoreEvents.splice(i, 1);
+ } else {
+ //Turn on the event for the object provided
+ $(that.dom.restoreEvents[i].obj).off(that.dom.restoreEvents[i].type).on(that.dom.restoreEvents[i].type, that.dom.restoreEvents[i].handler);
+ that.dom.restoreEvents.splice(i, 1);
+ }
+ }
+ }
+ },
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Mouse drop and drag
+ */
+
+ "_fnSetupMouseListeners":function() {
+ var that = this;
+ $(that.s.dt.nTableWrapper).off("mouseenter.ColResize").on("mouseenter.ColResize","th",function(e) {
+ e.preventDefault();
+ that._fnMouseEnter.call(that, e, this);
+ });
+ $(that.s.dt.nTableWrapper).off("mouseleave.ColResize").on("mouseleave.ColResize","th",function(e) {
+ e.preventDefault();
+ that._fnMouseLeave.call(that, e, this);
+ });
+ },
+
+ /**
+ * Add mouse listeners to the resize handle on TH element
+ * @method _fnMouseListener
+ * @param i Column index
+ * @param nTh TH resize handle element clicked on
+ * @returns void
+ * @private
+ */
+ "_fnMouseListener": function (i, nTh) {
+ var that = this;
+ $(nTh).off('mouseenter.ColResize').on('mouseenter.ColResize', function (e) {
+ e.preventDefault();
+ that._fnMouseEnter.call(that, e, nTh);
+ });
+ $(nTh).off('mouseleave.ColResize').on('mouseleave.ColResize', function (e) {
+ e.preventDefault();
+ that._fnMouseLeave.call(that, e, nTh);
+ });
+ },
+
+ /**
+ *
+ * @param e Mouse event
+ * @param nTh TH element that the mouse is over
+ */
+ "_fnMouseEnter": function (e, nTh) {
+ var that = this;
+ if(!that.s.isMousedown) {
+ //Once the mouse has entered the cell add mouse move event to see if the mouse is over resize handle
+ $(nTh).off('mousemove.ColResizeHandle').on('mousemove.ColResizeHandle', function (e) {
+ e.preventDefault();
+ that._fnResizeHandleCheck.call(that, e, nTh);
+ });
+ }
+ },
+
+ /**
+ * Clear mouse events when the mouse has left the th
+ * @param e Mouse event
+ * @param nTh TH element that the mouse has just left
+ */
+ "_fnMouseLeave": function (e, nTh) {
+ //Once the mouse has left the TH make suure to remove the mouse move listener
+ $(nTh).off('mousemove.ColResizeHandle');
+ },
+
+ /**
+ * Mouse down on a TH element in the table header
+ * @method _fnMouseDown
+ * @param event e Mouse event
+ * @param element nTh TH element to be resized
+ * @returns void
+ * @private
+ */
+ "_fnMouseDown": function (e, nTh) {
+ var that = this;
+
+ that.s.isMousedown = true;
+
+ /* Store information about the mouse position */
+ var target = $(e.target).closest('th, td');
+ var offset = target.offset();
+
+ /* Store information about the mouse position for resize calculations in mouse move function */
+ this.s.mouse.startX = e.pageX;
+ this.s.mouse.startY = e.pageY;
+
+ //Store the indexes of the columns the mouse is down on
+ var idx = that.dom.resizeCol[0].cellIndex;
+
+ // the last column has no 'right-side' neighbour
+ // with fixed this can make the table smaller
+ if (that.dom.resizeColNeighbour[0] === undefined){
+ var idxNeighbour = 0;
+ } else {
+ var idxNeighbour = that.dom.resizeColNeighbour[0].cellIndex;
+ }
+
+
+
+ if (idx === undefined) {
+ return;
+ }
+
+ this.s.mouse.targetIndex = idx;
+ this.s.mouse.targetColumn = this.s.dt.aoColumns[ idx ];
+
+ this.s.mouse.neighbourIndex = idxNeighbour;
+ this.s.mouse.neighbourColumn = this.s.dt.aoColumns[ idxNeighbour ];
+
+ /* Add event handlers to the document */
+ $(document)
+ .off('mousemove.ColResize').on('mousemove.ColResize', function (e) {
+ that._fnMouseMove.call(that, e);
+ })
+ .off('mouseup.ColResize').on('mouseup.ColResize', function (e) {
+ that._fnMouseUp.call(that, e);
+ });
+ },
+
+ /**
+ * Deal with a mouse move event while dragging to resize a column
+ * @method _fnMouseMove
+ * @param e Mouse event
+ * @returns void
+ * @private
+ */
+ "_fnMouseMove": function (e) {
+ var that = this;
+
+ var offset = $(that.s.mouse.targetColumn.nTh).offset();
+ var relativeX = (e.pageX - offset.left);
+ var distFromLeft = relativeX;
+ var distFromRight = $(that.s.mouse.targetColumn.nTh).outerWidth() - relativeX - 1;
+
+ //Change in mouse x position
+ var dx = e.pageX - that.s.mouse.startX;
+ //Get the minimum width of the column (default minimum 10px)
+ var minColumnWidth = Math.max(parseInt($(that.s.mouse.targetColumn.nTh).css('min-width')), 10);
+ //Store the previous width of the column
+ var prevWidth = $(that.s.mouse.targetColumn.nTh).width();
+ //As long as the cursor is past the handle, resize the columns
+ if ((dx > 0 && distFromRight <= 0) || (dx < 0 && distFromRight >= 0)) {
+ if (!that.s.init.tableWidthFixed) {
+ //As long as the width is larger than the minimum
+ var newColWidth = Math.max(minColumnWidth, prevWidth + dx);
+ //Get the width difference (take into account the columns minimum width)
+ var widthDiff = newColWidth - prevWidth;
+ var colResizeIdx = parseInt(that.dom.resizeCol.attr("data-column-index"));
+ //Set datatable column widths
+ that.s.mouse.targetColumn.sWidthOrig = that.s.mouse.targetColumn.sWidth = that.s.mouse.targetColumn.width = newColWidth + "px";
+ var domCols = $(that.s.dt.nTableWrapper).find("th[data-column-index='"+colResizeIdx+"']");
+ //For each table expand the width by the same amount as the column
+ //This accounts for other datatable plugins like FixedColumns
+ domCols.parents("table").each(function() {
+ if(!$(this).parent().hasClass("DTFC_LeftBodyLiner")) {
+ var newWidth = $(this).width() + widthDiff;
+ $(this).width(newWidth);
+ } else {
+ var newWidth =$(that.s.dt.nTableWrapper).find(".DTFC_LeftHeadWrapper").children("table").width();
+ $(this).parents(".DTFC_LeftWrapper").width(newWidth);
+ $(this).parent().width(newWidth+15);
+ $(this).width(newWidth);
+ }
+ });
+ //Apply the new width to the columns after the table has been resized
+ domCols.width(that.s.mouse.targetColumn.width);
+ } else {
+ //A neighbour column must exist in order to resize a column in a table with a fixed width
+ if (that.s.mouse.neighbourColumn) {
+ //Get the minimum width of the neighbor column (default minimum 10px)
+ var minColumnNeighbourWidth = Math.max(parseInt($(that.s.mouse.neighbourColumn.nTh).css('min-width')), 10);
+ //Store the previous width of the neighbour column
+ var prevNeighbourWidth = $(that.s.mouse.neighbourColumn.nTh).width();
+ //As long as the width is larger than the minimum
+ var newColWidth = Math.max(minColumnWidth, prevWidth + dx);
+ var newColNeighbourWidth = Math.max(minColumnNeighbourWidth, prevNeighbourWidth - dx);
+ //Get the width difference (take into account the columns minimum width)
+ var widthDiff = newColWidth - prevWidth;
+ var widthDiffNeighbour = newColNeighbourWidth - prevNeighbourWidth;
+ //Get the column index for the column being changed
+ var colResizeIdx = parseInt(that.dom.resizeCol.attr("data-column-index"));
+ var neighbourColResizeIdx = parseInt(that.dom.resizeColNeighbour.attr("data-column-index"));
+ //Set datatable column widths
+ that.s.mouse.neighbourColumn.sWidthOrig = that.s.mouse.neighbourColumn.sWidth = that.s.mouse.neighbourColumn.width = newColNeighbourWidth + "px";
+ that.s.mouse.targetColumn.sWidthOrig = that.s.mouse.targetColumn.sWidth = that.s.mouse.targetColumn.width = newColWidth + "px";
+ //Get list of columns based on column index in all affected tables tables. This accounts for other plugins like FixedColumns
+ var domNeighbourCols = $(that.s.dt.nTableWrapper).find("th[data-column-index='" + neighbourColResizeIdx + "']");
+ var domCols = $(that.s.dt.nTableWrapper).find("th[data-column-index='" + colResizeIdx + "']");
+ //If dx if positive (the width is getting larger) shrink the neighbour columns first
+ if(dx>0) {
+ domNeighbourCols.width(that.s.mouse.neighbourColumn.width);
+ domCols.width(that.s.mouse.targetColumn.width);
+ } else {
+ //Apply the new width to the columns then to the neighbour columns
+ domCols.width(that.s.mouse.targetColumn.width);
+ domNeighbourCols.width(that.s.mouse.neighbourColumn.width);
+ }
+ }
+ }
+ }
+ that.s.mouse.startX = e.pageX;
+ },
+
+ /**
+ * Check to see if the mouse is over the resize handle area
+ * @param e
+ * @param nTh
+ */
+ "_fnResizeHandleCheck": function (e, nTh) {
+ var that = this;
+
+ var offset = $(nTh).offset();
+ var relativeX = (e.pageX - offset.left);
+ var relativeY = (e.pageY - offset.top);
+ var distFromLeft = relativeX;
+ var distFromRight = $(nTh).outerWidth() - relativeX - 1;
+
+ var handleBuffer = this.s.init.handleWidth / 2;
+ var leftHandleOn = distFromLeft < handleBuffer;
+ var rightHandleOn = distFromRight < handleBuffer;
+
+ //If this is the first table cell
+ if ($(nTh).prev("th").length == 0) {
+ if(this.s.init.rtl)
+ rightHandleOn = false;
+ else
+ leftHandleOn = false;
+ }
+ //If this is the last cell and the table is fixed width don't let them expand the last cell directly
+ if ($(nTh).next("th").length == 0 && this.s.init.tableWidthFixed) {
+ if(this.s.init.rtl)
+ leftHandleOn = false;
+ else
+ rightHandleOn = false;
+ }
+
+ var resizeAvailable = leftHandleOn||rightHandleOn;
+
+ //If table is in right to left mode flip which TH is being resized
+ if (that.s.init.rtl) {
+ //Handle is to the left
+ if (leftHandleOn) {
+ that.dom.resizeCol = $(nTh);
+ that.dom.resizeColNeighbour = $(nTh).next();
+ } else if (rightHandleOn) {
+ that.dom.resizeCol = $(nTh).prev();
+ that.dom.resizeColNeighbour = $(nTh);
+ }
+ } else {
+ //Handle is to the right
+ if (rightHandleOn) {
+ that.dom.resizeCol = $(nTh);
+ that.dom.resizeColNeighbour = $(nTh).next();
+ } else if (leftHandleOn) {
+ that.dom.resizeCol = $(nTh).prev();
+ that.dom.resizeColNeighbour = $(nTh);
+ }
+ }
+
+ //If table width is fixed make sure both columns are resizable else just check the one.
+ if(this.s.init.tableWidthFixed)
+ resizeAvailable &= this.s.init.exclude.indexOf(parseInt($(that.dom.resizeCol).attr("data-column-index"))) == -1 && this.s.init.exclude.indexOf(parseInt($(that.dom.resizeColNeighbour).attr("data-column-index"))) == -1;
+ else
+ resizeAvailable &= this.s.init.exclude.indexOf(parseInt($(that.dom.resizeCol).attr("data-column-index"))) == -1;
+
+ $(nTh).off('mousedown.ColResize');
+ if (resizeAvailable) {
+ $(nTh).css("cursor", "ew-resize");
+
+ //Delay other mousedown events from the Reorder plugin
+ that._fnDelayEvents(null, nTh, "mousedown", "ColReorder");
+ that._fnDelayEvents("click", nTh, "click", "DT");
+
+ $(nTh).off('mousedown.ColResize').on('mousedown.ColResize', function (e) {
+ e.preventDefault();
+ that._fnMouseDown.call(that, e, nTh);
+ })
+ .off('click.ColResize').on('click.ColResize', function (e) {
+ that._fnClick.call(that, e);
+ });
+ } else {
+ $(nTh).css("cursor", "pointer");
+ $(nTh).off('mousedown.ColResize click.ColResize');
+ //Restore any events that were removed
+ that._fnRestoreEvents();
+ //This is to restore column sorting on click functionality
+ if (!that.s.isMousedown)
+ //Restore click event if mouse is not down
+ this._fnRestoreEvents("click");
+ }
+ },
+
+ "_fnClick": function (e) {
+ var that = this;
+ that.s.isMousedown = false;
+ e.stopImmediatePropagation();
+ },
+
+ /**
+ * Finish off the mouse drag
+ * @method _fnMouseUp
+ * @param e Mouse event
+ * @returns void
+ * @private
+ */
+ "_fnMouseUp": function (e) {
+ var that = this;
+ that.s.isMousedown = false;
+
+ //Fix width of column to be the size the dom is limited to (for when user sets min-width on a column)
+ that.s.mouse.targetColumn.width = that.dom.resizeCol.width();
+
+ $(document).off('mousemove.ColResize mouseup.ColResize');
+ this.s.dt.oInstance.fnAdjustColumnSizing();
+ //Table width fix, prevents extra gaps between tables
+ var LeftWrapper = $(that.s.dt.nTableWrapper).find(".DTFC_LeftWrapper");
+ var DTFC_LeftWidth = LeftWrapper.width();
+ LeftWrapper.children(".DTFC_LeftHeadWrapper").children("table").width(DTFC_LeftWidth);
+
+ if (that.s.init.resizeCallback) {
+ that.s.init.resizeCallback.call(that, that.s.mouse.targetColumn);
+ }
+ },
+
+ /**
+ * Clean up ColResize memory references and event handlers
+ * @method _fnDestroy
+ * @returns void
+ * @private
+ */
+ "_fnDestroy": function () {
+ var i, iLen;
+
+ for (i = 0, iLen = this.s.dt.aoDrawCallback.length; i < iLen; i++) {
+ if (this.s.dt.aoDrawCallback[i].sName === 'ColResize_Pre') {
+ this.s.dt.aoDrawCallback.splice(i, 1);
+ break;
+ }
+ }
+
+ $(this.s.dt.nTHead).find('*').off('.ColResize');
+
+ $.each(this.s.dt.aoColumns, function (i, column) {
+ $(column.nTh).removeAttr('data-column-index');
+ });
+
+ this.s.dt._colResize = null;
+ this.s = null;
+ },
+
+
+ /**
+ * Add a data attribute to the column headers, so we know the index of
+ * the row to be reordered. This allows fast detection of the index, and
+ * for this plug-in to work with FixedHeader which clones the nodes.
+ * @private
+ */
+ "_fnSetColumnIndexes": function () {
+ $.each(this.s.dt.aoColumns, function (i, column) {
+ $(column.nTh).attr('data-column-index', i);
+ });
+ }
+ };
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Static parameters
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+
+ /**
+ * ColResize default settings for initialisation
+ * @namespace
+ * @static
+ */
+ ColResize.defaults = {
+ /**
+ * Callback function that is fired when columns are resized
+ * @type function():void
+ * @default null
+ * @static
+ */
+ "resizeCallback": null,
+
+ /**
+ * Exclude array for columns that are not resizable
+ * @property exclude
+ * @type array of indexes that are excluded from resizing
+ * @default []
+ */
+ "exclude": [],
+
+ /**
+ * Check to see if user is using a fixed table width or dynamic
+ * if true:
+ * -Columns will resize themselves and their neighbour
+ * -If neighbour is excluded resize will not occur
+ * if false:
+ * -Columns will resize themselves and increase or decrease the width of the table accordingly
+ */
+ "tableWidthFixed": true,
+
+ /**
+ * Width of the resize handle in pixels
+ * @property handleWidth
+ * @type int (pixels)
+ * @default 10
+ */
+ "handleWidth": 10,
+
+ /**
+ * Right to left support, when true flips which column they are resizing on mouse down
+ * @property rtl
+ * @type bool
+ * @default false
+ */
+ "rtl": false
+ };
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Constants
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+ /**
+ * ColResize version
+ * @constant version
+ * @type String
+ * @default As code
+ */
+ ColResize.version = "0.0.10";
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * DataTables interfaces
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+ // Expose
+ $.fn.dataTable.ColResize = ColResize;
+ $.fn.DataTable.ColResize = ColResize;
+
+
+ // Register a new feature with DataTables
+ if (typeof $.fn.dataTable == "function" &&
+ typeof $.fn.dataTableExt.fnVersionCheck == "function" &&
+ $.fn.dataTableExt.fnVersionCheck('1.9.3')) {
+ $.fn.dataTableExt.aoFeatures.push({
+ "fnInit": function (settings) {
+ var table = settings.oInstance;
+
+ if (!settings._colResize) {
+ var dtInit = settings.oInit;
+ var opts = dtInit.colResize || dtInit.oColResize || {};
+
+ new ColResize(settings, opts);
+ }
+ else {
+ table.oApi._fnLog(settings, 1, "ColResize attempted to initialise twice. Ignoring second");
+ }
+
+ return null;
+ /* No node for DataTables to insert */
+ },
+ "cFeature": "Z",
+ "sFeature": "ColResize"
+ });
+ } else {
+ alert("Warning: ColResize requires DataTables 1.9.3 or greater - www.datatables.net/download");
+ }
+
+
+// API augmentation
+ if ($.fn.dataTable.Api) {
+ $.fn.dataTable.Api.register('colResize.reset()', function () {
+ return this.iterator('table', function (ctx) {
+ ctx._colResize.fnReset();
+ });
+ });
+ }
+
+ return ColResize;
+ }; // /factory
+
+
+// Define as an AMD module if possible
+if ( typeof define === 'function' && define.amd ) {
+ define( ['jquery', 'datatables'], factory );
+}
+else if ( typeof exports === 'object' ) {
+ // Node/CommonJS
+ factory( require('jquery'), require('datatables') );
+}
+else if (jQuery && !jQuery.fn.dataTable.ColResize) {
+ // Otherwise simply initialise as normal, stopping multiple evaluation
+ factory(jQuery, jQuery.fn.dataTable);
+}
+
+
+})(window, document); \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.colResize2.js b/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.colResize2.js
new file mode 100644
index 00000000..6ef9907a
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.colResize2.js
@@ -0,0 +1,943 @@
+var dt;
+(function (dt) {
+ var ColResize = (function () {
+ function ColResize($, api, settings) {
+ this.$ = $;
+ this.tableSize = -1;
+ this.initialized = false;
+ this.dt = {};
+ this.dom = {
+ fixedLayout: false,
+ fixedHeader: null,
+ winResizeTimer: null,
+ mouse: {
+ startX: -1,
+ startWidth: null
+ },
+ table: {
+ prevWidth: null
+ },
+ origState: true,
+ resize: false,
+ scrollHead: null,
+ scrollHeadTable: null,
+ scrollFoot: null,
+ scrollFootTable: null,
+ scrollFootInner: null,
+ scrollBody: null,
+ scrollBodyTable: null,
+ scrollX: false,
+ scrollY: false
+ };
+ this.settings = this.$.extend(true, {}, dt.ColResize.defaultSettings, settings);
+ this.dt.settings = api.settings()[0];
+ this.dt.api = api;
+ this.dt.settings.colResize = this;
+ this.registerCallbacks();
+ }
+ ColResize.prototype.initialize = function () {
+ var _this = this;
+ this.$.each(this.dt.settings.aoColumns, function (i, col) {
+ return _this.setupColumn(col);
+ });
+
+ //Initialize fixedHeader if specified
+ if (this.settings.fixedHeader)
+ this.setupFixedHeader();
+
+ //Save scroll head and body if found
+ this.dom.scrollHead = this.$('div.' + this.dt.settings.oClasses.sScrollHead, this.dt.settings.nTableWrapper);
+ this.dom.scrollHeadInner = this.$('div.' + this.dt.settings.oClasses.sScrollHeadInner, this.dom.scrollHead);
+ this.dom.scrollHeadTable = this.$('div.' + this.dt.settings.oClasses.sScrollHeadInner + ' > table', this.dom.scrollHead);
+
+ this.dom.scrollFoot = this.$('div.' + this.dt.settings.oClasses.sScrollFoot, this.dt.settings.nTableWrapper);
+ this.dom.scrollFootInner = this.$('div.' + this.dt.settings.oClasses.sScrollFootInner, this.dom.scrollFoot);
+ this.dom.scrollFootTable = this.$('div.' + this.dt.settings.oClasses.sScrollFootInner + ' > table', this.dom.scrollFoot);
+
+ this.dom.scrollBody = this.$('div.' + this.dt.settings.oClasses.sScrollBody, this.dt.settings.nTableWrapper);
+ this.dom.scrollBodyTable = this.$('> table', this.dom.scrollBody);
+ this.dt.api.on('draw.dt', this.onDraw.bind(this));
+ if (this.dom.scrollFootTable) {
+ this.dt.api.on('colPinFcDraw.dt', function (e, colPin, data) {
+ if (data.leftClone.header)
+ _this.$('tfoot', data.leftClone.header).remove();
+ if (data.leftClone.footer)
+ _this.$('thead', data.leftClone.footer).remove();
+ if (data.rightClone.header)
+ _this.$('tfoot', data.rightClone.header).remove();
+ if (data.rightClone.footer)
+ _this.$('thead', data.rightClone.footer).remove();
+ });
+ }
+
+ this.dom.scrollX = this.dt.settings.oInit.sScrollX === undefined ? false : true;
+ this.dom.scrollY = this.dt.settings.oInit.sScrollY === undefined ? false : true;
+
+ //SaveTableWidth
+ this.dt.settings.sTableWidthOrig = this.$(this.dt.settings.nTable).width();
+ this.updateTableSize();
+
+ this.dt.settings.oFeatures.bAutoWidthOrig = this.dt.settings.oFeatures.bAutoWidth;
+ this.dt.settings.oFeatures.bAutoWidth = false;
+
+ if (this.dt.settings.oInit.bStateSave && this.dt.settings.oLoadedState) {
+ this.loadState(this.dt.settings.oLoadedState);
+ }
+
+ this.onDraw();
+ this.dom.table.preWidth = parseFloat(this.dom.scrollBodyTable.css('width'));
+
+ if (!this.dom.scrollX && this.dom.scrollY && this.settings.fixedLayout && this.dt.settings._reszEvt) {
+ //We have to manually resize columns on window resize
+ var eventName = 'resize.DT-' + this.dt.settings.sInstance;
+ this.$(window).off(eventName);
+ this.$(window).on(eventName, function () {
+ _this.proportionallyColumnSizing();
+ //api._fnAdjustColumnSizing(this.dt.settings);
+ });
+ }
+
+ if (this.dom.scrollX || this.dom.scrollY) {
+ this.dt.api.on('column-sizing.dt', this.fixFootAndHeadTables.bind(this));
+ this.dt.api.on('column-visibility.dt', this.fixFootAndHeadTables.bind(this));
+ }
+
+ this.initialized = true;
+ this.dt.settings.oApi._fnCallbackFire(this.dt.settings, 'colResizeInitCompleted', 'colResizeInitCompleted', [this]);
+ };
+
+ ColResize.prototype.setupColumn = function (col) {
+ var _this = this;
+ var $th = this.$(col.nTh);
+ if (col.resizable === false)
+ return;
+
+ // listen to mousemove event for resize
+ $th.on('mousemove.ColResize', function (e) {
+ if (_this.dom.resize || col.resizable === false)
+ return;
+
+ /* Store information about the mouse position */
+ var $thTarget = e.target.nodeName.toUpperCase() == 'TH' ? _this.$(e.target) : _this.$(e.target).closest('TH');
+ var offset = $thTarget.offset();
+ var nLength = $thTarget.innerWidth();
+
+ /* are we on the col border (if so, resize col) */
+ if (Math.abs(e.pageX - Math.round(offset.left + nLength)) <= 5) {
+ $thTarget.css({ 'cursor': 'col-resize' });
+ } else
+ $thTarget.css({ 'cursor': 'pointer' });
+ });
+
+ //Save the original width
+ col._ColResize_sWidthOrig = col.sWidthOrig;
+ col.initWidth = $th.width();
+ col.minWidthOrig = col.minWidth;
+
+ $th.on('dblclick.ColResize', function (e) {
+ _this.onDblClick(e, $th, col);
+ });
+
+ $th.off('mousedown.ColReorder');
+
+ // listen to mousedown event
+ $th.on('mousedown.ColResize', function (e) {
+ return _this.onMouseDown(e, col);
+ });
+ };
+
+ ColResize.prototype.setupFixedHeader = function () {
+ var fhSettings = this.settings.fixedHeader === true ? undefined : this.settings.fixedHeader;
+
+ //If left or right option was set to true disable resizing for the first or last column
+ if (this.$.isPlainObject(fhSettings)) {
+ var columns = this.dt.settings.aoColumns;
+ if (fhSettings.left === true)
+ columns[0].resizable = false;
+ if (fhSettings.right === true)
+ columns[columns.length - 1].resizable = false;
+ }
+
+ this.dom.fixedHeader = new this.$.fn.dataTable.FixedHeader(this.dt.api, fhSettings);
+ var origUpdateClones = this.dom.fixedHeader._fnUpdateClones;
+ var that = this;
+
+ //FixeHeader doesn't have any callback after updating the clones so we have to wrap the orig function
+ this.dom.fixedHeader._fnUpdateClones = function () {
+ origUpdateClones.apply(this, arguments);
+ that.memorizeFixedHeaderNodes();
+ };
+
+ //As we missed the first call of _fnUpdateClones we have to call memorizeFixedHeaderNodes function manually
+ this.memorizeFixedHeaderNodes();
+ };
+
+ ColResize.prototype.memorizeFixedHeaderNodes = function () {
+ var _this = this;
+ var fhSettings = this.dom.fixedHeader.fnGetSettings();
+ var fhCache = fhSettings.aoCache;
+ var i, col;
+ for (i = 0; i < fhCache.length; i++) {
+ var type = fhCache[i].sType;
+ var propName;
+ var selector;
+ switch (type) {
+ case 'fixedHeader':
+ propName = 'fhTh';
+ selector = 'thead>tr>th';
+ this.dt.settings.fhTHead = fhCache[i].nNode;
+ break;
+ case 'fixedFooter':
+ propName = 'fhTf';
+ selector = 'thead>tr>th';
+
+ //prepend a cloned thead to the floating footer table so that resizing will work correctly
+ var tfoot = this.$(fhCache[i].nNode);
+ var thead = this.$(this.dt.settings.nTHead).clone().css({ height: 0, visibility: 'hidden' });
+ this.$('tr', thead).css('height', 0);
+ this.$('tr>th', thead).css({
+ 'height': 0,
+ 'padding-bottom': 0,
+ 'padding-top': 0,
+ 'border-bottom-width': 0,
+ 'border-top-width': 0,
+ 'line-height': 0
+ });
+ tfoot.prepend(thead);
+ this.$('tfoot>tr>th', tfoot).css('width', '');
+ this.dt.settings.fhTFoot = fhCache[i].nNode;
+ break;
+ default:
+ continue;
+ }
+
+ this.$(selector, fhCache[i].nNode).each(function (j, th) {
+ col = _this.getVisibleColumn(j);
+ col[propName] = th;
+ });
+ }
+ };
+
+ //zero based index
+ ColResize.prototype.getVisibleColumn = function (idx) {
+ var columns = this.dt.settings.aoColumns;
+ var currVisColIdx = -1;
+ for (var i = 0; i < columns.length; i++) {
+ if (!columns[i].bVisible)
+ continue;
+ currVisColIdx++;
+ if (currVisColIdx == idx)
+ return columns[i];
+ }
+ return null;
+ };
+
+ ColResize.prototype.updateTableSize = function () {
+ if (this.dom.scrollX && this.dom.scrollHeadTable.length)
+ this.tableSize = this.dom.scrollHeadTable.width();
+ else
+ this.tableSize = -1;
+ };
+
+ ColResize.prototype.proportionallyColumnSizing = function () {
+ var _this = this;
+ var prevWidths = [], newWidths = [], prevWidth, newWidth, newTableWidth, prevTableWidth, moveLength, multiplier, cWidth, i, j, delay = 500, prevTotalColWidths = 0, currTotalColWidths, columnRestWidths = [], columns = this.dt.settings.aoColumns, bodyTableColumns = this.$('thead th', this.dom.scrollBodyTable), headTableColumns = this.$('thead th', this.dom.scrollHeadTable), footTableColumns = this.dom.scrollFootTable.length ? this.$('thead th', this.dom.scrollFootTable) : [], visColumns = [];
+
+ for (i = 0; i < columns.length; i++) {
+ if (!columns[i].bVisible)
+ continue;
+ visColumns.push(columns[i]);
+ columnRestWidths.push(0); //set default value
+ }
+
+ for (i = 0; i < bodyTableColumns.length; i++) {
+ cWidth = parseFloat(bodyTableColumns[i].style.width);
+ prevTotalColWidths += cWidth;
+ prevWidths.push(cWidth);
+ }
+
+ for (i = 0; i < bodyTableColumns.length; i++) {
+ bodyTableColumns[i].style.width = '';
+ }
+
+ //Get the new table width calculated by the browser
+ newTableWidth = parseFloat(this.dom.scrollBodyTable.css('width'));
+
+ //Get the old table width
+ prevTableWidth = this.dom.table.preWidth;
+ moveLength = newTableWidth - prevTableWidth;
+ if (moveLength == 0) {
+ for (i = 0; i < bodyTableColumns.length; i++) {
+ bodyTableColumns[i].style.width = prevWidths[i] + 'px';
+ }
+ return;
+ }
+
+ //var tot = 0;
+ currTotalColWidths = prevTotalColWidths;
+ for (i = 0; i < visColumns.length; i++) {
+ //For each column calculate the new width
+ prevWidth = prevWidths[i];
+ multiplier = (+(prevWidth / prevTotalColWidths).toFixed(2));
+
+ //tot += multiplier;
+ newWidth = prevWidth + (moveLength * multiplier) + columnRestWidths[i];
+ currTotalColWidths -= prevWidth;
+
+ //Check whether the column can be resized to the new calculated value
+ //if not, set it to the min or max width depends on the moveLength value
+ if (!this.canResizeColumn(visColumns[i], newWidth)) {
+ cWidth = moveLength > 0 ? this.getColumnMaxWidth(visColumns[i]) : this.getColumnMinWidth(visColumns[i]);
+ var rest = newWidth - cWidth;
+ newWidth = cWidth;
+
+ for (j = (i + 1); j < visColumns.length; j++) {
+ columnRestWidths[j] += rest * (+(visColumns[j] / currTotalColWidths).toFixed(2));
+ }
+ }
+ newWidths.push(newWidth);
+ }
+
+ //Apply the calculated column widths to the headers cells
+ var tablesWidth = this.dom.scrollBodyTable.outerWidth() + 'px';
+ for (i = 0; i < headTableColumns.length; i++) {
+ headTableColumns[i].style.width = newWidths[i] + 'px';
+ }
+ this.dom.scrollHeadTable.css('width', tablesWidth);
+ this.dom.scrollHeadInner.css('width', tablesWidth);
+
+ for (i = 0; i < bodyTableColumns.length; i++) {
+ bodyTableColumns[i].style.width = newWidths[i] + 'px';
+ }
+
+ if (this.dom.scrollFootTable.length) {
+ for (i = 0; i < footTableColumns.length; i++) {
+ footTableColumns[i].style.width = newWidths[i] + 'px';
+ }
+ this.dom.scrollFootTable[0].style.width = tablesWidth;
+ this.dom.scrollFootInner[0].style.width = tablesWidth;
+ }
+
+ //console.log('moveLength: ' + moveLength + ' multiplier: ' + tot);
+ //console.log(newWidths);
+ this.dom.table.preWidth = newTableWidth;
+
+ //Call afterResizing function after the window stops resizing
+ if (this.dom.winResizeTimer)
+ clearTimeout(this.dom.winResizeTimer);
+ this.dom.winResizeTimer = setTimeout(function () {
+ _this.afterResizing();
+ _this.dom.winResizeTimer = null;
+ }, delay);
+ };
+
+ ColResize.prototype.getColumnIndex = function (col) {
+ //Get the current column position
+ var colIdx = -1;
+ for (var i = 0; i < this.dt.settings.aoColumns.length; i++) {
+ if (this.dt.settings.aoColumns[i] === col) {
+ colIdx = i;
+ break;
+ }
+ }
+ return colIdx;
+ };
+
+ ColResize.prototype.getColumnEvent = function (th, type, ns) {
+ var event;
+ var thEvents = this.$._data(th, "events");
+ this.$.each(thEvents[type] || [], function (idx, handler) {
+ if (handler.namespace === ns)
+ event = handler;
+ });
+ return event;
+ };
+
+ ColResize.prototype.loadState = function (data) {
+ var _this = this;
+ var i, col;
+
+ var onInit = function () {
+ if (_this.settings.fixedLayout) {
+ _this.setTablesLayout('fixed');
+ } else {
+ _this.setTablesLayout('auto');
+ }
+ if (!data.colResize) {
+ if (_this.dt.settings.oFeatures.bAutoWidthOrig)
+ _this.dt.settings.oFeatures.bAutoWidth = true;
+ else if (_this.dt.settings.sTableWidthOrig)
+ _this.$(_this.dt.settings.nTable).width(_this.dt.settings.sTableWidthOrig);
+
+ for (i = 0; i < _this.dt.settings.aoColumns.length; i++) {
+ col = _this.dt.settings.aoColumns[i];
+ if (col._ColResize_sWidthOrig) {
+ col.sWidthOrig = col._ColResize_sWidthOrig;
+ }
+ }
+ _this.dom.origState = true;
+ } else {
+ var columns = data.colResize.columns || [];
+ var wMap = {};
+
+ if (_this.dt.settings.oFeatures.bAutoWidth) {
+ _this.dt.settings.oFeatures.bAutoWidth = false;
+ }
+
+ if (_this.dom.scrollX && data.colResize.tableSize > 0) {
+ _this.dom.scrollHeadTable.width(data.colResize.tableSize);
+ _this.dom.scrollHeadInner.width(data.colResize.tableSize);
+ _this.dom.scrollBodyTable.width(data.colResize.tableSize);
+ _this.dom.scrollFootTable.width(data.colResize.tableSize);
+ }
+
+ for (i = 0; i < columns.length; i++) {
+ wMap[i] = columns[i];
+ }
+ for (i = 0; i < _this.dt.settings.aoColumns.length; i++) {
+ col = _this.dt.settings.aoColumns[i];
+ var idx = col._ColReorder_iOrigCol != null ? col._ColReorder_iOrigCol : i;
+ col.sWidth = wMap[idx];
+ col.sWidthOrig = wMap[idx];
+ col.nTh.style.width = columns[i];
+
+ //Check for FixedHeader
+ if (col.fhTh)
+ col.fhTh.style.width = columns[i];
+ if (col.fhTf)
+ col.fhTf.style.width = columns[i];
+ }
+ _this.dom.origState = false;
+ }
+
+ _this.dt.api.columns.adjust();
+ if (_this.dom.scrollX || _this.dom.scrollY)
+ _this.dt.api.draw(false);
+ };
+
+ if (this.initialized) {
+ onInit();
+ return;
+ }
+ this.dt.settings.oApi._fnCallbackReg(this.dt.settings, 'colResizeInitCompleted', function () {
+ onInit();
+ }, "ColResize_Init");
+ };
+
+ ColResize.prototype.saveState = function (data) {
+ if (!this.dt.settings._bInitComplete) {
+ var oData = this.dt.settings.fnStateLoadCallback.call(this.dt.settings.oInstance, this.dt.settings);
+ if (oData && oData.colResize)
+ data.colResize = oData.colResize;
+ return;
+ }
+ this.updateTableSize();
+ data.colResize = {
+ columns: [],
+ tableSize: this.tableSize
+ };
+
+ data.colResize.columns.length = this.dt.settings.aoColumns.length;
+ for (var i = 0; i < this.dt.settings.aoColumns.length; i++) {
+ var col = this.dt.settings.aoColumns[i];
+ var idx = col._ColReorder_iOrigCol != null ? col._ColReorder_iOrigCol : i;
+ data.colResize.columns[idx] = col.sWidth;
+ }
+ };
+
+ ColResize.prototype.registerCallbacks = function () {
+ var _this = this;
+ /* State saving */
+ this.dt.settings.oApi._fnCallbackReg(this.dt.settings, 'aoStateSaveParams', function (oS, oData) {
+ _this.saveState(oData);
+ }, "ColResize_StateSave");
+
+ /* State loading */
+ this.dt.settings.oApi._fnCallbackReg(this.dt.settings, 'aoStateLoaded', function (oS, oData) {
+ _this.loadState(oData);
+ }, "ColResize_StateLoad");
+
+ if (this.$.fn.DataTable.models.oSettings.remoteStateInitCompleted !== undefined) {
+ //Integrate with remote state
+ this.dt.settings.oApi._fnCallbackReg(this.dt.settings, 'remoteStateLoadedParams', function (s, data) {
+ _this.loadState(data);
+ }, "ColResize_StateLoad");
+ this.dt.settings.oApi._fnCallbackReg(this.dt.settings, 'remoteStateSaveParams', function (s, data) {
+ _this.saveState(data);
+ }, "ColResize_StateSave");
+ }
+ };
+
+ ColResize.prototype.setTablesLayout = function (value) {
+ if (this.dom.scrollX || this.dom.scrollY) {
+ this.dom.scrollHeadTable.css('table-layout', value);
+ this.dom.scrollBodyTable.css('table-layout', value);
+ this.dom.scrollFootTable.css('table-layout', value);
+ } else {
+ this.$(this.dt.settings.nTable).css('table-layout', value);
+ }
+ this.dom.fixedLayout = value == 'fixed';
+ };
+
+ //only when scrollX or scrollY are enabled
+ ColResize.prototype.fixFootAndHeadTables = function (e) {
+ var _this = this;
+ if (e != null && e.target !== this.dt.settings.nTable)
+ return;
+
+ if (this.dom.scrollFootTable.length) {
+ this.$('thead', this.dom.scrollFootTable).remove();
+ this.dom.scrollFootTable.prepend(this.$('thead', this.dom.scrollBodyTable).clone());
+ }
+ this.$('tfoot', this.dom.scrollHeadTable).remove();
+ this.dom.scrollHeadTable.append(this.$('tfoot', this.dom.scrollBodyTable).clone());
+ var removeFooterWidth = function (table) {
+ _this.$('tfoot>tr>th', table).each(function (i, th) {
+ _this.$(th).css('width', '');
+ });
+ };
+
+ //Remove all tfoot headers widths
+ removeFooterWidth(this.dom.scrollFootTable);
+ removeFooterWidth(this.dom.scrollBodyTable);
+ removeFooterWidth(this.dom.scrollHeadTable);
+ };
+
+ ColResize.prototype.onDraw = function (e) {
+ if (e != null && e.target !== this.dt.settings.nTable)
+ return;
+ if (this.dom.scrollX || this.dom.scrollY) {
+ this.fixFootAndHeadTables();
+
+ //Fix the header table padding
+ if (this.dt.settings._bInitComplete) {
+ var borderWidth = this.dom.scrollHeadTable.outerWidth() - this.dom.scrollHeadTable.innerWidth();
+ var paddingType = this.dt.settings.oBrowser.bScrollbarLeft ? 'padding-left' : 'padding-right';
+ var paddingVal = parseFloat(this.dom.scrollHeadInner.css(paddingType));
+ this.dom.scrollHeadInner.css(paddingType, (paddingVal + borderWidth) + 'px');
+ }
+ }
+
+ var autoWidthTypes = [];
+ if (this.settings.dblClick == 'autoMinFit' || !this.settings.fixedLayout)
+ autoWidthTypes.push('autoMinWidth');
+ if (this.settings.dblClick == 'autoFit')
+ autoWidthTypes.push('autoWidth');
+
+ //Call this only once so that the table will be cloned only one time
+ if (autoWidthTypes.length)
+ this.updateColumnsAutoWidth(autoWidthTypes);
+
+ if (!this.settings.fixedLayout) {
+ var columns = this.dt.settings.aoColumns;
+ var i;
+ for (i = 0; i < columns.length; i++) {
+ if (!columns[i].bVisible)
+ continue;
+ columns[i].minWidth = Math.max((columns[i].minWidthOrig || 0), columns[i].autoMinWidth);
+
+ //We have to resize if the current column width if is less that the column minWidth
+ if (this.$(columns[i].nTh).width() < columns[i].minWidth)
+ this.resize(columns[i], columns[i].minWidth);
+ }
+ } else {
+ if (!this.dom.fixedLayout) {
+ this.setTablesLayout('fixed');
+ this.afterResizing();
+ }
+ }
+ };
+
+ ColResize.prototype.getTableAutoColWidths = function (table, types) {
+ var widths = {}, i, colIdx;
+ var $table = this.$(table);
+ for (i = 0; i < types.length; i++) {
+ widths[types[i]] = [];
+ }
+ if (!types.length || !$table.length)
+ return widths;
+
+ var clnTable = $table.clone().removeAttr('id').css('table-layout', 'auto');
+
+ // Remove any assigned widths from the footer (from scrolling)
+ clnTable.find('thead th, tfoot th, tfoot td').css('width', '');
+ var container = this.$('<div />').css({
+ 'position': 'absolute',
+ 'width': '9999px',
+ 'height': '9999px'
+ });
+ container.append(clnTable);
+ this.$(this.dt.settings.nTableWrapper).append(container);
+
+ var headerCols = this.$('thead>tr>th', clnTable);
+
+ for (i = 0; i < types.length; i++) {
+ var type = types[i];
+ var fn = '';
+ switch (type) {
+ case 'autoMinWidth':
+ clnTable.css('width', '1px');
+ fn = 'width';
+ break;
+ case 'autoWidth':
+ clnTable.css('width', 'auto');
+ fn = 'outerWidth';
+ break;
+ default:
+ throw 'Invalid widthType ' + type;
+ }
+ for (colIdx = 0; colIdx < headerCols.length; colIdx++) {
+ widths[type].push(this.$(headerCols[colIdx])[fn]());
+ }
+ }
+
+ container.remove();
+ return widths;
+ };
+
+ ColResize.prototype.updateColumnsAutoWidth = function (types) {
+ var columns = this.dt.settings.aoColumns;
+ var i, j, colLen, type, visColIdx = 0;
+ var widths = {};
+ if (this.dom.scrollX || this.dom.scrollY) {
+ var headWidths = this.getTableAutoColWidths(this.dom.scrollHeadTable, types);
+ var bodyWidths = this.getTableAutoColWidths(this.dom.scrollBodyTable, types);
+ var footWidths = this.getTableAutoColWidths(this.dom.scrollFootTable, types);
+
+ for (i = 0; i < types.length; i++) {
+ type = types[i];
+ widths[type] = [];
+ footWidths[type].length = headWidths[type].length;
+ colLen = headWidths[type].length;
+ for (j = 0; j < colLen; j++) {
+ widths[type].push(Math.max(headWidths[type][j], bodyWidths[type][j], (footWidths[type][j] || 0)));
+ }
+ }
+ } else {
+ widths = this.getTableAutoColWidths(this.dt.settings.nTable, types);
+ }
+
+ for (i = 0; i < columns.length; i++) {
+ if (!columns[i].bVisible)
+ continue;
+ for (j = 0; j < types.length; j++) {
+ type = types[j];
+ columns[i][type] = widths[type][visColIdx];
+ }
+ visColIdx++;
+ }
+ };
+
+ ColResize.prototype.overrideClickHander = function (col, $th) {
+ var dtClickEvent = this.getColumnEvent($th.get(0), 'click', 'DT');
+
+ //Remove the DataTables event so that ordering will not occur
+ if (dtClickEvent) {
+ $th.off('click.DT');
+ this.$(document).one('click.ColResize', function (e) {
+ $th.on('click.DT', dtClickEvent.handler);
+ });
+ }
+ };
+
+ ColResize.prototype.onDblClick = function (e, $th, col) {
+ if (e.target !== $th.get(0))
+ return;
+ if ($th.css('cursor') != 'col-resize')
+ return;
+
+ var width;
+ switch (this.settings.dblClick) {
+ case 'autoMinFit':
+ width = col.autoMinWidth;
+ break;
+ case 'autoFit':
+ width = col.autoWidth;
+ break;
+ default:
+ width = col.initWidth;
+ }
+ this.resize(col, width);
+ };
+
+ ColResize.prototype.onMouseDown = function (e, col) {
+ var _this = this;
+ if (e.target !== col.nTh && e.target !== col.fhTh)
+ return true;
+
+ var $th = e.target === col.nTh ? this.$(col.nTh) : this.$(col.fhTh);
+
+ if ($th.css('cursor') != 'col-resize' || col.resizable === false) {
+ var colReorder = this.dt.settings._colReorder;
+ if (colReorder) {
+ colReorder._fnMouseDown.call(colReorder, e, e.target); //Here we fix the e.preventDefault() in ColReorder so that we can have working inputs in header
+ }
+ return true;
+ }
+ this.dom.mouse.startX = e.pageX;
+ this.dom.mouse.prevX = e.pageX;
+ this.dom.mouse.startWidth = $th.width();
+ this.dom.resize = true;
+
+ this.beforeResizing(col);
+
+ /* Add event handlers to the document */
+ this.$(document).on('mousemove.ColResize', function (event) {
+ _this.onMouseMove(event, col);
+ });
+ this.overrideClickHander(col, $th);
+ this.$(document).one('mouseup.ColResize', function (event) {
+ _this.onMouseUp(event, col);
+ });
+
+ return false;
+ };
+
+ ColResize.prototype.resize = function (col, width) {
+ var colWidth = this.$(col.nTh).width();
+ var moveLength = width - this.$(col.nTh).width();
+ this.beforeResizing(col);
+ var resized = this.resizeColumn(col, colWidth, moveLength, moveLength);
+ this.afterResizing();
+ return resized;
+ };
+
+ ColResize.prototype.beforeResizing = function (col) {
+ //if (this.settings.fixedLayout && !this.dom.fixedLayout)
+ // this.setTablesLayout('fixed');
+ };
+
+ ColResize.prototype.afterResizing = function () {
+ var i;
+ var columns = this.dt.settings.aoColumns;
+ for (i = 0; i < columns.length; i++) {
+ if (!columns[i].bVisible)
+ continue;
+ columns[i].sWidth = this.$(columns[i].nTh).css('width');
+ }
+
+ //Update the internal storage of the table's width (in case we changed it because the user resized some column and scrollX was enabled
+ this.updateTableSize();
+
+ //Save the state
+ this.dt.settings.oInstance.oApi._fnSaveState(this.dt.settings);
+ this.dom.origState = false;
+ };
+
+ ColResize.prototype.onMouseUp = function (e, col) {
+ this.$(document).off('mousemove.ColResize');
+ if (!this.dom.resize)
+ return;
+ this.dom.resize = false;
+ this.afterResizing();
+ };
+
+ ColResize.prototype.canResizeColumn = function (col, newWidth) {
+ return (col.resizable === undefined || col.resizable) && this.settings.minWidth <= newWidth && (!col.minWidth || col.minWidth <= newWidth) && (!this.settings.maxWidth || this.settings.maxWidth >= newWidth) && (!col.maxWidth || col.maxWidth >= newWidth);
+ };
+
+ ColResize.prototype.getColumnMaxWidth = function (col) {
+ return col.maxWidth ? col.maxWidth : this.settings.maxWidth;
+ };
+
+ ColResize.prototype.getColumnMinWidth = function (col) {
+ return col.minWidth ? col.minWidth : this.settings.minWidth;
+ };
+
+ ColResize.prototype.getPrevResizableColumnIdx = function (col, moveLength) {
+ var columns = this.dt.settings.aoColumns;
+ var colIdx = ColResizeHelper.indexOf(columns, col);
+ for (var i = colIdx; i >= 0; i--) {
+ if (!columns[i].bVisible)
+ continue;
+ var newWidth = this.$(columns[i].nTh).width() + moveLength;
+ if (this.canResizeColumn(columns[i], newWidth))
+ return i;
+ }
+ return -1;
+ };
+
+ ColResize.prototype.getNextResizableColumnIdx = function (col, moveLength) {
+ var columns = this.dt.settings.aoColumns;
+ var colIdx = ColResizeHelper.indexOf(columns, col);
+ for (var i = (colIdx + 1); i < columns.length; i++) {
+ if (!columns[i].bVisible)
+ continue;
+ var newWidth = this.$(columns[i].nTh).width() - moveLength;
+ if (this.canResizeColumn(columns[i], newWidth))
+ return i;
+ }
+ return -1;
+ };
+
+ ColResize.prototype.resizeColumn = function (col, startWidth, moveLength, lastMoveLength) {
+ if (moveLength == 0 || lastMoveLength == 0 || col.resizable === false)
+ return false;
+ var i;
+ var columns = this.dt.settings.aoColumns;
+ var headCol = this.$(col.nTh);
+ var headColNext = headCol.next();
+ var colIdx = this.getColumnIndex(col);
+ var thWidth = startWidth + moveLength;
+ var thNextWidth;
+ var nextColIdx;
+
+ if (!this.dom.scrollX) {
+ if (lastMoveLength < 0) {
+ thWidth = headColNext.width() - lastMoveLength;
+ nextColIdx = this.getPrevResizableColumnIdx(col, lastMoveLength);
+ if (nextColIdx < 0)
+ return false;
+ headCol = headColNext;
+ colIdx = colIdx + 1;
+ headColNext = this.$(columns[nextColIdx].nTh);
+ thNextWidth = headColNext.width() + lastMoveLength;
+ } else {
+ thWidth = headCol.width() + lastMoveLength;
+ nextColIdx = this.getNextResizableColumnIdx(col, lastMoveLength);
+
+ //If there is no columns that can be shrinked dont resize anymore
+ if (nextColIdx < 0)
+ return false;
+ headColNext = this.$(columns[nextColIdx].nTh);
+ thNextWidth = headColNext.width() - lastMoveLength;
+
+ if ((this.settings.maxWidth && this.settings.maxWidth < thWidth) || col.maxWidth && col.maxWidth < thWidth)
+ return false;
+ }
+ if (!this.canResizeColumn(columns[nextColIdx], thNextWidth) || !this.canResizeColumn(columns[colIdx], thWidth))
+ return false;
+ headColNext.width(thNextWidth);
+
+ //If fixed header is present we have to resize the cloned column too
+ if (this.dom.fixedHeader) {
+ this.$(columns[nextColIdx].fhTh).width(thNextWidth);
+ this.$(columns[colIdx].fhTh).width(thWidth);
+
+ //If fixedfooter was enabled resize that too
+ if (columns[nextColIdx].fhTf) {
+ this.$(columns[nextColIdx].fhTf).width(thNextWidth);
+ this.$(columns[colIdx].fhTf).width(thWidth);
+ }
+ }
+ } else {
+ if (!this.canResizeColumn(col, thWidth))
+ return false;
+ var tSize = this.tableSize + moveLength + 'px';
+ this.dom.scrollHeadInner.css('width', tSize);
+ this.dom.scrollHeadTable.css('width', tSize);
+ this.dom.scrollBodyTable.css('width', tSize);
+ this.dom.scrollFootTable.css('width', tSize);
+ }
+ headCol.width(thWidth);
+
+ //scrollX or scrollY enabled
+ if (this.dom.scrollBody.length) {
+ var colDomIdx = 0;
+ for (i = 0; i < this.dt.settings.aoColumns.length && i != colIdx; i++) {
+ if (this.dt.settings.aoColumns[i].bVisible)
+ colDomIdx++;
+ }
+
+ //Get the table
+ var bodyCol = this.$('thead>tr>th:nth(' + colDomIdx + ')', this.dom.scrollBodyTable);
+ var footCol = this.$('thead>tr>th:nth(' + colDomIdx + ')', this.dom.scrollFootTable);
+
+ //This will happen only when scrollY is used without scrollX
+ if (!this.dom.scrollX) {
+ var nextColDomIdx = 0;
+ for (i = 0; i < this.dt.settings.aoColumns.length && i != nextColIdx; i++) {
+ if (this.dt.settings.aoColumns[i].bVisible)
+ nextColDomIdx++;
+ }
+ var bodyColNext = this.$('thead>tr>th:nth(' + nextColDomIdx + ')', this.dom.scrollBodyTable);
+ var footColNext = this.$('thead>tr>th:nth(' + nextColDomIdx + ')', this.dom.scrollFootTable);
+
+ bodyColNext.width(thNextWidth);
+ if (thWidth > 0)
+ bodyCol.width(thWidth);
+
+ footColNext.width(thNextWidth);
+ if (thWidth > 0)
+ footCol.width(thWidth);
+ }
+
+ //Resize the table and the column
+ if (this.dom.scrollX && thWidth > 0) {
+ bodyCol.width(thWidth);
+ footCol.width(thWidth);
+ }
+ }
+ return true;
+ };
+
+ ColResize.prototype.onMouseMove = function (e, col) {
+ var moveLength = e.pageX - this.dom.mouse.startX;
+ var lastMoveLength = e.pageX - this.dom.mouse.prevX;
+ this.resizeColumn(col, this.dom.mouse.startWidth, moveLength, lastMoveLength);
+ this.dom.mouse.prevX = e.pageX;
+ };
+
+ ColResize.prototype.destroy = function () {
+ };
+ ColResize.defaultSettings = {
+ minWidth: 1,
+ maxWidth: null,
+ fixedLayout: true,
+ fixedHeader: null,
+ dblClick: 'initWidth'
+ };
+ return ColResize;
+ })();
+ dt.ColResize = ColResize;
+
+ var ColResizeHelper = (function () {
+ function ColResizeHelper() {
+ }
+ ColResizeHelper.indexOf = function (arr, item, equalFun) {
+ if (typeof equalFun === "undefined") { equalFun = null; }
+ for (var i = 0; i < arr.length; i++) {
+ if (equalFun) {
+ if (equalFun(arr[i], item))
+ return i;
+ } else if (arr[i] === item)
+ return i;
+ }
+ return -1;
+ };
+ return ColResizeHelper;
+ })();
+ dt.ColResizeHelper = ColResizeHelper;
+})(dt || (dt = {}));
+
+(function ($, window, document, undefined) {
+ //Register events
+ $.fn.DataTable.models.oSettings.colResizeInitCompleted = [];
+
+ //Register api function
+ $.fn.DataTable.Api.register('colResize.init()', function (settings) {
+ var colResize = new dt.ColResize($, this, settings);
+ if (this.settings()[0]._bInitComplete)
+ colResize.initialize();
+ else
+ this.one('init.dt', function () {
+ colResize.initialize();
+ });
+ return null;
+ });
+
+ $.fn.DataTable.Api.register('column().resize()', function (width) {
+ var oSettings = this.settings()[0];
+ var colResize = oSettings.colResize;
+ return colResize.resize(oSettings.aoColumns[this[0][0]], width);
+ });
+
+ //Add as feature
+ $.fn.dataTable.ext.feature.push({
+ "fnInit": function (oSettings) {
+ return oSettings.oInstance.api().colResize.init(oSettings.oInit.colResize);
+ },
+ "cFeature": "J",
+ "sFeature": "ColResize"
+ });
+}(jQuery, window, document, undefined)); \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.fixedHeader.css b/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.fixedHeader.css
new file mode 100644
index 00000000..4001ab12
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.fixedHeader.css
@@ -0,0 +1,4 @@
+div.FixedHeader_Cloned th,
+div.FixedHeader_Cloned td {
+ background-color: white !important;
+}
diff --git a/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.fixedHeader.min.js b/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.fixedHeader.min.js
new file mode 100644
index 00000000..e8d19608
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/DataTables/extensions/dataTables.fixedHeader.min.js
@@ -0,0 +1,14 @@
+/*!
+ FixedHeader 3.0.0
+ ©2009-2015 SpryMedia Ltd - datatables.net/license
+*/
+(function(h,j){var g=function(e,i){var g=0,f=function(b,a){if(!(this instanceof f))throw"FixedHeader must be initialised with the 'new' keyword.";!0===a&&(a={});b=new i.Api(b);this.c=e.extend(!0,{},f.defaults,a);this.s={dt:b,position:{theadTop:0,tbodyTop:0,tfootTop:0,tfootBottom:0,width:0,left:0,tfootHeight:0,theadHeight:0,windowHeight:e(h).height(),visible:!0},headerMode:null,footerMode:null,namespace:".dtfc"+g++};this.dom={floatingHeader:null,thead:e(b.table().header()),tbody:e(b.table().body()),
+tfoot:e(b.table().footer()),header:{host:null,floating:null,placeholder:null},footer:{host:null,floating:null,placeholder:null}};this.dom.header.host=this.dom.thead.parent();this.dom.footer.host=this.dom.tfoot.parent();var c=b.settings()[0];if(c._fixedHeader)throw"FixedHeader already initialised on table "+c.nTable.id;c._fixedHeader=this;this._constructor()};f.prototype={update:function(){this._positions();this._scroll(!0)},_constructor:function(){var b=this,a=this.s.dt;e(h).on("scroll"+this.s.namespace,
+function(){b._scroll()}).on("resize"+this.s.namespace,function(){b.s.position.windowHeight=e(h).height();b._positions();b._scroll(!0)});a.on("column-reorder.dt.dtfc column-visibility.dt.dtfc",function(){b._positions();b._scroll(!0)}).on("draw.dtfc",function(){b._positions();b._scroll()});a.on("destroy.dtfc",function(){a.off(".dtfc");e(h).off(this.s.namespace)});this._positions();this._scroll()},_clone:function(b,a){var c=this.s.dt,d=this.dom[b],k="header"===b?this.dom.thead:this.dom.tfoot;!a&&d.floating?
+d.floating.removeClass("fixedHeader-floating fixedHeader-locked"):(d.floating&&(d.placeholder.remove(),d.floating.children().detach(),d.floating.remove()),d.floating=e(c.table().node().cloneNode(!1)).removeAttr("id").append(k).appendTo("body"),d.placeholder=k.clone(!1),d.host.append(d.placeholder),"footer"===b&&this._footerMatch(d.placeholder,d.floating))},_footerMatch:function(b,a){var c=function(d){var c=e(d,b).map(function(){return e(this).width()}).toArray();e(d,a).each(function(a){e(this).width(c[a])})};
+c("th");c("td")},_footerUnsize:function(){var b=this.dom.footer.floating;b&&e("th, td",b).css("width","")},_modeChange:function(b,a,c){var d=this.dom[a],e=this.s.position;"in-place"===b?(d.placeholder&&(d.placeholder.remove(),d.placeholder=null),d.host.append("header"===a?this.dom.thead:this.dom.tfoot),d.floating&&(d.floating.remove(),d.floating=null),"footer"===a&&this._footerUnsize()):"in"===b?(this._clone(a,c),d.floating.addClass("fixedHeader-floating").css("header"===a?"top":"bottom",this.c[a+
+"Offset"]).css("left",e.left+"px").css("width",e.width+"px"),"footer"===a&&d.floating.css("top","")):"below"===b?(this._clone(a,c),d.floating.addClass("fixedHeader-locked").css("top",e.tfootTop-e.theadHeight).css("left",e.left+"px").css("width",e.width+"px")):"above"===b&&(this._clone(a,c),d.floating.addClass("fixedHeader-locked").css("top",e.tbodyTop).css("left",e.left+"px").css("width",e.width+"px"));this.s[a+"Mode"]=b},_positions:function(){var b=this.s.dt.table(),a=this.s.position,c=this.dom,
+b=e(b.node()),d=b.children("thead"),f=b.children("tfoot"),c=c.tbody;a.visible=b.is(":visible");a.width=b.outerWidth();a.left=b.offset().left;a.theadTop=d.offset().top;a.tbodyTop=c.offset().top;a.theadHeight=a.tbodyTop-a.theadTop;f.length?(a.tfootTop=f.offset().top,a.tfootBottom=a.tfootTop+f.outerHeight(),a.tfootHeight=a.tfootBottom-a.tfootTop):(a.tfootTop=a.tbodyTop+c.outerHeight(),a.tfootBottom=a.tfootTop,a.tfootHeight=a.tfootTop)},_scroll:function(b){var a=e(j).scrollTop(),c=this.s.position,d;this.c.header&&
+(d=!c.visible||a<=c.theadTop-this.c.headerOffset?"in-place":a<=c.tfootTop-c.theadHeight-this.c.headerOffset?"in":"below",(b||d!==this.s.headerMode)&&this._modeChange(d,"header",b));this.c.footer&&this.dom.tfoot.length&&(a=!c.visible||a+c.windowHeight>=c.tfootBottom+this.c.footerOffset?"in-place":c.windowHeight+a>c.tbodyTop+c.tfootHeight+this.c.footerOffset?"in":"above",(b||a!==this.s.footerMode)&&this._modeChange(a,"footer",b))}};f.version="3.0.0";f.defaults={header:!0,footer:!1,headerOffset:0,footerOffset:0};
+e.fn.dataTable.FixedHeader=f;e.fn.DataTable.FixedHeader=f;e(j).on("init.dt.dtb",function(b,a){if("dt"===b.namespace){var c=a.oInit.fixedHeader||i.defaults.fixedHeader;c&&!a._buttons&&new f(a,c)}});i.Api.register("fixedHeader()",function(){});i.Api.register("fixedHeader.adjust()",function(){return this.iterator("table",function(b){(b=b._fixedHeader)&&b.update()})});return f};"function"===typeof define&&define.amd?define(["jquery","datatables"],g):"object"===typeof exports?g(require("jquery"),require("datatables")):
+jQuery&&!jQuery.fn.dataTable.FixedHeader&&g(jQuery,jQuery.fn.dataTable)})(window,document);
diff --git a/wqflask/wqflask/static/new/packages/DataTables/js/jquery.dataTables.js b/wqflask/wqflask/static/new/packages/DataTables/js/jquery.dataTables.js
index 1d8a220b..1364bafc 100755
--- a/wqflask/wqflask/static/new/packages/DataTables/js/jquery.dataTables.js
+++ b/wqflask/wqflask/static/new/packages/DataTables/js/jquery.dataTables.js
@@ -1,4942 +1,5321 @@
+/*! DataTables 1.10.7
+ * ©2008-2014 SpryMedia Ltd - datatables.net/license
+ */
+
/**
* @summary DataTables
- * @description Paginate, search and sort HTML tables
- * @version 1.9.4
+ * @description Paginate, search and order HTML tables
+ * @version 1.10.7
* @file jquery.dataTables.js
- * @author Allan Jardine (www.sprymedia.co.uk)
+ * @author SpryMedia Ltd (www.sprymedia.co.uk)
* @contact www.sprymedia.co.uk/contact
+ * @copyright Copyright 2008-2014 SpryMedia Ltd.
*
- * @copyright Copyright 2008-2012 Allan Jardine, all rights reserved.
+ * This source file is free software, available under the following license:
+ * MIT license - http://datatables.net/license
*
- * This source file is free software, under either the GPL v2 license or a
- * BSD style license, available at:
- * http://datatables.net/license_gpl2
- * http://datatables.net/license_bsd
- *
- * This source file is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * This source file is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
- *
+ *
* For details please refer to: http://www.datatables.net
*/
/*jslint evil: true, undef: true, browser: true */
-/*globals $, jQuery,define,_fnExternApiFunc,_fnInitialise,_fnInitComplete,_fnLanguageCompat,_fnAddColumn,_fnColumnOptions,_fnAddData,_fnCreateTr,_fnGatherData,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAjaxUpdate,_fnAjaxParameters,_fnAjaxUpdateDraw,_fnServerParams,_fnAddOptionsHtml,_fnFeatureHtmlTable,_fnScrollDraw,_fnAdjustColumnSizing,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnBuildSearchArray,_fnBuildSearchRow,_fnFilterCreateSearch,_fnDataToSearch,_fnSort,_fnSortAttachListener,_fnSortingClasses,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnFeatureHtmlLength,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnNodeToDataIndex,_fnVisbleColumns,_fnCalculateEnd,_fnConvertToWidth,_fnCalculateColumnWidths,_fnScrollingWidthAdjust,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnDetectType,_fnSettingsFromNode,_fnGetDataMaster,_fnGetTrNodes,_fnGetTdNodes,_fnEscapeRegex,_fnDeleteIndex,_fnReOrderIndex,_fnColumnOrdering,_fnLog,_fnClearTable,_fnSaveState,_fnLoadState,_fnCreateCookie,_fnReadCookie,_fnDetectHeader,_fnGetUniqueThs,_fnScrollBarWidth,_fnApplyToChildren,_fnMap,_fnGetRowData,_fnGetCellData,_fnSetCellData,_fnGetObjectDataFn,_fnSetObjectDataFn,_fnApplyColumnDefs,_fnBindAction,_fnCallbackReg,_fnCallbackFire,_fnJsonString,_fnRender,_fnNodeToColumnIndex,_fnInfoMacros,_fnBrowserDetect,_fnGetColumns*/
+/*globals $,require,jQuery,define,_selector_run,_selector_opts,_selector_first,_selector_row_indexes,_ext,_Api,_api_register,_api_registerPlural,_re_new_lines,_re_html,_re_formatted_numeric,_re_escape_regex,_empty,_intVal,_numToDecimal,_isNumber,_isHtml,_htmlNumeric,_pluck,_pluck_order,_range,_stripHtml,_unique,_fnBuildAjax,_fnAjaxUpdate,_fnAjaxParameters,_fnAjaxUpdateDraw,_fnAjaxDataSrc,_fnAddColumn,_fnColumnOptions,_fnAdjustColumnSizing,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnVisbleColumns,_fnGetColumns,_fnColumnTypes,_fnApplyColumnDefs,_fnHungarianMap,_fnCamelToHungarian,_fnLanguageCompat,_fnBrowserDetect,_fnAddData,_fnAddTr,_fnNodeToDataIndex,_fnNodeToColumnIndex,_fnGetCellData,_fnSetCellData,_fnSplitObjNotation,_fnGetObjectDataFn,_fnSetObjectDataFn,_fnGetDataMaster,_fnClearTable,_fnDeleteIndex,_fnInvalidate,_fnGetRowElements,_fnCreateTr,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAddOptionsHtml,_fnDetectHeader,_fnGetUniqueThs,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnFilterCreateSearch,_fnEscapeRegex,_fnFilterData,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnInfoMacros,_fnInitialise,_fnInitComplete,_fnLengthChange,_fnFeatureHtmlLength,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnFeatureHtmlTable,_fnScrollDraw,_fnApplyToChildren,_fnCalculateColumnWidths,_fnThrottle,_fnConvertToWidth,_fnScrollingWidthAdjust,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnScrollBarWidth,_fnSortFlatten,_fnSort,_fnSortAria,_fnSortListener,_fnSortAttachListener,_fnSortingClasses,_fnSortData,_fnSaveState,_fnLoadState,_fnSettingsFromNode,_fnLog,_fnMap,_fnBindAction,_fnCallbackReg,_fnCallbackFire,_fnLengthOverflow,_fnRenderer,_fnDataSource,_fnRowAttributes*/
(/** @lends <global> */function( window, document, undefined ) {
(function( factory ) {
"use strict";
- // Define as an AMD module if possible
- if ( typeof define === 'function' && define.amd )
- {
- define( ['jquery'], factory );
+ if ( typeof define === 'function' && define.amd ) {
+ // Define as an AMD module if possible
+ define( 'datatables', ['jquery'], factory );
}
- /* Define using browser globals otherwise
- * Prevent multiple instantiations if the script is loaded twice
- */
- else if ( jQuery && !jQuery.fn.dataTable )
- {
+ else if ( typeof exports === 'object' ) {
+ // Node/CommonJS
+ module.exports = factory( require( 'jquery' ) );
+ }
+ else if ( jQuery && !jQuery.fn.dataTable ) {
+ // Define using browser globals otherwise
+ // Prevent multiple instantiations if the script is loaded twice
factory( jQuery );
}
}
(/** @lends <global> */function( $ ) {
"use strict";
- /**
- * DataTables is a plug-in for the jQuery Javascript library. It is a
- * highly flexible tool, based upon the foundations of progressive
- * enhancement, which will add advanced interaction controls to any
- * HTML table. For a full list of features please refer to
- * <a href="http://datatables.net">DataTables.net</a>.
+
+ /**
+ * DataTables is a plug-in for the jQuery Javascript library. It is a highly
+ * flexible tool, based upon the foundations of progressive enhancement,
+ * which will add advanced interaction controls to any HTML table. For a
+ * full list of features please refer to
+ * [DataTables.net](href="http://datatables.net).
*
- * Note that the <i>DataTable</i> object is not a global variable but is
- * aliased to <i>jQuery.fn.DataTable</i> and <i>jQuery.fn.dataTable</i> through which
- * it may be accessed.
+ * Note that the `DataTable` object is not a global variable but is aliased
+ * to `jQuery.fn.DataTable` and `jQuery.fn.dataTable` through which it may
+ * be accessed.
*
* @class
- * @param {object} [oInit={}] Configuration object for DataTables. Options
+ * @param {object} [init={}] Configuration object for DataTables. Options
* are defined by {@link DataTable.defaults}
- * @requires jQuery 1.3+
- *
+ * @requires jQuery 1.7+
+ *
* @example
* // Basic initialisation
* $(document).ready( function {
* $('#example').dataTable();
* } );
- *
+ *
* @example
* // Initialisation with configuration options - in this case, disable
* // pagination and sorting.
* $(document).ready( function {
* $('#example').dataTable( {
- * "bPaginate": false,
- * "bSort": false
+ * "paginate": false,
+ * "sort": false
* } );
* } );
*/
- var DataTable = function( oInit )
- {
-
-
- /**
- * Add a column to the list used for the table with default values
- * @param {object} oSettings dataTables settings object
- * @param {node} nTh The th element for this column
- * @memberof DataTable#oApi
- */
- function _fnAddColumn( oSettings, nTh )
- {
- var oDefaults = DataTable.defaults.columns;
- var iCol = oSettings.aoColumns.length;
- var oCol = $.extend( {}, DataTable.models.oColumn, oDefaults, {
- "sSortingClass": oSettings.oClasses.sSortable,
- "sSortingClassJUI": oSettings.oClasses.sSortJUI,
- "nTh": nTh ? nTh : document.createElement('th'),
- "sTitle": oDefaults.sTitle ? oDefaults.sTitle : nTh ? nTh.innerHTML : '',
- "aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol],
- "mData": oDefaults.mData ? oDefaults.oDefaults : iCol
- } );
- oSettings.aoColumns.push( oCol );
-
- /* Add a column specific filter */
- if ( oSettings.aoPreSearchCols[ iCol ] === undefined || oSettings.aoPreSearchCols[ iCol ] === null )
- {
- oSettings.aoPreSearchCols[ iCol ] = $.extend( {}, DataTable.models.oSearch );
+ var DataTable;
+
+
+ /*
+ * It is useful to have variables which are scoped locally so only the
+ * DataTables functions can access them and they don't leak into global space.
+ * At the same time these functions are often useful over multiple files in the
+ * core and API, so we list, or at least document, all variables which are used
+ * by DataTables as private variables here. This also ensures that there is no
+ * clashing of variable names and that they can easily referenced for reuse.
+ */
+
+
+ // Defined else where
+ // _selector_run
+ // _selector_opts
+ // _selector_first
+ // _selector_row_indexes
+
+ var _ext; // DataTable.ext
+ var _Api; // DataTable.Api
+ var _api_register; // DataTable.Api.register
+ var _api_registerPlural; // DataTable.Api.registerPlural
+
+ var _re_dic = {};
+ var _re_new_lines = /[\r\n]/g;
+ var _re_html = /<.*?>/g;
+ var _re_date_start = /^[\w\+\-]/;
+ var _re_date_end = /[\w\+\-]$/;
+
+ // Escape regular expression special characters
+ var _re_escape_regex = new RegExp( '(\\' + [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^', '-' ].join('|\\') + ')', 'g' );
+
+ // http://en.wikipedia.org/wiki/Foreign_exchange_market
+ // - \u20BD - Russian ruble.
+ // - \u20a9 - South Korean Won
+ // - \u20BA - Turkish Lira
+ // - \u20B9 - Indian Rupee
+ // - R - Brazil (R$) and South Africa
+ // - fr - Swiss Franc
+ // - kr - Swedish krona, Norwegian krone and Danish krone
+ // - \u2009 is thin space and \u202F is narrow no-break space, both used in many
+ // standards as thousands separators.
+ var _re_formatted_numeric = /[',$£€¥%\u2009\u202F\u20BD\u20a9\u20BArfk]/gi;
+
+
+ var _empty = function ( d ) {
+ return !d || d === true || d === '-' ? true : false;
+ };
+
+
+ var _intVal = function ( s ) {
+ var integer = parseInt( s, 10 );
+ return !isNaN(integer) && isFinite(s) ? integer : null;
+ };
+
+ // Convert from a formatted number with characters other than `.` as the
+ // decimal place, to a Javascript number
+ var _numToDecimal = function ( num, decimalPoint ) {
+ // Cache created regular expressions for speed as this function is called often
+ if ( ! _re_dic[ decimalPoint ] ) {
+ _re_dic[ decimalPoint ] = new RegExp( _fnEscapeRegex( decimalPoint ), 'g' );
+ }
+ return typeof num === 'string' && decimalPoint !== '.' ?
+ num.replace( /\./g, '' ).replace( _re_dic[ decimalPoint ], '.' ) :
+ num;
+ };
+
+
+ var _isNumber = function ( d, decimalPoint, formatted ) {
+ var strType = typeof d === 'string';
+
+ // If empty return immediately so there must be a number if it is a
+ // formatted string (this stops the string "k", or "kr", etc being detected
+ // as a formatted number for currency
+ if ( _empty( d ) ) {
+ return true;
+ }
+
+ if ( decimalPoint && strType ) {
+ d = _numToDecimal( d, decimalPoint );
+ }
+
+ if ( formatted && strType ) {
+ d = d.replace( _re_formatted_numeric, '' );
+ }
+
+ return !isNaN( parseFloat(d) ) && isFinite( d );
+ };
+
+
+ // A string without HTML in it can be considered to be HTML still
+ var _isHtml = function ( d ) {
+ return _empty( d ) || typeof d === 'string';
+ };
+
+
+ var _htmlNumeric = function ( d, decimalPoint, formatted ) {
+ if ( _empty( d ) ) {
+ return true;
+ }
+
+ var html = _isHtml( d );
+ return ! html ?
+ null :
+ _isNumber( _stripHtml( d ), decimalPoint, formatted ) ?
+ true :
+ null;
+ };
+
+
+ var _pluck = function ( a, prop, prop2 ) {
+ var out = [];
+ var i=0, ien=a.length;
+
+ // Could have the test in the loop for slightly smaller code, but speed
+ // is essential here
+ if ( prop2 !== undefined ) {
+ for ( ; i<ien ; i++ ) {
+ if ( a[i] && a[i][ prop ] ) {
+ out.push( a[i][ prop ][ prop2 ] );
+ }
}
- else
- {
- var oPre = oSettings.aoPreSearchCols[ iCol ];
-
- /* Don't require that the user must specify bRegex, bSmart or bCaseInsensitive */
- if ( oPre.bRegex === undefined )
- {
- oPre.bRegex = true;
+ }
+ else {
+ for ( ; i<ien ; i++ ) {
+ if ( a[i] ) {
+ out.push( a[i][ prop ] );
}
-
- if ( oPre.bSmart === undefined )
- {
- oPre.bSmart = true;
+ }
+ }
+
+ return out;
+ };
+
+
+ // Basically the same as _pluck, but rather than looping over `a` we use `order`
+ // as the indexes to pick from `a`
+ var _pluck_order = function ( a, order, prop, prop2 )
+ {
+ var out = [];
+ var i=0, ien=order.length;
+
+ // Could have the test in the loop for slightly smaller code, but speed
+ // is essential here
+ if ( prop2 !== undefined ) {
+ for ( ; i<ien ; i++ ) {
+ if ( a[ order[i] ][ prop ] ) {
+ out.push( a[ order[i] ][ prop ][ prop2 ] );
}
-
- if ( oPre.bCaseInsensitive === undefined )
- {
- oPre.bCaseInsensitive = true;
+ }
+ }
+ else {
+ for ( ; i<ien ; i++ ) {
+ out.push( a[ order[i] ][ prop ] );
+ }
+ }
+
+ return out;
+ };
+
+
+ var _range = function ( len, start )
+ {
+ var out = [];
+ var end;
+
+ if ( start === undefined ) {
+ start = 0;
+ end = len;
+ }
+ else {
+ end = start;
+ start = len;
+ }
+
+ for ( var i=start ; i<end ; i++ ) {
+ out.push( i );
+ }
+
+ return out;
+ };
+
+
+ var _removeEmpty = function ( a )
+ {
+ var out = [];
+
+ for ( var i=0, ien=a.length ; i<ien ; i++ ) {
+ if ( a[i] ) { // careful - will remove all falsy values!
+ out.push( a[i] );
+ }
+ }
+
+ return out;
+ };
+
+
+ var _stripHtml = function ( d ) {
+ return d.replace( _re_html, '' );
+ };
+
+
+ /**
+ * Find the unique elements in a source array.
+ *
+ * @param {array} src Source array
+ * @return {array} Array of unique items
+ * @ignore
+ */
+ var _unique = function ( src )
+ {
+ // A faster unique method is to use object keys to identify used values,
+ // but this doesn't work with arrays or objects, which we must also
+ // consider. See jsperf.com/compare-array-unique-versions/4 for more
+ // information.
+ var
+ out = [],
+ val,
+ i, ien=src.length,
+ j, k=0;
+
+ again: for ( i=0 ; i<ien ; i++ ) {
+ val = src[i];
+
+ for ( j=0 ; j<k ; j++ ) {
+ if ( out[j] === val ) {
+ continue again;
}
}
-
- /* Use the column options function to initialise classes etc */
- _fnColumnOptions( oSettings, iCol, null );
+
+ out.push( val );
+ k++;
}
-
-
- /**
- * Apply options for a column
- * @param {object} oSettings dataTables settings object
- * @param {int} iCol column index to consider
- * @param {object} oOptions object with sType, bVisible and bSearchable etc
- * @memberof DataTable#oApi
- */
- function _fnColumnOptions( oSettings, iCol, oOptions )
- {
- var oCol = oSettings.aoColumns[ iCol ];
-
- /* User specified column options */
- if ( oOptions !== undefined && oOptions !== null )
+
+ return out;
+ };
+
+
+
+ /**
+ * Create a mapping object that allows camel case parameters to be looked up
+ * for their Hungarian counterparts. The mapping is stored in a private
+ * parameter called `_hungarianMap` which can be accessed on the source object.
+ * @param {object} o
+ * @memberof DataTable#oApi
+ */
+ function _fnHungarianMap ( o )
+ {
+ var
+ hungarian = 'a aa ai ao as b fn i m o s ',
+ match,
+ newKey,
+ map = {};
+
+ $.each( o, function (key, val) {
+ match = key.match(/^([^A-Z]+?)([A-Z])/);
+
+ if ( match && hungarian.indexOf(match[1]+' ') !== -1 )
{
- /* Backwards compatibility for mDataProp */
- if ( oOptions.mDataProp && !oOptions.mData )
+ newKey = key.replace( match[0], match[2].toLowerCase() );
+ map[ newKey ] = key;
+
+ if ( match[1] === 'o' )
{
- oOptions.mData = oOptions.mDataProp;
+ _fnHungarianMap( o[key] );
}
-
- if ( oOptions.sType !== undefined )
+ }
+ } );
+
+ o._hungarianMap = map;
+ }
+
+
+ /**
+ * Convert from camel case parameters to Hungarian, based on a Hungarian map
+ * created by _fnHungarianMap.
+ * @param {object} src The model object which holds all parameters that can be
+ * mapped.
+ * @param {object} user The object to convert from camel case to Hungarian.
+ * @param {boolean} force When set to `true`, properties which already have a
+ * Hungarian value in the `user` object will be overwritten. Otherwise they
+ * won't be.
+ * @memberof DataTable#oApi
+ */
+ function _fnCamelToHungarian ( src, user, force )
+ {
+ if ( ! src._hungarianMap ) {
+ _fnHungarianMap( src );
+ }
+
+ var hungarianKey;
+
+ $.each( user, function (key, val) {
+ hungarianKey = src._hungarianMap[ key ];
+
+ if ( hungarianKey !== undefined && (force || user[hungarianKey] === undefined) )
+ {
+ // For objects, we need to buzz down into the object to copy parameters
+ if ( hungarianKey.charAt(0) === 'o' )
{
- oCol.sType = oOptions.sType;
- oCol._bAutoType = false;
+ // Copy the camelCase options over to the hungarian
+ if ( ! user[ hungarianKey ] ) {
+ user[ hungarianKey ] = {};
+ }
+ $.extend( true, user[hungarianKey], user[key] );
+
+ _fnCamelToHungarian( src[hungarianKey], user[hungarianKey], force );
}
-
- $.extend( oCol, oOptions );
- _fnMap( oCol, oOptions, "sWidth", "sWidthOrig" );
-
- /* iDataSort to be applied (backwards compatibility), but aDataSort will take
- * priority if defined
- */
- if ( oOptions.iDataSort !== undefined )
- {
- oCol.aDataSort = [ oOptions.iDataSort ];
+ else {
+ user[hungarianKey] = user[ key ];
}
- _fnMap( oCol, oOptions, "aDataSort" );
}
-
- /* Cache the data get and set functions for speed */
- var mRender = oCol.mRender ? _fnGetObjectDataFn( oCol.mRender ) : null;
- var mData = _fnGetObjectDataFn( oCol.mData );
-
- oCol.fnGetData = function (oData, sSpecific) {
- var innerData = mData( oData, sSpecific );
-
- if ( oCol.mRender && (sSpecific && sSpecific !== '') )
- {
- return mRender( innerData, sSpecific, oData );
+ } );
+ }
+
+
+ /**
+ * Language compatibility - when certain options are given, and others aren't, we
+ * need to duplicate the values over, in order to provide backwards compatibility
+ * with older language files.
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnLanguageCompat( lang )
+ {
+ var defaults = DataTable.defaults.oLanguage;
+ var zeroRecords = lang.sZeroRecords;
+
+ /* Backwards compatibility - if there is no sEmptyTable given, then use the same as
+ * sZeroRecords - assuming that is given.
+ */
+ if ( ! lang.sEmptyTable && zeroRecords &&
+ defaults.sEmptyTable === "No data available in table" )
+ {
+ _fnMap( lang, lang, 'sZeroRecords', 'sEmptyTable' );
+ }
+
+ /* Likewise with loading records */
+ if ( ! lang.sLoadingRecords && zeroRecords &&
+ defaults.sLoadingRecords === "Loading..." )
+ {
+ _fnMap( lang, lang, 'sZeroRecords', 'sLoadingRecords' );
+ }
+
+ // Old parameter name of the thousands separator mapped onto the new
+ if ( lang.sInfoThousands ) {
+ lang.sThousands = lang.sInfoThousands;
+ }
+
+ var decimal = lang.sDecimal;
+ if ( decimal ) {
+ _addNumericSort( decimal );
+ }
+ }
+
+
+ /**
+ * Map one parameter onto another
+ * @param {object} o Object to map
+ * @param {*} knew The new parameter name
+ * @param {*} old The old parameter name
+ */
+ var _fnCompatMap = function ( o, knew, old ) {
+ if ( o[ knew ] !== undefined ) {
+ o[ old ] = o[ knew ];
+ }
+ };
+
+
+ /**
+ * Provide backwards compatibility for the main DT options. Note that the new
+ * options are mapped onto the old parameters, so this is an external interface
+ * change only.
+ * @param {object} init Object to map
+ */
+ function _fnCompatOpts ( init )
+ {
+ _fnCompatMap( init, 'ordering', 'bSort' );
+ _fnCompatMap( init, 'orderMulti', 'bSortMulti' );
+ _fnCompatMap( init, 'orderClasses', 'bSortClasses' );
+ _fnCompatMap( init, 'orderCellsTop', 'bSortCellsTop' );
+ _fnCompatMap( init, 'order', 'aaSorting' );
+ _fnCompatMap( init, 'orderFixed', 'aaSortingFixed' );
+ _fnCompatMap( init, 'paging', 'bPaginate' );
+ _fnCompatMap( init, 'pagingType', 'sPaginationType' );
+ _fnCompatMap( init, 'pageLength', 'iDisplayLength' );
+ _fnCompatMap( init, 'searching', 'bFilter' );
+
+ // Column search objects are in an array, so it needs to be converted
+ // element by element
+ var searchCols = init.aoSearchCols;
+
+ if ( searchCols ) {
+ for ( var i=0, ien=searchCols.length ; i<ien ; i++ ) {
+ if ( searchCols[i] ) {
+ _fnCamelToHungarian( DataTable.models.oSearch, searchCols[i] );
}
- return innerData;
- };
- oCol.fnSetData = _fnSetObjectDataFn( oCol.mData );
-
- /* Feature sorting overrides column specific when off */
- if ( !oSettings.oFeatures.bSort )
- {
- oCol.bSortable = false;
}
-
- /* Check that the class assignment is correct for sorting */
- if ( !oCol.bSortable ||
- ($.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) == -1) )
- {
- oCol.sSortingClass = oSettings.oClasses.sSortableNone;
- oCol.sSortingClassJUI = "";
+ }
+ }
+
+
+ /**
+ * Provide backwards compatibility for column options. Note that the new options
+ * are mapped onto the old parameters, so this is an external interface change
+ * only.
+ * @param {object} init Object to map
+ */
+ function _fnCompatCols ( init )
+ {
+ _fnCompatMap( init, 'orderable', 'bSortable' );
+ _fnCompatMap( init, 'orderData', 'aDataSort' );
+ _fnCompatMap( init, 'orderSequence', 'asSorting' );
+ _fnCompatMap( init, 'orderDataType', 'sortDataType' );
+
+ // orderData can be given as an integer
+ var dataSort = init.aDataSort;
+ if ( dataSort && ! $.isArray( dataSort ) ) {
+ init.aDataSort = [ dataSort ];
+ }
+ }
+
+
+ /**
+ * Browser feature detection for capabilities, quirks
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnBrowserDetect( settings )
+ {
+ var browser = settings.oBrowser;
+
+ // Scrolling feature / quirks detection
+ var n = $('<div/>')
+ .css( {
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ height: 1,
+ width: 1,
+ overflow: 'hidden'
+ } )
+ .append(
+ $('<div/>')
+ .css( {
+ position: 'absolute',
+ top: 1,
+ left: 1,
+ width: 100,
+ overflow: 'scroll'
+ } )
+ .append(
+ $('<div class="test"/>')
+ .css( {
+ width: '100%',
+ height: 10
+ } )
+ )
+ )
+ .appendTo( 'body' );
+
+ var test = n.find('.test');
+
+ // IE6/7 will oversize a width 100% element inside a scrolling element, to
+ // include the width of the scrollbar, while other browsers ensure the inner
+ // element is contained without forcing scrolling
+ browser.bScrollOversize = test[0].offsetWidth === 100;
+
+ // In rtl text layout, some browsers (most, but not all) will place the
+ // scrollbar on the left, rather than the right.
+ browser.bScrollbarLeft = Math.round( test.offset().left ) !== 1;
+
+ n.remove();
+ }
+
+
+ /**
+ * Array.prototype reduce[Right] method, used for browsers which don't support
+ * JS 1.6. Done this way to reduce code size, since we iterate either way
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnReduce ( that, fn, init, start, end, inc )
+ {
+ var
+ i = start,
+ value,
+ isSet = false;
+
+ if ( init !== undefined ) {
+ value = init;
+ isSet = true;
+ }
+
+ while ( i !== end ) {
+ if ( ! that.hasOwnProperty(i) ) {
+ continue;
}
- else if ( $.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) == -1 )
- {
- oCol.sSortingClass = oSettings.oClasses.sSortable;
- oCol.sSortingClassJUI = oSettings.oClasses.sSortJUI;
+
+ value = isSet ?
+ fn( value, that[i], i, that ) :
+ that[i];
+
+ isSet = true;
+ i += inc;
+ }
+
+ return value;
+ }
+
+ /**
+ * Add a column to the list used for the table with default values
+ * @param {object} oSettings dataTables settings object
+ * @param {node} nTh The th element for this column
+ * @memberof DataTable#oApi
+ */
+ function _fnAddColumn( oSettings, nTh )
+ {
+ // Add column to aoColumns array
+ var oDefaults = DataTable.defaults.column;
+ var iCol = oSettings.aoColumns.length;
+ var oCol = $.extend( {}, DataTable.models.oColumn, oDefaults, {
+ "nTh": nTh ? nTh : document.createElement('th'),
+ "sTitle": oDefaults.sTitle ? oDefaults.sTitle : nTh ? nTh.innerHTML : '',
+ "aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol],
+ "mData": oDefaults.mData ? oDefaults.mData : iCol,
+ idx: iCol
+ } );
+ oSettings.aoColumns.push( oCol );
+
+ // Add search object for column specific search. Note that the `searchCols[ iCol ]`
+ // passed into extend can be undefined. This allows the user to give a default
+ // with only some of the parameters defined, and also not give a default
+ var searchCols = oSettings.aoPreSearchCols;
+ searchCols[ iCol ] = $.extend( {}, DataTable.models.oSearch, searchCols[ iCol ] );
+
+ // Use the default column options function to initialise classes etc
+ _fnColumnOptions( oSettings, iCol, $(nTh).data() );
+ }
+
+
+ /**
+ * Apply options for a column
+ * @param {object} oSettings dataTables settings object
+ * @param {int} iCol column index to consider
+ * @param {object} oOptions object with sType, bVisible and bSearchable etc
+ * @memberof DataTable#oApi
+ */
+ function _fnColumnOptions( oSettings, iCol, oOptions )
+ {
+ var oCol = oSettings.aoColumns[ iCol ];
+ var oClasses = oSettings.oClasses;
+ var th = $(oCol.nTh);
+
+ // Try to get width information from the DOM. We can't get it from CSS
+ // as we'd need to parse the CSS stylesheet. `width` option can override
+ if ( ! oCol.sWidthOrig ) {
+ // Width attribute
+ oCol.sWidthOrig = th.attr('width') || null;
+
+ // Style attribute
+ var t = (th.attr('style') || '').match(/width:\s*(\d+[px|em|%]+)/);
+ if ( t ) {
+ oCol.sWidthOrig = t[1];
}
- else if ( $.inArray('asc', oCol.asSorting) != -1 && $.inArray('desc', oCol.asSorting) == -1 )
+ }
+
+ /* User specified column options */
+ if ( oOptions !== undefined && oOptions !== null )
+ {
+ // Backwards compatibility
+ _fnCompatCols( oOptions );
+
+ // Map camel case parameters to their Hungarian counterparts
+ _fnCamelToHungarian( DataTable.defaults.column, oOptions );
+
+ /* Backwards compatibility for mDataProp */
+ if ( oOptions.mDataProp !== undefined && !oOptions.mData )
{
- oCol.sSortingClass = oSettings.oClasses.sSortableAsc;
- oCol.sSortingClassJUI = oSettings.oClasses.sSortJUIAscAllowed;
+ oOptions.mData = oOptions.mDataProp;
}
- else if ( $.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) != -1 )
+
+ if ( oOptions.sType )
{
- oCol.sSortingClass = oSettings.oClasses.sSortableDesc;
- oCol.sSortingClassJUI = oSettings.oClasses.sSortJUIDescAllowed;
+ oCol._sManualType = oOptions.sType;
}
- }
-
-
- /**
- * Adjust the table column widths for new data. Note: you would probably want to
- * do a redraw after calling this function!
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnAdjustColumnSizing ( oSettings )
- {
- /* Not interested in doing column width calculation if auto-width is disabled */
- if ( oSettings.oFeatures.bAutoWidth === false )
+
+ // `class` is a reserved word in Javascript, so we need to provide
+ // the ability to use a valid name for the camel case input
+ if ( oOptions.className && ! oOptions.sClass )
{
- return false;
+ oOptions.sClass = oOptions.className;
}
-
- _fnCalculateColumnWidths( oSettings );
- for ( var i=0 , iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
+
+ $.extend( oCol, oOptions );
+ _fnMap( oCol, oOptions, "sWidth", "sWidthOrig" );
+
+ /* iDataSort to be applied (backwards compatibility), but aDataSort will take
+ * priority if defined
+ */
+ if ( oOptions.iDataSort !== undefined )
{
- oSettings.aoColumns[i].nTh.style.width = oSettings.aoColumns[i].sWidth;
+ oCol.aDataSort = [ oOptions.iDataSort ];
}
+ _fnMap( oCol, oOptions, "aDataSort" );
}
-
-
- /**
- * Covert the index of a visible column to the index in the data array (take account
- * of hidden columns)
- * @param {object} oSettings dataTables settings object
- * @param {int} iMatch Visible column index to lookup
- * @returns {int} i the data index
- * @memberof DataTable#oApi
- */
- function _fnVisibleToColumnIndex( oSettings, iMatch )
- {
- var aiVis = _fnGetColumns( oSettings, 'bVisible' );
-
- return typeof aiVis[iMatch] === 'number' ?
- aiVis[iMatch] :
- null;
+
+ /* Cache the data get and set functions for speed */
+ var mDataSrc = oCol.mData;
+ var mData = _fnGetObjectDataFn( mDataSrc );
+ var mRender = oCol.mRender ? _fnGetObjectDataFn( oCol.mRender ) : null;
+
+ var attrTest = function( src ) {
+ return typeof src === 'string' && src.indexOf('@') !== -1;
+ };
+ oCol._bAttrSrc = $.isPlainObject( mDataSrc ) && (
+ attrTest(mDataSrc.sort) || attrTest(mDataSrc.type) || attrTest(mDataSrc.filter)
+ );
+
+ oCol.fnGetData = function (rowData, type, meta) {
+ var innerData = mData( rowData, type, undefined, meta );
+
+ return mRender && type ?
+ mRender( innerData, type, rowData, meta ) :
+ innerData;
+ };
+ oCol.fnSetData = function ( rowData, val, meta ) {
+ return _fnSetObjectDataFn( mDataSrc )( rowData, val, meta );
+ };
+
+ // Indicate if DataTables should read DOM data as an object or array
+ // Used in _fnGetRowElements
+ if ( typeof mDataSrc !== 'number' ) {
+ oSettings._rowReadObject = true;
}
-
-
- /**
- * Covert the index of an index in the data array and convert it to the visible
- * column index (take account of hidden columns)
- * @param {int} iMatch Column index to lookup
- * @param {object} oSettings dataTables settings object
- * @returns {int} i the data index
- * @memberof DataTable#oApi
- */
- function _fnColumnIndexToVisible( oSettings, iMatch )
+
+ /* Feature sorting overrides column specific when off */
+ if ( !oSettings.oFeatures.bSort )
{
- var aiVis = _fnGetColumns( oSettings, 'bVisible' );
- var iPos = $.inArray( iMatch, aiVis );
-
- return iPos !== -1 ? iPos : null;
+ oCol.bSortable = false;
+ th.addClass( oClasses.sSortableNone ); // Have to add class here as order event isn't called
}
-
-
- /**
- * Get the number of visible columns
- * @param {object} oSettings dataTables settings object
- * @returns {int} i the number of visible columns
- * @memberof DataTable#oApi
- */
- function _fnVisbleColumns( oSettings )
+
+ /* Check that the class assignment is correct for sorting */
+ var bAsc = $.inArray('asc', oCol.asSorting) !== -1;
+ var bDesc = $.inArray('desc', oCol.asSorting) !== -1;
+ if ( !oCol.bSortable || (!bAsc && !bDesc) )
{
- return _fnGetColumns( oSettings, 'bVisible' ).length;
+ oCol.sSortingClass = oClasses.sSortableNone;
+ oCol.sSortingClassJUI = "";
}
-
-
- /**
- * Get an array of column indexes that match a given property
- * @param {object} oSettings dataTables settings object
- * @param {string} sParam Parameter in aoColumns to look for - typically
- * bVisible or bSearchable
- * @returns {array} Array of indexes with matched properties
- * @memberof DataTable#oApi
- */
- function _fnGetColumns( oSettings, sParam )
+ else if ( bAsc && !bDesc )
{
- var a = [];
-
- $.map( oSettings.aoColumns, function(val, i) {
- if ( val[sParam] ) {
- a.push( i );
- }
- } );
-
- return a;
+ oCol.sSortingClass = oClasses.sSortableAsc;
+ oCol.sSortingClassJUI = oClasses.sSortJUIAscAllowed;
}
-
-
- /**
- * Get the sort type based on an input string
- * @param {string} sData data we wish to know the type of
- * @returns {string} type (defaults to 'string' if no type can be detected)
- * @memberof DataTable#oApi
- */
- function _fnDetectType( sData )
+ else if ( !bAsc && bDesc )
{
- var aTypes = DataTable.ext.aTypes;
- var iLen = aTypes.length;
-
- for ( var i=0 ; i<iLen ; i++ )
- {
- var sType = aTypes[i]( sData );
- if ( sType !== null )
- {
- return sType;
- }
- }
-
- return 'string';
+ oCol.sSortingClass = oClasses.sSortableDesc;
+ oCol.sSortingClassJUI = oClasses.sSortJUIDescAllowed;
}
-
-
- /**
- * Figure out how to reorder a display list
- * @param {object} oSettings dataTables settings object
- * @returns array {int} aiReturn index list for reordering
- * @memberof DataTable#oApi
- */
- function _fnReOrderIndex ( oSettings, sColumns )
+ else
{
- var aColumns = sColumns.split(',');
- var aiReturn = [];
-
- for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
- {
- for ( var j=0 ; j<iLen ; j++ )
- {
- if ( oSettings.aoColumns[i].sName == aColumns[j] )
- {
- aiReturn.push( j );
- break;
- }
- }
- }
-
- return aiReturn;
+ oCol.sSortingClass = oClasses.sSortable;
+ oCol.sSortingClassJUI = oClasses.sSortJUI;
}
-
-
- /**
- * Get the column ordering that DataTables expects
- * @param {object} oSettings dataTables settings object
- * @returns {string} comma separated list of names
- * @memberof DataTable#oApi
- */
- function _fnColumnOrdering ( oSettings )
+ }
+
+
+ /**
+ * Adjust the table column widths for new data. Note: you would probably want to
+ * do a redraw after calling this function!
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnAdjustColumnSizing ( settings )
+ {
+ /* Not interested in doing column width calculation if auto-width is disabled */
+ if ( settings.oFeatures.bAutoWidth !== false )
{
- var sNames = '';
- for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
- {
- sNames += oSettings.aoColumns[i].sName+',';
- }
- if ( sNames.length == iLen )
+ var columns = settings.aoColumns;
+
+ _fnCalculateColumnWidths( settings );
+ for ( var i=0 , iLen=columns.length ; i<iLen ; i++ )
{
- return "";
+ columns[i].nTh.style.width = columns[i].sWidth;
}
- return sNames.slice(0, -1);
}
-
-
- /**
- * Take the column definitions and static columns arrays and calculate how
- * they relate to column indexes. The callback function will then apply the
- * definition found for a column to a suitable configuration object.
- * @param {object} oSettings dataTables settings object
- * @param {array} aoColDefs The aoColumnDefs array that is to be applied
- * @param {array} aoCols The aoColumns array that defines columns individually
- * @param {function} fn Callback function - takes two parameters, the calculated
- * column index and the definition for that column.
- * @memberof DataTable#oApi
- */
- function _fnApplyColumnDefs( oSettings, aoColDefs, aoCols, fn )
+
+ var scroll = settings.oScroll;
+ if ( scroll.sY !== '' || scroll.sX !== '')
{
- var i, iLen, j, jLen, k, kLen;
-
- // Column definitions with aTargets
- if ( aoColDefs )
- {
- /* Loop over the definitions array - loop in reverse so first instance has priority */
- for ( i=aoColDefs.length-1 ; i>=0 ; i-- )
- {
- /* Each definition can target multiple columns, as it is an array */
- var aTargets = aoColDefs[i].aTargets;
- if ( !$.isArray( aTargets ) )
- {
- _fnLog( oSettings, 1, 'aTargets must be an array of targets, not a '+(typeof aTargets) );
- }
-
- for ( j=0, jLen=aTargets.length ; j<jLen ; j++ )
- {
- if ( typeof aTargets[j] === 'number' && aTargets[j] >= 0 )
- {
- /* Add columns that we don't yet know about */
- while( oSettings.aoColumns.length <= aTargets[j] )
- {
- _fnAddColumn( oSettings );
- }
-
- /* Integer, basic index */
- fn( aTargets[j], aoColDefs[i] );
+ _fnScrollDraw( settings );
+ }
+
+ _fnCallbackFire( settings, null, 'column-sizing', [settings] );
+ }
+
+
+ /**
+ * Covert the index of a visible column to the index in the data array (take account
+ * of hidden columns)
+ * @param {object} oSettings dataTables settings object
+ * @param {int} iMatch Visible column index to lookup
+ * @returns {int} i the data index
+ * @memberof DataTable#oApi
+ */
+ function _fnVisibleToColumnIndex( oSettings, iMatch )
+ {
+ var aiVis = _fnGetColumns( oSettings, 'bVisible' );
+
+ return typeof aiVis[iMatch] === 'number' ?
+ aiVis[iMatch] :
+ null;
+ }
+
+
+ /**
+ * Covert the index of an index in the data array and convert it to the visible
+ * column index (take account of hidden columns)
+ * @param {int} iMatch Column index to lookup
+ * @param {object} oSettings dataTables settings object
+ * @returns {int} i the data index
+ * @memberof DataTable#oApi
+ */
+ function _fnColumnIndexToVisible( oSettings, iMatch )
+ {
+ var aiVis = _fnGetColumns( oSettings, 'bVisible' );
+ var iPos = $.inArray( iMatch, aiVis );
+
+ return iPos !== -1 ? iPos : null;
+ }
+
+
+ /**
+ * Get the number of visible columns
+ * @param {object} oSettings dataTables settings object
+ * @returns {int} i the number of visible columns
+ * @memberof DataTable#oApi
+ */
+ function _fnVisbleColumns( oSettings )
+ {
+ return _fnGetColumns( oSettings, 'bVisible' ).length;
+ }
+
+
+ /**
+ * Get an array of column indexes that match a given property
+ * @param {object} oSettings dataTables settings object
+ * @param {string} sParam Parameter in aoColumns to look for - typically
+ * bVisible or bSearchable
+ * @returns {array} Array of indexes with matched properties
+ * @memberof DataTable#oApi
+ */
+ function _fnGetColumns( oSettings, sParam )
+ {
+ var a = [];
+
+ $.map( oSettings.aoColumns, function(val, i) {
+ if ( val[sParam] ) {
+ a.push( i );
+ }
+ } );
+
+ return a;
+ }
+
+
+ /**
+ * Calculate the 'type' of a column
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnColumnTypes ( settings )
+ {
+ var columns = settings.aoColumns;
+ var data = settings.aoData;
+ var types = DataTable.ext.type.detect;
+ var i, ien, j, jen, k, ken;
+ var col, cell, detectedType, cache;
+
+ // For each column, spin over the
+ for ( i=0, ien=columns.length ; i<ien ; i++ ) {
+ col = columns[i];
+ cache = [];
+
+ if ( ! col.sType && col._sManualType ) {
+ col.sType = col._sManualType;
+ }
+ else if ( ! col.sType ) {
+ for ( j=0, jen=types.length ; j<jen ; j++ ) {
+ for ( k=0, ken=data.length ; k<ken ; k++ ) {
+ // Use a cache array so we only need to get the type data
+ // from the formatter once (when using multiple detectors)
+ if ( cache[k] === undefined ) {
+ cache[k] = _fnGetCellData( settings, k, i, 'type' );
}
- else if ( typeof aTargets[j] === 'number' && aTargets[j] < 0 )
- {
- /* Negative integer, right to left column counting */
- fn( oSettings.aoColumns.length+aTargets[j], aoColDefs[i] );
+
+ detectedType = types[j]( cache[k], settings );
+
+ // If null, then this type can't apply to this column, so
+ // rather than testing all cells, break out. There is an
+ // exception for the last type which is `html`. We need to
+ // scan all rows since it is possible to mix string and HTML
+ // types
+ if ( ! detectedType && j !== types.length-1 ) {
+ break;
}
- else if ( typeof aTargets[j] === 'string' )
- {
- /* Class name matching on TH element */
- for ( k=0, kLen=oSettings.aoColumns.length ; k<kLen ; k++ )
- {
- if ( aTargets[j] == "_all" ||
- $(oSettings.aoColumns[k].nTh).hasClass( aTargets[j] ) )
- {
- fn( k, aoColDefs[i] );
- }
- }
+
+ // Only a single match is needed for html type since it is
+ // bottom of the pile and very similar to string
+ if ( detectedType === 'html' ) {
+ break;
}
}
+
+ // Type is valid for all data points in the column - use this
+ // type
+ if ( detectedType ) {
+ col.sType = detectedType;
+ break;
+ }
}
- }
-
- // Statically defined columns array
- if ( aoCols )
- {
- for ( i=0, iLen=aoCols.length ; i<iLen ; i++ )
- {
- fn( i, aoCols[i] );
+
+ // Fall back - if no type was detected, always use string
+ if ( ! col.sType ) {
+ col.sType = 'string';
}
}
}
-
- /**
- * Add a data array to the table, creating DOM node etc. This is the parallel to
- * _fnGatherData, but for adding rows from a Javascript source, rather than a
- * DOM source.
- * @param {object} oSettings dataTables settings object
- * @param {array} aData data array to be added
- * @returns {int} >=0 if successful (index of new aoData entry), -1 if failed
- * @memberof DataTable#oApi
- */
- function _fnAddData ( oSettings, aDataSupplied )
+ }
+
+
+ /**
+ * Take the column definitions and static columns arrays and calculate how
+ * they relate to column indexes. The callback function will then apply the
+ * definition found for a column to a suitable configuration object.
+ * @param {object} oSettings dataTables settings object
+ * @param {array} aoColDefs The aoColumnDefs array that is to be applied
+ * @param {array} aoCols The aoColumns array that defines columns individually
+ * @param {function} fn Callback function - takes two parameters, the calculated
+ * column index and the definition for that column.
+ * @memberof DataTable#oApi
+ */
+ function _fnApplyColumnDefs( oSettings, aoColDefs, aoCols, fn )
+ {
+ var i, iLen, j, jLen, k, kLen, def;
+ var columns = oSettings.aoColumns;
+
+ // Column definitions with aTargets
+ if ( aoColDefs )
{
- var oCol;
-
- /* Take an independent copy of the data source so we can bash it about as we wish */
- var aDataIn = ($.isArray(aDataSupplied)) ?
- aDataSupplied.slice() :
- $.extend( true, {}, aDataSupplied );
-
- /* Create the object for storing information about this new row */
- var iRow = oSettings.aoData.length;
- var oData = $.extend( true, {}, DataTable.models.oRow );
- oData._aData = aDataIn;
- oSettings.aoData.push( oData );
-
- /* Create the cells */
- var nTd, sThisType;
- for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
+ /* Loop over the definitions array - loop in reverse so first instance has priority */
+ for ( i=aoColDefs.length-1 ; i>=0 ; i-- )
{
- oCol = oSettings.aoColumns[i];
-
- /* Use rendered data for filtering / sorting */
- if ( typeof oCol.fnRender === 'function' && oCol.bUseRendered && oCol.mData !== null )
- {
- _fnSetCellData( oSettings, iRow, i, _fnRender(oSettings, iRow, i) );
- }
- else
- {
- _fnSetCellData( oSettings, iRow, i, _fnGetCellData( oSettings, iRow, i ) );
- }
-
- /* See if we should auto-detect the column type */
- if ( oCol._bAutoType && oCol.sType != 'string' )
+ def = aoColDefs[i];
+
+ /* Each definition can target multiple columns, as it is an array */
+ var aTargets = def.targets !== undefined ?
+ def.targets :
+ def.aTargets;
+
+ if ( ! $.isArray( aTargets ) )
{
- /* Attempt to auto detect the type - same as _fnGatherData() */
- var sVarType = _fnGetCellData( oSettings, iRow, i, 'type' );
- if ( sVarType !== null && sVarType !== '' )
- {
- sThisType = _fnDetectType( sVarType );
- if ( oCol.sType === null )
- {
- oCol.sType = sThisType;
- }
- else if ( oCol.sType != sThisType && oCol.sType != "html" )
- {
- /* String is always the 'fallback' option */
- oCol.sType = 'string';
- }
- }
+ aTargets = [ aTargets ];
}
- }
-
- /* Add to the display array */
- oSettings.aiDisplayMaster.push( iRow );
-
- /* Create the DOM information */
- if ( !oSettings.oFeatures.bDeferRender )
- {
- _fnCreateTr( oSettings, iRow );
- }
-
- return iRow;
- }
-
-
- /**
- * Read in the data from the target table from the DOM
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnGatherData( oSettings )
- {
- var iLoop, i, iLen, j, jLen, jInner,
- nTds, nTrs, nTd, nTr, aLocalData, iThisIndex,
- iRow, iRows, iColumn, iColumns, sNodeName,
- oCol, oData;
-
- /*
- * Process by row first
- * Add the data object for the whole table - storing the tr node. Note - no point in getting
- * DOM based data if we are going to go and replace it with Ajax source data.
- */
- if ( oSettings.bDeferLoading || oSettings.sAjaxSource === null )
- {
- nTr = oSettings.nTBody.firstChild;
- while ( nTr )
+
+ for ( j=0, jLen=aTargets.length ; j<jLen ; j++ )
{
- if ( nTr.nodeName.toUpperCase() == "TR" )
+ if ( typeof aTargets[j] === 'number' && aTargets[j] >= 0 )
{
- iThisIndex = oSettings.aoData.length;
- nTr._DT_RowIndex = iThisIndex;
- oSettings.aoData.push( $.extend( true, {}, DataTable.models.oRow, {
- "nTr": nTr
- } ) );
-
- oSettings.aiDisplayMaster.push( iThisIndex );
- nTd = nTr.firstChild;
- jInner = 0;
- while ( nTd )
+ /* Add columns that we don't yet know about */
+ while( columns.length <= aTargets[j] )
{
- sNodeName = nTd.nodeName.toUpperCase();
- if ( sNodeName == "TD" || sNodeName == "TH" )
- {
- _fnSetCellData( oSettings, iThisIndex, jInner, $.trim(nTd.innerHTML) );
- jInner++;
- }
- nTd = nTd.nextSibling;
+ _fnAddColumn( oSettings );
}
+
+ /* Integer, basic index */
+ fn( aTargets[j], def );
}
- nTr = nTr.nextSibling;
- }
- }
-
- /* Gather in the TD elements of the Table - note that this is basically the same as
- * fnGetTdNodes, but that function takes account of hidden columns, which we haven't yet
- * setup!
- */
- nTrs = _fnGetTrNodes( oSettings );
- nTds = [];
- for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
- {
- nTd = nTrs[i].firstChild;
- while ( nTd )
- {
- sNodeName = nTd.nodeName.toUpperCase();
- if ( sNodeName == "TD" || sNodeName == "TH" )
+ else if ( typeof aTargets[j] === 'number' && aTargets[j] < 0 )
{
- nTds.push( nTd );
+ /* Negative integer, right to left column counting */
+ fn( columns.length+aTargets[j], def );
}
- nTd = nTd.nextSibling;
- }
- }
-
- /* Now process by column */
- for ( iColumn=0, iColumns=oSettings.aoColumns.length ; iColumn<iColumns ; iColumn++ )
- {
- oCol = oSettings.aoColumns[iColumn];
-
- /* Get the title of the column - unless there is a user set one */
- if ( oCol.sTitle === null )
- {
- oCol.sTitle = oCol.nTh.innerHTML;
- }
-
- var
- bAutoType = oCol._bAutoType,
- bRender = typeof oCol.fnRender === 'function',
- bClass = oCol.sClass !== null,
- bVisible = oCol.bVisible,
- nCell, sThisType, sRendered, sValType;
-
- /* A single loop to rule them all (and be more efficient) */
- if ( bAutoType || bRender || bClass || !bVisible )
- {
- for ( iRow=0, iRows=oSettings.aoData.length ; iRow<iRows ; iRow++ )
+ else if ( typeof aTargets[j] === 'string' )
{
- oData = oSettings.aoData[iRow];
- nCell = nTds[ (iRow*iColumns) + iColumn ];
-
- /* Type detection */
- if ( bAutoType && oCol.sType != 'string' )
+ /* Class name matching on TH element */
+ for ( k=0, kLen=columns.length ; k<kLen ; k++ )
{
- sValType = _fnGetCellData( oSettings, iRow, iColumn, 'type' );
- if ( sValType !== '' )
+ if ( aTargets[j] == "_all" ||
+ $(columns[k].nTh).hasClass( aTargets[j] ) )
{
- sThisType = _fnDetectType( sValType );
- if ( oCol.sType === null )
- {
- oCol.sType = sThisType;
- }
- else if ( oCol.sType != sThisType &&
- oCol.sType != "html" )
- {
- /* String is always the 'fallback' option */
- oCol.sType = 'string';
- }
+ fn( k, def );
}
}
-
- if ( oCol.mRender )
- {
- // mRender has been defined, so we need to get the value and set it
- nCell.innerHTML = _fnGetCellData( oSettings, iRow, iColumn, 'display' );
- }
- else if ( oCol.mData !== iColumn )
- {
- // If mData is not the same as the column number, then we need to
- // get the dev set value. If it is the column, no point in wasting
- // time setting the value that is already there!
- nCell.innerHTML = _fnGetCellData( oSettings, iRow, iColumn, 'display' );
- }
-
- /* Rendering */
- if ( bRender )
- {
- sRendered = _fnRender( oSettings, iRow, iColumn );
- nCell.innerHTML = sRendered;
- if ( oCol.bUseRendered )
- {
- /* Use the rendered data for filtering / sorting */
- _fnSetCellData( oSettings, iRow, iColumn, sRendered );
- }
- }
-
- /* Classes */
- if ( bClass )
- {
- nCell.className += ' '+oCol.sClass;
- }
-
- /* Column visibility */
- if ( !bVisible )
- {
- oData._anHidden[iColumn] = nCell;
- nCell.parentNode.removeChild( nCell );
- }
- else
- {
- oData._anHidden[iColumn] = null;
- }
-
- if ( oCol.fnCreatedCell )
- {
- oCol.fnCreatedCell.call( oSettings.oInstance,
- nCell, _fnGetCellData( oSettings, iRow, iColumn, 'display' ), oData._aData, iRow, iColumn
- );
- }
}
}
}
-
- /* Row created callbacks */
- if ( oSettings.aoRowCreatedCallback.length !== 0 )
- {
- for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ )
- {
- oData = oSettings.aoData[i];
- _fnCallbackFire( oSettings, 'aoRowCreatedCallback', null, [oData.nTr, oData._aData, i] );
- }
- }
- }
-
-
- /**
- * Take a TR element and convert it to an index in aoData
- * @param {object} oSettings dataTables settings object
- * @param {node} n the TR element to find
- * @returns {int} index if the node is found, null if not
- * @memberof DataTable#oApi
- */
- function _fnNodeToDataIndex( oSettings, n )
- {
- return (n._DT_RowIndex!==undefined) ? n._DT_RowIndex : null;
}
-
-
- /**
- * Take a TD element and convert it into a column data index (not the visible index)
- * @param {object} oSettings dataTables settings object
- * @param {int} iRow The row number the TD/TH can be found in
- * @param {node} n The TD/TH element to find
- * @returns {int} index if the node is found, -1 if not
- * @memberof DataTable#oApi
- */
- function _fnNodeToColumnIndex( oSettings, iRow, n )
+
+ // Statically defined columns array
+ if ( aoCols )
{
- var anCells = _fnGetTdNodes( oSettings, iRow );
-
- for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
+ for ( i=0, iLen=aoCols.length ; i<iLen ; i++ )
{
- if ( anCells[i] === n )
- {
- return i;
- }
+ fn( i, aoCols[i] );
}
- return -1;
}
-
-
- /**
- * Get an array of data for a given row from the internal data cache
- * @param {object} oSettings dataTables settings object
- * @param {int} iRow aoData row id
- * @param {string} sSpecific data get type ('type' 'filter' 'sort')
- * @param {array} aiColumns Array of column indexes to get data from
- * @returns {array} Data array
- * @memberof DataTable#oApi
- */
- function _fnGetRowData( oSettings, iRow, sSpecific, aiColumns )
+ }
+
+ /**
+ * Add a data array to the table, creating DOM node etc. This is the parallel to
+ * _fnGatherData, but for adding rows from a Javascript source, rather than a
+ * DOM source.
+ * @param {object} oSettings dataTables settings object
+ * @param {array} aData data array to be added
+ * @param {node} [nTr] TR element to add to the table - optional. If not given,
+ * DataTables will create a row automatically
+ * @param {array} [anTds] Array of TD|TH elements for the row - must be given
+ * if nTr is.
+ * @returns {int} >=0 if successful (index of new aoData entry), -1 if failed
+ * @memberof DataTable#oApi
+ */
+ function _fnAddData ( oSettings, aDataIn, nTr, anTds )
+ {
+ /* Create the object for storing information about this new row */
+ var iRow = oSettings.aoData.length;
+ var oData = $.extend( true, {}, DataTable.models.oRow, {
+ src: nTr ? 'dom' : 'data'
+ } );
+
+ oData._aData = aDataIn;
+ oSettings.aoData.push( oData );
+
+ /* Create the cells */
+ var nTd, sThisType;
+ var columns = oSettings.aoColumns;
+ for ( var i=0, iLen=columns.length ; i<iLen ; i++ )
{
- var out = [];
- for ( var i=0, iLen=aiColumns.length ; i<iLen ; i++ )
- {
- out.push( _fnGetCellData( oSettings, iRow, aiColumns[i], sSpecific ) );
+ // When working with a row, the data source object must be populated. In
+ // all other cases, the data source object is already populated, so we
+ // don't overwrite it, which might break bindings etc
+ if ( nTr ) {
+ _fnSetCellData( oSettings, iRow, i, _fnGetCellData( oSettings, iRow, i ) );
}
- return out;
+ columns[i].sType = null;
}
-
-
- /**
- * Get the data for a given cell from the internal cache, taking into account data mapping
- * @param {object} oSettings dataTables settings object
- * @param {int} iRow aoData row id
- * @param {int} iCol Column index
- * @param {string} sSpecific data get type ('display', 'type' 'filter' 'sort')
- * @returns {*} Cell data
- * @memberof DataTable#oApi
- */
- function _fnGetCellData( oSettings, iRow, iCol, sSpecific )
+
+ /* Add to the display array */
+ oSettings.aiDisplayMaster.push( iRow );
+
+ /* Create the DOM information, or register it if already present */
+ if ( nTr || ! oSettings.oFeatures.bDeferRender )
{
- var sData;
- var oCol = oSettings.aoColumns[iCol];
- var oData = oSettings.aoData[iRow]._aData;
-
- if ( (sData=oCol.fnGetData( oData, sSpecific )) === undefined )
- {
- if ( oSettings.iDrawError != oSettings.iDraw && oCol.sDefaultContent === null )
- {
- _fnLog( oSettings, 0, "Requested unknown parameter "+
- (typeof oCol.mData=='function' ? '{mData function}' : "'"+oCol.mData+"'")+
- " from the data source for row "+iRow );
- oSettings.iDrawError = oSettings.iDraw;
- }
- return oCol.sDefaultContent;
- }
-
- /* When the data source is null, we can use default column data */
- if ( sData === null && oCol.sDefaultContent !== null )
- {
- sData = oCol.sDefaultContent;
- }
- else if ( typeof sData === 'function' )
- {
- /* If the data source is a function, then we run it and use the return */
- return sData();
- }
-
- if ( sSpecific == 'display' && sData === null )
- {
- return '';
+ _fnCreateTr( oSettings, iRow, nTr, anTds );
+ }
+
+ return iRow;
+ }
+
+
+ /**
+ * Add one or more TR elements to the table. Generally we'd expect to
+ * use this for reading data from a DOM sourced table, but it could be
+ * used for an TR element. Note that if a TR is given, it is used (i.e.
+ * it is not cloned).
+ * @param {object} settings dataTables settings object
+ * @param {array|node|jQuery} trs The TR element(s) to add to the table
+ * @returns {array} Array of indexes for the added rows
+ * @memberof DataTable#oApi
+ */
+ function _fnAddTr( settings, trs )
+ {
+ var row;
+
+ // Allow an individual node to be passed in
+ if ( ! (trs instanceof $) ) {
+ trs = $(trs);
+ }
+
+ return trs.map( function (i, el) {
+ row = _fnGetRowElements( settings, el );
+ return _fnAddData( settings, row.data, el, row.cells );
+ } );
+ }
+
+
+ /**
+ * Take a TR element and convert it to an index in aoData
+ * @param {object} oSettings dataTables settings object
+ * @param {node} n the TR element to find
+ * @returns {int} index if the node is found, null if not
+ * @memberof DataTable#oApi
+ */
+ function _fnNodeToDataIndex( oSettings, n )
+ {
+ return (n._DT_RowIndex!==undefined) ? n._DT_RowIndex : null;
+ }
+
+
+ /**
+ * Take a TD element and convert it into a column data index (not the visible index)
+ * @param {object} oSettings dataTables settings object
+ * @param {int} iRow The row number the TD/TH can be found in
+ * @param {node} n The TD/TH element to find
+ * @returns {int} index if the node is found, -1 if not
+ * @memberof DataTable#oApi
+ */
+ function _fnNodeToColumnIndex( oSettings, iRow, n )
+ {
+ return $.inArray( n, oSettings.aoData[ iRow ].anCells );
+ }
+
+
+ /**
+ * Get the data for a given cell from the internal cache, taking into account data mapping
+ * @param {object} settings dataTables settings object
+ * @param {int} rowIdx aoData row id
+ * @param {int} colIdx Column index
+ * @param {string} type data get type ('display', 'type' 'filter' 'sort')
+ * @returns {*} Cell data
+ * @memberof DataTable#oApi
+ */
+ function _fnGetCellData( settings, rowIdx, colIdx, type )
+ {
+ var draw = settings.iDraw;
+ var col = settings.aoColumns[colIdx];
+ var rowData = settings.aoData[rowIdx]._aData;
+ var defaultContent = col.sDefaultContent;
+ var cellData = col.fnGetData( rowData, type, {
+ settings: settings,
+ row: rowIdx,
+ col: colIdx
+ } );
+
+ if ( cellData === undefined ) {
+ if ( settings.iDrawError != draw && defaultContent === null ) {
+ _fnLog( settings, 0, "Requested unknown parameter "+
+ (typeof col.mData=='function' ? '{function}' : "'"+col.mData+"'")+
+ " for row "+rowIdx, 4 );
+ settings.iDrawError = draw;
}
- return sData;
+ return defaultContent;
}
-
-
- /**
- * Set the value for a specific cell, into the internal data cache
- * @param {object} oSettings dataTables settings object
- * @param {int} iRow aoData row id
- * @param {int} iCol Column index
- * @param {*} val Value to set
- * @memberof DataTable#oApi
- */
- function _fnSetCellData( oSettings, iRow, iCol, val )
+
+ /* When the data source is null, we can use default column data */
+ if ( (cellData === rowData || cellData === null) && defaultContent !== null ) {
+ cellData = defaultContent;
+ }
+ else if ( typeof cellData === 'function' ) {
+ // If the data source is a function, then we run it and use the return,
+ // executing in the scope of the data object (for instances)
+ return cellData.call( rowData );
+ }
+
+ if ( cellData === null && type == 'display' ) {
+ return '';
+ }
+ return cellData;
+ }
+
+
+ /**
+ * Set the value for a specific cell, into the internal data cache
+ * @param {object} settings dataTables settings object
+ * @param {int} rowIdx aoData row id
+ * @param {int} colIdx Column index
+ * @param {*} val Value to set
+ * @memberof DataTable#oApi
+ */
+ function _fnSetCellData( settings, rowIdx, colIdx, val )
+ {
+ var col = settings.aoColumns[colIdx];
+ var rowData = settings.aoData[rowIdx]._aData;
+
+ col.fnSetData( rowData, val, {
+ settings: settings,
+ row: rowIdx,
+ col: colIdx
+ } );
+ }
+
+
+ // Private variable that is used to match action syntax in the data property object
+ var __reArray = /\[.*?\]$/;
+ var __reFn = /\(\)$/;
+
+ /**
+ * Split string on periods, taking into account escaped periods
+ * @param {string} str String to split
+ * @return {array} Split string
+ */
+ function _fnSplitObjNotation( str )
+ {
+ return $.map( str.match(/(\\.|[^\.])+/g), function ( s ) {
+ return s.replace(/\\./g, '.');
+ } );
+ }
+
+
+ /**
+ * Return a function that can be used to get data from a source object, taking
+ * into account the ability to use nested objects as a source
+ * @param {string|int|function} mSource The data source for the object
+ * @returns {function} Data get function
+ * @memberof DataTable#oApi
+ */
+ function _fnGetObjectDataFn( mSource )
+ {
+ if ( $.isPlainObject( mSource ) )
{
- var oCol = oSettings.aoColumns[iCol];
- var oData = oSettings.aoData[iRow]._aData;
-
- oCol.fnSetData( oData, val );
+ /* Build an object of get functions, and wrap them in a single call */
+ var o = {};
+ $.each( mSource, function (key, val) {
+ if ( val ) {
+ o[key] = _fnGetObjectDataFn( val );
+ }
+ } );
+
+ return function (data, type, row, meta) {
+ var t = o[type] || o._;
+ return t !== undefined ?
+ t(data, type, row, meta) :
+ data;
+ };
}
-
-
- // Private variable that is used to match array syntax in the data property object
- var __reArray = /\[.*?\]$/;
-
- /**
- * Return a function that can be used to get data from a source object, taking
- * into account the ability to use nested objects as a source
- * @param {string|int|function} mSource The data source for the object
- * @returns {function} Data get function
- * @memberof DataTable#oApi
- */
- function _fnGetObjectDataFn( mSource )
+ else if ( mSource === null )
{
- if ( mSource === null )
- {
- /* Give an empty string for rendering / sorting etc */
- return function (data, type) {
- return null;
- };
- }
- else if ( typeof mSource === 'function' )
- {
- return function (data, type, extra) {
- return mSource( data, type, extra );
- };
- }
- else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 || mSource.indexOf('[') !== -1) )
- {
- /* If there is a . in the source string then the data source is in a
- * nested object so we loop over the data for each level to get the next
- * level down. On each loop we test for undefined, and if found immediately
- * return. This allows entire objects to be missing and sDefaultContent to
- * be used if defined, rather than throwing an error
- */
- var fetchData = function (data, type, src) {
- var a = src.split('.');
- var arrayNotation, out, innerSrc;
-
- if ( src !== "" )
- {
- for ( var i=0, iLen=a.length ; i<iLen ; i++ )
- {
- // Check if we are dealing with an array notation request
- arrayNotation = a[i].match(__reArray);
-
- if ( arrayNotation ) {
- a[i] = a[i].replace(__reArray, '');
-
- // Condition allows simply [] to be passed in
- if ( a[i] !== "" ) {
- data = data[ a[i] ];
- }
- out = [];
-
- // Get the remainder of the nested object to get
- a.splice( 0, i+1 );
- innerSrc = a.join('.');
-
- // Traverse each entry in the array getting the properties requested
- for ( var j=0, jLen=data.length ; j<jLen ; j++ ) {
- out.push( fetchData( data[j], type, innerSrc ) );
- }
-
- // If a string is given in between the array notation indicators, that
- // is used to join the strings together, otherwise an array is returned
- var join = arrayNotation[0].substring(1, arrayNotation[0].length-1);
- data = (join==="") ? out : out.join(join);
-
- // The inner call to fetchData has already traversed through the remainder
- // of the source requested, so we exit from the loop
- break;
- }
-
- if ( data === null || data[ a[i] ] === undefined )
- {
- return undefined;
- }
- data = data[ a[i] ];
- }
- }
-
- return data;
- };
-
- return function (data, type) {
- return fetchData( data, type, mSource );
- };
- }
- else
- {
- /* Array or flat object mapping */
- return function (data, type) {
- return data[mSource];
- };
- }
+ /* Give an empty string for rendering / sorting etc */
+ return function (data) { // type, row and meta also passed, but not used
+ return data;
+ };
}
-
-
- /**
- * Return a function that can be used to set data from a source object, taking
- * into account the ability to use nested objects as a source
- * @param {string|int|function} mSource The data source for the object
- * @returns {function} Data set function
- * @memberof DataTable#oApi
- */
- function _fnSetObjectDataFn( mSource )
+ else if ( typeof mSource === 'function' )
{
- if ( mSource === null )
- {
- /* Nothing to do when the data source is null */
- return function (data, val) {};
- }
- else if ( typeof mSource === 'function' )
- {
- return function (data, val) {
- mSource( data, 'set', val );
- };
- }
- else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 || mSource.indexOf('[') !== -1) )
- {
- /* Like the get, we need to get data from a nested object */
- var setData = function (data, val, src) {
- var a = src.split('.'), b;
- var arrayNotation, o, innerSrc;
-
- for ( var i=0, iLen=a.length-1 ; i<iLen ; i++ )
+ return function (data, type, row, meta) {
+ return mSource( data, type, row, meta );
+ };
+ }
+ else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
+ mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )
+ {
+ /* If there is a . in the source string then the data source is in a
+ * nested object so we loop over the data for each level to get the next
+ * level down. On each loop we test for undefined, and if found immediately
+ * return. This allows entire objects to be missing and sDefaultContent to
+ * be used if defined, rather than throwing an error
+ */
+ var fetchData = function (data, type, src) {
+ var arrayNotation, funcNotation, out, innerSrc;
+
+ if ( src !== "" )
+ {
+ var a = _fnSplitObjNotation( src );
+
+ for ( var i=0, iLen=a.length ; i<iLen ; i++ )
{
- // Check if we are dealing with an array notation request
+ // Check if we are dealing with special notation
arrayNotation = a[i].match(__reArray);
-
+ funcNotation = a[i].match(__reFn);
+
if ( arrayNotation )
{
+ // Array notation
a[i] = a[i].replace(__reArray, '');
- data[ a[i] ] = [];
-
- // Get the remainder of the nested object to set so we can recurse
- b = a.slice();
- b.splice( 0, i+1 );
- innerSrc = b.join('.');
-
- // Traverse each entry in the array setting the properties requested
- for ( var j=0, jLen=val.length ; j<jLen ; j++ )
- {
- o = {};
- setData( o, val[j], innerSrc );
- data[ a[i] ].push( o );
+
+ // Condition allows simply [] to be passed in
+ if ( a[i] !== "" ) {
+ data = data[ a[i] ];
}
-
- // The inner call to setData has already traversed through the remainder
- // of the source and has set the data, thus we can exit here
- return;
+ out = [];
+
+ // Get the remainder of the nested object to get
+ a.splice( 0, i+1 );
+ innerSrc = a.join('.');
+
+ // Traverse each entry in the array getting the properties requested
+ for ( var j=0, jLen=data.length ; j<jLen ; j++ ) {
+ out.push( fetchData( data[j], type, innerSrc ) );
+ }
+
+ // If a string is given in between the array notation indicators, that
+ // is used to join the strings together, otherwise an array is returned
+ var join = arrayNotation[0].substring(1, arrayNotation[0].length-1);
+ data = (join==="") ? out : out.join(join);
+
+ // The inner call to fetchData has already traversed through the remainder
+ // of the source requested, so we exit from the loop
+ break;
}
-
- // If the nested object doesn't currently exist - since we are
- // trying to set the value - create it
- if ( data[ a[i] ] === null || data[ a[i] ] === undefined )
+ else if ( funcNotation )
+ {
+ // Function call
+ a[i] = a[i].replace(__reFn, '');
+ data = data[ a[i] ]();
+ continue;
+ }
+
+ if ( data === null || data[ a[i] ] === undefined )
{
- data[ a[i] ] = {};
+ return undefined;
}
data = data[ a[i] ];
}
-
- // If array notation is used, we just want to strip it and use the property name
- // and assign the value. If it isn't used, then we get the result we want anyway
- data[ a[a.length-1].replace(__reArray, '') ] = val;
- };
-
- return function (data, val) {
- return setData( data, val, mSource );
- };
- }
- else
- {
- /* Array or flat object mapping */
- return function (data, val) {
- data[mSource] = val;
- };
- }
- }
-
-
- /**
- * Return an array with the full table data
- * @param {object} oSettings dataTables settings object
- * @returns array {array} aData Master data array
- * @memberof DataTable#oApi
- */
- function _fnGetDataMaster ( oSettings )
- {
- var aData = [];
- var iLen = oSettings.aoData.length;
- for ( var i=0 ; i<iLen; i++ )
- {
- aData.push( oSettings.aoData[i]._aData );
- }
- return aData;
+ }
+
+ return data;
+ };
+
+ return function (data, type) { // row and meta also passed, but not used
+ return fetchData( data, type, mSource );
+ };
}
-
-
- /**
- * Nuke the table
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnClearTable( oSettings )
+ else
{
- oSettings.aoData.splice( 0, oSettings.aoData.length );
- oSettings.aiDisplayMaster.splice( 0, oSettings.aiDisplayMaster.length );
- oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length );
- _fnCalculateEnd( oSettings );
+ /* Array or flat object mapping */
+ return function (data, type) { // row and meta also passed, but not used
+ return data[mSource];
+ };
}
-
-
- /**
- * Take an array of integers (index array) and remove a target integer (value - not
- * the key!)
- * @param {array} a Index array to target
- * @param {int} iTarget value to find
- * @memberof DataTable#oApi
- */
- function _fnDeleteIndex( a, iTarget )
+ }
+
+
+ /**
+ * Return a function that can be used to set data from a source object, taking
+ * into account the ability to use nested objects as a source
+ * @param {string|int|function} mSource The data source for the object
+ * @returns {function} Data set function
+ * @memberof DataTable#oApi
+ */
+ function _fnSetObjectDataFn( mSource )
+ {
+ if ( $.isPlainObject( mSource ) )
{
- var iTargetIndex = -1;
-
- for ( var i=0, iLen=a.length ; i<iLen ; i++ )
- {
- if ( a[i] == iTarget )
- {
- iTargetIndex = i;
- }
- else if ( a[i] > iTarget )
- {
- a[i]--;
- }
- }
-
- if ( iTargetIndex != -1 )
- {
- a.splice( iTargetIndex, 1 );
- }
+ /* Unlike get, only the underscore (global) option is used for for
+ * setting data since we don't know the type here. This is why an object
+ * option is not documented for `mData` (which is read/write), but it is
+ * for `mRender` which is read only.
+ */
+ return _fnSetObjectDataFn( mSource._ );
}
-
-
- /**
- * Call the developer defined fnRender function for a given cell (row/column) with
- * the required parameters and return the result.
- * @param {object} oSettings dataTables settings object
- * @param {int} iRow aoData index for the row
- * @param {int} iCol aoColumns index for the column
- * @returns {*} Return of the developer's fnRender function
- * @memberof DataTable#oApi
- */
- function _fnRender( oSettings, iRow, iCol )
+ else if ( mSource === null )
{
- var oCol = oSettings.aoColumns[iCol];
-
- return oCol.fnRender( {
- "iDataRow": iRow,
- "iDataColumn": iCol,
- "oSettings": oSettings,
- "aData": oSettings.aoData[iRow]._aData,
- "mDataProp": oCol.mData
- }, _fnGetCellData(oSettings, iRow, iCol, 'display') );
+ /* Nothing to do when the data source is null */
+ return function () {};
}
- /**
- * Create a new TR element (and it's TD children) for a row
- * @param {object} oSettings dataTables settings object
- * @param {int} iRow Row to consider
- * @memberof DataTable#oApi
- */
- function _fnCreateTr ( oSettings, iRow )
+ else if ( typeof mSource === 'function' )
{
- var oData = oSettings.aoData[iRow];
- var nTd;
-
- if ( oData.nTr === null )
- {
- oData.nTr = document.createElement('tr');
-
- /* Use a private property on the node to allow reserve mapping from the node
- * to the aoData array for fast look up
- */
- oData.nTr._DT_RowIndex = iRow;
-
- /* Special parameters can be given by the data source to be used on the row */
- if ( oData._aData.DT_RowId )
- {
- oData.nTr.id = oData._aData.DT_RowId;
- }
-
- if ( oData._aData.DT_RowClass )
- {
- oData.nTr.className = oData._aData.DT_RowClass;
- }
-
- /* Process each column */
- for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
- {
- var oCol = oSettings.aoColumns[i];
- nTd = document.createElement( oCol.sCellType );
-
- /* Render if needed - if bUseRendered is true then we already have the rendered
- * value in the data source - so can just use that
- */
- nTd.innerHTML = (typeof oCol.fnRender === 'function' && (!oCol.bUseRendered || oCol.mData === null)) ?
- _fnRender( oSettings, iRow, i ) :
- _fnGetCellData( oSettings, iRow, i, 'display' );
-
- /* Add user defined class */
- if ( oCol.sClass !== null )
- {
- nTd.className = oCol.sClass;
- }
-
- if ( oCol.bVisible )
- {
- oData.nTr.appendChild( nTd );
- oData._anHidden[i] = null;
- }
- else
- {
- oData._anHidden[i] = nTd;
- }
-
- if ( oCol.fnCreatedCell )
- {
- oCol.fnCreatedCell.call( oSettings.oInstance,
- nTd, _fnGetCellData( oSettings, iRow, i, 'display' ), oData._aData, iRow, i
- );
- }
- }
-
- _fnCallbackFire( oSettings, 'aoRowCreatedCallback', null, [oData.nTr, oData._aData, iRow] );
- }
+ return function (data, val, meta) {
+ mSource( data, 'set', val, meta );
+ };
}
-
-
- /**
- * Create the HTML header for the table
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnBuildHead( oSettings )
+ else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
+ mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )
{
- var i, nTh, iLen, j, jLen;
- var iThs = $('th, td', oSettings.nTHead).length;
- var iCorrector = 0;
- var jqChildren;
-
- /* If there is a header in place - then use it - otherwise it's going to get nuked... */
- if ( iThs !== 0 )
- {
- /* We've got a thead from the DOM, so remove hidden columns and apply width to vis cols */
- for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
+ /* Like the get, we need to get data from a nested object */
+ var setData = function (data, val, src) {
+ var a = _fnSplitObjNotation( src ), b;
+ var aLast = a[a.length-1];
+ var arrayNotation, funcNotation, o, innerSrc;
+
+ for ( var i=0, iLen=a.length-1 ; i<iLen ; i++ )
{
- nTh = oSettings.aoColumns[i].nTh;
- nTh.setAttribute('role', 'columnheader');
- if ( oSettings.aoColumns[i].bSortable )
- {
- nTh.setAttribute('tabindex', oSettings.iTabIndex);
- nTh.setAttribute('aria-controls', oSettings.sTableId);
- }
-
- if ( oSettings.aoColumns[i].sClass !== null )
+ // Check if we are dealing with an array notation request
+ arrayNotation = a[i].match(__reArray);
+ funcNotation = a[i].match(__reFn);
+
+ if ( arrayNotation )
{
- $(nTh).addClass( oSettings.aoColumns[i].sClass );
+ a[i] = a[i].replace(__reArray, '');
+ data[ a[i] ] = [];
+
+ // Get the remainder of the nested object to set so we can recurse
+ b = a.slice();
+ b.splice( 0, i+1 );
+ innerSrc = b.join('.');
+
+ // Traverse each entry in the array setting the properties requested
+ for ( var j=0, jLen=val.length ; j<jLen ; j++ )
+ {
+ o = {};
+ setData( o, val[j], innerSrc );
+ data[ a[i] ].push( o );
+ }
+
+ // The inner call to setData has already traversed through the remainder
+ // of the source and has set the data, thus we can exit here
+ return;
}
-
- /* Set the title of the column if it is user defined (not what was auto detected) */
- if ( oSettings.aoColumns[i].sTitle != nTh.innerHTML )
+ else if ( funcNotation )
{
- nTh.innerHTML = oSettings.aoColumns[i].sTitle;
+ // Function call
+ a[i] = a[i].replace(__reFn, '');
+ data = data[ a[i] ]( val );
}
- }
- }
- else
- {
- /* We don't have a header in the DOM - so we are going to have to create one */
- var nTr = document.createElement( "tr" );
-
- for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
- {
- nTh = oSettings.aoColumns[i].nTh;
- nTh.innerHTML = oSettings.aoColumns[i].sTitle;
- nTh.setAttribute('tabindex', '0');
-
- if ( oSettings.aoColumns[i].sClass !== null )
+
+ // If the nested object doesn't currently exist - since we are
+ // trying to set the value - create it
+ if ( data[ a[i] ] === null || data[ a[i] ] === undefined )
{
- $(nTh).addClass( oSettings.aoColumns[i].sClass );
+ data[ a[i] ] = {};
}
-
- nTr.appendChild( nTh );
+ data = data[ a[i] ];
}
- $(oSettings.nTHead).html( '' )[0].appendChild( nTr );
- _fnDetectHeader( oSettings.aoHeader, oSettings.nTHead );
- }
-
- /* ARIA role for the rows */
- $(oSettings.nTHead).children('tr').attr('role', 'row');
-
- /* Add the extra markup needed by jQuery UI's themes */
- if ( oSettings.bJUI )
- {
- for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
+
+ // Last item in the input - i.e, the actual set
+ if ( aLast.match(__reFn ) )
{
- nTh = oSettings.aoColumns[i].nTh;
-
- var nDiv = document.createElement('div');
- nDiv.className = oSettings.oClasses.sSortJUIWrapper;
- $(nTh).contents().appendTo(nDiv);
-
- var nSpan = document.createElement('span');
- nSpan.className = oSettings.oClasses.sSortIcon;
- nDiv.appendChild( nSpan );
- nTh.appendChild( nDiv );
+ // Function call
+ data = data[ aLast.replace(__reFn, '') ]( val );
}
- }
-
- if ( oSettings.oFeatures.bSort )
- {
- for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
+ else
{
- if ( oSettings.aoColumns[i].bSortable !== false )
- {
- _fnSortAttachListener( oSettings, oSettings.aoColumns[i].nTh, i );
- }
- else
- {
- $(oSettings.aoColumns[i].nTh).addClass( oSettings.oClasses.sSortableNone );
- }
+ // If array notation is used, we just want to strip it and use the property name
+ // and assign the value. If it isn't used, then we get the result we want anyway
+ data[ aLast.replace(__reArray, '') ] = val;
}
- }
-
- /* Deal with the footer - add classes if required */
- if ( oSettings.oClasses.sFooterTH !== "" )
+ };
+
+ return function (data, val) { // meta is also passed in, but not used
+ return setData( data, val, mSource );
+ };
+ }
+ else
+ {
+ /* Array or flat object mapping */
+ return function (data, val) { // meta is also passed in, but not used
+ data[mSource] = val;
+ };
+ }
+ }
+
+
+ /**
+ * Return an array with the full table data
+ * @param {object} oSettings dataTables settings object
+ * @returns array {array} aData Master data array
+ * @memberof DataTable#oApi
+ */
+ function _fnGetDataMaster ( settings )
+ {
+ return _pluck( settings.aoData, '_aData' );
+ }
+
+
+ /**
+ * Nuke the table
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnClearTable( settings )
+ {
+ settings.aoData.length = 0;
+ settings.aiDisplayMaster.length = 0;
+ settings.aiDisplay.length = 0;
+ }
+
+
+ /**
+ * Take an array of integers (index array) and remove a target integer (value - not
+ * the key!)
+ * @param {array} a Index array to target
+ * @param {int} iTarget value to find
+ * @memberof DataTable#oApi
+ */
+ function _fnDeleteIndex( a, iTarget, splice )
+ {
+ var iTargetIndex = -1;
+
+ for ( var i=0, iLen=a.length ; i<iLen ; i++ )
+ {
+ if ( a[i] == iTarget )
{
- $(oSettings.nTFoot).children('tr').children('th').addClass( oSettings.oClasses.sFooterTH );
+ iTargetIndex = i;
}
-
- /* Cache the footer elements */
- if ( oSettings.nTFoot !== null )
+ else if ( a[i] > iTarget )
{
- var anCells = _fnGetUniqueThs( oSettings, null, oSettings.aoFooter );
- for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
- {
- if ( anCells[i] )
- {
- oSettings.aoColumns[i].nTf = anCells[i];
- if ( oSettings.aoColumns[i].sClass )
- {
- $(anCells[i]).addClass( oSettings.aoColumns[i].sClass );
- }
- }
- }
+ a[i]--;
}
}
-
-
- /**
- * Draw the header (or footer) element based on the column visibility states. The
- * methodology here is to use the layout array from _fnDetectHeader, modified for
- * the instantaneous column visibility, to construct the new layout. The grid is
- * traversed over cell at a time in a rows x columns grid fashion, although each
- * cell insert can cover multiple elements in the grid - which is tracks using the
- * aApplied array. Cell inserts in the grid will only occur where there isn't
- * already a cell in that position.
- * @param {object} oSettings dataTables settings object
- * @param array {objects} aoSource Layout array from _fnDetectHeader
- * @param {boolean} [bIncludeHidden=false] If true then include the hidden columns in the calc,
- * @memberof DataTable#oApi
- */
- function _fnDrawHead( oSettings, aoSource, bIncludeHidden )
+
+ if ( iTargetIndex != -1 && splice === undefined )
{
- var i, iLen, j, jLen, k, kLen, n, nLocalTr;
- var aoLocal = [];
- var aApplied = [];
- var iColumns = oSettings.aoColumns.length;
- var iRowspan, iColspan;
-
- if ( bIncludeHidden === undefined )
- {
- bIncludeHidden = false;
- }
-
- /* Make a copy of the master layout array, but without the visible columns in it */
- for ( i=0, iLen=aoSource.length ; i<iLen ; i++ )
- {
- aoLocal[i] = aoSource[i].slice();
- aoLocal[i].nTr = aoSource[i].nTr;
-
- /* Remove any columns which are currently hidden */
- for ( j=iColumns-1 ; j>=0 ; j-- )
- {
- if ( !oSettings.aoColumns[j].bVisible && !bIncludeHidden )
- {
- aoLocal[i].splice( j, 1 );
- }
- }
-
- /* Prep the applied array - it needs an element for each row */
- aApplied.push( [] );
+ a.splice( iTargetIndex, 1 );
+ }
+ }
+
+
+ /**
+ * Mark cached data as invalid such that a re-read of the data will occur when
+ * the cached data is next requested. Also update from the data source object.
+ *
+ * @param {object} settings DataTables settings object
+ * @param {int} rowIdx Row index to invalidate
+ * @param {string} [src] Source to invalidate from: undefined, 'auto', 'dom'
+ * or 'data'
+ * @param {int} [colIdx] Column index to invalidate. If undefined the whole
+ * row will be invalidated
+ * @memberof DataTable#oApi
+ *
+ * @todo For the modularisation of v1.11 this will need to become a callback, so
+ * the sort and filter methods can subscribe to it. That will required
+ * initialisation options for sorting, which is why it is not already baked in
+ */
+ function _fnInvalidate( settings, rowIdx, src, colIdx )
+ {
+ var row = settings.aoData[ rowIdx ];
+ var i, ien;
+ var cellWrite = function ( cell, col ) {
+ // This is very frustrating, but in IE if you just write directly
+ // to innerHTML, and elements that are overwritten are GC'ed,
+ // even if there is a reference to them elsewhere
+ while ( cell.childNodes.length ) {
+ cell.removeChild( cell.firstChild );
}
-
- for ( i=0, iLen=aoLocal.length ; i<iLen ; i++ )
- {
- nLocalTr = aoLocal[i].nTr;
-
- /* All cells are going to be replaced, so empty out the row */
- if ( nLocalTr )
- {
- while( (n = nLocalTr.firstChild) )
- {
- nLocalTr.removeChild( n );
- }
+
+ cell.innerHTML = _fnGetCellData( settings, rowIdx, col, 'display' );
+ };
+
+ // Are we reading last data from DOM or the data object?
+ if ( src === 'dom' || ((! src || src === 'auto') && row.src === 'dom') ) {
+ // Read the data from the DOM
+ row._aData = _fnGetRowElements(
+ settings, row, colIdx, colIdx === undefined ? undefined : row._aData
+ )
+ .data;
+ }
+ else {
+ // Reading from data object, update the DOM
+ var cells = row.anCells;
+
+ if ( cells ) {
+ if ( colIdx !== undefined ) {
+ cellWrite( cells[colIdx], colIdx );
}
-
- for ( j=0, jLen=aoLocal[i].length ; j<jLen ; j++ )
- {
- iRowspan = 1;
- iColspan = 1;
-
- /* Check to see if there is already a cell (row/colspan) covering our target
- * insert point. If there is, then there is nothing to do.
- */
- if ( aApplied[i][j] === undefined )
- {
- nLocalTr.appendChild( aoLocal[i][j].cell );
- aApplied[i][j] = 1;
-
- /* Expand the cell to cover as many rows as needed */
- while ( aoLocal[i+iRowspan] !== undefined &&
- aoLocal[i][j].cell == aoLocal[i+iRowspan][j].cell )
- {
- aApplied[i+iRowspan][j] = 1;
- iRowspan++;
- }
-
- /* Expand the cell to cover as many columns as needed */
- while ( aoLocal[i][j+iColspan] !== undefined &&
- aoLocal[i][j].cell == aoLocal[i][j+iColspan].cell )
- {
- /* Must update the applied array over the rows for the columns */
- for ( k=0 ; k<iRowspan ; k++ )
- {
- aApplied[i+k][j+iColspan] = 1;
- }
- iColspan++;
- }
-
- /* Do the actual expansion in the DOM */
- aoLocal[i][j].cell.rowSpan = iRowspan;
- aoLocal[i][j].cell.colSpan = iColspan;
+ else {
+ for ( i=0, ien=cells.length ; i<ien ; i++ ) {
+ cellWrite( cells[i], i );
}
}
}
}
-
-
- /**
- * Insert the required TR nodes into the table for display
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnDraw( oSettings )
- {
- /* Provide a pre-callback function which can be used to cancel the draw is false is returned */
- var aPreDraw = _fnCallbackFire( oSettings, 'aoPreDrawCallback', 'preDraw', [oSettings] );
- if ( $.inArray( false, aPreDraw ) !== -1 )
- {
- _fnProcessingDisplay( oSettings, false );
- return;
+
+ // For both row and cell invalidation, the cached data for sorting and
+ // filtering is nulled out
+ row._aSortData = null;
+ row._aFilterData = null;
+
+ // Invalidate the type for a specific column (if given) or all columns since
+ // the data might have changed
+ var cols = settings.aoColumns;
+ if ( colIdx !== undefined ) {
+ cols[ colIdx ].sType = null;
+ }
+ else {
+ for ( i=0, ien=cols.length ; i<ien ; i++ ) {
+ cols[i].sType = null;
}
-
- var i, iLen, n;
- var anRows = [];
- var iRowCount = 0;
- var iStripes = oSettings.asStripeClasses.length;
- var iOpenRows = oSettings.aoOpenRows.length;
-
- oSettings.bDrawing = true;
-
- /* Check and see if we have an initial draw position from state saving */
- if ( oSettings.iInitDisplayStart !== undefined && oSettings.iInitDisplayStart != -1 )
- {
- if ( oSettings.oFeatures.bServerSide )
- {
- oSettings._iDisplayStart = oSettings.iInitDisplayStart;
- }
- else
- {
- oSettings._iDisplayStart = (oSettings.iInitDisplayStart >= oSettings.fnRecordsDisplay()) ?
- 0 : oSettings.iInitDisplayStart;
+
+ // Update DataTables special `DT_*` attributes for the row
+ _fnRowAttributes( row );
+ }
+ }
+
+
+ /**
+ * Build a data source object from an HTML row, reading the contents of the
+ * cells that are in the row.
+ *
+ * @param {object} settings DataTables settings object
+ * @param {node|object} TR element from which to read data or existing row
+ * object from which to re-read the data from the cells
+ * @param {int} [colIdx] Optional column index
+ * @param {array|object} [d] Data source object. If `colIdx` is given then this
+ * parameter should also be given and will be used to write the data into.
+ * Only the column in question will be written
+ * @returns {object} Object with two parameters: `data` the data read, in
+ * document order, and `cells` and array of nodes (they can be useful to the
+ * caller, so rather than needing a second traversal to get them, just return
+ * them from here).
+ * @memberof DataTable#oApi
+ */
+ function _fnGetRowElements( settings, row, colIdx, d )
+ {
+ var
+ tds = [],
+ td = row.firstChild,
+ name, col, o, i=0, contents,
+ columns = settings.aoColumns,
+ objectRead = settings._rowReadObject;
+
+ // Allow the data object to be passed in, or construct
+ d = d || objectRead ? {} : [];
+
+ var attr = function ( str, td ) {
+ if ( typeof str === 'string' ) {
+ var idx = str.indexOf('@');
+
+ if ( idx !== -1 ) {
+ var attr = str.substring( idx+1 );
+ var setter = _fnSetObjectDataFn( str );
+ setter( d, td.getAttribute( attr ) );
}
- oSettings.iInitDisplayStart = -1;
- _fnCalculateEnd( oSettings );
- }
-
- /* Server-side processing draw intercept */
- if ( oSettings.bDeferLoading )
- {
- oSettings.bDeferLoading = false;
- oSettings.iDraw++;
}
- else if ( !oSettings.oFeatures.bServerSide )
- {
- oSettings.iDraw++;
- }
- else if ( !oSettings.bDestroying && !_fnAjaxUpdate( oSettings ) )
- {
- return;
- }
-
- if ( oSettings.aiDisplay.length !== 0 )
- {
- var iStart = oSettings._iDisplayStart;
- var iEnd = oSettings._iDisplayEnd;
-
- if ( oSettings.oFeatures.bServerSide )
- {
- iStart = 0;
- iEnd = oSettings.aoData.length;
- }
-
- for ( var j=iStart ; j<iEnd ; j++ )
- {
- var aoData = oSettings.aoData[ oSettings.aiDisplay[j] ];
- if ( aoData.nTr === null )
- {
- _fnCreateTr( oSettings, oSettings.aiDisplay[j] );
- }
-
- var nRow = aoData.nTr;
-
- /* Remove the old striping classes and then add the new one */
- if ( iStripes !== 0 )
- {
- var sStripe = oSettings.asStripeClasses[ iRowCount % iStripes ];
- if ( aoData._sRowStripe != sStripe )
- {
- $(nRow).removeClass( aoData._sRowStripe ).addClass( sStripe );
- aoData._sRowStripe = sStripe;
- }
- }
-
- /* Row callback functions - might want to manipulate the row */
- _fnCallbackFire( oSettings, 'aoRowCallback', null,
- [nRow, oSettings.aoData[ oSettings.aiDisplay[j] ]._aData, iRowCount, j] );
-
- anRows.push( nRow );
- iRowCount++;
-
- /* If there is an open row - and it is attached to this parent - attach it on redraw */
- if ( iOpenRows !== 0 )
- {
- for ( var k=0 ; k<iOpenRows ; k++ )
- {
- if ( nRow == oSettings.aoOpenRows[k].nParent )
- {
- anRows.push( oSettings.aoOpenRows[k].nTr );
- break;
- }
+ };
+
+ // Read data from a cell and store into the data object
+ var cellProcess = function ( cell ) {
+ if ( colIdx === undefined || colIdx === i ) {
+ col = columns[i];
+ contents = $.trim(cell.innerHTML);
+
+ if ( col && col._bAttrSrc ) {
+ var setter = _fnSetObjectDataFn( col.mData._ );
+ setter( d, contents );
+
+ attr( col.mData.sort, cell );
+ attr( col.mData.type, cell );
+ attr( col.mData.filter, cell );
+ }
+ else {
+ // Depending on the `data` option for the columns the data can
+ // be read to either an object or an array.
+ if ( objectRead ) {
+ if ( ! col._setter ) {
+ // Cache the setter function
+ col._setter = _fnSetObjectDataFn( col.mData );
}
+ col._setter( d, contents );
}
- }
- }
- else
- {
- /* Table is empty - create a row with an empty message in it */
- anRows[ 0 ] = document.createElement( 'tr' );
-
- if ( oSettings.asStripeClasses[0] )
- {
- anRows[ 0 ].className = oSettings.asStripeClasses[0];
- }
-
- var oLang = oSettings.oLanguage;
- var sZero = oLang.sZeroRecords;
- if ( oSettings.iDraw == 1 && oSettings.sAjaxSource !== null && !oSettings.oFeatures.bServerSide )
- {
- sZero = oLang.sLoadingRecords;
- }
- else if ( oLang.sEmptyTable && oSettings.fnRecordsTotal() === 0 )
- {
- sZero = oLang.sEmptyTable;
- }
-
- var nTd = document.createElement( 'td' );
- nTd.setAttribute( 'valign', "top" );
- nTd.colSpan = _fnVisbleColumns( oSettings );
- nTd.className = oSettings.oClasses.sRowEmpty;
- nTd.innerHTML = _fnInfoMacros( oSettings, sZero );
-
- anRows[ iRowCount ].appendChild( nTd );
- }
-
- /* Header and footer callbacks */
- _fnCallbackFire( oSettings, 'aoHeaderCallback', 'header', [ $(oSettings.nTHead).children('tr')[0],
- _fnGetDataMaster( oSettings ), oSettings._iDisplayStart, oSettings.fnDisplayEnd(), oSettings.aiDisplay ] );
-
- _fnCallbackFire( oSettings, 'aoFooterCallback', 'footer', [ $(oSettings.nTFoot).children('tr')[0],
- _fnGetDataMaster( oSettings ), oSettings._iDisplayStart, oSettings.fnDisplayEnd(), oSettings.aiDisplay ] );
-
- /*
- * Need to remove any old row from the display - note we can't just empty the tbody using
- * $().html('') since this will unbind the jQuery event handlers (even although the node
- * still exists!) - equally we can't use innerHTML, since IE throws an exception.
- */
- var
- nAddFrag = document.createDocumentFragment(),
- nRemoveFrag = document.createDocumentFragment(),
- nBodyPar, nTrs;
-
- if ( oSettings.nTBody )
- {
- nBodyPar = oSettings.nTBody.parentNode;
- nRemoveFrag.appendChild( oSettings.nTBody );
-
- /* When doing infinite scrolling, only remove child rows when sorting, filtering or start
- * up. When not infinite scroll, always do it.
- */
- if ( !oSettings.oScroll.bInfinite || !oSettings._bInitComplete ||
- oSettings.bSorted || oSettings.bFiltered )
- {
- while( (n = oSettings.nTBody.firstChild) )
- {
- oSettings.nTBody.removeChild( n );
+ else {
+ d[i] = contents;
}
}
-
- /* Put the draw table into the dom */
- for ( i=0, iLen=anRows.length ; i<iLen ; i++ )
- {
- nAddFrag.appendChild( anRows[i] );
- }
-
- oSettings.nTBody.appendChild( nAddFrag );
- if ( nBodyPar !== null )
- {
- nBodyPar.appendChild( oSettings.nTBody );
- }
}
-
- /* Call all required callback functions for the end of a draw */
- _fnCallbackFire( oSettings, 'aoDrawCallback', 'draw', [oSettings] );
-
- /* Draw is complete, sorting and filtering must be as well */
- oSettings.bSorted = false;
- oSettings.bFiltered = false;
- oSettings.bDrawing = false;
-
- if ( oSettings.oFeatures.bServerSide )
- {
- _fnProcessingDisplay( oSettings, false );
- if ( !oSettings._bInitComplete )
- {
- _fnInitComplete( oSettings );
+
+ i++;
+ };
+
+ if ( td ) {
+ // `tr` element was passed in
+ while ( td ) {
+ name = td.nodeName.toUpperCase();
+
+ if ( name == "TD" || name == "TH" ) {
+ cellProcess( td );
+ tds.push( td );
}
+
+ td = td.nextSibling;
}
}
-
-
- /**
- * Redraw the table - taking account of the various features which are enabled
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnReDraw( oSettings )
- {
- if ( oSettings.oFeatures.bSort )
- {
- /* Sorting will refilter and draw for us */
- _fnSort( oSettings, oSettings.oPreviousSearch );
- }
- else if ( oSettings.oFeatures.bFilter )
- {
- /* Filtering will redraw for us */
- _fnFilterComplete( oSettings, oSettings.oPreviousSearch );
- }
- else
- {
- _fnCalculateEnd( oSettings );
- _fnDraw( oSettings );
+ else {
+ // Existing row object passed in
+ tds = row.anCells;
+
+ for ( var j=0, jen=tds.length ; j<jen ; j++ ) {
+ cellProcess( tds[j] );
}
}
-
-
- /**
- * Add the options to the page HTML for the table
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnAddOptionsHtml ( oSettings )
+
+ return {
+ data: d,
+ cells: tds
+ };
+ }
+ /**
+ * Create a new TR element (and it's TD children) for a row
+ * @param {object} oSettings dataTables settings object
+ * @param {int} iRow Row to consider
+ * @param {node} [nTrIn] TR element to add to the table - optional. If not given,
+ * DataTables will create a row automatically
+ * @param {array} [anTds] Array of TD|TH elements for the row - must be given
+ * if nTr is.
+ * @memberof DataTable#oApi
+ */
+ function _fnCreateTr ( oSettings, iRow, nTrIn, anTds )
+ {
+ var
+ row = oSettings.aoData[iRow],
+ rowData = row._aData,
+ cells = [],
+ nTr, nTd, oCol,
+ i, iLen;
+
+ if ( row.nTr === null )
{
- /*
- * Create a temporary, empty, div which we can later on replace with what we have generated
- * we do it this way to rendering the 'options' html offline - speed :-)
- */
- var nHolding = $('<div></div>')[0];
- oSettings.nTable.parentNode.insertBefore( nHolding, oSettings.nTable );
-
- /*
- * All DataTables are wrapped in a div
+ nTr = nTrIn || document.createElement('tr');
+
+ row.nTr = nTr;
+ row.anCells = cells;
+
+ /* Use a private property on the node to allow reserve mapping from the node
+ * to the aoData array for fast look up
*/
- oSettings.nTableWrapper = $('<div id="'+oSettings.sTableId+'_wrapper" class="'+oSettings.oClasses.sWrapper+'" role="grid"></div>')[0];
- oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling;
-
- /* Track where we want to insert the option */
- var nInsertNode = oSettings.nTableWrapper;
-
- /* Loop over the user set positioning and place the elements as needed */
- var aDom = oSettings.sDom.split('');
- var nTmp, iPushFeature, cOption, nNewNode, cNext, sAttr, j;
- for ( var i=0 ; i<aDom.length ; i++ )
+ nTr._DT_RowIndex = iRow;
+
+ /* Special parameters can be given by the data source to be used on the row */
+ _fnRowAttributes( row );
+
+ /* Process each column */
+ for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
- iPushFeature = 0;
- cOption = aDom[i];
-
- if ( cOption == '<' )
- {
- /* New container div */
- nNewNode = $('<div></div>')[0];
-
- /* Check to see if we should append an id and/or a class name to the container */
- cNext = aDom[i+1];
- if ( cNext == "'" || cNext == '"' )
- {
- sAttr = "";
- j = 2;
- while ( aDom[i+j] != cNext )
- {
- sAttr += aDom[i+j];
- j++;
- }
-
- /* Replace jQuery UI constants */
- if ( sAttr == "H" )
- {
- sAttr = oSettings.oClasses.sJUIHeader;
- }
- else if ( sAttr == "F" )
- {
- sAttr = oSettings.oClasses.sJUIFooter;
- }
-
- /* The attribute can be in the format of "#id.class", "#id" or "class" This logic
- * breaks the string into parts and applies them as needed
- */
- if ( sAttr.indexOf('.') != -1 )
- {
- var aSplit = sAttr.split('.');
- nNewNode.id = aSplit[0].substr(1, aSplit[0].length-1);
- nNewNode.className = aSplit[1];
- }
- else if ( sAttr.charAt(0) == "#" )
- {
- nNewNode.id = sAttr.substr(1, sAttr.length-1);
- }
- else
- {
- nNewNode.className = sAttr;
- }
-
- i += j; /* Move along the position array */
- }
-
- nInsertNode.appendChild( nNewNode );
- nInsertNode = nNewNode;
- }
- else if ( cOption == '>' )
- {
- /* End container div */
- nInsertNode = nInsertNode.parentNode;
- }
- else if ( cOption == 'l' && oSettings.oFeatures.bPaginate && oSettings.oFeatures.bLengthChange )
- {
- /* Length */
- nTmp = _fnFeatureHtmlLength( oSettings );
- iPushFeature = 1;
- }
- else if ( cOption == 'f' && oSettings.oFeatures.bFilter )
- {
- /* Filter */
- nTmp = _fnFeatureHtmlFilter( oSettings );
- iPushFeature = 1;
- }
- else if ( cOption == 'r' && oSettings.oFeatures.bProcessing )
- {
- /* pRocessing */
- nTmp = _fnFeatureHtmlProcessing( oSettings );
- iPushFeature = 1;
- }
- else if ( cOption == 't' )
+ oCol = oSettings.aoColumns[i];
+
+ nTd = nTrIn ? anTds[i] : document.createElement( oCol.sCellType );
+ cells.push( nTd );
+
+ // Need to create the HTML if new, or if a rendering function is defined
+ if ( !nTrIn || oCol.mRender || oCol.mData !== i )
{
- /* Table */
- nTmp = _fnFeatureHtmlTable( oSettings );
- iPushFeature = 1;
+ nTd.innerHTML = _fnGetCellData( oSettings, iRow, i, 'display' );
}
- else if ( cOption == 'i' && oSettings.oFeatures.bInfo )
+
+ /* Add user defined class */
+ if ( oCol.sClass )
{
- /* Info */
- nTmp = _fnFeatureHtmlInfo( oSettings );
- iPushFeature = 1;
+ nTd.className += ' '+oCol.sClass;
}
- else if ( cOption == 'p' && oSettings.oFeatures.bPaginate )
+
+ // Visibility - add or remove as required
+ if ( oCol.bVisible && ! nTrIn )
{
- /* Pagination */
- nTmp = _fnFeatureHtmlPaginate( oSettings );
- iPushFeature = 1;
+ nTr.appendChild( nTd );
}
- else if ( DataTable.ext.aoFeatures.length !== 0 )
+ else if ( ! oCol.bVisible && nTrIn )
{
- /* Plug-in features */
- var aoFeatures = DataTable.ext.aoFeatures;
- for ( var k=0, kLen=aoFeatures.length ; k<kLen ; k++ )
- {
- if ( cOption == aoFeatures[k].cFeature )
- {
- nTmp = aoFeatures[k].fnInit( oSettings );
- if ( nTmp )
- {
- iPushFeature = 1;
- }
- break;
- }
- }
+ nTd.parentNode.removeChild( nTd );
}
-
- /* Add to the 2D features array */
- if ( iPushFeature == 1 && nTmp !== null )
+
+ if ( oCol.fnCreatedCell )
{
- if ( typeof oSettings.aanFeatures[cOption] !== 'object' )
- {
- oSettings.aanFeatures[cOption] = [];
- }
- oSettings.aanFeatures[cOption].push( nTmp );
- nInsertNode.appendChild( nTmp );
+ oCol.fnCreatedCell.call( oSettings.oInstance,
+ nTd, _fnGetCellData( oSettings, iRow, i ), rowData, iRow, i
+ );
}
}
-
- /* Built our DOM structure - replace the holding div with what we want */
- nHolding.parentNode.replaceChild( oSettings.nTableWrapper, nHolding );
+
+ _fnCallbackFire( oSettings, 'aoRowCreatedCallback', null, [nTr, rowData, iRow] );
}
-
-
- /**
- * Use the DOM source to create up an array of header cells. The idea here is to
- * create a layout grid (array) of rows x columns, which contains a reference
- * to the cell that that point in the grid (regardless of col/rowspan), such that
- * any column / row could be removed and the new grid constructed
- * @param array {object} aLayout Array to store the calculated layout in
- * @param {node} nThead The header/footer element for the table
- * @memberof DataTable#oApi
- */
- function _fnDetectHeader ( aLayout, nThead )
- {
- var nTrs = $(nThead).children('tr');
- var nTr, nCell;
- var i, k, l, iLen, jLen, iColShifted, iColumn, iColspan, iRowspan;
- var bUnique;
- var fnShiftCol = function ( a, i, j ) {
- var k = a[i];
- while ( k[j] ) {
- j++;
- }
- return j;
- };
-
- aLayout.splice( 0, aLayout.length );
-
- /* We know how many rows there are in the layout - so prep it */
- for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
- {
- aLayout.push( [] );
+
+ // Remove once webkit bug 131819 and Chromium bug 365619 have been resolved
+ // and deployed
+ row.nTr.setAttribute( 'role', 'row' );
+ }
+
+
+ /**
+ * Add attributes to a row based on the special `DT_*` parameters in a data
+ * source object.
+ * @param {object} DataTables row object for the row to be modified
+ * @memberof DataTable#oApi
+ */
+ function _fnRowAttributes( row )
+ {
+ var tr = row.nTr;
+ var data = row._aData;
+
+ if ( tr ) {
+ if ( data.DT_RowId ) {
+ tr.id = data.DT_RowId;
}
-
- /* Calculate a layout array */
- for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
- {
- nTr = nTrs[i];
- iColumn = 0;
-
- /* For every cell in the row... */
- nCell = nTr.firstChild;
- while ( nCell ) {
- if ( nCell.nodeName.toUpperCase() == "TD" ||
- nCell.nodeName.toUpperCase() == "TH" )
- {
- /* Get the col and rowspan attributes from the DOM and sanitise them */
- iColspan = nCell.getAttribute('colspan') * 1;
- iRowspan = nCell.getAttribute('rowspan') * 1;
- iColspan = (!iColspan || iColspan===0 || iColspan===1) ? 1 : iColspan;
- iRowspan = (!iRowspan || iRowspan===0 || iRowspan===1) ? 1 : iRowspan;
-
- /* There might be colspan cells already in this row, so shift our target
- * accordingly
- */
- iColShifted = fnShiftCol( aLayout, i, iColumn );
-
- /* Cache calculation for unique columns */
- bUnique = iColspan === 1 ? true : false;
-
- /* If there is col / rowspan, copy the information into the layout grid */
- for ( l=0 ; l<iColspan ; l++ )
- {
- for ( k=0 ; k<iRowspan ; k++ )
- {
- aLayout[i+k][iColShifted+l] = {
- "cell": nCell,
- "unique": bUnique
- };
- aLayout[i+k].nTr = nTr;
- }
- }
- }
- nCell = nCell.nextSibling;
- }
+
+ if ( data.DT_RowClass ) {
+ // Remove any classes added by DT_RowClass before
+ var a = data.DT_RowClass.split(' ');
+ row.__rowc = row.__rowc ?
+ _unique( row.__rowc.concat( a ) ) :
+ a;
+
+ $(tr)
+ .removeClass( row.__rowc.join(' ') )
+ .addClass( data.DT_RowClass );
}
- }
-
-
- /**
- * Get an array of unique th elements, one for each column
- * @param {object} oSettings dataTables settings object
- * @param {node} nHeader automatically detect the layout from this node - optional
- * @param {array} aLayout thead/tfoot layout from _fnDetectHeader - optional
- * @returns array {node} aReturn list of unique th's
- * @memberof DataTable#oApi
- */
- function _fnGetUniqueThs ( oSettings, nHeader, aLayout )
- {
- var aReturn = [];
- if ( !aLayout )
- {
- aLayout = oSettings.aoHeader;
- if ( nHeader )
- {
- aLayout = [];
- _fnDetectHeader( aLayout, nHeader );
- }
+
+ if ( data.DT_RowAttr ) {
+ $(tr).attr( data.DT_RowAttr );
}
-
- for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ )
- {
- for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ )
- {
- if ( aLayout[i][j].unique &&
- (!aReturn[j] || !oSettings.bSortCellsTop) )
- {
- aReturn[j] = aLayout[i][j].cell;
- }
- }
+
+ if ( data.DT_RowData ) {
+ $(tr).data( data.DT_RowData );
}
-
- return aReturn;
}
-
-
-
- /**
- * Update the table using an Ajax call
- * @param {object} oSettings dataTables settings object
- * @returns {boolean} Block the table drawing or not
- * @memberof DataTable#oApi
- */
- function _fnAjaxUpdate( oSettings )
- {
- if ( oSettings.bAjaxDataGet )
- {
- oSettings.iDraw++;
- _fnProcessingDisplay( oSettings, true );
- var iColumns = oSettings.aoColumns.length;
- var aoData = _fnAjaxParameters( oSettings );
- _fnServerParams( oSettings, aoData );
-
- oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, aoData,
- function(json) {
- _fnAjaxUpdateDraw( oSettings, json );
- }, oSettings );
- return false;
- }
- else
- {
- return true;
- }
+ }
+
+
+ /**
+ * Create the HTML header for the table
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnBuildHead( oSettings )
+ {
+ var i, ien, cell, row, column;
+ var thead = oSettings.nTHead;
+ var tfoot = oSettings.nTFoot;
+ var createHeader = $('th, td', thead).length === 0;
+ var classes = oSettings.oClasses;
+ var columns = oSettings.aoColumns;
+
+ if ( createHeader ) {
+ row = $('<tr/>').appendTo( thead );
}
-
-
- /**
- * Build up the parameters in an object needed for a server-side processing request
- * @param {object} oSettings dataTables settings object
- * @returns {bool} block the table drawing or not
- * @memberof DataTable#oApi
- */
- function _fnAjaxParameters( oSettings )
- {
- var iColumns = oSettings.aoColumns.length;
- var aoData = [], mDataProp, aaSort, aDataSort;
- var i, j;
-
- aoData.push( { "name": "sEcho", "value": oSettings.iDraw } );
- aoData.push( { "name": "iColumns", "value": iColumns } );
- aoData.push( { "name": "sColumns", "value": _fnColumnOrdering(oSettings) } );
- aoData.push( { "name": "iDisplayStart", "value": oSettings._iDisplayStart } );
- aoData.push( { "name": "iDisplayLength", "value": oSettings.oFeatures.bPaginate !== false ?
- oSettings._iDisplayLength : -1 } );
-
- for ( i=0 ; i<iColumns ; i++ )
- {
- mDataProp = oSettings.aoColumns[i].mData;
- aoData.push( { "name": "mDataProp_"+i, "value": typeof(mDataProp)==="function" ? 'function' : mDataProp } );
+
+ for ( i=0, ien=columns.length ; i<ien ; i++ ) {
+ column = columns[i];
+ cell = $( column.nTh ).addClass( column.sClass );
+
+ if ( createHeader ) {
+ cell.appendTo( row );
}
-
- /* Filtering */
- if ( oSettings.oFeatures.bFilter !== false )
- {
- aoData.push( { "name": "sSearch", "value": oSettings.oPreviousSearch.sSearch } );
- aoData.push( { "name": "bRegex", "value": oSettings.oPreviousSearch.bRegex } );
- for ( i=0 ; i<iColumns ; i++ )
- {
- aoData.push( { "name": "sSearch_"+i, "value": oSettings.aoPreSearchCols[i].sSearch } );
- aoData.push( { "name": "bRegex_"+i, "value": oSettings.aoPreSearchCols[i].bRegex } );
- aoData.push( { "name": "bSearchable_"+i, "value": oSettings.aoColumns[i].bSearchable } );
+
+ // 1.11 move into sorting
+ if ( oSettings.oFeatures.bSort ) {
+ cell.addClass( column.sSortingClass );
+
+ if ( column.bSortable !== false ) {
+ cell
+ .attr( 'tabindex', oSettings.iTabIndex )
+ .attr( 'aria-controls', oSettings.sTableId );
+
+ _fnSortAttachListener( oSettings, column.nTh, i );
}
}
-
- /* Sorting */
- if ( oSettings.oFeatures.bSort !== false )
- {
- var iCounter = 0;
-
- aaSort = ( oSettings.aaSortingFixed !== null ) ?
- oSettings.aaSortingFixed.concat( oSettings.aaSorting ) :
- oSettings.aaSorting.slice();
-
- for ( i=0 ; i<aaSort.length ; i++ )
- {
- aDataSort = oSettings.aoColumns[ aaSort[i][0] ].aDataSort;
-
- for ( j=0 ; j<aDataSort.length ; j++ )
- {
- aoData.push( { "name": "iSortCol_"+iCounter, "value": aDataSort[j] } );
- aoData.push( { "name": "sSortDir_"+iCounter, "value": aaSort[i][1] } );
- iCounter++;
- }
- }
- aoData.push( { "name": "iSortingCols", "value": iCounter } );
-
- for ( i=0 ; i<iColumns ; i++ )
- {
- aoData.push( { "name": "bSortable_"+i, "value": oSettings.aoColumns[i].bSortable } );
- }
+
+ if ( column.sTitle != cell.html() ) {
+ cell.html( column.sTitle );
}
-
- return aoData;
+
+ _fnRenderer( oSettings, 'header' )(
+ oSettings, cell, column, classes
+ );
}
-
-
- /**
- * Add Ajax parameters from plug-ins
- * @param {object} oSettings dataTables settings object
- * @param array {objects} aoData name/value pairs to send to the server
- * @memberof DataTable#oApi
- */
- function _fnServerParams( oSettings, aoData )
- {
- _fnCallbackFire( oSettings, 'aoServerParams', 'serverParams', [aoData] );
+
+ if ( createHeader ) {
+ _fnDetectHeader( oSettings.aoHeader, thead );
}
-
- /**
- * Data the data from the server (nuking the old) and redraw the table
- * @param {object} oSettings dataTables settings object
- * @param {object} json json data return from the server.
- * @param {string} json.sEcho Tracking flag for DataTables to match requests
- * @param {int} json.iTotalRecords Number of records in the data set, not accounting for filtering
- * @param {int} json.iTotalDisplayRecords Number of records in the data set, accounting for filtering
- * @param {array} json.aaData The data to display on this page
- * @param {string} [json.sColumns] Column ordering (sName, comma separated)
- * @memberof DataTable#oApi
- */
- function _fnAjaxUpdateDraw ( oSettings, json )
- {
- if ( json.sEcho !== undefined )
- {
- /* Protect against old returns over-writing a new one. Possible when you get
- * very fast interaction, and later queries are completed much faster
- */
- if ( json.sEcho*1 < oSettings.iDraw )
- {
- return;
- }
- else
- {
- oSettings.iDraw = json.sEcho * 1;
- }
- }
-
- if ( !oSettings.oScroll.bInfinite ||
- (oSettings.oScroll.bInfinite && (oSettings.bSorted || oSettings.bFiltered)) )
- {
- _fnClearTable( oSettings );
- }
- oSettings._iRecordsTotal = parseInt(json.iTotalRecords, 10);
- oSettings._iRecordsDisplay = parseInt(json.iTotalDisplayRecords, 10);
-
- /* Determine if reordering is required */
- var sOrdering = _fnColumnOrdering(oSettings);
- var bReOrder = (json.sColumns !== undefined && sOrdering !== "" && json.sColumns != sOrdering );
- var aiIndex;
- if ( bReOrder )
- {
- aiIndex = _fnReOrderIndex( oSettings, json.sColumns );
- }
-
- var aData = _fnGetObjectDataFn( oSettings.sAjaxDataProp )( json );
- for ( var i=0, iLen=aData.length ; i<iLen ; i++ )
- {
- if ( bReOrder )
- {
- /* If we need to re-order, then create a new array with the correct order and add it */
- var aDataSorted = [];
- for ( var j=0, jLen=oSettings.aoColumns.length ; j<jLen ; j++ )
- {
- aDataSorted.push( aData[i][ aiIndex[j] ] );
- }
- _fnAddData( oSettings, aDataSorted );
- }
- else
- {
- /* No re-order required, sever got it "right" - just straight add */
- _fnAddData( oSettings, aData[i] );
+ /* ARIA role for the rows */
+ $(thead).find('>tr').attr('role', 'row');
+
+ /* Deal with the footer - add classes if required */
+ $(thead).find('>tr>th, >tr>td').addClass( classes.sHeaderTH );
+ $(tfoot).find('>tr>th, >tr>td').addClass( classes.sFooterTH );
+
+ // Cache the footer cells. Note that we only take the cells from the first
+ // row in the footer. If there is more than one row the user wants to
+ // interact with, they need to use the table().foot() method. Note also this
+ // allows cells to be used for multiple columns using colspan
+ if ( tfoot !== null ) {
+ var cells = oSettings.aoFooter[0];
+
+ for ( i=0, ien=cells.length ; i<ien ; i++ ) {
+ column = columns[i];
+ column.nTf = cells[i].cell;
+
+ if ( column.sClass ) {
+ $(column.nTf).addClass( column.sClass );
}
}
- oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
-
- oSettings.bAjaxDataGet = false;
- _fnDraw( oSettings );
- oSettings.bAjaxDataGet = true;
- _fnProcessingDisplay( oSettings, false );
}
-
-
-
- /**
- * Generate the node required for filtering text
- * @returns {node} Filter control element
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnFeatureHtmlFilter ( oSettings )
+ }
+
+
+ /**
+ * Draw the header (or footer) element based on the column visibility states. The
+ * methodology here is to use the layout array from _fnDetectHeader, modified for
+ * the instantaneous column visibility, to construct the new layout. The grid is
+ * traversed over cell at a time in a rows x columns grid fashion, although each
+ * cell insert can cover multiple elements in the grid - which is tracks using the
+ * aApplied array. Cell inserts in the grid will only occur where there isn't
+ * already a cell in that position.
+ * @param {object} oSettings dataTables settings object
+ * @param array {objects} aoSource Layout array from _fnDetectHeader
+ * @param {boolean} [bIncludeHidden=false] If true then include the hidden columns in the calc,
+ * @memberof DataTable#oApi
+ */
+ function _fnDrawHead( oSettings, aoSource, bIncludeHidden )
+ {
+ var i, iLen, j, jLen, k, kLen, n, nLocalTr;
+ var aoLocal = [];
+ var aApplied = [];
+ var iColumns = oSettings.aoColumns.length;
+ var iRowspan, iColspan;
+
+ if ( ! aoSource )
{
- var oPreviousSearch = oSettings.oPreviousSearch;
-
- var sSearchStr = oSettings.oLanguage.sSearch;
- sSearchStr = (sSearchStr.indexOf('_INPUT_') !== -1) ?
- sSearchStr.replace('_INPUT_', '<input type="text" />') :
- sSearchStr==="" ? '<input type="text" />' : sSearchStr+' <input type="text" />';
-
- var nFilter = document.createElement( 'div' );
- nFilter.className = oSettings.oClasses.sFilter;
- nFilter.innerHTML = '<label>'+sSearchStr+'</label>';
- if ( !oSettings.aanFeatures.f )
- {
- nFilter.id = oSettings.sTableId+'_filter';
- }
-
- var jqFilter = $('input[type="text"]', nFilter);
-
- // Store a reference to the input element, so other input elements could be
- // added to the filter wrapper if needed (submit button for example)
- nFilter._DT_Input = jqFilter[0];
-
- jqFilter.val( oPreviousSearch.sSearch.replace('"','&quot;') );
- jqFilter.bind( 'keyup.DT', function(e) {
- /* Update all other filter input elements for the new display */
- var n = oSettings.aanFeatures.f;
- var val = this.value==="" ? "" : this.value; // mental IE8 fix :-(
-
- for ( var i=0, iLen=n.length ; i<iLen ; i++ )
- {
- if ( n[i] != $(this).parents('div.dataTables_filter')[0] )
- {
- $(n[i]._DT_Input).val( val );
- }
- }
-
- /* Now do the filter */
- if ( val != oPreviousSearch.sSearch )
- {
- _fnFilterComplete( oSettings, {
- "sSearch": val,
- "bRegex": oPreviousSearch.bRegex,
- "bSmart": oPreviousSearch.bSmart ,
- "bCaseInsensitive": oPreviousSearch.bCaseInsensitive
- } );
- }
- } );
-
- jqFilter
- .attr('aria-controls', oSettings.sTableId)
- .bind( 'keypress.DT', function(e) {
- /* Prevent form submission */
- if ( e.keyCode == 13 )
- {
- return false;
- }
- }
- );
-
- return nFilter;
+ return;
}
-
-
- /**
- * Filter the table using both the global filter and column based filtering
- * @param {object} oSettings dataTables settings object
- * @param {object} oSearch search information
- * @param {int} [iForce] force a research of the master array (1) or not (undefined or 0)
- * @memberof DataTable#oApi
- */
- function _fnFilterComplete ( oSettings, oInput, iForce )
+
+ if ( bIncludeHidden === undefined )
{
- var oPrevSearch = oSettings.oPreviousSearch;
- var aoPrevSearch = oSettings.aoPreSearchCols;
- var fnSaveFilter = function ( oFilter ) {
- /* Save the filtering values */
- oPrevSearch.sSearch = oFilter.sSearch;
- oPrevSearch.bRegex = oFilter.bRegex;
- oPrevSearch.bSmart = oFilter.bSmart;
- oPrevSearch.bCaseInsensitive = oFilter.bCaseInsensitive;
- };
-
- /* In server-side processing all filtering is done by the server, so no point hanging around here */
- if ( !oSettings.oFeatures.bServerSide )
- {
- /* Global filter */
- _fnFilter( oSettings, oInput.sSearch, iForce, oInput.bRegex, oInput.bSmart, oInput.bCaseInsensitive );
- fnSaveFilter( oInput );
-
- /* Now do the individual column filter */
- for ( var i=0 ; i<oSettings.aoPreSearchCols.length ; i++ )
- {
- _fnFilterColumn( oSettings, aoPrevSearch[i].sSearch, i, aoPrevSearch[i].bRegex,
- aoPrevSearch[i].bSmart, aoPrevSearch[i].bCaseInsensitive );
- }
-
- /* Custom filtering */
- _fnFilterCustom( oSettings );
- }
- else
- {
- fnSaveFilter( oInput );
- }
-
- /* Tell the draw function we have been filtering */
- oSettings.bFiltered = true;
- $(oSettings.oInstance).trigger('filter', oSettings);
-
- /* Redraw the table */
- oSettings._iDisplayStart = 0;
- _fnCalculateEnd( oSettings );
- _fnDraw( oSettings );
-
- /* Rebuild search array 'offline' */
- _fnBuildSearchArray( oSettings, 0 );
+ bIncludeHidden = false;
}
-
-
- /**
- * Apply custom filtering functions
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnFilterCustom( oSettings )
+
+ /* Make a copy of the master layout array, but without the visible columns in it */
+ for ( i=0, iLen=aoSource.length ; i<iLen ; i++ )
{
- var afnFilters = DataTable.ext.afnFiltering;
- var aiFilterColumns = _fnGetColumns( oSettings, 'bSearchable' );
-
- for ( var i=0, iLen=afnFilters.length ; i<iLen ; i++ )
+ aoLocal[i] = aoSource[i].slice();
+ aoLocal[i].nTr = aoSource[i].nTr;
+
+ /* Remove any columns which are currently hidden */
+ for ( j=iColumns-1 ; j>=0 ; j-- )
{
- var iCorrector = 0;
- for ( var j=0, jLen=oSettings.aiDisplay.length ; j<jLen ; j++ )
+ if ( !oSettings.aoColumns[j].bVisible && !bIncludeHidden )
{
- var iDisIndex = oSettings.aiDisplay[j-iCorrector];
- var bTest = afnFilters[i](
- oSettings,
- _fnGetRowData( oSettings, iDisIndex, 'filter', aiFilterColumns ),
- iDisIndex
- );
-
- /* Check if we should use this row based on the filtering function */
- if ( !bTest )
- {
- oSettings.aiDisplay.splice( j-iCorrector, 1 );
- iCorrector++;
- }
+ aoLocal[i].splice( j, 1 );
}
}
+
+ /* Prep the applied array - it needs an element for each row */
+ aApplied.push( [] );
}
-
-
- /**
- * Filter the table on a per-column basis
- * @param {object} oSettings dataTables settings object
- * @param {string} sInput string to filter on
- * @param {int} iColumn column to filter
- * @param {bool} bRegex treat search string as a regular expression or not
- * @param {bool} bSmart use smart filtering or not
- * @param {bool} bCaseInsensitive Do case insenstive matching or not
- * @memberof DataTable#oApi
- */
- function _fnFilterColumn ( oSettings, sInput, iColumn, bRegex, bSmart, bCaseInsensitive )
+
+ for ( i=0, iLen=aoLocal.length ; i<iLen ; i++ )
{
- if ( sInput === "" )
- {
- return;
- }
-
- var iIndexCorrector = 0;
- var rpSearch = _fnFilterCreateSearch( sInput, bRegex, bSmart, bCaseInsensitive );
-
- for ( var i=oSettings.aiDisplay.length-1 ; i>=0 ; i-- )
+ nLocalTr = aoLocal[i].nTr;
+
+ /* All cells are going to be replaced, so empty out the row */
+ if ( nLocalTr )
{
- var sData = _fnDataToSearch( _fnGetCellData( oSettings, oSettings.aiDisplay[i], iColumn, 'filter' ),
- oSettings.aoColumns[iColumn].sType );
- if ( ! rpSearch.test( sData ) )
+ while( (n = nLocalTr.firstChild) )
{
- oSettings.aiDisplay.splice( i, 1 );
- iIndexCorrector++;
+ nLocalTr.removeChild( n );
}
}
- }
-
-
- /**
- * Filter the data table based on user input and draw the table
- * @param {object} oSettings dataTables settings object
- * @param {string} sInput string to filter on
- * @param {int} iForce optional - force a research of the master array (1) or not (undefined or 0)
- * @param {bool} bRegex treat as a regular expression or not
- * @param {bool} bSmart perform smart filtering or not
- * @param {bool} bCaseInsensitive Do case insenstive matching or not
- * @memberof DataTable#oApi
- */
- function _fnFilter( oSettings, sInput, iForce, bRegex, bSmart, bCaseInsensitive )
- {
- var i;
- var rpSearch = _fnFilterCreateSearch( sInput, bRegex, bSmart, bCaseInsensitive );
- var oPrevSearch = oSettings.oPreviousSearch;
-
- /* Check if we are forcing or not - optional parameter */
- if ( !iForce )
- {
- iForce = 0;
- }
-
- /* Need to take account of custom filtering functions - always filter */
- if ( DataTable.ext.afnFiltering.length !== 0 )
- {
- iForce = 1;
- }
-
- /*
- * If the input is blank - we want the full data set
- */
- if ( sInput.length <= 0 )
- {
- oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length);
- oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
- }
- else
+
+ for ( j=0, jLen=aoLocal[i].length ; j<jLen ; j++ )
{
- /*
- * We are starting a new search or the new search string is smaller
- * then the old one (i.e. delete). Search from the master array
- */
- if ( oSettings.aiDisplay.length == oSettings.aiDisplayMaster.length ||
- oPrevSearch.sSearch.length > sInput.length || iForce == 1 ||
- sInput.indexOf(oPrevSearch.sSearch) !== 0 )
+ iRowspan = 1;
+ iColspan = 1;
+
+ /* Check to see if there is already a cell (row/colspan) covering our target
+ * insert point. If there is, then there is nothing to do.
+ */
+ if ( aApplied[i][j] === undefined )
{
- /* Nuke the old display array - we are going to rebuild it */
- oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length);
-
- /* Force a rebuild of the search array */
- _fnBuildSearchArray( oSettings, 1 );
-
- /* Search through all records to populate the search array
- * The the oSettings.aiDisplayMaster and asDataSearch arrays have 1 to 1
- * mapping
- */
- for ( i=0 ; i<oSettings.aiDisplayMaster.length ; i++ )
+ nLocalTr.appendChild( aoLocal[i][j].cell );
+ aApplied[i][j] = 1;
+
+ /* Expand the cell to cover as many rows as needed */
+ while ( aoLocal[i+iRowspan] !== undefined &&
+ aoLocal[i][j].cell == aoLocal[i+iRowspan][j].cell )
{
- if ( rpSearch.test(oSettings.asDataSearch[i]) )
- {
- oSettings.aiDisplay.push( oSettings.aiDisplayMaster[i] );
- }
+ aApplied[i+iRowspan][j] = 1;
+ iRowspan++;
}
- }
- else
- {
- /* Using old search array - refine it - do it this way for speed
- * Don't have to search the whole master array again
- */
- var iIndexCorrector = 0;
-
- /* Search the current results */
- for ( i=0 ; i<oSettings.asDataSearch.length ; i++ )
+
+ /* Expand the cell to cover as many columns as needed */
+ while ( aoLocal[i][j+iColspan] !== undefined &&
+ aoLocal[i][j].cell == aoLocal[i][j+iColspan].cell )
{
- if ( ! rpSearch.test(oSettings.asDataSearch[i]) )
+ /* Must update the applied array over the rows for the columns */
+ for ( k=0 ; k<iRowspan ; k++ )
{
- oSettings.aiDisplay.splice( i-iIndexCorrector, 1 );
- iIndexCorrector++;
- }
- }
- }
- }
- }
-
-
- /**
- * Create an array which can be quickly search through
- * @param {object} oSettings dataTables settings object
- * @param {int} iMaster use the master data array - optional
- * @memberof DataTable#oApi
- */
- function _fnBuildSearchArray ( oSettings, iMaster )
- {
- if ( !oSettings.oFeatures.bServerSide )
- {
- /* Clear out the old data */
- oSettings.asDataSearch = [];
-
- var aiFilterColumns = _fnGetColumns( oSettings, 'bSearchable' );
- var aiIndex = (iMaster===1) ?
- oSettings.aiDisplayMaster :
- oSettings.aiDisplay;
-
- for ( var i=0, iLen=aiIndex.length ; i<iLen ; i++ )
- {
- oSettings.asDataSearch[i] = _fnBuildSearchRow(
- oSettings,
- _fnGetRowData( oSettings, aiIndex[i], 'filter', aiFilterColumns )
- );
+ aApplied[i+k][j+iColspan] = 1;
+ }
+ iColspan++;
+ }
+
+ /* Do the actual expansion in the DOM */
+ $(aoLocal[i][j].cell)
+ .attr('rowspan', iRowspan)
+ .attr('colspan', iColspan);
}
}
}
-
-
- /**
- * Create a searchable string from a single data row
- * @param {object} oSettings dataTables settings object
- * @param {array} aData Row data array to use for the data to search
- * @memberof DataTable#oApi
- */
- function _fnBuildSearchRow( oSettings, aData )
+ }
+
+
+ /**
+ * Insert the required TR nodes into the table for display
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnDraw( oSettings )
+ {
+ /* Provide a pre-callback function which can be used to cancel the draw is false is returned */
+ var aPreDraw = _fnCallbackFire( oSettings, 'aoPreDrawCallback', 'preDraw', [oSettings] );
+ if ( $.inArray( false, aPreDraw ) !== -1 )
{
- var sSearch = aData.join(' ');
-
- /* If it looks like there is an HTML entity in the string, attempt to decode it */
- if ( sSearch.indexOf('&') !== -1 )
- {
- sSearch = $('<div>').html(sSearch).text();
- }
-
- // Strip newline characters
- return sSearch.replace( /[\n\r]/g, " " );
+ _fnProcessingDisplay( oSettings, false );
+ return;
}
-
- /**
- * Build a regular expression object suitable for searching a table
- * @param {string} sSearch string to search for
- * @param {bool} bRegex treat as a regular expression or not
- * @param {bool} bSmart perform smart filtering or not
- * @param {bool} bCaseInsensitive Do case insensitive matching or not
- * @returns {RegExp} constructed object
- * @memberof DataTable#oApi
- */
- function _fnFilterCreateSearch( sSearch, bRegex, bSmart, bCaseInsensitive )
+
+ var i, iLen, n;
+ var anRows = [];
+ var iRowCount = 0;
+ var asStripeClasses = oSettings.asStripeClasses;
+ var iStripes = asStripeClasses.length;
+ var iOpenRows = oSettings.aoOpenRows.length;
+ var oLang = oSettings.oLanguage;
+ var iInitDisplayStart = oSettings.iInitDisplayStart;
+ var bServerSide = _fnDataSource( oSettings ) == 'ssp';
+ var aiDisplay = oSettings.aiDisplay;
+
+ oSettings.bDrawing = true;
+
+ /* Check and see if we have an initial draw position from state saving */
+ if ( iInitDisplayStart !== undefined && iInitDisplayStart !== -1 )
+ {
+ oSettings._iDisplayStart = bServerSide ?
+ iInitDisplayStart :
+ iInitDisplayStart >= oSettings.fnRecordsDisplay() ?
+ 0 :
+ iInitDisplayStart;
+
+ oSettings.iInitDisplayStart = -1;
+ }
+
+ var iDisplayStart = oSettings._iDisplayStart;
+ var iDisplayEnd = oSettings.fnDisplayEnd();
+
+ /* Server-side processing draw intercept */
+ if ( oSettings.bDeferLoading )
{
- var asSearch, sRegExpString;
-
- if ( bSmart )
- {
- /* Generate the regular expression to use. Something along the lines of:
- * ^(?=.*?\bone\b)(?=.*?\btwo\b)(?=.*?\bthree\b).*$
- */
- asSearch = bRegex ? sSearch.split( ' ' ) : _fnEscapeRegex( sSearch ).split( ' ' );
- sRegExpString = '^(?=.*?'+asSearch.join( ')(?=.*?' )+').*$';
- return new RegExp( sRegExpString, bCaseInsensitive ? "i" : "" );
- }
- else
- {
- sSearch = bRegex ? sSearch : _fnEscapeRegex( sSearch );
- return new RegExp( sSearch, bCaseInsensitive ? "i" : "" );
- }
+ oSettings.bDeferLoading = false;
+ oSettings.iDraw++;
+ _fnProcessingDisplay( oSettings, false );
}
-
-
- /**
- * Convert raw data into something that the user can search on
- * @param {string} sData data to be modified
- * @param {string} sType data type
- * @returns {string} search string
- * @memberof DataTable#oApi
- */
- function _fnDataToSearch ( sData, sType )
+ else if ( !bServerSide )
{
- if ( typeof DataTable.ext.ofnSearch[sType] === "function" )
- {
- return DataTable.ext.ofnSearch[sType]( sData );
- }
- else if ( sData === null )
- {
- return '';
- }
- else if ( sType == "html" )
- {
- return sData.replace(/[\r\n]/g," ").replace( /<.*?>/g, "" );
- }
- else if ( typeof sData === "string" )
- {
- return sData.replace(/[\r\n]/g," ");
- }
- return sData;
+ oSettings.iDraw++;
}
-
-
- /**
- * scape a string such that it can be used in a regular expression
- * @param {string} sVal string to escape
- * @returns {string} escaped string
- * @memberof DataTable#oApi
- */
- function _fnEscapeRegex ( sVal )
+ else if ( !oSettings.bDestroying && !_fnAjaxUpdate( oSettings ) )
{
- var acEscape = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^', '-' ];
- var reReplace = new RegExp( '(\\' + acEscape.join('|\\') + ')', 'g' );
- return sVal.replace(reReplace, '\\$1');
+ return;
}
-
-
- /**
- * Generate the node required for the info display
- * @param {object} oSettings dataTables settings object
- * @returns {node} Information element
- * @memberof DataTable#oApi
- */
- function _fnFeatureHtmlInfo ( oSettings )
+
+ if ( aiDisplay.length !== 0 )
{
- var nInfo = document.createElement( 'div' );
- nInfo.className = oSettings.oClasses.sInfo;
-
- /* Actions that are to be taken once only for this feature */
- if ( !oSettings.aanFeatures.i )
+ var iStart = bServerSide ? 0 : iDisplayStart;
+ var iEnd = bServerSide ? oSettings.aoData.length : iDisplayEnd;
+
+ for ( var j=iStart ; j<iEnd ; j++ )
{
- /* Add draw callback */
- oSettings.aoDrawCallback.push( {
- "fn": _fnUpdateInfo,
- "sName": "information"
- } );
-
- /* Add id */
- nInfo.id = oSettings.sTableId+'_info';
+ var iDataIndex = aiDisplay[j];
+ var aoData = oSettings.aoData[ iDataIndex ];
+ if ( aoData.nTr === null )
+ {
+ _fnCreateTr( oSettings, iDataIndex );
+ }
+
+ var nRow = aoData.nTr;
+
+ /* Remove the old striping classes and then add the new one */
+ if ( iStripes !== 0 )
+ {
+ var sStripe = asStripeClasses[ iRowCount % iStripes ];
+ if ( aoData._sRowStripe != sStripe )
+ {
+ $(nRow).removeClass( aoData._sRowStripe ).addClass( sStripe );
+ aoData._sRowStripe = sStripe;
+ }
+ }
+
+ // Row callback functions - might want to manipulate the row
+ // iRowCount and j are not currently documented. Are they at all
+ // useful?
+ _fnCallbackFire( oSettings, 'aoRowCallback', null,
+ [nRow, aoData._aData, iRowCount, j] );
+
+ anRows.push( nRow );
+ iRowCount++;
}
- oSettings.nTable.setAttribute( 'aria-describedby', oSettings.sTableId+'_info' );
-
- return nInfo;
}
-
-
- /**
- * Update the information elements in the display
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnUpdateInfo ( oSettings )
+ else
{
- /* Show information about the table */
- if ( !oSettings.oFeatures.bInfo || oSettings.aanFeatures.i.length === 0 )
- {
- return;
- }
-
- var
- oLang = oSettings.oLanguage,
- iStart = oSettings._iDisplayStart+1,
- iEnd = oSettings.fnDisplayEnd(),
- iMax = oSettings.fnRecordsTotal(),
- iTotal = oSettings.fnRecordsDisplay(),
- sOut;
-
- if ( iTotal === 0 )
+ /* Table is empty - create a row with an empty message in it */
+ var sZero = oLang.sZeroRecords;
+ if ( oSettings.iDraw == 1 && _fnDataSource( oSettings ) == 'ajax' )
{
- /* Empty record set */
- sOut = oLang.sInfoEmpty;
- }
- else {
- /* Normal record set */
- sOut = oLang.sInfo;
+ sZero = oLang.sLoadingRecords;
}
-
- if ( iTotal != iMax )
+ else if ( oLang.sEmptyTable && oSettings.fnRecordsTotal() === 0 )
{
- /* Record set after filtering */
- sOut += ' ' + oLang.sInfoFiltered;
- }
-
- // Convert the macros
- sOut += oLang.sInfoPostFix;
- sOut = _fnInfoMacros( oSettings, sOut );
-
- if ( oLang.fnInfoCallback !== null )
- {
- sOut = oLang.fnInfoCallback.call( oSettings.oInstance,
- oSettings, iStart, iEnd, iMax, iTotal, sOut );
- }
-
- var n = oSettings.aanFeatures.i;
- for ( var i=0, iLen=n.length ; i<iLen ; i++ )
- {
- $(n[i]).html( sOut );
+ sZero = oLang.sEmptyTable;
}
+
+ anRows[ 0 ] = $( '<tr/>', { 'class': iStripes ? asStripeClasses[0] : '' } )
+ .append( $('<td />', {
+ 'valign': 'top',
+ 'colSpan': _fnVisbleColumns( oSettings ),
+ 'class': oSettings.oClasses.sRowEmpty
+ } ).html( sZero ) )[0];
}
-
-
- function _fnInfoMacros ( oSettings, str )
- {
- var
- iStart = oSettings._iDisplayStart+1,
- sStart = oSettings.fnFormatNumber( iStart ),
- iEnd = oSettings.fnDisplayEnd(),
- sEnd = oSettings.fnFormatNumber( iEnd ),
- iTotal = oSettings.fnRecordsDisplay(),
- sTotal = oSettings.fnFormatNumber( iTotal ),
- iMax = oSettings.fnRecordsTotal(),
- sMax = oSettings.fnFormatNumber( iMax );
-
- // When infinite scrolling, we are always starting at 1. _iDisplayStart is used only
- // internally
- if ( oSettings.oScroll.bInfinite )
- {
- sStart = oSettings.fnFormatNumber( 1 );
- }
-
- return str.
- replace(/_START_/g, sStart).
- replace(/_END_/g, sEnd).
- replace(/_TOTAL_/g, sTotal).
- replace(/_MAX_/g, sMax);
+
+ /* Header and footer callbacks */
+ _fnCallbackFire( oSettings, 'aoHeaderCallback', 'header', [ $(oSettings.nTHead).children('tr')[0],
+ _fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] );
+
+ _fnCallbackFire( oSettings, 'aoFooterCallback', 'footer', [ $(oSettings.nTFoot).children('tr')[0],
+ _fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] );
+
+ var body = $(oSettings.nTBody);
+
+ body.children().detach();
+ body.append( $(anRows) );
+
+ /* Call all required callback functions for the end of a draw */
+ _fnCallbackFire( oSettings, 'aoDrawCallback', 'draw', [oSettings] );
+
+ /* Draw is complete, sorting and filtering must be as well */
+ oSettings.bSorted = false;
+ oSettings.bFiltered = false;
+ oSettings.bDrawing = false;
+ }
+
+
+ /**
+ * Redraw the table - taking account of the various features which are enabled
+ * @param {object} oSettings dataTables settings object
+ * @param {boolean} [holdPosition] Keep the current paging position. By default
+ * the paging is reset to the first page
+ * @memberof DataTable#oApi
+ */
+ function _fnReDraw( settings, holdPosition )
+ {
+ var
+ features = settings.oFeatures,
+ sort = features.bSort,
+ filter = features.bFilter;
+
+ if ( sort ) {
+ _fnSort( settings );
}
-
-
-
- /**
- * Draw the table for the first time, adding all required features
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnInitialise ( oSettings )
+
+ if ( filter ) {
+ _fnFilterComplete( settings, settings.oPreviousSearch );
+ }
+ else {
+ // No filtering, so we want to just use the display master
+ settings.aiDisplay = settings.aiDisplayMaster.slice();
+ }
+
+ if ( holdPosition !== true ) {
+ settings._iDisplayStart = 0;
+ }
+
+ // Let any modules know about the draw hold position state (used by
+ // scrolling internally)
+ settings._drawHold = holdPosition;
+
+ _fnDraw( settings );
+
+ settings._drawHold = false;
+ }
+
+
+ /**
+ * Add the options to the page HTML for the table
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnAddOptionsHtml ( oSettings )
+ {
+ var classes = oSettings.oClasses;
+ var table = $(oSettings.nTable);
+ var holding = $('<div/>').insertBefore( table ); // Holding element for speed
+ var features = oSettings.oFeatures;
+
+ // All DataTables are wrapped in a div
+ var insert = $('<div/>', {
+ id: oSettings.sTableId+'_wrapper',
+ 'class': classes.sWrapper + (oSettings.nTFoot ? '' : ' '+classes.sNoFooter)
+ } );
+
+ oSettings.nHolding = holding[0];
+ oSettings.nTableWrapper = insert[0];
+ oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling;
+
+ /* Loop over the user set positioning and place the elements as needed */
+ var aDom = oSettings.sDom.split('');
+ var featureNode, cOption, nNewNode, cNext, sAttr, j;
+ for ( var i=0 ; i<aDom.length ; i++ )
{
- var i, iLen, iAjaxStart=oSettings.iInitDisplayStart;
-
- /* Ensure that the table data is fully initialised */
- if ( oSettings.bInitialised === false )
- {
- setTimeout( function(){ _fnInitialise( oSettings ); }, 200 );
- return;
- }
-
- /* Show the display HTML options */
- _fnAddOptionsHtml( oSettings );
-
- /* Build and draw the header / footer for the table */
- _fnBuildHead( oSettings );
- _fnDrawHead( oSettings, oSettings.aoHeader );
- if ( oSettings.nTFoot )
- {
- _fnDrawHead( oSettings, oSettings.aoFooter );
- }
-
- /* Okay to show that something is going on now */
- _fnProcessingDisplay( oSettings, true );
-
- /* Calculate sizes for columns */
- if ( oSettings.oFeatures.bAutoWidth )
- {
- _fnCalculateColumnWidths( oSettings );
- }
-
- for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
+ featureNode = null;
+ cOption = aDom[i];
+
+ if ( cOption == '<' )
{
- if ( oSettings.aoColumns[i].sWidth !== null )
+ /* New container div */
+ nNewNode = $('<div/>')[0];
+
+ /* Check to see if we should append an id and/or a class name to the container */
+ cNext = aDom[i+1];
+ if ( cNext == "'" || cNext == '"' )
{
- oSettings.aoColumns[i].nTh.style.width = _fnStringToCss( oSettings.aoColumns[i].sWidth );
- }
- }
-
- /* If there is default sorting required - let's do it. The sort function will do the
- * drawing for us. Otherwise we draw the table regardless of the Ajax source - this allows
- * the table to look initialised for Ajax sourcing data (show 'loading' message possibly)
- */
- if ( oSettings.oFeatures.bSort )
- {
- _fnSort( oSettings );
- }
- else if ( oSettings.oFeatures.bFilter )
- {
- _fnFilterComplete( oSettings, oSettings.oPreviousSearch );
- }
- else
- {
- oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
- _fnCalculateEnd( oSettings );
- _fnDraw( oSettings );
- }
-
- /* if there is an ajax source load the data */
- if ( oSettings.sAjaxSource !== null && !oSettings.oFeatures.bServerSide )
- {
- var aoData = [];
- _fnServerParams( oSettings, aoData );
- oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, aoData, function(json) {
- var aData = (oSettings.sAjaxDataProp !== "") ?
- _fnGetObjectDataFn( oSettings.sAjaxDataProp )(json) : json;
-
- /* Got the data - add it to the table */
- for ( i=0 ; i<aData.length ; i++ )
+ sAttr = "";
+ j = 2;
+ while ( aDom[i+j] != cNext )
{
- _fnAddData( oSettings, aData[i] );
+ sAttr += aDom[i+j];
+ j++;
}
-
- /* Reset the init display for cookie saving. We've already done a filter, and
- * therefore cleared it before. So we need to make it appear 'fresh'
+
+ /* Replace jQuery UI constants @todo depreciated */
+ if ( sAttr == "H" )
+ {
+ sAttr = classes.sJUIHeader;
+ }
+ else if ( sAttr == "F" )
+ {
+ sAttr = classes.sJUIFooter;
+ }
+
+ /* The attribute can be in the format of "#id.class", "#id" or "class" This logic
+ * breaks the string into parts and applies them as needed
*/
- oSettings.iInitDisplayStart = iAjaxStart;
-
- if ( oSettings.oFeatures.bSort )
+ if ( sAttr.indexOf('.') != -1 )
{
- _fnSort( oSettings );
+ var aSplit = sAttr.split('.');
+ nNewNode.id = aSplit[0].substr(1, aSplit[0].length-1);
+ nNewNode.className = aSplit[1];
+ }
+ else if ( sAttr.charAt(0) == "#" )
+ {
+ nNewNode.id = sAttr.substr(1, sAttr.length-1);
}
else
{
- oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
- _fnCalculateEnd( oSettings );
- _fnDraw( oSettings );
+ nNewNode.className = sAttr;
}
-
- _fnProcessingDisplay( oSettings, false );
- _fnInitComplete( oSettings, json );
- }, oSettings );
- return;
+
+ i += j; /* Move along the position array */
+ }
+
+ insert.append( nNewNode );
+ insert = $(nNewNode);
}
-
- /* Server-side processing initialisation complete is done at the end of _fnDraw */
- if ( !oSettings.oFeatures.bServerSide )
+ else if ( cOption == '>' )
{
- _fnProcessingDisplay( oSettings, false );
- _fnInitComplete( oSettings );
+ /* End container div */
+ insert = insert.parent();
}
- }
-
-
- /**
- * Draw the table for the first time, adding all required features
- * @param {object} oSettings dataTables settings object
- * @param {object} [json] JSON from the server that completed the table, if using Ajax source
- * with client-side processing (optional)
- * @memberof DataTable#oApi
- */
- function _fnInitComplete ( oSettings, json )
- {
- oSettings._bInitComplete = true;
- _fnCallbackFire( oSettings, 'aoInitComplete', 'init', [oSettings, json] );
- }
-
-
- /**
- * Language compatibility - when certain options are given, and others aren't, we
- * need to duplicate the values over, in order to provide backwards compatibility
- * with older language files.
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnLanguageCompat( oLanguage )
- {
- var oDefaults = DataTable.defaults.oLanguage;
-
- /* Backwards compatibility - if there is no sEmptyTable given, then use the same as
- * sZeroRecords - assuming that is given.
- */
- if ( !oLanguage.sEmptyTable && oLanguage.sZeroRecords &&
- oDefaults.sEmptyTable === "No data available in table" )
+ // @todo Move options into their own plugins?
+ else if ( cOption == 'l' && features.bPaginate && features.bLengthChange )
{
- _fnMap( oLanguage, oLanguage, 'sZeroRecords', 'sEmptyTable' );
+ /* Length */
+ featureNode = _fnFeatureHtmlLength( oSettings );
}
-
- /* Likewise with loading records */
- if ( !oLanguage.sLoadingRecords && oLanguage.sZeroRecords &&
- oDefaults.sLoadingRecords === "Loading..." )
+ else if ( cOption == 'f' && features.bFilter )
{
- _fnMap( oLanguage, oLanguage, 'sZeroRecords', 'sLoadingRecords' );
+ /* Filter */
+ featureNode = _fnFeatureHtmlFilter( oSettings );
}
- }
-
-
-
- /**
- * Generate the node required for user display length changing
- * @param {object} oSettings dataTables settings object
- * @returns {node} Display length feature node
- * @memberof DataTable#oApi
- */
- function _fnFeatureHtmlLength ( oSettings )
- {
- if ( oSettings.oScroll.bInfinite )
+ else if ( cOption == 'r' && features.bProcessing )
{
- return null;
+ /* pRocessing */
+ featureNode = _fnFeatureHtmlProcessing( oSettings );
}
-
- /* This can be overruled by not using the _MENU_ var/macro in the language variable */
- var sName = 'name="'+oSettings.sTableId+'_length"';
- var sStdMenu = '<select size="1" '+sName+'>';
- var i, iLen;
- var aLengthMenu = oSettings.aLengthMenu;
-
- if ( aLengthMenu.length == 2 && typeof aLengthMenu[0] === 'object' &&
- typeof aLengthMenu[1] === 'object' )
+ else if ( cOption == 't' )
{
- for ( i=0, iLen=aLengthMenu[0].length ; i<iLen ; i++ )
- {
- sStdMenu += '<option value="'+aLengthMenu[0][i]+'">'+aLengthMenu[1][i]+'</option>';
- }
+ /* Table */
+ featureNode = _fnFeatureHtmlTable( oSettings );
}
- else
+ else if ( cOption == 'i' && features.bInfo )
{
- for ( i=0, iLen=aLengthMenu.length ; i<iLen ; i++ )
- {
- sStdMenu += '<option value="'+aLengthMenu[i]+'">'+aLengthMenu[i]+'</option>';
- }
+ /* Info */
+ featureNode = _fnFeatureHtmlInfo( oSettings );
}
- sStdMenu += '</select>';
-
- var nLength = document.createElement( 'div' );
- if ( !oSettings.aanFeatures.l )
+ else if ( cOption == 'p' && features.bPaginate )
{
- nLength.id = oSettings.sTableId+'_length';
+ /* Pagination */
+ featureNode = _fnFeatureHtmlPaginate( oSettings );
}
- nLength.className = oSettings.oClasses.sLength;
- nLength.innerHTML = '<label>'+oSettings.oLanguage.sLengthMenu.replace( '_MENU_', sStdMenu )+'</label>';
-
- /*
- * Set the length to the current display length - thanks to Andrea Pavlovic for this fix,
- * and Stefan Skopnik for fixing the fix!
- */
- $('select option[value="'+oSettings._iDisplayLength+'"]', nLength).attr("selected", true);
-
- $('select', nLength).bind( 'change.DT', function(e) {
- var iVal = $(this).val();
-
- /* Update all other length options for the new display */
- var n = oSettings.aanFeatures.l;
- for ( i=0, iLen=n.length ; i<iLen ; i++ )
- {
- if ( n[i] != this.parentNode )
- {
- $('select', n[i]).val( iVal );
- }
- }
-
- /* Redraw the table */
- oSettings._iDisplayLength = parseInt(iVal, 10);
- _fnCalculateEnd( oSettings );
-
- /* If we have space to show extra rows (backing up from the end point - then do so */
- if ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() )
+ else if ( DataTable.ext.feature.length !== 0 )
+ {
+ /* Plug-in features */
+ var aoFeatures = DataTable.ext.feature;
+ for ( var k=0, kLen=aoFeatures.length ; k<kLen ; k++ )
{
- oSettings._iDisplayStart = oSettings.fnDisplayEnd() - oSettings._iDisplayLength;
- if ( oSettings._iDisplayStart < 0 )
+ if ( cOption == aoFeatures[k].cFeature )
{
- oSettings._iDisplayStart = 0;
+ featureNode = aoFeatures[k].fnInit( oSettings );
+ break;
}
}
-
- if ( oSettings._iDisplayLength == -1 )
- {
- oSettings._iDisplayStart = 0;
- }
-
- _fnDraw( oSettings );
- } );
-
-
- $('select', nLength).attr('aria-controls', oSettings.sTableId);
-
- return nLength;
- }
-
-
- /**
- * Recalculate the end point based on the start point
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnCalculateEnd( oSettings )
- {
- if ( oSettings.oFeatures.bPaginate === false )
- {
- oSettings._iDisplayEnd = oSettings.aiDisplay.length;
}
- else
+
+ /* Add to the 2D features array */
+ if ( featureNode )
{
- /* Set the end point of the display - based on how many elements there are
- * still to display
- */
- if ( oSettings._iDisplayStart + oSettings._iDisplayLength > oSettings.aiDisplay.length ||
- oSettings._iDisplayLength == -1 )
- {
- oSettings._iDisplayEnd = oSettings.aiDisplay.length;
- }
- else
+ var aanFeatures = oSettings.aanFeatures;
+
+ if ( ! aanFeatures[cOption] )
{
- oSettings._iDisplayEnd = oSettings._iDisplayStart + oSettings._iDisplayLength;
+ aanFeatures[cOption] = [];
}
+
+ aanFeatures[cOption].push( featureNode );
+ insert.append( featureNode );
}
}
-
-
-
- /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
- * Note that most of the paging logic is done in
- * DataTable.ext.oPagination
- */
-
- /**
- * Generate the node required for default pagination
- * @param {object} oSettings dataTables settings object
- * @returns {node} Pagination feature node
- * @memberof DataTable#oApi
- */
- function _fnFeatureHtmlPaginate ( oSettings )
+
+ /* Built our DOM structure - replace the holding div with what we want */
+ holding.replaceWith( insert );
+ }
+
+
+ /**
+ * Use the DOM source to create up an array of header cells. The idea here is to
+ * create a layout grid (array) of rows x columns, which contains a reference
+ * to the cell that that point in the grid (regardless of col/rowspan), such that
+ * any column / row could be removed and the new grid constructed
+ * @param array {object} aLayout Array to store the calculated layout in
+ * @param {node} nThead The header/footer element for the table
+ * @memberof DataTable#oApi
+ */
+ function _fnDetectHeader ( aLayout, nThead )
+ {
+ var nTrs = $(nThead).children('tr');
+ var nTr, nCell;
+ var i, k, l, iLen, jLen, iColShifted, iColumn, iColspan, iRowspan;
+ var bUnique;
+ var fnShiftCol = function ( a, i, j ) {
+ var k = a[i];
+ while ( k[j] ) {
+ j++;
+ }
+ return j;
+ };
+
+ aLayout.splice( 0, aLayout.length );
+
+ /* We know how many rows there are in the layout - so prep it */
+ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
{
- if ( oSettings.oScroll.bInfinite )
- {
- return null;
- }
-
- var nPaginate = document.createElement( 'div' );
- nPaginate.className = oSettings.oClasses.sPaging+oSettings.sPaginationType;
-
- DataTable.ext.oPagination[ oSettings.sPaginationType ].fnInit( oSettings, nPaginate,
- function( oSettings ) {
- _fnCalculateEnd( oSettings );
- _fnDraw( oSettings );
- }
- );
-
- /* Add a draw callback for the pagination on first instance, to update the paging display */
- if ( !oSettings.aanFeatures.p )
- {
- oSettings.aoDrawCallback.push( {
- "fn": function( oSettings ) {
- DataTable.ext.oPagination[ oSettings.sPaginationType ].fnUpdate( oSettings, function( oSettings ) {
- _fnCalculateEnd( oSettings );
- _fnDraw( oSettings );
- } );
- },
- "sName": "pagination"
- } );
- }
- return nPaginate;
+ aLayout.push( [] );
}
-
-
- /**
- * Alter the display settings to change the page
- * @param {object} oSettings dataTables settings object
- * @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last"
- * or page number to jump to (integer)
- * @returns {bool} true page has changed, false - no change (no effect) eg 'first' on page 1
- * @memberof DataTable#oApi
- */
- function _fnPageChange ( oSettings, mAction )
+
+ /* Calculate a layout array */
+ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
{
- var iOldStart = oSettings._iDisplayStart;
-
- if ( typeof mAction === "number" )
- {
- oSettings._iDisplayStart = mAction * oSettings._iDisplayLength;
- if ( oSettings._iDisplayStart > oSettings.fnRecordsDisplay() )
+ nTr = nTrs[i];
+ iColumn = 0;
+
+ /* For every cell in the row... */
+ nCell = nTr.firstChild;
+ while ( nCell ) {
+ if ( nCell.nodeName.toUpperCase() == "TD" ||
+ nCell.nodeName.toUpperCase() == "TH" )
{
- oSettings._iDisplayStart = 0;
+ /* Get the col and rowspan attributes from the DOM and sanitise them */
+ iColspan = nCell.getAttribute('colspan') * 1;
+ iRowspan = nCell.getAttribute('rowspan') * 1;
+ iColspan = (!iColspan || iColspan===0 || iColspan===1) ? 1 : iColspan;
+ iRowspan = (!iRowspan || iRowspan===0 || iRowspan===1) ? 1 : iRowspan;
+
+ /* There might be colspan cells already in this row, so shift our target
+ * accordingly
+ */
+ iColShifted = fnShiftCol( aLayout, i, iColumn );
+
+ /* Cache calculation for unique columns */
+ bUnique = iColspan === 1 ? true : false;
+
+ /* If there is col / rowspan, copy the information into the layout grid */
+ for ( l=0 ; l<iColspan ; l++ )
+ {
+ for ( k=0 ; k<iRowspan ; k++ )
+ {
+ aLayout[i+k][iColShifted+l] = {
+ "cell": nCell,
+ "unique": bUnique
+ };
+ aLayout[i+k].nTr = nTr;
+ }
+ }
}
+ nCell = nCell.nextSibling;
}
- else if ( mAction == "first" )
+ }
+ }
+
+
+ /**
+ * Get an array of unique th elements, one for each column
+ * @param {object} oSettings dataTables settings object
+ * @param {node} nHeader automatically detect the layout from this node - optional
+ * @param {array} aLayout thead/tfoot layout from _fnDetectHeader - optional
+ * @returns array {node} aReturn list of unique th's
+ * @memberof DataTable#oApi
+ */
+ function _fnGetUniqueThs ( oSettings, nHeader, aLayout )
+ {
+ var aReturn = [];
+ if ( !aLayout )
+ {
+ aLayout = oSettings.aoHeader;
+ if ( nHeader )
{
- oSettings._iDisplayStart = 0;
+ aLayout = [];
+ _fnDetectHeader( aLayout, nHeader );
}
- else if ( mAction == "previous" )
+ }
+
+ for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ )
+ {
+ for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ )
{
- oSettings._iDisplayStart = oSettings._iDisplayLength>=0 ?
- oSettings._iDisplayStart - oSettings._iDisplayLength :
- 0;
-
- /* Correct for under-run */
- if ( oSettings._iDisplayStart < 0 )
+ if ( aLayout[i][j].unique &&
+ (!aReturn[j] || !oSettings.bSortCellsTop) )
{
- oSettings._iDisplayStart = 0;
+ aReturn[j] = aLayout[i][j].cell;
}
}
- else if ( mAction == "next" )
- {
- if ( oSettings._iDisplayLength >= 0 )
- {
- /* Make sure we are not over running the display array */
- if ( oSettings._iDisplayStart + oSettings._iDisplayLength < oSettings.fnRecordsDisplay() )
- {
- oSettings._iDisplayStart += oSettings._iDisplayLength;
+ }
+
+ return aReturn;
+ }
+
+ /**
+ * Create an Ajax call based on the table's settings, taking into account that
+ * parameters can have multiple forms, and backwards compatibility.
+ *
+ * @param {object} oSettings dataTables settings object
+ * @param {array} data Data to send to the server, required by
+ * DataTables - may be augmented by developer callbacks
+ * @param {function} fn Callback function to run when data is obtained
+ */
+ function _fnBuildAjax( oSettings, data, fn )
+ {
+ // Compatibility with 1.9-, allow fnServerData and event to manipulate
+ _fnCallbackFire( oSettings, 'aoServerParams', 'serverParams', [data] );
+
+ // Convert to object based for 1.10+ if using the old array scheme which can
+ // come from server-side processing or serverParams
+ if ( data && $.isArray(data) ) {
+ var tmp = {};
+ var rbracket = /(.*?)\[\]$/;
+
+ $.each( data, function (key, val) {
+ var match = val.name.match(rbracket);
+
+ if ( match ) {
+ // Support for arrays
+ var name = match[0];
+
+ if ( ! tmp[ name ] ) {
+ tmp[ name ] = [];
}
+ tmp[ name ].push( val.value );
}
- else
- {
- oSettings._iDisplayStart = 0;
+ else {
+ tmp[val.name] = val.value;
}
- }
- else if ( mAction == "last" )
- {
- if ( oSettings._iDisplayLength >= 0 )
- {
- var iPages = parseInt( (oSettings.fnRecordsDisplay()-1) / oSettings._iDisplayLength, 10 ) + 1;
- oSettings._iDisplayStart = (iPages-1) * oSettings._iDisplayLength;
+ } );
+ data = tmp;
+ }
+
+ var ajaxData;
+ var ajax = oSettings.ajax;
+ var instance = oSettings.oInstance;
+ var callback = function ( json ) {
+ _fnCallbackFire( oSettings, null, 'xhr', [oSettings, json, oSettings.jqXHR] );
+ fn( json );
+ };
+
+ if ( $.isPlainObject( ajax ) && ajax.data )
+ {
+ ajaxData = ajax.data;
+
+ var newData = $.isFunction( ajaxData ) ?
+ ajaxData( data, oSettings ) : // fn can manipulate data or return
+ ajaxData; // an object object or array to merge
+
+ // If the function returned something, use that alone
+ data = $.isFunction( ajaxData ) && newData ?
+ newData :
+ $.extend( true, data, newData );
+
+ // Remove the data property as we've resolved it already and don't want
+ // jQuery to do it again (it is restored at the end of the function)
+ delete ajax.data;
+ }
+
+ var baseAjax = {
+ "data": data,
+ "success": function (json) {
+ var error = json.error || json.sError;
+ if ( error ) {
+ _fnLog( oSettings, 0, error );
}
- else
- {
- oSettings._iDisplayStart = 0;
+
+ oSettings.json = json;
+ callback( json );
+ },
+ "dataType": "json",
+ "cache": false,
+ "type": oSettings.sServerMethod,
+ "error": function (xhr, error, thrown) {
+ var ret = _fnCallbackFire( oSettings, null, 'xhr', [oSettings, null, oSettings.jqXHR] );
+
+ if ( $.inArray( true, ret ) === -1 ) {
+ if ( error == "parsererror" ) {
+ _fnLog( oSettings, 0, 'Invalid JSON response', 1 );
+ }
+ else if ( xhr.readyState === 4 ) {
+ _fnLog( oSettings, 0, 'Ajax error', 7 );
+ }
}
+
+ _fnProcessingDisplay( oSettings, false );
}
- else
- {
- _fnLog( oSettings, 0, "Unknown paging action: "+mAction );
- }
- $(oSettings.oInstance).trigger('page', oSettings);
-
- return iOldStart != oSettings._iDisplayStart;
+ };
+
+ // Store the data submitted for the API
+ oSettings.oAjaxData = data;
+
+ // Allow plug-ins and external processes to modify the data
+ _fnCallbackFire( oSettings, null, 'preXhr', [oSettings, data] );
+
+ if ( oSettings.fnServerData )
+ {
+ // DataTables 1.9- compatibility
+ oSettings.fnServerData.call( instance,
+ oSettings.sAjaxSource,
+ $.map( data, function (val, key) { // Need to convert back to 1.9 trad format
+ return { name: key, value: val };
+ } ),
+ callback,
+ oSettings
+ );
}
-
-
-
- /**
- * Generate the node required for the processing node
- * @param {object} oSettings dataTables settings object
- * @returns {node} Processing element
- * @memberof DataTable#oApi
- */
- function _fnFeatureHtmlProcessing ( oSettings )
+ else if ( oSettings.sAjaxSource || typeof ajax === 'string' )
{
- var nProcessing = document.createElement( 'div' );
-
- if ( !oSettings.aanFeatures.r )
- {
- nProcessing.id = oSettings.sTableId+'_processing';
- }
- nProcessing.innerHTML = oSettings.oLanguage.sProcessing;
- nProcessing.className = oSettings.oClasses.sProcessing;
- oSettings.nTable.parentNode.insertBefore( nProcessing, oSettings.nTable );
-
- return nProcessing;
+ // DataTables 1.9- compatibility
+ oSettings.jqXHR = $.ajax( $.extend( baseAjax, {
+ url: ajax || oSettings.sAjaxSource
+ } ) );
}
-
-
- /**
- * Display or hide the processing indicator
- * @param {object} oSettings dataTables settings object
- * @param {bool} bShow Show the processing indicator (true) or not (false)
- * @memberof DataTable#oApi
- */
- function _fnProcessingDisplay ( oSettings, bShow )
+ else if ( $.isFunction( ajax ) )
{
- if ( oSettings.oFeatures.bProcessing )
- {
- var an = oSettings.aanFeatures.r;
- for ( var i=0, iLen=an.length ; i<iLen ; i++ )
- {
- an[i].style.visibility = bShow ? "visible" : "hidden";
- }
- }
-
- $(oSettings.oInstance).trigger('processing', [oSettings, bShow]);
+ // Is a function - let the caller define what needs to be done
+ oSettings.jqXHR = ajax.call( instance, data, callback, oSettings );
}
-
- /**
- * Add any control elements for the table - specifically scrolling
- * @param {object} oSettings dataTables settings object
- * @returns {node} Node to add to the DOM
- * @memberof DataTable#oApi
- */
- function _fnFeatureHtmlTable ( oSettings )
+ else
{
- /* Check if scrolling is enabled or not - if not then leave the DOM unaltered */
- if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY === "" )
- {
- return oSettings.nTable;
- }
-
- /*
- * The HTML structure that we want to generate in this function is:
- * div - nScroller
- * div - nScrollHead
- * div - nScrollHeadInner
- * table - nScrollHeadTable
- * thead - nThead
- * div - nScrollBody
- * table - oSettings.nTable
- * thead - nTheadSize
- * tbody - nTbody
- * div - nScrollFoot
- * div - nScrollFootInner
- * table - nScrollFootTable
- * tfoot - nTfoot
- */
- var
- nScroller = document.createElement('div'),
- nScrollHead = document.createElement('div'),
- nScrollHeadInner = document.createElement('div'),
- nScrollBody = document.createElement('div'),
- nScrollFoot = document.createElement('div'),
- nScrollFootInner = document.createElement('div'),
- nScrollHeadTable = oSettings.nTable.cloneNode(false),
- nScrollFootTable = oSettings.nTable.cloneNode(false),
- nThead = oSettings.nTable.getElementsByTagName('thead')[0],
- nTfoot = oSettings.nTable.getElementsByTagName('tfoot').length === 0 ? null :
- oSettings.nTable.getElementsByTagName('tfoot')[0],
- oClasses = oSettings.oClasses;
-
- nScrollHead.appendChild( nScrollHeadInner );
- nScrollFoot.appendChild( nScrollFootInner );
- nScrollBody.appendChild( oSettings.nTable );
- nScroller.appendChild( nScrollHead );
- nScroller.appendChild( nScrollBody );
- nScrollHeadInner.appendChild( nScrollHeadTable );
- nScrollHeadTable.appendChild( nThead );
- if ( nTfoot !== null )
- {
- nScroller.appendChild( nScrollFoot );
- nScrollFootInner.appendChild( nScrollFootTable );
- nScrollFootTable.appendChild( nTfoot );
- }
-
- nScroller.className = oClasses.sScrollWrapper;
- nScrollHead.className = oClasses.sScrollHead;
- nScrollHeadInner.className = oClasses.sScrollHeadInner;
- nScrollBody.className = oClasses.sScrollBody;
- nScrollFoot.className = oClasses.sScrollFoot;
- nScrollFootInner.className = oClasses.sScrollFootInner;
-
- if ( oSettings.oScroll.bAutoCss )
- {
- nScrollHead.style.overflow = "hidden";
- nScrollHead.style.position = "relative";
- nScrollFoot.style.overflow = "hidden";
- nScrollBody.style.overflow = "auto";
- }
-
- nScrollHead.style.border = "0";
- nScrollHead.style.width = "100%";
- nScrollFoot.style.border = "0";
- nScrollHeadInner.style.width = oSettings.oScroll.sXInner !== "" ?
- oSettings.oScroll.sXInner : "100%"; /* will be overwritten */
-
- /* Modify attributes to respect the clones */
- nScrollHeadTable.removeAttribute('id');
- nScrollHeadTable.style.marginLeft = "0";
- oSettings.nTable.style.marginLeft = "0";
- if ( nTfoot !== null )
- {
- nScrollFootTable.removeAttribute('id');
- nScrollFootTable.style.marginLeft = "0";
- }
-
- /* Move caption elements from the body to the header, footer or leave where it is
- * depending on the configuration. Note that the DTD says there can be only one caption */
- var nCaption = $(oSettings.nTable).children('caption');
- if ( nCaption.length > 0 )
- {
- nCaption = nCaption[0];
- if ( nCaption._captionSide === "top" )
- {
- nScrollHeadTable.appendChild( nCaption );
- }
- else if ( nCaption._captionSide === "bottom" && nTfoot )
- {
- nScrollFootTable.appendChild( nCaption );
+ // Object to extend the base settings
+ oSettings.jqXHR = $.ajax( $.extend( baseAjax, ajax ) );
+
+ // Restore for next time around
+ ajax.data = ajaxData;
+ }
+ }
+
+
+ /**
+ * Update the table using an Ajax call
+ * @param {object} settings dataTables settings object
+ * @returns {boolean} Block the table drawing or not
+ * @memberof DataTable#oApi
+ */
+ function _fnAjaxUpdate( settings )
+ {
+ if ( settings.bAjaxDataGet ) {
+ settings.iDraw++;
+ _fnProcessingDisplay( settings, true );
+
+ _fnBuildAjax(
+ settings,
+ _fnAjaxParameters( settings ),
+ function(json) {
+ _fnAjaxUpdateDraw( settings, json );
}
+ );
+
+ return false;
+ }
+ return true;
+ }
+
+
+ /**
+ * Build up the parameters in an object needed for a server-side processing
+ * request. Note that this is basically done twice, is different ways - a modern
+ * method which is used by default in DataTables 1.10 which uses objects and
+ * arrays, or the 1.9- method with is name / value pairs. 1.9 method is used if
+ * the sAjaxSource option is used in the initialisation, or the legacyAjax
+ * option is set.
+ * @param {object} oSettings dataTables settings object
+ * @returns {bool} block the table drawing or not
+ * @memberof DataTable#oApi
+ */
+ function _fnAjaxParameters( settings )
+ {
+ var
+ columns = settings.aoColumns,
+ columnCount = columns.length,
+ features = settings.oFeatures,
+ preSearch = settings.oPreviousSearch,
+ preColSearch = settings.aoPreSearchCols,
+ i, data = [], dataProp, column, columnSearch,
+ sort = _fnSortFlatten( settings ),
+ displayStart = settings._iDisplayStart,
+ displayLength = features.bPaginate !== false ?
+ settings._iDisplayLength :
+ -1;
+
+ var param = function ( name, value ) {
+ data.push( { 'name': name, 'value': value } );
+ };
+
+ // DataTables 1.9- compatible method
+ param( 'sEcho', settings.iDraw );
+ param( 'iColumns', columnCount );
+ param( 'sColumns', _pluck( columns, 'sName' ).join(',') );
+ param( 'iDisplayStart', displayStart );
+ param( 'iDisplayLength', displayLength );
+
+ // DataTables 1.10+ method
+ var d = {
+ draw: settings.iDraw,
+ columns: [],
+ order: [],
+ start: displayStart,
+ length: displayLength,
+ search: {
+ value: preSearch.sSearch,
+ regex: preSearch.bRegex
}
-
- /*
- * Sizing
- */
- /* When x-scrolling add the width and a scroller to move the header with the body */
- if ( oSettings.oScroll.sX !== "" )
- {
- nScrollHead.style.width = _fnStringToCss( oSettings.oScroll.sX );
- nScrollBody.style.width = _fnStringToCss( oSettings.oScroll.sX );
-
- if ( nTfoot !== null )
- {
- nScrollFoot.style.width = _fnStringToCss( oSettings.oScroll.sX );
+ };
+
+ for ( i=0 ; i<columnCount ; i++ ) {
+ column = columns[i];
+ columnSearch = preColSearch[i];
+ dataProp = typeof column.mData=="function" ? 'function' : column.mData ;
+
+ d.columns.push( {
+ data: dataProp,
+ name: column.sName,
+ searchable: column.bSearchable,
+ orderable: column.bSortable,
+ search: {
+ value: columnSearch.sSearch,
+ regex: columnSearch.bRegex
}
-
- /* When the body is scrolled, then we also want to scroll the headers */
- $(nScrollBody).scroll( function (e) {
- nScrollHead.scrollLeft = this.scrollLeft;
-
- if ( nTfoot !== null )
- {
- nScrollFoot.scrollLeft = this.scrollLeft;
- }
- } );
+ } );
+
+ param( "mDataProp_"+i, dataProp );
+
+ if ( features.bFilter ) {
+ param( 'sSearch_'+i, columnSearch.sSearch );
+ param( 'bRegex_'+i, columnSearch.bRegex );
+ param( 'bSearchable_'+i, column.bSearchable );
}
-
- /* When yscrolling, add the height */
- if ( oSettings.oScroll.sY !== "" )
- {
- nScrollBody.style.height = _fnStringToCss( oSettings.oScroll.sY );
+
+ if ( features.bSort ) {
+ param( 'bSortable_'+i, column.bSortable );
}
-
- /* Redraw - align columns across the tables */
- oSettings.aoDrawCallback.push( {
- "fn": _fnScrollDraw,
- "sName": "scrolling"
+ }
+
+ if ( features.bFilter ) {
+ param( 'sSearch', preSearch.sSearch );
+ param( 'bRegex', preSearch.bRegex );
+ }
+
+ if ( features.bSort ) {
+ $.each( sort, function ( i, val ) {
+ d.order.push( { column: val.col, dir: val.dir } );
+
+ param( 'iSortCol_'+i, val.col );
+ param( 'sSortDir_'+i, val.dir );
} );
-
- /* Infinite scrolling event handlers */
- if ( oSettings.oScroll.bInfinite )
- {
- $(nScrollBody).scroll( function() {
- /* Use a blocker to stop scrolling from loading more data while other data is still loading */
- if ( !oSettings.bDrawing && $(this).scrollTop() !== 0 )
- {
- /* Check if we should load the next data set */
- if ( $(this).scrollTop() + $(this).height() >
- $(oSettings.nTable).height() - oSettings.oScroll.iLoadGap )
- {
- /* Only do the redraw if we have to - we might be at the end of the data */
- if ( oSettings.fnDisplayEnd() < oSettings.fnRecordsDisplay() )
- {
- _fnPageChange( oSettings, 'next' );
- _fnCalculateEnd( oSettings );
- _fnDraw( oSettings );
- }
- }
- }
- } );
- }
-
- oSettings.nScrollHead = nScrollHead;
- oSettings.nScrollFoot = nScrollFoot;
-
- return nScroller;
+
+ param( 'iSortingCols', sort.length );
}
-
-
- /**
- * Update the various tables for resizing. It's a bit of a pig this function, but
- * basically the idea to:
- * 1. Re-create the table inside the scrolling div
- * 2. Take live measurements from the DOM
- * 3. Apply the measurements
- * 4. Clean up
- * @param {object} o dataTables settings object
- * @returns {node} Node to add to the DOM
- * @memberof DataTable#oApi
- */
- function _fnScrollDraw ( o )
- {
- var
- nScrollHeadInner = o.nScrollHead.getElementsByTagName('div')[0],
- nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0],
- nScrollBody = o.nTable.parentNode,
- i, iLen, j, jLen, anHeadToSize, anHeadSizers, anFootSizers, anFootToSize, oStyle, iVis,
- nTheadSize, nTfootSize,
- iWidth, aApplied=[], aAppliedFooter=[], iSanityWidth,
- nScrollFootInner = (o.nTFoot !== null) ? o.nScrollFoot.getElementsByTagName('div')[0] : null,
- nScrollFootTable = (o.nTFoot !== null) ? nScrollFootInner.getElementsByTagName('table')[0] : null,
- ie67 = o.oBrowser.bScrollOversize,
- zeroOut = function(nSizer) {
- oStyle = nSizer.style;
- oStyle.paddingTop = "0";
- oStyle.paddingBottom = "0";
- oStyle.borderTopWidth = "0";
- oStyle.borderBottomWidth = "0";
- oStyle.height = 0;
- };
-
- /*
- * 1. Re-create the table inside the scrolling div
- */
-
- /* Remove the old minimised thead and tfoot elements in the inner table */
- $(o.nTable).children('thead, tfoot').remove();
-
- /* Clone the current header and footer elements and then place it into the inner table */
- nTheadSize = $(o.nTHead).clone()[0];
- o.nTable.insertBefore( nTheadSize, o.nTable.childNodes[0] );
- anHeadToSize = o.nTHead.getElementsByTagName('tr');
- anHeadSizers = nTheadSize.getElementsByTagName('tr');
-
- if ( o.nTFoot !== null )
- {
- nTfootSize = $(o.nTFoot).clone()[0];
- o.nTable.insertBefore( nTfootSize, o.nTable.childNodes[1] );
- anFootToSize = o.nTFoot.getElementsByTagName('tr');
- anFootSizers = nTfootSize.getElementsByTagName('tr');
- }
-
- /*
- * 2. Take live measurements from the DOM - do not alter the DOM itself!
- */
-
- /* Remove old sizing and apply the calculated column widths
- * Get the unique column headers in the newly created (cloned) header. We want to apply the
- * calculated sizes to this header
- */
- if ( o.oScroll.sX === "" )
- {
- nScrollBody.style.width = '100%';
- nScrollHeadInner.parentNode.style.width = '100%';
- }
-
- var nThs = _fnGetUniqueThs( o, nTheadSize );
- for ( i=0, iLen=nThs.length ; i<iLen ; i++ )
- {
- iVis = _fnVisibleToColumnIndex( o, i );
- nThs[i].style.width = o.aoColumns[iVis].sWidth;
- }
-
- if ( o.nTFoot !== null )
- {
- _fnApplyToChildren( function(n) {
- n.style.width = "";
- }, anFootSizers );
- }
-
- // If scroll collapse is enabled, when we put the headers back into the body for sizing, we
- // will end up forcing the scrollbar to appear, making our measurements wrong for when we
- // then hide it (end of this function), so add the header height to the body scroller.
- if ( o.oScroll.bCollapse && o.oScroll.sY !== "" )
- {
- nScrollBody.style.height = (nScrollBody.offsetHeight + o.nTHead.offsetHeight)+"px";
+
+ // If the legacy.ajax parameter is null, then we automatically decide which
+ // form to use, based on sAjaxSource
+ var legacy = DataTable.ext.legacy.ajax;
+ if ( legacy === null ) {
+ return settings.sAjaxSource ? data : d;
+ }
+
+ // Otherwise, if legacy has been specified then we use that to decide on the
+ // form
+ return legacy ? data : d;
+ }
+
+
+ /**
+ * Data the data from the server (nuking the old) and redraw the table
+ * @param {object} oSettings dataTables settings object
+ * @param {object} json json data return from the server.
+ * @param {string} json.sEcho Tracking flag for DataTables to match requests
+ * @param {int} json.iTotalRecords Number of records in the data set, not accounting for filtering
+ * @param {int} json.iTotalDisplayRecords Number of records in the data set, accounting for filtering
+ * @param {array} json.aaData The data to display on this page
+ * @param {string} [json.sColumns] Column ordering (sName, comma separated)
+ * @memberof DataTable#oApi
+ */
+ function _fnAjaxUpdateDraw ( settings, json )
+ {
+ // v1.10 uses camelCase variables, while 1.9 uses Hungarian notation.
+ // Support both
+ var compat = function ( old, modern ) {
+ return json[old] !== undefined ? json[old] : json[modern];
+ };
+
+ var data = _fnAjaxDataSrc( settings, json );
+ var draw = compat( 'sEcho', 'draw' );
+ var recordsTotal = compat( 'iTotalRecords', 'recordsTotal' );
+ var recordsFiltered = compat( 'iTotalDisplayRecords', 'recordsFiltered' );
+
+ if ( draw ) {
+ // Protect against out of sequence returns
+ if ( draw*1 < settings.iDraw ) {
+ return;
}
-
- /* Size the table as a whole */
- iSanityWidth = $(o.nTable).outerWidth();
- if ( o.oScroll.sX === "" )
- {
- /* No x scrolling */
- o.nTable.style.width = "100%";
-
- /* I know this is rubbish - but IE7 will make the width of the table when 100% include
- * the scrollbar - which is shouldn't. When there is a scrollbar we need to take this
- * into account.
- */
- if ( ie67 && ($('tbody', nScrollBody).height() > nScrollBody.offsetHeight ||
- $(nScrollBody).css('overflow-y') == "scroll") )
- {
- o.nTable.style.width = _fnStringToCss( $(o.nTable).outerWidth() - o.oScroll.iBarWidth);
- }
+ settings.iDraw = draw * 1;
+ }
+
+ _fnClearTable( settings );
+ settings._iRecordsTotal = parseInt(recordsTotal, 10);
+ settings._iRecordsDisplay = parseInt(recordsFiltered, 10);
+
+ for ( var i=0, ien=data.length ; i<ien ; i++ ) {
+ _fnAddData( settings, data[i] );
+ }
+ settings.aiDisplay = settings.aiDisplayMaster.slice();
+
+ settings.bAjaxDataGet = false;
+ _fnDraw( settings );
+
+ if ( ! settings._bInitComplete ) {
+ _fnInitComplete( settings, json );
+ }
+
+ settings.bAjaxDataGet = true;
+ _fnProcessingDisplay( settings, false );
+ }
+
+
+ /**
+ * Get the data from the JSON data source to use for drawing a table. Using
+ * `_fnGetObjectDataFn` allows the data to be sourced from a property of the
+ * source object, or from a processing function.
+ * @param {object} oSettings dataTables settings object
+ * @param {object} json Data source object / array from the server
+ * @return {array} Array of data to use
+ */
+ function _fnAjaxDataSrc ( oSettings, json )
+ {
+ var dataSrc = $.isPlainObject( oSettings.ajax ) && oSettings.ajax.dataSrc !== undefined ?
+ oSettings.ajax.dataSrc :
+ oSettings.sAjaxDataProp; // Compatibility with 1.9-.
+
+ // Compatibility with 1.9-. In order to read from aaData, check if the
+ // default has been changed, if not, check for aaData
+ if ( dataSrc === 'data' ) {
+ return json.aaData || json[dataSrc];
+ }
+
+ return dataSrc !== "" ?
+ _fnGetObjectDataFn( dataSrc )( json ) :
+ json;
+ }
+
+ /**
+ * Generate the node required for filtering text
+ * @returns {node} Filter control element
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnFeatureHtmlFilter ( settings )
+ {
+ var classes = settings.oClasses;
+ var tableId = settings.sTableId;
+ var language = settings.oLanguage;
+ var previousSearch = settings.oPreviousSearch;
+ var features = settings.aanFeatures;
+ var input = '<input type="search" class="'+classes.sFilterInput+'"/>';
+
+ var str = language.sSearch;
+ str = str.match(/_INPUT_/) ?
+ str.replace('_INPUT_', input) :
+ str+input;
+
+ var filter = $('<div/>', {
+ 'id': ! features.f ? tableId+'_filter' : null,
+ 'class': classes.sFilter
+ } )
+ .append( $('<label/>' ).append( str ) );
+
+ var searchFn = function() {
+ /* Update all other filter input elements for the new display */
+ var n = features.f;
+ var val = !this.value ? "" : this.value; // mental IE8 fix :-(
+
+ /* Now do the filter */
+ if ( val != previousSearch.sSearch ) {
+ _fnFilterComplete( settings, {
+ "sSearch": val,
+ "bRegex": previousSearch.bRegex,
+ "bSmart": previousSearch.bSmart ,
+ "bCaseInsensitive": previousSearch.bCaseInsensitive
+ } );
+
+ // Need to redraw, without resorting
+ settings._iDisplayStart = 0;
+ _fnDraw( settings );
}
- else
- {
- if ( o.oScroll.sXInner !== "" )
- {
- /* x scroll inner has been given - use it */
- o.nTable.style.width = _fnStringToCss(o.oScroll.sXInner);
+ };
+
+ var searchDelay = settings.searchDelay !== null ?
+ settings.searchDelay :
+ _fnDataSource( settings ) === 'ssp' ?
+ 400 :
+ 0;
+
+ var jqFilter = $('input', filter)
+ .val( previousSearch.sSearch )
+ .attr( 'placeholder', language.sSearchPlaceholder )
+ .bind(
+ 'keyup.DT search.DT input.DT paste.DT cut.DT',
+ searchDelay ?
+ _fnThrottle( searchFn, searchDelay ) :
+ searchFn
+ )
+ .bind( 'keypress.DT', function(e) {
+ /* Prevent form submission */
+ if ( e.keyCode == 13 ) {
+ return false;
}
- else if ( iSanityWidth == $(nScrollBody).width() &&
- $(nScrollBody).height() < $(o.nTable).height() )
- {
- /* There is y-scrolling - try to take account of the y scroll bar */
- o.nTable.style.width = _fnStringToCss( iSanityWidth-o.oScroll.iBarWidth );
- if ( $(o.nTable).outerWidth() > iSanityWidth-o.oScroll.iBarWidth )
- {
- /* Not possible to take account of it */
- o.nTable.style.width = _fnStringToCss( iSanityWidth );
+ } )
+ .attr('aria-controls', tableId);
+
+ // Update the input elements whenever the table is filtered
+ $(settings.nTable).on( 'search.dt.DT', function ( ev, s ) {
+ if ( settings === s ) {
+ // IE9 throws an 'unknown error' if document.activeElement is used
+ // inside an iframe or frame...
+ try {
+ if ( jqFilter[0] !== document.activeElement ) {
+ jqFilter.val( previousSearch.sSearch );
}
}
- else
- {
- /* All else fails */
- o.nTable.style.width = _fnStringToCss( iSanityWidth );
- }
+ catch ( e ) {}
}
-
- /* Recalculate the sanity width - now that we've applied the required width, before it was
- * a temporary variable. This is required because the column width calculation is done
- * before this table DOM is created.
- */
- iSanityWidth = $(o.nTable).outerWidth();
-
- /* We want the hidden header to have zero height, so remove padding and borders. Then
- * set the width based on the real headers
- */
-
- // Apply all styles in one pass. Invalidates layout only once because we don't read any
- // DOM properties.
- _fnApplyToChildren( zeroOut, anHeadSizers );
-
- // Read all widths in next pass. Forces layout only once because we do not change
- // any DOM properties.
- _fnApplyToChildren( function(nSizer) {
- aApplied.push( _fnStringToCss( $(nSizer).width() ) );
- }, anHeadSizers );
-
- // Apply all widths in final pass. Invalidates layout only once because we do not
- // read any DOM properties.
- _fnApplyToChildren( function(nToSize, i) {
- nToSize.style.width = aApplied[i];
- }, anHeadToSize );
-
- $(anHeadSizers).height(0);
-
- /* Same again with the footer if we have one */
- if ( o.nTFoot !== null )
- {
- _fnApplyToChildren( zeroOut, anFootSizers );
-
- _fnApplyToChildren( function(nSizer) {
- aAppliedFooter.push( _fnStringToCss( $(nSizer).width() ) );
- }, anFootSizers );
-
- _fnApplyToChildren( function(nToSize, i) {
- nToSize.style.width = aAppliedFooter[i];
- }, anFootToSize );
-
- $(anFootSizers).height(0);
- }
-
- /*
- * 3. Apply the measurements
- */
-
- /* "Hide" the header and footer that we used for the sizing. We want to also fix their width
- * to what they currently are
- */
- _fnApplyToChildren( function(nSizer, i) {
- nSizer.innerHTML = "";
- nSizer.style.width = aApplied[i];
- }, anHeadSizers );
-
- if ( o.nTFoot !== null )
+ } );
+
+ return filter[0];
+ }
+
+
+ /**
+ * Filter the table using both the global filter and column based filtering
+ * @param {object} oSettings dataTables settings object
+ * @param {object} oSearch search information
+ * @param {int} [iForce] force a research of the master array (1) or not (undefined or 0)
+ * @memberof DataTable#oApi
+ */
+ function _fnFilterComplete ( oSettings, oInput, iForce )
+ {
+ var oPrevSearch = oSettings.oPreviousSearch;
+ var aoPrevSearch = oSettings.aoPreSearchCols;
+ var fnSaveFilter = function ( oFilter ) {
+ /* Save the filtering values */
+ oPrevSearch.sSearch = oFilter.sSearch;
+ oPrevSearch.bRegex = oFilter.bRegex;
+ oPrevSearch.bSmart = oFilter.bSmart;
+ oPrevSearch.bCaseInsensitive = oFilter.bCaseInsensitive;
+ };
+ var fnRegex = function ( o ) {
+ // Backwards compatibility with the bEscapeRegex option
+ return o.bEscapeRegex !== undefined ? !o.bEscapeRegex : o.bRegex;
+ };
+
+ // Resolve any column types that are unknown due to addition or invalidation
+ // @todo As per sort - can this be moved into an event handler?
+ _fnColumnTypes( oSettings );
+
+ /* In server-side processing all filtering is done by the server, so no point hanging around here */
+ if ( _fnDataSource( oSettings ) != 'ssp' )
+ {
+ /* Global filter */
+ _fnFilter( oSettings, oInput.sSearch, iForce, fnRegex(oInput), oInput.bSmart, oInput.bCaseInsensitive );
+ fnSaveFilter( oInput );
+
+ /* Now do the individual column filter */
+ for ( var i=0 ; i<aoPrevSearch.length ; i++ )
{
- _fnApplyToChildren( function(nSizer, i) {
- nSizer.innerHTML = "";
- nSizer.style.width = aAppliedFooter[i];
- }, anFootSizers );
+ _fnFilterColumn( oSettings, aoPrevSearch[i].sSearch, i, fnRegex(aoPrevSearch[i]),
+ aoPrevSearch[i].bSmart, aoPrevSearch[i].bCaseInsensitive );
}
-
- /* Sanity check that the table is of a sensible width. If not then we are going to get
- * misalignment - try to prevent this by not allowing the table to shrink below its min width
- */
- if ( $(o.nTable).outerWidth() < iSanityWidth )
- {
- /* The min width depends upon if we have a vertical scrollbar visible or not */
- var iCorrection = ((nScrollBody.scrollHeight > nScrollBody.offsetHeight ||
- $(nScrollBody).css('overflow-y') == "scroll")) ?
- iSanityWidth+o.oScroll.iBarWidth : iSanityWidth;
-
- /* IE6/7 are a law unto themselves... */
- if ( ie67 && (nScrollBody.scrollHeight >
- nScrollBody.offsetHeight || $(nScrollBody).css('overflow-y') == "scroll") )
- {
- o.nTable.style.width = _fnStringToCss( iCorrection-o.oScroll.iBarWidth );
- }
-
- /* Apply the calculated minimum width to the table wrappers */
- nScrollBody.style.width = _fnStringToCss( iCorrection );
- o.nScrollHead.style.width = _fnStringToCss( iCorrection );
-
- if ( o.nTFoot !== null )
- {
- o.nScrollFoot.style.width = _fnStringToCss( iCorrection );
- }
-
- /* And give the user a warning that we've stopped the table getting too small */
- if ( o.oScroll.sX === "" )
- {
- _fnLog( o, 1, "The table cannot fit into the current element which will cause column"+
- " misalignment. The table has been drawn at its minimum possible width." );
- }
- else if ( o.oScroll.sXInner !== "" )
- {
- _fnLog( o, 1, "The table cannot fit into the current element which will cause column"+
- " misalignment. Increase the sScrollXInner value or remove it to allow automatic"+
- " calculation" );
+
+ /* Custom filtering */
+ _fnFilterCustom( oSettings );
+ }
+ else
+ {
+ fnSaveFilter( oInput );
+ }
+
+ /* Tell the draw function we have been filtering */
+ oSettings.bFiltered = true;
+ _fnCallbackFire( oSettings, null, 'search', [oSettings] );
+ }
+
+
+ /**
+ * Apply custom filtering functions
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnFilterCustom( settings )
+ {
+ var filters = DataTable.ext.search;
+ var displayRows = settings.aiDisplay;
+ var row, rowIdx;
+
+ for ( var i=0, ien=filters.length ; i<ien ; i++ ) {
+ var rows = [];
+
+ // Loop over each row and see if it should be included
+ for ( var j=0, jen=displayRows.length ; j<jen ; j++ ) {
+ rowIdx = displayRows[ j ];
+ row = settings.aoData[ rowIdx ];
+
+ if ( filters[i]( settings, row._aFilterData, rowIdx, row._aData, j ) ) {
+ rows.push( rowIdx );
}
}
- else
- {
- nScrollBody.style.width = _fnStringToCss( '100%' );
- o.nScrollHead.style.width = _fnStringToCss( '100%' );
-
- if ( o.nTFoot !== null )
- {
- o.nScrollFoot.style.width = _fnStringToCss( '100%' );
- }
+
+ // So the array reference doesn't break set the results into the
+ // existing array
+ displayRows.length = 0;
+ displayRows.push.apply( displayRows, rows );
+ }
+ }
+
+
+ /**
+ * Filter the table on a per-column basis
+ * @param {object} oSettings dataTables settings object
+ * @param {string} sInput string to filter on
+ * @param {int} iColumn column to filter
+ * @param {bool} bRegex treat search string as a regular expression or not
+ * @param {bool} bSmart use smart filtering or not
+ * @param {bool} bCaseInsensitive Do case insenstive matching or not
+ * @memberof DataTable#oApi
+ */
+ function _fnFilterColumn ( settings, searchStr, colIdx, regex, smart, caseInsensitive )
+ {
+ if ( searchStr === '' ) {
+ return;
+ }
+
+ var data;
+ var display = settings.aiDisplay;
+ var rpSearch = _fnFilterCreateSearch( searchStr, regex, smart, caseInsensitive );
+
+ for ( var i=display.length-1 ; i>=0 ; i-- ) {
+ data = settings.aoData[ display[i] ]._aFilterData[ colIdx ];
+
+ if ( ! rpSearch.test( data ) ) {
+ display.splice( i, 1 );
}
-
-
- /*
- * 4. Clean up
- */
- if ( o.oScroll.sY === "" )
- {
- /* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting
- * the scrollbar height from the visible display, rather than adding it on. We need to
- * set the height in order to sort this. Don't want to do it in any other browsers.
- */
- if ( ie67 )
- {
- nScrollBody.style.height = _fnStringToCss( o.nTable.offsetHeight+o.oScroll.iBarWidth );
- }
+ }
+ }
+
+
+ /**
+ * Filter the data table based on user input and draw the table
+ * @param {object} settings dataTables settings object
+ * @param {string} input string to filter on
+ * @param {int} force optional - force a research of the master array (1) or not (undefined or 0)
+ * @param {bool} regex treat as a regular expression or not
+ * @param {bool} smart perform smart filtering or not
+ * @param {bool} caseInsensitive Do case insenstive matching or not
+ * @memberof DataTable#oApi
+ */
+ function _fnFilter( settings, input, force, regex, smart, caseInsensitive )
+ {
+ var rpSearch = _fnFilterCreateSearch( input, regex, smart, caseInsensitive );
+ var prevSearch = settings.oPreviousSearch.sSearch;
+ var displayMaster = settings.aiDisplayMaster;
+ var display, invalidated, i;
+
+ // Need to take account of custom filtering functions - always filter
+ if ( DataTable.ext.search.length !== 0 ) {
+ force = true;
+ }
+
+ // Check if any of the rows were invalidated
+ invalidated = _fnFilterData( settings );
+
+ // If the input is blank - we just want the full data set
+ if ( input.length <= 0 ) {
+ settings.aiDisplay = displayMaster.slice();
+ }
+ else {
+ // New search - start from the master array
+ if ( invalidated ||
+ force ||
+ prevSearch.length > input.length ||
+ input.indexOf(prevSearch) !== 0 ||
+ settings.bSorted // On resort, the display master needs to be
+ // re-filtered since indexes will have changed
+ ) {
+ settings.aiDisplay = displayMaster.slice();
}
-
- if ( o.oScroll.sY !== "" && o.oScroll.bCollapse )
- {
- nScrollBody.style.height = _fnStringToCss( o.oScroll.sY );
-
- var iExtra = (o.oScroll.sX !== "" && o.nTable.offsetWidth > nScrollBody.offsetWidth) ?
- o.oScroll.iBarWidth : 0;
- if ( o.nTable.offsetHeight < nScrollBody.offsetHeight )
- {
- nScrollBody.style.height = _fnStringToCss( o.nTable.offsetHeight+iExtra );
+
+ // Search the display array
+ display = settings.aiDisplay;
+
+ for ( i=display.length-1 ; i>=0 ; i-- ) {
+ if ( ! rpSearch.test( settings.aoData[ display[i] ]._sFilterRow ) ) {
+ display.splice( i, 1 );
}
}
-
- /* Finally set the width's of the header and footer tables */
- var iOuterWidth = $(o.nTable).outerWidth();
- nScrollHeadTable.style.width = _fnStringToCss( iOuterWidth );
- nScrollHeadInner.style.width = _fnStringToCss( iOuterWidth );
-
- // Figure out if there are scrollbar present - if so then we need a the header and footer to
- // provide a bit more space to allow "overflow" scrolling (i.e. past the scrollbar)
- var bScrolling = $(o.nTable).height() > nScrollBody.clientHeight || $(nScrollBody).css('overflow-y') == "scroll";
- nScrollHeadInner.style.paddingRight = bScrolling ? o.oScroll.iBarWidth+"px" : "0px";
-
- if ( o.nTFoot !== null )
- {
- nScrollFootTable.style.width = _fnStringToCss( iOuterWidth );
- nScrollFootInner.style.width = _fnStringToCss( iOuterWidth );
- nScrollFootInner.style.paddingRight = bScrolling ? o.oScroll.iBarWidth+"px" : "0px";
- }
-
- /* Adjust the position of the header in case we loose the y-scrollbar */
- $(nScrollBody).scroll();
-
- /* If sorting or filtering has occurred, jump the scrolling back to the top */
- if ( o.bSorted || o.bFiltered )
- {
- nScrollBody.scrollTop = 0;
- }
}
-
-
- /**
- * Apply a given function to the display child nodes of an element array (typically
- * TD children of TR rows
- * @param {function} fn Method to apply to the objects
- * @param array {nodes} an1 List of elements to look through for display children
- * @param array {nodes} an2 Another list (identical structure to the first) - optional
- * @memberof DataTable#oApi
- */
- function _fnApplyToChildren( fn, an1, an2 )
- {
- var index=0, i=0, iLen=an1.length;
- var nNode1, nNode2;
-
- while ( i < iLen )
- {
- nNode1 = an1[i].firstChild;
- nNode2 = an2 ? an2[i].firstChild : null;
- while ( nNode1 )
- {
- if ( nNode1.nodeType === 1 )
- {
- if ( an2 )
- {
- fn( nNode1, nNode2, index );
+ }
+
+
+ /**
+ * Build a regular expression object suitable for searching a table
+ * @param {string} sSearch string to search for
+ * @param {bool} bRegex treat as a regular expression or not
+ * @param {bool} bSmart perform smart filtering or not
+ * @param {bool} bCaseInsensitive Do case insensitive matching or not
+ * @returns {RegExp} constructed object
+ * @memberof DataTable#oApi
+ */
+ function _fnFilterCreateSearch( search, regex, smart, caseInsensitive )
+ {
+ search = regex ?
+ search :
+ _fnEscapeRegex( search );
+
+ if ( smart ) {
+ /* For smart filtering we want to allow the search to work regardless of
+ * word order. We also want double quoted text to be preserved, so word
+ * order is important - a la google. So this is what we want to
+ * generate:
+ *
+ * ^(?=.*?\bone\b)(?=.*?\btwo three\b)(?=.*?\bfour\b).*$
+ */
+ var a = $.map( search.match( /"[^"]+"|[^ ]+/g ) || [''], function ( word ) {
+ if ( word.charAt(0) === '"' ) {
+ var m = word.match( /^"(.*)"$/ );
+ word = m ? m[1] : word;
+ }
+
+ return word.replace('"', '');
+ } );
+
+ search = '^(?=.*?'+a.join( ')(?=.*?' )+').*$';
+ }
+
+ return new RegExp( search, caseInsensitive ? 'i' : '' );
+ }
+
+
+ /**
+ * Escape a string such that it can be used in a regular expression
+ * @param {string} sVal string to escape
+ * @returns {string} escaped string
+ * @memberof DataTable#oApi
+ */
+ function _fnEscapeRegex ( sVal )
+ {
+ return sVal.replace( _re_escape_regex, '\\$1' );
+ }
+
+
+
+ var __filter_div = $('<div>')[0];
+ var __filter_div_textContent = __filter_div.textContent !== undefined;
+
+ // Update the filtering data for each row if needed (by invalidation or first run)
+ function _fnFilterData ( settings )
+ {
+ var columns = settings.aoColumns;
+ var column;
+ var i, j, ien, jen, filterData, cellData, row;
+ var fomatters = DataTable.ext.type.search;
+ var wasInvalidated = false;
+
+ for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
+ row = settings.aoData[i];
+
+ if ( ! row._aFilterData ) {
+ filterData = [];
+
+ for ( j=0, jen=columns.length ; j<jen ; j++ ) {
+ column = columns[j];
+
+ if ( column.bSearchable ) {
+ cellData = _fnGetCellData( settings, i, j, 'filter' );
+
+ if ( fomatters[ column.sType ] ) {
+ cellData = fomatters[ column.sType ]( cellData );
}
- else
- {
- fn( nNode1, index );
+
+ // Search in DataTables 1.10 is string based. In 1.11 this
+ // should be altered to also allow strict type checking.
+ if ( cellData === null ) {
+ cellData = '';
+ }
+
+ if ( typeof cellData !== 'string' && cellData.toString ) {
+ cellData = cellData.toString();
}
- index++;
}
- nNode1 = nNode1.nextSibling;
- nNode2 = an2 ? nNode2.nextSibling : null;
+ else {
+ cellData = '';
+ }
+
+ // If it looks like there is an HTML entity in the string,
+ // attempt to decode it so sorting works as expected. Note that
+ // we could use a single line of jQuery to do this, but the DOM
+ // method used here is much faster http://jsperf.com/html-decode
+ if ( cellData.indexOf && cellData.indexOf('&') !== -1 ) {
+ __filter_div.innerHTML = cellData;
+ cellData = __filter_div_textContent ?
+ __filter_div.textContent :
+ __filter_div.innerText;
+ }
+
+ if ( cellData.replace ) {
+ cellData = cellData.replace(/[\r\n]/g, '');
+ }
+
+ filterData.push( cellData );
}
- i++;
+
+ row._aFilterData = filterData;
+ row._sFilterRow = filterData.join(' ');
+ wasInvalidated = true;
}
}
-
- /**
- * Convert a CSS unit width to pixels (e.g. 2em)
- * @param {string} sWidth width to be converted
- * @param {node} nParent parent to get the with for (required for relative widths) - optional
- * @returns {int} iWidth width in pixels
- * @memberof DataTable#oApi
- */
- function _fnConvertToWidth ( sWidth, nParent )
- {
- if ( !sWidth || sWidth === null || sWidth === '' )
- {
- return 0;
- }
-
- if ( !nParent )
- {
- nParent = document.body;
+
+ return wasInvalidated;
+ }
+
+
+ /**
+ * Convert from the internal Hungarian notation to camelCase for external
+ * interaction
+ * @param {object} obj Object to convert
+ * @returns {object} Inverted object
+ * @memberof DataTable#oApi
+ */
+ function _fnSearchToCamel ( obj )
+ {
+ return {
+ search: obj.sSearch,
+ smart: obj.bSmart,
+ regex: obj.bRegex,
+ caseInsensitive: obj.bCaseInsensitive
+ };
+ }
+
+
+
+ /**
+ * Convert from camelCase notation to the internal Hungarian. We could use the
+ * Hungarian convert function here, but this is cleaner
+ * @param {object} obj Object to convert
+ * @returns {object} Inverted object
+ * @memberof DataTable#oApi
+ */
+ function _fnSearchToHung ( obj )
+ {
+ return {
+ sSearch: obj.search,
+ bSmart: obj.smart,
+ bRegex: obj.regex,
+ bCaseInsensitive: obj.caseInsensitive
+ };
+ }
+
+ /**
+ * Generate the node required for the info display
+ * @param {object} oSettings dataTables settings object
+ * @returns {node} Information element
+ * @memberof DataTable#oApi
+ */
+ function _fnFeatureHtmlInfo ( settings )
+ {
+ var
+ tid = settings.sTableId,
+ nodes = settings.aanFeatures.i,
+ n = $('<div/>', {
+ 'class': settings.oClasses.sInfo,
+ 'id': ! nodes ? tid+'_info' : null
+ } );
+
+ if ( ! nodes ) {
+ // Update display on each draw
+ settings.aoDrawCallback.push( {
+ "fn": _fnUpdateInfo,
+ "sName": "information"
+ } );
+
+ n
+ .attr( 'role', 'status' )
+ .attr( 'aria-live', 'polite' );
+
+ // Table is described by our info div
+ $(settings.nTable).attr( 'aria-describedby', tid+'_info' );
+ }
+
+ return n[0];
+ }
+
+
+ /**
+ * Update the information elements in the display
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnUpdateInfo ( settings )
+ {
+ /* Show information about the table */
+ var nodes = settings.aanFeatures.i;
+ if ( nodes.length === 0 ) {
+ return;
+ }
+
+ var
+ lang = settings.oLanguage,
+ start = settings._iDisplayStart+1,
+ end = settings.fnDisplayEnd(),
+ max = settings.fnRecordsTotal(),
+ total = settings.fnRecordsDisplay(),
+ out = total ?
+ lang.sInfo :
+ lang.sInfoEmpty;
+
+ if ( total !== max ) {
+ /* Record set after filtering */
+ out += ' ' + lang.sInfoFiltered;
+ }
+
+ // Convert the macros
+ out += lang.sInfoPostFix;
+ out = _fnInfoMacros( settings, out );
+
+ var callback = lang.fnInfoCallback;
+ if ( callback !== null ) {
+ out = callback.call( settings.oInstance,
+ settings, start, end, max, total, out
+ );
+ }
+
+ $(nodes).html( out );
+ }
+
+
+ function _fnInfoMacros ( settings, str )
+ {
+ // When infinite scrolling, we are always starting at 1. _iDisplayStart is used only
+ // internally
+ var
+ formatter = settings.fnFormatNumber,
+ start = settings._iDisplayStart+1,
+ len = settings._iDisplayLength,
+ vis = settings.fnRecordsDisplay(),
+ all = len === -1;
+
+ return str.
+ replace(/_START_/g, formatter.call( settings, start ) ).
+ replace(/_END_/g, formatter.call( settings, settings.fnDisplayEnd() ) ).
+ replace(/_MAX_/g, formatter.call( settings, settings.fnRecordsTotal() ) ).
+ replace(/_TOTAL_/g, formatter.call( settings, vis ) ).
+ replace(/_PAGE_/g, formatter.call( settings, all ? 1 : Math.ceil( start / len ) ) ).
+ replace(/_PAGES_/g, formatter.call( settings, all ? 1 : Math.ceil( vis / len ) ) );
+ }
+
+
+
+ /**
+ * Draw the table for the first time, adding all required features
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnInitialise ( settings )
+ {
+ var i, iLen, iAjaxStart=settings.iInitDisplayStart;
+ var columns = settings.aoColumns, column;
+ var features = settings.oFeatures;
+
+ /* Ensure that the table data is fully initialised */
+ if ( ! settings.bInitialised ) {
+ setTimeout( function(){ _fnInitialise( settings ); }, 200 );
+ return;
+ }
+
+ /* Show the display HTML options */
+ _fnAddOptionsHtml( settings );
+
+ /* Build and draw the header / footer for the table */
+ _fnBuildHead( settings );
+ _fnDrawHead( settings, settings.aoHeader );
+ _fnDrawHead( settings, settings.aoFooter );
+
+ /* Okay to show that something is going on now */
+ _fnProcessingDisplay( settings, true );
+
+ /* Calculate sizes for columns */
+ if ( features.bAutoWidth ) {
+ _fnCalculateColumnWidths( settings );
+ }
+
+ for ( i=0, iLen=columns.length ; i<iLen ; i++ ) {
+ column = columns[i];
+
+ if ( column.sWidth ) {
+ column.nTh.style.width = _fnStringToCss( column.sWidth );
}
-
- var iWidth;
- var nTmp = document.createElement( "div" );
- nTmp.style.width = _fnStringToCss( sWidth );
-
- nParent.appendChild( nTmp );
- iWidth = nTmp.offsetWidth;
- nParent.removeChild( nTmp );
-
- return ( iWidth );
}
-
-
- /**
- * Calculate the width of columns for the table
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnCalculateColumnWidths ( oSettings )
- {
- var iTableWidth = oSettings.nTable.offsetWidth;
- var iUserInputs = 0;
- var iTmpWidth;
- var iVisibleColumns = 0;
- var iColums = oSettings.aoColumns.length;
- var i, iIndex, iCorrector, iWidth;
- var oHeaders = $('th', oSettings.nTHead);
- var widthAttr = oSettings.nTable.getAttribute('width');
- var nWrapper = oSettings.nTable.parentNode;
-
- /* Convert any user input sizes into pixel sizes */
- for ( i=0 ; i<iColums ; i++ )
- {
- if ( oSettings.aoColumns[i].bVisible )
- {
- iVisibleColumns++;
-
- if ( oSettings.aoColumns[i].sWidth !== null )
- {
- iTmpWidth = _fnConvertToWidth( oSettings.aoColumns[i].sWidthOrig,
- nWrapper );
- if ( iTmpWidth !== null )
- {
- oSettings.aoColumns[i].sWidth = _fnStringToCss( iTmpWidth );
- }
-
- iUserInputs++;
+
+ // If there is default sorting required - let's do it. The sort function
+ // will do the drawing for us. Otherwise we draw the table regardless of the
+ // Ajax source - this allows the table to look initialised for Ajax sourcing
+ // data (show 'loading' message possibly)
+ _fnReDraw( settings );
+
+ // Server-side processing init complete is done by _fnAjaxUpdateDraw
+ var dataSrc = _fnDataSource( settings );
+ if ( dataSrc != 'ssp' ) {
+ // if there is an ajax source load the data
+ if ( dataSrc == 'ajax' ) {
+ _fnBuildAjax( settings, [], function(json) {
+ var aData = _fnAjaxDataSrc( settings, json );
+
+ // Got the data - add it to the table
+ for ( i=0 ; i<aData.length ; i++ ) {
+ _fnAddData( settings, aData[i] );
}
- }
+
+ // Reset the init display for cookie saving. We've already done
+ // a filter, and therefore cleared it before. So we need to make
+ // it appear 'fresh'
+ settings.iInitDisplayStart = iAjaxStart;
+
+ _fnReDraw( settings );
+
+ _fnProcessingDisplay( settings, false );
+ _fnInitComplete( settings, json );
+ }, settings );
}
-
- /* If the number of columns in the DOM equals the number that we have to process in
- * DataTables, then we can use the offsets that are created by the web-browser. No custom
- * sizes can be set in order for this to happen, nor scrolling used
- */
- if ( iColums == oHeaders.length && iUserInputs === 0 && iVisibleColumns == iColums &&
- oSettings.oScroll.sX === "" && oSettings.oScroll.sY === "" )
- {
- for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
- {
- iTmpWidth = $(oHeaders[i]).width();
- if ( iTmpWidth !== null )
- {
- oSettings.aoColumns[i].sWidth = _fnStringToCss( iTmpWidth );
- }
- }
+ else {
+ _fnProcessingDisplay( settings, false );
+ _fnInitComplete( settings );
}
- else
- {
- /* Otherwise we are going to have to do some calculations to get the width of each column.
- * Construct a 1 row table with the widest node in the data, and any user defined widths,
- * then insert it into the DOM and allow the browser to do all the hard work of
- * calculating table widths.
- */
- var
- nCalcTmp = oSettings.nTable.cloneNode( false ),
- nTheadClone = oSettings.nTHead.cloneNode(true),
- nBody = document.createElement( 'tbody' ),
- nTr = document.createElement( 'tr' ),
- nDivSizing;
-
- nCalcTmp.removeAttribute( "id" );
- nCalcTmp.appendChild( nTheadClone );
- if ( oSettings.nTFoot !== null )
- {
- nCalcTmp.appendChild( oSettings.nTFoot.cloneNode(true) );
- _fnApplyToChildren( function(n) {
- n.style.width = "";
- }, nCalcTmp.getElementsByTagName('tr') );
- }
-
- nCalcTmp.appendChild( nBody );
- nBody.appendChild( nTr );
-
- /* Remove any sizing that was previously applied by the styles */
- var jqColSizing = $('thead th', nCalcTmp);
- if ( jqColSizing.length === 0 )
- {
- jqColSizing = $('tbody tr:eq(0)>td', nCalcTmp);
- }
-
- /* Apply custom sizing to the cloned header */
- var nThs = _fnGetUniqueThs( oSettings, nTheadClone );
- iCorrector = 0;
- for ( i=0 ; i<iColums ; i++ )
- {
- var oColumn = oSettings.aoColumns[i];
- if ( oColumn.bVisible && oColumn.sWidthOrig !== null && oColumn.sWidthOrig !== "" )
- {
- nThs[i-iCorrector].style.width = _fnStringToCss( oColumn.sWidthOrig );
- }
- else if ( oColumn.bVisible )
- {
- nThs[i-iCorrector].style.width = "";
- }
- else
- {
- iCorrector++;
- }
- }
-
- /* Find the biggest td for each column and put it into the table */
- for ( i=0 ; i<iColums ; i++ )
- {
- if ( oSettings.aoColumns[i].bVisible )
- {
- var nTd = _fnGetWidestNode( oSettings, i );
- if ( nTd !== null )
- {
- nTd = nTd.cloneNode(true);
- if ( oSettings.aoColumns[i].sContentPadding !== "" )
- {
- nTd.innerHTML += oSettings.aoColumns[i].sContentPadding;
- }
- nTr.appendChild( nTd );
- }
- }
- }
-
- /* Build the table and 'display' it */
- nWrapper.appendChild( nCalcTmp );
-
- /* When scrolling (X or Y) we want to set the width of the table as appropriate. However,
- * when not scrolling leave the table width as it is. This results in slightly different,
- * but I think correct behaviour
- */
- if ( oSettings.oScroll.sX !== "" && oSettings.oScroll.sXInner !== "" )
- {
- nCalcTmp.style.width = _fnStringToCss(oSettings.oScroll.sXInner);
- }
- else if ( oSettings.oScroll.sX !== "" )
- {
- nCalcTmp.style.width = "";
- if ( $(nCalcTmp).width() < nWrapper.offsetWidth )
- {
- nCalcTmp.style.width = _fnStringToCss( nWrapper.offsetWidth );
- }
- }
- else if ( oSettings.oScroll.sY !== "" )
- {
- nCalcTmp.style.width = _fnStringToCss( nWrapper.offsetWidth );
- }
- else if ( widthAttr )
- {
- nCalcTmp.style.width = _fnStringToCss( widthAttr );
- }
- nCalcTmp.style.visibility = "hidden";
-
- /* Scrolling considerations */
- _fnScrollingWidthAdjust( oSettings, nCalcTmp );
-
- /* Read the width's calculated by the browser and store them for use by the caller. We
- * first of all try to use the elements in the body, but it is possible that there are
- * no elements there, under which circumstances we use the header elements
- */
- var oNodes = $("tbody tr:eq(0)", nCalcTmp).children();
- if ( oNodes.length === 0 )
- {
- oNodes = _fnGetUniqueThs( oSettings, $('thead', nCalcTmp)[0] );
- }
-
- /* Browsers need a bit of a hand when a width is assigned to any columns when
- * x-scrolling as they tend to collapse the table to the min-width, even if
- * we sent the column widths. So we need to keep track of what the table width
- * should be by summing the user given values, and the automatic values
- */
- if ( oSettings.oScroll.sX !== "" )
- {
- var iTotal = 0;
- iCorrector = 0;
- for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
- {
- if ( oSettings.aoColumns[i].bVisible )
- {
- if ( oSettings.aoColumns[i].sWidthOrig === null )
- {
- iTotal += $(oNodes[iCorrector]).outerWidth();
- }
- else
- {
- iTotal += parseInt(oSettings.aoColumns[i].sWidth.replace('px',''), 10) +
- ($(oNodes[iCorrector]).outerWidth() - $(oNodes[iCorrector]).width());
- }
- iCorrector++;
+ }
+ }
+
+
+ /**
+ * Draw the table for the first time, adding all required features
+ * @param {object} oSettings dataTables settings object
+ * @param {object} [json] JSON from the server that completed the table, if using Ajax source
+ * with client-side processing (optional)
+ * @memberof DataTable#oApi
+ */
+ function _fnInitComplete ( settings, json )
+ {
+ settings._bInitComplete = true;
+
+ // On an Ajax load we now have data and therefore want to apply the column
+ // sizing
+ if ( json ) {
+ _fnAdjustColumnSizing( settings );
+ }
+
+ _fnCallbackFire( settings, 'aoInitComplete', 'init', [settings, json] );
+ }
+
+
+ function _fnLengthChange ( settings, val )
+ {
+ var len = parseInt( val, 10 );
+ settings._iDisplayLength = len;
+
+ _fnLengthOverflow( settings );
+
+ // Fire length change event
+ _fnCallbackFire( settings, null, 'length', [settings, len] );
+ }
+
+
+ /**
+ * Generate the node required for user display length changing
+ * @param {object} settings dataTables settings object
+ * @returns {node} Display length feature node
+ * @memberof DataTable#oApi
+ */
+ function _fnFeatureHtmlLength ( settings )
+ {
+ var
+ classes = settings.oClasses,
+ tableId = settings.sTableId,
+ menu = settings.aLengthMenu,
+ d2 = $.isArray( menu[0] ),
+ lengths = d2 ? menu[0] : menu,
+ language = d2 ? menu[1] : menu;
+
+ var select = $('<select/>', {
+ 'name': tableId+'_length',
+ 'aria-controls': tableId,
+ 'class': classes.sLengthSelect
+ } );
+
+ for ( var i=0, ien=lengths.length ; i<ien ; i++ ) {
+ select[0][ i ] = new Option( language[i], lengths[i] );
+ }
+
+ var div = $('<div><label/></div>').addClass( classes.sLength );
+ if ( ! settings.aanFeatures.l ) {
+ div[0].id = tableId+'_length';
+ }
+
+ div.children().append(
+ settings.oLanguage.sLengthMenu.replace( '_MENU_', select[0].outerHTML )
+ );
+
+ // Can't use `select` variable as user might provide their own and the
+ // reference is broken by the use of outerHTML
+ $('select', div)
+ .val( settings._iDisplayLength )
+ .bind( 'change.DT', function(e) {
+ _fnLengthChange( settings, $(this).val() );
+ _fnDraw( settings );
+ } );
+
+ // Update node value whenever anything changes the table's length
+ $(settings.nTable).bind( 'length.dt.DT', function (e, s, len) {
+ if ( settings === s ) {
+ $('select', div).val( len );
+ }
+ } );
+
+ return div[0];
+ }
+
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Note that most of the paging logic is done in
+ * DataTable.ext.pager
+ */
+
+ /**
+ * Generate the node required for default pagination
+ * @param {object} oSettings dataTables settings object
+ * @returns {node} Pagination feature node
+ * @memberof DataTable#oApi
+ */
+ function _fnFeatureHtmlPaginate ( settings )
+ {
+ var
+ type = settings.sPaginationType,
+ plugin = DataTable.ext.pager[ type ],
+ modern = typeof plugin === 'function',
+ redraw = function( settings ) {
+ _fnDraw( settings );
+ },
+ node = $('<div/>').addClass( settings.oClasses.sPaging + type )[0],
+ features = settings.aanFeatures;
+
+ if ( ! modern ) {
+ plugin.fnInit( settings, node, redraw );
+ }
+
+ /* Add a draw callback for the pagination on first instance, to update the paging display */
+ if ( ! features.p )
+ {
+ node.id = settings.sTableId+'_paginate';
+
+ settings.aoDrawCallback.push( {
+ "fn": function( settings ) {
+ if ( modern ) {
+ var
+ start = settings._iDisplayStart,
+ len = settings._iDisplayLength,
+ visRecords = settings.fnRecordsDisplay(),
+ all = len === -1,
+ page = all ? 0 : Math.ceil( start / len ),
+ pages = all ? 1 : Math.ceil( visRecords / len ),
+ buttons = plugin(page, pages),
+ i, ien;
+
+ for ( i=0, ien=features.p.length ; i<ien ; i++ ) {
+ _fnRenderer( settings, 'pageButton' )(
+ settings, features.p[i], i, buttons, page, pages
+ );
}
}
-
- nCalcTmp.style.width = _fnStringToCss( iTotal );
- oSettings.nTable.style.width = _fnStringToCss( iTotal );
- }
-
- iCorrector = 0;
- for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
- {
- if ( oSettings.aoColumns[i].bVisible )
- {
- iWidth = $(oNodes[iCorrector]).width();
- if ( iWidth !== null && iWidth > 0 )
- {
- oSettings.aoColumns[i].sWidth = _fnStringToCss( iWidth );
- }
- iCorrector++;
+ else {
+ plugin.fnUpdate( settings, redraw );
}
- }
-
- var cssWidth = $(nCalcTmp).css('width');
- oSettings.nTable.style.width = (cssWidth.indexOf('%') !== -1) ?
- cssWidth : _fnStringToCss( $(nCalcTmp).outerWidth() );
- nCalcTmp.parentNode.removeChild( nCalcTmp );
- }
-
- if ( widthAttr )
- {
- oSettings.nTable.style.width = _fnStringToCss( widthAttr );
- }
+ },
+ "sName": "pagination"
+ } );
}
-
-
- /**
- * Adjust a table's width to take account of scrolling
- * @param {object} oSettings dataTables settings object
- * @param {node} n table node
- * @memberof DataTable#oApi
- */
- function _fnScrollingWidthAdjust ( oSettings, n )
+
+ return node;
+ }
+
+
+ /**
+ * Alter the display settings to change the page
+ * @param {object} settings DataTables settings object
+ * @param {string|int} action Paging action to take: "first", "previous",
+ * "next" or "last" or page number to jump to (integer)
+ * @param [bool] redraw Automatically draw the update or not
+ * @returns {bool} true page has changed, false - no change
+ * @memberof DataTable#oApi
+ */
+ function _fnPageChange ( settings, action, redraw )
+ {
+ var
+ start = settings._iDisplayStart,
+ len = settings._iDisplayLength,
+ records = settings.fnRecordsDisplay();
+
+ if ( records === 0 || len === -1 )
{
- if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY !== "" )
- {
- /* When y-scrolling only, we want to remove the width of the scroll bar so the table
- * + scroll bar will fit into the area avaialble.
- */
- var iOrigWidth = $(n).width();
- n.style.width = _fnStringToCss( $(n).outerWidth()-oSettings.oScroll.iBarWidth );
- }
- else if ( oSettings.oScroll.sX !== "" )
- {
- /* When x-scrolling both ways, fix the table at it's current size, without adjusting */
- n.style.width = _fnStringToCss( $(n).outerWidth() );
- }
+ start = 0;
}
-
-
- /**
- * Get the widest node
- * @param {object} oSettings dataTables settings object
- * @param {int} iCol column of interest
- * @returns {node} widest table node
- * @memberof DataTable#oApi
- */
- function _fnGetWidestNode( oSettings, iCol )
+ else if ( typeof action === "number" )
{
- var iMaxIndex = _fnGetMaxLenString( oSettings, iCol );
- if ( iMaxIndex < 0 )
+ start = action * len;
+
+ if ( start > records )
{
- return null;
+ start = 0;
}
-
- if ( oSettings.aoData[iMaxIndex].nTr === null )
+ }
+ else if ( action == "first" )
+ {
+ start = 0;
+ }
+ else if ( action == "previous" )
+ {
+ start = len >= 0 ?
+ start - len :
+ 0;
+
+ if ( start < 0 )
{
- var n = document.createElement('td');
- n.innerHTML = _fnGetCellData( oSettings, iMaxIndex, iCol, '' );
- return n;
+ start = 0;
}
- return _fnGetTdNodes(oSettings, iMaxIndex)[iCol];
}
-
-
- /**
- * Get the maximum strlen for each data column
- * @param {object} oSettings dataTables settings object
- * @param {int} iCol column of interest
- * @returns {string} max string length for each column
- * @memberof DataTable#oApi
- */
- function _fnGetMaxLenString( oSettings, iCol )
+ else if ( action == "next" )
{
- var iMax = -1;
- var iMaxIndex = -1;
-
- for ( var i=0 ; i<oSettings.aoData.length ; i++ )
+ if ( start + len < records )
{
- var s = _fnGetCellData( oSettings, i, iCol, 'display' )+"";
- s = s.replace( /<.*?>/g, "" );
- if ( s.length > iMax )
- {
- iMax = s.length;
- iMaxIndex = i;
- }
+ start += len;
}
-
- return iMaxIndex;
}
-
-
- /**
- * Append a CSS unit (only if required) to a string
- * @param {array} aArray1 first array
- * @param {array} aArray2 second array
- * @returns {int} 0 if match, 1 if length is different, 2 if no match
- * @memberof DataTable#oApi
- */
- function _fnStringToCss( s )
+ else if ( action == "last" )
{
- if ( s === null )
- {
- return "0px";
+ start = Math.floor( (records-1) / len) * len;
+ }
+ else
+ {
+ _fnLog( settings, 0, "Unknown paging action: "+action, 5 );
+ }
+
+ var changed = settings._iDisplayStart !== start;
+ settings._iDisplayStart = start;
+
+ if ( changed ) {
+ _fnCallbackFire( settings, null, 'page', [settings] );
+
+ if ( redraw ) {
+ _fnDraw( settings );
}
-
- if ( typeof s == 'number' )
- {
- if ( s < 0 )
- {
- return "0px";
+ }
+
+ return changed;
+ }
+
+
+
+ /**
+ * Generate the node required for the processing node
+ * @param {object} settings dataTables settings object
+ * @returns {node} Processing element
+ * @memberof DataTable#oApi
+ */
+ function _fnFeatureHtmlProcessing ( settings )
+ {
+ return $('<div/>', {
+ 'id': ! settings.aanFeatures.r ? settings.sTableId+'_processing' : null,
+ 'class': settings.oClasses.sProcessing
+ } )
+ .html( settings.oLanguage.sProcessing )
+ .insertBefore( settings.nTable )[0];
+ }
+
+
+ /**
+ * Display or hide the processing indicator
+ * @param {object} settings dataTables settings object
+ * @param {bool} show Show the processing indicator (true) or not (false)
+ * @memberof DataTable#oApi
+ */
+ function _fnProcessingDisplay ( settings, show )
+ {
+ if ( settings.oFeatures.bProcessing ) {
+ $(settings.aanFeatures.r).css( 'display', show ? 'block' : 'none' );
+ }
+
+ _fnCallbackFire( settings, null, 'processing', [settings, show] );
+ }
+
+ /**
+ * Add any control elements for the table - specifically scrolling
+ * @param {object} settings dataTables settings object
+ * @returns {node} Node to add to the DOM
+ * @memberof DataTable#oApi
+ */
+ function _fnFeatureHtmlTable ( settings )
+ {
+ var table = $(settings.nTable);
+
+ // Add the ARIA grid role to the table
+ table.attr( 'role', 'grid' );
+
+ // Scrolling from here on in
+ var scroll = settings.oScroll;
+
+ if ( scroll.sX === '' && scroll.sY === '' ) {
+ return settings.nTable;
+ }
+
+ var scrollX = scroll.sX;
+ var scrollY = scroll.sY;
+ var classes = settings.oClasses;
+ var caption = table.children('caption');
+ var captionSide = caption.length ? caption[0]._captionSide : null;
+ var headerClone = $( table[0].cloneNode(false) );
+ var footerClone = $( table[0].cloneNode(false) );
+ var footer = table.children('tfoot');
+ var _div = '<div/>';
+ var size = function ( s ) {
+ return !s ? null : _fnStringToCss( s );
+ };
+
+ // This is fairly messy, but with x scrolling enabled, if the table has a
+ // width attribute, regardless of any width applied using the column width
+ // options, the browser will shrink or grow the table as needed to fit into
+ // that 100%. That would make the width options useless. So we remove it.
+ // This is okay, under the assumption that width:100% is applied to the
+ // table in CSS (it is in the default stylesheet) which will set the table
+ // width as appropriate (the attribute and css behave differently...)
+ if ( scroll.sX && table.attr('width') === '100%' ) {
+ table.removeAttr('width');
+ }
+
+ if ( ! footer.length ) {
+ footer = null;
+ }
+
+ /*
+ * The HTML structure that we want to generate in this function is:
+ * div - scroller
+ * div - scroll head
+ * div - scroll head inner
+ * table - scroll head table
+ * thead - thead
+ * div - scroll body
+ * table - table (master table)
+ * thead - thead clone for sizing
+ * tbody - tbody
+ * div - scroll foot
+ * div - scroll foot inner
+ * table - scroll foot table
+ * tfoot - tfoot
+ */
+ var scroller = $( _div, { 'class': classes.sScrollWrapper } )
+ .append(
+ $(_div, { 'class': classes.sScrollHead } )
+ .css( {
+ overflow: 'hidden',
+ position: 'relative',
+ border: 0,
+ width: scrollX ? size(scrollX) : '100%'
+ } )
+ .append(
+ $(_div, { 'class': classes.sScrollHeadInner } )
+ .css( {
+ 'box-sizing': 'content-box',
+ width: scroll.sXInner || '100%'
+ } )
+ .append(
+ headerClone
+ .removeAttr('id')
+ .css( 'margin-left', 0 )
+ .append( captionSide === 'top' ? caption : null )
+ .append(
+ table.children('thead')
+ )
+ )
+ )
+ )
+ .append(
+ $(_div, { 'class': classes.sScrollBody } )
+ .css( {
+ overflow: 'auto',
+ height: size( scrollY ),
+ width: size( scrollX )
+ } )
+ .append( table )
+ );
+
+ if ( footer ) {
+ scroller.append(
+ $(_div, { 'class': classes.sScrollFoot } )
+ .css( {
+ overflow: 'hidden',
+ border: 0,
+ width: scrollX ? size(scrollX) : '100%'
+ } )
+ .append(
+ $(_div, { 'class': classes.sScrollFootInner } )
+ .append(
+ footerClone
+ .removeAttr('id')
+ .css( 'margin-left', 0 )
+ .append( captionSide === 'bottom' ? caption : null )
+ .append(
+ table.children('tfoot')
+ )
+ )
+ )
+ );
+ }
+
+ var children = scroller.children();
+ var scrollHead = children[0];
+ var scrollBody = children[1];
+ var scrollFoot = footer ? children[2] : null;
+
+ // When the body is scrolled, then we also want to scroll the headers
+ if ( scrollX ) {
+ $(scrollBody).on( 'scroll.DT', function (e) {
+ var scrollLeft = this.scrollLeft;
+
+ scrollHead.scrollLeft = scrollLeft;
+
+ if ( footer ) {
+ scrollFoot.scrollLeft = scrollLeft;
}
- return s+"px";
- }
-
- /* Check if the last character is not 0-9 */
- var c = s.charCodeAt( s.length-1 );
- if (c < 0x30 || c > 0x39)
- {
- return s;
- }
- return s+"px";
+ } );
}
-
-
- /**
- * Get the width of a scroll bar in this browser being used
- * @returns {int} width in pixels
- * @memberof DataTable#oApi
- */
- function _fnScrollBarWidth ()
- {
- var inner = document.createElement('p');
- var style = inner.style;
- style.width = "100%";
- style.height = "200px";
- style.padding = "0px";
-
- var outer = document.createElement('div');
- style = outer.style;
- style.position = "absolute";
- style.top = "0px";
- style.left = "0px";
- style.visibility = "hidden";
- style.width = "200px";
- style.height = "150px";
- style.padding = "0px";
- style.overflow = "hidden";
- outer.appendChild(inner);
-
- document.body.appendChild(outer);
- var w1 = inner.offsetWidth;
- outer.style.overflow = 'scroll';
- var w2 = inner.offsetWidth;
- if ( w1 == w2 )
- {
- w2 = outer.clientWidth;
- }
-
- document.body.removeChild(outer);
- return (w1 - w2);
+
+ settings.nScrollHead = scrollHead;
+ settings.nScrollBody = scrollBody;
+ settings.nScrollFoot = scrollFoot;
+
+ // On redraw - align columns
+ settings.aoDrawCallback.push( {
+ "fn": _fnScrollDraw,
+ "sName": "scrolling"
+ } );
+
+ return scroller[0];
+ }
+
+
+
+ /**
+ * Update the header, footer and body tables for resizing - i.e. column
+ * alignment.
+ *
+ * Welcome to the most horrible function DataTables. The process that this
+ * function follows is basically:
+ * 1. Re-create the table inside the scrolling div
+ * 2. Take live measurements from the DOM
+ * 3. Apply the measurements to align the columns
+ * 4. Clean up
+ *
+ * @param {object} settings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnScrollDraw ( settings )
+ {
+ // Given that this is such a monster function, a lot of variables are use
+ // to try and keep the minimised size as small as possible
+ var
+ scroll = settings.oScroll,
+ scrollX = scroll.sX,
+ scrollXInner = scroll.sXInner,
+ scrollY = scroll.sY,
+ barWidth = scroll.iBarWidth,
+ divHeader = $(settings.nScrollHead),
+ divHeaderStyle = divHeader[0].style,
+ divHeaderInner = divHeader.children('div'),
+ divHeaderInnerStyle = divHeaderInner[0].style,
+ divHeaderTable = divHeaderInner.children('table'),
+ divBodyEl = settings.nScrollBody,
+ divBody = $(divBodyEl),
+ divBodyStyle = divBodyEl.style,
+ divFooter = $(settings.nScrollFoot),
+ divFooterInner = divFooter.children('div'),
+ divFooterTable = divFooterInner.children('table'),
+ header = $(settings.nTHead),
+ table = $(settings.nTable),
+ tableEl = table[0],
+ tableStyle = tableEl.style,
+ footer = settings.nTFoot ? $(settings.nTFoot) : null,
+ browser = settings.oBrowser,
+ ie67 = browser.bScrollOversize,
+ headerTrgEls, footerTrgEls,
+ headerSrcEls, footerSrcEls,
+ headerCopy, footerCopy,
+ headerWidths=[], footerWidths=[],
+ headerContent=[],
+ idx, correction, sanityWidth,
+ zeroOut = function(nSizer) {
+ var style = nSizer.style;
+ style.paddingTop = "0";
+ style.paddingBottom = "0";
+ style.borderTopWidth = "0";
+ style.borderBottomWidth = "0";
+ style.height = 0;
+ };
+
+ /*
+ * 1. Re-create the table inside the scrolling div
+ */
+
+ // Remove the old minimised thead and tfoot elements in the inner table
+ table.children('thead, tfoot').remove();
+
+ // Clone the current header and footer elements and then place it into the inner table
+ headerCopy = header.clone().prependTo( table );
+ headerTrgEls = header.find('tr'); // original header is in its own table
+ headerSrcEls = headerCopy.find('tr');
+ headerCopy.find('th, td').removeAttr('tabindex');
+
+ if ( footer ) {
+ footerCopy = footer.clone().prependTo( table );
+ footerTrgEls = footer.find('tr'); // the original tfoot is in its own table and must be sized
+ footerSrcEls = footerCopy.find('tr');
}
-
- /**
- * Change the order of the table
- * @param {object} oSettings dataTables settings object
- * @param {bool} bApplyClasses optional - should we apply classes or not
- * @memberof DataTable#oApi
+
+
+ /*
+ * 2. Take live measurements from the DOM - do not alter the DOM itself!
*/
- function _fnSort ( oSettings, bApplyClasses )
+
+ // Remove old sizing and apply the calculated column widths
+ // Get the unique column headers in the newly created (cloned) header. We want to apply the
+ // calculated sizes to this header
+ if ( ! scrollX )
{
- var
- i, iLen, j, jLen, k, kLen,
- sDataType, nTh,
- aaSort = [],
- aiOrig = [],
- oSort = DataTable.ext.oSort,
- aoData = oSettings.aoData,
- aoColumns = oSettings.aoColumns,
- oAria = oSettings.oLanguage.oAria;
-
- /* No sorting required if server-side or no sorting array */
- if ( !oSettings.oFeatures.bServerSide &&
- (oSettings.aaSorting.length !== 0 || oSettings.aaSortingFixed !== null) )
- {
- aaSort = ( oSettings.aaSortingFixed !== null ) ?
- oSettings.aaSortingFixed.concat( oSettings.aaSorting ) :
- oSettings.aaSorting.slice();
-
- /* If there is a sorting data type, and a function belonging to it, then we need to
- * get the data from the developer's function and apply it for this column
- */
- for ( i=0 ; i<aaSort.length ; i++ )
- {
- var iColumn = aaSort[i][0];
- var iVisColumn = _fnColumnIndexToVisible( oSettings, iColumn );
- sDataType = oSettings.aoColumns[ iColumn ].sSortDataType;
- if ( DataTable.ext.afnSortData[sDataType] )
- {
- var aData = DataTable.ext.afnSortData[sDataType].call(
- oSettings.oInstance, oSettings, iColumn, iVisColumn
- );
- if ( aData.length === aoData.length )
- {
- for ( j=0, jLen=aoData.length ; j<jLen ; j++ )
- {
- _fnSetCellData( oSettings, j, iColumn, aData[j] );
- }
- }
- else
- {
- _fnLog( oSettings, 0, "Returned data sort array (col "+iColumn+") is the wrong length" );
- }
- }
- }
-
- /* Create a value - key array of the current row positions such that we can use their
- * current position during the sort, if values match, in order to perform stable sorting
- */
- for ( i=0, iLen=oSettings.aiDisplayMaster.length ; i<iLen ; i++ )
- {
- aiOrig[ oSettings.aiDisplayMaster[i] ] = i;
- }
-
- /* Build an internal data array which is specific to the sort, so we can get and prep
- * the data to be sorted only once, rather than needing to do it every time the sorting
- * function runs. This make the sorting function a very simple comparison
- */
- var iSortLen = aaSort.length;
- var fnSortFormat, aDataSort;
- for ( i=0, iLen=aoData.length ; i<iLen ; i++ )
- {
- for ( j=0 ; j<iSortLen ; j++ )
- {
- aDataSort = aoColumns[ aaSort[j][0] ].aDataSort;
-
- for ( k=0, kLen=aDataSort.length ; k<kLen ; k++ )
- {
- sDataType = aoColumns[ aDataSort[k] ].sType;
- fnSortFormat = oSort[ (sDataType ? sDataType : 'string')+"-pre" ];
-
- aoData[i]._aSortData[ aDataSort[k] ] = fnSortFormat ?
- fnSortFormat( _fnGetCellData( oSettings, i, aDataSort[k], 'sort' ) ) :
- _fnGetCellData( oSettings, i, aDataSort[k], 'sort' );
- }
- }
- }
-
- /* Do the sort - here we want multi-column sorting based on a given data source (column)
- * and sorting function (from oSort) in a certain direction. It's reasonably complex to
- * follow on it's own, but this is what we want (example two column sorting):
- * fnLocalSorting = function(a,b){
- * var iTest;
- * iTest = oSort['string-asc']('data11', 'data12');
- * if (iTest !== 0)
- * return iTest;
- * iTest = oSort['numeric-desc']('data21', 'data22');
- * if (iTest !== 0)
- * return iTest;
- * return oSort['numeric-asc']( aiOrig[a], aiOrig[b] );
- * }
- * Basically we have a test for each sorting column, if the data in that column is equal,
- * test the next column. If all columns match, then we use a numeric sort on the row
- * positions in the original data array to provide a stable sort.
- */
- oSettings.aiDisplayMaster.sort( function ( a, b ) {
- var k, l, lLen, iTest, aDataSort, sDataType;
- for ( k=0 ; k<iSortLen ; k++ )
- {
- aDataSort = aoColumns[ aaSort[k][0] ].aDataSort;
-
- for ( l=0, lLen=aDataSort.length ; l<lLen ; l++ )
- {
- sDataType = aoColumns[ aDataSort[l] ].sType;
-
- iTest = oSort[ (sDataType ? sDataType : 'string')+"-"+aaSort[k][1] ](
- aoData[a]._aSortData[ aDataSort[l] ],
- aoData[b]._aSortData[ aDataSort[l] ]
- );
-
- if ( iTest !== 0 )
- {
- return iTest;
- }
- }
- }
-
- return oSort['numeric-asc']( aiOrig[a], aiOrig[b] );
- } );
+ divBodyStyle.width = '100%';
+ divHeader[0].style.width = '100%';
+ }
+
+ $.each( _fnGetUniqueThs( settings, headerCopy ), function ( i, el ) {
+ idx = _fnVisibleToColumnIndex( settings, i );
+ el.style.width = settings.aoColumns[idx].sWidth;
+ } );
+
+ if ( footer ) {
+ _fnApplyToChildren( function(n) {
+ n.style.width = "";
+ }, footerSrcEls );
+ }
+
+ // If scroll collapse is enabled, when we put the headers back into the body for sizing, we
+ // will end up forcing the scrollbar to appear, making our measurements wrong for when we
+ // then hide it (end of this function), so add the header height to the body scroller.
+ if ( scroll.bCollapse && scrollY !== "" ) {
+ divBodyStyle.height = (divBody[0].offsetHeight + header[0].offsetHeight)+"px";
+ }
+
+ // Size the table as a whole
+ sanityWidth = table.outerWidth();
+ if ( scrollX === "" ) {
+ // No x scrolling
+ tableStyle.width = "100%";
+
+ // IE7 will make the width of the table when 100% include the scrollbar
+ // - which is shouldn't. When there is a scrollbar we need to take this
+ // into account.
+ if ( ie67 && (table.find('tbody').height() > divBodyEl.offsetHeight ||
+ divBody.css('overflow-y') == "scroll")
+ ) {
+ tableStyle.width = _fnStringToCss( table.outerWidth() - barWidth);
}
-
- /* Alter the sorting classes to take account of the changes */
- if ( (bApplyClasses === undefined || bApplyClasses) && !oSettings.oFeatures.bDeferRender )
- {
- _fnSortingClasses( oSettings );
+ }
+ else
+ {
+ // x scrolling
+ if ( scrollXInner !== "" ) {
+ // x scroll inner has been given - use it
+ tableStyle.width = _fnStringToCss(scrollXInner);
}
-
- for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
- {
- var sTitle = aoColumns[i].sTitle.replace( /<.*?>/g, "" );
- nTh = aoColumns[i].nTh;
- nTh.removeAttribute('aria-sort');
- nTh.removeAttribute('aria-label');
-
- /* In ARIA only the first sorting column can be marked as sorting - no multi-sort option */
- if ( aoColumns[i].bSortable )
- {
- if ( aaSort.length > 0 && aaSort[0][0] == i )
- {
- nTh.setAttribute('aria-sort', aaSort[0][1]=="asc" ? "ascending" : "descending" );
-
- var nextSort = (aoColumns[i].asSorting[ aaSort[0][2]+1 ]) ?
- aoColumns[i].asSorting[ aaSort[0][2]+1 ] : aoColumns[i].asSorting[0];
- nTh.setAttribute('aria-label', sTitle+
- (nextSort=="asc" ? oAria.sSortAscending : oAria.sSortDescending) );
- }
- else
- {
- nTh.setAttribute('aria-label', sTitle+
- (aoColumns[i].asSorting[0]=="asc" ? oAria.sSortAscending : oAria.sSortDescending) );
- }
- }
- else
- {
- nTh.setAttribute('aria-label', sTitle);
+ else if ( sanityWidth == divBody.width() && divBody.height() < table.height() ) {
+ // There is y-scrolling - try to take account of the y scroll bar
+ tableStyle.width = _fnStringToCss( sanityWidth-barWidth );
+ if ( table.outerWidth() > sanityWidth-barWidth ) {
+ // Not possible to take account of it
+ tableStyle.width = _fnStringToCss( sanityWidth );
}
}
-
- /* Tell the draw function that we have sorted the data */
- oSettings.bSorted = true;
- $(oSettings.oInstance).trigger('sort', oSettings);
-
- /* Copy the master data into the draw array and re-draw */
- if ( oSettings.oFeatures.bFilter )
- {
- /* _fnFilter() will redraw the table for us */
- _fnFilterComplete( oSettings, oSettings.oPreviousSearch, 1 );
- }
- else
- {
- oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
- oSettings._iDisplayStart = 0; /* reset display back to page 0 */
- _fnCalculateEnd( oSettings );
- _fnDraw( oSettings );
+ else {
+ // When all else fails
+ tableStyle.width = _fnStringToCss( sanityWidth );
}
}
-
-
- /**
- * Attach a sort handler (click) to a node
- * @param {object} oSettings dataTables settings object
- * @param {node} nNode node to attach the handler to
- * @param {int} iDataIndex column sorting index
- * @param {function} [fnCallback] callback function
- * @memberof DataTable#oApi
- */
- function _fnSortAttachListener ( oSettings, nNode, iDataIndex, fnCallback )
+
+ // Recalculate the sanity width - now that we've applied the required width,
+ // before it was a temporary variable. This is required because the column
+ // width calculation is done before this table DOM is created.
+ sanityWidth = table.outerWidth();
+
+ // Hidden header should have zero height, so remove padding and borders. Then
+ // set the width based on the real headers
+
+ // Apply all styles in one pass
+ _fnApplyToChildren( zeroOut, headerSrcEls );
+
+ // Read all widths in next pass
+ _fnApplyToChildren( function(nSizer) {
+ headerContent.push( nSizer.innerHTML );
+ headerWidths.push( _fnStringToCss( $(nSizer).css('width') ) );
+ }, headerSrcEls );
+
+ // Apply all widths in final pass
+ _fnApplyToChildren( function(nToSize, i) {
+ nToSize.style.width = headerWidths[i];
+ }, headerTrgEls );
+
+ $(headerSrcEls).height(0);
+
+ /* Same again with the footer if we have one */
+ if ( footer )
{
- _fnBindAction( nNode, {}, function (e) {
- /* If the column is not sortable - don't to anything */
- if ( oSettings.aoColumns[iDataIndex].bSortable === false )
- {
- return;
- }
-
- /*
- * This is a little bit odd I admit... I declare a temporary function inside the scope of
- * _fnBuildHead and the click handler in order that the code presented here can be used
- * twice - once for when bProcessing is enabled, and another time for when it is
- * disabled, as we need to perform slightly different actions.
- * Basically the issue here is that the Javascript engine in modern browsers don't
- * appear to allow the rendering engine to update the display while it is still executing
- * it's thread (well - it does but only after long intervals). This means that the
- * 'processing' display doesn't appear for a table sort. To break the js thread up a bit
- * I force an execution break by using setTimeout - but this breaks the expected
- * thread continuation for the end-developer's point of view (their code would execute
- * too early), so we only do it when we absolutely have to.
- */
- var fnInnerSorting = function () {
- var iColumn, iNextSort;
-
- /* If the shift key is pressed then we are multiple column sorting */
- if ( e.shiftKey )
- {
- /* Are we already doing some kind of sort on this column? */
- var bFound = false;
- for ( var i=0 ; i<oSettings.aaSorting.length ; i++ )
- {
- if ( oSettings.aaSorting[i][0] == iDataIndex )
- {
- bFound = true;
- iColumn = oSettings.aaSorting[i][0];
- iNextSort = oSettings.aaSorting[i][2]+1;
-
- if ( !oSettings.aoColumns[iColumn].asSorting[iNextSort] )
- {
- /* Reached the end of the sorting options, remove from multi-col sort */
- oSettings.aaSorting.splice( i, 1 );
- }
- else
- {
- /* Move onto next sorting direction */
- oSettings.aaSorting[i][1] = oSettings.aoColumns[iColumn].asSorting[iNextSort];
- oSettings.aaSorting[i][2] = iNextSort;
- }
- break;
- }
- }
-
- /* No sort yet - add it in */
- if ( bFound === false )
- {
- oSettings.aaSorting.push( [ iDataIndex,
- oSettings.aoColumns[iDataIndex].asSorting[0], 0 ] );
- }
- }
- else
- {
- /* If no shift key then single column sort */
- if ( oSettings.aaSorting.length == 1 && oSettings.aaSorting[0][0] == iDataIndex )
- {
- iColumn = oSettings.aaSorting[0][0];
- iNextSort = oSettings.aaSorting[0][2]+1;
- if ( !oSettings.aoColumns[iColumn].asSorting[iNextSort] )
- {
- iNextSort = 0;
- }
- oSettings.aaSorting[0][1] = oSettings.aoColumns[iColumn].asSorting[iNextSort];
- oSettings.aaSorting[0][2] = iNextSort;
- }
- else
- {
- oSettings.aaSorting.splice( 0, oSettings.aaSorting.length );
- oSettings.aaSorting.push( [ iDataIndex,
- oSettings.aoColumns[iDataIndex].asSorting[0], 0 ] );
- }
- }
-
- /* Run the sort */
- _fnSort( oSettings );
- }; /* /fnInnerSorting */
-
- if ( !oSettings.oFeatures.bProcessing )
- {
- fnInnerSorting();
- }
- else
- {
- _fnProcessingDisplay( oSettings, true );
- setTimeout( function() {
- fnInnerSorting();
- if ( !oSettings.oFeatures.bServerSide )
- {
- _fnProcessingDisplay( oSettings, false );
- }
- }, 0 );
- }
-
- /* Call the user specified callback function - used for async user interaction */
- if ( typeof fnCallback == 'function' )
- {
- fnCallback( oSettings );
- }
- } );
+ _fnApplyToChildren( zeroOut, footerSrcEls );
+
+ _fnApplyToChildren( function(nSizer) {
+ footerWidths.push( _fnStringToCss( $(nSizer).css('width') ) );
+ }, footerSrcEls );
+
+ _fnApplyToChildren( function(nToSize, i) {
+ nToSize.style.width = footerWidths[i];
+ }, footerTrgEls );
+
+ $(footerSrcEls).height(0);
}
-
-
- /**
- * Set the sorting classes on the header, Note: it is safe to call this function
- * when bSort and bSortClasses are false
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
+
+
+ /*
+ * 3. Apply the measurements
*/
- function _fnSortingClasses( oSettings )
+
+ // "Hide" the header and footer that we used for the sizing. We need to keep
+ // the content of the cell so that the width applied to the header and body
+ // both match, but we want to hide it completely. We want to also fix their
+ // width to what they currently are
+ _fnApplyToChildren( function(nSizer, i) {
+ nSizer.innerHTML = '<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+headerContent[i]+'</div>';
+ nSizer.style.width = headerWidths[i];
+ }, headerSrcEls );
+
+ if ( footer )
{
- var i, iLen, j, jLen, iFound;
- var aaSort, sClass;
- var iColumns = oSettings.aoColumns.length;
- var oClasses = oSettings.oClasses;
-
- for ( i=0 ; i<iColumns ; i++ )
- {
- if ( oSettings.aoColumns[i].bSortable )
- {
- $(oSettings.aoColumns[i].nTh).removeClass( oClasses.sSortAsc +" "+ oClasses.sSortDesc +
- " "+ oSettings.aoColumns[i].sSortingClass );
- }
+ _fnApplyToChildren( function(nSizer, i) {
+ nSizer.innerHTML = "";
+ nSizer.style.width = footerWidths[i];
+ }, footerSrcEls );
+ }
+
+ // Sanity check that the table is of a sensible width. If not then we are going to get
+ // misalignment - try to prevent this by not allowing the table to shrink below its min width
+ if ( table.outerWidth() < sanityWidth )
+ {
+ // The min width depends upon if we have a vertical scrollbar visible or not */
+ correction = ((divBodyEl.scrollHeight > divBodyEl.offsetHeight ||
+ divBody.css('overflow-y') == "scroll")) ?
+ sanityWidth+barWidth :
+ sanityWidth;
+
+ // IE6/7 are a law unto themselves...
+ if ( ie67 && (divBodyEl.scrollHeight >
+ divBodyEl.offsetHeight || divBody.css('overflow-y') == "scroll")
+ ) {
+ tableStyle.width = _fnStringToCss( correction-barWidth );
}
-
- if ( oSettings.aaSortingFixed !== null )
- {
- aaSort = oSettings.aaSortingFixed.concat( oSettings.aaSorting );
+
+ // And give the user a warning that we've stopped the table getting too small
+ if ( scrollX === "" || scrollXInner !== "" ) {
+ _fnLog( settings, 1, 'Possible column misalignment', 6 );
}
- else
- {
- aaSort = oSettings.aaSorting.slice();
+ }
+ else
+ {
+ correction = '100%';
+ }
+
+ // Apply to the container elements
+ divBodyStyle.width = _fnStringToCss( correction );
+ divHeaderStyle.width = _fnStringToCss( correction );
+
+ if ( footer ) {
+ settings.nScrollFoot.style.width = _fnStringToCss( correction );
+ }
+
+
+ /*
+ * 4. Clean up
+ */
+ if ( ! scrollY ) {
+ /* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting
+ * the scrollbar height from the visible display, rather than adding it on. We need to
+ * set the height in order to sort this. Don't want to do it in any other browsers.
+ */
+ if ( ie67 ) {
+ divBodyStyle.height = _fnStringToCss( tableEl.offsetHeight+barWidth );
}
-
- /* Apply the required classes to the header */
- for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
- {
- if ( oSettings.aoColumns[i].bSortable )
- {
- sClass = oSettings.aoColumns[i].sSortingClass;
- iFound = -1;
- for ( j=0 ; j<aaSort.length ; j++ )
- {
- if ( aaSort[j][0] == i )
- {
- sClass = ( aaSort[j][1] == "asc" ) ?
- oClasses.sSortAsc : oClasses.sSortDesc;
- iFound = j;
- break;
- }
- }
- $(oSettings.aoColumns[i].nTh).addClass( sClass );
-
- if ( oSettings.bJUI )
- {
- /* jQuery UI uses extra markup */
- var jqSpan = $("span."+oClasses.sSortIcon, oSettings.aoColumns[i].nTh);
- jqSpan.removeClass(oClasses.sSortJUIAsc +" "+ oClasses.sSortJUIDesc +" "+
- oClasses.sSortJUI +" "+ oClasses.sSortJUIAscAllowed +" "+ oClasses.sSortJUIDescAllowed );
-
- var sSpanClass;
- if ( iFound == -1 )
- {
- sSpanClass = oSettings.aoColumns[i].sSortingClassJUI;
- }
- else if ( aaSort[iFound][1] == "asc" )
- {
- sSpanClass = oClasses.sSortJUIAsc;
- }
- else
- {
- sSpanClass = oClasses.sSortJUIDesc;
- }
-
- jqSpan.addClass( sSpanClass );
- }
- }
- else
- {
- /* No sorting on this column, so add the base class. This will have been assigned by
- * _fnAddColumn
- */
- $(oSettings.aoColumns[i].nTh).addClass( oSettings.aoColumns[i].sSortingClass );
- }
+ }
+
+ if ( scrollY && scroll.bCollapse ) {
+ divBodyStyle.height = _fnStringToCss( scrollY );
+
+ var iExtra = (scrollX && tableEl.offsetWidth > divBodyEl.offsetWidth) ?
+ barWidth :
+ 0;
+
+ if ( tableEl.offsetHeight < divBodyEl.offsetHeight ) {
+ divBodyStyle.height = _fnStringToCss( tableEl.offsetHeight+iExtra );
}
-
- /*
- * Apply the required classes to the table body
- * Note that this is given as a feature switch since it can significantly slow down a sort
- * on large data sets (adding and removing of classes is always slow at the best of times..)
- * Further to this, note that this code is admittedly fairly ugly. It could be made a lot
- * simpler using jQuery selectors and add/removeClass, but that is significantly slower
- * (on the order of 5 times slower) - hence the direct DOM manipulation here.
- * Note that for deferred drawing we do use jQuery - the reason being that taking the first
- * row found to see if the whole column needs processed can miss classes since the first
- * column might be new.
- */
- sClass = oClasses.sSortColumn;
-
- if ( oSettings.oFeatures.bSort && oSettings.oFeatures.bSortClasses )
- {
- var nTds = _fnGetTdNodes( oSettings );
-
- /* Determine what the sorting class for each column should be */
- var iClass, iTargetCol;
- var asClasses = [];
- for (i = 0; i < iColumns; i++)
- {
- asClasses.push("");
- }
- for (i = 0, iClass = 1; i < aaSort.length; i++)
- {
- iTargetCol = parseInt( aaSort[i][0], 10 );
- asClasses[iTargetCol] = sClass + iClass;
-
- if ( iClass < 3 )
- {
- iClass++;
- }
- }
-
- /* Make changes to the classes for each cell as needed */
- var reClass = new RegExp(sClass + "[123]");
- var sTmpClass, sCurrentClass, sNewClass;
- for ( i=0, iLen=nTds.length; i<iLen; i++ )
- {
- /* Determine which column we're looking at */
- iTargetCol = i % iColumns;
-
- /* What is the full list of classes now */
- sCurrentClass = nTds[i].className;
- /* What sorting class should be applied? */
- sNewClass = asClasses[iTargetCol];
- /* What would the new full list be if we did a replacement? */
- sTmpClass = sCurrentClass.replace(reClass, sNewClass);
-
- if ( sTmpClass != sCurrentClass )
- {
- /* We changed something */
- nTds[i].className = $.trim( sTmpClass );
+ }
+
+ /* Finally set the width's of the header and footer tables */
+ var iOuterWidth = table.outerWidth();
+ divHeaderTable[0].style.width = _fnStringToCss( iOuterWidth );
+ divHeaderInnerStyle.width = _fnStringToCss( iOuterWidth );
+
+ // Figure out if there are scrollbar present - if so then we need a the header and footer to
+ // provide a bit more space to allow "overflow" scrolling (i.e. past the scrollbar)
+ var bScrolling = table.height() > divBodyEl.clientHeight || divBody.css('overflow-y') == "scroll";
+ var padding = 'padding' + (browser.bScrollbarLeft ? 'Left' : 'Right' );
+ divHeaderInnerStyle[ padding ] = bScrolling ? barWidth+"px" : "0px";
+
+ if ( footer ) {
+ divFooterTable[0].style.width = _fnStringToCss( iOuterWidth );
+ divFooterInner[0].style.width = _fnStringToCss( iOuterWidth );
+ divFooterInner[0].style[padding] = bScrolling ? barWidth+"px" : "0px";
+ }
+
+ /* Adjust the position of the header in case we loose the y-scrollbar */
+ divBody.scroll();
+
+ // If sorting or filtering has occurred, jump the scrolling back to the top
+ // only if we aren't holding the position
+ if ( (settings.bSorted || settings.bFiltered) && ! settings._drawHold ) {
+ divBodyEl.scrollTop = 0;
+ }
+ }
+
+
+
+ /**
+ * Apply a given function to the display child nodes of an element array (typically
+ * TD children of TR rows
+ * @param {function} fn Method to apply to the objects
+ * @param array {nodes} an1 List of elements to look through for display children
+ * @param array {nodes} an2 Another list (identical structure to the first) - optional
+ * @memberof DataTable#oApi
+ */
+ function _fnApplyToChildren( fn, an1, an2 )
+ {
+ var index=0, i=0, iLen=an1.length;
+ var nNode1, nNode2;
+
+ while ( i < iLen ) {
+ nNode1 = an1[i].firstChild;
+ nNode2 = an2 ? an2[i].firstChild : null;
+
+ while ( nNode1 ) {
+ if ( nNode1.nodeType === 1 ) {
+ if ( an2 ) {
+ fn( nNode1, nNode2, index );
}
- else if ( sNewClass.length > 0 && sCurrentClass.indexOf(sNewClass) == -1 )
- {
- /* We need to add a class */
- nTds[i].className = sCurrentClass + " " + sNewClass;
+ else {
+ fn( nNode1, index );
}
+
+ index++;
}
+
+ nNode1 = nNode1.nextSibling;
+ nNode2 = an2 ? nNode2.nextSibling : null;
}
+
+ i++;
}
-
-
-
- /**
- * Save the state of a table in a cookie such that the page can be reloaded
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnSaveState ( oSettings )
- {
- if ( !oSettings.oFeatures.bStateSave || oSettings.bDestroying )
- {
- return;
- }
-
- /* Store the interesting variables */
- var i, iLen, bInfinite=oSettings.oScroll.bInfinite;
- var oState = {
- "iCreate": new Date().getTime(),
- "iStart": (bInfinite ? 0 : oSettings._iDisplayStart),
- "iEnd": (bInfinite ? oSettings._iDisplayLength : oSettings._iDisplayEnd),
- "iLength": oSettings._iDisplayLength,
- "aaSorting": $.extend( true, [], oSettings.aaSorting ),
- "oSearch": $.extend( true, {}, oSettings.oPreviousSearch ),
- "aoSearchCols": $.extend( true, [], oSettings.aoPreSearchCols ),
- "abVisCols": []
- };
-
- for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
- {
- oState.abVisCols.push( oSettings.aoColumns[i].bVisible );
+ }
+
+
+
+ var __re_html_remove = /<.*?>/g;
+
+
+ /**
+ * Calculate the width of columns for the table
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnCalculateColumnWidths ( oSettings )
+ {
+ var
+ table = oSettings.nTable,
+ columns = oSettings.aoColumns,
+ scroll = oSettings.oScroll,
+ scrollY = scroll.sY,
+ scrollX = scroll.sX,
+ scrollXInner = scroll.sXInner,
+ columnCount = columns.length,
+ visibleColumns = _fnGetColumns( oSettings, 'bVisible' ),
+ headerCells = $('th', oSettings.nTHead),
+ tableWidthAttr = table.getAttribute('width'), // from DOM element
+ tableContainer = table.parentNode,
+ userInputs = false,
+ i, column, columnIdx, width, outerWidth;
+
+ var styleWidth = table.style.width;
+ if ( styleWidth && styleWidth.indexOf('%') !== -1 ) {
+ tableWidthAttr = styleWidth;
+ }
+
+ /* Convert any user input sizes into pixel sizes */
+ for ( i=0 ; i<visibleColumns.length ; i++ ) {
+ column = columns[ visibleColumns[i] ];
+
+ if ( column.sWidth !== null ) {
+ column.sWidth = _fnConvertToWidth( column.sWidthOrig, tableContainer );
+
+ userInputs = true;
}
-
- _fnCallbackFire( oSettings, "aoStateSaveParams", 'stateSaveParams', [oSettings, oState] );
-
- oSettings.fnStateSave.call( oSettings.oInstance, oSettings, oState );
}
-
-
- /**
- * Attempt to load a saved table state from a cookie
- * @param {object} oSettings dataTables settings object
- * @param {object} oInit DataTables init object so we can override settings
- * @memberof DataTable#oApi
+
+ /* If the number of columns in the DOM equals the number that we have to
+ * process in DataTables, then we can use the offsets that are created by
+ * the web- browser. No custom sizes can be set in order for this to happen,
+ * nor scrolling used
*/
- function _fnLoadState ( oSettings, oInit )
+ if ( ! userInputs && ! scrollX && ! scrollY &&
+ columnCount == _fnVisbleColumns( oSettings ) &&
+ columnCount == headerCells.length
+ ) {
+ for ( i=0 ; i<columnCount ; i++ ) {
+ columns[i].sWidth = _fnStringToCss( headerCells.eq(i).width() );
+ }
+ }
+ else
{
- if ( !oSettings.oFeatures.bStateSave )
- {
- return;
+ // Otherwise construct a single row, worst case, table with the widest
+ // node in the data, assign any user defined widths, then insert it into
+ // the DOM and allow the browser to do all the hard work of calculating
+ // table widths
+ var tmpTable = $(table).clone() // don't use cloneNode - IE8 will remove events on the main table
+ .css( 'visibility', 'hidden' )
+ .removeAttr( 'id' );
+
+ // Clean up the table body
+ tmpTable.find('tbody tr').remove();
+ var tr = $('<tr/>').appendTo( tmpTable.find('tbody') );
+
+ // Remove any assigned widths from the footer (from scrolling)
+ tmpTable.find('tfoot th, tfoot td').css('width', '');
+
+ // Apply custom sizing to the cloned header
+ headerCells = _fnGetUniqueThs( oSettings, tmpTable.find('thead')[0] );
+
+ for ( i=0 ; i<visibleColumns.length ; i++ ) {
+ column = columns[ visibleColumns[i] ];
+
+ headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !== '' ?
+ _fnStringToCss( column.sWidthOrig ) :
+ '';
}
-
- var oData = oSettings.fnStateLoad.call( oSettings.oInstance, oSettings );
- if ( !oData )
- {
- return;
+
+ // Find the widest cell for each column and put it into the table
+ if ( oSettings.aoData.length ) {
+ for ( i=0 ; i<visibleColumns.length ; i++ ) {
+ columnIdx = visibleColumns[i];
+ column = columns[ columnIdx ];
+
+ $( _fnGetWidestNode( oSettings, columnIdx ) )
+ .clone( false )
+ .append( column.sContentPadding )
+ .appendTo( tr );
+ }
}
-
- /* Allow custom and plug-in manipulation functions to alter the saved data set and
- * cancelling of loading by returning false
- */
- var abStateLoad = _fnCallbackFire( oSettings, 'aoStateLoadParams', 'stateLoadParams', [oSettings, oData] );
- if ( $.inArray( false, abStateLoad ) !== -1 )
- {
- return;
+
+ // Table has been built, attach to the document so we can work with it
+ tmpTable.appendTo( tableContainer );
+
+ // When scrolling (X or Y) we want to set the width of the table as
+ // appropriate. However, when not scrolling leave the table width as it
+ // is. This results in slightly different, but I think correct behaviour
+ if ( scrollX && scrollXInner ) {
+ tmpTable.width( scrollXInner );
}
-
- /* Store the saved state so it might be accessed at any time */
- oSettings.oLoadedState = $.extend( true, {}, oData );
-
- /* Restore key features */
- oSettings._iDisplayStart = oData.iStart;
- oSettings.iInitDisplayStart = oData.iStart;
- oSettings._iDisplayEnd = oData.iEnd;
- oSettings._iDisplayLength = oData.iLength;
- oSettings.aaSorting = oData.aaSorting.slice();
- oSettings.saved_aaSorting = oData.aaSorting.slice();
-
- /* Search filtering */
- $.extend( oSettings.oPreviousSearch, oData.oSearch );
- $.extend( true, oSettings.aoPreSearchCols, oData.aoSearchCols );
-
- /* Column visibility state
- * Pass back visibility settings to the init handler, but to do not here override
- * the init object that the user might have passed in
- */
- oInit.saved_aoColumns = [];
- for ( var i=0 ; i<oData.abVisCols.length ; i++ )
- {
- oInit.saved_aoColumns[i] = {};
- oInit.saved_aoColumns[i].bVisible = oData.abVisCols[i];
+ else if ( scrollX ) {
+ tmpTable.css( 'width', 'auto' );
+
+ if ( tmpTable.width() < tableContainer.offsetWidth ) {
+ tmpTable.width( tableContainer.offsetWidth );
+ }
}
-
- _fnCallbackFire( oSettings, 'aoStateLoaded', 'stateLoaded', [oSettings, oData] );
- }
-
-
- /**
- * Create a new cookie with a value to store the state of a table
- * @param {string} sName name of the cookie to create
- * @param {string} sValue the value the cookie should take
- * @param {int} iSecs duration of the cookie
- * @param {string} sBaseName sName is made up of the base + file name - this is the base
- * @param {function} fnCallback User definable function to modify the cookie
- * @memberof DataTable#oApi
- */
- function _fnCreateCookie ( sName, sValue, iSecs, sBaseName, fnCallback )
- {
- var date = new Date();
- date.setTime( date.getTime()+(iSecs*1000) );
-
- /*
- * Shocking but true - it would appear IE has major issues with having the path not having
- * a trailing slash on it. We need the cookie to be available based on the path, so we
- * have to append the file name to the cookie name. Appalling. Thanks to vex for adding the
- * patch to use at least some of the path
- */
- var aParts = window.location.pathname.split('/');
- var sNameFile = sName + '_' + aParts.pop().replace(/[\/:]/g,"").toLowerCase();
- var sFullCookie, oData;
-
- if ( fnCallback !== null )
- {
- oData = (typeof $.parseJSON === 'function') ?
- $.parseJSON( sValue ) : eval( '('+sValue+')' );
- sFullCookie = fnCallback( sNameFile, oData, date.toGMTString(),
- aParts.join('/')+"/" );
+ else if ( scrollY ) {
+ tmpTable.width( tableContainer.offsetWidth );
}
- else
- {
- sFullCookie = sNameFile + "=" + encodeURIComponent(sValue) +
- "; expires=" + date.toGMTString() +"; path=" + aParts.join('/')+"/";
+ else if ( tableWidthAttr ) {
+ tmpTable.width( tableWidthAttr );
}
-
- /* Are we going to go over the cookie limit of 4KiB? If so, try to delete a cookies
- * belonging to DataTables.
- */
- var
- aCookies =document.cookie.split(';'),
- iNewCookieLen = sFullCookie.split(';')[0].length,
- aOldCookies = [];
-
- if ( iNewCookieLen+document.cookie.length+10 > 4096 ) /* Magic 10 for padding */
+
+ // Take into account the y scrollbar
+ _fnScrollingWidthAdjust( oSettings, tmpTable[0] );
+
+ // Browsers need a bit of a hand when a width is assigned to any columns
+ // when x-scrolling as they tend to collapse the table to the min-width,
+ // even if we sent the column widths. So we need to keep track of what
+ // the table width should be by summing the user given values, and the
+ // automatic values
+ if ( scrollX )
{
- for ( var i=0, iLen=aCookies.length ; i<iLen ; i++ )
- {
- if ( aCookies[i].indexOf( sBaseName ) != -1 )
- {
- /* It's a DataTables cookie, so eval it and check the time stamp */
- var aSplitCookie = aCookies[i].split('=');
- try {
- oData = eval( '('+decodeURIComponent(aSplitCookie[1])+')' );
-
- if ( oData && oData.iCreate )
- {
- aOldCookies.push( {
- "name": aSplitCookie[0],
- "time": oData.iCreate
- } );
- }
- }
- catch( e ) {}
- }
+ var total = 0;
+
+ for ( i=0 ; i<visibleColumns.length ; i++ ) {
+ column = columns[ visibleColumns[i] ];
+ outerWidth = $(headerCells[i]).outerWidth();
+
+ total += column.sWidthOrig === null ?
+ outerWidth :
+ parseInt( column.sWidth, 10 ) + outerWidth - $(headerCells[i]).width();
}
-
- // Make sure we delete the oldest ones first
- aOldCookies.sort( function (a, b) {
- return b.time - a.time;
- } );
-
- // Eliminate as many old DataTables cookies as we need to
- while ( iNewCookieLen + document.cookie.length + 10 > 4096 ) {
- if ( aOldCookies.length === 0 ) {
- // Deleted all DT cookies and still not enough space. Can't state save
- return;
- }
-
- var old = aOldCookies.pop();
- document.cookie = old.name+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path="+
- aParts.join('/') + "/";
+
+ tmpTable.width( _fnStringToCss( total ) );
+ table.style.width = _fnStringToCss( total );
+ }
+
+ // Get the width of each column in the constructed table
+ for ( i=0 ; i<visibleColumns.length ; i++ ) {
+ column = columns[ visibleColumns[i] ];
+ width = $(headerCells[i]).width();
+
+ if ( width ) {
+ column.sWidth = _fnStringToCss( width );
}
}
-
- document.cookie = sFullCookie;
+
+ table.style.width = _fnStringToCss( tmpTable.css('width') );
+
+ // Finished with the table - ditch it
+ tmpTable.remove();
}
-
-
- /**
- * Read an old cookie to get a cookie with an old table state
- * @param {string} sName name of the cookie to read
- * @returns {string} contents of the cookie - or null if no cookie with that name found
- * @memberof DataTable#oApi
- */
- function _fnReadCookie ( sName )
- {
+
+ // If there is a width attr, we want to attach an event listener which
+ // allows the table sizing to automatically adjust when the window is
+ // resized. Use the width attr rather than CSS, since we can't know if the
+ // CSS is a relative value or absolute - DOM read is always px.
+ if ( tableWidthAttr ) {
+ table.style.width = _fnStringToCss( tableWidthAttr );
+ }
+
+ if ( (tableWidthAttr || scrollX) && ! oSettings._reszEvt ) {
+ var bindResize = function () {
+ $(window).bind('resize.DT-'+oSettings.sInstance, _fnThrottle( function () {
+ _fnAdjustColumnSizing( oSettings );
+ } ) );
+ };
+
+ // IE6/7 will crash if we bind a resize event handler on page load.
+ // To be removed in 1.11 which drops IE6/7 support
+ if ( oSettings.oBrowser.bScrollOversize ) {
+ setTimeout( bindResize, 1000 );
+ }
+ else {
+ bindResize();
+ }
+
+ oSettings._reszEvt = true;
+ }
+ }
+
+
+ /**
+ * Throttle the calls to a function. Arguments and context are maintained for
+ * the throttled function
+ * @param {function} fn Function to be called
+ * @param {int} [freq=200] call frequency in mS
+ * @returns {function} wrapped function
+ * @memberof DataTable#oApi
+ */
+ function _fnThrottle( fn, freq ) {
+ var
+ frequency = freq !== undefined ? freq : 200,
+ last,
+ timer;
+
+ return function () {
var
- aParts = window.location.pathname.split('/'),
- sNameEQ = sName + '_' + aParts[aParts.length-1].replace(/[\/:]/g,"").toLowerCase() + '=',
- sCookieContents = document.cookie.split(';');
-
- for( var i=0 ; i<sCookieContents.length ; i++ )
- {
- var c = sCookieContents[i];
-
- while (c.charAt(0)==' ')
- {
- c = c.substring(1,c.length);
- }
-
- if (c.indexOf(sNameEQ) === 0)
- {
- return decodeURIComponent( c.substring(sNameEQ.length,c.length) );
- }
+ that = this,
+ now = +new Date(),
+ args = arguments;
+
+ if ( last && now < last + frequency ) {
+ clearTimeout( timer );
+
+ timer = setTimeout( function () {
+ last = undefined;
+ fn.apply( that, args );
+ }, frequency );
+ }
+ else {
+ last = now;
+ fn.apply( that, args );
}
+ };
+ }
+
+
+ /**
+ * Convert a CSS unit width to pixels (e.g. 2em)
+ * @param {string} width width to be converted
+ * @param {node} parent parent to get the with for (required for relative widths) - optional
+ * @returns {int} width in pixels
+ * @memberof DataTable#oApi
+ */
+ function _fnConvertToWidth ( width, parent )
+ {
+ if ( ! width ) {
+ return 0;
+ }
+
+ var n = $('<div/>')
+ .css( 'width', _fnStringToCss( width ) )
+ .appendTo( parent || document.body );
+
+ var val = n[0].offsetWidth;
+ n.remove();
+
+ return val;
+ }
+
+
+ /**
+ * Adjust a table's width to take account of vertical scroll bar
+ * @param {object} oSettings dataTables settings object
+ * @param {node} n table node
+ * @memberof DataTable#oApi
+ */
+
+ function _fnScrollingWidthAdjust ( settings, n )
+ {
+ var scroll = settings.oScroll;
+
+ if ( scroll.sX || scroll.sY ) {
+ // When y-scrolling only, we want to remove the width of the scroll bar
+ // so the table + scroll bar will fit into the area available, otherwise
+ // we fix the table at its current size with no adjustment
+ var correction = ! scroll.sX ? scroll.iBarWidth : 0;
+ n.style.width = _fnStringToCss( $(n).outerWidth() - correction );
+ }
+ }
+
+
+ /**
+ * Get the widest node
+ * @param {object} settings dataTables settings object
+ * @param {int} colIdx column of interest
+ * @returns {node} widest table node
+ * @memberof DataTable#oApi
+ */
+ function _fnGetWidestNode( settings, colIdx )
+ {
+ var idx = _fnGetMaxLenString( settings, colIdx );
+ if ( idx < 0 ) {
return null;
}
-
-
- /**
- * Return the settings object for a particular table
- * @param {node} nTable table we are using as a dataTable
- * @returns {object} Settings object - or null if not found
- * @memberof DataTable#oApi
- */
- function _fnSettingsFromNode ( nTable )
- {
- for ( var i=0 ; i<DataTable.settings.length ; i++ )
- {
- if ( DataTable.settings[i].nTable === nTable )
- {
- return DataTable.settings[i];
- }
+
+ var data = settings.aoData[ idx ];
+ return ! data.nTr ? // Might not have been created when deferred rendering
+ $('<td/>').html( _fnGetCellData( settings, idx, colIdx, 'display' ) )[0] :
+ data.anCells[ colIdx ];
+ }
+
+
+ /**
+ * Get the maximum strlen for each data column
+ * @param {object} settings dataTables settings object
+ * @param {int} colIdx column of interest
+ * @returns {string} max string length for each column
+ * @memberof DataTable#oApi
+ */
+ function _fnGetMaxLenString( settings, colIdx )
+ {
+ var s, max=-1, maxIdx = -1;
+
+ for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
+ s = _fnGetCellData( settings, i, colIdx, 'display' )+'';
+ s = s.replace( __re_html_remove, '' );
+
+ if ( s.length > max ) {
+ max = s.length;
+ maxIdx = i;
}
-
- return null;
}
-
-
- /**
- * Return an array with the TR nodes for the table
- * @param {object} oSettings dataTables settings object
- * @returns {array} TR array
- * @memberof DataTable#oApi
- */
- function _fnGetTrNodes ( oSettings )
- {
- var aNodes = [];
- var aoData = oSettings.aoData;
- for ( var i=0, iLen=aoData.length ; i<iLen ; i++ )
- {
- if ( aoData[i].nTr !== null )
- {
- aNodes.push( aoData[i].nTr );
+
+ return maxIdx;
+ }
+
+
+ /**
+ * Append a CSS unit (only if required) to a string
+ * @param {string} value to css-ify
+ * @returns {string} value with css unit
+ * @memberof DataTable#oApi
+ */
+ function _fnStringToCss( s )
+ {
+ if ( s === null ) {
+ return '0px';
+ }
+
+ if ( typeof s == 'number' ) {
+ return s < 0 ?
+ '0px' :
+ s+'px';
+ }
+
+ // Check it has a unit character already
+ return s.match(/\d$/) ?
+ s+'px' :
+ s;
+ }
+
+
+ /**
+ * Get the width of a scroll bar in this browser being used
+ * @returns {int} width in pixels
+ * @memberof DataTable#oApi
+ */
+ function _fnScrollBarWidth ()
+ {
+ // On first run a static variable is set, since this is only needed once.
+ // Subsequent runs will just use the previously calculated value
+ var width = DataTable.__scrollbarWidth;
+
+ if ( width === undefined ) {
+ var sizer = $('<p/>').css( {
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ width: '100%',
+ height: 150,
+ padding: 0,
+ overflow: 'scroll',
+ visibility: 'hidden'
+ } )
+ .appendTo('body');
+
+ width = sizer[0].offsetWidth - sizer[0].clientWidth;
+ DataTable.__scrollbarWidth = width;
+
+ sizer.remove();
+ }
+
+ return width;
+ }
+
+
+
+ function _fnSortFlatten ( settings )
+ {
+ var
+ i, iLen, k, kLen,
+ aSort = [],
+ aiOrig = [],
+ aoColumns = settings.aoColumns,
+ aDataSort, iCol, sType, srcCol,
+ fixed = settings.aaSortingFixed,
+ fixedObj = $.isPlainObject( fixed ),
+ nestedSort = [],
+ add = function ( a ) {
+ if ( a.length && ! $.isArray( a[0] ) ) {
+ // 1D array
+ nestedSort.push( a );
+ }
+ else {
+ // 2D array
+ nestedSort.push.apply( nestedSort, a );
}
- }
- return aNodes;
+ };
+
+ // Build the sort array, with pre-fix and post-fix options if they have been
+ // specified
+ if ( $.isArray( fixed ) ) {
+ add( fixed );
}
-
-
- /**
- * Return an flat array with all TD nodes for the table, or row
- * @param {object} oSettings dataTables settings object
- * @param {int} [iIndividualRow] aoData index to get the nodes for - optional
- * if not given then the return array will contain all nodes for the table
- * @returns {array} TD array
- * @memberof DataTable#oApi
- */
- function _fnGetTdNodes ( oSettings, iIndividualRow )
+
+ if ( fixedObj && fixed.pre ) {
+ add( fixed.pre );
+ }
+
+ add( settings.aaSorting );
+
+ if (fixedObj && fixed.post ) {
+ add( fixed.post );
+ }
+
+ for ( i=0 ; i<nestedSort.length ; i++ )
{
- var anReturn = [];
- var iCorrector;
- var anTds, nTd;
- var iRow, iRows=oSettings.aoData.length,
- iColumn, iColumns, oData, sNodeName, iStart=0, iEnd=iRows;
-
- /* Allow the collection to be limited to just one row */
- if ( iIndividualRow !== undefined )
+ srcCol = nestedSort[i][0];
+ aDataSort = aoColumns[ srcCol ].aDataSort;
+
+ for ( k=0, kLen=aDataSort.length ; k<kLen ; k++ )
{
- iStart = iIndividualRow;
- iEnd = iIndividualRow+1;
+ iCol = aDataSort[k];
+ sType = aoColumns[ iCol ].sType || 'string';
+
+ if ( nestedSort[i]._idx === undefined ) {
+ nestedSort[i]._idx = $.inArray( nestedSort[i][1], aoColumns[iCol].asSorting );
+ }
+
+ aSort.push( {
+ src: srcCol,
+ col: iCol,
+ dir: nestedSort[i][1],
+ index: nestedSort[i]._idx,
+ type: sType,
+ formatter: DataTable.ext.type.order[ sType+"-pre" ]
+ } );
}
-
- for ( iRow=iStart ; iRow<iEnd ; iRow++ )
- {
- oData = oSettings.aoData[iRow];
- if ( oData.nTr !== null )
- {
- /* get the TD child nodes - taking into account text etc nodes */
- anTds = [];
- nTd = oData.nTr.firstChild;
- while ( nTd )
- {
- sNodeName = nTd.nodeName.toLowerCase();
- if ( sNodeName == 'td' || sNodeName == 'th' )
- {
- anTds.push( nTd );
+ }
+
+ return aSort;
+ }
+
+ /**
+ * Change the order of the table
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ * @todo This really needs split up!
+ */
+ function _fnSort ( oSettings )
+ {
+ var
+ i, ien, iLen, j, jLen, k, kLen,
+ sDataType, nTh,
+ aiOrig = [],
+ oExtSort = DataTable.ext.type.order,
+ aoData = oSettings.aoData,
+ aoColumns = oSettings.aoColumns,
+ aDataSort, data, iCol, sType, oSort,
+ formatters = 0,
+ sortCol,
+ displayMaster = oSettings.aiDisplayMaster,
+ aSort;
+
+ // Resolve any column types that are unknown due to addition or invalidation
+ // @todo Can this be moved into a 'data-ready' handler which is called when
+ // data is going to be used in the table?
+ _fnColumnTypes( oSettings );
+
+ aSort = _fnSortFlatten( oSettings );
+
+ for ( i=0, ien=aSort.length ; i<ien ; i++ ) {
+ sortCol = aSort[i];
+
+ // Track if we can use the fast sort algorithm
+ if ( sortCol.formatter ) {
+ formatters++;
+ }
+
+ // Load the data needed for the sort, for each cell
+ _fnSortData( oSettings, sortCol.col );
+ }
+
+ /* No sorting required if server-side or no sorting array */
+ if ( _fnDataSource( oSettings ) != 'ssp' && aSort.length !== 0 )
+ {
+ // Create a value - key array of the current row positions such that we can use their
+ // current position during the sort, if values match, in order to perform stable sorting
+ for ( i=0, iLen=displayMaster.length ; i<iLen ; i++ ) {
+ aiOrig[ displayMaster[i] ] = i;
+ }
+
+ /* Do the sort - here we want multi-column sorting based on a given data source (column)
+ * and sorting function (from oSort) in a certain direction. It's reasonably complex to
+ * follow on it's own, but this is what we want (example two column sorting):
+ * fnLocalSorting = function(a,b){
+ * var iTest;
+ * iTest = oSort['string-asc']('data11', 'data12');
+ * if (iTest !== 0)
+ * return iTest;
+ * iTest = oSort['numeric-desc']('data21', 'data22');
+ * if (iTest !== 0)
+ * return iTest;
+ * return oSort['numeric-asc']( aiOrig[a], aiOrig[b] );
+ * }
+ * Basically we have a test for each sorting column, if the data in that column is equal,
+ * test the next column. If all columns match, then we use a numeric sort on the row
+ * positions in the original data array to provide a stable sort.
+ *
+ * Note - I know it seems excessive to have two sorting methods, but the first is around
+ * 15% faster, so the second is only maintained for backwards compatibility with sorting
+ * methods which do not have a pre-sort formatting function.
+ */
+ if ( formatters === aSort.length ) {
+ // All sort types have formatting functions
+ displayMaster.sort( function ( a, b ) {
+ var
+ x, y, k, test, sort,
+ len=aSort.length,
+ dataA = aoData[a]._aSortData,
+ dataB = aoData[b]._aSortData;
+
+ for ( k=0 ; k<len ; k++ ) {
+ sort = aSort[k];
+
+ x = dataA[ sort.col ];
+ y = dataB[ sort.col ];
+
+ test = x<y ? -1 : x>y ? 1 : 0;
+ if ( test !== 0 ) {
+ return sort.dir === 'asc' ? test : -test;
}
- nTd = nTd.nextSibling;
}
-
- iCorrector = 0;
- for ( iColumn=0, iColumns=oSettings.aoColumns.length ; iColumn<iColumns ; iColumn++ )
- {
- if ( oSettings.aoColumns[iColumn].bVisible )
- {
- anReturn.push( anTds[iColumn-iCorrector] );
- }
- else
- {
- anReturn.push( oData._anHidden[iColumn] );
- iCorrector++;
+
+ x = aiOrig[a];
+ y = aiOrig[b];
+ return x<y ? -1 : x>y ? 1 : 0;
+ } );
+ }
+ else {
+ // Depreciated - remove in 1.11 (providing a plug-in option)
+ // Not all sort types have formatting methods, so we have to call their sorting
+ // methods.
+ displayMaster.sort( function ( a, b ) {
+ var
+ x, y, k, l, test, sort, fn,
+ len=aSort.length,
+ dataA = aoData[a]._aSortData,
+ dataB = aoData[b]._aSortData;
+
+ for ( k=0 ; k<len ; k++ ) {
+ sort = aSort[k];
+
+ x = dataA[ sort.col ];
+ y = dataB[ sort.col ];
+
+ fn = oExtSort[ sort.type+"-"+sort.dir ] || oExtSort[ "string-"+sort.dir ];
+ test = fn( x, y );
+ if ( test !== 0 ) {
+ return test;
}
}
- }
+
+ x = aiOrig[a];
+ y = aiOrig[b];
+ return x<y ? -1 : x>y ? 1 : 0;
+ } );
}
-
- return anReturn;
}
-
-
- /**
- * Log an error message
- * @param {object} oSettings dataTables settings object
- * @param {int} iLevel log error messages, or display them to the user
- * @param {string} sMesg error message
- * @memberof DataTable#oApi
- */
- function _fnLog( oSettings, iLevel, sMesg )
- {
- var sAlert = (oSettings===null) ?
- "DataTables warning: "+sMesg :
- "DataTables warning (table id = '"+oSettings.sTableId+"'): "+sMesg;
-
- if ( iLevel === 0 )
- {
- if ( DataTable.ext.sErrMode == 'alert' )
- {
- alert( sAlert );
+
+ /* Tell the draw function that we have sorted the data */
+ oSettings.bSorted = true;
+ }
+
+
+ function _fnSortAria ( settings )
+ {
+ var label;
+ var nextSort;
+ var columns = settings.aoColumns;
+ var aSort = _fnSortFlatten( settings );
+ var oAria = settings.oLanguage.oAria;
+
+ // ARIA attributes - need to loop all columns, to update all (removing old
+ // attributes as needed)
+ for ( var i=0, iLen=columns.length ; i<iLen ; i++ )
+ {
+ var col = columns[i];
+ var asSorting = col.asSorting;
+ var sTitle = col.sTitle.replace( /<.*?>/g, "" );
+ var th = col.nTh;
+
+ // IE7 is throwing an error when setting these properties with jQuery's
+ // attr() and removeAttr() methods...
+ th.removeAttribute('aria-sort');
+
+ /* In ARIA only the first sorting column can be marked as sorting - no multi-sort option */
+ if ( col.bSortable ) {
+ if ( aSort.length > 0 && aSort[0].col == i ) {
+ th.setAttribute('aria-sort', aSort[0].dir=="asc" ? "ascending" : "descending" );
+ nextSort = asSorting[ aSort[0].index+1 ] || asSorting[0];
+ }
+ else {
+ nextSort = asSorting[0];
+ }
+
+ label = sTitle + ( nextSort === "asc" ?
+ oAria.sSortAscending :
+ oAria.sSortDescending
+ );
+ }
+ else {
+ label = sTitle;
+ }
+
+ th.setAttribute('aria-label', label);
+ }
+ }
+
+
+ /**
+ * Function to run on user sort request
+ * @param {object} settings dataTables settings object
+ * @param {node} attachTo node to attach the handler to
+ * @param {int} colIdx column sorting index
+ * @param {boolean} [append=false] Append the requested sort to the existing
+ * sort if true (i.e. multi-column sort)
+ * @param {function} [callback] callback function
+ * @memberof DataTable#oApi
+ */
+ function _fnSortListener ( settings, colIdx, append, callback )
+ {
+ var col = settings.aoColumns[ colIdx ];
+ var sorting = settings.aaSorting;
+ var asSorting = col.asSorting;
+ var nextSortIdx;
+ var next = function ( a, overflow ) {
+ var idx = a._idx;
+ if ( idx === undefined ) {
+ idx = $.inArray( a[1], asSorting );
+ }
+
+ return idx+1 < asSorting.length ?
+ idx+1 :
+ overflow ?
+ null :
+ 0;
+ };
+
+ // Convert to 2D array if needed
+ if ( typeof sorting[0] === 'number' ) {
+ sorting = settings.aaSorting = [ sorting ];
+ }
+
+ // If appending the sort then we are multi-column sorting
+ if ( append && settings.oFeatures.bSortMulti ) {
+ // Are we already doing some kind of sort on this column?
+ var sortIdx = $.inArray( colIdx, _pluck(sorting, '0') );
+
+ if ( sortIdx !== -1 ) {
+ // Yes, modify the sort
+ nextSortIdx = next( sorting[sortIdx], true );
+
+ if ( nextSortIdx === null && sorting.length === 1 ) {
+ nextSortIdx = 0; // can't remove sorting completely
}
- else
- {
- throw new Error(sAlert);
+
+ if ( nextSortIdx === null ) {
+ sorting.splice( sortIdx, 1 );
+ }
+ else {
+ sorting[sortIdx][1] = asSorting[ nextSortIdx ];
+ sorting[sortIdx]._idx = nextSortIdx;
}
- return;
}
- else if ( window.console && console.log )
- {
- console.log( sAlert );
+ else {
+ // No sort on this column yet
+ sorting.push( [ colIdx, asSorting[0], 0 ] );
+ sorting[sorting.length-1]._idx = 0;
}
}
-
-
- /**
- * See if a property is defined on one object, if so assign it to the other object
- * @param {object} oRet target object
- * @param {object} oSrc source object
- * @param {string} sName property
- * @param {string} [sMappedName] name to map too - optional, sName used if not given
- * @memberof DataTable#oApi
- */
- function _fnMap( oRet, oSrc, sName, sMappedName )
- {
- if ( sMappedName === undefined )
- {
- sMappedName = sName;
+ else if ( sorting.length && sorting[0][0] == colIdx ) {
+ // Single column - already sorting on this column, modify the sort
+ nextSortIdx = next( sorting[0] );
+
+ sorting.length = 1;
+ sorting[0][1] = asSorting[ nextSortIdx ];
+ sorting[0]._idx = nextSortIdx;
+ }
+ else {
+ // Single column - sort only on this column
+ sorting.length = 0;
+ sorting.push( [ colIdx, asSorting[0] ] );
+ sorting[0]._idx = 0;
+ }
+
+ // Run the sort by calling a full redraw
+ _fnReDraw( settings );
+
+ // callback used for async user interaction
+ if ( typeof callback == 'function' ) {
+ callback( settings );
+ }
+ }
+
+
+ /**
+ * Attach a sort handler (click) to a node
+ * @param {object} settings dataTables settings object
+ * @param {node} attachTo node to attach the handler to
+ * @param {int} colIdx column sorting index
+ * @param {function} [callback] callback function
+ * @memberof DataTable#oApi
+ */
+ function _fnSortAttachListener ( settings, attachTo, colIdx, callback )
+ {
+ var col = settings.aoColumns[ colIdx ];
+
+ _fnBindAction( attachTo, {}, function (e) {
+ /* If the column is not sortable - don't to anything */
+ if ( col.bSortable === false ) {
+ return;
}
- if ( oSrc[sName] !== undefined )
- {
- oRet[sMappedName] = oSrc[sName];
+
+ // If processing is enabled use a timeout to allow the processing
+ // display to be shown - otherwise to it synchronously
+ if ( settings.oFeatures.bProcessing ) {
+ _fnProcessingDisplay( settings, true );
+
+ setTimeout( function() {
+ _fnSortListener( settings, colIdx, e.shiftKey, callback );
+
+ // In server-side processing, the draw callback will remove the
+ // processing display
+ if ( _fnDataSource( settings ) !== 'ssp' ) {
+ _fnProcessingDisplay( settings, false );
+ }
+ }, 0 );
+ }
+ else {
+ _fnSortListener( settings, colIdx, e.shiftKey, callback );
+ }
+ } );
+ }
+
+
+ /**
+ * Set the sorting classes on table's body, Note: it is safe to call this function
+ * when bSort and bSortClasses are false
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnSortingClasses( settings )
+ {
+ var oldSort = settings.aLastSort;
+ var sortClass = settings.oClasses.sSortColumn;
+ var sort = _fnSortFlatten( settings );
+ var features = settings.oFeatures;
+ var i, ien, colIdx;
+
+ if ( features.bSort && features.bSortClasses ) {
+ // Remove old sorting classes
+ for ( i=0, ien=oldSort.length ; i<ien ; i++ ) {
+ colIdx = oldSort[i].src;
+
+ // Remove column sorting
+ $( _pluck( settings.aoData, 'anCells', colIdx ) )
+ .removeClass( sortClass + (i<2 ? i+1 : 3) );
+ }
+
+ // Add new column sorting
+ for ( i=0, ien=sort.length ; i<ien ; i++ ) {
+ colIdx = sort[i].src;
+
+ $( _pluck( settings.aoData, 'anCells', colIdx ) )
+ .addClass( sortClass + (i<2 ? i+1 : 3) );
}
}
-
-
- /**
- * Extend objects - very similar to jQuery.extend, but deep copy objects, and shallow
- * copy arrays. The reason we need to do this, is that we don't want to deep copy array
- * init values (such as aaSorting) since the dev wouldn't be able to override them, but
- * we do want to deep copy arrays.
- * @param {object} oOut Object to extend
- * @param {object} oExtender Object from which the properties will be applied to oOut
- * @returns {object} oOut Reference, just for convenience - oOut === the return.
- * @memberof DataTable#oApi
- * @todo This doesn't take account of arrays inside the deep copied objects.
- */
- function _fnExtend( oOut, oExtender )
- {
- var val;
-
- for ( var prop in oExtender )
- {
- if ( oExtender.hasOwnProperty(prop) )
- {
- val = oExtender[prop];
-
- if ( typeof oInit[prop] === 'object' && val !== null && $.isArray(val) === false )
- {
- $.extend( true, oOut[prop], val );
- }
- else
- {
- oOut[prop] = val;
- }
- }
+
+ settings.aLastSort = sort;
+ }
+
+
+ // Get the data to sort a column, be it from cache, fresh (populating the
+ // cache), or from a sort formatter
+ function _fnSortData( settings, idx )
+ {
+ // Custom sorting function - provided by the sort data type
+ var column = settings.aoColumns[ idx ];
+ var customSort = DataTable.ext.order[ column.sSortDataType ];
+ var customData;
+
+ if ( customSort ) {
+ customData = customSort.call( settings.oInstance, settings, idx,
+ _fnColumnIndexToVisible( settings, idx )
+ );
+ }
+
+ // Use / populate cache
+ var row, cellData;
+ var formatter = DataTable.ext.type.order[ column.sType+"-pre" ];
+
+ for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
+ row = settings.aoData[i];
+
+ if ( ! row._aSortData ) {
+ row._aSortData = [];
+ }
+
+ if ( ! row._aSortData[idx] || customSort ) {
+ cellData = customSort ?
+ customData[i] : // If there was a custom sort function, use data from there
+ _fnGetCellData( settings, i, idx, 'sort' );
+
+ row._aSortData[ idx ] = formatter ?
+ formatter( cellData ) :
+ cellData;
}
-
- return oOut;
}
-
-
- /**
- * Bind an event handers to allow a click or return key to activate the callback.
- * This is good for accessibility since a return on the keyboard will have the
- * same effect as a click, if the element has focus.
- * @param {element} n Element to bind the action to
- * @param {object} oData Data object to pass to the triggered function
- * @param {function} fn Callback function for when the event is triggered
- * @memberof DataTable#oApi
- */
- function _fnBindAction( n, oData, fn )
+ }
+
+
+
+ /**
+ * Save the state of a table
+ * @param {object} oSettings dataTables settings object
+ * @memberof DataTable#oApi
+ */
+ function _fnSaveState ( settings )
+ {
+ if ( !settings.oFeatures.bStateSave || settings.bDestroying )
{
- $(n)
- .bind( 'click.DT', oData, function (e) {
- n.blur(); // Remove focus outline for mouse users
- fn(e);
- } )
- .bind( 'keypress.DT', oData, function (e){
- if ( e.which === 13 ) {
- fn(e);
- } } )
- .bind( 'selectstart.DT', function () {
- /* Take the brutal approach to cancelling text selection */
- return false;
- } );
+ return;
}
-
-
- /**
- * Register a callback function. Easily allows a callback function to be added to
- * an array store of callback functions that can then all be called together.
- * @param {object} oSettings dataTables settings object
- * @param {string} sStore Name of the array storage for the callbacks in oSettings
- * @param {function} fn Function to be called back
- * @param {string} sName Identifying name for the callback (i.e. a label)
- * @memberof DataTable#oApi
+
+ /* Store the interesting variables */
+ var state = {
+ time: +new Date(),
+ start: settings._iDisplayStart,
+ length: settings._iDisplayLength,
+ order: $.extend( true, [], settings.aaSorting ),
+ search: _fnSearchToCamel( settings.oPreviousSearch ),
+ columns: $.map( settings.aoColumns, function ( col, i ) {
+ return {
+ visible: col.bVisible,
+ search: _fnSearchToCamel( settings.aoPreSearchCols[i] )
+ };
+ } )
+ };
+
+ _fnCallbackFire( settings, "aoStateSaveParams", 'stateSaveParams', [settings, state] );
+
+ settings.oSavedState = state;
+ settings.fnStateSaveCallback.call( settings.oInstance, settings, state );
+ }
+
+
+ /**
+ * Attempt to load a saved table state
+ * @param {object} oSettings dataTables settings object
+ * @param {object} oInit DataTables init object so we can override settings
+ * @memberof DataTable#oApi
+ */
+ function _fnLoadState ( settings, oInit )
+ {
+ var i, ien;
+ var columns = settings.aoColumns;
+
+ if ( ! settings.oFeatures.bStateSave ) {
+ return;
+ }
+
+ var state = settings.fnStateLoadCallback.call( settings.oInstance, settings );
+ if ( ! state || ! state.time ) {
+ return;
+ }
+
+ /* Allow custom and plug-in manipulation functions to alter the saved data set and
+ * cancelling of loading by returning false
*/
- function _fnCallbackReg( oSettings, sStore, fn, sName )
- {
- if ( fn )
- {
- oSettings[sStore].push( {
- "fn": fn,
- "sName": sName
- } );
+ var abStateLoad = _fnCallbackFire( settings, 'aoStateLoadParams', 'stateLoadParams', [settings, state] );
+ if ( $.inArray( false, abStateLoad ) !== -1 ) {
+ return;
+ }
+
+ /* Reject old data */
+ var duration = settings.iStateDuration;
+ if ( duration > 0 && state.time < +new Date() - (duration*1000) ) {
+ return;
+ }
+
+ // Number of columns have changed - all bets are off, no restore of settings
+ if ( columns.length !== state.columns.length ) {
+ return;
+ }
+
+ // Store the saved state so it might be accessed at any time
+ settings.oLoadedState = $.extend( true, {}, state );
+
+ // Restore key features - todo - for 1.11 this needs to be done by
+ // subscribed events
+ if ( state.start !== undefined ) {
+ settings._iDisplayStart = state.start;
+ settings.iInitDisplayStart = state.start;
+ }
+ if ( state.length !== undefined ) {
+ settings._iDisplayLength = state.length;
+ }
+
+ // Order
+ if ( state.order !== undefined ) {
+ settings.aaSorting = [];
+ $.each( state.order, function ( i, col ) {
+ settings.aaSorting.push( col[0] >= columns.length ?
+ [ 0, col[1] ] :
+ col
+ );
+ } );
+ }
+
+ // Search
+ if ( state.search !== undefined ) {
+ $.extend( settings.oPreviousSearch, _fnSearchToHung( state.search ) );
+ }
+
+ // Columns
+ for ( i=0, ien=state.columns.length ; i<ien ; i++ ) {
+ var col = state.columns[i];
+
+ // Visibility
+ if ( col.visible !== undefined ) {
+ columns[i].bVisible = col.visible;
+ }
+
+ // Search
+ if ( col.search !== undefined ) {
+ $.extend( settings.aoPreSearchCols[i], _fnSearchToHung( col.search ) );
}
}
-
-
- /**
- * Fire callback functions and trigger events. Note that the loop over the callback
- * array store is done backwards! Further note that you do not want to fire off triggers
- * in time sensitive applications (for example cell creation) as its slow.
- * @param {object} oSettings dataTables settings object
- * @param {string} sStore Name of the array storage for the callbacks in oSettings
- * @param {string} sTrigger Name of the jQuery custom event to trigger. If null no trigger
- * is fired
- * @param {array} aArgs Array of arguments to pass to the callback function / trigger
- * @memberof DataTable#oApi
- */
- function _fnCallbackFire( oSettings, sStore, sTrigger, aArgs )
- {
- var aoStore = oSettings[sStore];
- var aRet =[];
-
- for ( var i=aoStore.length-1 ; i>=0 ; i-- )
- {
- aRet.push( aoStore[i].fn.apply( oSettings.oInstance, aArgs ) );
+
+ _fnCallbackFire( settings, 'aoStateLoaded', 'stateLoaded', [settings, state] );
+ }
+
+
+ /**
+ * Return the settings object for a particular table
+ * @param {node} table table we are using as a dataTable
+ * @returns {object} Settings object - or null if not found
+ * @memberof DataTable#oApi
+ */
+ function _fnSettingsFromNode ( table )
+ {
+ var settings = DataTable.settings;
+ var idx = $.inArray( table, _pluck( settings, 'nTable' ) );
+
+ return idx !== -1 ?
+ settings[ idx ] :
+ null;
+ }
+
+
+ /**
+ * Log an error message
+ * @param {object} settings dataTables settings object
+ * @param {int} level log error messages, or display them to the user
+ * @param {string} msg error message
+ * @param {int} tn Technical note id to get more information about the error.
+ * @memberof DataTable#oApi
+ */
+ function _fnLog( settings, level, msg, tn )
+ {
+ msg = 'DataTables warning: '+
+ (settings!==null ? 'table id='+settings.sTableId+' - ' : '')+msg;
+
+ if ( tn ) {
+ msg += '. For more information about this error, please see '+
+ 'http://datatables.net/tn/'+tn;
+ }
+
+ if ( ! level ) {
+ // Backwards compatibility pre 1.10
+ var ext = DataTable.ext;
+ var type = ext.sErrMode || ext.errMode;
+
+ _fnCallbackFire( settings, null, 'error', [ settings, tn, msg ] );
+
+ if ( type == 'alert' ) {
+ alert( msg );
}
-
- if ( sTrigger !== null )
- {
- $(oSettings.oInstance).trigger(sTrigger, aArgs);
+ else if ( type == 'throw' ) {
+ throw new Error(msg);
+ }
+ else if ( typeof type == 'function' ) {
+ type( settings, tn, msg );
}
-
- return aRet;
}
-
-
- /**
- * JSON stringify. If JSON.stringify it provided by the browser, json2.js or any other
- * library, then we use that as it is fast, safe and accurate. If the function isn't
- * available then we need to built it ourselves - the inspiration for this function comes
- * from Craig Buckler ( http://www.sitepoint.com/javascript-json-serialization/ ). It is
- * not perfect and absolutely should not be used as a replacement to json2.js - but it does
- * do what we need, without requiring a dependency for DataTables.
- * @param {object} o JSON object to be converted
- * @returns {string} JSON string
- * @memberof DataTable#oApi
- */
- var _fnJsonString = (window.JSON) ? JSON.stringify : function( o )
- {
- /* Not an object or array */
- var sType = typeof o;
- if (sType !== "object" || o === null)
- {
- // simple data type
- if (sType === "string")
- {
- o = '"'+o+'"';
+ else if ( window.console && console.log ) {
+ console.log( msg );
+ }
+ }
+
+
+ /**
+ * See if a property is defined on one object, if so assign it to the other object
+ * @param {object} ret target object
+ * @param {object} src source object
+ * @param {string} name property
+ * @param {string} [mappedName] name to map too - optional, name used if not given
+ * @memberof DataTable#oApi
+ */
+ function _fnMap( ret, src, name, mappedName )
+ {
+ if ( $.isArray( name ) ) {
+ $.each( name, function (i, val) {
+ if ( $.isArray( val ) ) {
+ _fnMap( ret, src, val[0], val[1] );
}
- return o+"";
- }
-
- /* If object or array, need to recurse over it */
- var
- sProp, mValue,
- json = [],
- bArr = $.isArray(o);
-
- for (sProp in o)
- {
- mValue = o[sProp];
- sType = typeof mValue;
-
- if (sType === "string")
- {
- mValue = '"'+mValue+'"';
+ else {
+ _fnMap( ret, src, val );
}
- else if (sType === "object" && mValue !== null)
- {
- mValue = _fnJsonString(mValue);
+ } );
+
+ return;
+ }
+
+ if ( mappedName === undefined ) {
+ mappedName = name;
+ }
+
+ if ( src[name] !== undefined ) {
+ ret[mappedName] = src[name];
+ }
+ }
+
+
+ /**
+ * Extend objects - very similar to jQuery.extend, but deep copy objects, and
+ * shallow copy arrays. The reason we need to do this, is that we don't want to
+ * deep copy array init values (such as aaSorting) since the dev wouldn't be
+ * able to override them, but we do want to deep copy arrays.
+ * @param {object} out Object to extend
+ * @param {object} extender Object from which the properties will be applied to
+ * out
+ * @param {boolean} breakRefs If true, then arrays will be sliced to take an
+ * independent copy with the exception of the `data` or `aaData` parameters
+ * if they are present. This is so you can pass in a collection to
+ * DataTables and have that used as your data source without breaking the
+ * references
+ * @returns {object} out Reference, just for convenience - out === the return.
+ * @memberof DataTable#oApi
+ * @todo This doesn't take account of arrays inside the deep copied objects.
+ */
+ function _fnExtend( out, extender, breakRefs )
+ {
+ var val;
+
+ for ( var prop in extender ) {
+ if ( extender.hasOwnProperty(prop) ) {
+ val = extender[prop];
+
+ if ( $.isPlainObject( val ) ) {
+ if ( ! $.isPlainObject( out[prop] ) ) {
+ out[prop] = {};
+ }
+ $.extend( true, out[prop], val );
+ }
+ else if ( breakRefs && prop !== 'data' && prop !== 'aaData' && $.isArray(val) ) {
+ out[prop] = val.slice();
+ }
+ else {
+ out[prop] = val;
}
-
- json.push((bArr ? "" : '"'+sProp+'":') + mValue);
}
-
- return (bArr ? "[" : "{") + json + (bArr ? "]" : "}");
- };
-
-
- /**
- * From some browsers (specifically IE6/7) we need special handling to work around browser
- * bugs - this function is used to detect when these workarounds are needed.
- * @param {object} oSettings dataTables settings object
- * @memberof DataTable#oApi
- */
- function _fnBrowserDetect( oSettings )
+ }
+
+ return out;
+ }
+
+
+ /**
+ * Bind an event handers to allow a click or return key to activate the callback.
+ * This is good for accessibility since a return on the keyboard will have the
+ * same effect as a click, if the element has focus.
+ * @param {element} n Element to bind the action to
+ * @param {object} oData Data object to pass to the triggered function
+ * @param {function} fn Callback function for when the event is triggered
+ * @memberof DataTable#oApi
+ */
+ function _fnBindAction( n, oData, fn )
+ {
+ $(n)
+ .bind( 'click.DT', oData, function (e) {
+ n.blur(); // Remove focus outline for mouse users
+ fn(e);
+ } )
+ .bind( 'keypress.DT', oData, function (e){
+ if ( e.which === 13 ) {
+ e.preventDefault();
+ fn(e);
+ }
+ } )
+ .bind( 'selectstart.DT', function () {
+ /* Take the brutal approach to cancelling text selection */
+ return false;
+ } );
+ }
+
+
+ /**
+ * Register a callback function. Easily allows a callback function to be added to
+ * an array store of callback functions that can then all be called together.
+ * @param {object} oSettings dataTables settings object
+ * @param {string} sStore Name of the array storage for the callbacks in oSettings
+ * @param {function} fn Function to be called back
+ * @param {string} sName Identifying name for the callback (i.e. a label)
+ * @memberof DataTable#oApi
+ */
+ function _fnCallbackReg( oSettings, sStore, fn, sName )
+ {
+ if ( fn )
{
- /* IE6/7 will oversize a width 100% element inside a scrolling element, to include the
- * width of the scrollbar, while other browsers ensure the inner element is contained
- * without forcing scrolling
- */
- var n = $(
- '<div style="position:absolute; top:0; left:0; height:1px; width:1px; overflow:hidden">'+
- '<div style="position:absolute; top:1px; left:1px; width:100px; overflow:scroll;">'+
- '<div id="DT_BrowserTest" style="width:100%; height:10px;"></div>'+
- '</div>'+
- '</div>')[0];
-
- document.body.appendChild( n );
- oSettings.oBrowser.bScrollOversize = $('#DT_BrowserTest', n)[0].offsetWidth === 100 ? true : false;
- document.body.removeChild( n );
+ oSettings[sStore].push( {
+ "fn": fn,
+ "sName": sName
+ } );
}
-
+ }
+
+
+ /**
+ * Fire callback functions and trigger events. Note that the loop over the
+ * callback array store is done backwards! Further note that you do not want to
+ * fire off triggers in time sensitive applications (for example cell creation)
+ * as its slow.
+ * @param {object} settings dataTables settings object
+ * @param {string} callbackArr Name of the array storage for the callbacks in
+ * oSettings
+ * @param {string} eventName Name of the jQuery custom event to trigger. If
+ * null no trigger is fired
+ * @param {array} args Array of arguments to pass to the callback function /
+ * trigger
+ * @memberof DataTable#oApi
+ */
+ function _fnCallbackFire( settings, callbackArr, eventName, args )
+ {
+ var ret = [];
+
+ if ( callbackArr ) {
+ ret = $.map( settings[callbackArr].slice().reverse(), function (val, i) {
+ return val.fn.apply( settings.oInstance, args );
+ } );
+ }
+
+ if ( eventName !== null ) {
+ var e = $.Event( eventName+'.dt' );
+
+ $(settings.nTable).trigger( e, args );
+
+ ret.push( e.result );
+ }
+
+ return ret;
+ }
+
+
+ function _fnLengthOverflow ( settings )
+ {
+ var
+ start = settings._iDisplayStart,
+ end = settings.fnDisplayEnd(),
+ len = settings._iDisplayLength;
+
+ /* If we have space to show extra rows (backing up from the end point - then do so */
+ if ( start >= end )
+ {
+ start = end - len;
+ }
+
+ // Keep the start record on the current page
+ start -= (start % len);
+
+ if ( len === -1 || start < 0 )
+ {
+ start = 0;
+ }
+
+ settings._iDisplayStart = start;
+ }
+
+
+ function _fnRenderer( settings, type )
+ {
+ var renderer = settings.renderer;
+ var host = DataTable.ext.renderer[type];
+
+ if ( $.isPlainObject( renderer ) && renderer[type] ) {
+ // Specific renderer for this type. If available use it, otherwise use
+ // the default.
+ return host[renderer[type]] || host._;
+ }
+ else if ( typeof renderer === 'string' ) {
+ // Common renderer - if there is one available for this type use it,
+ // otherwise use the default
+ return host[renderer] || host._;
+ }
+
+ // Use the default
+ return host._;
+ }
+
+
+ /**
+ * Detect the data source being used for the table. Used to simplify the code
+ * a little (ajax) and to make it compress a little smaller.
+ *
+ * @param {object} settings dataTables settings object
+ * @returns {string} Data source
+ * @memberof DataTable#oApi
+ */
+ function _fnDataSource ( settings )
+ {
+ if ( settings.oFeatures.bServerSide ) {
+ return 'ssp';
+ }
+ else if ( settings.ajax || settings.sAjaxSource ) {
+ return 'ajax';
+ }
+ return 'dom';
+ }
+
+ DataTable = function( options )
+ {
/**
* Perform a jQuery selector action on the table's TR elements (from the tbody) and
* return the resulting jQuery object.
@@ -4948,10 +5327,11 @@
* Can be either 'current', whereby the current sorting of the table is used, or
* 'original' whereby the original order the data was read into the table is used.
* @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
- * ("current") or not ("all"). If 'current' is given, then order is assumed to be
+ * ("current") or not ("all"). If 'current' is given, then order is assumed to be
* 'current' and filter is 'applied', regardless of what they might be given as.
* @returns {object} jQuery object, filtered by the given selector.
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
@@ -4968,100 +5348,13 @@
* // Filter to rows with 'Webkit' in them, add a background colour and then
* // remove the filter, thus highlighting the 'Webkit' rows only.
* oTable.fnFilter('Webkit');
- * oTable.$('tr', {"filter": "applied"}).css('backgroundColor', 'blue');
+ * oTable.$('tr', {"search": "applied"}).css('backgroundColor', 'blue');
* oTable.fnFilter('');
* } );
*/
this.$ = function ( sSelector, oOpts )
{
- var i, iLen, a = [], tr;
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
- var aoData = oSettings.aoData;
- var aiDisplay = oSettings.aiDisplay;
- var aiDisplayMaster = oSettings.aiDisplayMaster;
-
- if ( !oOpts )
- {
- oOpts = {};
- }
-
- oOpts = $.extend( {}, {
- "filter": "none", // applied
- "order": "current", // "original"
- "page": "all" // current
- }, oOpts );
-
- // Current page implies that order=current and fitler=applied, since it is fairly
- // senseless otherwise
- if ( oOpts.page == 'current' )
- {
- for ( i=oSettings._iDisplayStart, iLen=oSettings.fnDisplayEnd() ; i<iLen ; i++ )
- {
- tr = aoData[ aiDisplay[i] ].nTr;
- if ( tr )
- {
- a.push( tr );
- }
- }
- }
- else if ( oOpts.order == "current" && oOpts.filter == "none" )
- {
- for ( i=0, iLen=aiDisplayMaster.length ; i<iLen ; i++ )
- {
- tr = aoData[ aiDisplayMaster[i] ].nTr;
- if ( tr )
- {
- a.push( tr );
- }
- }
- }
- else if ( oOpts.order == "current" && oOpts.filter == "applied" )
- {
- for ( i=0, iLen=aiDisplay.length ; i<iLen ; i++ )
- {
- tr = aoData[ aiDisplay[i] ].nTr;
- if ( tr )
- {
- a.push( tr );
- }
- }
- }
- else if ( oOpts.order == "original" && oOpts.filter == "none" )
- {
- for ( i=0, iLen=aoData.length ; i<iLen ; i++ )
- {
- tr = aoData[ i ].nTr ;
- if ( tr )
- {
- a.push( tr );
- }
- }
- }
- else if ( oOpts.order == "original" && oOpts.filter == "applied" )
- {
- for ( i=0, iLen=aoData.length ; i<iLen ; i++ )
- {
- tr = aoData[ i ].nTr;
- if ( $.inArray( i, aiDisplay ) !== -1 && tr )
- {
- a.push( tr );
- }
- }
- }
- else
- {
- _fnLog( oSettings, 1, "Unknown selection options" );
- }
-
- /* We need to filter on the TR elements and also 'find' in their descendants
- * to make the selector act like it would in a full table - so we need
- * to build both results and then combine them together
- */
- var jqA = $(a);
- var jqTRs = jqA.filter( sSelector );
- var jqDescendants = jqA.find( sSelector );
-
- return $( [].concat($.makeArray(jqTRs), $.makeArray(jqDescendants)) );
+ return this.api(true).$( sSelector, oOpts );
};
@@ -5069,7 +5362,7 @@
* Almost identical to $ in operation, but in this case returns the data for the matched
* rows - as such, the jQuery selector used should match TR row nodes or TD/TH cell nodes
* rather than any descendants, so the data can be obtained for the row/cell. If matching
- * rows are found, the data returned is the original data array/object that was used to
+ * rows are found, the data returned is the original data array/object that was used to
* create the row (or a generated array if from a DOM source).
*
* This method is often useful in-combination with $ where both functions are given the
@@ -5082,12 +5375,13 @@
* Can be either 'current', whereby the current sorting of the table is used, or
* 'original' whereby the original order the data was read into the table is used.
* @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
- * ("current") or not ("all"). If 'current' is given, then order is assumed to be
+ * ("current") or not ("all"). If 'current' is given, then order is assumed to be
* 'current' and filter is 'applied', regardless of what they might be given as.
* @returns {array} Data for the matched elements. If any elements, as a result of the
- * selector, were not TR, TD or TH elements in the DataTable, they will have a null
+ * selector, were not TR, TD or TH elements in the DataTable, they will have a null
* entry in the array.
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
@@ -5104,55 +5398,66 @@
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
- * // Filter to 'Webkit' and get all data for
+ * // Filter to 'Webkit' and get all data for
* oTable.fnFilter('Webkit');
- * var data = oTable._('tr', {"filter": "applied"});
- *
+ * var data = oTable._('tr', {"search": "applied"});
+ *
* // Do something with the data
- * alert( data.length+" rows matched the filter" );
+ * alert( data.length+" rows matched the search" );
* } );
*/
this._ = function ( sSelector, oOpts )
{
- var aOut = [];
- var i, iLen, iIndex;
- var aTrs = this.$( sSelector, oOpts );
+ return this.api(true).rows( sSelector, oOpts ).data();
+ };
- for ( i=0, iLen=aTrs.length ; i<iLen ; i++ )
- {
- aOut.push( this.fnGetData(aTrs[i]) );
- }
- return aOut;
+ /**
+ * Create a DataTables Api instance, with the currently selected tables for
+ * the Api's context.
+ * @param {boolean} [traditional=false] Set the API instance's context to be
+ * only the table referred to by the `DataTable.ext.iApiIndex` option, as was
+ * used in the API presented by DataTables 1.9- (i.e. the traditional mode),
+ * or if all tables captured in the jQuery object should be used.
+ * @return {DataTables.Api}
+ */
+ this.api = function ( traditional )
+ {
+ return traditional ?
+ new _Api(
+ _fnSettingsFromNode( this[ _ext.iApiIndex ] )
+ ) :
+ new _Api( this );
};
/**
* Add a single new row or multiple rows of data to the table. Please note
- * that this is suitable for client-side processing only - if you are using
+ * that this is suitable for client-side processing only - if you are using
* server-side processing (i.e. "bServerSide": true), then to add data, you
* must add it to the data source, i.e. the server-side, through an Ajax call.
- * @param {array|object} mData The data to be added to the table. This can be:
+ * @param {array|object} data The data to be added to the table. This can be:
* <ul>
* <li>1D array of data - add a single row with the data provided</li>
* <li>2D array of arrays - add multiple rows in a single call</li>
* <li>object - data object when using <i>mData</i></li>
* <li>array of objects - multiple data objects when using <i>mData</i></li>
* </ul>
- * @param {bool} [bRedraw=true] redraw the table or not
- * @returns {array} An array of integers, representing the list of indexes in
- * <i>aoData</i> ({@link DataTable.models.oSettings}) that have been added to
+ * @param {bool} [redraw=true] redraw the table or not
+ * @returns {array} An array of integers, representing the list of indexes in
+ * <i>aoData</i> ({@link DataTable.models.oSettings}) that have been added to
* the table.
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* // Global var for counter
* var giCount = 2;
- *
+ *
* $(document).ready(function() {
* $('#example').dataTable();
* } );
- *
+ *
* function fnClickAddRow() {
* $('#example').dataTable().fnAddData( [
* giCount+".1",
@@ -5160,63 +5465,35 @@
* giCount+".3",
* giCount+".4" ]
* );
- *
+ *
* giCount++;
* }
*/
- this.fnAddData = function( mData, bRedraw )
+ this.fnAddData = function( data, redraw )
{
- if ( mData.length === 0 )
- {
- return [];
- }
-
- var aiReturn = [];
- var iTest;
-
- /* Find settings from table node */
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
-
+ var api = this.api( true );
+
/* Check if we want to add multiple rows or not */
- if ( typeof mData[0] === "object" && mData[0] !== null )
- {
- for ( var i=0 ; i<mData.length ; i++ )
- {
- iTest = _fnAddData( oSettings, mData[i] );
- if ( iTest == -1 )
- {
- return aiReturn;
- }
- aiReturn.push( iTest );
- }
- }
- else
- {
- iTest = _fnAddData( oSettings, mData );
- if ( iTest == -1 )
- {
- return aiReturn;
- }
- aiReturn.push( iTest );
- }
-
- oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
-
- if ( bRedraw === undefined || bRedraw )
- {
- _fnReDraw( oSettings );
+ var rows = $.isArray(data) && ( $.isArray(data[0]) || $.isPlainObject(data[0]) ) ?
+ api.rows.add( data ) :
+ api.row.add( data );
+
+ if ( redraw === undefined || redraw ) {
+ api.draw();
}
- return aiReturn;
+
+ return rows.flatten().toArray();
};
/**
- * This function will make DataTables recalculate the column sizes, based on the data
- * contained in the table and the sizes applied to the columns (in the DOM, CSS or
- * through the sWidth parameter). This can be useful when the width of the table's
+ * This function will make DataTables recalculate the column sizes, based on the data
+ * contained in the table and the sizes applied to the columns (in the DOM, CSS or
+ * through the sWidth parameter). This can be useful when the width of the table's
* parent element changes (for example a window resize).
* @param {boolean} [bRedraw=true] Redraw the table or not, you will typically want to
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
@@ -5224,7 +5501,7 @@
* "sScrollY": "200px",
* "bPaginate": false
* } );
- *
+ *
* $(window).bind('resize', function () {
* oTable.fnAdjustColumnSizing();
* } );
@@ -5232,17 +5509,16 @@
*/
this.fnAdjustColumnSizing = function ( bRedraw )
{
- var oSettings = _fnSettingsFromNode(this[DataTable.ext.iApiIndex]);
- _fnAdjustColumnSizing( oSettings );
-
- if ( bRedraw === undefined || bRedraw )
- {
- this.fnDraw( false );
+ var api = this.api( true ).columns.adjust();
+ var settings = api.settings()[0];
+ var scroll = settings.oScroll;
+
+ if ( bRedraw === undefined || bRedraw ) {
+ api.draw( false );
}
- else if ( oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "" )
- {
+ else if ( scroll.sX !== "" || scroll.sY !== "" ) {
/* If not redrawing, but scrolling, we want to apply the new column sizes anyway */
- this.oApi._fnScrollDraw(oSettings);
+ _fnScrollDraw( settings );
}
};
@@ -5251,39 +5527,38 @@
* Quickly and simply clear a table
* @param {bool} [bRedraw=true] redraw the table or not
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
- *
+ *
* // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...)
* oTable.fnClearTable();
* } );
*/
this.fnClearTable = function( bRedraw )
{
- /* Find settings from table node */
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
- _fnClearTable( oSettings );
-
- if ( bRedraw === undefined || bRedraw )
- {
- _fnDraw( oSettings );
+ var api = this.api( true ).clear();
+
+ if ( bRedraw === undefined || bRedraw ) {
+ api.draw();
}
};
/**
- * The exact opposite of 'opening' a row, this function will close any rows which
+ * The exact opposite of 'opening' a row, this function will close any rows which
* are currently 'open'.
* @param {node} nTr the table row to 'close'
* @returns {int} 0 on success, or 1 if failed (can't find the row)
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable;
- *
+ *
* // 'open' an information row when a row is clicked on
* $('#example tbody tr').click( function () {
* if ( oTable.fnIsOpen(this) ) {
@@ -5292,110 +5567,61 @@
* oTable.fnOpen( this, "Temporary row opened", "info_row" );
* }
* } );
- *
+ *
* oTable = $('#example').dataTable();
* } );
*/
this.fnClose = function( nTr )
{
- /* Find settings from table node */
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
-
- for ( var i=0 ; i<oSettings.aoOpenRows.length ; i++ )
- {
- if ( oSettings.aoOpenRows[i].nParent == nTr )
- {
- var nTrParent = oSettings.aoOpenRows[i].nTr.parentNode;
- if ( nTrParent )
- {
- /* Remove it if it is currently on display */
- nTrParent.removeChild( oSettings.aoOpenRows[i].nTr );
- }
- oSettings.aoOpenRows.splice( i, 1 );
- return 0;
- }
- }
- return 1;
+ this.api( true ).row( nTr ).child.hide();
};
/**
* Remove a row for the table
- * @param {mixed} mTarget The index of the row from aoData to be deleted, or
+ * @param {mixed} target The index of the row from aoData to be deleted, or
* the TR element you want to delete
- * @param {function|null} [fnCallBack] Callback function
- * @param {bool} [bRedraw=true] Redraw the table or not
+ * @param {function|null} [callBack] Callback function
+ * @param {bool} [redraw=true] Redraw the table or not
* @returns {array} The row that was deleted
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
- *
+ *
* // Immediately remove the first row
* oTable.fnDeleteRow( 0 );
* } );
*/
- this.fnDeleteRow = function( mTarget, fnCallBack, bRedraw )
+ this.fnDeleteRow = function( target, callback, redraw )
{
- /* Find settings from table node */
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
- var i, iLen, iAODataIndex;
-
- iAODataIndex = (typeof mTarget === 'object') ?
- _fnNodeToDataIndex(oSettings, mTarget) : mTarget;
-
- /* Return the data array from this row */
- var oData = oSettings.aoData.splice( iAODataIndex, 1 );
+ var api = this.api( true );
+ var rows = api.rows( target );
+ var settings = rows.settings()[0];
+ var data = settings.aoData[ rows[0][0] ];
- /* Update the _DT_RowIndex parameter */
- for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ )
- {
- if ( oSettings.aoData[i].nTr !== null )
- {
- oSettings.aoData[i].nTr._DT_RowIndex = i;
- }
- }
-
- /* Remove the target row from the search array */
- var iDisplayIndex = $.inArray( iAODataIndex, oSettings.aiDisplay );
- oSettings.asDataSearch.splice( iDisplayIndex, 1 );
-
- /* Delete from the display arrays */
- _fnDeleteIndex( oSettings.aiDisplayMaster, iAODataIndex );
- _fnDeleteIndex( oSettings.aiDisplay, iAODataIndex );
-
- /* If there is a user callback function - call it */
- if ( typeof fnCallBack === "function" )
- {
- fnCallBack.call( this, oSettings, oData );
- }
-
- /* Check for an 'overflow' they case for displaying the table */
- if ( oSettings._iDisplayStart >= oSettings.fnRecordsDisplay() )
- {
- oSettings._iDisplayStart -= oSettings._iDisplayLength;
- if ( oSettings._iDisplayStart < 0 )
- {
- oSettings._iDisplayStart = 0;
- }
+ rows.remove();
+
+ if ( callback ) {
+ callback.call( this, settings, data );
}
-
- if ( bRedraw === undefined || bRedraw )
- {
- _fnCalculateEnd( oSettings );
- _fnDraw( oSettings );
+
+ if ( redraw === undefined || redraw ) {
+ api.draw();
}
-
- return oData;
+
+ return data;
};
/**
- * Restore the table to it's original state in the DOM by removing all of DataTables
+ * Restore the table to it's original state in the DOM by removing all of DataTables
* enhancements, alterations to the DOM structure of the table and event listeners.
- * @param {boolean} [bRemove=false] Completely remove the table from the DOM
+ * @param {boolean} [remove=false] Completely remove the table from the DOM
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
@@ -5404,159 +5630,31 @@
* oTable.fnDestroy();
* } );
*/
- this.fnDestroy = function ( bRemove )
+ this.fnDestroy = function ( remove )
{
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
- var nOrig = oSettings.nTableWrapper.parentNode;
- var nBody = oSettings.nTBody;
- var i, iLen;
-
- bRemove = (bRemove===undefined) ? false : bRemove;
-
- /* Flag to note that the table is currently being destroyed - no action should be taken */
- oSettings.bDestroying = true;
-
- /* Fire off the destroy callbacks for plug-ins etc */
- _fnCallbackFire( oSettings, "aoDestroyCallback", "destroy", [oSettings] );
-
- /* If the table is not being removed, restore the hidden columns */
- if ( !bRemove )
- {
- for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
- {
- if ( oSettings.aoColumns[i].bVisible === false )
- {
- this.fnSetColumnVis( i, true );
- }
- }
- }
-
- /* Blitz all DT events */
- $(oSettings.nTableWrapper).find('*').andSelf().unbind('.DT');
-
- /* If there is an 'empty' indicator row, remove it */
- $('tbody>tr>td.'+oSettings.oClasses.sRowEmpty, oSettings.nTable).parent().remove();
-
- /* When scrolling we had to break the table up - restore it */
- if ( oSettings.nTable != oSettings.nTHead.parentNode )
- {
- $(oSettings.nTable).children('thead').remove();
- oSettings.nTable.appendChild( oSettings.nTHead );
- }
-
- if ( oSettings.nTFoot && oSettings.nTable != oSettings.nTFoot.parentNode )
- {
- $(oSettings.nTable).children('tfoot').remove();
- oSettings.nTable.appendChild( oSettings.nTFoot );
- }
-
- /* Remove the DataTables generated nodes, events and classes */
- oSettings.nTable.parentNode.removeChild( oSettings.nTable );
- $(oSettings.nTableWrapper).remove();
-
- oSettings.aaSorting = [];
- oSettings.aaSortingFixed = [];
- _fnSortingClasses( oSettings );
-
- $(_fnGetTrNodes( oSettings )).removeClass( oSettings.asStripeClasses.join(' ') );
-
- $('th, td', oSettings.nTHead).removeClass( [
- oSettings.oClasses.sSortable,
- oSettings.oClasses.sSortableAsc,
- oSettings.oClasses.sSortableDesc,
- oSettings.oClasses.sSortableNone ].join(' ')
- );
- if ( oSettings.bJUI )
- {
- $('th span.'+oSettings.oClasses.sSortIcon
- + ', td span.'+oSettings.oClasses.sSortIcon, oSettings.nTHead).remove();
-
- $('th, td', oSettings.nTHead).each( function () {
- var jqWrapper = $('div.'+oSettings.oClasses.sSortJUIWrapper, this);
- var kids = jqWrapper.contents();
- $(this).append( kids );
- jqWrapper.remove();
- } );
- }
-
- /* Add the TR elements back into the table in their original order */
- if ( !bRemove && oSettings.nTableReinsertBefore )
- {
- nOrig.insertBefore( oSettings.nTable, oSettings.nTableReinsertBefore );
- }
- else if ( !bRemove )
- {
- nOrig.appendChild( oSettings.nTable );
- }
-
- for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ )
- {
- if ( oSettings.aoData[i].nTr !== null )
- {
- nBody.appendChild( oSettings.aoData[i].nTr );
- }
- }
-
- /* Restore the width of the original table */
- if ( oSettings.oFeatures.bAutoWidth === true )
- {
- oSettings.nTable.style.width = _fnStringToCss(oSettings.sDestroyWidth);
- }
-
- /* If the were originally stripe classes - then we add them back here. Note
- * this is not fool proof (for example if not all rows had stripe classes - but
- * it's a good effort without getting carried away
- */
- iLen = oSettings.asDestroyStripes.length;
- if (iLen)
- {
- var anRows = $(nBody).children('tr');
- for ( i=0 ; i<iLen ; i++ )
- {
- anRows.filter(':nth-child(' + iLen + 'n + ' + i + ')').addClass( oSettings.asDestroyStripes[i] );
- }
- }
-
- /* Remove the settings object from the settings array */
- for ( i=0, iLen=DataTable.settings.length ; i<iLen ; i++ )
- {
- if ( DataTable.settings[i] == oSettings )
- {
- DataTable.settings.splice( i, 1 );
- }
- }
-
- /* End it all */
- oSettings = null;
- oInit = null;
+ this.api( true ).destroy( remove );
};
/**
* Redraw the table
- * @param {bool} [bComplete=true] Re-filter and resort (if enabled) the table before the draw.
+ * @param {bool} [complete=true] Re-filter and resort (if enabled) the table before the draw.
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
- *
+ *
* // Re-draw the table - you wouldn't want to do it here, but it's an example :-)
* oTable.fnDraw();
* } );
*/
- this.fnDraw = function( bComplete )
+ this.fnDraw = function( complete )
{
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
- if ( bComplete === false )
- {
- _fnCalculateEnd( oSettings );
- _fnDraw( oSettings );
- }
- else
- {
- _fnReDraw( oSettings );
- }
+ // Note that this isn't an exact match to the old call to _fnDraw - it takes
+ // into account the new data, but can hold position.
+ this.api( true ).draw( complete );
};
@@ -5569,100 +5667,45 @@
* @param {bool} [bShowGlobal=true] Show the input global filter in it's input box(es)
* @param {bool} [bCaseInsensitive=true] Do case-insensitive matching (true) or not (false)
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
- *
+ *
* // Sometime later - filter...
* oTable.fnFilter( 'test string' );
* } );
*/
this.fnFilter = function( sInput, iColumn, bRegex, bSmart, bShowGlobal, bCaseInsensitive )
{
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
-
- if ( !oSettings.oFeatures.bFilter )
- {
- return;
- }
-
- if ( bRegex === undefined || bRegex === null )
- {
- bRegex = false;
- }
-
- if ( bSmart === undefined || bSmart === null )
- {
- bSmart = true;
- }
-
- if ( bShowGlobal === undefined || bShowGlobal === null )
- {
- bShowGlobal = true;
- }
-
- if ( bCaseInsensitive === undefined || bCaseInsensitive === null )
- {
- bCaseInsensitive = true;
- }
-
- if ( iColumn === undefined || iColumn === null )
- {
- /* Global filter */
- _fnFilterComplete( oSettings, {
- "sSearch":sInput+"",
- "bRegex": bRegex,
- "bSmart": bSmart,
- "bCaseInsensitive": bCaseInsensitive
- }, 1 );
-
- if ( bShowGlobal && oSettings.aanFeatures.f )
- {
- var n = oSettings.aanFeatures.f;
- for ( var i=0, iLen=n.length ; i<iLen ; i++ )
- {
- // IE9 throws an 'unknown error' if document.activeElement is used
- // inside an iframe or frame...
- try {
- if ( n[i]._DT_Input != document.activeElement )
- {
- $(n[i]._DT_Input).val( sInput );
- }
- }
- catch ( e ) {
- $(n[i]._DT_Input).val( sInput );
- }
- }
- }
+ var api = this.api( true );
+
+ if ( iColumn === null || iColumn === undefined ) {
+ api.search( sInput, bRegex, bSmart, bCaseInsensitive );
}
- else
- {
- /* Single column filter */
- $.extend( oSettings.aoPreSearchCols[ iColumn ], {
- "sSearch": sInput+"",
- "bRegex": bRegex,
- "bSmart": bSmart,
- "bCaseInsensitive": bCaseInsensitive
- } );
- _fnFilterComplete( oSettings, oSettings.oPreviousSearch, 1 );
+ else {
+ api.column( iColumn ).search( sInput, bRegex, bSmart, bCaseInsensitive );
}
+
+ api.draw();
};
/**
- * Get the data for the whole table, an individual row or an individual cell based on the
+ * Get the data for the whole table, an individual row or an individual cell based on the
* provided parameters.
- * @param {int|node} [mRow] A TR row node, TD/TH cell node or an integer. If given as
+ * @param {int|node} [src] A TR row node, TD/TH cell node or an integer. If given as
* a TR node then the data source for the whole row will be returned. If given as a
* TD/TH cell node then iCol will be automatically calculated and the data for the
* cell returned. If given as an integer, then this is treated as the aoData internal
* data index for the row (see fnGetPosition) and the data for that row used.
- * @param {int} [iCol] Optional column index that you want the data of.
+ * @param {int} [col] Optional column index that you want the data of.
* @returns {array|object|string} If mRow is undefined, then the data for all rows is
* returned. If mRow is defined, just data for that row, and is iCol is
* defined, only data for the designated cell is returned.
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* // Row data
@@ -5686,108 +5729,94 @@
* } );
* } );
*/
- this.fnGetData = function( mRow, iCol )
+ this.fnGetData = function( src, col )
{
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
-
- if ( mRow !== undefined )
- {
- var iRow = mRow;
- if ( typeof mRow === 'object' )
- {
- var sNode = mRow.nodeName.toLowerCase();
- if (sNode === "tr" )
- {
- iRow = _fnNodeToDataIndex(oSettings, mRow);
- }
- else if ( sNode === "td" )
- {
- iRow = _fnNodeToDataIndex(oSettings, mRow.parentNode);
- iCol = _fnNodeToColumnIndex( oSettings, iRow, mRow );
- }
- }
+ var api = this.api( true );
- if ( iCol !== undefined )
- {
- return _fnGetCellData( oSettings, iRow, iCol, '' );
- }
- return (oSettings.aoData[iRow]!==undefined) ?
- oSettings.aoData[iRow]._aData : null;
+ if ( src !== undefined ) {
+ var type = src.nodeName ? src.nodeName.toLowerCase() : '';
+
+ return col !== undefined || type == 'td' || type == 'th' ?
+ api.cell( src, col ).data() :
+ api.row( src ).data() || null;
}
- return _fnGetDataMaster( oSettings );
+
+ return api.data().toArray();
};
/**
- * Get an array of the TR nodes that are used in the table's body. Note that you will
- * typically want to use the '$' API method in preference to this as it is more
+ * Get an array of the TR nodes that are used in the table's body. Note that you will
+ * typically want to use the '$' API method in preference to this as it is more
* flexible.
* @param {int} [iRow] Optional row index for the TR element you want
* @returns {array|node} If iRow is undefined, returns an array of all TR elements
* in the table's body, or iRow is defined, just the TR element requested.
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
- *
+ *
* // Get the nodes from the table
* var nNodes = oTable.fnGetNodes( );
* } );
*/
this.fnGetNodes = function( iRow )
{
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
-
- if ( iRow !== undefined ) {
- return (oSettings.aoData[iRow]!==undefined) ?
- oSettings.aoData[iRow].nTr : null;
- }
- return _fnGetTrNodes( oSettings );
+ var api = this.api( true );
+
+ return iRow !== undefined ?
+ api.row( iRow ).node() :
+ api.rows().nodes().flatten().toArray();
};
/**
* Get the array indexes of a particular cell from it's DOM element
* and column index including hidden columns
- * @param {node} nNode this can either be a TR, TD or TH in the table's body
+ * @param {node} node this can either be a TR, TD or TH in the table's body
* @returns {int} If nNode is given as a TR, then a single index is returned, or
- * if given as a cell, an array of [row index, column index (visible),
+ * if given as a cell, an array of [row index, column index (visible),
* column index (all)] is given.
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* $('#example tbody td').click( function () {
* // Get the position of the current data from the node
* var aPos = oTable.fnGetPosition( this );
- *
+ *
* // Get the data array for this row
* var aData = oTable.fnGetData( aPos[0] );
- *
+ *
* // Update the data array and return the value
* aData[ aPos[1] ] = 'clicked';
* this.innerHTML = 'clicked';
* } );
- *
+ *
* // Init DataTables
* oTable = $('#example').dataTable();
* } );
*/
- this.fnGetPosition = function( nNode )
+ this.fnGetPosition = function( node )
{
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
- var sNodeName = nNode.nodeName.toUpperCase();
-
- if ( sNodeName == "TR" )
- {
- return _fnNodeToDataIndex(oSettings, nNode);
+ var api = this.api( true );
+ var nodeName = node.nodeName.toUpperCase();
+
+ if ( nodeName == 'TR' ) {
+ return api.row( node ).index();
}
- else if ( sNodeName == "TD" || sNodeName == "TH" )
- {
- var iDataIndex = _fnNodeToDataIndex( oSettings, nNode.parentNode );
- var iColumnIndex = _fnNodeToColumnIndex( oSettings, iDataIndex, nNode );
- return [ iDataIndex, _fnColumnIndexToVisible(oSettings, iColumnIndex ), iColumnIndex ];
+ else if ( nodeName == 'TD' || nodeName == 'TH' ) {
+ var cell = api.cell( node ).index();
+
+ return [
+ cell.row,
+ cell.columnVisible,
+ cell.column
+ ];
}
return null;
};
@@ -5798,11 +5827,12 @@
* @param {node} nTr the table row to check
* @returns {boolean} true if the row is currently open, false otherwise
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable;
- *
+ *
* // 'open' an information row when a row is clicked on
* $('#example tbody tr').click( function () {
* if ( oTable.fnIsOpen(this) ) {
@@ -5811,30 +5841,20 @@
* oTable.fnOpen( this, "Temporary row opened", "info_row" );
* }
* } );
- *
+ *
* oTable = $('#example').dataTable();
* } );
*/
this.fnIsOpen = function( nTr )
{
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
- var aoOpenRows = oSettings.aoOpenRows;
-
- for ( var i=0 ; i<oSettings.aoOpenRows.length ; i++ )
- {
- if ( oSettings.aoOpenRows[i].nParent == nTr )
- {
- return true;
- }
- }
- return false;
+ return this.api( true ).row( nTr ).child.isShown();
};
/**
- * This function will place a new row directly after a row which is currently
- * on display on the page, with the HTML contents that is passed into the
- * function. This can be used, for example, to ask for confirmation that a
+ * This function will place a new row directly after a row which is currently
+ * on display on the page, with the HTML contents that is passed into the
+ * function. This can be used, for example, to ask for confirmation that a
* particular record should be deleted.
* @param {node} nTr The table row to 'open'
* @param {string|node|jQuery} mHtml The HTML to put into the row
@@ -5843,11 +5863,12 @@
* first parameter, is not found in the table, this method will silently
* return.
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable;
- *
+ *
* // 'open' an information row when a row is clicked on
* $('#example tbody tr').click( function () {
* if ( oTable.fnIsOpen(this) ) {
@@ -5856,64 +5877,29 @@
* oTable.fnOpen( this, "Temporary row opened", "info_row" );
* }
* } );
- *
+ *
* oTable = $('#example').dataTable();
* } );
*/
this.fnOpen = function( nTr, mHtml, sClass )
{
- /* Find settings from table node */
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
-
- /* Check that the row given is in the table */
- var nTableRows = _fnGetTrNodes( oSettings );
- if ( $.inArray(nTr, nTableRows) === -1 )
- {
- return;
- }
-
- /* the old open one if there is one */
- this.fnClose( nTr );
-
- var nNewRow = document.createElement("tr");
- var nNewCell = document.createElement("td");
- nNewRow.appendChild( nNewCell );
- nNewCell.className = sClass;
- nNewCell.colSpan = _fnVisbleColumns( oSettings );
-
- if (typeof mHtml === "string")
- {
- nNewCell.innerHTML = mHtml;
- }
- else
- {
- $(nNewCell).html( mHtml );
- }
-
- /* If the nTr isn't on the page at the moment - then we don't insert at the moment */
- var nTrs = $('tr', oSettings.nTBody);
- if ( $.inArray(nTr, nTrs) != -1 )
- {
- $(nNewRow).insertAfter(nTr);
- }
-
- oSettings.aoOpenRows.push( {
- "nTr": nNewRow,
- "nParent": nTr
- } );
-
- return nNewRow;
+ return this.api( true )
+ .row( nTr )
+ .child( mHtml, sClass )
+ .show()
+ .child()[0];
};
/**
- * Change the pagination - provides the internal logic for pagination in a simple API
- * function. With this function you can have a DataTables table go to the next,
+ * Change the pagination - provides the internal logic for pagination in a simple API
+ * function. With this function you can have a DataTables table go to the next,
* previous, first or last pages.
* @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last"
* or page number to jump to (integer), note that page 0 is the first page.
* @param {bool} [bRedraw=true] Redraw the table or not
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
@@ -5923,13 +5909,10 @@
*/
this.fnPageChange = function ( mAction, bRedraw )
{
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
- _fnPageChange( oSettings, mAction );
- _fnCalculateEnd( oSettings );
-
- if ( bRedraw === undefined || bRedraw )
- {
- _fnDraw( oSettings );
+ var api = this.api( true ).page( mAction );
+
+ if ( bRedraw === undefined || bRedraw ) {
+ api.draw(false);
}
};
@@ -5940,159 +5923,66 @@
* @param {bool} bShow Show (true) or hide (false) the column
* @param {bool} [bRedraw=true] Redraw the table or not
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
- *
+ *
* // Hide the second column after initialisation
* oTable.fnSetColumnVis( 1, false );
* } );
*/
this.fnSetColumnVis = function ( iCol, bShow, bRedraw )
{
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
- var i, iLen;
- var aoColumns = oSettings.aoColumns;
- var aoData = oSettings.aoData;
- var nTd, bAppend, iBefore;
-
- /* No point in doing anything if we are requesting what is already true */
- if ( aoColumns[iCol].bVisible == bShow )
- {
- return;
- }
-
- /* Show the column */
- if ( bShow )
- {
- var iInsert = 0;
- for ( i=0 ; i<iCol ; i++ )
- {
- if ( aoColumns[i].bVisible )
- {
- iInsert++;
- }
- }
-
- /* Need to decide if we should use appendChild or insertBefore */
- bAppend = (iInsert >= _fnVisbleColumns( oSettings ));
-
- /* Which coloumn should we be inserting before? */
- if ( !bAppend )
- {
- for ( i=iCol ; i<aoColumns.length ; i++ )
- {
- if ( aoColumns[i].bVisible )
- {
- iBefore = i;
- break;
- }
- }
- }
+ var api = this.api( true ).column( iCol ).visible( bShow );
- for ( i=0, iLen=aoData.length ; i<iLen ; i++ )
- {
- if ( aoData[i].nTr !== null )
- {
- if ( bAppend )
- {
- aoData[i].nTr.appendChild(
- aoData[i]._anHidden[iCol]
- );
- }
- else
- {
- aoData[i].nTr.insertBefore(
- aoData[i]._anHidden[iCol],
- _fnGetTdNodes( oSettings, i )[iBefore] );
- }
- }
- }
+ if ( bRedraw === undefined || bRedraw ) {
+ api.columns.adjust().draw();
}
- else
- {
- /* Remove a column from display */
- for ( i=0, iLen=aoData.length ; i<iLen ; i++ )
- {
- if ( aoData[i].nTr !== null )
- {
- nTd = _fnGetTdNodes( oSettings, i )[iCol];
- aoData[i]._anHidden[iCol] = nTd;
- nTd.parentNode.removeChild( nTd );
- }
- }
- }
-
- /* Clear to set the visible flag */
- aoColumns[iCol].bVisible = bShow;
-
- /* Redraw the header and footer based on the new column visibility */
- _fnDrawHead( oSettings, oSettings.aoHeader );
- if ( oSettings.nTFoot )
- {
- _fnDrawHead( oSettings, oSettings.aoFooter );
- }
-
- /* If there are any 'open' rows, then we need to alter the colspan for this col change */
- for ( i=0, iLen=oSettings.aoOpenRows.length ; i<iLen ; i++ )
- {
- oSettings.aoOpenRows[i].nTr.colSpan = _fnVisbleColumns( oSettings );
- }
-
- /* Do a redraw incase anything depending on the table columns needs it
- * (built-in: scrolling)
- */
- if ( bRedraw === undefined || bRedraw )
- {
- _fnAdjustColumnSizing( oSettings );
- _fnDraw( oSettings );
- }
-
- _fnSaveState( oSettings );
};
/**
* Get the settings for a particular table for external manipulation
- * @returns {object} DataTables settings object. See
+ * @returns {object} DataTables settings object. See
* {@link DataTable.models.oSettings}
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* var oSettings = oTable.fnSettings();
- *
+ *
* // Show an example parameter from the settings
* alert( oSettings._iDisplayStart );
* } );
*/
this.fnSettings = function()
{
- return _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
+ return _fnSettingsFromNode( this[_ext.iApiIndex] );
};
/**
* Sort the table by a particular column
- * @param {int} iCol the data index to sort on. Note that this will not match the
+ * @param {int} iCol the data index to sort on. Note that this will not match the
* 'display index' if you have hidden data entries
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
- *
+ *
* // Sort immediately with columns 0 and 1
* oTable.fnSort( [ [0,'asc'], [1,'asc'] ] );
* } );
*/
this.fnSort = function( aaSort )
{
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
- oSettings.aaSorting = aaSort;
- _fnSort( oSettings );
+ this.api( true ).order( aaSort ).draw();
};
@@ -6102,19 +5992,19 @@
* @param {int} iColumn the column that a click on this node will sort on
* @param {function} [fnCallback] callback function when sort is run
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
- *
+ *
* // Sort on column 1, when 'sorter' is clicked on
* oTable.fnSortListener( document.getElementById('sorter'), 1 );
* } );
*/
this.fnSortListener = function( nNode, iColumn, fnCallback )
{
- _fnSortAttachListener( _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ), nNode, iColumn,
- fnCallback );
+ this.api( true ).order.listener( nNode, iColumn, fnCallback );
};
@@ -6125,89 +6015,38 @@
* self-referencing in order to make the multi column updates easier.
* @param {object|array|string} mData Data to update the cell/row with
* @param {node|int} mRow TR element you want to update or the aoData index
- * @param {int} [iColumn] The column to update (not used of mData is an array or object)
+ * @param {int} [iColumn] The column to update, give as null or undefined to
+ * update a whole row.
* @param {bool} [bRedraw=true] Redraw the table or not
* @param {bool} [bAction=true] Perform pre-draw actions or not
* @returns {int} 0 on success, 1 on error
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell
- * oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], 1, 0 ); // Row
+ * oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], $('tbody tr')[0] ); // Row
* } );
*/
this.fnUpdate = function( mData, mRow, iColumn, bRedraw, bAction )
{
- var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
- var i, iLen, sDisplay;
- var iRow = (typeof mRow === 'object') ?
- _fnNodeToDataIndex(oSettings, mRow) : mRow;
-
- if ( $.isArray(mData) && iColumn === undefined )
- {
- /* Array update - update the whole row */
- oSettings.aoData[iRow]._aData = mData.slice();
-
- /* Flag to the function that we are recursing */
- for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
- {
- this.fnUpdate( _fnGetCellData( oSettings, iRow, i ), iRow, i, false, false );
- }
- }
- else if ( $.isPlainObject(mData) && iColumn === undefined )
- {
- /* Object update - update the whole row - assume the developer gets the object right */
- oSettings.aoData[iRow]._aData = $.extend( true, {}, mData );
+ var api = this.api( true );
- for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
- {
- this.fnUpdate( _fnGetCellData( oSettings, iRow, i ), iRow, i, false, false );
- }
+ if ( iColumn === undefined || iColumn === null ) {
+ api.row( mRow ).data( mData );
}
- else
- {
- /* Individual cell update */
- _fnSetCellData( oSettings, iRow, iColumn, mData );
- sDisplay = _fnGetCellData( oSettings, iRow, iColumn, 'display' );
-
- var oCol = oSettings.aoColumns[iColumn];
- if ( oCol.fnRender !== null )
- {
- sDisplay = _fnRender( oSettings, iRow, iColumn );
- if ( oCol.bUseRendered )
- {
- _fnSetCellData( oSettings, iRow, iColumn, sDisplay );
- }
- }
-
- if ( oSettings.aoData[iRow].nTr !== null )
- {
- /* Do the actual HTML update */
- _fnGetTdNodes( oSettings, iRow )[iColumn].innerHTML = sDisplay;
- }
+ else {
+ api.cell( mRow, iColumn ).data( mData );
}
-
- /* Modify the search index for this row (strictly this is likely not needed, since fnReDraw
- * will rebuild the search array - however, the redraw might be disabled by the user)
- */
- var iDisplayIndex = $.inArray( iRow, oSettings.aiDisplay );
- oSettings.asDataSearch[iDisplayIndex] = _fnBuildSearchRow(
- oSettings,
- _fnGetRowData( oSettings, iRow, 'filter', _fnGetColumns( oSettings, 'bSearchable' ) )
- );
-
- /* Perform pre-draw actions */
- if ( bAction === undefined || bAction )
- {
- _fnAdjustColumnSizing( oSettings );
+
+ if ( bAction === undefined || bAction ) {
+ api.columns.adjust();
}
-
- /* Redraw the table */
- if ( bRedraw === undefined || bRedraw )
- {
- _fnReDraw( oSettings );
+
+ if ( bRedraw === undefined || bRedraw ) {
+ api.draw();
}
return 0;
};
@@ -6222,6 +6061,7 @@
* version, or false if this version of DataTales is not suitable
* @method
* @dtopt API
+ * @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
@@ -6229,187 +6069,98 @@
* alert( oTable.fnVersionCheck( '1.9.0' ) );
* } );
*/
- this.fnVersionCheck = DataTable.ext.fnVersionCheck;
-
+ this.fnVersionCheck = _ext.fnVersionCheck;
- /*
- * This is really a good bit rubbish this method of exposing the internal methods
- * publicly... - To be fixed in 2.0 using methods on the prototype
- */
-
-
- /**
- * Create a wrapper function for exporting an internal functions to an external API.
- * @param {string} sFunc API function name
- * @returns {function} wrapped function
- * @memberof DataTable#oApi
- */
- function _fnExternApiFunc (sFunc)
- {
- return function() {
- var aArgs = [_fnSettingsFromNode(this[DataTable.ext.iApiIndex])].concat(
- Array.prototype.slice.call(arguments) );
- return DataTable.ext.oApi[sFunc].apply( this, aArgs );
- };
+
+ var _that = this;
+ var emptyInit = options === undefined;
+ var len = this.length;
+
+ if ( emptyInit ) {
+ options = {};
}
-
-
- /**
- * Reference to internal functions for use by plug-in developers. Note that these
- * methods are references to internal functions and are considered to be private.
- * If you use these methods, be aware that they are liable to change between versions
- * (check the upgrade notes).
- * @namespace
- */
- this.oApi = {
- "_fnExternApiFunc": _fnExternApiFunc,
- "_fnInitialise": _fnInitialise,
- "_fnInitComplete": _fnInitComplete,
- "_fnLanguageCompat": _fnLanguageCompat,
- "_fnAddColumn": _fnAddColumn,
- "_fnColumnOptions": _fnColumnOptions,
- "_fnAddData": _fnAddData,
- "_fnCreateTr": _fnCreateTr,
- "_fnGatherData": _fnGatherData,
- "_fnBuildHead": _fnBuildHead,
- "_fnDrawHead": _fnDrawHead,
- "_fnDraw": _fnDraw,
- "_fnReDraw": _fnReDraw,
- "_fnAjaxUpdate": _fnAjaxUpdate,
- "_fnAjaxParameters": _fnAjaxParameters,
- "_fnAjaxUpdateDraw": _fnAjaxUpdateDraw,
- "_fnServerParams": _fnServerParams,
- "_fnAddOptionsHtml": _fnAddOptionsHtml,
- "_fnFeatureHtmlTable": _fnFeatureHtmlTable,
- "_fnScrollDraw": _fnScrollDraw,
- "_fnAdjustColumnSizing": _fnAdjustColumnSizing,
- "_fnFeatureHtmlFilter": _fnFeatureHtmlFilter,
- "_fnFilterComplete": _fnFilterComplete,
- "_fnFilterCustom": _fnFilterCustom,
- "_fnFilterColumn": _fnFilterColumn,
- "_fnFilter": _fnFilter,
- "_fnBuildSearchArray": _fnBuildSearchArray,
- "_fnBuildSearchRow": _fnBuildSearchRow,
- "_fnFilterCreateSearch": _fnFilterCreateSearch,
- "_fnDataToSearch": _fnDataToSearch,
- "_fnSort": _fnSort,
- "_fnSortAttachListener": _fnSortAttachListener,
- "_fnSortingClasses": _fnSortingClasses,
- "_fnFeatureHtmlPaginate": _fnFeatureHtmlPaginate,
- "_fnPageChange": _fnPageChange,
- "_fnFeatureHtmlInfo": _fnFeatureHtmlInfo,
- "_fnUpdateInfo": _fnUpdateInfo,
- "_fnFeatureHtmlLength": _fnFeatureHtmlLength,
- "_fnFeatureHtmlProcessing": _fnFeatureHtmlProcessing,
- "_fnProcessingDisplay": _fnProcessingDisplay,
- "_fnVisibleToColumnIndex": _fnVisibleToColumnIndex,
- "_fnColumnIndexToVisible": _fnColumnIndexToVisible,
- "_fnNodeToDataIndex": _fnNodeToDataIndex,
- "_fnVisbleColumns": _fnVisbleColumns,
- "_fnCalculateEnd": _fnCalculateEnd,
- "_fnConvertToWidth": _fnConvertToWidth,
- "_fnCalculateColumnWidths": _fnCalculateColumnWidths,
- "_fnScrollingWidthAdjust": _fnScrollingWidthAdjust,
- "_fnGetWidestNode": _fnGetWidestNode,
- "_fnGetMaxLenString": _fnGetMaxLenString,
- "_fnStringToCss": _fnStringToCss,
- "_fnDetectType": _fnDetectType,
- "_fnSettingsFromNode": _fnSettingsFromNode,
- "_fnGetDataMaster": _fnGetDataMaster,
- "_fnGetTrNodes": _fnGetTrNodes,
- "_fnGetTdNodes": _fnGetTdNodes,
- "_fnEscapeRegex": _fnEscapeRegex,
- "_fnDeleteIndex": _fnDeleteIndex,
- "_fnReOrderIndex": _fnReOrderIndex,
- "_fnColumnOrdering": _fnColumnOrdering,
- "_fnLog": _fnLog,
- "_fnClearTable": _fnClearTable,
- "_fnSaveState": _fnSaveState,
- "_fnLoadState": _fnLoadState,
- "_fnCreateCookie": _fnCreateCookie,
- "_fnReadCookie": _fnReadCookie,
- "_fnDetectHeader": _fnDetectHeader,
- "_fnGetUniqueThs": _fnGetUniqueThs,
- "_fnScrollBarWidth": _fnScrollBarWidth,
- "_fnApplyToChildren": _fnApplyToChildren,
- "_fnMap": _fnMap,
- "_fnGetRowData": _fnGetRowData,
- "_fnGetCellData": _fnGetCellData,
- "_fnSetCellData": _fnSetCellData,
- "_fnGetObjectDataFn": _fnGetObjectDataFn,
- "_fnSetObjectDataFn": _fnSetObjectDataFn,
- "_fnApplyColumnDefs": _fnApplyColumnDefs,
- "_fnBindAction": _fnBindAction,
- "_fnExtend": _fnExtend,
- "_fnCallbackReg": _fnCallbackReg,
- "_fnCallbackFire": _fnCallbackFire,
- "_fnJsonString": _fnJsonString,
- "_fnRender": _fnRender,
- "_fnNodeToColumnIndex": _fnNodeToColumnIndex,
- "_fnInfoMacros": _fnInfoMacros,
- "_fnBrowserDetect": _fnBrowserDetect,
- "_fnGetColumns": _fnGetColumns
- };
-
- $.extend( DataTable.ext.oApi, this.oApi );
-
- for ( var sFunc in DataTable.ext.oApi )
- {
- if ( sFunc )
- {
- this[sFunc] = _fnExternApiFunc(sFunc);
+
+ this.oApi = this.internal = _ext.internal;
+
+ // Extend with old style plug-in API methods
+ for ( var fn in DataTable.ext.internal ) {
+ if ( fn ) {
+ this[fn] = _fnExternApiFunc(fn);
}
}
-
-
- var _that = this;
+
this.each(function() {
+ // For each initialisation we want to give it a clean initialisation
+ // object that can be bashed around
+ var o = {};
+ var oInit = len > 1 ? // optimisation for single table case
+ _fnExtend( o, options, true ) :
+ options;
+
+ /*global oInit,_that,emptyInit*/
var i=0, iLen, j, jLen, k, kLen;
var sId = this.getAttribute( 'id' );
var bInitHandedOff = false;
- var bUsePassedData = false;
+ var defaults = DataTable.defaults;
+ var $this = $(this);
/* Sanity check */
if ( this.nodeName.toLowerCase() != 'table' )
{
- _fnLog( null, 0, "Attempted to initialise DataTables on a node which is not a "+
- "table: "+this.nodeName );
+ _fnLog( null, 0, 'Non-table node initialisation ('+this.nodeName+')', 2 );
return;
}
+ /* Backwards compatibility for the defaults */
+ _fnCompatOpts( defaults );
+ _fnCompatCols( defaults.column );
+
+ /* Convert the camel-case defaults to Hungarian */
+ _fnCamelToHungarian( defaults, defaults, true );
+ _fnCamelToHungarian( defaults.column, defaults.column, true );
+
+ /* Setting up the initialisation object */
+ _fnCamelToHungarian( defaults, $.extend( oInit, $this.data() ) );
+
+
+
/* Check to see if we are re-initialising a table */
- for ( i=0, iLen=DataTable.settings.length ; i<iLen ; i++ )
+ var allSettings = DataTable.settings;
+ for ( i=0, iLen=allSettings.length ; i<iLen ; i++ )
{
+ var s = allSettings[i];
+
/* Base check on table node */
- if ( DataTable.settings[i].nTable == this )
+ if ( s.nTable == this || s.nTHead.parentNode == this || (s.nTFoot && s.nTFoot.parentNode == this) )
{
- if ( oInit === undefined || oInit.bRetrieve )
+ var bRetrieve = oInit.bRetrieve !== undefined ? oInit.bRetrieve : defaults.bRetrieve;
+ var bDestroy = oInit.bDestroy !== undefined ? oInit.bDestroy : defaults.bDestroy;
+
+ if ( emptyInit || bRetrieve )
{
- return DataTable.settings[i].oInstance;
+ return s.oInstance;
}
- else if ( oInit.bDestroy )
+ else if ( bDestroy )
{
- DataTable.settings[i].oInstance.fnDestroy();
+ s.oInstance.fnDestroy();
break;
}
else
{
- _fnLog( DataTable.settings[i], 0, "Cannot reinitialise DataTable.\n\n"+
- "To retrieve the DataTables object for this table, pass no arguments or see "+
- "the docs for bRetrieve and bDestroy" );
+ _fnLog( s, 0, 'Cannot reinitialise DataTable', 3 );
return;
}
}
-
+
/* If the element we are initialising has the same ID as a table which was previously
* initialised, but the table nodes don't match (from before) then we destroy the old
* instance by simply deleting it. This is under the assumption that the table has been
* destroyed by other methods. Anyone using non-id selectors will need to do this manually
*/
- if ( DataTable.settings[i].sTableId == this.id )
+ if ( s.sTableId == this.id )
{
- DataTable.settings.splice( i, 1 );
+ allSettings.splice( i, 1 );
break;
}
}
@@ -6417,80 +6168,92 @@
/* Ensure the table has an ID - required for accessibility */
if ( sId === null || sId === "" )
{
- sId = "DataTables_Table_"+(DataTable.ext._oExternConfig.iNextUnique++);
+ sId = "DataTables_Table_"+(DataTable.ext._unique++);
this.id = sId;
}
/* Create the settings object for this table and set some of the default parameters */
var oSettings = $.extend( true, {}, DataTable.models.oSettings, {
- "nTable": this,
- "oApi": _that.oApi,
- "oInit": oInit,
- "sDestroyWidth": $(this).width(),
+ "sDestroyWidth": $this[0].style.width,
"sInstance": sId,
"sTableId": sId
} );
- DataTable.settings.push( oSettings );
+ oSettings.nTable = this;
+ oSettings.oApi = _that.internal;
+ oSettings.oInit = oInit;
+
+ allSettings.push( oSettings );
// Need to add the instance after the instance after the settings object has been added
// to the settings array, so we can self reference the table instance if more than one
- oSettings.oInstance = (_that.length===1) ? _that : $(this).dataTable();
-
- /* Setting up the initialisation object */
- if ( !oInit )
- {
- oInit = {};
- }
+ oSettings.oInstance = (_that.length===1) ? _that : $this.dataTable();
// Backwards compatibility, before we apply all the defaults
+ _fnCompatOpts( oInit );
+
if ( oInit.oLanguage )
{
_fnLanguageCompat( oInit.oLanguage );
}
- oInit = _fnExtend( $.extend(true, {}, DataTable.defaults), oInit );
+ // If the length menu is given, but the init display length is not, use the length menu
+ if ( oInit.aLengthMenu && ! oInit.iDisplayLength )
+ {
+ oInit.iDisplayLength = $.isArray( oInit.aLengthMenu[0] ) ?
+ oInit.aLengthMenu[0][0] : oInit.aLengthMenu[0];
+ }
+
+ // Apply the defaults and init options to make a single init object will all
+ // options defined from defaults and instance options.
+ oInit = _fnExtend( $.extend( true, {}, defaults ), oInit );
+
// Map the initialisation options onto the settings object
- _fnMap( oSettings.oFeatures, oInit, "bPaginate" );
- _fnMap( oSettings.oFeatures, oInit, "bLengthChange" );
- _fnMap( oSettings.oFeatures, oInit, "bFilter" );
- _fnMap( oSettings.oFeatures, oInit, "bSort" );
- _fnMap( oSettings.oFeatures, oInit, "bInfo" );
- _fnMap( oSettings.oFeatures, oInit, "bProcessing" );
- _fnMap( oSettings.oFeatures, oInit, "bAutoWidth" );
- _fnMap( oSettings.oFeatures, oInit, "bSortClasses" );
- _fnMap( oSettings.oFeatures, oInit, "bServerSide" );
- _fnMap( oSettings.oFeatures, oInit, "bDeferRender" );
- _fnMap( oSettings.oScroll, oInit, "sScrollX", "sX" );
- _fnMap( oSettings.oScroll, oInit, "sScrollXInner", "sXInner" );
- _fnMap( oSettings.oScroll, oInit, "sScrollY", "sY" );
- _fnMap( oSettings.oScroll, oInit, "bScrollCollapse", "bCollapse" );
- _fnMap( oSettings.oScroll, oInit, "bScrollInfinite", "bInfinite" );
- _fnMap( oSettings.oScroll, oInit, "iScrollLoadGap", "iLoadGap" );
- _fnMap( oSettings.oScroll, oInit, "bScrollAutoCss", "bAutoCss" );
- _fnMap( oSettings, oInit, "asStripeClasses" );
- _fnMap( oSettings, oInit, "asStripClasses", "asStripeClasses" ); // legacy
- _fnMap( oSettings, oInit, "fnServerData" );
- _fnMap( oSettings, oInit, "fnFormatNumber" );
- _fnMap( oSettings, oInit, "sServerMethod" );
- _fnMap( oSettings, oInit, "aaSorting" );
- _fnMap( oSettings, oInit, "aaSortingFixed" );
- _fnMap( oSettings, oInit, "aLengthMenu" );
- _fnMap( oSettings, oInit, "sPaginationType" );
- _fnMap( oSettings, oInit, "sAjaxSource" );
- _fnMap( oSettings, oInit, "sAjaxDataProp" );
- _fnMap( oSettings, oInit, "iCookieDuration" );
- _fnMap( oSettings, oInit, "sCookiePrefix" );
- _fnMap( oSettings, oInit, "sDom" );
- _fnMap( oSettings, oInit, "bSortCellsTop" );
- _fnMap( oSettings, oInit, "iTabIndex" );
- _fnMap( oSettings, oInit, "oSearch", "oPreviousSearch" );
- _fnMap( oSettings, oInit, "aoSearchCols", "aoPreSearchCols" );
- _fnMap( oSettings, oInit, "iDisplayLength", "_iDisplayLength" );
- _fnMap( oSettings, oInit, "bJQueryUI", "bJUI" );
- _fnMap( oSettings, oInit, "fnCookieCallback" );
- _fnMap( oSettings, oInit, "fnStateLoad" );
- _fnMap( oSettings, oInit, "fnStateSave" );
+ _fnMap( oSettings.oFeatures, oInit, [
+ "bPaginate",
+ "bLengthChange",
+ "bFilter",
+ "bSort",
+ "bSortMulti",
+ "bInfo",
+ "bProcessing",
+ "bAutoWidth",
+ "bSortClasses",
+ "bServerSide",
+ "bDeferRender"
+ ] );
+ _fnMap( oSettings, oInit, [
+ "asStripeClasses",
+ "ajax",
+ "fnServerData",
+ "fnFormatNumber",
+ "sServerMethod",
+ "aaSorting",
+ "aaSortingFixed",
+ "aLengthMenu",
+ "sPaginationType",
+ "sAjaxSource",
+ "sAjaxDataProp",
+ "iStateDuration",
+ "sDom",
+ "bSortCellsTop",
+ "iTabIndex",
+ "fnStateLoadCallback",
+ "fnStateSaveCallback",
+ "renderer",
+ "searchDelay",
+ [ "iCookieDuration", "iStateDuration" ], // backwards compat
+ [ "oSearch", "oPreviousSearch" ],
+ [ "aoSearchCols", "aoPreSearchCols" ],
+ [ "iDisplayLength", "_iDisplayLength" ],
+ [ "bJQueryUI", "bJUI" ]
+ ] );
+ _fnMap( oSettings.oScroll, oInit, [
+ [ "sScrollX", "sX" ],
+ [ "sScrollXInner", "sXInner" ],
+ [ "sScrollY", "sY" ],
+ [ "bScrollCollapse", "bCollapse" ]
+ ] );
_fnMap( oSettings.oLanguage, oInit, "fnInfoCallback" );
/* Callback functions which are array driven */
@@ -6506,43 +6269,43 @@
_fnCallbackReg( oSettings, 'aoInitComplete', oInit.fnInitComplete, 'user' );
_fnCallbackReg( oSettings, 'aoPreDrawCallback', oInit.fnPreDrawCallback, 'user' );
- if ( oSettings.oFeatures.bServerSide && oSettings.oFeatures.bSort &&
- oSettings.oFeatures.bSortClasses )
- {
- /* Enable sort classes for server-side processing. Safe to do it here, since server-side
- * processing must be enabled by the developer
- */
- _fnCallbackReg( oSettings, 'aoDrawCallback', _fnSortingClasses, 'server_side_sort_classes' );
- }
- else if ( oSettings.oFeatures.bDeferRender )
- {
- _fnCallbackReg( oSettings, 'aoDrawCallback', _fnSortingClasses, 'defer_sort_classes' );
- }
+ var oClasses = oSettings.oClasses;
+ // @todo Remove in 1.11
if ( oInit.bJQueryUI )
{
- /* Use the JUI classes object for display. You could clone the oStdClasses object if
- * you want to have multiple tables with multiple independent classes
+ /* Use the JUI classes object for display. You could clone the oStdClasses object if
+ * you want to have multiple tables with multiple independent classes
*/
- $.extend( oSettings.oClasses, DataTable.ext.oJUIClasses );
-
- if ( oInit.sDom === DataTable.defaults.sDom && DataTable.defaults.sDom === "lfrtip" )
+ $.extend( oClasses, DataTable.ext.oJUIClasses, oInit.oClasses );
+
+ if ( oInit.sDom === defaults.sDom && defaults.sDom === "lfrtip" )
{
/* Set the DOM to use a layout suitable for jQuery UI's theming */
oSettings.sDom = '<"H"lfr>t<"F"ip>';
}
+
+ if ( ! oSettings.renderer ) {
+ oSettings.renderer = 'jqueryui';
+ }
+ else if ( $.isPlainObject( oSettings.renderer ) && ! oSettings.renderer.header ) {
+ oSettings.renderer.header = 'jqueryui';
+ }
}
else
{
- $.extend( oSettings.oClasses, DataTable.ext.oStdClasses );
+ $.extend( oClasses, DataTable.ext.classes, oInit.oClasses );
}
- $(this).addClass( oSettings.oClasses.sTable );
+ $this.addClass( oClasses.sTable );
/* Calculate the scroll bar width and cache it for use later on */
if ( oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "" )
{
oSettings.oScroll.iBarWidth = _fnScrollBarWidth();
}
+ if ( oSettings.oScroll.sX === true ) { // Easy initialisation of x-scrolling
+ oSettings.oScroll.sX = '100%';
+ }
if ( oSettings.iInitDisplayStart === undefined )
{
@@ -6551,14 +6314,6 @@
oSettings._iDisplayStart = oInit.iDisplayStart;
}
- /* Must be done after everything which can be overridden by a cookie! */
- if ( oInit.bStateSave )
- {
- oSettings.oFeatures.bStateSave = true;
- _fnLoadState( oSettings, oInit );
- _fnCallbackReg( oSettings, 'aoDrawCallback', _fnSaveState, 'state_save' );
- }
-
if ( oInit.iDeferLoading !== null )
{
oSettings.bDeferLoading = true;
@@ -6567,31 +6322,32 @@
oSettings._iRecordsTotal = tmp ? oInit.iDeferLoading[1] : oInit.iDeferLoading;
}
- if ( oInit.aaData !== null )
- {
- bUsePassedData = true;
- }
-
/* Language definitions */
- if ( oInit.oLanguage.sUrl !== "" )
+ var oLanguage = oSettings.oLanguage;
+ $.extend( true, oLanguage, oInit.oLanguage );
+
+ if ( oLanguage.sUrl !== "" )
{
/* Get the language definitions from a file - because this Ajax call makes the language
- * get async to the remainder of this function we use bInitHandedOff to indicate that
+ * get async to the remainder of this function we use bInitHandedOff to indicate that
* _fnInitialise will be fired by the returned Ajax handler, rather than the constructor
*/
- oSettings.oLanguage.sUrl = oInit.oLanguage.sUrl;
- $.getJSON( oSettings.oLanguage.sUrl, null, function( json ) {
- _fnLanguageCompat( json );
- $.extend( true, oSettings.oLanguage, oInit.oLanguage, json );
- _fnInitialise( oSettings );
+ $.ajax( {
+ dataType: 'json',
+ url: oLanguage.sUrl,
+ success: function ( json ) {
+ _fnLanguageCompat( json );
+ _fnCamelToHungarian( defaults.oLanguage, json );
+ $.extend( true, oLanguage, json );
+ _fnInitialise( oSettings );
+ },
+ error: function () {
+ // Error occurred loading language file, continue on as best we can
+ _fnInitialise( oSettings );
+ }
} );
bInitHandedOff = true;
}
- else
- {
- $.extend( true, oSettings.oLanguage, oInit.oLanguage );
- }
-
/*
* Stripes
@@ -6599,33 +6355,19 @@
if ( oInit.asStripeClasses === null )
{
oSettings.asStripeClasses =[
- oSettings.oClasses.sStripeOdd,
- oSettings.oClasses.sStripeEven
+ oClasses.sStripeOdd,
+ oClasses.sStripeEven
];
}
/* Remove row stripe classes if they are already on the table row */
- iLen=oSettings.asStripeClasses.length;
- oSettings.asDestroyStripes = [];
- if (iLen)
- {
- var bStripeRemove = false;
- var anRows = $(this).children('tbody').children('tr:lt(' + iLen + ')');
- for ( i=0 ; i<iLen ; i++ )
- {
- if ( anRows.hasClass( oSettings.asStripeClasses[i] ) )
- {
- bStripeRemove = true;
-
- /* Store the classes which we are about to remove so they can be re-added on destroy */
- oSettings.asDestroyStripes.push( oSettings.asStripeClasses[i] );
- }
- }
-
- if ( bStripeRemove )
- {
- anRows.removeClass( oSettings.asStripeClasses.join(' ') );
- }
+ var stripeClasses = oSettings.asStripeClasses;
+ var rowOne = $this.children('tbody').find('tr').eq(0);
+ if ( $.inArray( true, $.map( stripeClasses, function(el, i) {
+ return rowOne.hasClass(el);
+ } ) ) !== -1 ) {
+ $('tbody tr', this).removeClass( stripeClasses.join(' ') );
+ oSettings.asDestroyStripes = stripeClasses.slice();
}
/*
@@ -6658,16 +6400,6 @@
/* Add the columns */
for ( i=0, iLen=aoColumnsInit.length ; i<iLen ; i++ )
{
- /* Short cut - use the loop to check if we have column visibility state to restore */
- if ( oInit.saved_aoColumns !== undefined && oInit.saved_aoColumns.length == iLen )
- {
- if ( aoColumnsInit[i] === null )
- {
- aoColumnsInit[i] = {};
- }
- aoColumnsInit[i].bVisible = oInit.saved_aoColumns[i].bVisible;
- }
-
_fnAddColumn( oSettings, anThs ? anThs[i] : null );
}
@@ -6676,47 +6408,90 @@
_fnColumnOptions( oSettings, iCol, oDef );
} );
+ /* HTML5 attribute detection - build an mData object automatically if the
+ * attributes are found
+ */
+ if ( rowOne.length ) {
+ var a = function ( cell, name ) {
+ return cell.getAttribute( 'data-'+name ) !== null ? name : null;
+ };
+
+ $.each( _fnGetRowElements( oSettings, rowOne[0] ).cells, function (i, cell) {
+ var col = oSettings.aoColumns[i];
+
+ if ( col.mData === i ) {
+ var sort = a( cell, 'sort' ) || a( cell, 'order' );
+ var filter = a( cell, 'filter' ) || a( cell, 'search' );
+
+ if ( sort !== null || filter !== null ) {
+ col.mData = {
+ _: i+'.display',
+ sort: sort !== null ? i+'.@data-'+sort : undefined,
+ type: sort !== null ? i+'.@data-'+sort : undefined,
+ filter: filter !== null ? i+'.@data-'+filter : undefined
+ };
+
+ _fnColumnOptions( oSettings, i );
+ }
+ }
+ } );
+ }
+
+ var features = oSettings.oFeatures;
+
+ /* Must be done after everything which can be overridden by the state saving! */
+ if ( oInit.bStateSave )
+ {
+ features.bStateSave = true;
+ _fnLoadState( oSettings, oInit );
+ _fnCallbackReg( oSettings, 'aoDrawCallback', _fnSaveState, 'state_save' );
+ }
+
/*
* Sorting
- * Check the aaSorting array
+ * @todo For modularisation (1.11) this needs to do into a sort start up handler
*/
- for ( i=0, iLen=oSettings.aaSorting.length ; i<iLen ; i++ )
+
+ // If aaSorting is not defined, then we use the first indicator in asSorting
+ // in case that has been altered, so the default sort reflects that option
+ if ( oInit.aaSorting === undefined )
{
- if ( oSettings.aaSorting[i][0] >= oSettings.aoColumns.length )
+ var sorting = oSettings.aaSorting;
+ for ( i=0, iLen=sorting.length ; i<iLen ; i++ )
{
- oSettings.aaSorting[i][0] = 0;
- }
- var oColumn = oSettings.aoColumns[ oSettings.aaSorting[i][0] ];
-
- /* Add a default sorting index */
- if ( oSettings.aaSorting[i][2] === undefined )
- {
- oSettings.aaSorting[i][2] = 0;
- }
-
- /* If aaSorting is not defined, then we use the first indicator in asSorting */
- if ( oInit.aaSorting === undefined && oSettings.saved_aaSorting === undefined )
- {
- oSettings.aaSorting[i][1] = oColumn.asSorting[0];
- }
-
- /* Set the current sorting index based on aoColumns.asSorting */
- for ( j=0, jLen=oColumn.asSorting.length ; j<jLen ; j++ )
- {
- if ( oSettings.aaSorting[i][1] == oColumn.asSorting[j] )
- {
- oSettings.aaSorting[i][2] = j;
- break;
- }
+ sorting[i][1] = oSettings.aoColumns[ i ].asSorting[0];
}
}
-
+
/* Do a first pass on the sorting classes (allows any size changes to be taken into
* account, and also will apply sorting disabled classes if disabled
*/
_fnSortingClasses( oSettings );
+ if ( features.bSort )
+ {
+ _fnCallbackReg( oSettings, 'aoDrawCallback', function () {
+ if ( oSettings.bSorted ) {
+ var aSort = _fnSortFlatten( oSettings );
+ var sortedColumns = {};
+
+ $.each( aSort, function (i, val) {
+ sortedColumns[ val.src ] = val.dir;
+ } );
+
+ _fnCallbackFire( oSettings, null, 'order', [oSettings, aSort, sortedColumns] );
+ _fnSortAria( oSettings );
+ }
+ } );
+ }
+
+ _fnCallbackReg( oSettings, 'aoDrawCallback', function () {
+ if ( oSettings.bSorted || _fnDataSource( oSettings ) === 'ssp' || features.bDeferRender ) {
+ _fnSortingClasses( oSettings );
+ }
+ }, 'sc' );
+
/*
* Final init
@@ -6727,56 +6502,55 @@
_fnBrowserDetect( oSettings );
// Work around for Webkit bug 83867 - store the caption-side before removing from doc
- var captions = $(this).children('caption').each( function () {
- this._captionSide = $(this).css('caption-side');
+ var captions = $this.children('caption').each( function () {
+ this._captionSide = $this.css('caption-side');
} );
- var thead = $(this).children('thead');
+ var thead = $this.children('thead');
if ( thead.length === 0 )
{
- thead = [ document.createElement( 'thead' ) ];
- this.appendChild( thead[0] );
+ thead = $('<thead/>').appendTo(this);
}
oSettings.nTHead = thead[0];
- var tbody = $(this).children('tbody');
+ var tbody = $this.children('tbody');
if ( tbody.length === 0 )
{
- tbody = [ document.createElement( 'tbody' ) ];
- this.appendChild( tbody[0] );
+ tbody = $('<tbody/>').appendTo(this);
}
oSettings.nTBody = tbody[0];
- oSettings.nTBody.setAttribute( "role", "alert" );
- oSettings.nTBody.setAttribute( "aria-live", "polite" );
- oSettings.nTBody.setAttribute( "aria-relevant", "all" );
- var tfoot = $(this).children('tfoot');
+ var tfoot = $this.children('tfoot');
if ( tfoot.length === 0 && captions.length > 0 && (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "") )
{
// If we are a scrolling table, and no footer has been given, then we need to create
// a tfoot element for the caption element to be appended to
- tfoot = [ document.createElement( 'tfoot' ) ];
- this.appendChild( tfoot[0] );
+ tfoot = $('<tfoot/>').appendTo(this);
}
- if ( tfoot.length > 0 )
- {
+ if ( tfoot.length === 0 || tfoot.children().length === 0 ) {
+ $this.addClass( oClasses.sNoFooter );
+ }
+ else if ( tfoot.length > 0 ) {
oSettings.nTFoot = tfoot[0];
_fnDetectHeader( oSettings.aoFooter, oSettings.nTFoot );
}
/* Check if there is data passing into the constructor */
- if ( bUsePassedData )
+ if ( oInit.aaData )
{
for ( i=0 ; i<oInit.aaData.length ; i++ )
{
_fnAddData( oSettings, oInit.aaData[ i ] );
}
}
- else
+ else if ( oSettings.bDeferLoading || _fnDataSource( oSettings ) == 'dom' )
{
- /* Grab the data from the page */
- _fnGatherData( oSettings );
+ /* Grab the data from the page - only do this when deferred loading or no Ajax
+ * source since there is no point in reading the DOM data if we are then going
+ * to replace it with Ajax data
+ */
+ _fnAddTr( oSettings, $(oSettings.nTBody).children('tr') );
}
/* Copy the data index array */
@@ -6800,660 +6574,2588 @@
/**
- * Provide a common method for plug-ins to check the version of DataTables being used, in order
- * to ensure compatibility.
- * @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the
- * formats "X" and "X.Y" are also acceptable.
- * @returns {boolean} true if this version of DataTables is greater or equal to the required
- * version, or false if this version of DataTales is not suitable
- * @static
- * @dtopt API-Static
+ * Computed structure of the DataTables API, defined by the options passed to
+ * `DataTable.Api.register()` when building the API.
*
- * @example
- * alert( $.fn.dataTable.fnVersionCheck( '1.9.0' ) );
+ * The structure is built in order to speed creation and extension of the Api
+ * objects since the extensions are effectively pre-parsed.
+ *
+ * The array is an array of objects with the following structure, where this
+ * base array represents the Api prototype base:
+ *
+ * [
+ * {
+ * name: 'data' -- string - Property name
+ * val: function () {}, -- function - Api method (or undefined if just an object
+ * methodExt: [ ... ], -- array - Array of Api object definitions to extend the method result
+ * propExt: [ ... ] -- array - Array of Api object definitions to extend the property
+ * },
+ * {
+ * name: 'row'
+ * val: {},
+ * methodExt: [ ... ],
+ * propExt: [
+ * {
+ * name: 'data'
+ * val: function () {},
+ * methodExt: [ ... ],
+ * propExt: [ ... ]
+ * },
+ * ...
+ * ]
+ * }
+ * ]
+ *
+ * @type {Array}
+ * @ignore
*/
- DataTable.fnVersionCheck = function( sVersion )
+ var __apiStruct = [];
+
+
+ /**
+ * `Array.prototype` reference.
+ *
+ * @type object
+ * @ignore
+ */
+ var __arrayProto = Array.prototype;
+
+
+ /**
+ * Abstraction for `context` parameter of the `Api` constructor to allow it to
+ * take several different forms for ease of use.
+ *
+ * Each of the input parameter types will be converted to a DataTables settings
+ * object where possible.
+ *
+ * @param {string|node|jQuery|object} mixed DataTable identifier. Can be one
+ * of:
+ *
+ * * `string` - jQuery selector. Any DataTables' matching the given selector
+ * with be found and used.
+ * * `node` - `TABLE` node which has already been formed into a DataTable.
+ * * `jQuery` - A jQuery object of `TABLE` nodes.
+ * * `object` - DataTables settings object
+ * * `DataTables.Api` - API instance
+ * @return {array|null} Matching DataTables settings objects. `null` or
+ * `undefined` is returned if no matching DataTable is found.
+ * @ignore
+ */
+ var _toSettings = function ( mixed )
{
- /* This is cheap, but effective */
- var fnZPad = function (Zpad, count)
- {
- while(Zpad.length < count) {
- Zpad += '0';
+ var idx, jq;
+ var settings = DataTable.settings;
+ var tables = $.map( settings, function (el, i) {
+ return el.nTable;
+ } );
+
+ if ( ! mixed ) {
+ return [];
+ }
+ else if ( mixed.nTable && mixed.oApi ) {
+ // DataTables settings object
+ return [ mixed ];
+ }
+ else if ( mixed.nodeName && mixed.nodeName.toLowerCase() === 'table' ) {
+ // Table node
+ idx = $.inArray( mixed, tables );
+ return idx !== -1 ? [ settings[idx] ] : null;
+ }
+ else if ( mixed && typeof mixed.settings === 'function' ) {
+ return mixed.settings().toArray();
+ }
+ else if ( typeof mixed === 'string' ) {
+ // jQuery selector
+ jq = $(mixed);
+ }
+ else if ( mixed instanceof $ ) {
+ // jQuery object (also DataTables instance)
+ jq = mixed;
+ }
+
+ if ( jq ) {
+ return jq.map( function(i) {
+ idx = $.inArray( this, tables );
+ return idx !== -1 ? settings[idx] : null;
+ } ).toArray();
+ }
+ };
+
+
+ /**
+ * DataTables API class - used to control and interface with one or more
+ * DataTables enhanced tables.
+ *
+ * The API class is heavily based on jQuery, presenting a chainable interface
+ * that you can use to interact with tables. Each instance of the API class has
+ * a "context" - i.e. the tables that it will operate on. This could be a single
+ * table, all tables on a page or a sub-set thereof.
+ *
+ * Additionally the API is designed to allow you to easily work with the data in
+ * the tables, retrieving and manipulating it as required. This is done by
+ * presenting the API class as an array like interface. The contents of the
+ * array depend upon the actions requested by each method (for example
+ * `rows().nodes()` will return an array of nodes, while `rows().data()` will
+ * return an array of objects or arrays depending upon your table's
+ * configuration). The API object has a number of array like methods (`push`,
+ * `pop`, `reverse` etc) as well as additional helper methods (`each`, `pluck`,
+ * `unique` etc) to assist your working with the data held in a table.
+ *
+ * Most methods (those which return an Api instance) are chainable, which means
+ * the return from a method call also has all of the methods available that the
+ * top level object had. For example, these two calls are equivalent:
+ *
+ * // Not chained
+ * api.row.add( {...} );
+ * api.draw();
+ *
+ * // Chained
+ * api.row.add( {...} ).draw();
+ *
+ * @class DataTable.Api
+ * @param {array|object|string|jQuery} context DataTable identifier. This is
+ * used to define which DataTables enhanced tables this API will operate on.
+ * Can be one of:
+ *
+ * * `string` - jQuery selector. Any DataTables' matching the given selector
+ * with be found and used.
+ * * `node` - `TABLE` node which has already been formed into a DataTable.
+ * * `jQuery` - A jQuery object of `TABLE` nodes.
+ * * `object` - DataTables settings object
+ * @param {array} [data] Data to initialise the Api instance with.
+ *
+ * @example
+ * // Direct initialisation during DataTables construction
+ * var api = $('#example').DataTable();
+ *
+ * @example
+ * // Initialisation using a DataTables jQuery object
+ * var api = $('#example').dataTable().api();
+ *
+ * @example
+ * // Initialisation as a constructor
+ * var api = new $.fn.DataTable.Api( 'table.dataTable' );
+ */
+ _Api = function ( context, data )
+ {
+ if ( ! (this instanceof _Api) ) {
+ return new _Api( context, data );
+ }
+
+ var settings = [];
+ var ctxSettings = function ( o ) {
+ var a = _toSettings( o );
+ if ( a ) {
+ settings.push.apply( settings, a );
}
- return Zpad;
};
- var aThis = DataTable.ext.sVersion.split('.');
- var aThat = sVersion.split('.');
- var sThis = '', sThat = '';
-
- for ( var i=0, iLen=aThat.length ; i<iLen ; i++ )
+
+ if ( $.isArray( context ) ) {
+ for ( var i=0, ien=context.length ; i<ien ; i++ ) {
+ ctxSettings( context[i] );
+ }
+ }
+ else {
+ ctxSettings( context );
+ }
+
+ // Remove duplicates
+ this.context = _unique( settings );
+
+ // Initial data
+ if ( data ) {
+ this.push.apply( this, data.toArray ? data.toArray() : data );
+ }
+
+ // selector
+ this.selector = {
+ rows: null,
+ cols: null,
+ opts: null
+ };
+
+ _Api.extend( this, this, __apiStruct );
+ };
+
+ DataTable.Api = _Api;
+
+ _Api.prototype = /** @lends DataTables.Api */{
+ any: function ()
+ {
+ return this.flatten().length !== 0;
+ },
+
+
+ concat: __arrayProto.concat,
+
+
+ context: [], // array of table settings objects
+
+
+ each: function ( fn )
+ {
+ for ( var i=0, ien=this.length ; i<ien; i++ ) {
+ fn.call( this, this[i], i, this );
+ }
+
+ return this;
+ },
+
+
+ eq: function ( idx )
+ {
+ var ctx = this.context;
+
+ return ctx.length > idx ?
+ new _Api( ctx[idx], this[idx] ) :
+ null;
+ },
+
+
+ filter: function ( fn )
+ {
+ var a = [];
+
+ if ( __arrayProto.filter ) {
+ a = __arrayProto.filter.call( this, fn, this );
+ }
+ else {
+ // Compatibility for browsers without EMCA-252-5 (JS 1.6)
+ for ( var i=0, ien=this.length ; i<ien ; i++ ) {
+ if ( fn.call( this, this[i], i, this ) ) {
+ a.push( this[i] );
+ }
+ }
+ }
+
+ return new _Api( this.context, a );
+ },
+
+
+ flatten: function ()
+ {
+ var a = [];
+ return new _Api( this.context, a.concat.apply( a, this.toArray() ) );
+ },
+
+
+ join: __arrayProto.join,
+
+
+ indexOf: __arrayProto.indexOf || function (obj, start)
+ {
+ for ( var i=(start || 0), ien=this.length ; i<ien ; i++ ) {
+ if ( this[i] === obj ) {
+ return i;
+ }
+ }
+ return -1;
+ },
+
+ iterator: function ( flatten, type, fn, alwaysNew ) {
+ var
+ a = [], ret,
+ i, ien, j, jen,
+ context = this.context,
+ rows, items, item,
+ selector = this.selector;
+
+ // Argument shifting
+ if ( typeof flatten === 'string' ) {
+ alwaysNew = fn;
+ fn = type;
+ type = flatten;
+ flatten = false;
+ }
+
+ for ( i=0, ien=context.length ; i<ien ; i++ ) {
+ var apiInst = new _Api( context[i] );
+
+ if ( type === 'table' ) {
+ ret = fn.call( apiInst, context[i], i );
+
+ if ( ret !== undefined ) {
+ a.push( ret );
+ }
+ }
+ else if ( type === 'columns' || type === 'rows' ) {
+ // this has same length as context - one entry for each table
+ ret = fn.call( apiInst, context[i], this[i], i );
+
+ if ( ret !== undefined ) {
+ a.push( ret );
+ }
+ }
+ else if ( type === 'column' || type === 'column-rows' || type === 'row' || type === 'cell' ) {
+ // columns and rows share the same structure.
+ // 'this' is an array of column indexes for each context
+ items = this[i];
+
+ if ( type === 'column-rows' ) {
+ rows = _selector_row_indexes( context[i], selector.opts );
+ }
+
+ for ( j=0, jen=items.length ; j<jen ; j++ ) {
+ item = items[j];
+
+ if ( type === 'cell' ) {
+ ret = fn.call( apiInst, context[i], item.row, item.column, i, j );
+ }
+ else {
+ ret = fn.call( apiInst, context[i], item, i, j, rows );
+ }
+
+ if ( ret !== undefined ) {
+ a.push( ret );
+ }
+ }
+ }
+ }
+
+ if ( a.length || alwaysNew ) {
+ var api = new _Api( context, flatten ? a.concat.apply( [], a ) : a );
+ var apiSelector = api.selector;
+ apiSelector.rows = selector.rows;
+ apiSelector.cols = selector.cols;
+ apiSelector.opts = selector.opts;
+ return api;
+ }
+ return this;
+ },
+
+
+ lastIndexOf: __arrayProto.lastIndexOf || function (obj, start)
+ {
+ // Bit cheeky...
+ return this.indexOf.apply( this.toArray.reverse(), arguments );
+ },
+
+
+ length: 0,
+
+
+ map: function ( fn )
+ {
+ var a = [];
+
+ if ( __arrayProto.map ) {
+ a = __arrayProto.map.call( this, fn, this );
+ }
+ else {
+ // Compatibility for browsers without EMCA-252-5 (JS 1.6)
+ for ( var i=0, ien=this.length ; i<ien ; i++ ) {
+ a.push( fn.call( this, this[i], i ) );
+ }
+ }
+
+ return new _Api( this.context, a );
+ },
+
+
+ pluck: function ( prop )
{
- sThis += fnZPad( aThis[i], 3 );
- sThat += fnZPad( aThat[i], 3 );
+ return this.map( function ( el ) {
+ return el[ prop ];
+ } );
+ },
+
+ pop: __arrayProto.pop,
+
+
+ push: __arrayProto.push,
+
+
+ // Does not return an API instance
+ reduce: __arrayProto.reduce || function ( fn, init )
+ {
+ return _fnReduce( this, fn, init, 0, this.length, 1 );
+ },
+
+
+ reduceRight: __arrayProto.reduceRight || function ( fn, init )
+ {
+ return _fnReduce( this, fn, init, this.length-1, -1, -1 );
+ },
+
+
+ reverse: __arrayProto.reverse,
+
+
+ // Object with rows, columns and opts
+ selector: null,
+
+
+ shift: __arrayProto.shift,
+
+
+ sort: __arrayProto.sort, // ? name - order?
+
+
+ splice: __arrayProto.splice,
+
+
+ toArray: function ()
+ {
+ return __arrayProto.slice.call( this );
+ },
+
+
+ to$: function ()
+ {
+ return $( this );
+ },
+
+
+ toJQuery: function ()
+ {
+ return $( this );
+ },
+
+
+ unique: function ()
+ {
+ return new _Api( this.context, _unique(this) );
+ },
+
+
+ unshift: __arrayProto.unshift
+ };
+
+
+ _Api.extend = function ( scope, obj, ext )
+ {
+ // Only extend API instances and static properties of the API
+ if ( ! ext.length || ! obj || ( ! (obj instanceof _Api) && ! obj.__dt_wrapper ) ) {
+ return;
+ }
+
+ var
+ i, ien,
+ j, jen,
+ struct, inner,
+ methodScoping = function ( scope, fn, struc ) {
+ return function () {
+ var ret = fn.apply( scope, arguments );
+
+ // Method extension
+ _Api.extend( ret, ret, struc.methodExt );
+ return ret;
+ };
+ };
+
+ for ( i=0, ien=ext.length ; i<ien ; i++ ) {
+ struct = ext[i];
+
+ // Value
+ obj[ struct.name ] = typeof struct.val === 'function' ?
+ methodScoping( scope, struct.val, struct ) :
+ $.isPlainObject( struct.val ) ?
+ {} :
+ struct.val;
+
+ obj[ struct.name ].__dt_wrapper = true;
+
+ // Property extension
+ _Api.extend( scope, obj[ struct.name ], struct.propExt );
}
-
- return parseInt(sThis, 10) >= parseInt(sThat, 10);
+ };
+
+
+ // @todo - Is there need for an augment function?
+ // _Api.augment = function ( inst, name )
+ // {
+ // // Find src object in the structure from the name
+ // var parts = name.split('.');
+
+ // _Api.extend( inst, obj );
+ // };
+
+
+ // [
+ // {
+ // name: 'data' -- string - Property name
+ // val: function () {}, -- function - Api method (or undefined if just an object
+ // methodExt: [ ... ], -- array - Array of Api object definitions to extend the method result
+ // propExt: [ ... ] -- array - Array of Api object definitions to extend the property
+ // },
+ // {
+ // name: 'row'
+ // val: {},
+ // methodExt: [ ... ],
+ // propExt: [
+ // {
+ // name: 'data'
+ // val: function () {},
+ // methodExt: [ ... ],
+ // propExt: [ ... ]
+ // },
+ // ...
+ // ]
+ // }
+ // ]
+
+ _Api.register = _api_register = function ( name, val )
+ {
+ if ( $.isArray( name ) ) {
+ for ( var j=0, jen=name.length ; j<jen ; j++ ) {
+ _Api.register( name[j], val );
+ }
+ return;
+ }
+
+ var
+ i, ien,
+ heir = name.split('.'),
+ struct = __apiStruct,
+ key, method;
+
+ var find = function ( src, name ) {
+ for ( var i=0, ien=src.length ; i<ien ; i++ ) {
+ if ( src[i].name === name ) {
+ return src[i];
+ }
+ }
+ return null;
+ };
+
+ for ( i=0, ien=heir.length ; i<ien ; i++ ) {
+ method = heir[i].indexOf('()') !== -1;
+ key = method ?
+ heir[i].replace('()', '') :
+ heir[i];
+
+ var src = find( struct, key );
+ if ( ! src ) {
+ src = {
+ name: key,
+ val: {},
+ methodExt: [],
+ propExt: []
+ };
+ struct.push( src );
+ }
+
+ if ( i === ien-1 ) {
+ src.val = val;
+ }
+ else {
+ struct = method ?
+ src.methodExt :
+ src.propExt;
+ }
+ }
+ };
+
+
+ _Api.registerPlural = _api_registerPlural = function ( pluralName, singularName, val ) {
+ _Api.register( pluralName, val );
+
+ _Api.register( singularName, function () {
+ var ret = val.apply( this, arguments );
+
+ if ( ret === this ) {
+ // Returned item is the API instance that was passed in, return it
+ return this;
+ }
+ else if ( ret instanceof _Api ) {
+ // New API instance returned, want the value from the first item
+ // in the returned array for the singular result.
+ return ret.length ?
+ $.isArray( ret[0] ) ?
+ new _Api( ret.context, ret[0] ) : // Array results are 'enhanced'
+ ret[0] :
+ undefined;
+ }
+
+ // Non-API return - just fire it back
+ return ret;
+ } );
};
/**
- * Check if a TABLE node is a DataTable table already or not.
- * @param {node} nTable The TABLE node to check if it is a DataTable or not (note that other
- * node types can be passed in, but will always return false).
- * @returns {boolean} true the table given is a DataTable, or false otherwise
+ * Selector for HTML tables. Apply the given selector to the give array of
+ * DataTables settings objects.
+ *
+ * @param {string|integer} [selector] jQuery selector string or integer
+ * @param {array} Array of DataTables settings objects to be filtered
+ * @return {array}
+ * @ignore
+ */
+ var __table_selector = function ( selector, a )
+ {
+ // Integer is used to pick out a table by index
+ if ( typeof selector === 'number' ) {
+ return [ a[ selector ] ];
+ }
+
+ // Perform a jQuery selector on the table nodes
+ var nodes = $.map( a, function (el, i) {
+ return el.nTable;
+ } );
+
+ return $(nodes)
+ .filter( selector )
+ .map( function (i) {
+ // Need to translate back from the table node to the settings
+ var idx = $.inArray( this, nodes );
+ return a[ idx ];
+ } )
+ .toArray();
+ };
+
+
+
+ /**
+ * Context selector for the API's context (i.e. the tables the API instance
+ * refers to.
+ *
+ * @name DataTable.Api#tables
+ * @param {string|integer} [selector] Selector to pick which tables the iterator
+ * should operate on. If not given, all tables in the current context are
+ * used. This can be given as a jQuery selector (for example `':gt(0)'`) to
+ * select multiple tables or as an integer to select a single table.
+ * @returns {DataTable.Api} Returns a new API instance if a selector is given.
+ */
+ _api_register( 'tables()', function ( selector ) {
+ // A new instance is created if there was a selector specified
+ return selector ?
+ new _Api( __table_selector( selector, this.context ) ) :
+ this;
+ } );
+
+
+ _api_register( 'table()', function ( selector ) {
+ var tables = this.tables( selector );
+ var ctx = tables.context;
+
+ // Truncate to the first matched table
+ return ctx.length ?
+ new _Api( ctx[0] ) :
+ tables;
+ } );
+
+
+ _api_registerPlural( 'tables().nodes()', 'table().node()' , function () {
+ return this.iterator( 'table', function ( ctx ) {
+ return ctx.nTable;
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'tables().body()', 'table().body()' , function () {
+ return this.iterator( 'table', function ( ctx ) {
+ return ctx.nTBody;
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'tables().header()', 'table().header()' , function () {
+ return this.iterator( 'table', function ( ctx ) {
+ return ctx.nTHead;
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'tables().footer()', 'table().footer()' , function () {
+ return this.iterator( 'table', function ( ctx ) {
+ return ctx.nTFoot;
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'tables().containers()', 'table().container()' , function () {
+ return this.iterator( 'table', function ( ctx ) {
+ return ctx.nTableWrapper;
+ }, 1 );
+ } );
+
+
+
+ /**
+ * Redraw the tables in the current context.
+ *
+ * @param {boolean} [reset=true] Reset (default) or hold the current paging
+ * position. A full re-sort and re-filter is performed when this method is
+ * called, which is why the pagination reset is the default action.
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'draw()', function ( resetPaging ) {
+ return this.iterator( 'table', function ( settings ) {
+ _fnReDraw( settings, resetPaging===false );
+ } );
+ } );
+
+
+
+ /**
+ * Get the current page index.
+ *
+ * @return {integer} Current page index (zero based)
+ *//**
+ * Set the current page.
+ *
+ * Note that if you attempt to show a page which does not exist, DataTables will
+ * not throw an error, but rather reset the paging.
+ *
+ * @param {integer|string} action The paging action to take. This can be one of:
+ * * `integer` - The page index to jump to
+ * * `string` - An action to take:
+ * * `first` - Jump to first page.
+ * * `next` - Jump to the next page
+ * * `previous` - Jump to previous page
+ * * `last` - Jump to the last page.
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'page()', function ( action ) {
+ if ( action === undefined ) {
+ return this.page.info().page; // not an expensive call
+ }
+
+ // else, have an action to take on all tables
+ return this.iterator( 'table', function ( settings ) {
+ _fnPageChange( settings, action );
+ } );
+ } );
+
+
+ /**
+ * Paging information for the first table in the current context.
+ *
+ * If you require paging information for another table, use the `table()` method
+ * with a suitable selector.
+ *
+ * @return {object} Object with the following properties set:
+ * * `page` - Current page index (zero based - i.e. the first page is `0`)
+ * * `pages` - Total number of pages
+ * * `start` - Display index for the first record shown on the current page
+ * * `end` - Display index for the last record shown on the current page
+ * * `length` - Display length (number of records). Note that generally `start
+ * + length = end`, but this is not always true, for example if there are
+ * only 2 records to show on the final page, with a length of 10.
+ * * `recordsTotal` - Full data set length
+ * * `recordsDisplay` - Data set length once the current filtering criterion
+ * are applied.
+ */
+ _api_register( 'page.info()', function ( action ) {
+ if ( this.context.length === 0 ) {
+ return undefined;
+ }
+
+ var
+ settings = this.context[0],
+ start = settings._iDisplayStart,
+ len = settings._iDisplayLength,
+ visRecords = settings.fnRecordsDisplay(),
+ all = len === -1;
+
+ return {
+ "page": all ? 0 : Math.floor( start / len ),
+ "pages": all ? 1 : Math.ceil( visRecords / len ),
+ "start": start,
+ "end": settings.fnDisplayEnd(),
+ "length": len,
+ "recordsTotal": settings.fnRecordsTotal(),
+ "recordsDisplay": visRecords
+ };
+ } );
+
+
+ /**
+ * Get the current page length.
+ *
+ * @return {integer} Current page length. Note `-1` indicates that all records
+ * are to be shown.
+ *//**
+ * Set the current page length.
+ *
+ * @param {integer} Page length to set. Use `-1` to show all records.
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'page.len()', function ( len ) {
+ // Note that we can't call this function 'length()' because `length`
+ // is a Javascript property of functions which defines how many arguments
+ // the function expects.
+ if ( len === undefined ) {
+ return this.context.length !== 0 ?
+ this.context[0]._iDisplayLength :
+ undefined;
+ }
+
+ // else, set the page length
+ return this.iterator( 'table', function ( settings ) {
+ _fnLengthChange( settings, len );
+ } );
+ } );
+
+
+
+ var __reload = function ( settings, holdPosition, callback ) {
+ // Use the draw event to trigger a callback
+ if ( callback ) {
+ var api = new _Api( settings );
+
+ api.one( 'draw', function () {
+ callback( api.ajax.json() );
+ } );
+ }
+
+ if ( _fnDataSource( settings ) == 'ssp' ) {
+ _fnReDraw( settings, holdPosition );
+ }
+ else {
+ // Trigger xhr
+ _fnProcessingDisplay( settings, true );
+
+ _fnBuildAjax( settings, [], function( json ) {
+ _fnClearTable( settings );
+
+ var data = _fnAjaxDataSrc( settings, json );
+ for ( var i=0, ien=data.length ; i<ien ; i++ ) {
+ _fnAddData( settings, data[i] );
+ }
+
+ _fnReDraw( settings, holdPosition );
+ _fnProcessingDisplay( settings, false );
+ } );
+ }
+ };
+
+
+ /**
+ * Get the JSON response from the last Ajax request that DataTables made to the
+ * server. Note that this returns the JSON from the first table in the current
+ * context.
+ *
+ * @return {object} JSON received from the server.
+ */
+ _api_register( 'ajax.json()', function () {
+ var ctx = this.context;
+
+ if ( ctx.length > 0 ) {
+ return ctx[0].json;
+ }
+
+ // else return undefined;
+ } );
+
+
+ /**
+ * Get the data submitted in the last Ajax request
+ */
+ _api_register( 'ajax.params()', function () {
+ var ctx = this.context;
+
+ if ( ctx.length > 0 ) {
+ return ctx[0].oAjaxData;
+ }
+
+ // else return undefined;
+ } );
+
+
+ /**
+ * Reload tables from the Ajax data source. Note that this function will
+ * automatically re-draw the table when the remote data has been loaded.
+ *
+ * @param {boolean} [reset=true] Reset (default) or hold the current paging
+ * position. A full re-sort and re-filter is performed when this method is
+ * called, which is why the pagination reset is the default action.
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'ajax.reload()', function ( callback, resetPaging ) {
+ return this.iterator( 'table', function (settings) {
+ __reload( settings, resetPaging===false, callback );
+ } );
+ } );
+
+
+ /**
+ * Get the current Ajax URL. Note that this returns the URL from the first
+ * table in the current context.
+ *
+ * @return {string} Current Ajax source URL
+ *//**
+ * Set the Ajax URL. Note that this will set the URL for all tables in the
+ * current context.
+ *
+ * @param {string} url URL to set.
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'ajax.url()', function ( url ) {
+ var ctx = this.context;
+
+ if ( url === undefined ) {
+ // get
+ if ( ctx.length === 0 ) {
+ return undefined;
+ }
+ ctx = ctx[0];
+
+ return ctx.ajax ?
+ $.isPlainObject( ctx.ajax ) ?
+ ctx.ajax.url :
+ ctx.ajax :
+ ctx.sAjaxSource;
+ }
+
+ // set
+ return this.iterator( 'table', function ( settings ) {
+ if ( $.isPlainObject( settings.ajax ) ) {
+ settings.ajax.url = url;
+ }
+ else {
+ settings.ajax = url;
+ }
+ // No need to consider sAjaxSource here since DataTables gives priority
+ // to `ajax` over `sAjaxSource`. So setting `ajax` here, renders any
+ // value of `sAjaxSource` redundant.
+ } );
+ } );
+
+
+ /**
+ * Load data from the newly set Ajax URL. Note that this method is only
+ * available when `ajax.url()` is used to set a URL. Additionally, this method
+ * has the same effect as calling `ajax.reload()` but is provided for
+ * convenience when setting a new URL. Like `ajax.reload()` it will
+ * automatically redraw the table once the remote data has been loaded.
+ *
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'ajax.url().load()', function ( callback, resetPaging ) {
+ // Same as a reload, but makes sense to present it for easy access after a
+ // url change
+ return this.iterator( 'table', function ( ctx ) {
+ __reload( ctx, resetPaging===false, callback );
+ } );
+ } );
+
+
+
+
+ var _selector_run = function ( type, selector, selectFn, settings, opts )
+ {
+ var
+ out = [], res,
+ a, i, ien, j, jen,
+ selectorType = typeof selector;
+
+ // Can't just check for isArray here, as an API or jQuery instance might be
+ // given with their array like look
+ if ( ! selector || selectorType === 'string' || selectorType === 'function' || selector.length === undefined ) {
+ selector = [ selector ];
+ }
+
+ for ( i=0, ien=selector.length ; i<ien ; i++ ) {
+ a = selector[i] && selector[i].split ?
+ selector[i].split(',') :
+ [ selector[i] ];
+
+ for ( j=0, jen=a.length ; j<jen ; j++ ) {
+ res = selectFn( typeof a[j] === 'string' ? $.trim(a[j]) : a[j] );
+
+ if ( res && res.length ) {
+ out.push.apply( out, res );
+ }
+ }
+ }
+
+ // selector extensions
+ var ext = _ext.selector[ type ];
+ if ( ext.length ) {
+ for ( i=0, ien=ext.length ; i<ien ; i++ ) {
+ out = ext[i]( settings, opts, out );
+ }
+ }
+
+ return out;
+ };
+
+
+ var _selector_opts = function ( opts )
+ {
+ if ( ! opts ) {
+ opts = {};
+ }
+
+ // Backwards compatibility for 1.9- which used the terminology filter rather
+ // than search
+ if ( opts.filter && opts.search === undefined ) {
+ opts.search = opts.filter;
+ }
+
+ return $.extend( {
+ search: 'none',
+ order: 'current',
+ page: 'all'
+ }, opts );
+ };
+
+
+ var _selector_first = function ( inst )
+ {
+ // Reduce the API instance to the first item found
+ for ( var i=0, ien=inst.length ; i<ien ; i++ ) {
+ if ( inst[i].length > 0 ) {
+ // Assign the first element to the first item in the instance
+ // and truncate the instance and context
+ inst[0] = inst[i];
+ inst[0].length = 1;
+ inst.length = 1;
+ inst.context = [ inst.context[i] ];
+
+ return inst;
+ }
+ }
+
+ // Not found - return an empty instance
+ inst.length = 0;
+ return inst;
+ };
+
+
+ var _selector_row_indexes = function ( settings, opts )
+ {
+ var
+ i, ien, tmp, a=[],
+ displayFiltered = settings.aiDisplay,
+ displayMaster = settings.aiDisplayMaster;
+
+ var
+ search = opts.search, // none, applied, removed
+ order = opts.order, // applied, current, index (original - compatibility with 1.9)
+ page = opts.page; // all, current
+
+ if ( _fnDataSource( settings ) == 'ssp' ) {
+ // In server-side processing mode, most options are irrelevant since
+ // rows not shown don't exist and the index order is the applied order
+ // Removed is a special case - for consistency just return an empty
+ // array
+ return search === 'removed' ?
+ [] :
+ _range( 0, displayMaster.length );
+ }
+ else if ( page == 'current' ) {
+ // Current page implies that order=current and fitler=applied, since it is
+ // fairly senseless otherwise, regardless of what order and search actually
+ // are
+ for ( i=settings._iDisplayStart, ien=settings.fnDisplayEnd() ; i<ien ; i++ ) {
+ a.push( displayFiltered[i] );
+ }
+ }
+ else if ( order == 'current' || order == 'applied' ) {
+ a = search == 'none' ?
+ displayMaster.slice() : // no search
+ search == 'applied' ?
+ displayFiltered.slice() : // applied search
+ $.map( displayMaster, function (el, i) { // removed search
+ return $.inArray( el, displayFiltered ) === -1 ? el : null;
+ } );
+ }
+ else if ( order == 'index' || order == 'original' ) {
+ for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
+ if ( search == 'none' ) {
+ a.push( i );
+ }
+ else { // applied | removed
+ tmp = $.inArray( i, displayFiltered );
+
+ if ((tmp === -1 && search == 'removed') ||
+ (tmp >= 0 && search == 'applied') )
+ {
+ a.push( i );
+ }
+ }
+ }
+ }
+
+ return a;
+ };
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Rows
+ *
+ * {} - no selector - use all available rows
+ * {integer} - row aoData index
+ * {node} - TR node
+ * {string} - jQuery selector to apply to the TR elements
+ * {array} - jQuery array of nodes, or simply an array of TR nodes
+ *
+ */
+
+
+ var __row_selector = function ( settings, selector, opts )
+ {
+ var run = function ( sel ) {
+ var selInt = _intVal( sel );
+ var i, ien;
+
+ // Short cut - selector is a number and no options provided (default is
+ // all records, so no need to check if the index is in there, since it
+ // must be - dev error if the index doesn't exist).
+ if ( selInt !== null && ! opts ) {
+ return [ selInt ];
+ }
+
+ var rows = _selector_row_indexes( settings, opts );
+
+ if ( selInt !== null && $.inArray( selInt, rows ) !== -1 ) {
+ // Selector - integer
+ return [ selInt ];
+ }
+ else if ( ! sel ) {
+ // Selector - none
+ return rows;
+ }
+
+ // Selector - function
+ if ( typeof sel === 'function' ) {
+ return $.map( rows, function (idx) {
+ var row = settings.aoData[ idx ];
+ return sel( idx, row._aData, row.nTr ) ? idx : null;
+ } );
+ }
+
+ // Get nodes in the order from the `rows` array with null values removed
+ var nodes = _removeEmpty(
+ _pluck_order( settings.aoData, rows, 'nTr' )
+ );
+
+ // Selector - node
+ if ( sel.nodeName ) {
+ if ( $.inArray( sel, nodes ) !== -1 ) {
+ return [ sel._DT_RowIndex ]; // sel is a TR node that is in the table
+ // and DataTables adds a prop for fast lookup
+ }
+ }
+
+ // Selector - jQuery selector string, array of nodes or jQuery object/
+ // As jQuery's .filter() allows jQuery objects to be passed in filter,
+ // it also allows arrays, so this will cope with all three options
+ return $(nodes)
+ .filter( sel )
+ .map( function () {
+ return this._DT_RowIndex;
+ } )
+ .toArray();
+ };
+
+ return _selector_run( 'row', selector, run, settings, opts );
+ };
+
+
+ _api_register( 'rows()', function ( selector, opts ) {
+ // argument shifting
+ if ( selector === undefined ) {
+ selector = '';
+ }
+ else if ( $.isPlainObject( selector ) ) {
+ opts = selector;
+ selector = '';
+ }
+
+ opts = _selector_opts( opts );
+
+ var inst = this.iterator( 'table', function ( settings ) {
+ return __row_selector( settings, selector, opts );
+ }, 1 );
+
+ // Want argument shifting here and in __row_selector?
+ inst.selector.rows = selector;
+ inst.selector.opts = opts;
+
+ return inst;
+ } );
+
+ _api_register( 'rows().nodes()', function () {
+ return this.iterator( 'row', function ( settings, row ) {
+ return settings.aoData[ row ].nTr || undefined;
+ }, 1 );
+ } );
+
+ _api_register( 'rows().data()', function () {
+ return this.iterator( true, 'rows', function ( settings, rows ) {
+ return _pluck_order( settings.aoData, rows, '_aData' );
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'rows().cache()', 'row().cache()', function ( type ) {
+ return this.iterator( 'row', function ( settings, row ) {
+ var r = settings.aoData[ row ];
+ return type === 'search' ? r._aFilterData : r._aSortData;
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'rows().invalidate()', 'row().invalidate()', function ( src ) {
+ return this.iterator( 'row', function ( settings, row ) {
+ _fnInvalidate( settings, row, src );
+ } );
+ } );
+
+ _api_registerPlural( 'rows().indexes()', 'row().index()', function () {
+ return this.iterator( 'row', function ( settings, row ) {
+ return row;
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'rows().remove()', 'row().remove()', function () {
+ var that = this;
+
+ return this.iterator( 'row', function ( settings, row, thatIdx ) {
+ var data = settings.aoData;
+
+ data.splice( row, 1 );
+
+ // Update the _DT_RowIndex parameter on all rows in the table
+ for ( var i=0, ien=data.length ; i<ien ; i++ ) {
+ if ( data[i].nTr !== null ) {
+ data[i].nTr._DT_RowIndex = i;
+ }
+ }
+
+ // Remove the target row from the search array
+ var displayIndex = $.inArray( row, settings.aiDisplay );
+
+ // Delete from the display arrays
+ _fnDeleteIndex( settings.aiDisplayMaster, row );
+ _fnDeleteIndex( settings.aiDisplay, row );
+ _fnDeleteIndex( that[ thatIdx ], row, false ); // maintain local indexes
+
+ // Check for an 'overflow' they case for displaying the table
+ _fnLengthOverflow( settings );
+ } );
+ } );
+
+
+ _api_register( 'rows.add()', function ( rows ) {
+ var newRows = this.iterator( 'table', function ( settings ) {
+ var row, i, ien;
+ var out = [];
+
+ for ( i=0, ien=rows.length ; i<ien ; i++ ) {
+ row = rows[i];
+
+ if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) {
+ out.push( _fnAddTr( settings, row )[0] );
+ }
+ else {
+ out.push( _fnAddData( settings, row ) );
+ }
+ }
+
+ return out;
+ }, 1 );
+
+ // Return an Api.rows() extended instance, so rows().nodes() etc can be used
+ var modRows = this.rows( -1 );
+ modRows.pop();
+ modRows.push.apply( modRows, newRows.toArray() );
+
+ return modRows;
+ } );
+
+
+
+
+
+ /**
+ *
+ */
+ _api_register( 'row()', function ( selector, opts ) {
+ return _selector_first( this.rows( selector, opts ) );
+ } );
+
+
+ _api_register( 'row().data()', function ( data ) {
+ var ctx = this.context;
+
+ if ( data === undefined ) {
+ // Get
+ return ctx.length && this.length ?
+ ctx[0].aoData[ this[0] ]._aData :
+ undefined;
+ }
+
+ // Set
+ ctx[0].aoData[ this[0] ]._aData = data;
+
+ // Automatically invalidate
+ _fnInvalidate( ctx[0], this[0], 'data' );
+
+ return this;
+ } );
+
+
+ _api_register( 'row().node()', function () {
+ var ctx = this.context;
+
+ return ctx.length && this.length ?
+ ctx[0].aoData[ this[0] ].nTr || null :
+ null;
+ } );
+
+
+ _api_register( 'row.add()', function ( row ) {
+ // Allow a jQuery object to be passed in - only a single row is added from
+ // it though - the first element in the set
+ if ( row instanceof $ && row.length ) {
+ row = row[0];
+ }
+
+ var rows = this.iterator( 'table', function ( settings ) {
+ if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) {
+ return _fnAddTr( settings, row )[0];
+ }
+ return _fnAddData( settings, row );
+ } );
+
+ // Return an Api.rows() extended instance, with the newly added row selected
+ return this.row( rows[0] );
+ } );
+
+
+
+ var __details_add = function ( ctx, row, data, klass )
+ {
+ // Convert to array of TR elements
+ var rows = [];
+ var addRow = function ( r, k ) {
+ // Recursion to allow for arrays of jQuery objects
+ if ( $.isArray( r ) || r instanceof $ ) {
+ for ( var i=0, ien=r.length ; i<ien ; i++ ) {
+ addRow( r[i], k );
+ }
+ return;
+ }
+
+ // If we get a TR element, then just add it directly - up to the dev
+ // to add the correct number of columns etc
+ if ( r.nodeName && r.nodeName.toLowerCase() === 'tr' ) {
+ rows.push( r );
+ }
+ else {
+ // Otherwise create a row with a wrapper
+ var created = $('<tr><td/></tr>').addClass( k );
+ $('td', created)
+ .addClass( k )
+ .html( r )
+ [0].colSpan = _fnVisbleColumns( ctx );
+
+ rows.push( created[0] );
+ }
+ };
+
+ addRow( data, klass );
+
+ if ( row._details ) {
+ row._details.remove();
+ }
+
+ row._details = $(rows);
+
+ // If the children were already shown, that state should be retained
+ if ( row._detailsShow ) {
+ row._details.insertAfter( row.nTr );
+ }
+ };
+
+
+ var __details_remove = function ( api, idx )
+ {
+ var ctx = api.context;
+
+ if ( ctx.length ) {
+ var row = ctx[0].aoData[ idx !== undefined ? idx : api[0] ];
+
+ if ( row._details ) {
+ row._details.remove();
+
+ row._detailsShow = undefined;
+ row._details = undefined;
+ }
+ }
+ };
+
+
+ var __details_display = function ( api, show ) {
+ var ctx = api.context;
+
+ if ( ctx.length && api.length ) {
+ var row = ctx[0].aoData[ api[0] ];
+
+ if ( row._details ) {
+ row._detailsShow = show;
+
+ if ( show ) {
+ row._details.insertAfter( row.nTr );
+ }
+ else {
+ row._details.detach();
+ }
+
+ __details_events( ctx[0] );
+ }
+ }
+ };
+
+
+ var __details_events = function ( settings )
+ {
+ var api = new _Api( settings );
+ var namespace = '.dt.DT_details';
+ var drawEvent = 'draw'+namespace;
+ var colvisEvent = 'column-visibility'+namespace;
+ var destroyEvent = 'destroy'+namespace;
+ var data = settings.aoData;
+
+ api.off( drawEvent +' '+ colvisEvent +' '+ destroyEvent );
+
+ if ( _pluck( data, '_details' ).length > 0 ) {
+ // On each draw, insert the required elements into the document
+ api.on( drawEvent, function ( e, ctx ) {
+ if ( settings !== ctx ) {
+ return;
+ }
+
+ api.rows( {page:'current'} ).eq(0).each( function (idx) {
+ // Internal data grab
+ var row = data[ idx ];
+
+ if ( row._detailsShow ) {
+ row._details.insertAfter( row.nTr );
+ }
+ } );
+ } );
+
+ // Column visibility change - update the colspan
+ api.on( colvisEvent, function ( e, ctx, idx, vis ) {
+ if ( settings !== ctx ) {
+ return;
+ }
+
+ // Update the colspan for the details rows (note, only if it already has
+ // a colspan)
+ var row, visible = _fnVisbleColumns( ctx );
+
+ for ( var i=0, ien=data.length ; i<ien ; i++ ) {
+ row = data[i];
+
+ if ( row._details ) {
+ row._details.children('td[colspan]').attr('colspan', visible );
+ }
+ }
+ } );
+
+ // Table destroyed - nuke any child rows
+ api.on( destroyEvent, function ( e, ctx ) {
+ if ( settings !== ctx ) {
+ return;
+ }
+
+ for ( var i=0, ien=data.length ; i<ien ; i++ ) {
+ if ( data[i]._details ) {
+ __details_remove( api, i );
+ }
+ }
+ } );
+ }
+ };
+
+ // Strings for the method names to help minification
+ var _emp = '';
+ var _child_obj = _emp+'row().child';
+ var _child_mth = _child_obj+'()';
+
+ // data can be:
+ // tr
+ // string
+ // jQuery or array of any of the above
+ _api_register( _child_mth, function ( data, klass ) {
+ var ctx = this.context;
+
+ if ( data === undefined ) {
+ // get
+ return ctx.length && this.length ?
+ ctx[0].aoData[ this[0] ]._details :
+ undefined;
+ }
+ else if ( data === true ) {
+ // show
+ this.child.show();
+ }
+ else if ( data === false ) {
+ // remove
+ __details_remove( this );
+ }
+ else if ( ctx.length && this.length ) {
+ // set
+ __details_add( ctx[0], ctx[0].aoData[ this[0] ], data, klass );
+ }
+
+ return this;
+ } );
+
+
+ _api_register( [
+ _child_obj+'.show()',
+ _child_mth+'.show()' // only when `child()` was called with parameters (without
+ ], function ( show ) { // it returns an object and this method is not executed)
+ __details_display( this, true );
+ return this;
+ } );
+
+
+ _api_register( [
+ _child_obj+'.hide()',
+ _child_mth+'.hide()' // only when `child()` was called with parameters (without
+ ], function () { // it returns an object and this method is not executed)
+ __details_display( this, false );
+ return this;
+ } );
+
+
+ _api_register( [
+ _child_obj+'.remove()',
+ _child_mth+'.remove()' // only when `child()` was called with parameters (without
+ ], function () { // it returns an object and this method is not executed)
+ __details_remove( this );
+ return this;
+ } );
+
+
+ _api_register( _child_obj+'.isShown()', function () {
+ var ctx = this.context;
+
+ if ( ctx.length && this.length ) {
+ // _detailsShown as false or undefined will fall through to return false
+ return ctx[0].aoData[ this[0] ]._detailsShow || false;
+ }
+ return false;
+ } );
+
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Columns
+ *
+ * {integer} - column index (>=0 count from left, <0 count from right)
+ * "{integer}:visIdx" - visible column index (i.e. translate to column index) (>=0 count from left, <0 count from right)
+ * "{integer}:visible" - alias for {integer}:visIdx (>=0 count from left, <0 count from right)
+ * "{string}:name" - column name
+ * "{string}" - jQuery selector on column header nodes
+ *
+ */
+
+ // can be an array of these items, comma separated list, or an array of comma
+ // separated lists
+
+ var __re_column_selector = /^(.+):(name|visIdx|visible)$/;
+
+
+ // r1 and r2 are redundant - but it means that the parameters match for the
+ // iterator callback in columns().data()
+ var __columnData = function ( settings, column, r1, r2, rows ) {
+ var a = [];
+ for ( var row=0, ien=rows.length ; row<ien ; row++ ) {
+ a.push( _fnGetCellData( settings, rows[row], column ) );
+ }
+ return a;
+ };
+
+
+ var __column_selector = function ( settings, selector, opts )
+ {
+ var
+ columns = settings.aoColumns,
+ names = _pluck( columns, 'sName' ),
+ nodes = _pluck( columns, 'nTh' );
+
+ var run = function ( s ) {
+ var selInt = _intVal( s );
+
+ // Selector - all
+ if ( s === '' ) {
+ return _range( columns.length );
+ }
+
+ // Selector - index
+ if ( selInt !== null ) {
+ return [ selInt >= 0 ?
+ selInt : // Count from left
+ columns.length + selInt // Count from right (+ because its a negative value)
+ ];
+ }
+
+ // Selector = function
+ if ( typeof s === 'function' ) {
+ var rows = _selector_row_indexes( settings, opts );
+
+ return $.map( columns, function (col, idx) {
+ return s(
+ idx,
+ __columnData( settings, idx, 0, 0, rows ),
+ nodes[ idx ]
+ ) ? idx : null;
+ } );
+ }
+
+ // jQuery or string selector
+ var match = typeof s === 'string' ?
+ s.match( __re_column_selector ) :
+ '';
+
+ if ( match ) {
+ switch( match[2] ) {
+ case 'visIdx':
+ case 'visible':
+ var idx = parseInt( match[1], 10 );
+ // Visible index given, convert to column index
+ if ( idx < 0 ) {
+ // Counting from the right
+ var visColumns = $.map( columns, function (col,i) {
+ return col.bVisible ? i : null;
+ } );
+ return [ visColumns[ visColumns.length + idx ] ];
+ }
+ // Counting from the left
+ return [ _fnVisibleToColumnIndex( settings, idx ) ];
+
+ case 'name':
+ // match by name. `names` is column index complete and in order
+ return $.map( names, function (name, i) {
+ return name === match[1] ? i : null;
+ } );
+ }
+ }
+ else {
+ // jQuery selector on the TH elements for the columns
+ return $( nodes )
+ .filter( s )
+ .map( function () {
+ return $.inArray( this, nodes ); // `nodes` is column index complete and in order
+ } )
+ .toArray();
+ }
+ };
+
+ return _selector_run( 'column', selector, run, settings, opts );
+ };
+
+
+ var __setColumnVis = function ( settings, column, vis, recalc ) {
+ var
+ cols = settings.aoColumns,
+ col = cols[ column ],
+ data = settings.aoData,
+ row, cells, i, ien, tr;
+
+ // Get
+ if ( vis === undefined ) {
+ return col.bVisible;
+ }
+
+ // Set
+ // No change
+ if ( col.bVisible === vis ) {
+ return;
+ }
+
+ if ( vis ) {
+ // Insert column
+ // Need to decide if we should use appendChild or insertBefore
+ var insertBefore = $.inArray( true, _pluck(cols, 'bVisible'), column+1 );
+
+ for ( i=0, ien=data.length ; i<ien ; i++ ) {
+ tr = data[i].nTr;
+ cells = data[i].anCells;
+
+ if ( tr ) {
+ // insertBefore can act like appendChild if 2nd arg is null
+ tr.insertBefore( cells[ column ], cells[ insertBefore ] || null );
+ }
+ }
+ }
+ else {
+ // Remove column
+ $( _pluck( settings.aoData, 'anCells', column ) ).detach();
+ }
+
+ // Common actions
+ col.bVisible = vis;
+ _fnDrawHead( settings, settings.aoHeader );
+ _fnDrawHead( settings, settings.aoFooter );
+
+ if ( recalc === undefined || recalc ) {
+ // Automatically adjust column sizing
+ _fnAdjustColumnSizing( settings );
+
+ // Realign columns for scrolling
+ if ( settings.oScroll.sX || settings.oScroll.sY ) {
+ _fnScrollDraw( settings );
+ }
+ }
+
+ _fnCallbackFire( settings, null, 'column-visibility', [settings, column, vis] );
+
+ _fnSaveState( settings );
+ };
+
+
+ _api_register( 'columns()', function ( selector, opts ) {
+ // argument shifting
+ if ( selector === undefined ) {
+ selector = '';
+ }
+ else if ( $.isPlainObject( selector ) ) {
+ opts = selector;
+ selector = '';
+ }
+
+ opts = _selector_opts( opts );
+
+ var inst = this.iterator( 'table', function ( settings ) {
+ return __column_selector( settings, selector, opts );
+ }, 1 );
+
+ // Want argument shifting here and in _row_selector?
+ inst.selector.cols = selector;
+ inst.selector.opts = opts;
+
+ return inst;
+ } );
+
+ _api_registerPlural( 'columns().header()', 'column().header()', function ( selector, opts ) {
+ return this.iterator( 'column', function ( settings, column ) {
+ return settings.aoColumns[column].nTh;
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'columns().footer()', 'column().footer()', function ( selector, opts ) {
+ return this.iterator( 'column', function ( settings, column ) {
+ return settings.aoColumns[column].nTf;
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'columns().data()', 'column().data()', function () {
+ return this.iterator( 'column-rows', __columnData, 1 );
+ } );
+
+ _api_registerPlural( 'columns().dataSrc()', 'column().dataSrc()', function () {
+ return this.iterator( 'column', function ( settings, column ) {
+ return settings.aoColumns[column].mData;
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'columns().cache()', 'column().cache()', function ( type ) {
+ return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) {
+ return _pluck_order( settings.aoData, rows,
+ type === 'search' ? '_aFilterData' : '_aSortData', column
+ );
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'columns().nodes()', 'column().nodes()', function () {
+ return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) {
+ return _pluck_order( settings.aoData, rows, 'anCells', column ) ;
+ }, 1 );
+ } );
+
+ _api_registerPlural( 'columns().visible()', 'column().visible()', function ( vis, calc ) {
+ return this.iterator( 'column', function ( settings, column ) {
+ if ( vis === undefined ) {
+ return settings.aoColumns[ column ].bVisible;
+ } // else
+ __setColumnVis( settings, column, vis, calc );
+ } );
+ } );
+
+ _api_registerPlural( 'columns().indexes()', 'column().index()', function ( type ) {
+ return this.iterator( 'column', function ( settings, column ) {
+ return type === 'visible' ?
+ _fnColumnIndexToVisible( settings, column ) :
+ column;
+ }, 1 );
+ } );
+
+ _api_register( 'columns.adjust()', function () {
+ return this.iterator( 'table', function ( settings ) {
+ _fnAdjustColumnSizing( settings );
+ }, 1 );
+ } );
+
+ _api_register( 'column.index()', function ( type, idx ) {
+ if ( this.context.length !== 0 ) {
+ var ctx = this.context[0];
+
+ if ( type === 'fromVisible' || type === 'toData' ) {
+ return _fnVisibleToColumnIndex( ctx, idx );
+ }
+ else if ( type === 'fromData' || type === 'toVisible' ) {
+ return _fnColumnIndexToVisible( ctx, idx );
+ }
+ }
+ } );
+
+ _api_register( 'column()', function ( selector, opts ) {
+ return _selector_first( this.columns( selector, opts ) );
+ } );
+
+
+
+
+ var __cell_selector = function ( settings, selector, opts )
+ {
+ var data = settings.aoData;
+ var rows = _selector_row_indexes( settings, opts );
+ var cells = _removeEmpty( _pluck_order( data, rows, 'anCells' ) );
+ var allCells = $( [].concat.apply([], cells) );
+ var row;
+ var columns = settings.aoColumns.length;
+ var a, i, ien, j, o, host;
+
+ var run = function ( s ) {
+ var fnSelector = typeof s === 'function';
+
+ if ( s === null || s === undefined || fnSelector ) {
+ // All cells and function selectors
+ a = [];
+
+ for ( i=0, ien=rows.length ; i<ien ; i++ ) {
+ row = rows[i];
+
+ for ( j=0 ; j<columns ; j++ ) {
+ o = {
+ row: row,
+ column: j
+ };
+
+ if ( fnSelector ) {
+ // Selector - function
+ host = settings.aoData[ row ];
+
+ if ( s( o, _fnGetCellData(settings, row, j), host.anCells ? host.anCells[j] : null ) ) {
+ a.push( o );
+ }
+ }
+ else {
+ // Selector - all
+ a.push( o );
+ }
+ }
+ }
+
+ return a;
+ }
+
+ // Selector - index
+ if ( $.isPlainObject( s ) ) {
+ return [s];
+ }
+
+ // Selector - jQuery filtered cells
+ return allCells
+ .filter( s )
+ .map( function (i, el) {
+ row = el.parentNode._DT_RowIndex;
+
+ return {
+ row: row,
+ column: $.inArray( el, data[ row ].anCells )
+ };
+ } )
+ .toArray();
+ };
+
+ return _selector_run( 'cell', selector, run, settings, opts );
+ };
+
+
+
+
+ _api_register( 'cells()', function ( rowSelector, columnSelector, opts ) {
+ // Argument shifting
+ if ( $.isPlainObject( rowSelector ) ) {
+ // Indexes
+ if ( rowSelector.row === undefined ) {
+ // Selector options in first parameter
+ opts = rowSelector;
+ rowSelector = null;
+ }
+ else {
+ // Cell index objects in first parameter
+ opts = columnSelector;
+ columnSelector = null;
+ }
+ }
+ if ( $.isPlainObject( columnSelector ) ) {
+ opts = columnSelector;
+ columnSelector = null;
+ }
+
+ // Cell selector
+ if ( columnSelector === null || columnSelector === undefined ) {
+ return this.iterator( 'table', function ( settings ) {
+ return __cell_selector( settings, rowSelector, _selector_opts( opts ) );
+ } );
+ }
+
+ // Row + column selector
+ var columns = this.columns( columnSelector, opts );
+ var rows = this.rows( rowSelector, opts );
+ var a, i, ien, j, jen;
+
+ var cells = this.iterator( 'table', function ( settings, idx ) {
+ a = [];
+
+ for ( i=0, ien=rows[idx].length ; i<ien ; i++ ) {
+ for ( j=0, jen=columns[idx].length ; j<jen ; j++ ) {
+ a.push( {
+ row: rows[idx][i],
+ column: columns[idx][j]
+ } );
+ }
+ }
+
+ return a;
+ }, 1 );
+
+ $.extend( cells.selector, {
+ cols: columnSelector,
+ rows: rowSelector,
+ opts: opts
+ } );
+
+ return cells;
+ } );
+
+
+ _api_registerPlural( 'cells().nodes()', 'cell().node()', function () {
+ return this.iterator( 'cell', function ( settings, row, column ) {
+ var cells = settings.aoData[ row ].anCells;
+ return cells ?
+ cells[ column ] :
+ undefined;
+ }, 1 );
+ } );
+
+
+ _api_register( 'cells().data()', function () {
+ return this.iterator( 'cell', function ( settings, row, column ) {
+ return _fnGetCellData( settings, row, column );
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'cells().cache()', 'cell().cache()', function ( type ) {
+ type = type === 'search' ? '_aFilterData' : '_aSortData';
+
+ return this.iterator( 'cell', function ( settings, row, column ) {
+ return settings.aoData[ row ][ type ][ column ];
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'cells().render()', 'cell().render()', function ( type ) {
+ return this.iterator( 'cell', function ( settings, row, column ) {
+ return _fnGetCellData( settings, row, column, type );
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'cells().indexes()', 'cell().index()', function () {
+ return this.iterator( 'cell', function ( settings, row, column ) {
+ return {
+ row: row,
+ column: column,
+ columnVisible: _fnColumnIndexToVisible( settings, column )
+ };
+ }, 1 );
+ } );
+
+
+ _api_registerPlural( 'cells().invalidate()', 'cell().invalidate()', function ( src ) {
+ return this.iterator( 'cell', function ( settings, row, column ) {
+ _fnInvalidate( settings, row, src, column );
+ } );
+ } );
+
+
+
+ _api_register( 'cell()', function ( rowSelector, columnSelector, opts ) {
+ return _selector_first( this.cells( rowSelector, columnSelector, opts ) );
+ } );
+
+
+ _api_register( 'cell().data()', function ( data ) {
+ var ctx = this.context;
+ var cell = this[0];
+
+ if ( data === undefined ) {
+ // Get
+ return ctx.length && cell.length ?
+ _fnGetCellData( ctx[0], cell[0].row, cell[0].column ) :
+ undefined;
+ }
+
+ // Set
+ _fnSetCellData( ctx[0], cell[0].row, cell[0].column, data );
+ _fnInvalidate( ctx[0], cell[0].row, 'data', cell[0].column );
+
+ return this;
+ } );
+
+
+
+ /**
+ * Get current ordering (sorting) that has been applied to the table.
+ *
+ * @returns {array} 2D array containing the sorting information for the first
+ * table in the current context. Each element in the parent array represents
+ * a column being sorted upon (i.e. multi-sorting with two columns would have
+ * 2 inner arrays). The inner arrays may have 2 or 3 elements. The first is
+ * the column index that the sorting condition applies to, the second is the
+ * direction of the sort (`desc` or `asc`) and, optionally, the third is the
+ * index of the sorting order from the `column.sorting` initialisation array.
+ *//**
+ * Set the ordering for the table.
+ *
+ * @param {integer} order Column index to sort upon.
+ * @param {string} direction Direction of the sort to be applied (`asc` or `desc`)
+ * @returns {DataTables.Api} this
+ *//**
+ * Set the ordering for the table.
+ *
+ * @param {array} order 1D array of sorting information to be applied.
+ * @param {array} [...] Optional additional sorting conditions
+ * @returns {DataTables.Api} this
+ *//**
+ * Set the ordering for the table.
+ *
+ * @param {array} order 2D array of sorting information to be applied.
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'order()', function ( order, dir ) {
+ var ctx = this.context;
+
+ if ( order === undefined ) {
+ // get
+ return ctx.length !== 0 ?
+ ctx[0].aaSorting :
+ undefined;
+ }
+
+ // set
+ if ( typeof order === 'number' ) {
+ // Simple column / direction passed in
+ order = [ [ order, dir ] ];
+ }
+ else if ( ! $.isArray( order[0] ) ) {
+ // Arguments passed in (list of 1D arrays)
+ order = Array.prototype.slice.call( arguments );
+ }
+ // otherwise a 2D array was passed in
+
+ return this.iterator( 'table', function ( settings ) {
+ settings.aaSorting = order.slice();
+ } );
+ } );
+
+
+ /**
+ * Attach a sort listener to an element for a given column
+ *
+ * @param {node|jQuery|string} node Identifier for the element(s) to attach the
+ * listener to. This can take the form of a single DOM node, a jQuery
+ * collection of nodes or a jQuery selector which will identify the node(s).
+ * @param {integer} column the column that a click on this node will sort on
+ * @param {function} [callback] callback function when sort is run
+ * @returns {DataTables.Api} this
+ */
+ _api_register( 'order.listener()', function ( node, column, callback ) {
+ return this.iterator( 'table', function ( settings ) {
+ _fnSortAttachListener( settings, node, column, callback );
+ } );
+ } );
+
+
+ // Order by the selected column(s)
+ _api_register( [
+ 'columns().order()',
+ 'column().order()'
+ ], function ( dir ) {
+ var that = this;
+
+ return this.iterator( 'table', function ( settings, i ) {
+ var sort = [];
+
+ $.each( that[i], function (j, col) {
+ sort.push( [ col, dir ] );
+ } );
+
+ settings.aaSorting = sort;
+ } );
+ } );
+
+
+
+ _api_register( 'search()', function ( input, regex, smart, caseInsen ) {
+ var ctx = this.context;
+
+ if ( input === undefined ) {
+ // get
+ return ctx.length !== 0 ?
+ ctx[0].oPreviousSearch.sSearch :
+ undefined;
+ }
+
+ // set
+ return this.iterator( 'table', function ( settings ) {
+ if ( ! settings.oFeatures.bFilter ) {
+ return;
+ }
+
+ _fnFilterComplete( settings, $.extend( {}, settings.oPreviousSearch, {
+ "sSearch": input+"",
+ "bRegex": regex === null ? false : regex,
+ "bSmart": smart === null ? true : smart,
+ "bCaseInsensitive": caseInsen === null ? true : caseInsen
+ } ), 1 );
+ } );
+ } );
+
+
+ _api_registerPlural(
+ 'columns().search()',
+ 'column().search()',
+ function ( input, regex, smart, caseInsen ) {
+ return this.iterator( 'column', function ( settings, column ) {
+ var preSearch = settings.aoPreSearchCols;
+
+ if ( input === undefined ) {
+ // get
+ return preSearch[ column ].sSearch;
+ }
+
+ // set
+ if ( ! settings.oFeatures.bFilter ) {
+ return;
+ }
+
+ $.extend( preSearch[ column ], {
+ "sSearch": input+"",
+ "bRegex": regex === null ? false : regex,
+ "bSmart": smart === null ? true : smart,
+ "bCaseInsensitive": caseInsen === null ? true : caseInsen
+ } );
+
+ _fnFilterComplete( settings, settings.oPreviousSearch, 1 );
+ } );
+ }
+ );
+
+ /*
+ * State API methods
+ */
+
+ _api_register( 'state()', function () {
+ return this.context.length ?
+ this.context[0].oSavedState :
+ null;
+ } );
+
+
+ _api_register( 'state.clear()', function () {
+ return this.iterator( 'table', function ( settings ) {
+ // Save an empty object
+ settings.fnStateSaveCallback.call( settings.oInstance, settings, {} );
+ } );
+ } );
+
+
+ _api_register( 'state.loaded()', function () {
+ return this.context.length ?
+ this.context[0].oLoadedState :
+ null;
+ } );
+
+
+ _api_register( 'state.save()', function () {
+ return this.iterator( 'table', function ( settings ) {
+ _fnSaveState( settings );
+ } );
+ } );
+
+
+
+ /**
+ * Provide a common method for plug-ins to check the version of DataTables being
+ * used, in order to ensure compatibility.
+ *
+ * @param {string} version Version string to check for, in the format "X.Y.Z".
+ * Note that the formats "X" and "X.Y" are also acceptable.
+ * @returns {boolean} true if this version of DataTables is greater or equal to
+ * the required version, or false if this version of DataTales is not
+ * suitable
* @static
* @dtopt API-Static
*
* @example
- * var ex = document.getElementById('example');
- * if ( ! $.fn.DataTable.fnIsDataTable( ex ) ) {
- * $(ex).dataTable();
- * }
+ * alert( $.fn.dataTable.versionCheck( '1.9.0' ) );
*/
- DataTable.fnIsDataTable = function ( nTable )
+ DataTable.versionCheck = DataTable.fnVersionCheck = function( version )
{
- var o = DataTable.settings;
+ var aThis = DataTable.version.split('.');
+ var aThat = version.split('.');
+ var iThis, iThat;
- for ( var i=0 ; i<o.length ; i++ )
- {
- if ( o[i].nTable === nTable || o[i].nScrollHead === nTable || o[i].nScrollFoot === nTable )
- {
- return true;
+ for ( var i=0, iLen=aThat.length ; i<iLen ; i++ ) {
+ iThis = parseInt( aThis[i], 10 ) || 0;
+ iThat = parseInt( aThat[i], 10 ) || 0;
+
+ // Parts are the same, keep comparing
+ if (iThis === iThat) {
+ continue;
}
+
+ // Parts are different, return immediately
+ return iThis > iThat;
}
- return false;
+ return true;
};
/**
- * Get all DataTable tables that have been initialised - optionally you can select to
- * get only currently visible tables.
- * @param {boolean} [bVisible=false] Flag to indicate if you want all (default) or
- * visible tables only.
- * @returns {array} Array of TABLE nodes (not DataTable instances) which are DataTables
+ * Check if a `<table>` node is a DataTable table already or not.
+ *
+ * @param {node|jquery|string} table Table node, jQuery object or jQuery
+ * selector for the table to test. Note that if more than more than one
+ * table is passed on, only the first will be checked
+ * @returns {boolean} true the table given is a DataTable, or false otherwise
* @static
* @dtopt API-Static
*
* @example
- * var table = $.fn.dataTable.fnTables(true);
- * if ( table.length > 0 ) {
- * $(table).dataTable().fnAdjustColumnSizing();
+ * if ( ! $.fn.DataTable.isDataTable( '#example' ) ) {
+ * $('#example').dataTable();
* }
*/
- DataTable.fnTables = function ( bVisible )
+ DataTable.isDataTable = DataTable.fnIsDataTable = function ( table )
{
- var out = [];
+ var t = $(table).get(0);
+ var is = false;
- jQuery.each( DataTable.settings, function (i, o) {
- if ( !bVisible || (bVisible === true && $(o.nTable).is(':visible')) )
- {
- out.push( o.nTable );
+ $.each( DataTable.settings, function (i, o) {
+ var head = o.nScrollHead ? $('table', o.nScrollHead)[0] : null;
+ var foot = o.nScrollFoot ? $('table', o.nScrollFoot)[0] : null;
+
+ if ( o.nTable === t || head === t || foot === t ) {
+ is = true;
}
} );
- return out;
+ return is;
};
-
- /**
- * Version string for plug-ins to check compatibility. Allowed format is
- * a.b.c.d.e where: a:int, b:int, c:int, d:string(dev|beta), e:int. d and
- * e are optional
- * @member
- * @type string
- * @default Version number
- */
- DataTable.version = "1.9.4";
-
- /**
- * Private data store, containing all of the settings objects that are created for the
- * tables on a given page.
- *
- * Note that the <i>DataTable.settings</i> object is aliased to <i>jQuery.fn.dataTableExt</i>
- * through which it may be accessed and manipulated, or <i>jQuery.fn.dataTable.settings</i>.
- * @member
- * @type array
- * @default []
- * @private
- */
- DataTable.settings = [];
-
+
/**
- * Object models container, for the various models that DataTables has available
- * to it. These models define the objects that are used to hold the active state
- * and configuration of the table.
- * @namespace
+ * Get all DataTable tables that have been initialised - optionally you can
+ * select to get only currently visible tables.
+ *
+ * @param {boolean} [visible=false] Flag to indicate if you want all (default)
+ * or visible tables only.
+ * @returns {array} Array of `table` nodes (not DataTable instances) which are
+ * DataTables
+ * @static
+ * @dtopt API-Static
+ *
+ * @example
+ * $.each( $.fn.dataTable.tables(true), function () {
+ * $(table).DataTable().columns.adjust();
+ * } );
*/
- DataTable.models = {};
+ DataTable.tables = DataTable.fnTables = function ( visible )
+ {
+ return $.map( DataTable.settings, function (o) {
+ if ( !visible || (visible && $(o.nTable).is(':visible')) ) {
+ return o.nTable;
+ }
+ } );
+ };
/**
- * DataTables extension options and plug-ins. This namespace acts as a collection "area"
- * for plug-ins that can be used to extend the default DataTables behaviour - indeed many
- * of the build in methods use this method to provide their own capabilities (sorting methods
- * for example).
+ * DataTables utility methods
*
- * Note that this namespace is aliased to jQuery.fn.dataTableExt so it can be readily accessed
- * and modified by plug-ins.
+ * This namespace provides helper methods that DataTables uses internally to
+ * create a DataTable, but which are not exclusively used only for DataTables.
+ * These methods can be used by extension authors to save the duplication of
+ * code.
+ *
* @namespace
*/
- DataTable.models.ext = {
+ DataTable.util = {
/**
- * Plug-in filtering functions - this method of filtering is complimentary to the default
- * type based filtering, and a lot more comprehensive as it allows you complete control
- * over the filtering logic. Each element in this array is a function (parameters
- * described below) that is called for every row in the table, and your logic decides if
- * it should be included in the filtered data set or not.
- * <ul>
- * <li>
- * Function input parameters:
- * <ul>
- * <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li>
- * <li>{array|object} Data for the row to be processed (same as the original format
- * that was passed in as the data source, or an array from a DOM data source</li>
- * <li>{int} Row index in aoData ({@link DataTable.models.oSettings.aoData}), which can
- * be useful to retrieve the TR element if you need DOM interaction.</li>
- * </ul>
- * </li>
- * <li>
- * Function return:
- * <ul>
- * <li>{boolean} Include the row in the filtered result set (true) or not (false)</li>
- * </ul>
- * </il>
- * </ul>
- * @type array
- * @default []
+ * Throttle the calls to a function. Arguments and context are maintained
+ * for the throttled function.
*
- * @example
- * // The following example shows custom filtering being applied to the fourth column (i.e.
- * // the aData[3] index) based on two input values from the end-user, matching the data in
- * // a certain range.
- * $.fn.dataTableExt.afnFiltering.push(
- * function( oSettings, aData, iDataIndex ) {
- * var iMin = document.getElementById('min').value * 1;
- * var iMax = document.getElementById('max').value * 1;
- * var iVersion = aData[3] == "-" ? 0 : aData[3]*1;
- * if ( iMin == "" && iMax == "" ) {
- * return true;
- * }
- * else if ( iMin == "" && iVersion < iMax ) {
- * return true;
- * }
- * else if ( iMin < iVersion && "" == iMax ) {
- * return true;
- * }
- * else if ( iMin < iVersion && iVersion < iMax ) {
- * return true;
- * }
- * return false;
- * }
- * );
+ * @param {function} fn Function to be called
+ * @param {integer} freq Call frequency in mS
+ * @return {function} Wrapped function
*/
- "afnFiltering": [],
+ throttle: _fnThrottle,
/**
- * Plug-in sorting functions - this method of sorting is complimentary to the default type
- * based sorting that DataTables does automatically, allowing much greater control over the
- * the data that is being used to sort a column. This is useful if you want to do sorting
- * based on live data (for example the contents of an 'input' element) rather than just the
- * static string that DataTables knows of. The way these plug-ins work is that you create
- * an array of the values you wish to be sorted for the column in question and then return
- * that array. Which pre-sorting function is run here depends on the sSortDataType parameter
- * that is used for the column (if any). This is the corollary of <i>ofnSearch</i> for sort
- * data.
- * <ul>
- * <li>
- * Function input parameters:
- * <ul>
- * <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li>
- * <li>{int} Target column index</li>
- * </ul>
- * </li>
- * <li>
- * Function return:
- * <ul>
- * <li>{array} Data for the column to be sorted upon</li>
- * </ul>
- * </il>
- * </ul>
- *
- * Note that as of v1.9, it is typically preferable to use <i>mData</i> to prepare data for
- * the different uses that DataTables can put the data to. Specifically <i>mData</i> when
- * used as a function will give you a 'type' (sorting, filtering etc) that you can use to
- * prepare the data as required for the different types. As such, this method is deprecated.
- * @type array
- * @default []
- * @deprecated
+ * Escape a string such that it can be used in a regular expression
*
- * @example
- * // Updating the cached sorting information with user entered values in HTML input elements
- * jQuery.fn.dataTableExt.afnSortData['dom-text'] = function ( oSettings, iColumn )
- * {
- * var aData = [];
- * $( 'td:eq('+iColumn+') input', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
- * aData.push( this.value );
- * } );
- * return aData;
- * }
+ * @param {string} sVal string to escape
+ * @returns {string} escaped string
*/
- "afnSortData": [],
+ escapeRegex: _fnEscapeRegex
+ };
- /**
- * Feature plug-ins - This is an array of objects which describe the feature plug-ins that are
- * available to DataTables. These feature plug-ins are accessible through the sDom initialisation
- * option. As such, each feature plug-in must describe a function that is used to initialise
- * itself (fnInit), a character so the feature can be enabled by sDom (cFeature) and the name
- * of the feature (sFeature). Thus the objects attached to this method must provide:
- * <ul>
- * <li>{function} fnInit Initialisation of the plug-in
- * <ul>
- * <li>
- * Function input parameters:
- * <ul>
- * <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li>
- * </ul>
- * </li>
- * <li>
- * Function return:
- * <ul>
- * <li>{node|null} The element which contains your feature. Note that the return
- * may also be void if your plug-in does not require to inject any DOM elements
- * into DataTables control (sDom) - for example this might be useful when
- * developing a plug-in which allows table control via keyboard entry.</li>
- * </ul>
- * </il>
- * </ul>
- * </li>
- * <li>{character} cFeature Character that will be matched in sDom - case sensitive</li>
- * <li>{string} sFeature Feature name</li>
- * </ul>
- * @type array
- * @default []
- *
- * @example
- * // How TableTools initialises itself.
- * $.fn.dataTableExt.aoFeatures.push( {
- * "fnInit": function( oSettings ) {
- * return new TableTools( { "oDTSettings": oSettings } );
- * },
- * "cFeature": "T",
- * "sFeature": "TableTools"
- * } );
- */
- "aoFeatures": [],
+ /**
+ * Convert from camel case parameters to Hungarian notation. This is made public
+ * for the extensions to provide the same ability as DataTables core to accept
+ * either the 1.9 style Hungarian notation, or the 1.10+ style camelCase
+ * parameters.
+ *
+ * @param {object} src The model object which holds all parameters that can be
+ * mapped.
+ * @param {object} user The object to convert from camel case to Hungarian.
+ * @param {boolean} force When set to `true`, properties which already have a
+ * Hungarian value in the `user` object will be overwritten. Otherwise they
+ * won't be.
+ */
+ DataTable.camelToHungarian = _fnCamelToHungarian;
- /**
- * Type detection plug-in functions - DataTables utilises types to define how sorting and
- * filtering behave, and types can be either be defined by the developer (sType for the
- * column) or they can be automatically detected by the methods in this array. The functions
- * defined in the array are quite simple, taking a single parameter (the data to analyse)
- * and returning the type if it is a known type, or null otherwise.
- * <ul>
- * <li>
- * Function input parameters:
- * <ul>
- * <li>{*} Data from the column cell to be analysed</li>
- * </ul>
- * </li>
- * <li>
- * Function return:
- * <ul>
- * <li>{string|null} Data type detected, or null if unknown (and thus pass it
- * on to the other type detection functions.</li>
- * </ul>
- * </il>
- * </ul>
- * @type array
- * @default []
- *
- * @example
- * // Currency type detection plug-in:
- * jQuery.fn.dataTableExt.aTypes.push(
- * function ( sData ) {
- * var sValidChars = "0123456789.-";
- * var Char;
- *
- * // Check the numeric part
- * for ( i=1 ; i<sData.length ; i++ ) {
- * Char = sData.charAt(i);
- * if (sValidChars.indexOf(Char) == -1) {
- * return null;
- * }
- * }
- *
- * // Check prefixed by currency
- * if ( sData.charAt(0) == '$' || sData.charAt(0) == '&pound;' ) {
- * return 'currency';
- * }
- * return null;
- * }
- * );
- */
- "aTypes": [],
+ /**
+ *
+ */
+ _api_register( '$()', function ( selector, opts ) {
+ var
+ rows = this.rows( opts ).nodes(), // Get all rows
+ jqRows = $(rows);
+
+ return $( [].concat(
+ jqRows.filter( selector ).toArray(),
+ jqRows.find( selector ).toArray()
+ ) );
+ } );
- /**
- * Provide a common method for plug-ins to check the version of DataTables being used,
- * in order to ensure compatibility.
- * @type function
- * @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note
- * that the formats "X" and "X.Y" are also acceptable.
- * @returns {boolean} true if this version of DataTables is greater or equal to the
- * required version, or false if this version of DataTales is not suitable
- *
- * @example
- * $(document).ready(function() {
- * var oTable = $('#example').dataTable();
- * alert( oTable.fnVersionCheck( '1.9.0' ) );
- * } );
- */
- "fnVersionCheck": DataTable.fnVersionCheck,
+ // jQuery functions to operate on the tables
+ $.each( [ 'on', 'one', 'off' ], function (i, key) {
+ _api_register( key+'()', function ( /* event, handler */ ) {
+ var args = Array.prototype.slice.call(arguments);
- /**
- * Index for what 'this' index API functions should use
- * @type int
- * @default 0
- */
- "iApiIndex": 0,
+ // Add the `dt` namespace automatically if it isn't already present
+ if ( ! args[0].match(/\.dt\b/) ) {
+ args[0] += '.dt';
+ }
+ var inst = $( this.tables().nodes() );
+ inst[key].apply( inst, args );
+ return this;
+ } );
+ } );
- /**
- * Pre-processing of filtering data plug-ins - When you assign the sType for a column
- * (or have it automatically detected for you by DataTables or a type detection plug-in),
- * you will typically be using this for custom sorting, but it can also be used to provide
- * custom filtering by allowing you to pre-processing the data and returning the data in
- * the format that should be filtered upon. This is done by adding functions this object
- * with a parameter name which matches the sType for that target column. This is the
- * corollary of <i>afnSortData</i> for filtering data.
- * <ul>
- * <li>
- * Function input parameters:
- * <ul>
- * <li>{*} Data from the column cell to be prepared for filtering</li>
- * </ul>
- * </li>
- * <li>
- * Function return:
- * <ul>
- * <li>{string|null} Formatted string that will be used for the filtering.</li>
- * </ul>
- * </il>
- * </ul>
- *
- * Note that as of v1.9, it is typically preferable to use <i>mData</i> to prepare data for
- * the different uses that DataTables can put the data to. Specifically <i>mData</i> when
- * used as a function will give you a 'type' (sorting, filtering etc) that you can use to
- * prepare the data as required for the different types. As such, this method is deprecated.
- * @type object
- * @default {}
- * @deprecated
- *
- * @example
- * $.fn.dataTableExt.ofnSearch['title-numeric'] = function ( sData ) {
- * return sData.replace(/\n/g," ").replace( /<.*?>/g, "" );
- * }
- */
- "ofnSearch": {},
+ _api_register( 'clear()', function () {
+ return this.iterator( 'table', function ( settings ) {
+ _fnClearTable( settings );
+ } );
+ } );
- /**
- * Container for all private functions in DataTables so they can be exposed externally
- * @type object
- * @default {}
- */
- "oApi": {},
+ _api_register( 'settings()', function () {
+ return new _Api( this.context, this.context );
+ } );
- /**
- * Storage for the various classes that DataTables uses
- * @type object
- * @default {}
- */
- "oStdClasses": {},
-
- /**
- * Storage for the various classes that DataTables uses - jQuery UI suitable
- * @type object
- * @default {}
- */
- "oJUIClasses": {},
+ _api_register( 'init()', function () {
+ var ctx = this.context;
+ return ctx.length ? ctx[0].oInit : null;
+ } );
- /**
- * Pagination plug-in methods - The style and controls of the pagination can significantly
- * impact on how the end user interacts with the data in your table, and DataTables allows
- * the addition of pagination controls by extending this object, which can then be enabled
- * through the <i>sPaginationType</i> initialisation parameter. Each pagination type that
- * is added is an object (the property name of which is what <i>sPaginationType</i> refers
- * to) that has two properties, both methods that are used by DataTables to update the
- * control's state.
- * <ul>
- * <li>
- * fnInit - Initialisation of the paging controls. Called only during initialisation
- * of the table. It is expected that this function will add the required DOM elements
- * to the page for the paging controls to work. The element pointer
- * 'oSettings.aanFeatures.p' array is provided by DataTables to contain the paging
- * controls (note that this is a 2D array to allow for multiple instances of each
- * DataTables DOM element). It is suggested that you add the controls to this element
- * as children
- * <ul>
- * <li>
- * Function input parameters:
- * <ul>
- * <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li>
- * <li>{node} Container into which the pagination controls must be inserted</li>
- * <li>{function} Draw callback function - whenever the controls cause a page
- * change, this method must be called to redraw the table.</li>
- * </ul>
- * </li>
- * <li>
- * Function return:
- * <ul>
- * <li>No return required</li>
- * </ul>
- * </il>
- * </ul>
- * </il>
- * <li>
- * fnInit - This function is called whenever the paging status of the table changes and is
- * typically used to update classes and/or text of the paging controls to reflex the new
- * status.
- * <ul>
- * <li>
- * Function input parameters:
- * <ul>
- * <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li>
- * <li>{function} Draw callback function - in case you need to redraw the table again
- * or attach new event listeners</li>
- * </ul>
- * </li>
- * <li>
- * Function return:
- * <ul>
- * <li>No return required</li>
- * </ul>
- * </il>
- * </ul>
- * </il>
- * </ul>
- * @type object
- * @default {}
- *
- * @example
- * $.fn.dataTableExt.oPagination.four_button = {
- * "fnInit": function ( oSettings, nPaging, fnCallbackDraw ) {
- * nFirst = document.createElement( 'span' );
- * nPrevious = document.createElement( 'span' );
- * nNext = document.createElement( 'span' );
- * nLast = document.createElement( 'span' );
- *
- * nFirst.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sFirst ) );
- * nPrevious.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sPrevious ) );
- * nNext.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sNext ) );
- * nLast.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sLast ) );
- *
- * nFirst.className = "paginate_button first";
- * nPrevious.className = "paginate_button previous";
- * nNext.className="paginate_button next";
- * nLast.className = "paginate_button last";
- *
- * nPaging.appendChild( nFirst );
- * nPaging.appendChild( nPrevious );
- * nPaging.appendChild( nNext );
- * nPaging.appendChild( nLast );
- *
- * $(nFirst).click( function () {
- * oSettings.oApi._fnPageChange( oSettings, "first" );
- * fnCallbackDraw( oSettings );
- * } );
- *
- * $(nPrevious).click( function() {
- * oSettings.oApi._fnPageChange( oSettings, "previous" );
- * fnCallbackDraw( oSettings );
- * } );
- *
- * $(nNext).click( function() {
- * oSettings.oApi._fnPageChange( oSettings, "next" );
- * fnCallbackDraw( oSettings );
- * } );
- *
- * $(nLast).click( function() {
- * oSettings.oApi._fnPageChange( oSettings, "last" );
- * fnCallbackDraw( oSettings );
- * } );
- *
- * $(nFirst).bind( 'selectstart', function () { return false; } );
- * $(nPrevious).bind( 'selectstart', function () { return false; } );
- * $(nNext).bind( 'selectstart', function () { return false; } );
- * $(nLast).bind( 'selectstart', function () { return false; } );
- * },
- *
- * "fnUpdate": function ( oSettings, fnCallbackDraw ) {
- * if ( !oSettings.aanFeatures.p ) {
- * return;
- * }
- *
- * // Loop over each instance of the pager
- * var an = oSettings.aanFeatures.p;
- * for ( var i=0, iLen=an.length ; i<iLen ; i++ ) {
- * var buttons = an[i].getElementsByTagName('span');
- * if ( oSettings._iDisplayStart === 0 ) {
- * buttons[0].className = "paginate_disabled_previous";
- * buttons[1].className = "paginate_disabled_previous";
- * }
- * else {
- * buttons[0].className = "paginate_enabled_previous";
- * buttons[1].className = "paginate_enabled_previous";
- * }
- *
- * if ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() ) {
- * buttons[2].className = "paginate_disabled_next";
- * buttons[3].className = "paginate_disabled_next";
- * }
- * else {
- * buttons[2].className = "paginate_enabled_next";
- * buttons[3].className = "paginate_enabled_next";
- * }
- * }
- * }
- * };
- */
- "oPagination": {},
+ _api_register( 'data()', function () {
+ return this.iterator( 'table', function ( settings ) {
+ return _pluck( settings.aoData, '_aData' );
+ } ).flatten();
+ } );
- /**
- * Sorting plug-in methods - Sorting in DataTables is based on the detected type of the
- * data column (you can add your own type detection functions, or override automatic
- * detection using sType). With this specific type given to the column, DataTables will
- * apply the required sort from the functions in the object. Each sort type must provide
- * two mandatory methods, one each for ascending and descending sorting, and can optionally
- * provide a pre-formatting method that will help speed up sorting by allowing DataTables
- * to pre-format the sort data only once (rather than every time the actual sort functions
- * are run). The two sorting functions are typical Javascript sort methods:
- * <ul>
- * <li>
- * Function input parameters:
- * <ul>
- * <li>{*} Data to compare to the second parameter</li>
- * <li>{*} Data to compare to the first parameter</li>
- * </ul>
- * </li>
- * <li>
- * Function return:
- * <ul>
- * <li>{int} Sorting match: <0 if first parameter should be sorted lower than
- * the second parameter, ===0 if the two parameters are equal and >0 if
- * the first parameter should be sorted height than the second parameter.</li>
- * </ul>
- * </il>
- * </ul>
- * @type object
- * @default {}
- *
- * @example
- * // Case-sensitive string sorting, with no pre-formatting method
- * $.extend( $.fn.dataTableExt.oSort, {
- * "string-case-asc": function(x,y) {
- * return ((x < y) ? -1 : ((x > y) ? 1 : 0));
- * },
- * "string-case-desc": function(x,y) {
- * return ((x < y) ? 1 : ((x > y) ? -1 : 0));
- * }
- * } );
- *
- * @example
- * // Case-insensitive string sorting, with pre-formatting
- * $.extend( $.fn.dataTableExt.oSort, {
- * "string-pre": function(x) {
- * return x.toLowerCase();
- * },
- * "string-asc": function(x,y) {
- * return ((x < y) ? -1 : ((x > y) ? 1 : 0));
- * },
- * "string-desc": function(x,y) {
- * return ((x < y) ? 1 : ((x > y) ? -1 : 0));
- * }
- * } );
- */
- "oSort": {},
+ _api_register( 'destroy()', function ( remove ) {
+ remove = remove || false;
+ return this.iterator( 'table', function ( settings ) {
+ var orig = settings.nTableWrapper.parentNode;
+ var classes = settings.oClasses;
+ var table = settings.nTable;
+ var tbody = settings.nTBody;
+ var thead = settings.nTHead;
+ var tfoot = settings.nTFoot;
+ var jqTable = $(table);
+ var jqTbody = $(tbody);
+ var jqWrapper = $(settings.nTableWrapper);
+ var rows = $.map( settings.aoData, function (r) { return r.nTr; } );
+ var i, ien;
- /**
- * Version string for plug-ins to check compatibility. Allowed format is
- * a.b.c.d.e where: a:int, b:int, c:int, d:string(dev|beta), e:int. d and
- * e are optional
- * @type string
- * @default Version number
- */
- "sVersion": DataTable.version,
+ // Flag to note that the table is currently being destroyed - no action
+ // should be taken
+ settings.bDestroying = true;
+ // Fire off the destroy callbacks for plug-ins etc
+ _fnCallbackFire( settings, "aoDestroyCallback", "destroy", [settings] );
- /**
- * How should DataTables report an error. Can take the value 'alert' or 'throw'
- * @type string
- * @default alert
- */
- "sErrMode": "alert",
+ // If not being removed from the document, make all columns visible
+ if ( ! remove ) {
+ new _Api( settings ).columns().visible( true );
+ }
+ // Blitz all `DT` namespaced events (these are internal events, the
+ // lowercase, `dt` events are user subscribed and they are responsible
+ // for removing them
+ jqWrapper.unbind('.DT').find(':not(tbody *)').unbind('.DT');
+ $(window).unbind('.DT-'+settings.sInstance);
- /**
- * Store information for DataTables to access globally about other instances
- * @namespace
- * @private
- */
- "_oExternConfig": {
- /* int:iNextUnique - next unique number for an instance */
- "iNextUnique": 0
+ // When scrolling we had to break the table up - restore it
+ if ( table != thead.parentNode ) {
+ jqTable.children('thead').detach();
+ jqTable.append( thead );
+ }
+
+ if ( tfoot && table != tfoot.parentNode ) {
+ jqTable.children('tfoot').detach();
+ jqTable.append( tfoot );
+ }
+
+ // Remove the DataTables generated nodes, events and classes
+ jqTable.detach();
+ jqWrapper.detach();
+
+ settings.aaSorting = [];
+ settings.aaSortingFixed = [];
+ _fnSortingClasses( settings );
+
+ $( rows ).removeClass( settings.asStripeClasses.join(' ') );
+
+ $('th, td', thead).removeClass( classes.sSortable+' '+
+ classes.sSortableAsc+' '+classes.sSortableDesc+' '+classes.sSortableNone
+ );
+
+ if ( settings.bJUI ) {
+ $('th span.'+classes.sSortIcon+ ', td span.'+classes.sSortIcon, thead).detach();
+ $('th, td', thead).each( function () {
+ var wrapper = $('div.'+classes.sSortJUIWrapper, this);
+ $(this).append( wrapper.contents() );
+ wrapper.detach();
+ } );
+ }
+
+ if ( ! remove && orig ) {
+ // insertBefore acts like appendChild if !arg[1]
+ orig.insertBefore( table, settings.nTableReinsertBefore );
+ }
+
+ // Add the TR elements back into the table in their original order
+ jqTbody.children().detach();
+ jqTbody.append( rows );
+
+ // Restore the width of the original table - was read from the style property,
+ // so we can restore directly to that
+ jqTable
+ .css( 'width', settings.sDestroyWidth )
+ .removeClass( classes.sTable );
+
+ // If the were originally stripe classes - then we add them back here.
+ // Note this is not fool proof (for example if not all rows had stripe
+ // classes - but it's a good effort without getting carried away
+ ien = settings.asDestroyStripes.length;
+
+ if ( ien ) {
+ jqTbody.children().each( function (i) {
+ $(this).addClass( settings.asDestroyStripes[i % ien] );
+ } );
+ }
+
+ /* Remove the settings object from the settings array */
+ var idx = $.inArray( settings, DataTable.settings );
+ if ( idx !== -1 ) {
+ DataTable.settings.splice( idx, 1 );
+ }
+ } );
+ } );
+
+
+ // Add the `every()` method for rows, columns and cells in a compact form
+ $.each( [ 'column', 'row', 'cell' ], function ( i, type ) {
+ _api_register( type+'s().every()', function ( fn ) {
+ return this.iterator( type, function ( settings, idx, idx2 ) {
+ // idx2 is undefined for rows and columns.
+ fn.call( new _Api( settings )[ type ]( idx, idx2 ) );
+ } );
+ } );
+ } );
+
+
+ // i18n method for extensions to be able to use the language object from the
+ // DataTable
+ _api_register( 'i18n()', function ( token, def, plural ) {
+ var ctx = this.context[0];
+ var resolved = _fnGetObjectDataFn( token )( ctx.oLanguage );
+
+ if ( resolved === undefined ) {
+ resolved = def;
+ }
+
+ if ( plural !== undefined && $.isPlainObject( resolved ) ) {
+ resolved = resolved[ plural ] !== undefined ?
+ resolved[ plural ] :
+ resolved._;
}
- };
+ return resolved.replace( '%d', plural ); // nb: plural might be undefined,
+ } );
+
+ /**
+ * Version string for plug-ins to check compatibility. Allowed format is
+ * `a.b.c-d` where: a:int, b:int, c:int, d:string(dev|beta|alpha). `d` is used
+ * only for non-release builds. See http://semver.org/ for more information.
+ * @member
+ * @type string
+ * @default Version number
+ */
+ DataTable.version = "1.10.7";
+
+ /**
+ * Private data store, containing all of the settings objects that are
+ * created for the tables on a given page.
+ *
+ * Note that the `DataTable.settings` object is aliased to
+ * `jQuery.fn.dataTableExt` through which it may be accessed and
+ * manipulated, or `jQuery.fn.dataTable.settings`.
+ * @member
+ * @type array
+ * @default []
+ * @private
+ */
+ DataTable.settings = [];
+
+ /**
+ * Object models container, for the various models that DataTables has
+ * available to it. These models define the objects that are used to hold
+ * the active state and configuration of the table.
+ * @namespace
+ */
+ DataTable.models = {};
@@ -7499,7 +9201,7 @@
/**
* Template object for the way in which DataTables holds information about
- * each individual row. This is the object format used for the settings
+ * each individual row. This is the object format used for the settings
* aoData array.
* @namespace
*/
@@ -7512,10 +9214,18 @@
"nTr": null,
/**
+ * Array of TD elements for each row. This is null until the row has been
+ * created.
+ * @type array nodes
+ * @default []
+ */
+ "anCells": null,
+
+ /**
* Data object from the original data source for the row. This is either
* an array if using the traditional form of DataTables, or an object if
* using mData options. The exact type will depend on the passed in
- * data from the data source, or will be an array if using DOM a data
+ * data from the data source, or will be an array if using DOM a data
* source.
* @type array|object
* @default []
@@ -7524,29 +9234,37 @@
/**
* Sorting data cache - this array is ostensibly the same length as the
- * number of columns (although each index is generated only as it is
+ * number of columns (although each index is generated only as it is
* needed), and holds the data that is used for sorting each column in the
* row. We do this cache generation at the start of the sort in order that
* the formatting of the sort data need be done only once for each cell
* per sort. This array should not be read from or written to by anything
* other than the master sorting methods.
* @type array
- * @default []
+ * @default null
* @private
*/
- "_aSortData": [],
+ "_aSortData": null,
/**
- * Array of TD elements that are cached for hidden rows, so they can be
- * reinserted into the table if a column is made visible again (or to act
- * as a store if a column is made hidden). Only hidden columns have a
- * reference in the array. For non-hidden columns the value is either
- * undefined or null.
- * @type array nodes
- * @default []
+ * Per cell filtering data cache. As per the sort data cache, used to
+ * increase the performance of the filtering in DataTables
+ * @type array
+ * @default null
+ * @private
+ */
+ "_aFilterData": null,
+
+ /**
+ * Filtering data cache. This is the same as the cell filtering cache, but
+ * in this case a string rather than an array. This is easily computed with
+ * a join on `_aFilterData`, but is provided as a cache so the join isn't
+ * needed on every search (memory traded for performance)
+ * @type array
+ * @default null
* @private
*/
- "_anHidden": [],
+ "_sFilterRow": null,
/**
* Cache of the class name that DataTables has applied to the row, so we
@@ -7556,17 +9274,27 @@
* @default <i>Empty string</i>
* @private
*/
- "_sRowStripe": ""
- };
+ "_sRowStripe": "",
+ /**
+ * Denote if the original data source was from the DOM, or the data source
+ * object. This is used for invalidating data, so DataTables can
+ * automatically read data from the original source, unless uninstructed
+ * otherwise.
+ * @type string
+ * @default null
+ * @private
+ */
+ "src": null
+ };
/**
* Template object for the column information object in DataTables. This object
* is held in the settings aoColumns array and contains all the information that
* DataTables needs about each individual column.
- *
- * Note that this object is related to {@link DataTable.defaults.columns}
+ *
+ * Note that this object is related to {@link DataTable.defaults.column}
* but this one is the internal data store for DataTables's cache of columns.
* It should NOT be manipulated outside of DataTables. Any configuration should
* be done through the initialisation options.
@@ -7574,6 +9302,14 @@
*/
DataTable.models.oColumn = {
/**
+ * Column index. This could be worked out on-the-fly with $.inArray, but it
+ * is faster to just hold it as a variable
+ * @type integer
+ * @default null
+ */
+ "idx": null,
+
+ /**
* A list of the columns that sorting should occur on when this column
* is sorted. That this property is an array allows multi-column sorting
* to be defined for a column (for example first name / last name columns
@@ -7593,49 +9329,44 @@
* @type array
*/
"asSorting": null,
-
+
/**
* Flag to indicate if the column is searchable, and thus should be included
* in the filtering or not.
* @type boolean
*/
"bSearchable": null,
-
+
/**
* Flag to indicate if the column is sortable or not.
* @type boolean
*/
"bSortable": null,
-
- /**
- * <code>Deprecated</code> When using fnRender, you have two options for what
- * to do with the data, and this property serves as the switch. Firstly, you
- * can have the sorting and filtering use the rendered value (true - default),
- * or you can have the sorting and filtering us the original value (false).
- *
- * Please note that this option has now been deprecated and will be removed
- * in the next version of DataTables. Please use mRender / mData rather than
- * fnRender.
- * @type boolean
- * @deprecated
- */
- "bUseRendered": null,
-
+
/**
* Flag to indicate if the column is currently visible in the table or not
* @type boolean
*/
"bVisible": null,
-
+
+ /**
+ * Store for manual type assignment using the `column.type` option. This
+ * is held in store so we can manipulate the column's `sType` property.
+ * @type string
+ * @default null
+ * @private
+ */
+ "_sManualType": null,
+
/**
- * Flag to indicate to the type detection method if the automatic type
- * detection should be used, or if a column type (sType) has been specified
+ * Flag to indicate if HTML5 data attributes should be used as the data
+ * source for filtering or sorting. True is either are.
* @type boolean
- * @default true
+ * @default false
* @private
*/
- "_bAutoType": true,
-
+ "_bAttrSrc": false,
+
/**
* Developer definable function that is called whenever a cell is created (Ajax source,
* etc) or processed for input (DOM source). This can be used as a compliment to mRender
@@ -7649,64 +9380,45 @@
* @default null
*/
"fnCreatedCell": null,
-
+
/**
* Function to get data from a cell in a column. You should <b>never</b>
* access data directly through _aData internally in DataTables - always use
* the method attached to this property. It allows mData to function as
- * required. This function is automatically assigned by the column
+ * required. This function is automatically assigned by the column
* initialisation method
* @type function
- * @param {array|object} oData The data array/object for the array
+ * @param {array|object} oData The data array/object for the array
* (i.e. aoData[]._aData)
- * @param {string} sSpecific The specific data type you want to get -
+ * @param {string} sSpecific The specific data type you want to get -
* 'display', 'type' 'filter' 'sort'
* @returns {*} The data for the cell from the given row's data
* @default null
*/
"fnGetData": null,
-
- /**
- * <code>Deprecated</code> Custom display function that will be called for the
- * display of each cell in this column.
- *
- * Please note that this option has now been deprecated and will be removed
- * in the next version of DataTables. Please use mRender / mData rather than
- * fnRender.
- * @type function
- * @param {object} o Object with the following parameters:
- * @param {int} o.iDataRow The row in aoData
- * @param {int} o.iDataColumn The column in question
- * @param {array} o.aData The data for the row in question
- * @param {object} o.oSettings The settings object for this DataTables instance
- * @returns {string} The string you which to use in the display
- * @default null
- * @deprecated
- */
- "fnRender": null,
-
+
/**
- * Function to set data for a cell in the column. You should <b>never</b>
+ * Function to set data for a cell in the column. You should <b>never</b>
* set the data directly to _aData internally in DataTables - always use
* this method. It allows mData to function as required. This function
* is automatically assigned by the column initialisation method
* @type function
- * @param {array|object} oData The data array/object for the array
+ * @param {array|object} oData The data array/object for the array
* (i.e. aoData[]._aData)
* @param {*} sValue Value to set
* @default null
*/
"fnSetData": null,
-
+
/**
- * Property to read the value for the cells in the column from the data
+ * Property to read the value for the cells in the column from the data
* source array / object. If null, then the default content is used, if a
* function is given then the return from the function is used.
* @type function|int|string|null
* @default null
*/
"mData": null,
-
+
/**
* Partner property to mData which is used (only when defined) to get
* the data - i.e. it is basically the same as mData, but without the
@@ -7716,7 +9428,7 @@
* @default null
*/
"mRender": null,
-
+
/**
* Unique header TH/TD element for this column - this is what the sorting
* listener is attached to (if sorting is enabled.)
@@ -7724,28 +9436,28 @@
* @default null
*/
"nTh": null,
-
+
/**
- * Unique footer TH/TD element for this column (if there is one). Not used
- * in DataTables as such, but can be used for plug-ins to reference the
+ * Unique footer TH/TD element for this column (if there is one). Not used
+ * in DataTables as such, but can be used for plug-ins to reference the
* footer for each column.
* @type node
* @default null
*/
"nTf": null,
-
+
/**
* The class to apply to all TD elements in the table's TBODY for the column
* @type string
* @default null
*/
"sClass": null,
-
+
/**
* When DataTables calculates the column widths to assign to each column,
* it finds the longest string in each column and then constructs a
* temporary table and reads the widths from that. The problem with this
- * is that "mmm" is much wider then "iiii", but the latter is a longer
+ * is that "mmm" is much wider then "iiii", but the latter is a longer
* string - thus the calculation can go wrong (doing it properly and putting
* it into an DOM object and measuring that is horribly(!) slow). Thus as
* a "work around" we provide this option. It will append its value to the
@@ -7753,7 +9465,7 @@
* @type string
*/
"sContentPadding": null,
-
+
/**
* Allows a default value to be given for a column's data, and will be used
* whenever a null data source is encountered (this can be because mData
@@ -7762,14 +9474,14 @@
* @default null
*/
"sDefaultContent": null,
-
+
/**
* Name for the column, allowing reference to the column by name as well as
* by index (needs a lookup to work by name).
* @type string
*/
"sName": null,
-
+
/**
* Custom sorting data type - defines which of the available plug-ins in
* afnSortData the custom sorting will use - if any is defined.
@@ -7777,14 +9489,14 @@
* @default std
*/
"sSortDataType": 'std',
-
+
/**
* Class to be applied to the header element when sorting on this column
* @type string
* @default null
*/
"sSortingClass": null,
-
+
/**
* Class to be applied to the header element when sorting on this column -
* when jQuery UI theming is used.
@@ -7792,27 +9504,27 @@
* @default null
*/
"sSortingClassJUI": null,
-
+
/**
* Title of the column - what is seen in the TH element (nTh).
* @type string
*/
"sTitle": null,
-
+
/**
* Column sorting and filtering type
* @type string
* @default null
*/
"sType": null,
-
+
/**
* Width of the column
* @type string
* @default null
*/
"sWidth": null,
-
+
/**
* Width of the column when it was first "encountered"
* @type string
@@ -7822,45 +9534,62 @@
};
+ /*
+ * Developer note: The properties of the object below are given in Hungarian
+ * notation, that was used as the interface for DataTables prior to v1.10, however
+ * from v1.10 onwards the primary interface is camel case. In order to avoid
+ * breaking backwards compatibility utterly with this change, the Hungarian
+ * version is still, internally the primary interface, but is is not documented
+ * - hence the @name tags in each doc comment. This allows a Javascript function
+ * to create a map from Hungarian notation to camel case (going the other direction
+ * would require each property to be listed, which would at around 3K to the size
+ * of DataTables, while this method is about a 0.5K hit.
+ *
+ * Ultimately this does pave the way for Hungarian notation to be dropped
+ * completely, but that is a massive amount of work and will break current
+ * installs (therefore is on-hold until v2).
+ */
/**
- * Initialisation options that can be given to DataTables at initialisation
+ * Initialisation options that can be given to DataTables at initialisation
* time.
* @namespace
*/
DataTable.defaults = {
/**
- * An array of data to use for the table, passed in at initialisation which
+ * An array of data to use for the table, passed in at initialisation which
* will be used in preference to any data which is already in the DOM. This is
* particularly useful for constructing tables purely in Javascript, for
* example with a custom Ajax call.
* @type array
* @default null
+ *
* @dtopt Option
- *
+ * @name DataTable.defaults.data
+ *
* @example
* // Using a 2D array data source
* $(document).ready( function () {
* $('#example').dataTable( {
- * "aaData": [
+ * "data": [
* ['Trident', 'Internet Explorer 4.0', 'Win 95+', 4, 'X'],
* ['Trident', 'Internet Explorer 5.0', 'Win 95+', 5, 'C'],
* ],
- * "aoColumns": [
- * { "sTitle": "Engine" },
- * { "sTitle": "Browser" },
- * { "sTitle": "Platform" },
- * { "sTitle": "Version" },
- * { "sTitle": "Grade" }
+ * "columns": [
+ * { "title": "Engine" },
+ * { "title": "Browser" },
+ * { "title": "Platform" },
+ * { "title": "Version" },
+ * { "title": "Grade" }
* ]
* } );
* } );
- *
+ *
* @example
- * // Using an array of objects as a data source (mData)
+ * // Using an array of objects as a data source (`data`)
* $(document).ready( function () {
* $('#example').dataTable( {
- * "aaData": [
+ * "data": [
* {
* "engine": "Trident",
* "browser": "Internet Explorer 4.0",
@@ -7876,12 +9605,12 @@
* "grade": "C"
* }
* ],
- * "aoColumns": [
- * { "sTitle": "Engine", "mData": "engine" },
- * { "sTitle": "Browser", "mData": "browser" },
- * { "sTitle": "Platform", "mData": "platform" },
- * { "sTitle": "Version", "mData": "version" },
- * { "sTitle": "Grade", "mData": "grade" }
+ * "columns": [
+ * { "title": "Engine", "data": "engine" },
+ * { "title": "Browser", "data": "browser" },
+ * { "title": "Platform", "data": "platform" },
+ * { "title": "Version", "data": "version" },
+ * { "title": "Grade", "data": "grade" }
* ]
* } );
* } );
@@ -7890,27 +9619,29 @@
/**
- * If sorting is enabled, then DataTables will perform a first pass sort on
- * initialisation. You can define which column(s) the sort is performed upon,
- * and the sorting direction, with this variable. The aaSorting array should
- * contain an array for each column to be sorted initially containing the
- * column's index and a direction string ('asc' or 'desc').
+ * If ordering is enabled, then DataTables will perform a first pass sort on
+ * initialisation. You can define which column(s) the sort is performed
+ * upon, and the sorting direction, with this variable. The `sorting` array
+ * should contain an array for each column to be sorted initially containing
+ * the column's index and a direction string ('asc' or 'desc').
* @type array
* @default [[0,'asc']]
+ *
* @dtopt Option
- *
+ * @name DataTable.defaults.order
+ *
* @example
* // Sort by 3rd column first, and then 4th column
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aaSorting": [[2,'asc'], [3,'desc']]
+ * "order": [[2,'asc'], [3,'desc']]
* } );
* } );
- *
+ *
* // No initial sorting
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aaSorting": []
+ * "order": []
* } );
* } );
*/
@@ -7918,52 +9649,205 @@
/**
- * This parameter is basically identical to the aaSorting parameter, but
- * cannot be overridden by user interaction with the table. What this means
- * is that you could have a column (visible or hidden) which the sorting will
- * always be forced on first - any sorting after that (from the user) will
- * then be performed as required. This can be useful for grouping rows
+ * This parameter is basically identical to the `sorting` parameter, but
+ * cannot be overridden by user interaction with the table. What this means
+ * is that you could have a column (visible or hidden) which the sorting
+ * will always be forced on first - any sorting after that (from the user)
+ * will then be performed as required. This can be useful for grouping rows
* together.
* @type array
* @default null
+ *
* @dtopt Option
- *
+ * @name DataTable.defaults.orderFixed
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aaSortingFixed": [[0,'asc']]
+ * "orderFixed": [[0,'asc']]
* } );
* } )
*/
- "aaSortingFixed": null,
+ "aaSortingFixed": [],
+
+
+ /**
+ * DataTables can be instructed to load data to display in the table from a
+ * Ajax source. This option defines how that Ajax call is made and where to.
+ *
+ * The `ajax` property has three different modes of operation, depending on
+ * how it is defined. These are:
+ *
+ * * `string` - Set the URL from where the data should be loaded from.
+ * * `object` - Define properties for `jQuery.ajax`.
+ * * `function` - Custom data get function
+ *
+ * `string`
+ * --------
+ *
+ * As a string, the `ajax` property simply defines the URL from which
+ * DataTables will load data.
+ *
+ * `object`
+ * --------
+ *
+ * As an object, the parameters in the object are passed to
+ * [jQuery.ajax](http://api.jquery.com/jQuery.ajax/) allowing fine control
+ * of the Ajax request. DataTables has a number of default parameters which
+ * you can override using this option. Please refer to the jQuery
+ * documentation for a full description of the options available, although
+ * the following parameters provide additional options in DataTables or
+ * require special consideration:
+ *
+ * * `data` - As with jQuery, `data` can be provided as an object, but it
+ * can also be used as a function to manipulate the data DataTables sends
+ * to the server. The function takes a single parameter, an object of
+ * parameters with the values that DataTables has readied for sending. An
+ * object may be returned which will be merged into the DataTables
+ * defaults, or you can add the items to the object that was passed in and
+ * not return anything from the function. This supersedes `fnServerParams`
+ * from DataTables 1.9-.
+ *
+ * * `dataSrc` - By default DataTables will look for the property `data` (or
+ * `aaData` for compatibility with DataTables 1.9-) when obtaining data
+ * from an Ajax source or for server-side processing - this parameter
+ * allows that property to be changed. You can use Javascript dotted
+ * object notation to get a data source for multiple levels of nesting, or
+ * it my be used as a function. As a function it takes a single parameter,
+ * the JSON returned from the server, which can be manipulated as
+ * required, with the returned value being that used by DataTables as the
+ * data source for the table. This supersedes `sAjaxDataProp` from
+ * DataTables 1.9-.
+ *
+ * * `success` - Should not be overridden it is used internally in
+ * DataTables. To manipulate / transform the data returned by the server
+ * use `ajax.dataSrc`, or use `ajax` as a function (see below).
+ *
+ * `function`
+ * ----------
+ *
+ * As a function, making the Ajax call is left up to yourself allowing
+ * complete control of the Ajax request. Indeed, if desired, a method other
+ * than Ajax could be used to obtain the required data, such as Web storage
+ * or an AIR database.
+ *
+ * The function is given four parameters and no return is required. The
+ * parameters are:
+ *
+ * 1. _object_ - Data to send to the server
+ * 2. _function_ - Callback function that must be executed when the required
+ * data has been obtained. That data should be passed into the callback
+ * as the only parameter
+ * 3. _object_ - DataTables settings object for the table
+ *
+ * Note that this supersedes `fnServerData` from DataTables 1.9-.
+ *
+ * @type string|object|function
+ * @default null
+ *
+ * @dtopt Option
+ * @name DataTable.defaults.ajax
+ * @since 1.10.0
+ *
+ * @example
+ * // Get JSON data from a file via Ajax.
+ * // Note DataTables expects data in the form `{ data: [ ...data... ] }` by default).
+ * $('#example').dataTable( {
+ * "ajax": "data.json"
+ * } );
+ *
+ * @example
+ * // Get JSON data from a file via Ajax, using `dataSrc` to change
+ * // `data` to `tableData` (i.e. `{ tableData: [ ...data... ] }`)
+ * $('#example').dataTable( {
+ * "ajax": {
+ * "url": "data.json",
+ * "dataSrc": "tableData"
+ * }
+ * } );
+ *
+ * @example
+ * // Get JSON data from a file via Ajax, using `dataSrc` to read data
+ * // from a plain array rather than an array in an object
+ * $('#example').dataTable( {
+ * "ajax": {
+ * "url": "data.json",
+ * "dataSrc": ""
+ * }
+ * } );
+ *
+ * @example
+ * // Manipulate the data returned from the server - add a link to data
+ * // (note this can, should, be done using `render` for the column - this
+ * // is just a simple example of how the data can be manipulated).
+ * $('#example').dataTable( {
+ * "ajax": {
+ * "url": "data.json",
+ * "dataSrc": function ( json ) {
+ * for ( var i=0, ien=json.length ; i<ien ; i++ ) {
+ * json[i][0] = '<a href="/message/'+json[i][0]+'>View message</a>';
+ * }
+ * return json;
+ * }
+ * }
+ * } );
+ *
+ * @example
+ * // Add data to the request
+ * $('#example').dataTable( {
+ * "ajax": {
+ * "url": "data.json",
+ * "data": function ( d ) {
+ * return {
+ * "extra_search": $('#extra').val()
+ * };
+ * }
+ * }
+ * } );
+ *
+ * @example
+ * // Send request as POST
+ * $('#example').dataTable( {
+ * "ajax": {
+ * "url": "data.json",
+ * "type": "POST"
+ * }
+ * } );
+ *
+ * @example
+ * // Get the data from localStorage (could interface with a form for
+ * // adding, editing and removing rows).
+ * $('#example').dataTable( {
+ * "ajax": function (data, callback, settings) {
+ * callback(
+ * JSON.parse( localStorage.getItem('dataTablesData') )
+ * );
+ * }
+ * } );
+ */
+ "ajax": null,
/**
* This parameter allows you to readily specify the entries in the length drop
- * down menu that DataTables shows when pagination is enabled. It can be
- * either a 1D array of options which will be used for both the displayed
- * option and the value, or a 2D array which will use the array in the first
- * position as the value, and the array in the second position as the
+ * down menu that DataTables shows when pagination is enabled. It can be
+ * either a 1D array of options which will be used for both the displayed
+ * option and the value, or a 2D array which will use the array in the first
+ * position as the value, and the array in the second position as the
* displayed options (useful for language strings such as 'All').
+ *
+ * Note that the `pageLength` property will be automatically set to the
+ * first value given in this array, unless `pageLength` is also provided.
* @type array
* @default [ 10, 25, 50, 100 ]
+ *
* @dtopt Option
- *
- * @example
- * $(document).ready( function() {
- * $('#example').dataTable( {
- * "aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
- * } );
- * } );
- *
+ * @name DataTable.defaults.lengthMenu
+ *
* @example
- * // Setting the default display length as well as length menu
- * // This is likely to be wanted if you remove the '10' option which
- * // is the iDisplayLength default.
* $(document).ready( function() {
* $('#example').dataTable( {
- * "iDisplayLength": 25,
- * "aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]]
+ * "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
* } );
* } );
*/
@@ -7971,25 +9855,27 @@
/**
- * The aoColumns option in the initialisation parameter allows you to define
+ * The `columns` option in the initialisation parameter allows you to define
* details about the way individual columns behave. For a full list of
- * column options that can be set, please see
- * {@link DataTable.defaults.columns}. Note that if you use aoColumns to
+ * column options that can be set, please see
+ * {@link DataTable.defaults.column}. Note that if you use `columns` to
* define your columns, you must have an entry in the array for every single
* column that you have in your table (these can be null if you don't which
* to specify any options).
* @member
+ *
+ * @name DataTable.defaults.column
*/
"aoColumns": null,
/**
- * Very similar to aoColumns, aoColumnDefs allows you to target a specific
- * column, multiple columns, or all columns, using the aTargets property of
- * each object in the array. This allows great flexibility when creating
- * tables, as the aoColumnDefs arrays can be of any length, targeting the
- * columns you specifically want. aoColumnDefs may use any of the column
- * options available: {@link DataTable.defaults.columns}, but it _must_
- * have aTargets defined in each object in the array. Values in the aTargets
+ * Very similar to `columns`, `columnDefs` allows you to target a specific
+ * column, multiple columns, or all columns, using the `targets` property of
+ * each object in the array. This allows great flexibility when creating
+ * tables, as the `columnDefs` arrays can be of any length, targeting the
+ * columns you specifically want. `columnDefs` may use any of the column
+ * options available: {@link DataTable.defaults.column}, but it _must_
+ * have `targets` defined in each object in the array. Values in the `targets`
* array may be:
* <ul>
* <li>a string - class name will be matched on the TH for the column</li>
@@ -7998,28 +9884,32 @@
* <li>the string "_all" - all columns (i.e. assign a default)</li>
* </ul>
* @member
+ *
+ * @name DataTable.defaults.columnDefs
*/
"aoColumnDefs": null,
/**
- * Basically the same as oSearch, this parameter defines the individual column
- * filtering state at initialisation time. The array must be of the same size
+ * Basically the same as `search`, this parameter defines the individual column
+ * filtering state at initialisation time. The array must be of the same size
* as the number of columns, and each element be an object with the parameters
- * "sSearch" and "bEscapeRegex" (the latter is optional). 'null' is also
+ * `search` and `escapeRegex` (the latter is optional). 'null' is also
* accepted and the default will be used.
* @type array
* @default []
+ *
* @dtopt Option
- *
+ * @name DataTable.defaults.searchCols
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoSearchCols": [
+ * "searchCols": [
* null,
- * { "sSearch": "My filter" },
+ * { "search": "My filter" },
* null,
- * { "sSearch": "^[0-9]", "bEscapeRegex": false }
+ * { "search": "^[0-9]", "escapeRegex": false }
* ]
* } );
* } )
@@ -8028,18 +9918,20 @@
/**
- * An array of CSS classes that should be applied to displayed rows. This
- * array may be of any length, and DataTables will apply each class
+ * An array of CSS classes that should be applied to displayed rows. This
+ * array may be of any length, and DataTables will apply each class
* sequentially, looping when required.
* @type array
- * @default null <i>Will take the values determined by the oClasses.sStripe*
+ * @default null <i>Will take the values determined by the `oClasses.stripe*`
* options</i>
+ *
* @dtopt Option
- *
+ * @name DataTable.defaults.stripeClasses
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "asStripeClasses": [ 'strip1', 'strip2', 'strip3' ]
+ * "stripeClasses": [ 'strip1', 'strip2', 'strip3' ]
* } );
* } )
*/
@@ -8049,15 +9941,17 @@
/**
* Enable or disable automatic column width calculation. This can be disabled
* as an optimisation (it takes some time to calculate the widths) if the
- * tables widths are passed in using aoColumns.
+ * tables widths are passed in using `columns`.
* @type boolean
* @default true
+ *
* @dtopt Features
- *
+ * @name DataTable.defaults.autoWidth
+ *
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
- * "bAutoWidth": false
+ * "autoWidth": false
* } );
* } );
*/
@@ -8072,13 +9966,15 @@
* time.
* @type boolean
* @default false
+ *
* @dtopt Features
- *
+ * @name DataTable.defaults.deferRender
+ *
* @example
* $(document).ready( function() {
- * var oTable = $('#example').dataTable( {
- * "sAjaxSource": "sources/arrays.txt",
- * "bDeferRender": true
+ * $('#example').dataTable( {
+ * "ajax": "sources/arrays.txt",
+ * "deferRender": true
* } );
* } );
*/
@@ -8086,25 +9982,27 @@
/**
- * Replace a DataTable which matches the given selector and replace it with
+ * Replace a DataTable which matches the given selector and replace it with
* one which has the properties of the new initialisation object passed. If no
* table matches the selector, then the new DataTable will be constructed as
* per normal.
* @type boolean
* @default false
+ *
* @dtopt Options
- *
+ * @name DataTable.defaults.destroy
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "sScrollY": "200px",
- * "bPaginate": false
+ * "srollY": "200px",
+ * "paginate": false
* } );
- *
+ *
* // Some time later....
* $('#example').dataTable( {
- * "bFilter": false,
- * "bDestroy": true
+ * "filter": false,
+ * "destroy": true
* } );
* } );
*/
@@ -8118,15 +10016,17 @@
* specified (this allow matching across multiple columns). Note that if you
* wish to use filtering in DataTables this must remain 'true' - to remove the
* default filtering input box and retain filtering abilities, please use
- * {@link DataTable.defaults.sDom}.
+ * {@link DataTable.defaults.dom}.
* @type boolean
* @default true
+ *
* @dtopt Features
- *
+ * @name DataTable.defaults.searching
+ *
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
- * "bFilter": false
+ * "searching": false
* } );
* } );
*/
@@ -8134,17 +10034,19 @@
/**
- * Enable or disable the table information display. This shows information
+ * Enable or disable the table information display. This shows information
* about the data that is currently visible on the page, including information
* about filtered data if that action is being performed.
* @type boolean
* @default true
+ *
* @dtopt Features
- *
+ * @name DataTable.defaults.info
+ *
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
- * "bInfo": false
+ * "info": false
* } );
* } );
*/
@@ -8157,12 +10059,14 @@
* traditionally used).
* @type boolean
* @default false
+ *
* @dtopt Features
- *
+ * @name DataTable.defaults.jQueryUI
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "bJQueryUI": true
+ * "jQueryUI": true
* } );
* } );
*/
@@ -8171,15 +10075,17 @@
/**
* Allows the end user to select the size of a formatted page from a select
- * menu (sizes are 10, 25, 50 and 100). Requires pagination (bPaginate).
+ * menu (sizes are 10, 25, 50 and 100). Requires pagination (`paginate`).
* @type boolean
* @default true
+ *
* @dtopt Features
- *
+ * @name DataTable.defaults.lengthChange
+ *
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
- * "bLengthChange": false
+ * "lengthChange": false
* } );
* } );
*/
@@ -8190,12 +10096,14 @@
* Enable or disable pagination.
* @type boolean
* @default true
+ *
* @dtopt Features
- *
+ * @name DataTable.defaults.paging
+ *
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
- * "bPaginate": false
+ * "paging": false
* } );
* } );
*/
@@ -8209,12 +10117,14 @@
* the entries.
* @type boolean
* @default false
+ *
* @dtopt Features
- *
+ * @name DataTable.defaults.processing
+ *
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
- * "bProcessing": true
+ * "processing": true
* } );
* } );
*/
@@ -8227,56 +10137,39 @@
* to simply return the object that has already been set up - it will not take
* account of any changes you might have made to the initialisation object
* passed to DataTables (setting this parameter to true is an acknowledgement
- * that you understand this). bDestroy can be used to reinitialise a table if
+ * that you understand this). `destroy` can be used to reinitialise a table if
* you need.
* @type boolean
* @default false
+ *
* @dtopt Options
- *
+ * @name DataTable.defaults.retrieve
+ *
* @example
* $(document).ready( function() {
* initTable();
* tableActions();
* } );
- *
+ *
* function initTable ()
* {
* return $('#example').dataTable( {
- * "sScrollY": "200px",
- * "bPaginate": false,
- * "bRetrieve": true
+ * "scrollY": "200px",
+ * "paginate": false,
+ * "retrieve": true
* } );
* }
- *
+ *
* function tableActions ()
* {
- * var oTable = initTable();
- * // perform API operations with oTable
+ * var table = initTable();
+ * // perform API operations with oTable
* }
*/
"bRetrieve": false,
/**
- * Indicate if DataTables should be allowed to set the padding / margin
- * etc for the scrolling header elements or not. Typically you will want
- * this.
- * @type boolean
- * @default true
- * @dtopt Options
- *
- * @example
- * $(document).ready( function() {
- * $('#example').dataTable( {
- * "bScrollAutoCss": false,
- * "sScrollY": "200px"
- * } );
- * } );
- */
- "bScrollAutoCss": true,
-
-
- /**
* When vertical (y) scrolling is enabled, DataTables will force the height of
* the table's viewport to the given height at all times (useful for layout).
* However, this can look odd when filtering data down to a small data set,
@@ -8285,13 +10178,15 @@
* the result set will fit within the given Y height.
* @type boolean
* @default false
+ *
* @dtopt Options
- *
+ * @name DataTable.defaults.scrollCollapse
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "sScrollY": "200",
- * "bScrollCollapse": true
+ * "scrollY": "200",
+ * "scrollCollapse": true
* } );
* } );
*/
@@ -8299,63 +10194,64 @@
/**
- * Enable infinite scrolling for DataTables (to be used in combination with
- * sScrollY). Infinite scrolling means that DataTables will continually load
- * data as a user scrolls through a table, which is very useful for large
- * dataset. This cannot be used with pagination, which is automatically
- * disabled. Note - the Scroller extra for DataTables is recommended in
- * in preference to this option.
+ * Configure DataTables to use server-side processing. Note that the
+ * `ajax` parameter must also be given in order to give DataTables a
+ * source to obtain the required data for each draw.
* @type boolean
* @default false
+ *
* @dtopt Features
- *
+ * @dtopt Server-side
+ * @name DataTable.defaults.serverSide
+ *
* @example
- * $(document).ready( function() {
+ * $(document).ready( function () {
* $('#example').dataTable( {
- * "bScrollInfinite": true,
- * "bScrollCollapse": true,
- * "sScrollY": "200px"
+ * "serverSide": true,
+ * "ajax": "xhr.php"
* } );
* } );
*/
- "bScrollInfinite": false,
+ "bServerSide": false,
/**
- * Configure DataTables to use server-side processing. Note that the
- * sAjaxSource parameter must also be given in order to give DataTables a
- * source to obtain the required data for each draw.
+ * Enable or disable sorting of columns. Sorting of individual columns can be
+ * disabled by the `sortable` option for each column.
* @type boolean
- * @default false
+ * @default true
+ *
* @dtopt Features
- * @dtopt Server-side
- *
+ * @name DataTable.defaults.ordering
+ *
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
- * "bServerSide": true,
- * "sAjaxSource": "xhr.php"
+ * "ordering": false
* } );
* } );
*/
- "bServerSide": false,
+ "bSort": true,
/**
- * Enable or disable sorting of columns. Sorting of individual columns can be
- * disabled by the "bSortable" option for each column.
+ * Enable or display DataTables' ability to sort multiple columns at the
+ * same time (activated by shift-click by the user).
* @type boolean
* @default true
- * @dtopt Features
- *
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.orderMulti
+ *
* @example
+ * // Disable multiple column sorting ability
* $(document).ready( function () {
* $('#example').dataTable( {
- * "bSort": false
+ * "orderMulti": false
* } );
* } );
*/
- "bSort": true,
+ "bSortMulti": true,
/**
@@ -8364,12 +10260,14 @@
* This is useful when using complex headers.
* @type boolean
* @default false
+ *
* @dtopt Options
- *
+ * @name DataTable.defaults.orderCellsTop
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "bSortCellsTop": true
+ * "orderCellsTop": true
* } );
* } );
*/
@@ -8377,19 +10275,21 @@
/**
- * Enable or disable the addition of the classes 'sorting_1', 'sorting_2' and
- * 'sorting_3' to the columns which are currently being sorted on. This is
+ * Enable or disable the addition of the classes `sorting\_1`, `sorting\_2` and
+ * `sorting\_3` to the columns which are currently being sorted on. This is
* presented as a feature switch as it can increase processing time (while
* classes are removed and added) so for large data sets you might want to
* turn this off.
* @type boolean
* @default true
+ *
* @dtopt Features
- *
+ * @name DataTable.defaults.orderClasses
+ *
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
- * "bSortClasses": false
+ * "orderClasses": false
* } );
* } );
*/
@@ -8397,18 +10297,24 @@
/**
- * Enable or disable state saving. When enabled a cookie will be used to save
- * table display information such as pagination information, display length,
- * filtering and sorting. As such when the end user reloads the page the
- * display display will match what thy had previously set up.
+ * Enable or disable state saving. When enabled HTML5 `localStorage` will be
+ * used to save table display information such as pagination information,
+ * display length, filtering and sorting. As such when the end user reloads
+ * the page the display display will match what thy had previously set up.
+ *
+ * Due to the use of `localStorage` the default state saving is not supported
+ * in IE6 or 7. If state saving is required in those browsers, use
+ * `stateSaveCallback` to provide a storage solution such as cookies.
* @type boolean
* @default false
+ *
* @dtopt Features
- *
+ * @name DataTable.defaults.stateSave
+ *
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
- * "bStateSave": true
+ * "stateSave": true
* } );
* } );
*/
@@ -8416,51 +10322,25 @@
/**
- * Customise the cookie and / or the parameters being stored when using
- * DataTables with state saving enabled. This function is called whenever
- * the cookie is modified, and it expects a fully formed cookie string to be
- * returned. Note that the data object passed in is a Javascript object which
- * must be converted to a string (JSON.stringify for example).
- * @type function
- * @param {string} sName Name of the cookie defined by DataTables
- * @param {object} oData Data to be stored in the cookie
- * @param {string} sExpires Cookie expires string
- * @param {string} sPath Path of the cookie to set
- * @returns {string} Cookie formatted string (which should be encoded by
- * using encodeURIComponent())
- * @dtopt Callbacks
- *
- * @example
- * $(document).ready( function () {
- * $('#example').dataTable( {
- * "fnCookieCallback": function (sName, oData, sExpires, sPath) {
- * // Customise oData or sName or whatever else here
- * return sName + "="+JSON.stringify(oData)+"; expires=" + sExpires +"; path=" + sPath;
- * }
- * } );
- * } );
- */
- "fnCookieCallback": null,
-
-
- /**
* This function is called when a TR element is created (and all TD child
* elements have been inserted), or registered if using a DOM source, allowing
* manipulation of the TR element (adding classes etc).
* @type function
- * @param {node} nRow "TR" element for the current row
- * @param {array} aData Raw data array for this row
- * @param {int} iDataIndex The index of this row in aoData
+ * @param {node} row "TR" element for the current row
+ * @param {array} data Raw data array for this row
+ * @param {int} dataIndex The index of this row in the internal aoData array
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.createdRow
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "fnCreatedRow": function( nRow, aData, iDataIndex ) {
+ * "createdRow": function( row, data, dataIndex ) {
* // Bold the grade for all 'A' grade browsers
- * if ( aData[4] == "A" )
+ * if ( data[4] == "A" )
* {
- * $('td:eq(4)', nRow).html( '<b>A</b>' );
+ * $('td:eq(4)', row).html( '<b>A</b>' );
* }
* }
* } );
@@ -8473,13 +10353,15 @@
* This function is called on every 'draw' event, and allows you to
* dynamically modify any aspect you want about the created DOM.
* @type function
- * @param {object} oSettings DataTables settings object
+ * @param {object} settings DataTables settings object
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.drawCallback
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "fnDrawCallback": function( oSettings ) {
+ * "drawCallback": function( settings ) {
* alert( 'DataTables has redrawn the table' );
* }
* } );
@@ -8490,23 +10372,25 @@
/**
* Identical to fnHeaderCallback() but for the table footer this function
- * allows you to modify the table footer on every 'draw' even.
+ * allows you to modify the table footer on every 'draw' event.
* @type function
- * @param {node} nFoot "TR" element for the footer
- * @param {array} aData Full table data (as derived from the original HTML)
- * @param {int} iStart Index for the current display starting point in the
+ * @param {node} foot "TR" element for the footer
+ * @param {array} data Full table data (as derived from the original HTML)
+ * @param {int} start Index for the current display starting point in the
* display array
- * @param {int} iEnd Index for the current display ending point in the
+ * @param {int} end Index for the current display ending point in the
* display array
- * @param {array int} aiDisplay Index array to translate the visual position
+ * @param {array int} display Index array to translate the visual position
* to the full data array
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.footerCallback
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "fnFooterCallback": function( nFoot, aData, iStart, iEnd, aiDisplay ) {
- * nFoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+iStart;
+ * "footerCallback": function( tfoot, data, start, end, display ) {
+ * tfoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+start;
* }
* } );
* } )
@@ -8522,52 +10406,30 @@
* function will override the default method DataTables uses.
* @type function
* @member
- * @param {int} iIn number to be formatted
+ * @param {int} toFormat number to be formatted
* @returns {string} formatted string for DataTables to show the number
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.formatNumber
+ *
* @example
+ * // Format a number using a single quote for the separator (note that
+ * // this can also be done with the language.thousands option)
* $(document).ready( function() {
* $('#example').dataTable( {
- * "fnFormatNumber": function ( iIn ) {
- * if ( iIn &lt; 1000 ) {
- * return iIn;
- * } else {
- * var
- * s=(iIn+""),
- * a=s.split(""), out="",
- * iLen=s.length;
- *
- * for ( var i=0 ; i&lt;iLen ; i++ ) {
- * if ( i%3 === 0 &amp;&amp; i !== 0 ) {
- * out = "'"+out;
- * }
- * out = a[iLen-i-1]+out;
- * }
- * }
- * return out;
+ * "formatNumber": function ( toFormat ) {
+ * return toFormat.toString().replace(
+ * /\B(?=(\d{3})+(?!\d))/g, "'"
+ * );
* };
* } );
* } );
*/
- "fnFormatNumber": function ( iIn ) {
- if ( iIn < 1000 )
- {
- // A small optimisation for what is likely to be the majority of use cases
- return iIn;
- }
-
- var s=(iIn+""), a=s.split(""), out="", iLen=s.length;
-
- for ( var i=0 ; i<iLen ; i++ )
- {
- if ( i%3 === 0 && i !== 0 )
- {
- out = this.oLanguage.sInfoThousands+out;
- }
- out = a[iLen-i-1]+out;
- }
- return out;
+ "fnFormatNumber": function ( toFormat ) {
+ return toFormat.toString().replace(
+ /\B(?=(\d{3})+(?!\d))/g,
+ this.oLanguage.sThousands
+ );
},
@@ -8576,21 +10438,23 @@
* dynamically modify the header row. This can be used to calculate and
* display useful information about the table.
* @type function
- * @param {node} nHead "TR" element for the header
- * @param {array} aData Full table data (as derived from the original HTML)
- * @param {int} iStart Index for the current display starting point in the
+ * @param {node} head "TR" element for the header
+ * @param {array} data Full table data (as derived from the original HTML)
+ * @param {int} start Index for the current display starting point in the
* display array
- * @param {int} iEnd Index for the current display ending point in the
+ * @param {int} end Index for the current display ending point in the
* display array
- * @param {array int} aiDisplay Index array to translate the visual position
+ * @param {array int} display Index array to translate the visual position
* to the full data array
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.headerCallback
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "fnHeaderCallback": function( nHead, aData, iStart, iEnd, aiDisplay ) {
- * nHead.getElementsByTagName('th')[0].innerHTML = "Displaying "+(iEnd-iStart)+" records";
+ * "fheaderCallback": function( head, data, start, end, display ) {
+ * head.getElementsByTagName('th')[0].innerHTML = "Displaying "+(end-start)+" records";
* }
* } );
* } )
@@ -8606,20 +10470,22 @@
* allows you to do exactly that.
* @type function
* @param {object} oSettings DataTables settings object
- * @param {int} iStart Starting position in data for the draw
- * @param {int} iEnd End position in data for the draw
- * @param {int} iMax Total number of rows in the table (regardless of
+ * @param {int} start Starting position in data for the draw
+ * @param {int} end End position in data for the draw
+ * @param {int} max Total number of rows in the table (regardless of
* filtering)
- * @param {int} iTotal Total number of rows in the data set, after filtering
- * @param {string} sPre The string that DataTables has formatted using it's
+ * @param {int} total Total number of rows in the data set, after filtering
+ * @param {string} pre The string that DataTables has formatted using it's
* own rules
* @returns {string} The string to be displayed in the information element.
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.infoCallback
+ *
* @example
* $('#example').dataTable( {
- * "fnInfoCallback": function( oSettings, iStart, iEnd, iMax, iTotal, sPre ) {
- * return iStart +" to "+ iEnd;
+ * "infoCallback": function( settings, start, end, max, total, pre ) {
+ * return start +" to "+ end;
* }
* } );
*/
@@ -8632,15 +10498,17 @@
* however, this does not hold true when using external language information
* since that is obtained using an async XHR call.
* @type function
- * @param {object} oSettings DataTables settings object
+ * @param {object} settings DataTables settings object
* @param {object} json The JSON object request from the server - only
* present if client-side Ajax sourced data is used
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.initComplete
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "fnInitComplete": function(oSettings, json) {
+ * "initComplete": function(settings, json) {
* alert( 'DataTables has finished its initialisation.' );
* }
* } );
@@ -8654,15 +10522,17 @@
* draw by returning false, any other return (including undefined) results in
* the full draw occurring).
* @type function
- * @param {object} oSettings DataTables settings object
+ * @param {object} settings DataTables settings object
* @returns {boolean} False will cancel the draw, anything else (including no
* return) will allow it to complete.
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.preDrawCallback
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "fnPreDrawCallback": function( oSettings ) {
+ * "preDrawCallback": function( settings ) {
* if ( $('#test').val() == 1 ) {
* return false;
* }
@@ -8678,21 +10548,22 @@
* generated for each table draw, but before it is rendered on screen. This
* function might be used for setting the row class name etc.
* @type function
- * @param {node} nRow "TR" element for the current row
- * @param {array} aData Raw data array for this row
- * @param {int} iDisplayIndex The display index for the current table draw
- * @param {int} iDisplayIndexFull The index of the data in the full list of
+ * @param {node} row "TR" element for the current row
+ * @param {array} data Raw data array for this row
+ * @param {int} displayIndex The display index for the current table draw
+ * @param {int} displayIndexFull The index of the data in the full list of
* rows (after filtering)
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.rowCallback
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
+ * "rowCallback": function( row, data, displayIndex, displayIndexFull ) {
* // Bold the grade for all 'A' grade browsers
- * if ( aData[4] == "A" )
- * {
- * $('td:eq(4)', nRow).html( '<b>A</b>' );
+ * if ( data[4] == "A" ) {
+ * $('td:eq(4)', row).html( '<b>A</b>' );
* }
* }
* } );
@@ -8702,114 +10573,77 @@
/**
+ * __Deprecated__ The functionality provided by this parameter has now been
+ * superseded by that provided through `ajax`, which should be used instead.
+ *
* This parameter allows you to override the default function which obtains
- * the data from the server ($.getJSON) so something more suitable for your
- * application. For example you could use POST data, or pull information from
- * a Gears or AIR database.
+ * the data from the server so something more suitable for your application.
+ * For example you could use POST data, or pull information from a Gears or
+ * AIR database.
* @type function
* @member
- * @param {string} sSource HTTP source to obtain the data from (sAjaxSource)
- * @param {array} aoData A key/value pair object containing the data to send
+ * @param {string} source HTTP source to obtain the data from (`ajax`)
+ * @param {array} data A key/value pair object containing the data to send
* to the server
- * @param {function} fnCallback to be called on completion of the data get
+ * @param {function} callback to be called on completion of the data get
* process that will draw the data on the page.
- * @param {object} oSettings DataTables settings object
+ * @param {object} settings DataTables settings object
+ *
* @dtopt Callbacks
* @dtopt Server-side
- *
- * @example
- * // POST data to server
- * $(document).ready( function() {
- * $('#example').dataTable( {
- * "bProcessing": true,
- * "bServerSide": true,
- * "sAjaxSource": "xhr.php",
- * "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
- * oSettings.jqXHR = $.ajax( {
- * "dataType": 'json',
- * "type": "POST",
- * "url": sSource,
- * "data": aoData,
- * "success": fnCallback
- * } );
- * }
- * } );
- * } );
+ * @name DataTable.defaults.serverData
+ *
+ * @deprecated 1.10. Please use `ajax` for this functionality now.
*/
- "fnServerData": function ( sUrl, aoData, fnCallback, oSettings ) {
- oSettings.jqXHR = $.ajax( {
- "url": sUrl,
- "data": aoData,
- "success": function (json) {
- if ( json.sError ) {
- oSettings.oApi._fnLog( oSettings, 0, json.sError );
- }
-
- $(oSettings.oInstance).trigger('xhr', [oSettings, json]);
- fnCallback( json );
- },
- "dataType": "json",
- "cache": false,
- "type": oSettings.sServerMethod,
- "error": function (xhr, error, thrown) {
- if ( error == "parsererror" ) {
- oSettings.oApi._fnLog( oSettings, 0, "DataTables warning: JSON data from "+
- "server could not be parsed. This is caused by a JSON formatting error." );
- }
- }
- } );
- },
+ "fnServerData": null,
/**
- * It is often useful to send extra data to the server when making an Ajax
+ * __Deprecated__ The functionality provided by this parameter has now been
+ * superseded by that provided through `ajax`, which should be used instead.
+ *
+ * It is often useful to send extra data to the server when making an Ajax
* request - for example custom filtering information, and this callback
* function makes it trivial to send extra information to the server. The
* passed in parameter is the data set that has been constructed by
* DataTables, and you can add to this or modify it as you require.
* @type function
- * @param {array} aoData Data array (array of objects which are name/value
+ * @param {array} data Data array (array of objects which are name/value
* pairs) that has been constructed by DataTables and will be sent to the
* server. In the case of Ajax sourced data with server-side processing
* this will be an empty array, for server-side processing there will be a
* significant number of parameters!
- * @returns {undefined} Ensure that you modify the aoData array passed in,
+ * @returns {undefined} Ensure that you modify the data array passed in,
* as this is passed by reference.
+ *
* @dtopt Callbacks
* @dtopt Server-side
- *
- * @example
- * $(document).ready( function() {
- * $('#example').dataTable( {
- * "bProcessing": true,
- * "bServerSide": true,
- * "sAjaxSource": "scripts/server_processing.php",
- * "fnServerParams": function ( aoData ) {
- * aoData.push( { "name": "more_data", "value": "my_value" } );
- * }
- * } );
- * } );
+ * @name DataTable.defaults.serverParams
+ *
+ * @deprecated 1.10. Please use `ajax` for this functionality now.
*/
"fnServerParams": null,
/**
* Load the table state. With this function you can define from where, and how, the
- * state of a table is loaded. By default DataTables will load from its state saving
- * cookie, but you might wish to use local storage (HTML5) or a server-side database.
+ * state of a table is loaded. By default DataTables will load from `localStorage`
+ * but you might wish to use a server-side database or cookies.
* @type function
* @member
- * @param {object} oSettings DataTables settings object
+ * @param {object} settings DataTables settings object
* @return {object} The DataTables state object to be loaded
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.stateLoadCallback
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "bStateSave": true,
- * "fnStateLoad": function (oSettings) {
+ * "stateSave": true,
+ * "stateLoadCallback": function (settings) {
* var o;
- *
+ *
* // Send an Ajax request to the server to get the data. Note that
* // this is a synchronous request.
* $.ajax( {
@@ -8820,55 +10654,53 @@
* o = json;
* }
* } );
- *
+ *
* return o;
* }
* } );
* } );
*/
- "fnStateLoad": function ( oSettings ) {
- var sData = this.oApi._fnReadCookie( oSettings.sCookiePrefix+oSettings.sInstance );
- var oData;
-
+ "fnStateLoadCallback": function ( settings ) {
try {
- oData = (typeof $.parseJSON === 'function') ?
- $.parseJSON(sData) : eval( '('+sData+')' );
- } catch (e) {
- oData = null;
- }
-
- return oData;
+ return JSON.parse(
+ (settings.iStateDuration === -1 ? sessionStorage : localStorage).getItem(
+ 'DataTables_'+settings.sInstance+'_'+location.pathname
+ )
+ );
+ } catch (e) {}
},
/**
* Callback which allows modification of the saved state prior to loading that state.
* This callback is called when the table is loading state from the stored data, but
- * prior to the settings object being modified by the saved state. Note that for
- * plug-in authors, you should use the 'stateLoadParams' event to load parameters for
+ * prior to the settings object being modified by the saved state. Note that for
+ * plug-in authors, you should use the `stateLoadParams` event to load parameters for
* a plug-in.
* @type function
- * @param {object} oSettings DataTables settings object
- * @param {object} oData The state object that is to be loaded
+ * @param {object} settings DataTables settings object
+ * @param {object} data The state object that is to be loaded
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.stateLoadParams
+ *
* @example
* // Remove a saved filter, so filtering is never loaded
* $(document).ready( function() {
* $('#example').dataTable( {
- * "bStateSave": true,
- * "fnStateLoadParams": function (oSettings, oData) {
- * oData.oSearch.sSearch = "";
+ * "stateSave": true,
+ * "stateLoadParams": function (settings, data) {
+ * data.oSearch.sSearch = "";
* }
* } );
* } );
- *
+ *
* @example
* // Disallow state loading by returning false
* $(document).ready( function() {
* $('#example').dataTable( {
- * "bStateSave": true,
- * "fnStateLoadParams": function (oSettings, oData) {
+ * "stateSave": true,
+ * "stateLoadParams": function (settings, data) {
* return false;
* }
* } );
@@ -8881,17 +10713,19 @@
* Callback that is called when the state has been loaded from the state saving method
* and the DataTables settings object has been modified as a result of the loaded state.
* @type function
- * @param {object} oSettings DataTables settings object
- * @param {object} oData The state object that was loaded
+ * @param {object} settings DataTables settings object
+ * @param {object} data The state object that was loaded
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.stateLoaded
+ *
* @example
* // Show an alert with the filtering value that was saved
* $(document).ready( function() {
* $('#example').dataTable( {
- * "bStateSave": true,
- * "fnStateLoaded": function (oSettings, oData) {
- * alert( 'Saved filter was: '+oData.oSearch.sSearch );
+ * "stateSave": true,
+ * "stateLoaded": function (settings, data) {
+ * alert( 'Saved filter was: '+data.oSearch.sSearch );
* }
* } );
* } );
@@ -8901,23 +10735,25 @@
/**
* Save the table state. This function allows you to define where and how the state
- * information for the table is stored - by default it will use a cookie, but you
- * might want to use local storage (HTML5) or a server-side database.
+ * information for the table is stored By default DataTables will use `localStorage`
+ * but you might wish to use a server-side database or cookies.
* @type function
* @member
- * @param {object} oSettings DataTables settings object
- * @param {object} oData The state object to be saved
+ * @param {object} settings DataTables settings object
+ * @param {object} data The state object to be saved
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.stateSaveCallback
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "bStateSave": true,
- * "fnStateSave": function (oSettings, oData) {
+ * "stateSave": true,
+ * "stateSaveCallback": function (settings, data) {
* // Send an Ajax request to the server with the state object
* $.ajax( {
* "url": "/state_save",
- * "data": oData,
+ * "data": data,
* "dataType": "json",
* "method": "POST"
* "success": function () {}
@@ -8926,35 +10762,36 @@
* } );
* } );
*/
- "fnStateSave": function ( oSettings, oData ) {
- this.oApi._fnCreateCookie(
- oSettings.sCookiePrefix+oSettings.sInstance,
- this.oApi._fnJsonString(oData),
- oSettings.iCookieDuration,
- oSettings.sCookiePrefix,
- oSettings.fnCookieCallback
- );
+ "fnStateSaveCallback": function ( settings, data ) {
+ try {
+ (settings.iStateDuration === -1 ? sessionStorage : localStorage).setItem(
+ 'DataTables_'+settings.sInstance+'_'+location.pathname,
+ JSON.stringify( data )
+ );
+ } catch (e) {}
},
/**
- * Callback which allows modification of the state to be saved. Called when the table
+ * Callback which allows modification of the state to be saved. Called when the table
* has changed state a new state save is required. This method allows modification of
- * the state saving object prior to actually doing the save, including addition or
- * other state properties or modification. Note that for plug-in authors, you should
- * use the 'stateSaveParams' event to save parameters for a plug-in.
+ * the state saving object prior to actually doing the save, including addition or
+ * other state properties or modification. Note that for plug-in authors, you should
+ * use the `stateSaveParams` event to save parameters for a plug-in.
* @type function
- * @param {object} oSettings DataTables settings object
- * @param {object} oData The state object to be saved
+ * @param {object} settings DataTables settings object
+ * @param {object} data The state object to be saved
+ *
* @dtopt Callbacks
- *
+ * @name DataTable.defaults.stateSaveParams
+ *
* @example
* // Remove a saved filter, so filtering is never saved
* $(document).ready( function() {
* $('#example').dataTable( {
- * "bStateSave": true,
- * "fnStateSaveParams": function (oSettings, oData) {
- * oData.oSearch.sSearch = "";
+ * "stateSave": true,
+ * "stateSaveParams": function (settings, data) {
+ * data.oSearch.sSearch = "";
* }
* } );
* } );
@@ -8963,26 +10800,29 @@
/**
- * Duration of the cookie which is used for storing session information. This
- * value is given in seconds.
+ * Duration for which the saved state information is considered valid. After this period
+ * has elapsed the state will be returned to the default.
+ * Value is given in seconds.
* @type int
* @default 7200 <i>(2 hours)</i>
+ *
* @dtopt Options
- *
+ * @name DataTable.defaults.stateDuration
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "iCookieDuration": 60*60*24; // 1 day
+ * "stateDuration": 60*60*24; // 1 day
* } );
* } )
*/
- "iCookieDuration": 7200,
+ "iStateDuration": 7200,
/**
* When enabled DataTables will not make a request to the server for the first
* page draw - rather it will use the data already on the page (no sorting etc
- * will be applied to it), thus saving on an XHR at load time. iDeferLoading
+ * will be applied to it), thus saving on an XHR at load time. `deferLoading`
* is used to indicate that deferred loading is required, but it is also used
* to tell DataTables how many records there are in the full table (allowing
* the information element and pagination to be displayed correctly). In the case
@@ -8993,27 +10833,29 @@
* to be shown correctly).
* @type int | array
* @default null
+ *
* @dtopt Options
- *
+ * @name DataTable.defaults.deferLoading
+ *
* @example
* // 57 records available in the table, no filtering applied
* $(document).ready( function() {
* $('#example').dataTable( {
- * "bServerSide": true,
- * "sAjaxSource": "scripts/server_processing.php",
- * "iDeferLoading": 57
+ * "serverSide": true,
+ * "ajax": "scripts/server_processing.php",
+ * "deferLoading": 57
* } );
* } );
- *
+ *
* @example
* // 57 records after filtering, 100 without filtering (an initial filter applied)
* $(document).ready( function() {
* $('#example').dataTable( {
- * "bServerSide": true,
- * "sAjaxSource": "scripts/server_processing.php",
- * "iDeferLoading": [ 57, 100 ],
- * "oSearch": {
- * "sSearch": "my_filter"
+ * "serverSide": true,
+ * "ajax": "scripts/server_processing.php",
+ * "deferLoading": [ 57, 100 ],
+ * "search": {
+ * "search": "my_filter"
* }
* } );
* } );
@@ -9023,16 +10865,18 @@
/**
* Number of rows to display on a single page when using pagination. If
- * feature enabled (bLengthChange) then the end user will be able to override
+ * feature enabled (`lengthChange`) then the end user will be able to override
* this to a custom setting using a pop-up menu.
* @type int
* @default 10
+ *
* @dtopt Options
- *
+ * @name DataTable.defaults.pageLength
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "iDisplayLength": 50
+ * "pageLength": 50
* } );
* } )
*/
@@ -9046,12 +10890,14 @@
* the third page, it should be "20".
* @type int
* @default 0
+ *
* @dtopt Options
- *
+ * @name DataTable.defaults.displayStart
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "iDisplayStart": 20
+ * "displayStart": 20
* } );
* } )
*/
@@ -9059,42 +10905,22 @@
/**
- * The scroll gap is the amount of scrolling that is left to go before
- * DataTables will load the next 'page' of data automatically. You typically
- * want a gap which is big enough that the scrolling will be smooth for the
- * user, while not so large that it will load more data than need.
- * @type int
- * @default 100
- * @dtopt Options
- *
- * @example
- * $(document).ready( function() {
- * $('#example').dataTable( {
- * "bScrollInfinite": true,
- * "bScrollCollapse": true,
- * "sScrollY": "200px",
- * "iScrollLoadGap": 50
- * } );
- * } );
- */
- "iScrollLoadGap": 100,
-
-
- /**
* By default DataTables allows keyboard navigation of the table (sorting, paging,
- * and filtering) by adding a tabindex attribute to the required elements. This
+ * and filtering) by adding a `tabindex` attribute to the required elements. This
* allows you to tab through the controls and press the enter key to activate them.
* The tabindex is default 0, meaning that the tab follows the flow of the document.
* You can overrule this using this parameter if you wish. Use a value of -1 to
* disable built-in keyboard navigation.
* @type int
* @default 0
+ *
* @dtopt Options
- *
+ * @name DataTable.defaults.tabIndex
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "iTabIndex": 1
+ * "tabIndex": 1
* } );
* } );
*/
@@ -9102,10 +10928,22 @@
/**
+ * Classes that DataTables assigns to the various components and features
+ * that it adds to the HTML table. This allows classes to be configured
+ * during initialisation in addition to through the static
+ * {@link DataTable.ext.oStdClasses} object).
+ * @namespace
+ * @name DataTable.defaults.classes
+ */
+ "oClasses": {},
+
+
+ /**
* All strings that DataTables uses in the user interface that it creates
* are defined in this object, allowing you to modified them individually or
* completely replace them all as required.
* @namespace
+ * @name DataTable.defaults.language
*/
"oLanguage": {
/**
@@ -9113,6 +10951,7 @@
* actually visible on the page, but will be read by screenreaders, and thus
* must be internationalised as well).
* @namespace
+ * @name DataTable.defaults.language.aria
*/
"oAria": {
/**
@@ -9121,14 +10960,16 @@
* Note that the column header is prefixed to this string.
* @type string
* @default : activate to sort column ascending
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.aria.sortAscending
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "oAria": {
- * "sSortAscending": " - click/return to sort ascending"
+ * "language": {
+ * "aria": {
+ * "sortAscending": " - click/return to sort ascending"
* }
* }
* } );
@@ -9142,14 +10983,16 @@
* Note that the column header is prefixed to this string.
* @type string
* @default : activate to sort column ascending
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.aria.sortDescending
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "oAria": {
- * "sSortDescending": " - click/return to sort descending"
+ * "language": {
+ * "aria": {
+ * "sortDescending": " - click/return to sort descending"
* }
* }
* } );
@@ -9159,9 +11002,10 @@
},
/**
- * Pagination string used by DataTables for the two built-in pagination
- * control types ("two_button" and "full_numbers")
+ * Pagination string used by DataTables for the built-in pagination
+ * control types.
* @namespace
+ * @name DataTable.defaults.language.paginate
*/
"oPaginate": {
/**
@@ -9169,77 +11013,85 @@
* button to take the user to the first page.
* @type string
* @default First
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.paginate.first
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "oPaginate": {
- * "sFirst": "First page"
+ * "language": {
+ * "paginate": {
+ * "first": "First page"
* }
* }
* } );
* } );
*/
"sFirst": "First",
-
-
+
+
/**
* Text to use when using the 'full_numbers' type of pagination for the
* button to take the user to the last page.
* @type string
* @default Last
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.paginate.last
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "oPaginate": {
- * "sLast": "Last page"
+ * "language": {
+ * "paginate": {
+ * "last": "Last page"
* }
* }
* } );
* } );
*/
"sLast": "Last",
-
-
+
+
/**
- * Text to use for the 'next' pagination button (to take the user to the
+ * Text to use for the 'next' pagination button (to take the user to the
* next page).
* @type string
* @default Next
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.paginate.next
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "oPaginate": {
- * "sNext": "Next page"
+ * "language": {
+ * "paginate": {
+ * "next": "Next page"
* }
* }
* } );
* } );
*/
"sNext": "Next",
-
-
+
+
/**
- * Text to use for the 'previous' pagination button (to take the user to
+ * Text to use for the 'previous' pagination button (to take the user to
* the previous page).
* @type string
* @default Previous
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.paginate.previous
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "oPaginate": {
- * "sPrevious": "Previous page"
+ * "language": {
+ * "paginate": {
+ * "previous": "Previous page"
* }
* }
* } );
@@ -9247,130 +11099,182 @@
*/
"sPrevious": "Previous"
},
-
+
/**
- * This string is shown in preference to sZeroRecords when the table is
+ * This string is shown in preference to `zeroRecords` when the table is
* empty of data (regardless of filtering). Note that this is an optional
- * parameter - if it is not given, the value of sZeroRecords will be used
+ * parameter - if it is not given, the value of `zeroRecords` will be used
* instead (either the default or given value).
* @type string
* @default No data available in table
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.emptyTable
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sEmptyTable": "No data available in table"
+ * "language": {
+ * "emptyTable": "No data available in table"
* }
* } );
* } );
*/
"sEmptyTable": "No data available in table",
-
-
+
+
/**
- * This string gives information to the end user about the information that
- * is current on display on the page. The _START_, _END_ and _TOTAL_
- * variables are all dynamically replaced as the table display updates, and
- * can be freely moved or removed as the language requirements change.
+ * This string gives information to the end user about the information
+ * that is current on display on the page. The following tokens can be
+ * used in the string and will be dynamically replaced as the table
+ * display updates. This tokens can be placed anywhere in the string, or
+ * removed as needed by the language requires:
+ *
+ * * `\_START\_` - Display index of the first record on the current page
+ * * `\_END\_` - Display index of the last record on the current page
+ * * `\_TOTAL\_` - Number of records in the table after filtering
+ * * `\_MAX\_` - Number of records in the table without filtering
+ * * `\_PAGE\_` - Current page number
+ * * `\_PAGES\_` - Total number of pages of data in the table
+ *
* @type string
* @default Showing _START_ to _END_ of _TOTAL_ entries
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.info
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sInfo": "Got a total of _TOTAL_ entries to show (_START_ to _END_)"
+ * "language": {
+ * "info": "Showing page _PAGE_ of _PAGES_"
* }
* } );
* } );
*/
"sInfo": "Showing _START_ to _END_ of _TOTAL_ entries",
-
-
+
+
/**
- * Display information string for when the table is empty. Typically the
- * format of this string should match sInfo.
+ * Display information string for when the table is empty. Typically the
+ * format of this string should match `info`.
* @type string
* @default Showing 0 to 0 of 0 entries
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.infoEmpty
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sInfoEmpty": "No entries to show"
+ * "language": {
+ * "infoEmpty": "No entries to show"
* }
* } );
* } );
*/
"sInfoEmpty": "Showing 0 to 0 of 0 entries",
-
-
+
+
/**
- * When a user filters the information in a table, this string is appended
- * to the information (sInfo) to give an idea of how strong the filtering
+ * When a user filters the information in a table, this string is appended
+ * to the information (`info`) to give an idea of how strong the filtering
* is. The variable _MAX_ is dynamically updated.
* @type string
* @default (filtered from _MAX_ total entries)
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.infoFiltered
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sInfoFiltered": " - filtering from _MAX_ records"
+ * "language": {
+ * "infoFiltered": " - filtering from _MAX_ records"
* }
* } );
* } );
*/
"sInfoFiltered": "(filtered from _MAX_ total entries)",
-
-
+
+
/**
* If can be useful to append extra information to the info string at times,
* and this variable does exactly that. This information will be appended to
- * the sInfo (sInfoEmpty and sInfoFiltered in whatever combination they are
+ * the `info` (`infoEmpty` and `infoFiltered` in whatever combination they are
* being used) at all times.
* @type string
* @default <i>Empty string</i>
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.infoPostFix
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sInfoPostFix": "All records shown are derived from real information."
+ * "language": {
+ * "infoPostFix": "All records shown are derived from real information."
* }
* } );
* } );
*/
"sInfoPostFix": "",
-
-
+
+
/**
- * DataTables has a build in number formatter (fnFormatNumber) which is used
- * to format large numbers that are used in the table information. By
- * default a comma is used, but this can be trivially changed to any
+ * This decimal place operator is a little different from the other
+ * language options since DataTables doesn't output floating point
+ * numbers, so it won't ever use this for display of a number. Rather,
+ * what this parameter does is modify the sort methods of the table so
+ * that numbers which are in a format which has a character other than
+ * a period (`.`) as a decimal place will be sorted numerically.
+ *
+ * Note that numbers with different decimal places cannot be shown in
+ * the same table and still be sortable, the table must be consistent.
+ * However, multiple different tables on the page can use different
+ * decimal place characters.
+ * @type string
+ * @default
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.decimal
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "language": {
+ * "decimal": ","
+ * "thousands": "."
+ * }
+ * } );
+ * } );
+ */
+ "sDecimal": "",
+
+
+ /**
+ * DataTables has a build in number formatter (`formatNumber`) which is
+ * used to format large numbers that are used in the table information.
+ * By default a comma is used, but this can be trivially changed to any
* character you wish with this parameter.
* @type string
* @default ,
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.thousands
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sInfoThousands": "'"
+ * "language": {
+ * "thousands": "'"
* }
* } );
* } );
*/
- "sInfoThousands": ",",
-
-
+ "sThousands": ",",
+
+
/**
* Detail the action that will be taken when the drop down menu for the
* pagination length option is changed. The '_MENU_' variable is replaced
@@ -9378,24 +11282,26 @@
* with a custom select box if required.
* @type string
* @default Show _MENU_ entries
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.lengthMenu
+ *
* @example
* // Language change only
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sLengthMenu": "Display _MENU_ records"
+ * "language": {
+ * "lengthMenu": "Display _MENU_ records"
* }
* } );
* } );
- *
+ *
* @example
* // Language and options change
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sLengthMenu": 'Display <select>'+
+ * "language": {
+ * "lengthMenu": 'Display <select>'+
* '<option value="10">10</option>'+
* '<option value="20">20</option>'+
* '<option value="30">30</option>'+
@@ -9408,8 +11314,8 @@
* } );
*/
"sLengthMenu": "Show _MENU_ entries",
-
-
+
+
/**
* When using Ajax sourced data and during the first draw when DataTables is
* gathering the data, this message is shown in an empty row in the table to
@@ -9418,39 +11324,43 @@
* Ajax sourced data with client-side processing.
* @type string
* @default Loading...
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.loadingRecords
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sLoadingRecords": "Please wait - loading..."
+ * "language": {
+ * "loadingRecords": "Please wait - loading..."
* }
* } );
* } );
*/
"sLoadingRecords": "Loading...",
-
-
+
+
/**
* Text which is displayed when the table is processing a user action
* (usually a sort command or similar).
* @type string
* @default Processing...
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.processing
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sProcessing": "DataTables is currently busy"
+ * "language": {
+ * "processing": "DataTables is currently busy"
* }
* } );
* } );
*/
"sProcessing": "Processing...",
-
-
+
+
/**
* Details the actions that will be taken when the user types into the
* filtering input text box. The variable "_INPUT_", if used in the string,
@@ -9459,31 +11369,44 @@
* then the input box is appended to the string automatically.
* @type string
* @default Search:
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.search
+ *
* @example
* // Input text box will be appended at the end automatically
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sSearch": "Filter records:"
+ * "language": {
+ * "search": "Filter records:"
* }
* } );
* } );
- *
+ *
* @example
* // Specify where the filter should appear
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sSearch": "Apply filter _INPUT_ to table"
+ * "language": {
+ * "search": "Apply filter _INPUT_ to table"
* }
* } );
* } );
*/
"sSearch": "Search:",
-
-
+
+
+ /**
+ * Assign a `placeholder` attribute to the search `input` element
+ * @type string
+ * @default
+ *
+ * @dtopt Language
+ * @name DataTable.defaults.language.searchPlaceholder
+ */
+ "sSearchPlaceholder": "",
+
+
/**
* All of the language information can be stored in a file on the
* server-side, which DataTables will look up if this parameter is passed.
@@ -9493,33 +11416,37 @@
* the example language files to see how this works in action.
* @type string
* @default <i>Empty string - i.e. disabled</i>
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.url
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sUrl": "http://www.sprymedia.co.uk/dataTables/lang.txt"
+ * "language": {
+ * "url": "http://www.sprymedia.co.uk/dataTables/lang.txt"
* }
* } );
* } );
*/
"sUrl": "",
-
-
+
+
/**
* Text shown inside the table records when the is no information to be
- * displayed after filtering. sEmptyTable is shown when there is simply no
+ * displayed after filtering. `emptyTable` is shown when there is simply no
* information in the table at all (regardless of filtering).
* @type string
* @default No matching records found
+ *
* @dtopt Language
- *
+ * @name DataTable.defaults.language.zeroRecords
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oLanguage": {
- * "sZeroRecords": "No records to display"
+ * "language": {
+ * "zeroRecords": "No records to display"
* }
* } );
* } );
@@ -9530,20 +11457,22 @@
/**
* This parameter allows you to have define the global filtering state at
- * initialisation time. As an object the "sSearch" parameter must be
- * defined, but all other parameters are optional. When "bRegex" is true,
+ * initialisation time. As an object the `search` parameter must be
+ * defined, but all other parameters are optional. When `regex` is true,
* the search string will be treated as a regular expression, when false
- * (default) it will be treated as a straight string. When "bSmart"
+ * (default) it will be treated as a straight string. When `smart`
* DataTables will use it's smart filtering methods (to word match at
* any point in the data), when false this will not be done.
* @namespace
* @extends DataTable.models.oSearch
+ *
* @dtopt Options
- *
+ * @name DataTable.defaults.search
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "oSearch": {"sSearch": "Initial search"}
+ * "search": {"search": "Initial search"}
* } );
* } )
*/
@@ -9551,83 +11480,55 @@
/**
- * By default DataTables will look for the property 'aaData' when obtaining
- * data from an Ajax source or for server-side processing - this parameter
- * allows that property to be changed. You can use Javascript dotted object
- * notation to get a data source for multiple levels of nesting.
+ * __Deprecated__ The functionality provided by this parameter has now been
+ * superseded by that provided through `ajax`, which should be used instead.
+ *
+ * By default DataTables will look for the property `data` (or `aaData` for
+ * compatibility with DataTables 1.9-) when obtaining data from an Ajax
+ * source or for server-side processing - this parameter allows that
+ * property to be changed. You can use Javascript dotted object notation to
+ * get a data source for multiple levels of nesting.
* @type string
- * @default aaData
+ * @default data
+ *
* @dtopt Options
* @dtopt Server-side
- *
- * @example
- * // Get data from { "data": [...] }
- * $(document).ready( function() {
- * var oTable = $('#example').dataTable( {
- * "sAjaxSource": "sources/data.txt",
- * "sAjaxDataProp": "data"
- * } );
- * } );
- *
- * @example
- * // Get data from { "data": { "inner": [...] } }
- * $(document).ready( function() {
- * var oTable = $('#example').dataTable( {
- * "sAjaxSource": "sources/data.txt",
- * "sAjaxDataProp": "data.inner"
- * } );
- * } );
+ * @name DataTable.defaults.ajaxDataProp
+ *
+ * @deprecated 1.10. Please use `ajax` for this functionality now.
*/
- "sAjaxDataProp": "aaData",
+ "sAjaxDataProp": "data",
/**
- * You can instruct DataTables to load data from an external source using this
- * parameter (use aData if you want to pass data in you already have). Simply
- * provide a url a JSON object can be obtained from. This object must include
- * the parameter 'aaData' which is the data source for the table.
+ * __Deprecated__ The functionality provided by this parameter has now been
+ * superseded by that provided through `ajax`, which should be used instead.
+ *
+ * You can instruct DataTables to load data from an external
+ * source using this parameter (use aData if you want to pass data in you
+ * already have). Simply provide a url a JSON object can be obtained from.
* @type string
* @default null
+ *
* @dtopt Options
* @dtopt Server-side
- *
- * @example
- * $(document).ready( function() {
- * $('#example').dataTable( {
- * "sAjaxSource": "http://www.sprymedia.co.uk/dataTables/json.php"
- * } );
- * } )
+ * @name DataTable.defaults.ajaxSource
+ *
+ * @deprecated 1.10. Please use `ajax` for this functionality now.
*/
"sAjaxSource": null,
/**
- * This parameter can be used to override the default prefix that DataTables
- * assigns to a cookie when state saving is enabled.
- * @type string
- * @default SpryMedia_DataTables_
- * @dtopt Options
- *
- * @example
- * $(document).ready( function() {
- * $('#example').dataTable( {
- * "sCookiePrefix": "my_datatable_",
- * } );
- * } );
- */
- "sCookiePrefix": "SpryMedia_DataTables_",
-
-
- /**
* This initialisation variable allows you to specify exactly where in the
* DOM you want DataTables to inject the various controls it adds to the page
* (for example you might want the pagination controls at the top of the
* table). DIV elements (with or without a custom class) can also be added to
* aid styling. The follow syntax is used:
* <ul>
- * <li>The following options are allowed:
+ * <li>The following options are allowed:
* <ul>
- * <li>'l' - Length changing</li
+ * <li>'l' - Length changing</li>
* <li>'f' - Filtering input</li>
* <li>'t' - The table!</li>
* <li>'i' - Information</li>
@@ -9656,14 +11557,16 @@
* </li>
* </ul>
* @type string
- * @default lfrtip <i>(when bJQueryUI is false)</i> <b>or</b>
- * <"H"lfr>t<"F"ip> <i>(when bJQueryUI is true)</i>
+ * @default lfrtip <i>(when `jQueryUI` is false)</i> <b>or</b>
+ * <"H"lfr>t<"F"ip> <i>(when `jQueryUI` is true)</i>
+ *
* @dtopt Options
- *
+ * @name DataTable.defaults.dom
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "sDom": '&lt;"top"i&gt;rt&lt;"bottom"flp&gt;&lt;"clear"&gt;'
+ * "dom": '&lt;"top"i&gt;rt&lt;"bottom"flp&gt;&lt;"clear"&gt;'
* } );
* } );
*/
@@ -9671,38 +11574,71 @@
/**
- * DataTables features two different built-in pagination interaction methods
- * ('two_button' or 'full_numbers') which present different page controls to
- * the end user. Further methods can be added using the API (see below).
- * @type string
- * @default two_button
+ * Search delay option. This will throttle full table searches that use the
+ * DataTables provided search input element (it does not effect calls to
+ * `dt-api search()`, providing a delay before the search is made.
+ * @type integer
+ * @default 0
+ *
* @dtopt Options
- *
+ * @name DataTable.defaults.searchDelay
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "sPaginationType": "full_numbers"
+ * "searchDelay": 200
* } );
* } )
*/
- "sPaginationType": "two_button",
+ "searchDelay": null,
/**
- * Enable horizontal scrolling. When a table is too wide to fit into a certain
- * layout, or you have a large number of columns in the table, you can enable
- * x-scrolling to show the table in a viewport, which can be scrolled. This
- * property can be any CSS unit, or a number (in which case it will be treated
- * as a pixel measurement).
+ * DataTables features four different built-in options for the buttons to
+ * display for pagination control:
+ *
+ * * `simple` - 'Previous' and 'Next' buttons only
+ * * 'simple_numbers` - 'Previous' and 'Next' buttons, plus page numbers
+ * * `full` - 'First', 'Previous', 'Next' and 'Last' buttons
+ * * `full_numbers` - 'First', 'Previous', 'Next' and 'Last' buttons, plus
+ * page numbers
+ *
+ * Further methods can be added using {@link DataTable.ext.oPagination}.
* @type string
+ * @default simple_numbers
+ *
+ * @dtopt Options
+ * @name DataTable.defaults.pagingType
+ *
+ * @example
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "pagingType": "full_numbers"
+ * } );
+ * } )
+ */
+ "sPaginationType": "simple_numbers",
+
+
+ /**
+ * Enable horizontal scrolling. When a table is too wide to fit into a
+ * certain layout, or you have a large number of columns in the table, you
+ * can enable x-scrolling to show the table in a viewport, which can be
+ * scrolled. This property can be `true` which will allow the table to
+ * scroll horizontally when needed, or any CSS unit, or a number (in which
+ * case it will be treated as a pixel measurement). Setting as simply `true`
+ * is recommended.
+ * @type boolean|string
* @default <i>blank string - i.e. disabled</i>
+ *
* @dtopt Features
- *
+ * @name DataTable.defaults.scrollX
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "sScrollX": "100%",
- * "bScrollCollapse": true
+ * "scrollX": true,
+ * "scrollCollapse": true
* } );
* } );
*/
@@ -9718,13 +11654,15 @@
* measurement).
* @type string
* @default <i>blank string - i.e. disabled</i>
+ *
* @dtopt Options
- *
+ * @name DataTable.defaults.scrollXInner
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "sScrollX": "100%",
- * "sScrollXInner": "110%"
+ * "scrollX": "100%",
+ * "scrollXInner": "110%"
* } );
* } );
*/
@@ -9740,13 +11678,15 @@
* (in which case it will be treated as a pixel measurement).
* @type string
* @default <i>blank string - i.e. disabled</i>
+ *
* @dtopt Features
- *
+ * @name DataTable.defaults.scrollY
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "sScrollY": "200px",
- * "bPaginate": false
+ * "scrollY": "200px",
+ * "paginate": false
* } );
* } );
*/
@@ -9754,60 +11694,87 @@
/**
+ * __Deprecated__ The functionality provided by this parameter has now been
+ * superseded by that provided through `ajax`, which should be used instead.
+ *
* Set the HTTP method that is used to make the Ajax call for server-side
* processing or Ajax sourced data.
* @type string
* @default GET
+ *
* @dtopt Options
* @dtopt Server-side
- *
- * @example
- * $(document).ready( function() {
- * $('#example').dataTable( {
- * "bServerSide": true,
- * "sAjaxSource": "scripts/post.php",
- * "sServerMethod": "POST"
- * } );
- * } );
+ * @name DataTable.defaults.serverMethod
+ *
+ * @deprecated 1.10. Please use `ajax` for this functionality now.
+ */
+ "sServerMethod": "GET",
+
+
+ /**
+ * DataTables makes use of renderers when displaying HTML elements for
+ * a table. These renderers can be added or modified by plug-ins to
+ * generate suitable mark-up for a site. For example the Bootstrap
+ * integration plug-in for DataTables uses a paging button renderer to
+ * display pagination buttons in the mark-up required by Bootstrap.
+ *
+ * For further information about the renderers available see
+ * DataTable.ext.renderer
+ * @type string|object
+ * @default null
+ *
+ * @name DataTable.defaults.renderer
+ *
*/
- "sServerMethod": "GET"
+ "renderer": null
};
+ _fnHungarianMap( DataTable.defaults );
+
+
+ /*
+ * Developer note - See note in model.defaults.js about the use of Hungarian
+ * notation and camel case.
+ */
/**
* Column options that can be given to DataTables at initialisation time.
* @namespace
*/
- DataTable.defaults.columns = {
- /**
- * Allows a column's sorting to take multiple columns into account when
- * doing a sort. For example first name / last name columns make sense to
- * do a multi-column sort over the two columns.
- * @type array
+ DataTable.defaults.column = {
+ /**
+ * Define which column(s) an order will occur on for this column. This
+ * allows a column's ordering to take multiple columns into account when
+ * doing a sort or use the data from a different column. For example first
+ * name / last name columns make sense to do a multi-column sort over the
+ * two columns.
+ * @type array|int
* @default null <i>Takes the value of the column index automatically</i>
+ *
+ * @name DataTable.defaults.column.orderData
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumnDefs
+ * // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [
- * { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
- * { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
- * { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
+ * "columnDefs": [
+ * { "orderData": [ 0, 1 ], "targets": [ 0 ] },
+ * { "orderData": [ 1, 0 ], "targets": [ 1 ] },
+ * { "orderData": 2, "targets": [ 2 ] }
* ]
* } );
* } );
- *
+ *
* @example
- * // Using aoColumns
+ * // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
- * { "aDataSort": [ 0, 1 ] },
- * { "aDataSort": [ 1, 0 ] },
- * { "aDataSort": [ 2, 3, 4 ] },
+ * "columns": [
+ * { "orderData": [ 0, 1 ] },
+ * { "orderData": [ 1, 0 ] },
+ * { "orderData": 2 },
* null,
* null
* ]
@@ -9815,37 +11782,40 @@
* } );
*/
"aDataSort": null,
+ "iDataSort": -1,
/**
- * You can control the default sorting direction, and even alter the behaviour
- * of the sort handler (i.e. only allow ascending sorting etc) using this
- * parameter.
+ * You can control the default ordering direction, and even alter the
+ * behaviour of the sort handler (i.e. only allow ascending ordering etc)
+ * using this parameter.
* @type array
* @default [ 'asc', 'desc' ]
+ *
+ * @name DataTable.defaults.column.orderSequence
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumnDefs
+ * // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [
- * { "asSorting": [ "asc" ], "aTargets": [ 1 ] },
- * { "asSorting": [ "desc", "asc", "asc" ], "aTargets": [ 2 ] },
- * { "asSorting": [ "desc" ], "aTargets": [ 3 ] }
+ * "columnDefs": [
+ * { "orderSequence": [ "asc" ], "targets": [ 1 ] },
+ * { "orderSequence": [ "desc", "asc", "asc" ], "targets": [ 2 ] },
+ * { "orderSequence": [ "desc" ], "targets": [ 3 ] }
* ]
* } );
* } );
- *
+ *
* @example
- * // Using aoColumns
+ * // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
+ * "columns": [
* null,
- * { "asSorting": [ "asc" ] },
- * { "asSorting": [ "desc", "asc", "asc" ] },
- * { "asSorting": [ "desc" ] },
+ * { "orderSequence": [ "asc" ] },
+ * { "orderSequence": [ "desc", "asc", "asc" ] },
+ * { "orderSequence": [ "desc" ] },
* null
* ]
* } );
@@ -9858,23 +11828,25 @@
* Enable or disable filtering on the data in this column.
* @type boolean
* @default true
+ *
+ * @name DataTable.defaults.column.searchable
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumnDefs
+ * // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [
- * { "bSearchable": false, "aTargets": [ 0 ] }
+ * "columnDefs": [
+ * { "searchable": false, "targets": [ 0 ] }
* ] } );
* } );
- *
+ *
* @example
- * // Using aoColumns
+ * // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
- * { "bSearchable": false },
+ * "columns": [
+ * { "searchable": false },
* null,
* null,
* null,
@@ -9886,26 +11858,28 @@
/**
- * Enable or disable sorting on this column.
+ * Enable or disable ordering on this column.
* @type boolean
* @default true
+ *
+ * @name DataTable.defaults.column.orderable
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumnDefs
+ * // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [
- * { "bSortable": false, "aTargets": [ 0 ] }
+ * "columnDefs": [
+ * { "orderable": false, "targets": [ 0 ] }
* ] } );
* } );
- *
+ *
* @example
- * // Using aoColumns
+ * // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
- * { "bSortable": false },
+ * "columns": [
+ * { "orderable": false },
* null,
* null,
* null,
@@ -9917,43 +11891,28 @@
/**
- * <code>Deprecated</code> When using fnRender() for a column, you may wish
- * to use the original data (before rendering) for sorting and filtering
- * (the default is to used the rendered data that the user can see). This
- * may be useful for dates etc.
- *
- * Please note that this option has now been deprecated and will be removed
- * in the next version of DataTables. Please use mRender / mData rather than
- * fnRender.
- * @type boolean
- * @default true
- * @dtopt Columns
- * @deprecated
- */
- "bUseRendered": true,
-
-
- /**
* Enable or disable the display of this column.
* @type boolean
* @default true
+ *
+ * @name DataTable.defaults.column.visible
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumnDefs
+ * // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [
- * { "bVisible": false, "aTargets": [ 0 ] }
+ * "columnDefs": [
+ * { "visible": false, "targets": [ 0 ] }
* ] } );
* } );
- *
+ *
* @example
- * // Using aoColumns
+ * // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
- * { "bVisible": false },
+ * "columns": [
+ * { "visible": false },
* null,
* null,
* null,
@@ -9962,29 +11921,31 @@
* } );
*/
"bVisible": true,
-
-
+
+
/**
* Developer definable function that is called whenever a cell is created (Ajax source,
* etc) or processed for input (DOM source). This can be used as a compliment to mRender
* allowing you to modify the DOM element (add background colour for example) when the
* element is available.
* @type function
- * @param {element} nTd The TD node that has been created
- * @param {*} sData The Data for the cell
- * @param {array|object} oData The data for the whole row
- * @param {int} iRow The row index for the aoData data store
- * @param {int} iCol The column index for aoColumns
+ * @param {element} td The TD node that has been created
+ * @param {*} cellData The Data for the cell
+ * @param {array|object} rowData The data for the whole row
+ * @param {int} row The row index for the aoData data store
+ * @param {int} col The column index for aoColumns
+ *
+ * @name DataTable.defaults.column.createdCell
* @dtopt Columns
- *
+ *
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [ {
- * "aTargets": [3],
- * "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
- * if ( sData == "1.7" ) {
- * $(nTd).css('color', 'blue')
+ * "columnDefs": [ {
+ * "targets": [3],
+ * "createdCell": function (td, cellData, rowData, row, col) {
+ * if ( cellData == "1.7" ) {
+ * $(td).css('color', 'blue')
* }
* }
* } ]
@@ -9995,132 +11956,139 @@
/**
- * <code>Deprecated</code> Custom display function that will be called for the
- * display of each cell in this column.
- *
- * Please note that this option has now been deprecated and will be removed
- * in the next version of DataTables. Please use mRender / mData rather than
- * fnRender.
- * @type function
- * @param {object} o Object with the following parameters:
- * @param {int} o.iDataRow The row in aoData
- * @param {int} o.iDataColumn The column in question
- * @param {array} o.aData The data for the row in question
- * @param {object} o.oSettings The settings object for this DataTables instance
- * @param {object} o.mDataProp The data property used for this column
- * @param {*} val The current cell value
- * @returns {string} The string you which to use in the display
- * @dtopt Columns
- * @deprecated
+ * This parameter has been replaced by `data` in DataTables to ensure naming
+ * consistency. `dataProp` can still be used, as there is backwards
+ * compatibility in DataTables for this option, but it is strongly
+ * recommended that you use `data` in preference to `dataProp`.
+ * @name DataTable.defaults.column.dataProp
*/
- "fnRender": null,
/**
- * The column index (starting from 0!) that you wish a sort to be performed
- * upon when this column is selected for sorting. This can be used for sorting
- * on hidden columns for example.
- * @type int
- * @default -1 <i>Use automatically calculated column index</i>
+ * This property can be used to read data from any data source property,
+ * including deeply nested objects / properties. `data` can be given in a
+ * number of different ways which effect its behaviour:
+ *
+ * * `integer` - treated as an array index for the data source. This is the
+ * default that DataTables uses (incrementally increased for each column).
+ * * `string` - read an object property from the data source. There are
+ * three 'special' options that can be used in the string to alter how
+ * DataTables reads the data from the source object:
+ * * `.` - Dotted Javascript notation. Just as you use a `.` in
+ * Javascript to read from nested objects, so to can the options
+ * specified in `data`. For example: `browser.version` or
+ * `browser.name`. If your object parameter name contains a period, use
+ * `\\` to escape it - i.e. `first\\.name`.
+ * * `[]` - Array notation. DataTables can automatically combine data
+ * from and array source, joining the data with the characters provided
+ * between the two brackets. For example: `name[, ]` would provide a
+ * comma-space separated list from the source array. If no characters
+ * are provided between the brackets, the original array source is
+ * returned.
+ * * `()` - Function notation. Adding `()` to the end of a parameter will
+ * execute a function of the name given. For example: `browser()` for a
+ * simple function on the data source, `browser.version()` for a
+ * function in a nested property or even `browser().version` to get an
+ * object property if the function called returns an object. Note that
+ * function notation is recommended for use in `render` rather than
+ * `data` as it is much simpler to use as a renderer.
+ * * `null` - use the original data source for the row rather than plucking
+ * data directly from it. This action has effects on two other
+ * initialisation options:
+ * * `defaultContent` - When null is given as the `data` option and
+ * `defaultContent` is specified for the column, the value defined by
+ * `defaultContent` will be used for the cell.
+ * * `render` - When null is used for the `data` option and the `render`
+ * option is specified for the column, the whole data source for the
+ * row is used for the renderer.
+ * * `function` - the function given will be executed whenever DataTables
+ * needs to set or get the data for a cell in the column. The function
+ * takes three parameters:
+ * * Parameters:
+ * * `{array|object}` The data source for the row
+ * * `{string}` The type call data requested - this will be 'set' when
+ * setting data or 'filter', 'display', 'type', 'sort' or undefined
+ * when gathering data. Note that when `undefined` is given for the
+ * type DataTables expects to get the raw data for the object back<
+ * * `{*}` Data to set when the second parameter is 'set'.
+ * * Return:
+ * * The return value from the function is not required when 'set' is
+ * the type of call, but otherwise the return is what will be used
+ * for the data requested.
+ *
+ * Note that `data` is a getter and setter option. If you just require
+ * formatting of data for output, you will likely want to use `render` which
+ * is simply a getter and thus simpler to use.
+ *
+ * Note that prior to DataTables 1.9.2 `data` was called `mDataProp`. The
+ * name change reflects the flexibility of this property and is consistent
+ * with the naming of mRender. If 'mDataProp' is given, then it will still
+ * be used by DataTables, as it automatically maps the old name to the new
+ * if required.
+ *
+ * @type string|int|function|null
+ * @default null <i>Use automatically calculated column index</i>
+ *
+ * @name DataTable.defaults.column.data
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumnDefs
+ * // Read table data from objects
+ * // JSON structure for each row:
+ * // {
+ * // "engine": {value},
+ * // "browser": {value},
+ * // "platform": {value},
+ * // "version": {value},
+ * // "grade": {value}
+ * // }
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [
- * { "iDataSort": 1, "aTargets": [ 0 ] }
+ * "ajaxSource": "sources/objects.txt",
+ * "columns": [
+ * { "data": "engine" },
+ * { "data": "browser" },
+ * { "data": "platform" },
+ * { "data": "version" },
+ * { "data": "grade" }
* ]
* } );
* } );
- *
+ *
* @example
- * // Using aoColumns
+ * // Read information from deeply nested objects
+ * // JSON structure for each row:
+ * // {
+ * // "engine": {value},
+ * // "browser": {value},
+ * // "platform": {
+ * // "inner": {value}
+ * // },
+ * // "details": [
+ * // {value}, {value}
+ * // ]
+ * // }
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
- * { "iDataSort": 1 },
- * null,
- * null,
- * null,
- * null
+ * "ajaxSource": "sources/deep.txt",
+ * "columns": [
+ * { "data": "engine" },
+ * { "data": "browser" },
+ * { "data": "platform.inner" },
+ * { "data": "platform.details.0" },
+ * { "data": "platform.details.1" }
* ]
* } );
* } );
- */
- "iDataSort": -1,
-
-
- /**
- * This parameter has been replaced by mData in DataTables to ensure naming
- * consistency. mDataProp can still be used, as there is backwards compatibility
- * in DataTables for this option, but it is strongly recommended that you use
- * mData in preference to mDataProp.
- * @name DataTable.defaults.columns.mDataProp
- */
-
-
- /**
- * This property can be used to read data from any JSON data source property,
- * including deeply nested objects / properties. mData can be given in a
- * number of different ways which effect its behaviour:
- * <ul>
- * <li>integer - treated as an array index for the data source. This is the
- * default that DataTables uses (incrementally increased for each column).</li>
- * <li>string - read an object property from the data source. Note that you can
- * use Javascript dotted notation to read deep properties / arrays from the
- * data source.</li>
- * <li>null - the sDefaultContent option will be used for the cell (null
- * by default, so you will need to specify the default content you want -
- * typically an empty string). This can be useful on generated columns such
- * as edit / delete action columns.</li>
- * <li>function - the function given will be executed whenever DataTables
- * needs to set or get the data for a cell in the column. The function
- * takes three parameters:
- * <ul>
- * <li>{array|object} The data source for the row</li>
- * <li>{string} The type call data requested - this will be 'set' when
- * setting data or 'filter', 'display', 'type', 'sort' or undefined when
- * gathering data. Note that when <i>undefined</i> is given for the type
- * DataTables expects to get the raw data for the object back</li>
- * <li>{*} Data to set when the second parameter is 'set'.</li>
- * </ul>
- * The return value from the function is not required when 'set' is the type
- * of call, but otherwise the return is what will be used for the data
- * requested.</li>
- * </ul>
*
- * Note that prior to DataTables 1.9.2 mData was called mDataProp. The name change
- * reflects the flexibility of this property and is consistent with the naming of
- * mRender. If 'mDataProp' is given, then it will still be used by DataTables, as
- * it automatically maps the old name to the new if required.
- * @type string|int|function|null
- * @default null <i>Use automatically calculated column index</i>
- * @dtopt Columns
- *
- * @example
- * // Read table data from objects
- * $(document).ready( function() {
- * var oTable = $('#example').dataTable( {
- * "sAjaxSource": "sources/deep.txt",
- * "aoColumns": [
- * { "mData": "engine" },
- * { "mData": "browser" },
- * { "mData": "platform.inner" },
- * { "mData": "platform.details.0" },
- * { "mData": "platform.details.1" }
- * ]
- * } );
- * } );
- *
* @example
- * // Using mData as a function to provide different information for
+ * // Using `data` as a function to provide different information for
* // sorting, filtering and display. In this case, currency (price)
* $(document).ready( function() {
- * var oTable = $('#example').dataTable( {
- * "aoColumnDefs": [ {
- * "aTargets": [ 0 ],
- * "mData": function ( source, type, val ) {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "data": function ( source, type, val ) {
* if (type === 'set') {
* source.price = val;
* // Store the computed dislay and filter values for efficiency
@@ -10140,73 +12108,150 @@
* } ]
* } );
* } );
+ *
+ * @example
+ * // Using default content
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "data": null,
+ * "defaultContent": "Click to edit"
+ * } ]
+ * } );
+ * } );
+ *
+ * @example
+ * // Using array notation - outputting a list from an array
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "data": "name[, ]"
+ * } ]
+ * } );
+ * } );
+ *
*/
"mData": null,
/**
- * This property is the rendering partner to mData and it is suggested that
- * when you want to manipulate data for display (including filtering, sorting etc)
- * but not altering the underlying data for the table, use this property. mData
- * can actually do everything this property can and more, but this parameter is
- * easier to use since there is no 'set' option. Like mData is can be given
- * in a number of different ways to effect its behaviour, with the addition of
- * supporting array syntax for easy outputting of arrays (including arrays of
- * objects):
- * <ul>
- * <li>integer - treated as an array index for the data source. This is the
- * default that DataTables uses (incrementally increased for each column).</li>
- * <li>string - read an object property from the data source. Note that you can
- * use Javascript dotted notation to read deep properties / arrays from the
- * data source and also array brackets to indicate that the data reader should
- * loop over the data source array. When characters are given between the array
- * brackets, these characters are used to join the data source array together.
- * For example: "accounts[, ].name" would result in a comma separated list with
- * the 'name' value from the 'accounts' array of objects.</li>
- * <li>function - the function given will be executed whenever DataTables
- * needs to set or get the data for a cell in the column. The function
- * takes three parameters:
- * <ul>
- * <li>{array|object} The data source for the row (based on mData)</li>
- * <li>{string} The type call data requested - this will be 'filter', 'display',
- * 'type' or 'sort'.</li>
- * <li>{array|object} The full data source for the row (not based on mData)</li>
- * </ul>
- * The return value from the function is what will be used for the data
- * requested.</li>
- * </ul>
- * @type string|int|function|null
- * @default null <i>Use mData</i>
+ * This property is the rendering partner to `data` and it is suggested that
+ * when you want to manipulate data for display (including filtering,
+ * sorting etc) without altering the underlying data for the table, use this
+ * property. `render` can be considered to be the the read only companion to
+ * `data` which is read / write (then as such more complex). Like `data`
+ * this option can be given in a number of different ways to effect its
+ * behaviour:
+ *
+ * * `integer` - treated as an array index for the data source. This is the
+ * default that DataTables uses (incrementally increased for each column).
+ * * `string` - read an object property from the data source. There are
+ * three 'special' options that can be used in the string to alter how
+ * DataTables reads the data from the source object:
+ * * `.` - Dotted Javascript notation. Just as you use a `.` in
+ * Javascript to read from nested objects, so to can the options
+ * specified in `data`. For example: `browser.version` or
+ * `browser.name`. If your object parameter name contains a period, use
+ * `\\` to escape it - i.e. `first\\.name`.
+ * * `[]` - Array notation. DataTables can automatically combine data
+ * from and array source, joining the data with the characters provided
+ * between the two brackets. For example: `name[, ]` would provide a
+ * comma-space separated list from the source array. If no characters
+ * are provided between the brackets, the original array source is
+ * returned.
+ * * `()` - Function notation. Adding `()` to the end of a parameter will
+ * execute a function of the name given. For example: `browser()` for a
+ * simple function on the data source, `browser.version()` for a
+ * function in a nested property or even `browser().version` to get an
+ * object property if the function called returns an object.
+ * * `object` - use different data for the different data types requested by
+ * DataTables ('filter', 'display', 'type' or 'sort'). The property names
+ * of the object is the data type the property refers to and the value can
+ * defined using an integer, string or function using the same rules as
+ * `render` normally does. Note that an `_` option _must_ be specified.
+ * This is the default value to use if you haven't specified a value for
+ * the data type requested by DataTables.
+ * * `function` - the function given will be executed whenever DataTables
+ * needs to set or get the data for a cell in the column. The function
+ * takes three parameters:
+ * * Parameters:
+ * * {array|object} The data source for the row (based on `data`)
+ * * {string} The type call data requested - this will be 'filter',
+ * 'display', 'type' or 'sort'.
+ * * {array|object} The full data source for the row (not based on
+ * `data`)
+ * * Return:
+ * * The return value from the function is what will be used for the
+ * data requested.
+ *
+ * @type string|int|function|object|null
+ * @default null Use the data source value.
+ *
+ * @name DataTable.defaults.column.render
* @dtopt Columns
- *
+ *
* @example
* // Create a comma separated list from an array of objects
* $(document).ready( function() {
- * var oTable = $('#example').dataTable( {
- * "sAjaxSource": "sources/deep.txt",
- * "aoColumns": [
- * { "mData": "engine" },
- * { "mData": "browser" },
+ * $('#example').dataTable( {
+ * "ajaxSource": "sources/deep.txt",
+ * "columns": [
+ * { "data": "engine" },
+ * { "data": "browser" },
* {
- * "mData": "platform",
- * "mRender": "[, ].name"
+ * "data": "platform",
+ * "render": "[, ].name"
* }
* ]
* } );
* } );
- *
+ *
+ * @example
+ * // Execute a function to obtain data
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "data": null, // Use the full data source object for the renderer's source
+ * "render": "browserName()"
+ * } ]
+ * } );
+ * } );
+ *
+ * @example
+ * // As an object, extracting different data for the different types
+ * // This would be used with a data source such as:
+ * // { "phone": 5552368, "phone_filter": "5552368 555-2368", "phone_display": "555-2368" }
+ * // Here the `phone` integer is used for sorting and type detection, while `phone_filter`
+ * // (which has both forms) is used for filtering for if a user inputs either format, while
+ * // the formatted phone number is the one that is shown in the table.
+ * $(document).ready( function() {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "data": null, // Use the full data source object for the renderer's source
+ * "render": {
+ * "_": "phone",
+ * "filter": "phone_filter",
+ * "display": "phone_display"
+ * }
+ * } ]
+ * } );
+ * } );
+ *
* @example
* // Use as a function to create a link from the data source
* $(document).ready( function() {
- * var oTable = $('#example').dataTable( {
- * "aoColumnDefs": [
- * {
- * "aTargets": [ 0 ],
- * "mData": "download_link",
- * "mRender": function ( data, type, full ) {
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "data": "download_link",
+ * "render": function ( data, type, full ) {
* return '<a href="'+data+'">Download</a>';
* }
- * ]
+ * } ]
* } );
* } );
*/
@@ -10219,15 +12264,17 @@
* to act as a header for a row (you may wish to add scope='row' to the TH elements).
* @type string
* @default td
+ *
+ * @name DataTable.defaults.column.cellType
* @dtopt Columns
- *
+ *
* @example
* // Make the first column use TH cells
* $(document).ready( function() {
- * var oTable = $('#example').dataTable( {
- * "aoColumnDefs": [ {
- * "aTargets": [ 0 ],
- * "sCellType": "th"
+ * $('#example').dataTable( {
+ * "columnDefs": [ {
+ * "targets": [ 0 ],
+ * "cellType": "th"
* } ]
* } );
* } );
@@ -10239,24 +12286,26 @@
* Class to give to each cell in this column.
* @type string
* @default <i>Empty string</i>
+ *
+ * @name DataTable.defaults.column.class
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumnDefs
+ * // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [
- * { "sClass": "my_class", "aTargets": [ 0 ] }
+ * "columnDefs": [
+ * { "class": "my_class", "targets": [ 0 ] }
* ]
* } );
* } );
- *
+ *
* @example
- * // Using aoColumns
+ * // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
- * { "sClass": "my_class" },
+ * "columns": [
+ * { "class": "my_class" },
* null,
* null,
* null,
@@ -10266,32 +12315,33 @@
* } );
*/
"sClass": "",
-
+
/**
* When DataTables calculates the column widths to assign to each column,
* it finds the longest string in each column and then constructs a
* temporary table and reads the widths from that. The problem with this
- * is that "mmm" is much wider then "iiii", but the latter is a longer
+ * is that "mmm" is much wider then "iiii", but the latter is a longer
* string - thus the calculation can go wrong (doing it properly and putting
* it into an DOM object and measuring that is horribly(!) slow). Thus as
* a "work around" we provide this option. It will append its value to the
* text that is found to be the longest string for the column - i.e. padding.
- * Generally you shouldn't need this, and it is not documented on the
- * general DataTables.net documentation
+ * Generally you shouldn't need this!
* @type string
* @default <i>Empty string<i>
+ *
+ * @name DataTable.defaults.column.contentPadding
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumns
+ * // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
+ * "columns": [
* null,
* null,
* null,
* {
- * "sContentPadding": "mmm"
+ * "contentPadding": "mmm"
* }
* ]
* } );
@@ -10302,37 +12352,39 @@
/**
* Allows a default value to be given for a column's data, and will be used
- * whenever a null data source is encountered (this can be because mData
+ * whenever a null data source is encountered (this can be because `data`
* is set to null, or because the data source itself is null).
* @type string
* @default null
+ *
+ * @name DataTable.defaults.column.defaultContent
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumnDefs
+ * // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [
+ * "columnDefs": [
* {
- * "mData": null,
- * "sDefaultContent": "Edit",
- * "aTargets": [ -1 ]
+ * "data": null,
+ * "defaultContent": "Edit",
+ * "targets": [ -1 ]
* }
* ]
* } );
* } );
- *
+ *
* @example
- * // Using aoColumns
+ * // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
+ * "columns": [
* null,
* null,
* null,
* {
- * "mData": null,
- * "sDefaultContent": "Edit"
+ * "data": null,
+ * "defaultContent": "Edit"
* }
* ]
* } );
@@ -10350,32 +12402,34 @@
* client-side, your server-side code does not also need updating).
* @type string
* @default <i>Empty string</i>
+ *
+ * @name DataTable.defaults.column.name
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumnDefs
+ * // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [
- * { "sName": "engine", "aTargets": [ 0 ] },
- * { "sName": "browser", "aTargets": [ 1 ] },
- * { "sName": "platform", "aTargets": [ 2 ] },
- * { "sName": "version", "aTargets": [ 3 ] },
- * { "sName": "grade", "aTargets": [ 4 ] }
+ * "columnDefs": [
+ * { "name": "engine", "targets": [ 0 ] },
+ * { "name": "browser", "targets": [ 1 ] },
+ * { "name": "platform", "targets": [ 2 ] },
+ * { "name": "version", "targets": [ 3 ] },
+ * { "name": "grade", "targets": [ 4 ] }
* ]
* } );
* } );
- *
+ *
* @example
- * // Using aoColumns
+ * // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
- * { "sName": "engine" },
- * { "sName": "browser" },
- * { "sName": "platform" },
- * { "sName": "version" },
- * { "sName": "grade" }
+ * "columns": [
+ * { "name": "engine" },
+ * { "name": "browser" },
+ * { "name": "platform" },
+ * { "name": "version" },
+ * { "name": "grade" }
* ]
* } );
* } );
@@ -10384,38 +12438,40 @@
/**
- * Defines a data source type for the sorting which can be used to read
+ * Defines a data source type for the ordering which can be used to read
* real-time information from the table (updating the internally cached
- * version) prior to sorting. This allows sorting to occur on user editable
- * elements such as form inputs.
+ * version) prior to ordering. This allows ordering to occur on user
+ * editable elements such as form inputs.
* @type string
* @default std
+ *
+ * @name DataTable.defaults.column.orderDataType
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumnDefs
+ * // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [
- * { "sSortDataType": "dom-text", "aTargets": [ 2, 3 ] },
- * { "sType": "numeric", "aTargets": [ 3 ] },
- * { "sSortDataType": "dom-select", "aTargets": [ 4 ] },
- * { "sSortDataType": "dom-checkbox", "aTargets": [ 5 ] }
+ * "columnDefs": [
+ * { "orderDataType": "dom-text", "targets": [ 2, 3 ] },
+ * { "type": "numeric", "targets": [ 3 ] },
+ * { "orderDataType": "dom-select", "targets": [ 4 ] },
+ * { "orderDataType": "dom-checkbox", "targets": [ 5 ] }
* ]
* } );
* } );
- *
+ *
* @example
- * // Using aoColumns
+ * // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
+ * "columns": [
* null,
* null,
- * { "sSortDataType": "dom-text" },
- * { "sSortDataType": "dom-text", "sType": "numeric" },
- * { "sSortDataType": "dom-select" },
- * { "sSortDataType": "dom-checkbox" }
+ * { "orderDataType": "dom-text" },
+ * { "orderDataType": "dom-text", "type": "numeric" },
+ * { "orderDataType": "dom-select" },
+ * { "orderDataType": "dom-checkbox" }
* ]
* } );
* } );
@@ -10426,26 +12482,28 @@
/**
* The title of this column.
* @type string
- * @default null <i>Derived from the 'TH' value for this column in the
+ * @default null <i>Derived from the 'TH' value for this column in the
* original HTML table.</i>
+ *
+ * @name DataTable.defaults.column.title
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumnDefs
+ * // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [
- * { "sTitle": "My column title", "aTargets": [ 0 ] }
+ * "columnDefs": [
+ * { "title": "My column title", "targets": [ 0 ] }
* ]
* } );
* } );
- *
+ *
* @example
- * // Using aoColumns
+ * // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
- * { "sTitle": "My column title" },
+ * "columns": [
+ * { "title": "My column title" },
* null,
* null,
* null,
@@ -10458,33 +12516,35 @@
/**
- * The type allows you to specify how the data for this column will be sorted.
- * Four types (string, numeric, date and html (which will strip HTML tags
- * before sorting)) are currently available. Note that only date formats
- * understood by Javascript's Date() object will be accepted as type date. For
- * example: "Mar 26, 2008 5:03 PM". May take the values: 'string', 'numeric',
- * 'date' or 'html' (by default). Further types can be adding through
- * plug-ins.
+ * The type allows you to specify how the data for this column will be
+ * ordered. Four types (string, numeric, date and html (which will strip
+ * HTML tags before ordering)) are currently available. Note that only date
+ * formats understood by Javascript's Date() object will be accepted as type
+ * date. For example: "Mar 26, 2008 5:03 PM". May take the values: 'string',
+ * 'numeric', 'date' or 'html' (by default). Further types can be adding
+ * through plug-ins.
* @type string
* @default null <i>Auto-detected from raw data</i>
+ *
+ * @name DataTable.defaults.column.type
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumnDefs
+ * // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [
- * { "sType": "html", "aTargets": [ 0 ] }
+ * "columnDefs": [
+ * { "type": "html", "targets": [ 0 ] }
* ]
* } );
* } );
- *
+ *
* @example
- * // Using aoColumns
+ * // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
- * { "sType": "html" },
+ * "columns": [
+ * { "type": "html" },
* null,
* null,
* null,
@@ -10498,29 +12558,31 @@
/**
* Defining the width of the column, this parameter may take any CSS value
- * (3em, 20px etc). DataTables apples 'smart' widths to columns which have not
+ * (3em, 20px etc). DataTables applies 'smart' widths to columns which have not
* been given a specific width through this interface ensuring that the table
* remains readable.
* @type string
* @default null <i>Automatic</i>
+ *
+ * @name DataTable.defaults.column.width
* @dtopt Columns
- *
+ *
* @example
- * // Using aoColumnDefs
+ * // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumnDefs": [
- * { "sWidth": "20%", "aTargets": [ 0 ] }
+ * "columnDefs": [
+ * { "width": "20%", "targets": [ 0 ] }
* ]
* } );
* } );
- *
+ *
* @example
- * // Using aoColumns
+ * // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
- * "aoColumns": [
- * { "sWidth": "20%" },
+ * "columns": [
+ * { "width": "20%" },
* null,
* null,
* null,
@@ -10532,6 +12594,8 @@
"sWidth": null
};
+ _fnHungarianMap( DataTable.defaults.column );
+
/**
@@ -10539,11 +12603,11 @@
* given table, including configuration, data and current application of the
* table options. DataTables does not have a single instance for each DataTable
* with the settings attached to that instance, but rather instances of the
- * DataTable "class" are created on-the-fly as needed (typically by a
+ * DataTable "class" are created on-the-fly as needed (typically by a
* $().dataTable() call) and the settings object is then applied to that
* instance.
- *
- * Note that this object is related to {@link DataTable.defaults} but this
+ *
+ * Note that this object is related to {@link DataTable.defaults} but this
* one is the internal data store for DataTables's cache of columns. It should
* NOT be manipulated outside of DataTables. Any configuration should be done
* through the initialisation options.
@@ -10551,7 +12615,7 @@
* @todo Really should attach the settings object to individual instances so we
* don't need to create new instances on each $().dataTable() call (if the
* table already exists). It would also save passing oSettings around and
- * into every single function. However, this is a very significant
+ * into every single function. However, this is a very significant
* architecture change for DataTables and will almost certainly break
* backwards compatibility with older installations. This is something that
* will be done in 2.0.
@@ -10562,7 +12626,7 @@
* @namespace
*/
"oFeatures": {
-
+
/**
* Flag to say if DataTables should automatically try to calculate the
* optimum table and columns widths (true) or not (false).
@@ -10582,7 +12646,7 @@
* @type boolean
*/
"bDeferRender": null,
-
+
/**
* Enable filtering on the table or not. Note that if this is disabled
* then there is no filtering at all on the table, including fnFilter.
@@ -10592,7 +12656,7 @@
* @type boolean
*/
"bFilter": null,
-
+
/**
* Table information element (the 'Showing x of y records' div) enable
* flag.
@@ -10601,7 +12665,7 @@
* @type boolean
*/
"bInfo": null,
-
+
/**
* Present a user control allowing the end user to change the page size
* when pagination is enabled.
@@ -10619,7 +12683,7 @@
* @type boolean
*/
"bPaginate": null,
-
+
/**
* Processing indicator enable flag whenever DataTables is enacting a
* user request - typically an Ajax request for server-side processing.
@@ -10628,7 +12692,7 @@
* @type boolean
*/
"bProcessing": null,
-
+
/**
* Server-side processing enabled flag - when enabled DataTables will
* get all data from the server for every draw - there is no filtering,
@@ -10638,7 +12702,7 @@
* @type boolean
*/
"bServerSide": null,
-
+
/**
* Sorting enablement flag.
* Note that this parameter will be set by the initialisation routine. To
@@ -10646,7 +12710,15 @@
* @type boolean
*/
"bSort": null,
-
+
+ /**
+ * Multi-column sorting
+ * Note that this parameter will be set by the initialisation routine. To
+ * set a default use {@link DataTable.defaults}.
+ * @type boolean
+ */
+ "bSortMulti": null,
+
/**
* Apply a class to the columns which are being sorted to provide a
* visual highlight or not. This can slow things down when enabled since
@@ -10656,7 +12728,7 @@
* @type boolean
*/
"bSortClasses": null,
-
+
/**
* State saving enablement flag.
* Note that this parameter will be set by the initialisation routine. To
@@ -10665,7 +12737,7 @@
*/
"bStateSave": null
},
-
+
/**
* Scrolling settings for a table.
@@ -10673,16 +12745,6 @@
*/
"oScroll": {
/**
- * Indicate if DataTables should be allowed to set the padding / margin
- * etc for the scrolling header elements or not. Typically you will want
- * this.
- * Note that this parameter will be set by the initialisation routine. To
- * set a default use {@link DataTable.defaults}.
- * @type boolean
- */
- "bAutoCss": null,
-
- /**
* When the table is shorter in height than sScrollY, collapse the
* table container down to the height of the table (when true).
* Note that this parameter will be set by the initialisation routine. To
@@ -10690,16 +12752,7 @@
* @type boolean
*/
"bCollapse": null,
-
- /**
- * Infinite scrolling enablement flag. Now deprecated in favour of
- * using the Scroller plug-in.
- * Note that this parameter will be set by the initialisation routine. To
- * set a default use {@link DataTable.defaults}.
- * @type boolean
- */
- "bInfinite": null,
-
+
/**
* Width of the scrollbar for the web-browser's platform. Calculated
* during table initialisation.
@@ -10707,26 +12760,16 @@
* @default 0
*/
"iBarWidth": 0,
-
- /**
- * Space (in pixels) between the bottom of the scrolling container and
- * the bottom of the scrolling viewport before the next page is loaded
- * when using infinite scrolling.
- * Note that this parameter will be set by the initialisation routine. To
- * set a default use {@link DataTable.defaults}.
- * @type int
- */
- "iLoadGap": null,
-
+
/**
- * Viewport width for horizontal scrolling. Horizontal scrolling is
+ * Viewport width for horizontal scrolling. Horizontal scrolling is
* disabled if an empty string.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sX": null,
-
+
/**
* Width to expand the table to when using x-scrolling. Typically you
* should not need to use this.
@@ -10736,7 +12779,7 @@
* @deprecated
*/
"sXInner": null,
-
+
/**
* Viewport height for vertical scrolling. Vertical scrolling is disabled
* if an empty string.
@@ -10746,7 +12789,7 @@
*/
"sY": null
},
-
+
/**
* Language information for the table.
* @namespace
@@ -10754,14 +12797,14 @@
*/
"oLanguage": {
/**
- * Information callback function. See
+ * Information callback function. See
* {@link DataTable.defaults.fnInfoCallback}
* @type function
* @default null
*/
"fnInfoCallback": null
},
-
+
/**
* Browser support parameters
* @namespace
@@ -10773,11 +12816,24 @@
* @type boolean
* @default false
*/
- "bScrollOversize": false
+ "bScrollOversize": false,
+
+ /**
+ * Determine if the vertical scrollbar is on the right or left of the
+ * scrolling container - needed for rtl language layout, although not
+ * all browsers move the scrollbar (Safari).
+ * @type boolean
+ * @default false
+ */
+ "bScrollbarLeft": false
},
-
+
+
+ "ajax": null,
+
+
/**
- * Array referencing the nodes which are used for the features. The
+ * Array referencing the nodes which are used for the features. The
* parameters of this object match what is allowed by sDom - i.e.
* <ul>
* <li>'l' - Length changing</li>
@@ -10791,7 +12847,7 @@
* @default []
*/
"aanFeatures": [],
-
+
/**
* Store data information - see {@link DataTable.models.oRow} for detailed
* information.
@@ -10799,51 +12855,44 @@
* @default []
*/
"aoData": [],
-
+
/**
* Array of indexes which are in the current display (after filtering etc)
* @type array
* @default []
*/
"aiDisplay": [],
-
+
/**
* Array of indexes for display - no filtering
* @type array
* @default []
*/
"aiDisplayMaster": [],
-
+
/**
* Store information about each column that is in use
* @type array
* @default []
*/
"aoColumns": [],
-
+
/**
* Store information about the table's header
* @type array
* @default []
*/
"aoHeader": [],
-
+
/**
* Store information about the table's footer
* @type array
* @default []
*/
"aoFooter": [],
-
- /**
- * Search data array for regular expression searching
- * @type array
- * @default []
- */
- "asDataSearch": [],
-
+
/**
- * Store the applied global search information in case we want to force a
+ * Store the applied global search information in case we want to force a
* research or compare the old search to a new one.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
@@ -10851,23 +12900,22 @@
* @extends DataTable.models.oSearch
*/
"oPreviousSearch": {},
-
+
/**
- * Store the applied search for each column - see
+ * Store the applied search for each column - see
* {@link DataTable.models.oSearch} for the format that is used for the
* filtering information for each column.
* @type array
* @default []
*/
"aoPreSearchCols": [],
-
+
/**
* Sorting that is applied to the table. Note that the inner arrays are
* used in the following manner:
* <ul>
* <li>Index 0 - column number</li>
* <li>Index 1 - current sorting direction</li>
- * <li>Index 2 - index of asSorting for this column</li>
* </ul>
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
@@ -10875,17 +12923,17 @@
* @todo These inner arrays should really be objects
*/
"aaSorting": null,
-
+
/**
* Sorting that is always applied to the table (i.e. prefixed in front of
* aaSorting).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
- * @type array|null
- * @default null
+ * @type array
+ * @default []
*/
- "aaSortingFixed": null,
-
+ "aaSortingFixed": [],
+
/**
* Classes to use for the striping of a table.
* Note that this parameter will be set by the initialisation routine. To
@@ -10894,64 +12942,64 @@
* @default []
*/
"asStripeClasses": null,
-
+
/**
* If restoring a table - we should restore its striping classes as well
* @type array
* @default []
*/
"asDestroyStripes": [],
-
+
/**
- * If restoring a table - we should restore its width
+ * If restoring a table - we should restore its width
* @type int
* @default 0
*/
"sDestroyWidth": 0,
-
+
/**
* Callback functions array for every time a row is inserted (i.e. on a draw).
* @type array
* @default []
*/
"aoRowCallback": [],
-
+
/**
* Callback functions for the header on each draw.
* @type array
* @default []
*/
"aoHeaderCallback": [],
-
+
/**
* Callback function for the footer on each draw.
* @type array
* @default []
*/
"aoFooterCallback": [],
-
+
/**
* Array of callback functions for draw callback functions
* @type array
* @default []
*/
"aoDrawCallback": [],
-
+
/**
* Array of callback functions for row created function
* @type array
* @default []
*/
"aoRowCreatedCallback": [],
-
+
/**
- * Callback functions for just before the table is redrawn. A return of
+ * Callback functions for just before the table is redrawn. A return of
* false will be used to cancel the draw.
* @type array
* @default []
*/
"aoPreDrawCallback": [],
-
+
/**
* Callback functions for when the table has been initialised.
* @type array
@@ -10959,7 +13007,7 @@
*/
"aoInitComplete": [],
-
+
/**
* Callbacks for modifying the settings to be stored for state saving, prior to
* saving state.
@@ -10967,7 +13015,7 @@
* @default []
*/
"aoStateSaveParams": [],
-
+
/**
* Callbacks for modifying the settings that have been stored for state saving
* prior to using the stored values to restore the state.
@@ -10975,7 +13023,7 @@
* @default []
*/
"aoStateLoadParams": [],
-
+
/**
* Callbacks for operating on the settings object once the saved state has been
* loaded
@@ -10983,51 +13031,51 @@
* @default []
*/
"aoStateLoaded": [],
-
+
/**
* Cache the table ID for quick access
* @type string
* @default <i>Empty string</i>
*/
"sTableId": "",
-
+
/**
* The TABLE node for the main table
* @type node
* @default null
*/
"nTable": null,
-
+
/**
* Permanent ref to the thead element
* @type node
* @default null
*/
"nTHead": null,
-
+
/**
* Permanent ref to the tfoot element - if it exists
* @type node
* @default null
*/
"nTFoot": null,
-
+
/**
* Permanent ref to the tbody element
* @type node
* @default null
*/
"nTBody": null,
-
+
/**
* Cache the wrapper node (contains all DataTables controlled elements)
* @type node
* @default null
*/
"nTableWrapper": null,
-
+
/**
- * Indicate if when using server-side processing the loading of data
+ * Indicate if when using server-side processing the loading of data
* should be deferred until the second draw.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
@@ -11035,14 +13083,14 @@
* @default false
*/
"bDeferLoading": false,
-
+
/**
* Indicate if all required information has been read in
* @type boolean
* @default false
*/
"bInitialised": false,
-
+
/**
* Information about open rows. Each object in the array has the parameters
* 'nTr' and 'nParent'
@@ -11050,7 +13098,7 @@
* @default []
*/
"aoOpenRows": [],
-
+
/**
* Dictate the positioning of DataTables' control elements - see
* {@link DataTable.model.oInit.sDom}.
@@ -11060,50 +13108,39 @@
* @default null
*/
"sDom": null,
-
+
+ /**
+ * Search delay (in mS)
+ * @type integer
+ * @default null
+ */
+ "searchDelay": null,
+
/**
* Which type of pagination should be used.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
- * @type string
+ * @type string
* @default two_button
*/
"sPaginationType": "two_button",
-
+
/**
- * The cookie duration (for bStateSave) in seconds.
+ * The state duration (for `stateSave`) in seconds.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type int
* @default 0
*/
- "iCookieDuration": 0,
-
- /**
- * The cookie name prefix.
- * Note that this parameter will be set by the initialisation routine. To
- * set a default use {@link DataTable.defaults}.
- * @type string
- * @default <i>Empty string</i>
- */
- "sCookiePrefix": "",
-
- /**
- * Callback function for cookie creation.
- * Note that this parameter will be set by the initialisation routine. To
- * set a default use {@link DataTable.defaults}.
- * @type function
- * @default null
- */
- "fnCookieCallback": null,
-
+ "iStateDuration": 0,
+
/**
- * Array of callback functions for state saving. Each array element is an
+ * Array of callback functions for state saving. Each array element is an
* object with the following parameters:
* <ul>
* <li>function:fn - function to call. Takes two parameters, oSettings
* and the JSON string to save that has been thus far created. Returns
- * a JSON string to be inserted into a json object
+ * a JSON string to be inserted into a json object
* (i.e. '"param": [ 0, 1, 2]')</li>
* <li>string:sName - name of callback</li>
* </ul>
@@ -11111,12 +13148,12 @@
* @default []
*/
"aoStateSave": [],
-
+
/**
- * Array of callback functions for state loading. Each array element is an
+ * Array of callback functions for state loading. Each array element is an
* object with the following parameters:
* <ul>
- * <li>function:fn - function to call. Takes two parameters, oSettings
+ * <li>function:fn - function to call. Takes two parameters, oSettings
* and the object stored. May return false to cancel state loading</li>
* <li>string:sName - name of callback</li>
* </ul>
@@ -11124,14 +13161,21 @@
* @default []
*/
"aoStateLoad": [],
-
+
+ /**
+ * State that was saved. Useful for back reference
+ * @type object
+ * @default null
+ */
+ "oSavedState": null,
+
/**
- * State that was loaded from the cookie. Useful for back reference
+ * State that was loaded. Useful for back reference
* @type object
* @default null
*/
"oLoadedState": null,
-
+
/**
* Source url for AJAX data for the table.
* Note that this parameter will be set by the initialisation routine. To
@@ -11140,33 +13184,47 @@
* @default null
*/
"sAjaxSource": null,
-
+
/**
* Property from a given object from which to read the table data from. This
- * can be an empty string (when not server-side processing), in which case
+ * can be an empty string (when not server-side processing), in which case
* it is assumed an an array is given directly.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sAjaxDataProp": null,
-
+
/**
* Note if draw should be blocked while getting data
* @type boolean
* @default true
*/
"bAjaxDataGet": true,
-
+
/**
- * The last jQuery XHR object that was used for server-side data gathering.
- * This can be used for working with the XHR information in one of the
+ * The last jQuery XHR object that was used for server-side data gathering.
+ * This can be used for working with the XHR information in one of the
* callbacks
* @type object
* @default null
*/
"jqXHR": null,
-
+
+ /**
+ * JSON returned from the server in the last Ajax request
+ * @type object
+ * @default undefined
+ */
+ "json": undefined,
+
+ /**
+ * Data submitted as part of the last Ajax request
+ * @type object
+ * @default undefined
+ */
+ "oAjaxData": undefined,
+
/**
* Function to get the server-side data.
* Note that this parameter will be set by the initialisation routine. To
@@ -11174,24 +13232,24 @@
* @type function
*/
"fnServerData": null,
-
+
/**
- * Functions which are called prior to sending an Ajax request so extra
+ * Functions which are called prior to sending an Ajax request so extra
* parameters can easily be sent to the server
* @type array
* @default []
*/
"aoServerParams": [],
-
+
/**
- * Send the XHR HTTP method - GET or POST (could be PUT or DELETE if
+ * Send the XHR HTTP method - GET or POST (could be PUT or DELETE if
* required).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sServerMethod": null,
-
+
/**
* Format numbers for display.
* Note that this parameter will be set by the initialisation routine. To
@@ -11199,7 +13257,7 @@
* @type function
*/
"fnFormatNumber": null,
-
+
/**
* List of options that can be used for the user selectable length menu.
* Note that this parameter will be set by the initialisation routine. To
@@ -11208,7 +13266,7 @@
* @default []
*/
"aLengthMenu": null,
-
+
/**
* Counter for the draws that the table does. Also used as a tracker for
* server-side processing
@@ -11216,21 +13274,21 @@
* @default 0
*/
"iDraw": 0,
-
+
/**
* Indicate if a redraw is being done - useful for Ajax
* @type boolean
* @default false
*/
"bDrawing": false,
-
+
/**
* Draw index (iDraw) of the last error when parsing the returned data
* @type int
* @default -1
*/
"iDrawError": -1,
-
+
/**
* Paging display length
* @type int
@@ -11246,15 +13304,6 @@
"_iDisplayStart": 0,
/**
- * Paging end point - aiDisplay index. Use fnDisplayEnd rather than
- * this property to get the end point
- * @type int
- * @default 10
- * @private
- */
- "_iDisplayEnd": 10,
-
- /**
* Server-side processing - number of records in the result set
* (i.e. before filtering), Use fnRecordsTotal rather than
* this property to get the value of the number of records, regardless of
@@ -11275,7 +13324,7 @@
* @private
*/
"_iRecordsDisplay": 0,
-
+
/**
* Flag to indicate if jQuery UI marking and classes should be used.
* Note that this parameter will be set by the initialisation routine. To
@@ -11283,16 +13332,16 @@
* @type boolean
*/
"bJUI": null,
-
+
/**
* The classes to use for the table
* @type object
* @default {}
*/
"oClasses": {},
-
+
/**
- * Flag attached to the settings object so you can check in the draw
+ * Flag attached to the settings object so you can check in the draw
* callback if filtering has been done in the draw. Deprecated in favour of
* events.
* @type boolean
@@ -11300,9 +13349,9 @@
* @deprecated
*/
"bFiltered": false,
-
+
/**
- * Flag attached to the settings object so you can check in the draw
+ * Flag attached to the settings object so you can check in the draw
* callback if sorting has been done in the draw. Deprecated in favour of
* events.
* @type boolean
@@ -11310,24 +13359,24 @@
* @deprecated
*/
"bSorted": false,
-
+
/**
- * Indicate that if multiple rows are in the header and there is more than
- * one unique cell per column, if the top one (true) or bottom one (false)
+ * Indicate that if multiple rows are in the header and there is more than
+ * one unique cell per column, if the top one (true) or bottom one (false)
* should be used for sorting / title by DataTables.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bSortCellsTop": null,
-
+
/**
* Initialisation object that is used for the table
* @type object
* @default null
*/
"oInit": null,
-
+
/**
* Destroy callback functions - for plug-ins to attach themselves to the
* destroy so they can clean up markup and events.
@@ -11336,59 +13385,62 @@
*/
"aoDestroyCallback": [],
-
+
/**
* Get the number of records in the current record set, before filtering
* @type function
*/
"fnRecordsTotal": function ()
{
- if ( this.oFeatures.bServerSide ) {
- return parseInt(this._iRecordsTotal, 10);
- } else {
- return this.aiDisplayMaster.length;
- }
+ return _fnDataSource( this ) == 'ssp' ?
+ this._iRecordsTotal * 1 :
+ this.aiDisplayMaster.length;
},
-
+
/**
* Get the number of records in the current record set, after filtering
* @type function
*/
"fnRecordsDisplay": function ()
{
- if ( this.oFeatures.bServerSide ) {
- return parseInt(this._iRecordsDisplay, 10);
- } else {
- return this.aiDisplay.length;
- }
+ return _fnDataSource( this ) == 'ssp' ?
+ this._iRecordsDisplay * 1 :
+ this.aiDisplay.length;
},
-
+
/**
- * Set the display end point - aiDisplay index
+ * Get the display end point - aiDisplay index
* @type function
- * @todo Should do away with _iDisplayEnd and calculate it on-the-fly here
*/
"fnDisplayEnd": function ()
{
- if ( this.oFeatures.bServerSide ) {
- if ( this.oFeatures.bPaginate === false || this._iDisplayLength == -1 ) {
- return this._iDisplayStart+this.aiDisplay.length;
- } else {
- return Math.min( this._iDisplayStart+this._iDisplayLength,
- this._iRecordsDisplay );
- }
- } else {
- return this._iDisplayEnd;
+ var
+ len = this._iDisplayLength,
+ start = this._iDisplayStart,
+ calc = start + len,
+ records = this.aiDisplay.length,
+ features = this.oFeatures,
+ paginate = features.bPaginate;
+
+ if ( features.bServerSide ) {
+ return paginate === false || len === -1 ?
+ start + records :
+ Math.min( start+len, this._iRecordsDisplay );
+ }
+ else {
+ return ! paginate || calc>records || len===-1 ?
+ records :
+ calc;
}
},
-
+
/**
* The DataTables object for this table
* @type object
* @default null
*/
"oInstance": null,
-
+
/**
* Unique identifier for each instance of the DataTables object. If there
* is an ID on the table node, then it takes that value, otherwise an
@@ -11412,47 +13464,582 @@
/**
* DIV container for the footer scrolling table if scrolling
*/
- "nScrollFoot": null
+ "nScrollFoot": null,
+
+ /**
+ * Last applied sort
+ * @type array
+ * @default []
+ */
+ "aLastSort": [],
+
+ /**
+ * Stored plug-in instances
+ * @type object
+ * @default {}
+ */
+ "oPlugins": {}
};
/**
- * Extension object for DataTables that is used to provide all extension options.
- *
- * Note that the <i>DataTable.ext</i> object is available through
- * <i>jQuery.fn.dataTable.ext</i> where it may be accessed and manipulated. It is
- * also aliased to <i>jQuery.fn.dataTableExt</i> for historic reasons.
+ * Extension object for DataTables that is used to provide all extension
+ * options.
+ *
+ * Note that the `DataTable.ext` object is available through
+ * `jQuery.fn.dataTable.ext` where it may be accessed and manipulated. It is
+ * also aliased to `jQuery.fn.dataTableExt` for historic reasons.
* @namespace
* @extends DataTable.models.ext
*/
- DataTable.ext = $.extend( true, {}, DataTable.models.ext );
- $.extend( DataTable.ext.oStdClasses, {
+
+ /**
+ * DataTables extensions
+ *
+ * This namespace acts as a collection area for plug-ins that can be used to
+ * extend DataTables capabilities. Indeed many of the build in methods
+ * use this method to provide their own capabilities (sorting methods for
+ * example).
+ *
+ * Note that this namespace is aliased to `jQuery.fn.dataTableExt` for legacy
+ * reasons
+ *
+ * @namespace
+ */
+ DataTable.ext = _ext = {
+ /**
+ * Buttons. For use with the Buttons extension for DataTables. This is
+ * defined here so other extensions can define buttons regardless of load
+ * order. It is _not_ used by DataTables core.
+ *
+ * @type object
+ * @default {}
+ */
+ buttons: {},
+
+
+ /**
+ * Element class names
+ *
+ * @type object
+ * @default {}
+ */
+ classes: {},
+
+
+ /**
+ * Error reporting.
+ *
+ * How should DataTables report an error. Can take the value 'alert',
+ * 'throw', 'none' or a function.
+ *
+ * @type string|function
+ * @default alert
+ */
+ errMode: "alert",
+
+
+ /**
+ * Feature plug-ins.
+ *
+ * This is an array of objects which describe the feature plug-ins that are
+ * available to DataTables. These feature plug-ins are then available for
+ * use through the `dom` initialisation option.
+ *
+ * Each feature plug-in is described by an object which must have the
+ * following properties:
+ *
+ * * `fnInit` - function that is used to initialise the plug-in,
+ * * `cFeature` - a character so the feature can be enabled by the `dom`
+ * instillation option. This is case sensitive.
+ *
+ * The `fnInit` function has the following input parameters:
+ *
+ * 1. `{object}` DataTables settings object: see
+ * {@link DataTable.models.oSettings}
+ *
+ * And the following return is expected:
+ *
+ * * {node|null} The element which contains your feature. Note that the
+ * return may also be void if your plug-in does not require to inject any
+ * DOM elements into DataTables control (`dom`) - for example this might
+ * be useful when developing a plug-in which allows table control via
+ * keyboard entry
+ *
+ * @type array
+ *
+ * @example
+ * $.fn.dataTable.ext.features.push( {
+ * "fnInit": function( oSettings ) {
+ * return new TableTools( { "oDTSettings": oSettings } );
+ * },
+ * "cFeature": "T"
+ * } );
+ */
+ feature: [],
+
+
+ /**
+ * Row searching.
+ *
+ * This method of searching is complimentary to the default type based
+ * searching, and a lot more comprehensive as it allows you complete control
+ * over the searching logic. Each element in this array is a function
+ * (parameters described below) that is called for every row in the table,
+ * and your logic decides if it should be included in the searching data set
+ * or not.
+ *
+ * Searching functions have the following input parameters:
+ *
+ * 1. `{object}` DataTables settings object: see
+ * {@link DataTable.models.oSettings}
+ * 2. `{array|object}` Data for the row to be processed (same as the
+ * original format that was passed in as the data source, or an array
+ * from a DOM data source
+ * 3. `{int}` Row index ({@link DataTable.models.oSettings.aoData}), which
+ * can be useful to retrieve the `TR` element if you need DOM interaction.
+ *
+ * And the following return is expected:
+ *
+ * * {boolean} Include the row in the searched result set (true) or not
+ * (false)
+ *
+ * Note that as with the main search ability in DataTables, technically this
+ * is "filtering", since it is subtractive. However, for consistency in
+ * naming we call it searching here.
+ *
+ * @type array
+ * @default []
+ *
+ * @example
+ * // The following example shows custom search being applied to the
+ * // fourth column (i.e. the data[3] index) based on two input values
+ * // from the end-user, matching the data in a certain range.
+ * $.fn.dataTable.ext.search.push(
+ * function( settings, data, dataIndex ) {
+ * var min = document.getElementById('min').value * 1;
+ * var max = document.getElementById('max').value * 1;
+ * var version = data[3] == "-" ? 0 : data[3]*1;
+ *
+ * if ( min == "" && max == "" ) {
+ * return true;
+ * }
+ * else if ( min == "" && version < max ) {
+ * return true;
+ * }
+ * else if ( min < version && "" == max ) {
+ * return true;
+ * }
+ * else if ( min < version && version < max ) {
+ * return true;
+ * }
+ * return false;
+ * }
+ * );
+ */
+ search: [],
+
+
+ /**
+ * Selector extensions
+ *
+ * The `selector` option can be used to extend the options available for the
+ * selector modifier options (`selector-modifier` object data type) that
+ * each of the three built in selector types offer (row, column and cell +
+ * their plural counterparts). For example the Select extension uses this
+ * mechanism to provide an option to select only rows, columns and cells
+ * that have been marked as selected by the end user (`{selected: true}`),
+ * which can be used in conjunction with the existing built in selector
+ * options.
+ *
+ * Each property is an array to which functions can be pushed. The functions
+ * take three attributes:
+ *
+ * * Settings object for the host table
+ * * Options object (`selector-modifier` object type)
+ * * Array of selected item indexes
+ *
+ * The return is an array of the resulting item indexes after the custom
+ * selector has been applied.
+ *
+ * @type object
+ */
+ selector: {
+ cell: [],
+ column: [],
+ row: []
+ },
+
+
+ /**
+ * Internal functions, exposed for used in plug-ins.
+ *
+ * Please note that you should not need to use the internal methods for
+ * anything other than a plug-in (and even then, try to avoid if possible).
+ * The internal function may change between releases.
+ *
+ * @type object
+ * @default {}
+ */
+ internal: {},
+
+
+ /**
+ * Legacy configuration options. Enable and disable legacy options that
+ * are available in DataTables.
+ *
+ * @type object
+ */
+ legacy: {
+ /**
+ * Enable / disable DataTables 1.9 compatible server-side processing
+ * requests
+ *
+ * @type boolean
+ * @default null
+ */
+ ajax: null
+ },
+
+
+ /**
+ * Pagination plug-in methods.
+ *
+ * Each entry in this object is a function and defines which buttons should
+ * be shown by the pagination rendering method that is used for the table:
+ * {@link DataTable.ext.renderer.pageButton}. The renderer addresses how the
+ * buttons are displayed in the document, while the functions here tell it
+ * what buttons to display. This is done by returning an array of button
+ * descriptions (what each button will do).
+ *
+ * Pagination types (the four built in options and any additional plug-in
+ * options defined here) can be used through the `paginationType`
+ * initialisation parameter.
+ *
+ * The functions defined take two parameters:
+ *
+ * 1. `{int} page` The current page index
+ * 2. `{int} pages` The number of pages in the table
+ *
+ * Each function is expected to return an array where each element of the
+ * array can be one of:
+ *
+ * * `first` - Jump to first page when activated
+ * * `last` - Jump to last page when activated
+ * * `previous` - Show previous page when activated
+ * * `next` - Show next page when activated
+ * * `{int}` - Show page of the index given
+ * * `{array}` - A nested array containing the above elements to add a
+ * containing 'DIV' element (might be useful for styling).
+ *
+ * Note that DataTables v1.9- used this object slightly differently whereby
+ * an object with two functions would be defined for each plug-in. That
+ * ability is still supported by DataTables 1.10+ to provide backwards
+ * compatibility, but this option of use is now decremented and no longer
+ * documented in DataTables 1.10+.
+ *
+ * @type object
+ * @default {}
+ *
+ * @example
+ * // Show previous, next and current page buttons only
+ * $.fn.dataTableExt.oPagination.current = function ( page, pages ) {
+ * return [ 'previous', page, 'next' ];
+ * };
+ */
+ pager: {},
+
+
+ renderer: {
+ pageButton: {},
+ header: {}
+ },
+
+
+ /**
+ * Ordering plug-ins - custom data source
+ *
+ * The extension options for ordering of data available here is complimentary
+ * to the default type based ordering that DataTables typically uses. It
+ * allows much greater control over the the data that is being used to
+ * order a column, but is necessarily therefore more complex.
+ *
+ * This type of ordering is useful if you want to do ordering based on data
+ * live from the DOM (for example the contents of an 'input' element) rather
+ * than just the static string that DataTables knows of.
+ *
+ * The way these plug-ins work is that you create an array of the values you
+ * wish to be ordering for the column in question and then return that
+ * array. The data in the array much be in the index order of the rows in
+ * the table (not the currently ordering order!). Which order data gathering
+ * function is run here depends on the `dt-init columns.orderDataType`
+ * parameter that is used for the column (if any).
+ *
+ * The functions defined take two parameters:
+ *
+ * 1. `{object}` DataTables settings object: see
+ * {@link DataTable.models.oSettings}
+ * 2. `{int}` Target column index
+ *
+ * Each function is expected to return an array:
+ *
+ * * `{array}` Data for the column to be ordering upon
+ *
+ * @type array
+ *
+ * @example
+ * // Ordering using `input` node values
+ * $.fn.dataTable.ext.order['dom-text'] = function ( settings, col )
+ * {
+ * return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
+ * return $('input', td).val();
+ * } );
+ * }
+ */
+ order: {},
+
+
+ /**
+ * Type based plug-ins.
+ *
+ * Each column in DataTables has a type assigned to it, either by automatic
+ * detection or by direct assignment using the `type` option for the column.
+ * The type of a column will effect how it is ordering and search (plug-ins
+ * can also make use of the column type if required).
+ *
+ * @namespace
+ */
+ type: {
+ /**
+ * Type detection functions.
+ *
+ * The functions defined in this object are used to automatically detect
+ * a column's type, making initialisation of DataTables super easy, even
+ * when complex data is in the table.
+ *
+ * The functions defined take two parameters:
+ *
+ * 1. `{*}` Data from the column cell to be analysed
+ * 2. `{settings}` DataTables settings object. This can be used to
+ * perform context specific type detection - for example detection
+ * based on language settings such as using a comma for a decimal
+ * place. Generally speaking the options from the settings will not
+ * be required
+ *
+ * Each function is expected to return:
+ *
+ * * `{string|null}` Data type detected, or null if unknown (and thus
+ * pass it on to the other type detection functions.
+ *
+ * @type array
+ *
+ * @example
+ * // Currency type detection plug-in:
+ * $.fn.dataTable.ext.type.detect.push(
+ * function ( data, settings ) {
+ * // Check the numeric part
+ * if ( ! $.isNumeric( data.substring(1) ) ) {
+ * return null;
+ * }
+ *
+ * // Check prefixed by currency
+ * if ( data.charAt(0) == '$' || data.charAt(0) == '&pound;' ) {
+ * return 'currency';
+ * }
+ * return null;
+ * }
+ * );
+ */
+ detect: [],
+
+
+ /**
+ * Type based search formatting.
+ *
+ * The type based searching functions can be used to pre-format the
+ * data to be search on. For example, it can be used to strip HTML
+ * tags or to de-format telephone numbers for numeric only searching.
+ *
+ * Note that is a search is not defined for a column of a given type,
+ * no search formatting will be performed.
+ *
+ * Pre-processing of searching data plug-ins - When you assign the sType
+ * for a column (or have it automatically detected for you by DataTables
+ * or a type detection plug-in), you will typically be using this for
+ * custom sorting, but it can also be used to provide custom searching
+ * by allowing you to pre-processing the data and returning the data in
+ * the format that should be searched upon. This is done by adding
+ * functions this object with a parameter name which matches the sType
+ * for that target column. This is the corollary of <i>afnSortData</i>
+ * for searching data.
+ *
+ * The functions defined take a single parameter:
+ *
+ * 1. `{*}` Data from the column cell to be prepared for searching
+ *
+ * Each function is expected to return:
+ *
+ * * `{string|null}` Formatted string that will be used for the searching.
+ *
+ * @type object
+ * @default {}
+ *
+ * @example
+ * $.fn.dataTable.ext.type.search['title-numeric'] = function ( d ) {
+ * return d.replace(/\n/g," ").replace( /<.*?>/g, "" );
+ * }
+ */
+ search: {},
+
+
+ /**
+ * Type based ordering.
+ *
+ * The column type tells DataTables what ordering to apply to the table
+ * when a column is sorted upon. The order for each type that is defined,
+ * is defined by the functions available in this object.
+ *
+ * Each ordering option can be described by three properties added to
+ * this object:
+ *
+ * * `{type}-pre` - Pre-formatting function
+ * * `{type}-asc` - Ascending order function
+ * * `{type}-desc` - Descending order function
+ *
+ * All three can be used together, only `{type}-pre` or only
+ * `{type}-asc` and `{type}-desc` together. It is generally recommended
+ * that only `{type}-pre` is used, as this provides the optimal
+ * implementation in terms of speed, although the others are provided
+ * for compatibility with existing Javascript sort functions.
+ *
+ * `{type}-pre`: Functions defined take a single parameter:
+ *
+ * 1. `{*}` Data from the column cell to be prepared for ordering
+ *
+ * And return:
+ *
+ * * `{*}` Data to be sorted upon
+ *
+ * `{type}-asc` and `{type}-desc`: Functions are typical Javascript sort
+ * functions, taking two parameters:
+ *
+ * 1. `{*}` Data to compare to the second parameter
+ * 2. `{*}` Data to compare to the first parameter
+ *
+ * And returning:
+ *
+ * * `{*}` Ordering match: <0 if first parameter should be sorted lower
+ * than the second parameter, ===0 if the two parameters are equal and
+ * >0 if the first parameter should be sorted height than the second
+ * parameter.
+ *
+ * @type object
+ * @default {}
+ *
+ * @example
+ * // Numeric ordering of formatted numbers with a pre-formatter
+ * $.extend( $.fn.dataTable.ext.type.order, {
+ * "string-pre": function(x) {
+ * a = (a === "-" || a === "") ? 0 : a.replace( /[^\d\-\.]/g, "" );
+ * return parseFloat( a );
+ * }
+ * } );
+ *
+ * @example
+ * // Case-sensitive string ordering, with no pre-formatting method
+ * $.extend( $.fn.dataTable.ext.order, {
+ * "string-case-asc": function(x,y) {
+ * return ((x < y) ? -1 : ((x > y) ? 1 : 0));
+ * },
+ * "string-case-desc": function(x,y) {
+ * return ((x < y) ? 1 : ((x > y) ? -1 : 0));
+ * }
+ * } );
+ */
+ order: {}
+ },
+
+ /**
+ * Unique DataTables instance counter
+ *
+ * @type int
+ * @private
+ */
+ _unique: 0,
+
+
+ //
+ // Depreciated
+ // The following properties are retained for backwards compatiblity only.
+ // The should not be used in new projects and will be removed in a future
+ // version
+ //
+
+ /**
+ * Version check function.
+ * @type function
+ * @depreciated Since 1.10
+ */
+ fnVersionCheck: DataTable.fnVersionCheck,
+
+
+ /**
+ * Index for what 'this' index API functions should use
+ * @type int
+ * @deprecated Since v1.10
+ */
+ iApiIndex: 0,
+
+
+ /**
+ * jQuery UI class container
+ * @type object
+ * @deprecated Since v1.10
+ */
+ oJUIClasses: {},
+
+
+ /**
+ * Software version
+ * @type string
+ * @deprecated Since v1.10
+ */
+ sVersion: DataTable.version
+ };
+
+
+ //
+ // Backwards compatibility. Alias to pre 1.10 Hungarian notation counter parts
+ //
+ $.extend( _ext, {
+ afnFiltering: _ext.search,
+ aTypes: _ext.type.detect,
+ ofnSearch: _ext.type.search,
+ oSort: _ext.type.order,
+ afnSortData: _ext.order,
+ aoFeatures: _ext.feature,
+ oApi: _ext.internal,
+ oStdClasses: _ext.classes,
+ oPagination: _ext.pager
+ } );
+
+
+ $.extend( DataTable.ext.classes, {
"sTable": "dataTable",
+ "sNoFooter": "no-footer",
- /* Two buttons buttons */
- "sPagePrevEnabled": "paginate_enabled_previous",
- "sPagePrevDisabled": "paginate_disabled_previous",
- "sPageNextEnabled": "paginate_enabled_next",
- "sPageNextDisabled": "paginate_disabled_next",
- "sPageJUINext": "",
- "sPageJUIPrev": "",
-
- /* Full numbers paging buttons */
+ /* Paging buttons */
"sPageButton": "paginate_button",
- "sPageButtonActive": "paginate_active",
- "sPageButtonStaticDisabled": "paginate_button paginate_button_disabled",
- "sPageFirst": "first",
- "sPagePrevious": "previous",
- "sPageNext": "next",
- "sPageLast": "last",
-
+ "sPageButtonActive": "current",
+ "sPageButtonDisabled": "disabled",
+
/* Striping classes */
"sStripeOdd": "odd",
"sStripeEven": "even",
-
+
/* Empty row */
"sRowEmpty": "dataTables_empty",
-
+
/* Features */
"sWrapper": "dataTables_wrapper",
"sFilter": "dataTables_filter",
@@ -11460,7 +14047,7 @@
"sPaging": "dataTables_paginate paging_", /* Note that the type is postfixed */
"sLength": "dataTables_length",
"sProcessing": "dataTables_processing",
-
+
/* Sorting */
"sSortAsc": "sorting_asc",
"sSortDesc": "sorting_desc",
@@ -11469,14 +14056,13 @@
"sSortableDesc": "sorting_desc_disabled",
"sSortableNone": "sorting_disabled",
"sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */
- "sSortJUIAsc": "",
- "sSortJUIDesc": "",
- "sSortJUI": "",
- "sSortJUIAscAllowed": "",
- "sSortJUIDescAllowed": "",
- "sSortJUIWrapper": "",
- "sSortIcon": "",
-
+
+ /* Filtering */
+ "sFilterInput": "",
+
+ /* Page length */
+ "sLengthSelect": "",
+
/* Scrolling */
"sScrollWrapper": "dataTables_scroll",
"sScrollHead": "dataTables_scrollHead",
@@ -11484,518 +14070,733 @@
"sScrollBody": "dataTables_scrollBody",
"sScrollFoot": "dataTables_scrollFoot",
"sScrollFootInner": "dataTables_scrollFootInner",
-
+
/* Misc */
+ "sHeaderTH": "",
"sFooterTH": "",
+
+ // Deprecated
+ "sSortJUIAsc": "",
+ "sSortJUIDesc": "",
+ "sSortJUI": "",
+ "sSortJUIAscAllowed": "",
+ "sSortJUIDescAllowed": "",
+ "sSortJUIWrapper": "",
+ "sSortIcon": "",
"sJUIHeader": "",
"sJUIFooter": ""
} );
- $.extend( DataTable.ext.oJUIClasses, DataTable.ext.oStdClasses, {
- /* Two buttons buttons */
- "sPagePrevEnabled": "fg-button ui-button ui-state-default ui-corner-left",
- "sPagePrevDisabled": "fg-button ui-button ui-state-default ui-corner-left ui-state-disabled",
- "sPageNextEnabled": "fg-button ui-button ui-state-default ui-corner-right",
- "sPageNextDisabled": "fg-button ui-button ui-state-default ui-corner-right ui-state-disabled",
- "sPageJUINext": "ui-icon ui-icon-circle-arrow-e",
- "sPageJUIPrev": "ui-icon ui-icon-circle-arrow-w",
-
+ (function() {
+
+ // Reused strings for better compression. Closure compiler appears to have a
+ // weird edge case where it is trying to expand strings rather than use the
+ // variable version. This results in about 200 bytes being added, for very
+ // little preference benefit since it this run on script load only.
+ var _empty = '';
+ _empty = '';
+
+ var _stateDefault = _empty + 'ui-state-default';
+ var _sortIcon = _empty + 'css_right ui-icon ui-icon-';
+ var _headerFooter = _empty + 'fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix';
+
+ $.extend( DataTable.ext.oJUIClasses, DataTable.ext.classes, {
/* Full numbers paging buttons */
- "sPageButton": "fg-button ui-button ui-state-default",
- "sPageButtonActive": "fg-button ui-button ui-state-default ui-state-disabled",
- "sPageButtonStaticDisabled": "fg-button ui-button ui-state-default ui-state-disabled",
- "sPageFirst": "first ui-corner-tl ui-corner-bl",
- "sPageLast": "last ui-corner-tr ui-corner-br",
-
+ "sPageButton": "fg-button ui-button "+_stateDefault,
+ "sPageButtonActive": "ui-state-disabled",
+ "sPageButtonDisabled": "ui-state-disabled",
+
/* Features */
"sPaging": "dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi "+
"ui-buttonset-multi paging_", /* Note that the type is postfixed */
-
+
/* Sorting */
- "sSortAsc": "ui-state-default",
- "sSortDesc": "ui-state-default",
- "sSortable": "ui-state-default",
- "sSortableAsc": "ui-state-default",
- "sSortableDesc": "ui-state-default",
- "sSortableNone": "ui-state-default",
- "sSortJUIAsc": "css_right ui-icon ui-icon-triangle-1-n",
- "sSortJUIDesc": "css_right ui-icon ui-icon-triangle-1-s",
- "sSortJUI": "css_right ui-icon ui-icon-carat-2-n-s",
- "sSortJUIAscAllowed": "css_right ui-icon ui-icon-carat-1-n",
- "sSortJUIDescAllowed": "css_right ui-icon ui-icon-carat-1-s",
- "sSortJUIWrapper": "DataTables_sort_wrapper",
- "sSortIcon": "DataTables_sort_icon",
-
+ "sSortAsc": _stateDefault+" sorting_asc",
+ "sSortDesc": _stateDefault+" sorting_desc",
+ "sSortable": _stateDefault+" sorting",
+ "sSortableAsc": _stateDefault+" sorting_asc_disabled",
+ "sSortableDesc": _stateDefault+" sorting_desc_disabled",
+ "sSortableNone": _stateDefault+" sorting_disabled",
+ "sSortJUIAsc": _sortIcon+"triangle-1-n",
+ "sSortJUIDesc": _sortIcon+"triangle-1-s",
+ "sSortJUI": _sortIcon+"carat-2-n-s",
+ "sSortJUIAscAllowed": _sortIcon+"carat-1-n",
+ "sSortJUIDescAllowed": _sortIcon+"carat-1-s",
+ "sSortJUIWrapper": "DataTables_sort_wrapper",
+ "sSortIcon": "DataTables_sort_icon",
+
/* Scrolling */
- "sScrollHead": "dataTables_scrollHead ui-state-default",
- "sScrollFoot": "dataTables_scrollFoot ui-state-default",
-
+ "sScrollHead": "dataTables_scrollHead "+_stateDefault,
+ "sScrollFoot": "dataTables_scrollFoot "+_stateDefault,
+
/* Misc */
- "sFooterTH": "ui-state-default",
- "sJUIHeader": "fg-toolbar ui-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix",
- "sJUIFooter": "fg-toolbar ui-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"
+ "sHeaderTH": _stateDefault,
+ "sFooterTH": _stateDefault,
+ "sJUIHeader": _headerFooter+" ui-corner-tl ui-corner-tr",
+ "sJUIFooter": _headerFooter+" ui-corner-bl ui-corner-br"
} );
- /*
- * Variable: oPagination
- * Purpose:
- * Scope: jQuery.fn.dataTableExt
- */
- $.extend( DataTable.ext.oPagination, {
- /*
- * Variable: two_button
- * Purpose: Standard two button (forward/back) pagination
- * Scope: jQuery.fn.dataTableExt.oPagination
- */
- "two_button": {
- /*
- * Function: oPagination.two_button.fnInit
- * Purpose: Initialise dom elements required for pagination with forward/back buttons only
- * Returns: -
- * Inputs: object:oSettings - dataTables settings object
- * node:nPaging - the DIV which contains this pagination control
- * function:fnCallbackDraw - draw function which must be called on update
- */
- "fnInit": function ( oSettings, nPaging, fnCallbackDraw )
- {
- var oLang = oSettings.oLanguage.oPaginate;
- var oClasses = oSettings.oClasses;
- var fnClickHandler = function ( e ) {
- if ( oSettings.oApi._fnPageChange( oSettings, e.data.action ) )
- {
- fnCallbackDraw( oSettings );
- }
- };
+ }());
- var sAppend = (!oSettings.bJUI) ?
- '<a class="'+oSettings.oClasses.sPagePrevDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button">'+oLang.sPrevious+'</a>'+
- '<a class="'+oSettings.oClasses.sPageNextDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button">'+oLang.sNext+'</a>'
- :
- '<a class="'+oSettings.oClasses.sPagePrevDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button"><span class="'+oSettings.oClasses.sPageJUIPrev+'"></span></a>'+
- '<a class="'+oSettings.oClasses.sPageNextDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button"><span class="'+oSettings.oClasses.sPageJUINext+'"></span></a>';
- $(nPaging).append( sAppend );
-
- var els = $('a', nPaging);
- var nPrevious = els[0],
- nNext = els[1];
-
- oSettings.oApi._fnBindAction( nPrevious, {action: "previous"}, fnClickHandler );
- oSettings.oApi._fnBindAction( nNext, {action: "next"}, fnClickHandler );
-
- /* ID the first elements only */
- if ( !oSettings.aanFeatures.p )
- {
- nPaging.id = oSettings.sTableId+'_paginate';
- nPrevious.id = oSettings.sTableId+'_previous';
- nNext.id = oSettings.sTableId+'_next';
- nPrevious.setAttribute('aria-controls', oSettings.sTableId);
- nNext.setAttribute('aria-controls', oSettings.sTableId);
- }
- },
-
- /*
- * Function: oPagination.two_button.fnUpdate
- * Purpose: Update the two button pagination at the end of the draw
- * Returns: -
- * Inputs: object:oSettings - dataTables settings object
- * function:fnCallbackDraw - draw function to call on page change
- */
- "fnUpdate": function ( oSettings, fnCallbackDraw )
- {
- if ( !oSettings.aanFeatures.p )
- {
- return;
- }
-
- var oClasses = oSettings.oClasses;
- var an = oSettings.aanFeatures.p;
- var nNode;
- /* Loop over each instance of the pager */
- for ( var i=0, iLen=an.length ; i<iLen ; i++ )
- {
- nNode = an[i].firstChild;
- if ( nNode )
- {
- /* Previous page */
- nNode.className = ( oSettings._iDisplayStart === 0 ) ?
- oClasses.sPagePrevDisabled : oClasses.sPagePrevEnabled;
-
- /* Next page */
- nNode = nNode.nextSibling;
- nNode.className = ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() ) ?
- oClasses.sPageNextDisabled : oClasses.sPageNextEnabled;
- }
- }
- }
+ var extPagination = DataTable.ext.pager;
+
+ function _numbers ( page, pages ) {
+ var
+ numbers = [],
+ buttons = extPagination.numbers_length,
+ half = Math.floor( buttons / 2 ),
+ i = 1;
+
+ if ( pages <= buttons ) {
+ numbers = _range( 0, pages );
+ }
+ else if ( page <= half ) {
+ numbers = _range( 0, buttons-2 );
+ numbers.push( 'ellipsis' );
+ numbers.push( pages-1 );
+ }
+ else if ( page >= pages - 1 - half ) {
+ numbers = _range( pages-(buttons-2), pages );
+ numbers.splice( 0, 0, 'ellipsis' ); // no unshift in ie6
+ numbers.splice( 0, 0, 0 );
+ }
+ else {
+ numbers = _range( page-half+2, page+half-1 );
+ numbers.push( 'ellipsis' );
+ numbers.push( pages-1 );
+ numbers.splice( 0, 0, 'ellipsis' );
+ numbers.splice( 0, 0, 0 );
+ }
+
+ numbers.DT_el = 'span';
+ return numbers;
+ }
+
+
+ $.extend( extPagination, {
+ simple: function ( page, pages ) {
+ return [ 'previous', 'next' ];
},
-
-
- /*
- * Variable: iFullNumbersShowPages
- * Purpose: Change the number of pages which can be seen
- * Scope: jQuery.fn.dataTableExt.oPagination
- */
- "iFullNumbersShowPages": 5,
-
- /*
- * Variable: full_numbers
- * Purpose: Full numbers pagination
- * Scope: jQuery.fn.dataTableExt.oPagination
- */
- "full_numbers": {
- /*
- * Function: oPagination.full_numbers.fnInit
- * Purpose: Initialise dom elements required for pagination with a list of the pages
- * Returns: -
- * Inputs: object:oSettings - dataTables settings object
- * node:nPaging - the DIV which contains this pagination control
- * function:fnCallbackDraw - draw function which must be called on update
- */
- "fnInit": function ( oSettings, nPaging, fnCallbackDraw )
- {
- var oLang = oSettings.oLanguage.oPaginate;
- var oClasses = oSettings.oClasses;
- var fnClickHandler = function ( e ) {
- if ( oSettings.oApi._fnPageChange( oSettings, e.data.action ) )
- {
- fnCallbackDraw( oSettings );
+
+ full: function ( page, pages ) {
+ return [ 'first', 'previous', 'next', 'last' ];
+ },
+
+ simple_numbers: function ( page, pages ) {
+ return [ 'previous', _numbers(page, pages), 'next' ];
+ },
+
+ full_numbers: function ( page, pages ) {
+ return [ 'first', 'previous', _numbers(page, pages), 'next', 'last' ];
+ },
+
+ // For testing and plug-ins to use
+ _numbers: _numbers,
+
+ // Number of number buttons (including ellipsis) to show. _Must be odd!_
+ numbers_length: 7
+ } );
+
+
+ $.extend( true, DataTable.ext.renderer, {
+ pageButton: {
+ _: function ( settings, host, idx, buttons, page, pages ) {
+ var classes = settings.oClasses;
+ var lang = settings.oLanguage.oPaginate;
+ var btnDisplay, btnClass, counter=0;
+
+ var attach = function( container, buttons ) {
+ var i, ien, node, button;
+ var clickHandler = function ( e ) {
+ _fnPageChange( settings, e.data.action, true );
+ };
+
+ for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
+ button = buttons[i];
+
+ if ( $.isArray( button ) ) {
+ var inner = $( '<'+(button.DT_el || 'div')+'/>' )
+ .appendTo( container );
+ attach( inner, button );
+ }
+ else {
+ btnDisplay = '';
+ btnClass = '';
+
+ switch ( button ) {
+ case 'ellipsis':
+ container.append('<span class="ellipsis">&#x2026;</span>');
+ break;
+
+ case 'first':
+ btnDisplay = lang.sFirst;
+ btnClass = button + (page > 0 ?
+ '' : ' '+classes.sPageButtonDisabled);
+ break;
+
+ case 'previous':
+ btnDisplay = lang.sPrevious;
+ btnClass = button + (page > 0 ?
+ '' : ' '+classes.sPageButtonDisabled);
+ break;
+
+ case 'next':
+ btnDisplay = lang.sNext;
+ btnClass = button + (page < pages-1 ?
+ '' : ' '+classes.sPageButtonDisabled);
+ break;
+
+ case 'last':
+ btnDisplay = lang.sLast;
+ btnClass = button + (page < pages-1 ?
+ '' : ' '+classes.sPageButtonDisabled);
+ break;
+
+ default:
+ btnDisplay = button + 1;
+ btnClass = page === button ?
+ classes.sPageButtonActive : '';
+ break;
+ }
+
+ if ( btnDisplay ) {
+ node = $('<a>', {
+ 'class': classes.sPageButton+' '+btnClass,
+ 'aria-controls': settings.sTableId,
+ 'data-dt-idx': counter,
+ 'tabindex': settings.iTabIndex,
+ 'id': idx === 0 && typeof button === 'string' ?
+ settings.sTableId +'_'+ button :
+ null
+ } )
+ .html( btnDisplay )
+ .appendTo( container );
+
+ _fnBindAction(
+ node, {action: button}, clickHandler
+ );
+
+ counter++;
+ }
+ }
}
};
- $(nPaging).append(
- '<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageFirst+'">'+oLang.sFirst+'</a>'+
- '<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPagePrevious+'">'+oLang.sPrevious+'</a>'+
- '<span></span>'+
- '<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageNext+'">'+oLang.sNext+'</a>'+
- '<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageLast+'">'+oLang.sLast+'</a>'
- );
- var els = $('a', nPaging);
- var nFirst = els[0],
- nPrev = els[1],
- nNext = els[2],
- nLast = els[3];
-
- oSettings.oApi._fnBindAction( nFirst, {action: "first"}, fnClickHandler );
- oSettings.oApi._fnBindAction( nPrev, {action: "previous"}, fnClickHandler );
- oSettings.oApi._fnBindAction( nNext, {action: "next"}, fnClickHandler );
- oSettings.oApi._fnBindAction( nLast, {action: "last"}, fnClickHandler );
-
- /* ID the first elements only */
- if ( !oSettings.aanFeatures.p )
- {
- nPaging.id = oSettings.sTableId+'_paginate';
- nFirst.id =oSettings.sTableId+'_first';
- nPrev.id =oSettings.sTableId+'_previous';
- nNext.id =oSettings.sTableId+'_next';
- nLast.id =oSettings.sTableId+'_last';
- }
- },
-
- /*
- * Function: oPagination.full_numbers.fnUpdate
- * Purpose: Update the list of page buttons shows
- * Returns: -
- * Inputs: object:oSettings - dataTables settings object
- * function:fnCallbackDraw - draw function to call on page change
- */
- "fnUpdate": function ( oSettings, fnCallbackDraw )
- {
- if ( !oSettings.aanFeatures.p )
- {
- return;
- }
-
- var iPageCount = DataTable.ext.oPagination.iFullNumbersShowPages;
- var iPageCountHalf = Math.floor(iPageCount / 2);
- var iPages = Math.ceil((oSettings.fnRecordsDisplay()) / oSettings._iDisplayLength);
- var iCurrentPage = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;
- var sList = "";
- var iStartButton, iEndButton, i, iLen;
- var oClasses = oSettings.oClasses;
- var anButtons, anStatic, nPaginateList, nNode;
- var an = oSettings.aanFeatures.p;
- var fnBind = function (j) {
- oSettings.oApi._fnBindAction( this, {"page": j+iStartButton-1}, function(e) {
- /* Use the information in the element to jump to the required page */
- oSettings.oApi._fnPageChange( oSettings, e.data.page );
- fnCallbackDraw( oSettings );
- e.preventDefault();
- } );
- };
-
- /* Pages calculation */
- if ( oSettings._iDisplayLength === -1 )
- {
- iStartButton = 1;
- iEndButton = 1;
- iCurrentPage = 1;
- }
- else if (iPages < iPageCount)
- {
- iStartButton = 1;
- iEndButton = iPages;
- }
- else if (iCurrentPage <= iPageCountHalf)
- {
- iStartButton = 1;
- iEndButton = iPageCount;
- }
- else if (iCurrentPage >= (iPages - iPageCountHalf))
- {
- iStartButton = iPages - iPageCount + 1;
- iEndButton = iPages;
- }
- else
- {
- iStartButton = iCurrentPage - Math.ceil(iPageCount / 2) + 1;
- iEndButton = iStartButton + iPageCount - 1;
- }
+ // IE9 throws an 'unknown error' if document.activeElement is used
+ // inside an iframe or frame. Try / catch the error. Not good for
+ // accessibility, but neither are frames.
+ var activeEl;
-
- /* Build the dynamic list */
- for ( i=iStartButton ; i<=iEndButton ; i++ )
- {
- sList += (iCurrentPage !== i) ?
- '<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+'">'+oSettings.fnFormatNumber(i)+'</a>' :
- '<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButtonActive+'">'+oSettings.fnFormatNumber(i)+'</a>';
+ try {
+ // Because this approach is destroying and recreating the paging
+ // elements, focus is lost on the select button which is bad for
+ // accessibility. So we want to restore focus once the draw has
+ // completed
+ activeEl = $(document.activeElement).data('dt-idx');
}
-
- /* Loop over each instance of the pager */
- for ( i=0, iLen=an.length ; i<iLen ; i++ )
- {
- nNode = an[i];
- if ( !nNode.hasChildNodes() )
- {
- continue;
- }
-
- /* Build up the dynamic list first - html and listeners */
- $('span:eq(0)', nNode)
- .html( sList )
- .children('a').each( fnBind );
-
- /* Update the permanent button's classes */
- anButtons = nNode.getElementsByTagName('a');
- anStatic = [
- anButtons[0], anButtons[1],
- anButtons[anButtons.length-2], anButtons[anButtons.length-1]
- ];
-
- $(anStatic).removeClass( oClasses.sPageButton+" "+oClasses.sPageButtonActive+" "+oClasses.sPageButtonStaticDisabled );
- $([anStatic[0], anStatic[1]]).addClass(
- (iCurrentPage==1) ?
- oClasses.sPageButtonStaticDisabled :
- oClasses.sPageButton
- );
- $([anStatic[2], anStatic[3]]).addClass(
- (iPages===0 || iCurrentPage===iPages || oSettings._iDisplayLength===-1) ?
- oClasses.sPageButtonStaticDisabled :
- oClasses.sPageButton
- );
+ catch (e) {}
+
+ attach( $(host).empty(), buttons );
+
+ if ( activeEl ) {
+ $(host).find( '[data-dt-idx='+activeEl+']' ).focus();
}
}
}
} );
- $.extend( DataTable.ext.oSort, {
- /*
- * text sorting
- */
- "string-pre": function ( a )
- {
- if ( typeof a != 'string' ) {
- a = (a !== null && a.toString) ? a.toString() : '';
- }
- return a.toLowerCase();
- },
- "string-asc": function ( x, y )
- {
- return ((x < y) ? -1 : ((x > y) ? 1 : 0));
- },
-
- "string-desc": function ( x, y )
- {
- return ((x < y) ? 1 : ((x > y) ? -1 : 0));
- },
-
-
- /*
- * html sorting (ignore html tags)
- */
- "html-pre": function ( a )
- {
- return a.replace( /<.*?>/g, "" ).toLowerCase();
- },
-
- "html-asc": function ( x, y )
- {
- return ((x < y) ? -1 : ((x > y) ? 1 : 0));
- },
-
- "html-desc": function ( x, y )
+
+ // Built in type detection. See model.ext.aTypes for information about
+ // what is required from this methods.
+ $.extend( DataTable.ext.type.detect, [
+ // Plain numbers - first since V8 detects some plain numbers as dates
+ // e.g. Date.parse('55') (but not all, e.g. Date.parse('22')...).
+ function ( d, settings )
{
- return ((x < y) ? 1 : ((x > y) ? -1 : 0));
+ var decimal = settings.oLanguage.sDecimal;
+ return _isNumber( d, decimal ) ? 'num'+decimal : null;
},
-
-
- /*
- * date sorting
- */
- "date-pre": function ( a )
+
+ // Dates (only those recognised by the browser's Date.parse)
+ function ( d, settings )
{
- var x = Date.parse( a );
-
- if ( isNaN(x) || x==="" )
- {
- x = Date.parse( "01/01/1970 00:00:00" );
+ // V8 will remove any unknown characters at the start and end of the
+ // expression, leading to false matches such as `$245.12` or `10%` being
+ // a valid date. See forum thread 18941 for detail.
+ if ( d && !(d instanceof Date) && ( ! _re_date_start.test(d) || ! _re_date_end.test(d) ) ) {
+ return null;
}
- return x;
+ var parsed = Date.parse(d);
+ return (parsed !== null && !isNaN(parsed)) || _empty(d) ? 'date' : null;
},
- "date-asc": function ( x, y )
+ // Formatted numbers
+ function ( d, settings )
{
- return x - y;
+ var decimal = settings.oLanguage.sDecimal;
+ return _isNumber( d, decimal, true ) ? 'num-fmt'+decimal : null;
},
-
- "date-desc": function ( x, y )
+
+ // HTML numeric
+ function ( d, settings )
{
- return y - x;
+ var decimal = settings.oLanguage.sDecimal;
+ return _htmlNumeric( d, decimal ) ? 'html-num'+decimal : null;
},
-
-
- /*
- * numerical sorting
- */
- "numeric-pre": function ( a )
+
+ // HTML numeric, formatted
+ function ( d, settings )
{
- return (a=="-" || a==="") ? 0 : a*1;
+ var decimal = settings.oLanguage.sDecimal;
+ return _htmlNumeric( d, decimal, true ) ? 'html-num-fmt'+decimal : null;
},
- "numeric-asc": function ( x, y )
+ // HTML (this is strict checking - there must be html)
+ function ( d, settings )
{
- return x - y;
+ return _empty( d ) || (typeof d === 'string' && d.indexOf('<') !== -1) ?
+ 'html' : null;
+ }
+ ] );
+
+
+
+ // Filter formatting functions. See model.ext.ofnSearch for information about
+ // what is required from these methods.
+ //
+ // Note that additional search methods are added for the html numbers and
+ // html formatted numbers by `_addNumericSort()` when we know what the decimal
+ // place is
+
+
+ $.extend( DataTable.ext.type.search, {
+ html: function ( data ) {
+ return _empty(data) ?
+ data :
+ typeof data === 'string' ?
+ data
+ .replace( _re_new_lines, " " )
+ .replace( _re_html, "" ) :
+ '';
},
-
- "numeric-desc": function ( x, y )
- {
- return y - x;
+
+ string: function ( data ) {
+ return _empty(data) ?
+ data :
+ typeof data === 'string' ?
+ data.replace( _re_new_lines, " " ) :
+ data;
}
} );
- $.extend( DataTable.ext.aTypes, [
- /*
- * Function: -
- * Purpose: Check to see if a string is numeric
- * Returns: string:'numeric' or null
- * Inputs: mixed:sText - string to check
- */
- function ( sData )
- {
- /* Allow zero length strings as a number */
- if ( typeof sData === 'number' )
- {
- return 'numeric';
- }
- else if ( typeof sData !== 'string' )
- {
- return null;
+
+ var __numericReplace = function ( d, decimalPlace, re1, re2 ) {
+ if ( d !== 0 && (!d || d === '-') ) {
+ return -Infinity;
+ }
+
+ // If a decimal place other than `.` is used, it needs to be given to the
+ // function so we can detect it and replace with a `.` which is the only
+ // decimal place Javascript recognises - it is not locale aware.
+ if ( decimalPlace ) {
+ d = _numToDecimal( d, decimalPlace );
+ }
+
+ if ( d.replace ) {
+ if ( re1 ) {
+ d = d.replace( re1, '' );
}
-
- var sValidFirstChars = "0123456789-";
- var sValidChars = "0123456789.";
- var Char;
- var bDecimal = false;
-
- /* Check for a valid first char (no period and allow negatives) */
- Char = sData.charAt(0);
- if (sValidFirstChars.indexOf(Char) == -1)
- {
- return null;
+
+ if ( re2 ) {
+ d = d.replace( re2, '' );
}
-
- /* Check all the other characters are valid */
- for ( var i=1 ; i<sData.length ; i++ )
+ }
+
+ return d * 1;
+ };
+
+
+ // Add the numeric 'deformatting' functions for sorting and search. This is done
+ // in a function to provide an easy ability for the language options to add
+ // additional methods if a non-period decimal place is used.
+ function _addNumericSort ( decimalPlace ) {
+ $.each(
{
- Char = sData.charAt(i);
- if (sValidChars.indexOf(Char) == -1)
- {
- return null;
+ // Plain numbers
+ "num": function ( d ) {
+ return __numericReplace( d, decimalPlace );
+ },
+
+ // Formatted numbers
+ "num-fmt": function ( d ) {
+ return __numericReplace( d, decimalPlace, _re_formatted_numeric );
+ },
+
+ // HTML numeric
+ "html-num": function ( d ) {
+ return __numericReplace( d, decimalPlace, _re_html );
+ },
+
+ // HTML numeric, formatted
+ "html-num-fmt": function ( d ) {
+ return __numericReplace( d, decimalPlace, _re_html, _re_formatted_numeric );
}
-
- /* Only allowed one decimal place... */
- if ( Char == "." )
- {
- if ( bDecimal )
- {
- return null;
- }
- bDecimal = true;
+ },
+ function ( key, fn ) {
+ // Add the ordering method
+ _ext.type.order[ key+decimalPlace+'-pre' ] = fn;
+
+ // For HTML types add a search formatter that will strip the HTML
+ if ( key.match(/^html\-/) ) {
+ _ext.type.search[ key+decimalPlace ] = _ext.type.search.html;
}
}
-
- return 'numeric';
+ );
+ }
+
+
+ // Default sort methods
+ $.extend( _ext.type.order, {
+ // Dates
+ "date-pre": function ( d ) {
+ return Date.parse( d ) || 0;
},
-
- /*
- * Function: -
- * Purpose: Check to see if a string is actually a formatted date
- * Returns: string:'date' or null
- * Inputs: string:sText - string to check
- */
- function ( sData )
- {
- var iParse = Date.parse(sData);
- if ( (iParse !== null && !isNaN(iParse)) || (typeof sData === 'string' && sData.length === 0) )
- {
- return 'date';
- }
- return null;
+
+ // html
+ "html-pre": function ( a ) {
+ return _empty(a) ?
+ '' :
+ a.replace ?
+ a.replace( /<.*?>/g, "" ).toLowerCase() :
+ a+'';
},
-
- /*
- * Function: -
- * Purpose: Check to see if a string should be treated as an HTML string
- * Returns: string:'html' or null
- * Inputs: string:sText - string to check
- */
- function ( sData )
- {
- if ( typeof sData === 'string' && sData.indexOf('<') != -1 && sData.indexOf('>') != -1 )
- {
- return 'html';
+
+ // string
+ "string-pre": function ( a ) {
+ // This is a little complex, but faster than always calling toString,
+ // http://jsperf.com/tostring-v-check
+ return _empty(a) ?
+ '' :
+ typeof a === 'string' ?
+ a.toLowerCase() :
+ ! a.toString ?
+ '' :
+ a.toString();
+ },
+
+ // string-asc and -desc are retained only for compatibility with the old
+ // sort methods
+ "string-asc": function ( x, y ) {
+ return ((x < y) ? -1 : ((x > y) ? 1 : 0));
+ },
+
+ "string-desc": function ( x, y ) {
+ return ((x < y) ? 1 : ((x > y) ? -1 : 0));
+ }
+ } );
+
+
+ // Numeric sorting types - order doesn't matter here
+ _addNumericSort( '' );
+
+
+ $.extend( true, DataTable.ext.renderer, {
+ header: {
+ _: function ( settings, cell, column, classes ) {
+ // No additional mark-up required
+ // Attach a sort listener to update on sort - note that using the
+ // `DT` namespace will allow the event to be removed automatically
+ // on destroy, while the `dt` namespaced event is the one we are
+ // listening for
+ $(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
+ if ( settings !== ctx ) { // need to check this this is the host
+ return; // table, not a nested one
+ }
+
+ var colIdx = column.idx;
+
+ cell
+ .removeClass(
+ column.sSortingClass +' '+
+ classes.sSortAsc +' '+
+ classes.sSortDesc
+ )
+ .addClass( columns[ colIdx ] == 'asc' ?
+ classes.sSortAsc : columns[ colIdx ] == 'desc' ?
+ classes.sSortDesc :
+ column.sSortingClass
+ );
+ } );
+ },
+
+ jqueryui: function ( settings, cell, column, classes ) {
+ $('<div/>')
+ .addClass( classes.sSortJUIWrapper )
+ .append( cell.contents() )
+ .append( $('<span/>')
+ .addClass( classes.sSortIcon+' '+column.sSortingClassJUI )
+ )
+ .appendTo( cell );
+
+ // Attach a sort listener to update on sort
+ $(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
+ if ( settings !== ctx ) {
+ return;
+ }
+
+ var colIdx = column.idx;
+
+ cell
+ .removeClass( classes.sSortAsc +" "+classes.sSortDesc )
+ .addClass( columns[ colIdx ] == 'asc' ?
+ classes.sSortAsc : columns[ colIdx ] == 'desc' ?
+ classes.sSortDesc :
+ column.sSortingClass
+ );
+
+ cell
+ .find( 'span.'+classes.sSortIcon )
+ .removeClass(
+ classes.sSortJUIAsc +" "+
+ classes.sSortJUIDesc +" "+
+ classes.sSortJUI +" "+
+ classes.sSortJUIAscAllowed +" "+
+ classes.sSortJUIDescAllowed
+ )
+ .addClass( columns[ colIdx ] == 'asc' ?
+ classes.sSortJUIAsc : columns[ colIdx ] == 'desc' ?
+ classes.sSortJUIDesc :
+ column.sSortingClassJUI
+ );
+ } );
}
- return null;
}
- ] );
+ } );
+
+ /*
+ * Public helper functions. These aren't used internally by DataTables, or
+ * called by any of the options passed into DataTables, but they can be used
+ * externally by developers working with DataTables. They are helper functions
+ * to make working with DataTables a little bit easier.
+ */
+
+ /**
+ * Helpers for `columns.render`.
+ *
+ * The options defined here can be used with the `columns.render` initialisation
+ * option to provide a display renderer. The following functions are defined:
+ *
+ * * `number` - Will format numeric data (defined by `columns.data`) for
+ * display, retaining the original unformatted data for sorting and filtering.
+ * It takes 4 parameters:
+ * * `string` - Thousands grouping separator
+ * * `string` - Decimal point indicator
+ * * `integer` - Number of decimal points to show
+ * * `string` (optional) - Prefix.
+ *
+ * @example
+ * // Column definition using the number renderer
+ * {
+ * data: "salary",
+ * render: $.fn.dataTable.render.number( '\'', '.', 0, '$' )
+ * }
+ *
+ * @namespace
+ */
+ DataTable.render = {
+ number: function ( thousands, decimal, precision, prefix ) {
+ return {
+ display: function ( d ) {
+ if ( typeof d !== 'number' && typeof d !== 'string' ) {
+ return d;
+ }
+
+ var negative = d < 0 ? '-' : '';
+ d = Math.abs( parseFloat( d ) );
+
+ var intPart = parseInt( d, 10 );
+ var floatPart = precision ?
+ decimal+(d - intPart).toFixed( precision ).substring( 2 ):
+ '';
+
+ return negative + (prefix||'') +
+ intPart.toString().replace(
+ /\B(?=(\d{3})+(?!\d))/g, thousands
+ ) +
+ floatPart;
+ }
+ };
+ }
+ };
+
+
+ /*
+ * This is really a good bit rubbish this method of exposing the internal methods
+ * publicly... - To be fixed in 2.0 using methods on the prototype
+ */
+
+
+ /**
+ * Create a wrapper function for exporting an internal functions to an external API.
+ * @param {string} fn API function name
+ * @returns {function} wrapped function
+ * @memberof DataTable#internal
+ */
+ function _fnExternApiFunc (fn)
+ {
+ return function() {
+ var args = [_fnSettingsFromNode( this[DataTable.ext.iApiIndex] )].concat(
+ Array.prototype.slice.call(arguments)
+ );
+ return DataTable.ext.internal[fn].apply( this, args );
+ };
+ }
+
+
+ /**
+ * Reference to internal functions for use by plug-in developers. Note that
+ * these methods are references to internal functions and are considered to be
+ * private. If you use these methods, be aware that they are liable to change
+ * between versions.
+ * @namespace
+ */
+ $.extend( DataTable.ext.internal, {
+ _fnExternApiFunc: _fnExternApiFunc,
+ _fnBuildAjax: _fnBuildAjax,
+ _fnAjaxUpdate: _fnAjaxUpdate,
+ _fnAjaxParameters: _fnAjaxParameters,
+ _fnAjaxUpdateDraw: _fnAjaxUpdateDraw,
+ _fnAjaxDataSrc: _fnAjaxDataSrc,
+ _fnAddColumn: _fnAddColumn,
+ _fnColumnOptions: _fnColumnOptions,
+ _fnAdjustColumnSizing: _fnAdjustColumnSizing,
+ _fnVisibleToColumnIndex: _fnVisibleToColumnIndex,
+ _fnColumnIndexToVisible: _fnColumnIndexToVisible,
+ _fnVisbleColumns: _fnVisbleColumns,
+ _fnGetColumns: _fnGetColumns,
+ _fnColumnTypes: _fnColumnTypes,
+ _fnApplyColumnDefs: _fnApplyColumnDefs,
+ _fnHungarianMap: _fnHungarianMap,
+ _fnCamelToHungarian: _fnCamelToHungarian,
+ _fnLanguageCompat: _fnLanguageCompat,
+ _fnBrowserDetect: _fnBrowserDetect,
+ _fnAddData: _fnAddData,
+ _fnAddTr: _fnAddTr,
+ _fnNodeToDataIndex: _fnNodeToDataIndex,
+ _fnNodeToColumnIndex: _fnNodeToColumnIndex,
+ _fnGetCellData: _fnGetCellData,
+ _fnSetCellData: _fnSetCellData,
+ _fnSplitObjNotation: _fnSplitObjNotation,
+ _fnGetObjectDataFn: _fnGetObjectDataFn,
+ _fnSetObjectDataFn: _fnSetObjectDataFn,
+ _fnGetDataMaster: _fnGetDataMaster,
+ _fnClearTable: _fnClearTable,
+ _fnDeleteIndex: _fnDeleteIndex,
+ _fnInvalidate: _fnInvalidate,
+ _fnGetRowElements: _fnGetRowElements,
+ _fnCreateTr: _fnCreateTr,
+ _fnBuildHead: _fnBuildHead,
+ _fnDrawHead: _fnDrawHead,
+ _fnDraw: _fnDraw,
+ _fnReDraw: _fnReDraw,
+ _fnAddOptionsHtml: _fnAddOptionsHtml,
+ _fnDetectHeader: _fnDetectHeader,
+ _fnGetUniqueThs: _fnGetUniqueThs,
+ _fnFeatureHtmlFilter: _fnFeatureHtmlFilter,
+ _fnFilterComplete: _fnFilterComplete,
+ _fnFilterCustom: _fnFilterCustom,
+ _fnFilterColumn: _fnFilterColumn,
+ _fnFilter: _fnFilter,
+ _fnFilterCreateSearch: _fnFilterCreateSearch,
+ _fnEscapeRegex: _fnEscapeRegex,
+ _fnFilterData: _fnFilterData,
+ _fnFeatureHtmlInfo: _fnFeatureHtmlInfo,
+ _fnUpdateInfo: _fnUpdateInfo,
+ _fnInfoMacros: _fnInfoMacros,
+ _fnInitialise: _fnInitialise,
+ _fnInitComplete: _fnInitComplete,
+ _fnLengthChange: _fnLengthChange,
+ _fnFeatureHtmlLength: _fnFeatureHtmlLength,
+ _fnFeatureHtmlPaginate: _fnFeatureHtmlPaginate,
+ _fnPageChange: _fnPageChange,
+ _fnFeatureHtmlProcessing: _fnFeatureHtmlProcessing,
+ _fnProcessingDisplay: _fnProcessingDisplay,
+ _fnFeatureHtmlTable: _fnFeatureHtmlTable,
+ _fnScrollDraw: _fnScrollDraw,
+ _fnApplyToChildren: _fnApplyToChildren,
+ _fnCalculateColumnWidths: _fnCalculateColumnWidths,
+ _fnThrottle: _fnThrottle,
+ _fnConvertToWidth: _fnConvertToWidth,
+ _fnScrollingWidthAdjust: _fnScrollingWidthAdjust,
+ _fnGetWidestNode: _fnGetWidestNode,
+ _fnGetMaxLenString: _fnGetMaxLenString,
+ _fnStringToCss: _fnStringToCss,
+ _fnScrollBarWidth: _fnScrollBarWidth,
+ _fnSortFlatten: _fnSortFlatten,
+ _fnSort: _fnSort,
+ _fnSortAria: _fnSortAria,
+ _fnSortListener: _fnSortListener,
+ _fnSortAttachListener: _fnSortAttachListener,
+ _fnSortingClasses: _fnSortingClasses,
+ _fnSortData: _fnSortData,
+ _fnSaveState: _fnSaveState,
+ _fnLoadState: _fnLoadState,
+ _fnSettingsFromNode: _fnSettingsFromNode,
+ _fnLog: _fnLog,
+ _fnMap: _fnMap,
+ _fnBindAction: _fnBindAction,
+ _fnCallbackReg: _fnCallbackReg,
+ _fnCallbackFire: _fnCallbackFire,
+ _fnLengthOverflow: _fnLengthOverflow,
+ _fnRenderer: _fnRenderer,
+ _fnDataSource: _fnDataSource,
+ _fnRowAttributes: _fnRowAttributes,
+ _fnCalculateEnd: function () {} // Used by a lot of plug-ins, but redundant
+ // in 1.10, so this dead-end function is
+ // added to prevent errors
+ } );
- // jQuery aliases
- $.fn.DataTable = DataTable;
+ // jQuery access
$.fn.dataTable = DataTable;
+
+ // Legacy aliases
$.fn.dataTableSettings = DataTable.settings;
$.fn.dataTableExt = DataTable.ext;
+ // With a capital `D` we return a DataTables API instance rather than a
+ // jQuery object
+ $.fn.DataTable = function ( opts ) {
+ return $(this).dataTable( opts ).api();
+ };
+
+ // All properties that are available to $.fn.dataTable should also be
+ // available on $.fn.DataTable
+ $.each( DataTable, function ( prop, val ) {
+ $.fn.DataTable[ prop ] = val;
+ } );
+
// Information about events fired by DataTables - for documentation.
/**
- * Draw event, fired whenever the table is redrawn on the page, at the same point as
- * fnDrawCallback. This may be useful for binding events or performing calculations when
- * the table is altered at all.
- * @name DataTable#draw
+ * Draw event, fired whenever the table is redrawn on the page, at the same
+ * point as fnDrawCallback. This may be useful for binding events or
+ * performing calculations when the table is altered at all.
+ * @name DataTable#draw.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
- * Filter event, fired when the filtering applied to the table (using the build in global
- * global filter, or column filters) is altered.
- * @name DataTable#filter
+ * Search event, fired when the searching applied to the table (using the
+ * built-in global search, or column filters) is altered.
+ * @name DataTable#search.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
@@ -12003,24 +14804,24 @@
/**
* Page change event, fired when the paging of the table is altered.
- * @name DataTable#page
+ * @name DataTable#page.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
- * Sort event, fired when the sorting applied to the table is altered.
- * @name DataTable#sort
+ * Order event, fired when the ordering applied to the table is altered.
+ * @name DataTable#order.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
- * DataTables initialisation complete event, fired when the table is fully drawn,
- * including Ajax data loaded, if Ajax data is required.
- * @name DataTable#init
+ * DataTables initialisation complete event, fired when the table is fully
+ * drawn, including Ajax data loaded, if Ajax data is required.
+ * @name DataTable#init.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
@@ -12029,11 +14830,11 @@
*/
/**
- * State save event, fired when the table has changed state a new state save is required.
- * This method allows modification of the state saving object prior to actually doing the
- * save, including addition or other state properties (for plug-ins) or modification
- * of a DataTables core property.
- * @name DataTable#stateSaveParams
+ * State save event, fired when the table has changed state a new state save
+ * is required. This event allows modification of the state saving object
+ * prior to actually doing the save, including addition or other state
+ * properties (for plug-ins) or modification of a DataTables core property.
+ * @name DataTable#stateSaveParams.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
@@ -12041,10 +14842,11 @@
*/
/**
- * State load event, fired when the table is loading state from the stored data, but
- * prior to the settings object being modified by the saved state - allowing modification
- * of the saved state is required or loading of state for a plug-in.
- * @name DataTable#stateLoadParams
+ * State load event, fired when the table is loading state from the stored
+ * data, but prior to the settings object being modified by the saved state
+ * - allowing modification of the saved state is required or loading of
+ * state for a plug-in.
+ * @name DataTable#stateLoadParams.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
@@ -12052,9 +14854,9 @@
*/
/**
- * State loaded event, fired when state has been loaded from stored data and the settings
- * object has been modified by the loaded data.
- * @name DataTable#stateLoaded
+ * State loaded event, fired when state has been loaded from stored data and
+ * the settings object has been modified by the loaded data.
+ * @name DataTable#stateLoaded.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
@@ -12062,10 +14864,11 @@
*/
/**
- * Processing event, fired when DataTables is doing some kind of processing (be it,
- * sort, filter or anything else). Can be used to indicate to the end user that
- * there is something happening, or that something has finished.
- * @name DataTable#processing
+ * Processing event, fired when DataTables is doing some kind of processing
+ * (be it, order, searcg or anything else). It can be used to indicate to
+ * the end user that there is something happening, or that something has
+ * finished.
+ * @name DataTable#processing.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
@@ -12073,26 +14876,75 @@
*/
/**
- * Ajax (XHR) event, fired whenever an Ajax request is completed from a request to
- * made to the server for new data (note that this trigger is called in fnServerData,
- * if you override fnServerData and which to use this event, you need to trigger it in
- * you success function).
- * @name DataTable#xhr
+ * Ajax (XHR) event, fired whenever an Ajax request is completed from a
+ * request to made to the server for new data. This event is called before
+ * DataTables processed the returned data, so it can also be used to pre-
+ * process the data returned from the server, if needed.
+ *
+ * Note that this trigger is called in `fnServerData`, if you override
+ * `fnServerData` and which to use this event, you need to trigger it in you
+ * success function.
+ * @name DataTable#xhr.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
* @param {object} json JSON returned from the server
+ *
+ * @example
+ * // Use a custom property returned from the server in another DOM element
+ * $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
+ * $('#status').html( json.status );
+ * } );
+ *
+ * @example
+ * // Pre-process the data returned from the server
+ * $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
+ * for ( var i=0, ien=json.aaData.length ; i<ien ; i++ ) {
+ * json.aaData[i].sum = json.aaData[i].one + json.aaData[i].two;
+ * }
+ * // Note no return - manipulate the data directly in the JSON object.
+ * } );
+ */
+
+ /**
+ * Destroy event, fired when the DataTable is destroyed by calling fnDestroy
+ * or passing the bDestroy:true parameter in the initialisation object. This
+ * can be used to remove bound events, added DOM nodes, etc.
+ * @name DataTable#destroy.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} o DataTables settings object {@link DataTable.models.oSettings}
+ */
+
+ /**
+ * Page length change event, fired when number of records to show on each
+ * page (the length) is changed.
+ * @name DataTable#length.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} o DataTables settings object {@link DataTable.models.oSettings}
+ * @param {integer} len New length
+ */
+
+ /**
+ * Column sizing has changed.
+ * @name DataTable#column-sizing.dt
+ * @event
+ * @param {event} e jQuery event object
+ * @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
- * Destroy event, fired when the DataTable is destroyed by calling fnDestroy or passing
- * the bDestroy:true parameter in the initialisation object. This can be used to remove
- * bound events, added DOM nodes, etc.
- * @name DataTable#destroy
+ * Column visibility has changed.
+ * @name DataTable#column-visibility.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
+ * @param {int} column Column index
+ * @param {bool} vis `false` if column now hidden, or `true` if visible
*/
+
+ return $.fn.dataTable;
}));
}(window, document));
diff --git a/wqflask/wqflask/static/new/packages/DataTables/js/jquery.dataTables.min.js b/wqflask/wqflask/static/new/packages/DataTables/js/jquery.dataTables.min.js
index 02694a4a..85dd817e 100755
--- a/wqflask/wqflask/static/new/packages/DataTables/js/jquery.dataTables.min.js
+++ b/wqflask/wqflask/static/new/packages/DataTables/js/jquery.dataTables.min.js
@@ -1,155 +1,160 @@
-/*
- * File: jquery.dataTables.min.js
- * Version: 1.9.4
- * Author: Allan Jardine (www.sprymedia.co.uk)
- * Info: www.datatables.net
- *
- * Copyright 2008-2012 Allan Jardine, all rights reserved.
- *
- * This source file is free software, under either the GPL v2 license or a
- * BSD style license, available at:
- * http://datatables.net/license_gpl2
- * http://datatables.net/license_bsd
- *
- * This source file is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
+/*! DataTables 1.10.7
+ * ©2008-2015 SpryMedia Ltd - datatables.net/license
*/
-(function(X,l,n){var L=function(h){var j=function(e){function o(a,b){var c=j.defaults.columns,d=a.aoColumns.length,c=h.extend({},j.models.oColumn,c,{sSortingClass:a.oClasses.sSortable,sSortingClassJUI:a.oClasses.sSortJUI,nTh:b?b:l.createElement("th"),sTitle:c.sTitle?c.sTitle:b?b.innerHTML:"",aDataSort:c.aDataSort?c.aDataSort:[d],mData:c.mData?c.oDefaults:d});a.aoColumns.push(c);if(a.aoPreSearchCols[d]===n||null===a.aoPreSearchCols[d])a.aoPreSearchCols[d]=h.extend({},j.models.oSearch);else if(c=a.aoPreSearchCols[d],
-c.bRegex===n&&(c.bRegex=!0),c.bSmart===n&&(c.bSmart=!0),c.bCaseInsensitive===n)c.bCaseInsensitive=!0;m(a,d,null)}function m(a,b,c){var d=a.aoColumns[b];c!==n&&null!==c&&(c.mDataProp&&!c.mData&&(c.mData=c.mDataProp),c.sType!==n&&(d.sType=c.sType,d._bAutoType=!1),h.extend(d,c),p(d,c,"sWidth","sWidthOrig"),c.iDataSort!==n&&(d.aDataSort=[c.iDataSort]),p(d,c,"aDataSort"));var i=d.mRender?Q(d.mRender):null,f=Q(d.mData);d.fnGetData=function(a,b){var c=f(a,b);return d.mRender&&b&&""!==b?i(c,b,a):c};d.fnSetData=
-L(d.mData);a.oFeatures.bSort||(d.bSortable=!1);!d.bSortable||-1==h.inArray("asc",d.asSorting)&&-1==h.inArray("desc",d.asSorting)?(d.sSortingClass=a.oClasses.sSortableNone,d.sSortingClassJUI=""):-1==h.inArray("asc",d.asSorting)&&-1==h.inArray("desc",d.asSorting)?(d.sSortingClass=a.oClasses.sSortable,d.sSortingClassJUI=a.oClasses.sSortJUI):-1!=h.inArray("asc",d.asSorting)&&-1==h.inArray("desc",d.asSorting)?(d.sSortingClass=a.oClasses.sSortableAsc,d.sSortingClassJUI=a.oClasses.sSortJUIAscAllowed):-1==
-h.inArray("asc",d.asSorting)&&-1!=h.inArray("desc",d.asSorting)&&(d.sSortingClass=a.oClasses.sSortableDesc,d.sSortingClassJUI=a.oClasses.sSortJUIDescAllowed)}function k(a){if(!1===a.oFeatures.bAutoWidth)return!1;da(a);for(var b=0,c=a.aoColumns.length;b<c;b++)a.aoColumns[b].nTh.style.width=a.aoColumns[b].sWidth}function G(a,b){var c=r(a,"bVisible");return"number"===typeof c[b]?c[b]:null}function R(a,b){var c=r(a,"bVisible"),c=h.inArray(b,c);return-1!==c?c:null}function t(a){return r(a,"bVisible").length}
-function r(a,b){var c=[];h.map(a.aoColumns,function(a,i){a[b]&&c.push(i)});return c}function B(a){for(var b=j.ext.aTypes,c=b.length,d=0;d<c;d++){var i=b[d](a);if(null!==i)return i}return"string"}function u(a,b){for(var c=b.split(","),d=[],i=0,f=a.aoColumns.length;i<f;i++)for(var g=0;g<f;g++)if(a.aoColumns[i].sName==c[g]){d.push(g);break}return d}function M(a){for(var b="",c=0,d=a.aoColumns.length;c<d;c++)b+=a.aoColumns[c].sName+",";return b.length==d?"":b.slice(0,-1)}function ta(a,b,c,d){var i,f,
-g,e,w;if(b)for(i=b.length-1;0<=i;i--){var j=b[i].aTargets;h.isArray(j)||D(a,1,"aTargets must be an array of targets, not a "+typeof j);f=0;for(g=j.length;f<g;f++)if("number"===typeof j[f]&&0<=j[f]){for(;a.aoColumns.length<=j[f];)o(a);d(j[f],b[i])}else if("number"===typeof j[f]&&0>j[f])d(a.aoColumns.length+j[f],b[i]);else if("string"===typeof j[f]){e=0;for(w=a.aoColumns.length;e<w;e++)("_all"==j[f]||h(a.aoColumns[e].nTh).hasClass(j[f]))&&d(e,b[i])}}if(c){i=0;for(a=c.length;i<a;i++)d(i,c[i])}}function H(a,
-b){var c;c=h.isArray(b)?b.slice():h.extend(!0,{},b);var d=a.aoData.length,i=h.extend(!0,{},j.models.oRow);i._aData=c;a.aoData.push(i);for(var f,i=0,g=a.aoColumns.length;i<g;i++)c=a.aoColumns[i],"function"===typeof c.fnRender&&c.bUseRendered&&null!==c.mData?F(a,d,i,S(a,d,i)):F(a,d,i,v(a,d,i)),c._bAutoType&&"string"!=c.sType&&(f=v(a,d,i,"type"),null!==f&&""!==f&&(f=B(f),null===c.sType?c.sType=f:c.sType!=f&&"html"!=c.sType&&(c.sType="string")));a.aiDisplayMaster.push(d);a.oFeatures.bDeferRender||ea(a,
-d);return d}function ua(a){var b,c,d,i,f,g,e;if(a.bDeferLoading||null===a.sAjaxSource)for(b=a.nTBody.firstChild;b;){if("TR"==b.nodeName.toUpperCase()){c=a.aoData.length;b._DT_RowIndex=c;a.aoData.push(h.extend(!0,{},j.models.oRow,{nTr:b}));a.aiDisplayMaster.push(c);f=b.firstChild;for(d=0;f;){g=f.nodeName.toUpperCase();if("TD"==g||"TH"==g)F(a,c,d,h.trim(f.innerHTML)),d++;f=f.nextSibling}}b=b.nextSibling}i=T(a);d=[];b=0;for(c=i.length;b<c;b++)for(f=i[b].firstChild;f;)g=f.nodeName.toUpperCase(),("TD"==
-g||"TH"==g)&&d.push(f),f=f.nextSibling;c=0;for(i=a.aoColumns.length;c<i;c++){e=a.aoColumns[c];null===e.sTitle&&(e.sTitle=e.nTh.innerHTML);var w=e._bAutoType,o="function"===typeof e.fnRender,k=null!==e.sClass,n=e.bVisible,m,p;if(w||o||k||!n){g=0;for(b=a.aoData.length;g<b;g++)f=a.aoData[g],m=d[g*i+c],w&&"string"!=e.sType&&(p=v(a,g,c,"type"),""!==p&&(p=B(p),null===e.sType?e.sType=p:e.sType!=p&&"html"!=e.sType&&(e.sType="string"))),e.mRender?m.innerHTML=v(a,g,c,"display"):e.mData!==c&&(m.innerHTML=v(a,
-g,c,"display")),o&&(p=S(a,g,c),m.innerHTML=p,e.bUseRendered&&F(a,g,c,p)),k&&(m.className+=" "+e.sClass),n?f._anHidden[c]=null:(f._anHidden[c]=m,m.parentNode.removeChild(m)),e.fnCreatedCell&&e.fnCreatedCell.call(a.oInstance,m,v(a,g,c,"display"),f._aData,g,c)}}if(0!==a.aoRowCreatedCallback.length){b=0;for(c=a.aoData.length;b<c;b++)f=a.aoData[b],A(a,"aoRowCreatedCallback",null,[f.nTr,f._aData,b])}}function I(a,b){return b._DT_RowIndex!==n?b._DT_RowIndex:null}function fa(a,b,c){for(var b=J(a,b),d=0,a=
-a.aoColumns.length;d<a;d++)if(b[d]===c)return d;return-1}function Y(a,b,c,d){for(var i=[],f=0,g=d.length;f<g;f++)i.push(v(a,b,d[f],c));return i}function v(a,b,c,d){var i=a.aoColumns[c];if((c=i.fnGetData(a.aoData[b]._aData,d))===n)return a.iDrawError!=a.iDraw&&null===i.sDefaultContent&&(D(a,0,"Requested unknown parameter "+("function"==typeof i.mData?"{mData function}":"'"+i.mData+"'")+" from the data source for row "+b),a.iDrawError=a.iDraw),i.sDefaultContent;if(null===c&&null!==i.sDefaultContent)c=
-i.sDefaultContent;else if("function"===typeof c)return c();return"display"==d&&null===c?"":c}function F(a,b,c,d){a.aoColumns[c].fnSetData(a.aoData[b]._aData,d)}function Q(a){if(null===a)return function(){return null};if("function"===typeof a)return function(b,d,i){return a(b,d,i)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("["))){var b=function(a,d,i){var f=i.split("."),g;if(""!==i){var e=0;for(g=f.length;e<g;e++){if(i=f[e].match(U)){f[e]=f[e].replace(U,"");""!==f[e]&&(a=a[f[e]]);
-g=[];f.splice(0,e+1);for(var f=f.join("."),e=0,h=a.length;e<h;e++)g.push(b(a[e],d,f));a=i[0].substring(1,i[0].length-1);a=""===a?g:g.join(a);break}if(null===a||a[f[e]]===n)return n;a=a[f[e]]}}return a};return function(c,d){return b(c,d,a)}}return function(b){return b[a]}}function L(a){if(null===a)return function(){};if("function"===typeof a)return function(b,d){a(b,"set",d)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("["))){var b=function(a,d,i){var i=i.split("."),f,g,e=0;for(g=
-i.length-1;e<g;e++){if(f=i[e].match(U)){i[e]=i[e].replace(U,"");a[i[e]]=[];f=i.slice();f.splice(0,e+1);g=f.join(".");for(var h=0,j=d.length;h<j;h++)f={},b(f,d[h],g),a[i[e]].push(f);return}if(null===a[i[e]]||a[i[e]]===n)a[i[e]]={};a=a[i[e]]}a[i[i.length-1].replace(U,"")]=d};return function(c,d){return b(c,d,a)}}return function(b,d){b[a]=d}}function Z(a){for(var b=[],c=a.aoData.length,d=0;d<c;d++)b.push(a.aoData[d]._aData);return b}function ga(a){a.aoData.splice(0,a.aoData.length);a.aiDisplayMaster.splice(0,
-a.aiDisplayMaster.length);a.aiDisplay.splice(0,a.aiDisplay.length);y(a)}function ha(a,b){for(var c=-1,d=0,i=a.length;d<i;d++)a[d]==b?c=d:a[d]>b&&a[d]--; -1!=c&&a.splice(c,1)}function S(a,b,c){var d=a.aoColumns[c];return d.fnRender({iDataRow:b,iDataColumn:c,oSettings:a,aData:a.aoData[b]._aData,mDataProp:d.mData},v(a,b,c,"display"))}function ea(a,b){var c=a.aoData[b],d;if(null===c.nTr){c.nTr=l.createElement("tr");c.nTr._DT_RowIndex=b;c._aData.DT_RowId&&(c.nTr.id=c._aData.DT_RowId);c._aData.DT_RowClass&&
-(c.nTr.className=c._aData.DT_RowClass);for(var i=0,f=a.aoColumns.length;i<f;i++){var g=a.aoColumns[i];d=l.createElement(g.sCellType);d.innerHTML="function"===typeof g.fnRender&&(!g.bUseRendered||null===g.mData)?S(a,b,i):v(a,b,i,"display");null!==g.sClass&&(d.className=g.sClass);g.bVisible?(c.nTr.appendChild(d),c._anHidden[i]=null):c._anHidden[i]=d;g.fnCreatedCell&&g.fnCreatedCell.call(a.oInstance,d,v(a,b,i,"display"),c._aData,b,i)}A(a,"aoRowCreatedCallback",null,[c.nTr,c._aData,b])}}function va(a){var b,
-c,d;if(0!==h("th, td",a.nTHead).length){b=0;for(d=a.aoColumns.length;b<d;b++)if(c=a.aoColumns[b].nTh,c.setAttribute("role","columnheader"),a.aoColumns[b].bSortable&&(c.setAttribute("tabindex",a.iTabIndex),c.setAttribute("aria-controls",a.sTableId)),null!==a.aoColumns[b].sClass&&h(c).addClass(a.aoColumns[b].sClass),a.aoColumns[b].sTitle!=c.innerHTML)c.innerHTML=a.aoColumns[b].sTitle}else{var i=l.createElement("tr");b=0;for(d=a.aoColumns.length;b<d;b++)c=a.aoColumns[b].nTh,c.innerHTML=a.aoColumns[b].sTitle,
-c.setAttribute("tabindex","0"),null!==a.aoColumns[b].sClass&&h(c).addClass(a.aoColumns[b].sClass),i.appendChild(c);h(a.nTHead).html("")[0].appendChild(i);V(a.aoHeader,a.nTHead)}h(a.nTHead).children("tr").attr("role","row");if(a.bJUI){b=0;for(d=a.aoColumns.length;b<d;b++){c=a.aoColumns[b].nTh;i=l.createElement("div");i.className=a.oClasses.sSortJUIWrapper;h(c).contents().appendTo(i);var f=l.createElement("span");f.className=a.oClasses.sSortIcon;i.appendChild(f);c.appendChild(i)}}if(a.oFeatures.bSort)for(b=
-0;b<a.aoColumns.length;b++)!1!==a.aoColumns[b].bSortable?ia(a,a.aoColumns[b].nTh,b):h(a.aoColumns[b].nTh).addClass(a.oClasses.sSortableNone);""!==a.oClasses.sFooterTH&&h(a.nTFoot).children("tr").children("th").addClass(a.oClasses.sFooterTH);if(null!==a.nTFoot){c=N(a,null,a.aoFooter);b=0;for(d=a.aoColumns.length;b<d;b++)c[b]&&(a.aoColumns[b].nTf=c[b],a.aoColumns[b].sClass&&h(c[b]).addClass(a.aoColumns[b].sClass))}}function W(a,b,c){var d,i,f,g=[],e=[],h=a.aoColumns.length,j;c===n&&(c=!1);d=0;for(i=
-b.length;d<i;d++){g[d]=b[d].slice();g[d].nTr=b[d].nTr;for(f=h-1;0<=f;f--)!a.aoColumns[f].bVisible&&!c&&g[d].splice(f,1);e.push([])}d=0;for(i=g.length;d<i;d++){if(a=g[d].nTr)for(;f=a.firstChild;)a.removeChild(f);f=0;for(b=g[d].length;f<b;f++)if(j=h=1,e[d][f]===n){a.appendChild(g[d][f].cell);for(e[d][f]=1;g[d+h]!==n&&g[d][f].cell==g[d+h][f].cell;)e[d+h][f]=1,h++;for(;g[d][f+j]!==n&&g[d][f].cell==g[d][f+j].cell;){for(c=0;c<h;c++)e[d+c][f+j]=1;j++}g[d][f].cell.rowSpan=h;g[d][f].cell.colSpan=j}}}function x(a){var b=
-A(a,"aoPreDrawCallback","preDraw",[a]);if(-1!==h.inArray(!1,b))E(a,!1);else{var c,d,b=[],i=0,f=a.asStripeClasses.length;c=a.aoOpenRows.length;a.bDrawing=!0;a.iInitDisplayStart!==n&&-1!=a.iInitDisplayStart&&(a._iDisplayStart=a.oFeatures.bServerSide?a.iInitDisplayStart:a.iInitDisplayStart>=a.fnRecordsDisplay()?0:a.iInitDisplayStart,a.iInitDisplayStart=-1,y(a));if(a.bDeferLoading)a.bDeferLoading=!1,a.iDraw++;else if(a.oFeatures.bServerSide){if(!a.bDestroying&&!wa(a))return}else a.iDraw++;if(0!==a.aiDisplay.length){var g=
-a._iDisplayStart;d=a._iDisplayEnd;a.oFeatures.bServerSide&&(g=0,d=a.aoData.length);for(;g<d;g++){var e=a.aoData[a.aiDisplay[g]];null===e.nTr&&ea(a,a.aiDisplay[g]);var j=e.nTr;if(0!==f){var o=a.asStripeClasses[i%f];e._sRowStripe!=o&&(h(j).removeClass(e._sRowStripe).addClass(o),e._sRowStripe=o)}A(a,"aoRowCallback",null,[j,a.aoData[a.aiDisplay[g]]._aData,i,g]);b.push(j);i++;if(0!==c)for(e=0;e<c;e++)if(j==a.aoOpenRows[e].nParent){b.push(a.aoOpenRows[e].nTr);break}}}else b[0]=l.createElement("tr"),a.asStripeClasses[0]&&
-(b[0].className=a.asStripeClasses[0]),c=a.oLanguage,f=c.sZeroRecords,1==a.iDraw&&null!==a.sAjaxSource&&!a.oFeatures.bServerSide?f=c.sLoadingRecords:c.sEmptyTable&&0===a.fnRecordsTotal()&&(f=c.sEmptyTable),c=l.createElement("td"),c.setAttribute("valign","top"),c.colSpan=t(a),c.className=a.oClasses.sRowEmpty,c.innerHTML=ja(a,f),b[i].appendChild(c);A(a,"aoHeaderCallback","header",[h(a.nTHead).children("tr")[0],Z(a),a._iDisplayStart,a.fnDisplayEnd(),a.aiDisplay]);A(a,"aoFooterCallback","footer",[h(a.nTFoot).children("tr")[0],
-Z(a),a._iDisplayStart,a.fnDisplayEnd(),a.aiDisplay]);i=l.createDocumentFragment();c=l.createDocumentFragment();if(a.nTBody){f=a.nTBody.parentNode;c.appendChild(a.nTBody);if(!a.oScroll.bInfinite||!a._bInitComplete||a.bSorted||a.bFiltered)for(;c=a.nTBody.firstChild;)a.nTBody.removeChild(c);c=0;for(d=b.length;c<d;c++)i.appendChild(b[c]);a.nTBody.appendChild(i);null!==f&&f.appendChild(a.nTBody)}A(a,"aoDrawCallback","draw",[a]);a.bSorted=!1;a.bFiltered=!1;a.bDrawing=!1;a.oFeatures.bServerSide&&(E(a,!1),
-a._bInitComplete||$(a))}}function aa(a){a.oFeatures.bSort?O(a,a.oPreviousSearch):a.oFeatures.bFilter?K(a,a.oPreviousSearch):(y(a),x(a))}function xa(a){var b=h("<div></div>")[0];a.nTable.parentNode.insertBefore(b,a.nTable);a.nTableWrapper=h('<div id="'+a.sTableId+'_wrapper" class="'+a.oClasses.sWrapper+'" role="grid"></div>')[0];a.nTableReinsertBefore=a.nTable.nextSibling;for(var c=a.nTableWrapper,d=a.sDom.split(""),i,f,g,e,w,o,k,m=0;m<d.length;m++){f=0;g=d[m];if("<"==g){e=h("<div></div>")[0];w=d[m+
-1];if("'"==w||'"'==w){o="";for(k=2;d[m+k]!=w;)o+=d[m+k],k++;"H"==o?o=a.oClasses.sJUIHeader:"F"==o&&(o=a.oClasses.sJUIFooter);-1!=o.indexOf(".")?(w=o.split("."),e.id=w[0].substr(1,w[0].length-1),e.className=w[1]):"#"==o.charAt(0)?e.id=o.substr(1,o.length-1):e.className=o;m+=k}c.appendChild(e);c=e}else if(">"==g)c=c.parentNode;else if("l"==g&&a.oFeatures.bPaginate&&a.oFeatures.bLengthChange)i=ya(a),f=1;else if("f"==g&&a.oFeatures.bFilter)i=za(a),f=1;else if("r"==g&&a.oFeatures.bProcessing)i=Aa(a),f=
-1;else if("t"==g)i=Ba(a),f=1;else if("i"==g&&a.oFeatures.bInfo)i=Ca(a),f=1;else if("p"==g&&a.oFeatures.bPaginate)i=Da(a),f=1;else if(0!==j.ext.aoFeatures.length){e=j.ext.aoFeatures;k=0;for(w=e.length;k<w;k++)if(g==e[k].cFeature){(i=e[k].fnInit(a))&&(f=1);break}}1==f&&null!==i&&("object"!==typeof a.aanFeatures[g]&&(a.aanFeatures[g]=[]),a.aanFeatures[g].push(i),c.appendChild(i))}b.parentNode.replaceChild(a.nTableWrapper,b)}function V(a,b){var c=h(b).children("tr"),d,i,f,g,e,j,o,k,m,p;a.splice(0,a.length);
-f=0;for(j=c.length;f<j;f++)a.push([]);f=0;for(j=c.length;f<j;f++){d=c[f];for(i=d.firstChild;i;){if("TD"==i.nodeName.toUpperCase()||"TH"==i.nodeName.toUpperCase()){k=1*i.getAttribute("colspan");m=1*i.getAttribute("rowspan");k=!k||0===k||1===k?1:k;m=!m||0===m||1===m?1:m;g=0;for(e=a[f];e[g];)g++;o=g;p=1===k?!0:!1;for(e=0;e<k;e++)for(g=0;g<m;g++)a[f+g][o+e]={cell:i,unique:p},a[f+g].nTr=d}i=i.nextSibling}}}function N(a,b,c){var d=[];c||(c=a.aoHeader,b&&(c=[],V(c,b)));for(var b=0,i=c.length;b<i;b++)for(var f=
-0,g=c[b].length;f<g;f++)if(c[b][f].unique&&(!d[f]||!a.bSortCellsTop))d[f]=c[b][f].cell;return d}function wa(a){if(a.bAjaxDataGet){a.iDraw++;E(a,!0);var b=Ea(a);ka(a,b);a.fnServerData.call(a.oInstance,a.sAjaxSource,b,function(b){Fa(a,b)},a);return!1}return!0}function Ea(a){var b=a.aoColumns.length,c=[],d,i,f,g;c.push({name:"sEcho",value:a.iDraw});c.push({name:"iColumns",value:b});c.push({name:"sColumns",value:M(a)});c.push({name:"iDisplayStart",value:a._iDisplayStart});c.push({name:"iDisplayLength",
-value:!1!==a.oFeatures.bPaginate?a._iDisplayLength:-1});for(f=0;f<b;f++)d=a.aoColumns[f].mData,c.push({name:"mDataProp_"+f,value:"function"===typeof d?"function":d});if(!1!==a.oFeatures.bFilter){c.push({name:"sSearch",value:a.oPreviousSearch.sSearch});c.push({name:"bRegex",value:a.oPreviousSearch.bRegex});for(f=0;f<b;f++)c.push({name:"sSearch_"+f,value:a.aoPreSearchCols[f].sSearch}),c.push({name:"bRegex_"+f,value:a.aoPreSearchCols[f].bRegex}),c.push({name:"bSearchable_"+f,value:a.aoColumns[f].bSearchable})}if(!1!==
-a.oFeatures.bSort){var e=0;d=null!==a.aaSortingFixed?a.aaSortingFixed.concat(a.aaSorting):a.aaSorting.slice();for(f=0;f<d.length;f++){i=a.aoColumns[d[f][0]].aDataSort;for(g=0;g<i.length;g++)c.push({name:"iSortCol_"+e,value:i[g]}),c.push({name:"sSortDir_"+e,value:d[f][1]}),e++}c.push({name:"iSortingCols",value:e});for(f=0;f<b;f++)c.push({name:"bSortable_"+f,value:a.aoColumns[f].bSortable})}return c}function ka(a,b){A(a,"aoServerParams","serverParams",[b])}function Fa(a,b){if(b.sEcho!==n){if(1*b.sEcho<
-a.iDraw)return;a.iDraw=1*b.sEcho}(!a.oScroll.bInfinite||a.oScroll.bInfinite&&(a.bSorted||a.bFiltered))&&ga(a);a._iRecordsTotal=parseInt(b.iTotalRecords,10);a._iRecordsDisplay=parseInt(b.iTotalDisplayRecords,10);var c=M(a),c=b.sColumns!==n&&""!==c&&b.sColumns!=c,d;c&&(d=u(a,b.sColumns));for(var i=Q(a.sAjaxDataProp)(b),f=0,g=i.length;f<g;f++)if(c){for(var e=[],h=0,j=a.aoColumns.length;h<j;h++)e.push(i[f][d[h]]);H(a,e)}else H(a,i[f]);a.aiDisplay=a.aiDisplayMaster.slice();a.bAjaxDataGet=!1;x(a);a.bAjaxDataGet=
-!0;E(a,!1)}function za(a){var b=a.oPreviousSearch,c=a.oLanguage.sSearch,c=-1!==c.indexOf("_INPUT_")?c.replace("_INPUT_",'<input type="text" />'):""===c?'<input type="text" />':c+' <input type="text" />',d=l.createElement("div");d.className=a.oClasses.sFilter;d.innerHTML="<label>"+c+"</label>";a.aanFeatures.f||(d.id=a.sTableId+"_filter");c=h('input[type="text"]',d);d._DT_Input=c[0];c.val(b.sSearch.replace('"',"&quot;"));c.bind("keyup.DT",function(){for(var c=a.aanFeatures.f,d=this.value===""?"":this.value,
-g=0,e=c.length;g<e;g++)c[g]!=h(this).parents("div.dataTables_filter")[0]&&h(c[g]._DT_Input).val(d);d!=b.sSearch&&K(a,{sSearch:d,bRegex:b.bRegex,bSmart:b.bSmart,bCaseInsensitive:b.bCaseInsensitive})});c.attr("aria-controls",a.sTableId).bind("keypress.DT",function(a){if(a.keyCode==13)return false});return d}function K(a,b,c){var d=a.oPreviousSearch,i=a.aoPreSearchCols,f=function(a){d.sSearch=a.sSearch;d.bRegex=a.bRegex;d.bSmart=a.bSmart;d.bCaseInsensitive=a.bCaseInsensitive};if(a.oFeatures.bServerSide)f(b);
-else{Ga(a,b.sSearch,c,b.bRegex,b.bSmart,b.bCaseInsensitive);f(b);for(b=0;b<a.aoPreSearchCols.length;b++)Ha(a,i[b].sSearch,b,i[b].bRegex,i[b].bSmart,i[b].bCaseInsensitive);Ia(a)}a.bFiltered=!0;h(a.oInstance).trigger("filter",a);a._iDisplayStart=0;y(a);x(a);la(a,0)}function Ia(a){for(var b=j.ext.afnFiltering,c=r(a,"bSearchable"),d=0,i=b.length;d<i;d++)for(var f=0,g=0,e=a.aiDisplay.length;g<e;g++){var h=a.aiDisplay[g-f];b[d](a,Y(a,h,"filter",c),h)||(a.aiDisplay.splice(g-f,1),f++)}}function Ha(a,b,c,
-d,i,f){if(""!==b)for(var g=0,b=ma(b,d,i,f),d=a.aiDisplay.length-1;0<=d;d--)i=Ja(v(a,a.aiDisplay[d],c,"filter"),a.aoColumns[c].sType),b.test(i)||(a.aiDisplay.splice(d,1),g++)}function Ga(a,b,c,d,i,f){d=ma(b,d,i,f);i=a.oPreviousSearch;c||(c=0);0!==j.ext.afnFiltering.length&&(c=1);if(0>=b.length)a.aiDisplay.splice(0,a.aiDisplay.length),a.aiDisplay=a.aiDisplayMaster.slice();else if(a.aiDisplay.length==a.aiDisplayMaster.length||i.sSearch.length>b.length||1==c||0!==b.indexOf(i.sSearch)){a.aiDisplay.splice(0,
-a.aiDisplay.length);la(a,1);for(b=0;b<a.aiDisplayMaster.length;b++)d.test(a.asDataSearch[b])&&a.aiDisplay.push(a.aiDisplayMaster[b])}else for(b=c=0;b<a.asDataSearch.length;b++)d.test(a.asDataSearch[b])||(a.aiDisplay.splice(b-c,1),c++)}function la(a,b){if(!a.oFeatures.bServerSide){a.asDataSearch=[];for(var c=r(a,"bSearchable"),d=1===b?a.aiDisplayMaster:a.aiDisplay,i=0,f=d.length;i<f;i++)a.asDataSearch[i]=na(a,Y(a,d[i],"filter",c))}}function na(a,b){var c=b.join(" ");-1!==c.indexOf("&")&&(c=h("<div>").html(c).text());
-return c.replace(/[\n\r]/g," ")}function ma(a,b,c,d){if(c)return a=b?a.split(" "):oa(a).split(" "),a="^(?=.*?"+a.join(")(?=.*?")+").*$",RegExp(a,d?"i":"");a=b?a:oa(a);return RegExp(a,d?"i":"")}function Ja(a,b){return"function"===typeof j.ext.ofnSearch[b]?j.ext.ofnSearch[b](a):null===a?"":"html"==b?a.replace(/[\r\n]/g," ").replace(/<.*?>/g,""):"string"===typeof a?a.replace(/[\r\n]/g," "):a}function oa(a){return a.replace(RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\|\\$|\\^|\\-)","g"),
-"\\$1")}function Ca(a){var b=l.createElement("div");b.className=a.oClasses.sInfo;a.aanFeatures.i||(a.aoDrawCallback.push({fn:Ka,sName:"information"}),b.id=a.sTableId+"_info");a.nTable.setAttribute("aria-describedby",a.sTableId+"_info");return b}function Ka(a){if(a.oFeatures.bInfo&&0!==a.aanFeatures.i.length){var b=a.oLanguage,c=a._iDisplayStart+1,d=a.fnDisplayEnd(),i=a.fnRecordsTotal(),f=a.fnRecordsDisplay(),g;g=0===f?b.sInfoEmpty:b.sInfo;f!=i&&(g+=" "+b.sInfoFiltered);g+=b.sInfoPostFix;g=ja(a,g);
-null!==b.fnInfoCallback&&(g=b.fnInfoCallback.call(a.oInstance,a,c,d,i,f,g));a=a.aanFeatures.i;b=0;for(c=a.length;b<c;b++)h(a[b]).html(g)}}function ja(a,b){var c=a.fnFormatNumber(a._iDisplayStart+1),d=a.fnDisplayEnd(),d=a.fnFormatNumber(d),i=a.fnRecordsDisplay(),i=a.fnFormatNumber(i),f=a.fnRecordsTotal(),f=a.fnFormatNumber(f);a.oScroll.bInfinite&&(c=a.fnFormatNumber(1));return b.replace(/_START_/g,c).replace(/_END_/g,d).replace(/_TOTAL_/g,i).replace(/_MAX_/g,f)}function ba(a){var b,c,d=a.iInitDisplayStart;
-if(!1===a.bInitialised)setTimeout(function(){ba(a)},200);else{xa(a);va(a);W(a,a.aoHeader);a.nTFoot&&W(a,a.aoFooter);E(a,!0);a.oFeatures.bAutoWidth&&da(a);b=0;for(c=a.aoColumns.length;b<c;b++)null!==a.aoColumns[b].sWidth&&(a.aoColumns[b].nTh.style.width=q(a.aoColumns[b].sWidth));a.oFeatures.bSort?O(a):a.oFeatures.bFilter?K(a,a.oPreviousSearch):(a.aiDisplay=a.aiDisplayMaster.slice(),y(a),x(a));null!==a.sAjaxSource&&!a.oFeatures.bServerSide?(c=[],ka(a,c),a.fnServerData.call(a.oInstance,a.sAjaxSource,
-c,function(c){var f=a.sAjaxDataProp!==""?Q(a.sAjaxDataProp)(c):c;for(b=0;b<f.length;b++)H(a,f[b]);a.iInitDisplayStart=d;if(a.oFeatures.bSort)O(a);else{a.aiDisplay=a.aiDisplayMaster.slice();y(a);x(a)}E(a,false);$(a,c)},a)):a.oFeatures.bServerSide||(E(a,!1),$(a))}}function $(a,b){a._bInitComplete=!0;A(a,"aoInitComplete","init",[a,b])}function pa(a){var b=j.defaults.oLanguage;!a.sEmptyTable&&(a.sZeroRecords&&"No data available in table"===b.sEmptyTable)&&p(a,a,"sZeroRecords","sEmptyTable");!a.sLoadingRecords&&
-(a.sZeroRecords&&"Loading..."===b.sLoadingRecords)&&p(a,a,"sZeroRecords","sLoadingRecords")}function ya(a){if(a.oScroll.bInfinite)return null;var b='<select size="1" '+('name="'+a.sTableId+'_length"')+">",c,d,i=a.aLengthMenu;if(2==i.length&&"object"===typeof i[0]&&"object"===typeof i[1]){c=0;for(d=i[0].length;c<d;c++)b+='<option value="'+i[0][c]+'">'+i[1][c]+"</option>"}else{c=0;for(d=i.length;c<d;c++)b+='<option value="'+i[c]+'">'+i[c]+"</option>"}b+="</select>";i=l.createElement("div");a.aanFeatures.l||
-(i.id=a.sTableId+"_length");i.className=a.oClasses.sLength;i.innerHTML="<label>"+a.oLanguage.sLengthMenu.replace("_MENU_",b)+"</label>";h('select option[value="'+a._iDisplayLength+'"]',i).attr("selected",!0);h("select",i).bind("change.DT",function(){var b=h(this).val(),i=a.aanFeatures.l;c=0;for(d=i.length;c<d;c++)i[c]!=this.parentNode&&h("select",i[c]).val(b);a._iDisplayLength=parseInt(b,10);y(a);if(a.fnDisplayEnd()==a.fnRecordsDisplay()){a._iDisplayStart=a.fnDisplayEnd()-a._iDisplayLength;if(a._iDisplayStart<
-0)a._iDisplayStart=0}if(a._iDisplayLength==-1)a._iDisplayStart=0;x(a)});h("select",i).attr("aria-controls",a.sTableId);return i}function y(a){a._iDisplayEnd=!1===a.oFeatures.bPaginate?a.aiDisplay.length:a._iDisplayStart+a._iDisplayLength>a.aiDisplay.length||-1==a._iDisplayLength?a.aiDisplay.length:a._iDisplayStart+a._iDisplayLength}function Da(a){if(a.oScroll.bInfinite)return null;var b=l.createElement("div");b.className=a.oClasses.sPaging+a.sPaginationType;j.ext.oPagination[a.sPaginationType].fnInit(a,
-b,function(a){y(a);x(a)});a.aanFeatures.p||a.aoDrawCallback.push({fn:function(a){j.ext.oPagination[a.sPaginationType].fnUpdate(a,function(a){y(a);x(a)})},sName:"pagination"});return b}function qa(a,b){var c=a._iDisplayStart;if("number"===typeof b)a._iDisplayStart=b*a._iDisplayLength,a._iDisplayStart>a.fnRecordsDisplay()&&(a._iDisplayStart=0);else if("first"==b)a._iDisplayStart=0;else if("previous"==b)a._iDisplayStart=0<=a._iDisplayLength?a._iDisplayStart-a._iDisplayLength:0,0>a._iDisplayStart&&(a._iDisplayStart=
-0);else if("next"==b)0<=a._iDisplayLength?a._iDisplayStart+a._iDisplayLength<a.fnRecordsDisplay()&&(a._iDisplayStart+=a._iDisplayLength):a._iDisplayStart=0;else if("last"==b)if(0<=a._iDisplayLength){var d=parseInt((a.fnRecordsDisplay()-1)/a._iDisplayLength,10)+1;a._iDisplayStart=(d-1)*a._iDisplayLength}else a._iDisplayStart=0;else D(a,0,"Unknown paging action: "+b);h(a.oInstance).trigger("page",a);return c!=a._iDisplayStart}function Aa(a){var b=l.createElement("div");a.aanFeatures.r||(b.id=a.sTableId+
-"_processing");b.innerHTML=a.oLanguage.sProcessing;b.className=a.oClasses.sProcessing;a.nTable.parentNode.insertBefore(b,a.nTable);return b}function E(a,b){if(a.oFeatures.bProcessing)for(var c=a.aanFeatures.r,d=0,i=c.length;d<i;d++)c[d].style.visibility=b?"visible":"hidden";h(a.oInstance).trigger("processing",[a,b])}function Ba(a){if(""===a.oScroll.sX&&""===a.oScroll.sY)return a.nTable;var b=l.createElement("div"),c=l.createElement("div"),d=l.createElement("div"),i=l.createElement("div"),f=l.createElement("div"),
-g=l.createElement("div"),e=a.nTable.cloneNode(!1),j=a.nTable.cloneNode(!1),o=a.nTable.getElementsByTagName("thead")[0],k=0===a.nTable.getElementsByTagName("tfoot").length?null:a.nTable.getElementsByTagName("tfoot")[0],m=a.oClasses;c.appendChild(d);f.appendChild(g);i.appendChild(a.nTable);b.appendChild(c);b.appendChild(i);d.appendChild(e);e.appendChild(o);null!==k&&(b.appendChild(f),g.appendChild(j),j.appendChild(k));b.className=m.sScrollWrapper;c.className=m.sScrollHead;d.className=m.sScrollHeadInner;
-i.className=m.sScrollBody;f.className=m.sScrollFoot;g.className=m.sScrollFootInner;a.oScroll.bAutoCss&&(c.style.overflow="hidden",c.style.position="relative",f.style.overflow="hidden",i.style.overflow="auto");c.style.border="0";c.style.width="100%";f.style.border="0";d.style.width=""!==a.oScroll.sXInner?a.oScroll.sXInner:"100%";e.removeAttribute("id");e.style.marginLeft="0";a.nTable.style.marginLeft="0";null!==k&&(j.removeAttribute("id"),j.style.marginLeft="0");d=h(a.nTable).children("caption");0<
-d.length&&(d=d[0],"top"===d._captionSide?e.appendChild(d):"bottom"===d._captionSide&&k&&j.appendChild(d));""!==a.oScroll.sX&&(c.style.width=q(a.oScroll.sX),i.style.width=q(a.oScroll.sX),null!==k&&(f.style.width=q(a.oScroll.sX)),h(i).scroll(function(){c.scrollLeft=this.scrollLeft;if(k!==null)f.scrollLeft=this.scrollLeft}));""!==a.oScroll.sY&&(i.style.height=q(a.oScroll.sY));a.aoDrawCallback.push({fn:La,sName:"scrolling"});a.oScroll.bInfinite&&h(i).scroll(function(){if(!a.bDrawing&&h(this).scrollTop()!==
-0&&h(this).scrollTop()+h(this).height()>h(a.nTable).height()-a.oScroll.iLoadGap&&a.fnDisplayEnd()<a.fnRecordsDisplay()){qa(a,"next");y(a);x(a)}});a.nScrollHead=c;a.nScrollFoot=f;return b}function La(a){var b=a.nScrollHead.getElementsByTagName("div")[0],c=b.getElementsByTagName("table")[0],d=a.nTable.parentNode,i,f,g,e,j,o,k,m,p=[],n=[],l=null!==a.nTFoot?a.nScrollFoot.getElementsByTagName("div")[0]:null,R=null!==a.nTFoot?l.getElementsByTagName("table")[0]:null,r=a.oBrowser.bScrollOversize,s=function(a){k=
-a.style;k.paddingTop="0";k.paddingBottom="0";k.borderTopWidth="0";k.borderBottomWidth="0";k.height=0};h(a.nTable).children("thead, tfoot").remove();i=h(a.nTHead).clone()[0];a.nTable.insertBefore(i,a.nTable.childNodes[0]);g=a.nTHead.getElementsByTagName("tr");e=i.getElementsByTagName("tr");null!==a.nTFoot&&(j=h(a.nTFoot).clone()[0],a.nTable.insertBefore(j,a.nTable.childNodes[1]),o=a.nTFoot.getElementsByTagName("tr"),j=j.getElementsByTagName("tr"));""===a.oScroll.sX&&(d.style.width="100%",b.parentNode.style.width=
-"100%");var t=N(a,i);i=0;for(f=t.length;i<f;i++)m=G(a,i),t[i].style.width=a.aoColumns[m].sWidth;null!==a.nTFoot&&C(function(a){a.style.width=""},j);a.oScroll.bCollapse&&""!==a.oScroll.sY&&(d.style.height=d.offsetHeight+a.nTHead.offsetHeight+"px");i=h(a.nTable).outerWidth();if(""===a.oScroll.sX){if(a.nTable.style.width="100%",r&&(h("tbody",d).height()>d.offsetHeight||"scroll"==h(d).css("overflow-y")))a.nTable.style.width=q(h(a.nTable).outerWidth()-a.oScroll.iBarWidth)}else""!==a.oScroll.sXInner?a.nTable.style.width=
-q(a.oScroll.sXInner):i==h(d).width()&&h(d).height()<h(a.nTable).height()?(a.nTable.style.width=q(i-a.oScroll.iBarWidth),h(a.nTable).outerWidth()>i-a.oScroll.iBarWidth&&(a.nTable.style.width=q(i))):a.nTable.style.width=q(i);i=h(a.nTable).outerWidth();C(s,e);C(function(a){p.push(q(h(a).width()))},e);C(function(a,b){a.style.width=p[b]},g);h(e).height(0);null!==a.nTFoot&&(C(s,j),C(function(a){n.push(q(h(a).width()))},j),C(function(a,b){a.style.width=n[b]},o),h(j).height(0));C(function(a,b){a.innerHTML=
-"";a.style.width=p[b]},e);null!==a.nTFoot&&C(function(a,b){a.innerHTML="";a.style.width=n[b]},j);if(h(a.nTable).outerWidth()<i){g=d.scrollHeight>d.offsetHeight||"scroll"==h(d).css("overflow-y")?i+a.oScroll.iBarWidth:i;if(r&&(d.scrollHeight>d.offsetHeight||"scroll"==h(d).css("overflow-y")))a.nTable.style.width=q(g-a.oScroll.iBarWidth);d.style.width=q(g);a.nScrollHead.style.width=q(g);null!==a.nTFoot&&(a.nScrollFoot.style.width=q(g));""===a.oScroll.sX?D(a,1,"The table cannot fit into the current element which will cause column misalignment. The table has been drawn at its minimum possible width."):
-""!==a.oScroll.sXInner&&D(a,1,"The table cannot fit into the current element which will cause column misalignment. Increase the sScrollXInner value or remove it to allow automatic calculation")}else d.style.width=q("100%"),a.nScrollHead.style.width=q("100%"),null!==a.nTFoot&&(a.nScrollFoot.style.width=q("100%"));""===a.oScroll.sY&&r&&(d.style.height=q(a.nTable.offsetHeight+a.oScroll.iBarWidth));""!==a.oScroll.sY&&a.oScroll.bCollapse&&(d.style.height=q(a.oScroll.sY),r=""!==a.oScroll.sX&&a.nTable.offsetWidth>
-d.offsetWidth?a.oScroll.iBarWidth:0,a.nTable.offsetHeight<d.offsetHeight&&(d.style.height=q(a.nTable.offsetHeight+r)));r=h(a.nTable).outerWidth();c.style.width=q(r);b.style.width=q(r);c=h(a.nTable).height()>d.clientHeight||"scroll"==h(d).css("overflow-y");b.style.paddingRight=c?a.oScroll.iBarWidth+"px":"0px";null!==a.nTFoot&&(R.style.width=q(r),l.style.width=q(r),l.style.paddingRight=c?a.oScroll.iBarWidth+"px":"0px");h(d).scroll();if(a.bSorted||a.bFiltered)d.scrollTop=0}function C(a,b,c){for(var d=
-0,i=0,f=b.length,g,e;i<f;){g=b[i].firstChild;for(e=c?c[i].firstChild:null;g;)1===g.nodeType&&(c?a(g,e,d):a(g,d),d++),g=g.nextSibling,e=c?e.nextSibling:null;i++}}function Ma(a,b){if(!a||null===a||""===a)return 0;b||(b=l.body);var c,d=l.createElement("div");d.style.width=q(a);b.appendChild(d);c=d.offsetWidth;b.removeChild(d);return c}function da(a){var b=0,c,d=0,i=a.aoColumns.length,f,e,j=h("th",a.nTHead),o=a.nTable.getAttribute("width");e=a.nTable.parentNode;for(f=0;f<i;f++)a.aoColumns[f].bVisible&&
-(d++,null!==a.aoColumns[f].sWidth&&(c=Ma(a.aoColumns[f].sWidthOrig,e),null!==c&&(a.aoColumns[f].sWidth=q(c)),b++));if(i==j.length&&0===b&&d==i&&""===a.oScroll.sX&&""===a.oScroll.sY)for(f=0;f<a.aoColumns.length;f++)c=h(j[f]).width(),null!==c&&(a.aoColumns[f].sWidth=q(c));else{b=a.nTable.cloneNode(!1);f=a.nTHead.cloneNode(!0);d=l.createElement("tbody");c=l.createElement("tr");b.removeAttribute("id");b.appendChild(f);null!==a.nTFoot&&(b.appendChild(a.nTFoot.cloneNode(!0)),C(function(a){a.style.width=
-""},b.getElementsByTagName("tr")));b.appendChild(d);d.appendChild(c);d=h("thead th",b);0===d.length&&(d=h("tbody tr:eq(0)>td",b));j=N(a,f);for(f=d=0;f<i;f++){var k=a.aoColumns[f];k.bVisible&&null!==k.sWidthOrig&&""!==k.sWidthOrig?j[f-d].style.width=q(k.sWidthOrig):k.bVisible?j[f-d].style.width="":d++}for(f=0;f<i;f++)a.aoColumns[f].bVisible&&(d=Na(a,f),null!==d&&(d=d.cloneNode(!0),""!==a.aoColumns[f].sContentPadding&&(d.innerHTML+=a.aoColumns[f].sContentPadding),c.appendChild(d)));e.appendChild(b);
-""!==a.oScroll.sX&&""!==a.oScroll.sXInner?b.style.width=q(a.oScroll.sXInner):""!==a.oScroll.sX?(b.style.width="",h(b).width()<e.offsetWidth&&(b.style.width=q(e.offsetWidth))):""!==a.oScroll.sY?b.style.width=q(e.offsetWidth):o&&(b.style.width=q(o));b.style.visibility="hidden";Oa(a,b);i=h("tbody tr:eq(0)",b).children();0===i.length&&(i=N(a,h("thead",b)[0]));if(""!==a.oScroll.sX){for(f=d=e=0;f<a.aoColumns.length;f++)a.aoColumns[f].bVisible&&(e=null===a.aoColumns[f].sWidthOrig?e+h(i[d]).outerWidth():
-e+(parseInt(a.aoColumns[f].sWidth.replace("px",""),10)+(h(i[d]).outerWidth()-h(i[d]).width())),d++);b.style.width=q(e);a.nTable.style.width=q(e)}for(f=d=0;f<a.aoColumns.length;f++)a.aoColumns[f].bVisible&&(e=h(i[d]).width(),null!==e&&0<e&&(a.aoColumns[f].sWidth=q(e)),d++);i=h(b).css("width");a.nTable.style.width=-1!==i.indexOf("%")?i:q(h(b).outerWidth());b.parentNode.removeChild(b)}o&&(a.nTable.style.width=q(o))}function Oa(a,b){""===a.oScroll.sX&&""!==a.oScroll.sY?(h(b).width(),b.style.width=q(h(b).outerWidth()-
-a.oScroll.iBarWidth)):""!==a.oScroll.sX&&(b.style.width=q(h(b).outerWidth()))}function Na(a,b){var c=Pa(a,b);if(0>c)return null;if(null===a.aoData[c].nTr){var d=l.createElement("td");d.innerHTML=v(a,c,b,"");return d}return J(a,c)[b]}function Pa(a,b){for(var c=-1,d=-1,i=0;i<a.aoData.length;i++){var e=v(a,i,b,"display")+"",e=e.replace(/<.*?>/g,"");e.length>c&&(c=e.length,d=i)}return d}function q(a){if(null===a)return"0px";if("number"==typeof a)return 0>a?"0px":a+"px";var b=a.charCodeAt(a.length-1);
-return 48>b||57<b?a:a+"px"}function Qa(){var a=l.createElement("p"),b=a.style;b.width="100%";b.height="200px";b.padding="0px";var c=l.createElement("div"),b=c.style;b.position="absolute";b.top="0px";b.left="0px";b.visibility="hidden";b.width="200px";b.height="150px";b.padding="0px";b.overflow="hidden";c.appendChild(a);l.body.appendChild(c);b=a.offsetWidth;c.style.overflow="scroll";a=a.offsetWidth;b==a&&(a=c.clientWidth);l.body.removeChild(c);return b-a}function O(a,b){var c,d,i,e,g,k,o=[],m=[],p=
-j.ext.oSort,l=a.aoData,q=a.aoColumns,G=a.oLanguage.oAria;if(!a.oFeatures.bServerSide&&(0!==a.aaSorting.length||null!==a.aaSortingFixed)){o=null!==a.aaSortingFixed?a.aaSortingFixed.concat(a.aaSorting):a.aaSorting.slice();for(c=0;c<o.length;c++)if(d=o[c][0],i=R(a,d),e=a.aoColumns[d].sSortDataType,j.ext.afnSortData[e])if(g=j.ext.afnSortData[e].call(a.oInstance,a,d,i),g.length===l.length){i=0;for(e=l.length;i<e;i++)F(a,i,d,g[i])}else D(a,0,"Returned data sort array (col "+d+") is the wrong length");c=
-0;for(d=a.aiDisplayMaster.length;c<d;c++)m[a.aiDisplayMaster[c]]=c;var r=o.length,s;c=0;for(d=l.length;c<d;c++)for(i=0;i<r;i++){s=q[o[i][0]].aDataSort;g=0;for(k=s.length;g<k;g++)e=q[s[g]].sType,e=p[(e?e:"string")+"-pre"],l[c]._aSortData[s[g]]=e?e(v(a,c,s[g],"sort")):v(a,c,s[g],"sort")}a.aiDisplayMaster.sort(function(a,b){var c,d,e,i,f;for(c=0;c<r;c++){f=q[o[c][0]].aDataSort;d=0;for(e=f.length;d<e;d++)if(i=q[f[d]].sType,i=p[(i?i:"string")+"-"+o[c][1]](l[a]._aSortData[f[d]],l[b]._aSortData[f[d]]),0!==
-i)return i}return p["numeric-asc"](m[a],m[b])})}(b===n||b)&&!a.oFeatures.bDeferRender&&P(a);c=0;for(d=a.aoColumns.length;c<d;c++)e=q[c].sTitle.replace(/<.*?>/g,""),i=q[c].nTh,i.removeAttribute("aria-sort"),i.removeAttribute("aria-label"),q[c].bSortable?0<o.length&&o[0][0]==c?(i.setAttribute("aria-sort","asc"==o[0][1]?"ascending":"descending"),i.setAttribute("aria-label",e+("asc"==(q[c].asSorting[o[0][2]+1]?q[c].asSorting[o[0][2]+1]:q[c].asSorting[0])?G.sSortAscending:G.sSortDescending))):i.setAttribute("aria-label",
-e+("asc"==q[c].asSorting[0]?G.sSortAscending:G.sSortDescending)):i.setAttribute("aria-label",e);a.bSorted=!0;h(a.oInstance).trigger("sort",a);a.oFeatures.bFilter?K(a,a.oPreviousSearch,1):(a.aiDisplay=a.aiDisplayMaster.slice(),a._iDisplayStart=0,y(a),x(a))}function ia(a,b,c,d){Ra(b,{},function(b){if(!1!==a.aoColumns[c].bSortable){var e=function(){var d,e;if(b.shiftKey){for(var f=!1,h=0;h<a.aaSorting.length;h++)if(a.aaSorting[h][0]==c){f=!0;d=a.aaSorting[h][0];e=a.aaSorting[h][2]+1;a.aoColumns[d].asSorting[e]?
-(a.aaSorting[h][1]=a.aoColumns[d].asSorting[e],a.aaSorting[h][2]=e):a.aaSorting.splice(h,1);break}!1===f&&a.aaSorting.push([c,a.aoColumns[c].asSorting[0],0])}else 1==a.aaSorting.length&&a.aaSorting[0][0]==c?(d=a.aaSorting[0][0],e=a.aaSorting[0][2]+1,a.aoColumns[d].asSorting[e]||(e=0),a.aaSorting[0][1]=a.aoColumns[d].asSorting[e],a.aaSorting[0][2]=e):(a.aaSorting.splice(0,a.aaSorting.length),a.aaSorting.push([c,a.aoColumns[c].asSorting[0],0]));O(a)};a.oFeatures.bProcessing?(E(a,!0),setTimeout(function(){e();
-a.oFeatures.bServerSide||E(a,!1)},0)):e();"function"==typeof d&&d(a)}})}function P(a){var b,c,d,e,f,g=a.aoColumns.length,j=a.oClasses;for(b=0;b<g;b++)a.aoColumns[b].bSortable&&h(a.aoColumns[b].nTh).removeClass(j.sSortAsc+" "+j.sSortDesc+" "+a.aoColumns[b].sSortingClass);c=null!==a.aaSortingFixed?a.aaSortingFixed.concat(a.aaSorting):a.aaSorting.slice();for(b=0;b<a.aoColumns.length;b++)if(a.aoColumns[b].bSortable){f=a.aoColumns[b].sSortingClass;e=-1;for(d=0;d<c.length;d++)if(c[d][0]==b){f="asc"==c[d][1]?
-j.sSortAsc:j.sSortDesc;e=d;break}h(a.aoColumns[b].nTh).addClass(f);a.bJUI&&(f=h("span."+j.sSortIcon,a.aoColumns[b].nTh),f.removeClass(j.sSortJUIAsc+" "+j.sSortJUIDesc+" "+j.sSortJUI+" "+j.sSortJUIAscAllowed+" "+j.sSortJUIDescAllowed),f.addClass(-1==e?a.aoColumns[b].sSortingClassJUI:"asc"==c[e][1]?j.sSortJUIAsc:j.sSortJUIDesc))}else h(a.aoColumns[b].nTh).addClass(a.aoColumns[b].sSortingClass);f=j.sSortColumn;if(a.oFeatures.bSort&&a.oFeatures.bSortClasses){a=J(a);e=[];for(b=0;b<g;b++)e.push("");b=0;
-for(d=1;b<c.length;b++)j=parseInt(c[b][0],10),e[j]=f+d,3>d&&d++;f=RegExp(f+"[123]");var o;b=0;for(c=a.length;b<c;b++)j=b%g,d=a[b].className,o=e[j],j=d.replace(f,o),j!=d?a[b].className=h.trim(j):0<o.length&&-1==d.indexOf(o)&&(a[b].className=d+" "+o)}}function ra(a){if(a.oFeatures.bStateSave&&!a.bDestroying){var b,c;b=a.oScroll.bInfinite;var d={iCreate:(new Date).getTime(),iStart:b?0:a._iDisplayStart,iEnd:b?a._iDisplayLength:a._iDisplayEnd,iLength:a._iDisplayLength,aaSorting:h.extend(!0,[],a.aaSorting),
-oSearch:h.extend(!0,{},a.oPreviousSearch),aoSearchCols:h.extend(!0,[],a.aoPreSearchCols),abVisCols:[]};b=0;for(c=a.aoColumns.length;b<c;b++)d.abVisCols.push(a.aoColumns[b].bVisible);A(a,"aoStateSaveParams","stateSaveParams",[a,d]);a.fnStateSave.call(a.oInstance,a,d)}}function Sa(a,b){if(a.oFeatures.bStateSave){var c=a.fnStateLoad.call(a.oInstance,a);if(c){var d=A(a,"aoStateLoadParams","stateLoadParams",[a,c]);if(-1===h.inArray(!1,d)){a.oLoadedState=h.extend(!0,{},c);a._iDisplayStart=c.iStart;a.iInitDisplayStart=
-c.iStart;a._iDisplayEnd=c.iEnd;a._iDisplayLength=c.iLength;a.aaSorting=c.aaSorting.slice();a.saved_aaSorting=c.aaSorting.slice();h.extend(a.oPreviousSearch,c.oSearch);h.extend(!0,a.aoPreSearchCols,c.aoSearchCols);b.saved_aoColumns=[];for(d=0;d<c.abVisCols.length;d++)b.saved_aoColumns[d]={},b.saved_aoColumns[d].bVisible=c.abVisCols[d];A(a,"aoStateLoaded","stateLoaded",[a,c])}}}}function s(a){for(var b=0;b<j.settings.length;b++)if(j.settings[b].nTable===a)return j.settings[b];return null}function T(a){for(var b=
-[],a=a.aoData,c=0,d=a.length;c<d;c++)null!==a[c].nTr&&b.push(a[c].nTr);return b}function J(a,b){var c=[],d,e,f,g,h,j;e=0;var o=a.aoData.length;b!==n&&(e=b,o=b+1);for(f=e;f<o;f++)if(j=a.aoData[f],null!==j.nTr){e=[];for(d=j.nTr.firstChild;d;)g=d.nodeName.toLowerCase(),("td"==g||"th"==g)&&e.push(d),d=d.nextSibling;g=d=0;for(h=a.aoColumns.length;g<h;g++)a.aoColumns[g].bVisible?c.push(e[g-d]):(c.push(j._anHidden[g]),d++)}return c}function D(a,b,c){a=null===a?"DataTables warning: "+c:"DataTables warning (table id = '"+
-a.sTableId+"'): "+c;if(0===b)if("alert"==j.ext.sErrMode)alert(a);else throw Error(a);else X.console&&console.log&&console.log(a)}function p(a,b,c,d){d===n&&(d=c);b[c]!==n&&(a[d]=b[c])}function Ta(a,b){var c,d;for(d in b)b.hasOwnProperty(d)&&(c=b[d],"object"===typeof e[d]&&null!==c&&!1===h.isArray(c)?h.extend(!0,a[d],c):a[d]=c);return a}function Ra(a,b,c){h(a).bind("click.DT",b,function(b){a.blur();c(b)}).bind("keypress.DT",b,function(a){13===a.which&&c(a)}).bind("selectstart.DT",function(){return!1})}
-function z(a,b,c,d){c&&a[b].push({fn:c,sName:d})}function A(a,b,c,d){for(var b=a[b],e=[],f=b.length-1;0<=f;f--)e.push(b[f].fn.apply(a.oInstance,d));null!==c&&h(a.oInstance).trigger(c,d);return e}function Ua(a){var b=h('<div style="position:absolute; top:0; left:0; height:1px; width:1px; overflow:hidden"><div style="position:absolute; top:1px; left:1px; width:100px; overflow:scroll;"><div id="DT_BrowserTest" style="width:100%; height:10px;"></div></div></div>')[0];l.body.appendChild(b);a.oBrowser.bScrollOversize=
-100===h("#DT_BrowserTest",b)[0].offsetWidth?!0:!1;l.body.removeChild(b)}function Va(a){return function(){var b=[s(this[j.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return j.ext.oApi[a].apply(this,b)}}var U=/\[.*?\]$/,Wa=X.JSON?JSON.stringify:function(a){var b=typeof a;if("object"!==b||null===a)return"string"===b&&(a='"'+a+'"'),a+"";var c,d,e=[],f=h.isArray(a);for(c in a)d=a[c],b=typeof d,"string"===b?d='"'+d+'"':"object"===b&&null!==d&&(d=Wa(d)),e.push((f?"":'"'+c+'":')+d);return(f?
-"[":"{")+e+(f?"]":"}")};this.$=function(a,b){var c,d,e=[],f;d=s(this[j.ext.iApiIndex]);var g=d.aoData,o=d.aiDisplay,k=d.aiDisplayMaster;b||(b={});b=h.extend({},{filter:"none",order:"current",page:"all"},b);if("current"==b.page){c=d._iDisplayStart;for(d=d.fnDisplayEnd();c<d;c++)(f=g[o[c]].nTr)&&e.push(f)}else if("current"==b.order&&"none"==b.filter){c=0;for(d=k.length;c<d;c++)(f=g[k[c]].nTr)&&e.push(f)}else if("current"==b.order&&"applied"==b.filter){c=0;for(d=o.length;c<d;c++)(f=g[o[c]].nTr)&&e.push(f)}else if("original"==
-b.order&&"none"==b.filter){c=0;for(d=g.length;c<d;c++)(f=g[c].nTr)&&e.push(f)}else if("original"==b.order&&"applied"==b.filter){c=0;for(d=g.length;c<d;c++)f=g[c].nTr,-1!==h.inArray(c,o)&&f&&e.push(f)}else D(d,1,"Unknown selection options");e=h(e);c=e.filter(a);e=e.find(a);return h([].concat(h.makeArray(c),h.makeArray(e)))};this._=function(a,b){var c=[],d,e,f=this.$(a,b);d=0;for(e=f.length;d<e;d++)c.push(this.fnGetData(f[d]));return c};this.fnAddData=function(a,b){if(0===a.length)return[];var c=[],
-d,e=s(this[j.ext.iApiIndex]);if("object"===typeof a[0]&&null!==a[0])for(var f=0;f<a.length;f++){d=H(e,a[f]);if(-1==d)return c;c.push(d)}else{d=H(e,a);if(-1==d)return c;c.push(d)}e.aiDisplay=e.aiDisplayMaster.slice();(b===n||b)&&aa(e);return c};this.fnAdjustColumnSizing=function(a){var b=s(this[j.ext.iApiIndex]);k(b);a===n||a?this.fnDraw(!1):(""!==b.oScroll.sX||""!==b.oScroll.sY)&&this.oApi._fnScrollDraw(b)};this.fnClearTable=function(a){var b=s(this[j.ext.iApiIndex]);ga(b);(a===n||a)&&x(b)};this.fnClose=
-function(a){for(var b=s(this[j.ext.iApiIndex]),c=0;c<b.aoOpenRows.length;c++)if(b.aoOpenRows[c].nParent==a)return(a=b.aoOpenRows[c].nTr.parentNode)&&a.removeChild(b.aoOpenRows[c].nTr),b.aoOpenRows.splice(c,1),0;return 1};this.fnDeleteRow=function(a,b,c){var d=s(this[j.ext.iApiIndex]),e,f,a="object"===typeof a?I(d,a):a,g=d.aoData.splice(a,1);e=0;for(f=d.aoData.length;e<f;e++)null!==d.aoData[e].nTr&&(d.aoData[e].nTr._DT_RowIndex=e);e=h.inArray(a,d.aiDisplay);d.asDataSearch.splice(e,1);ha(d.aiDisplayMaster,
-a);ha(d.aiDisplay,a);"function"===typeof b&&b.call(this,d,g);d._iDisplayStart>=d.fnRecordsDisplay()&&(d._iDisplayStart-=d._iDisplayLength,0>d._iDisplayStart&&(d._iDisplayStart=0));if(c===n||c)y(d),x(d);return g};this.fnDestroy=function(a){var b=s(this[j.ext.iApiIndex]),c=b.nTableWrapper.parentNode,d=b.nTBody,i,f,a=a===n?!1:a;b.bDestroying=!0;A(b,"aoDestroyCallback","destroy",[b]);if(!a){i=0;for(f=b.aoColumns.length;i<f;i++)!1===b.aoColumns[i].bVisible&&this.fnSetColumnVis(i,!0)}h(b.nTableWrapper).find("*").andSelf().unbind(".DT");
-h("tbody>tr>td."+b.oClasses.sRowEmpty,b.nTable).parent().remove();b.nTable!=b.nTHead.parentNode&&(h(b.nTable).children("thead").remove(),b.nTable.appendChild(b.nTHead));b.nTFoot&&b.nTable!=b.nTFoot.parentNode&&(h(b.nTable).children("tfoot").remove(),b.nTable.appendChild(b.nTFoot));b.nTable.parentNode.removeChild(b.nTable);h(b.nTableWrapper).remove();b.aaSorting=[];b.aaSortingFixed=[];P(b);h(T(b)).removeClass(b.asStripeClasses.join(" "));h("th, td",b.nTHead).removeClass([b.oClasses.sSortable,b.oClasses.sSortableAsc,
-b.oClasses.sSortableDesc,b.oClasses.sSortableNone].join(" "));b.bJUI&&(h("th span."+b.oClasses.sSortIcon+", td span."+b.oClasses.sSortIcon,b.nTHead).remove(),h("th, td",b.nTHead).each(function(){var a=h("div."+b.oClasses.sSortJUIWrapper,this),c=a.contents();h(this).append(c);a.remove()}));!a&&b.nTableReinsertBefore?c.insertBefore(b.nTable,b.nTableReinsertBefore):a||c.appendChild(b.nTable);i=0;for(f=b.aoData.length;i<f;i++)null!==b.aoData[i].nTr&&d.appendChild(b.aoData[i].nTr);!0===b.oFeatures.bAutoWidth&&
-(b.nTable.style.width=q(b.sDestroyWidth));if(f=b.asDestroyStripes.length){a=h(d).children("tr");for(i=0;i<f;i++)a.filter(":nth-child("+f+"n + "+i+")").addClass(b.asDestroyStripes[i])}i=0;for(f=j.settings.length;i<f;i++)j.settings[i]==b&&j.settings.splice(i,1);e=b=null};this.fnDraw=function(a){var b=s(this[j.ext.iApiIndex]);!1===a?(y(b),x(b)):aa(b)};this.fnFilter=function(a,b,c,d,e,f){var g=s(this[j.ext.iApiIndex]);if(g.oFeatures.bFilter){if(c===n||null===c)c=!1;if(d===n||null===d)d=!0;if(e===n||null===
-e)e=!0;if(f===n||null===f)f=!0;if(b===n||null===b){if(K(g,{sSearch:a+"",bRegex:c,bSmart:d,bCaseInsensitive:f},1),e&&g.aanFeatures.f){b=g.aanFeatures.f;c=0;for(d=b.length;c<d;c++)try{b[c]._DT_Input!=l.activeElement&&h(b[c]._DT_Input).val(a)}catch(o){h(b[c]._DT_Input).val(a)}}}else h.extend(g.aoPreSearchCols[b],{sSearch:a+"",bRegex:c,bSmart:d,bCaseInsensitive:f}),K(g,g.oPreviousSearch,1)}};this.fnGetData=function(a,b){var c=s(this[j.ext.iApiIndex]);if(a!==n){var d=a;if("object"===typeof a){var e=a.nodeName.toLowerCase();
-"tr"===e?d=I(c,a):"td"===e&&(d=I(c,a.parentNode),b=fa(c,d,a))}return b!==n?v(c,d,b,""):c.aoData[d]!==n?c.aoData[d]._aData:null}return Z(c)};this.fnGetNodes=function(a){var b=s(this[j.ext.iApiIndex]);return a!==n?b.aoData[a]!==n?b.aoData[a].nTr:null:T(b)};this.fnGetPosition=function(a){var b=s(this[j.ext.iApiIndex]),c=a.nodeName.toUpperCase();return"TR"==c?I(b,a):"TD"==c||"TH"==c?(c=I(b,a.parentNode),a=fa(b,c,a),[c,R(b,a),a]):null};this.fnIsOpen=function(a){for(var b=s(this[j.ext.iApiIndex]),c=0;c<
-b.aoOpenRows.length;c++)if(b.aoOpenRows[c].nParent==a)return!0;return!1};this.fnOpen=function(a,b,c){var d=s(this[j.ext.iApiIndex]),e=T(d);if(-1!==h.inArray(a,e)){this.fnClose(a);var e=l.createElement("tr"),f=l.createElement("td");e.appendChild(f);f.className=c;f.colSpan=t(d);"string"===typeof b?f.innerHTML=b:h(f).html(b);b=h("tr",d.nTBody);-1!=h.inArray(a,b)&&h(e).insertAfter(a);d.aoOpenRows.push({nTr:e,nParent:a});return e}};this.fnPageChange=function(a,b){var c=s(this[j.ext.iApiIndex]);qa(c,a);
-y(c);(b===n||b)&&x(c)};this.fnSetColumnVis=function(a,b,c){var d=s(this[j.ext.iApiIndex]),e,f,g=d.aoColumns,h=d.aoData,o,m;if(g[a].bVisible!=b){if(b){for(e=f=0;e<a;e++)g[e].bVisible&&f++;m=f>=t(d);if(!m)for(e=a;e<g.length;e++)if(g[e].bVisible){o=e;break}e=0;for(f=h.length;e<f;e++)null!==h[e].nTr&&(m?h[e].nTr.appendChild(h[e]._anHidden[a]):h[e].nTr.insertBefore(h[e]._anHidden[a],J(d,e)[o]))}else{e=0;for(f=h.length;e<f;e++)null!==h[e].nTr&&(o=J(d,e)[a],h[e]._anHidden[a]=o,o.parentNode.removeChild(o))}g[a].bVisible=
-b;W(d,d.aoHeader);d.nTFoot&&W(d,d.aoFooter);e=0;for(f=d.aoOpenRows.length;e<f;e++)d.aoOpenRows[e].nTr.colSpan=t(d);if(c===n||c)k(d),x(d);ra(d)}};this.fnSettings=function(){return s(this[j.ext.iApiIndex])};this.fnSort=function(a){var b=s(this[j.ext.iApiIndex]);b.aaSorting=a;O(b)};this.fnSortListener=function(a,b,c){ia(s(this[j.ext.iApiIndex]),a,b,c)};this.fnUpdate=function(a,b,c,d,e){var f=s(this[j.ext.iApiIndex]),b="object"===typeof b?I(f,b):b;if(h.isArray(a)&&c===n){f.aoData[b]._aData=a.slice();
-for(c=0;c<f.aoColumns.length;c++)this.fnUpdate(v(f,b,c),b,c,!1,!1)}else if(h.isPlainObject(a)&&c===n){f.aoData[b]._aData=h.extend(!0,{},a);for(c=0;c<f.aoColumns.length;c++)this.fnUpdate(v(f,b,c),b,c,!1,!1)}else{F(f,b,c,a);var a=v(f,b,c,"display"),g=f.aoColumns[c];null!==g.fnRender&&(a=S(f,b,c),g.bUseRendered&&F(f,b,c,a));null!==f.aoData[b].nTr&&(J(f,b)[c].innerHTML=a)}c=h.inArray(b,f.aiDisplay);f.asDataSearch[c]=na(f,Y(f,b,"filter",r(f,"bSearchable")));(e===n||e)&&k(f);(d===n||d)&&aa(f);return 0};
-this.fnVersionCheck=j.ext.fnVersionCheck;this.oApi={_fnExternApiFunc:Va,_fnInitialise:ba,_fnInitComplete:$,_fnLanguageCompat:pa,_fnAddColumn:o,_fnColumnOptions:m,_fnAddData:H,_fnCreateTr:ea,_fnGatherData:ua,_fnBuildHead:va,_fnDrawHead:W,_fnDraw:x,_fnReDraw:aa,_fnAjaxUpdate:wa,_fnAjaxParameters:Ea,_fnAjaxUpdateDraw:Fa,_fnServerParams:ka,_fnAddOptionsHtml:xa,_fnFeatureHtmlTable:Ba,_fnScrollDraw:La,_fnAdjustColumnSizing:k,_fnFeatureHtmlFilter:za,_fnFilterComplete:K,_fnFilterCustom:Ia,_fnFilterColumn:Ha,
-_fnFilter:Ga,_fnBuildSearchArray:la,_fnBuildSearchRow:na,_fnFilterCreateSearch:ma,_fnDataToSearch:Ja,_fnSort:O,_fnSortAttachListener:ia,_fnSortingClasses:P,_fnFeatureHtmlPaginate:Da,_fnPageChange:qa,_fnFeatureHtmlInfo:Ca,_fnUpdateInfo:Ka,_fnFeatureHtmlLength:ya,_fnFeatureHtmlProcessing:Aa,_fnProcessingDisplay:E,_fnVisibleToColumnIndex:G,_fnColumnIndexToVisible:R,_fnNodeToDataIndex:I,_fnVisbleColumns:t,_fnCalculateEnd:y,_fnConvertToWidth:Ma,_fnCalculateColumnWidths:da,_fnScrollingWidthAdjust:Oa,_fnGetWidestNode:Na,
-_fnGetMaxLenString:Pa,_fnStringToCss:q,_fnDetectType:B,_fnSettingsFromNode:s,_fnGetDataMaster:Z,_fnGetTrNodes:T,_fnGetTdNodes:J,_fnEscapeRegex:oa,_fnDeleteIndex:ha,_fnReOrderIndex:u,_fnColumnOrdering:M,_fnLog:D,_fnClearTable:ga,_fnSaveState:ra,_fnLoadState:Sa,_fnCreateCookie:function(a,b,c,d,e){var f=new Date;f.setTime(f.getTime()+1E3*c);var c=X.location.pathname.split("/"),a=a+"_"+c.pop().replace(/[\/:]/g,"").toLowerCase(),g;null!==e?(g="function"===typeof h.parseJSON?h.parseJSON(b):eval("("+b+")"),
-b=e(a,g,f.toGMTString(),c.join("/")+"/")):b=a+"="+encodeURIComponent(b)+"; expires="+f.toGMTString()+"; path="+c.join("/")+"/";a=l.cookie.split(";");e=b.split(";")[0].length;f=[];if(4096<e+l.cookie.length+10){for(var j=0,o=a.length;j<o;j++)if(-1!=a[j].indexOf(d)){var k=a[j].split("=");try{(g=eval("("+decodeURIComponent(k[1])+")"))&&g.iCreate&&f.push({name:k[0],time:g.iCreate})}catch(m){}}for(f.sort(function(a,b){return b.time-a.time});4096<e+l.cookie.length+10;){if(0===f.length)return;d=f.pop();l.cookie=
-d.name+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path="+c.join("/")+"/"}}l.cookie=b},_fnReadCookie:function(a){for(var b=X.location.pathname.split("/"),a=a+"_"+b[b.length-1].replace(/[\/:]/g,"").toLowerCase()+"=",b=l.cookie.split(";"),c=0;c<b.length;c++){for(var d=b[c];" "==d.charAt(0);)d=d.substring(1,d.length);if(0===d.indexOf(a))return decodeURIComponent(d.substring(a.length,d.length))}return null},_fnDetectHeader:V,_fnGetUniqueThs:N,_fnScrollBarWidth:Qa,_fnApplyToChildren:C,_fnMap:p,_fnGetRowData:Y,
-_fnGetCellData:v,_fnSetCellData:F,_fnGetObjectDataFn:Q,_fnSetObjectDataFn:L,_fnApplyColumnDefs:ta,_fnBindAction:Ra,_fnExtend:Ta,_fnCallbackReg:z,_fnCallbackFire:A,_fnJsonString:Wa,_fnRender:S,_fnNodeToColumnIndex:fa,_fnInfoMacros:ja,_fnBrowserDetect:Ua,_fnGetColumns:r};h.extend(j.ext.oApi,this.oApi);for(var sa in j.ext.oApi)sa&&(this[sa]=Va(sa));var ca=this;this.each(function(){var a=0,b,c,d;c=this.getAttribute("id");var i=!1,f=!1;if("table"!=this.nodeName.toLowerCase())D(null,0,"Attempted to initialise DataTables on a node which is not a table: "+
-this.nodeName);else{a=0;for(b=j.settings.length;a<b;a++){if(j.settings[a].nTable==this){if(e===n||e.bRetrieve)return j.settings[a].oInstance;if(e.bDestroy){j.settings[a].oInstance.fnDestroy();break}else{D(j.settings[a],0,"Cannot reinitialise DataTable.\n\nTo retrieve the DataTables object for this table, pass no arguments or see the docs for bRetrieve and bDestroy");return}}if(j.settings[a].sTableId==this.id){j.settings.splice(a,1);break}}if(null===c||""===c)this.id=c="DataTables_Table_"+j.ext._oExternConfig.iNextUnique++;
-var g=h.extend(!0,{},j.models.oSettings,{nTable:this,oApi:ca.oApi,oInit:e,sDestroyWidth:h(this).width(),sInstance:c,sTableId:c});j.settings.push(g);g.oInstance=1===ca.length?ca:h(this).dataTable();e||(e={});e.oLanguage&&pa(e.oLanguage);e=Ta(h.extend(!0,{},j.defaults),e);p(g.oFeatures,e,"bPaginate");p(g.oFeatures,e,"bLengthChange");p(g.oFeatures,e,"bFilter");p(g.oFeatures,e,"bSort");p(g.oFeatures,e,"bInfo");p(g.oFeatures,e,"bProcessing");p(g.oFeatures,e,"bAutoWidth");p(g.oFeatures,e,"bSortClasses");
-p(g.oFeatures,e,"bServerSide");p(g.oFeatures,e,"bDeferRender");p(g.oScroll,e,"sScrollX","sX");p(g.oScroll,e,"sScrollXInner","sXInner");p(g.oScroll,e,"sScrollY","sY");p(g.oScroll,e,"bScrollCollapse","bCollapse");p(g.oScroll,e,"bScrollInfinite","bInfinite");p(g.oScroll,e,"iScrollLoadGap","iLoadGap");p(g.oScroll,e,"bScrollAutoCss","bAutoCss");p(g,e,"asStripeClasses");p(g,e,"asStripClasses","asStripeClasses");p(g,e,"fnServerData");p(g,e,"fnFormatNumber");p(g,e,"sServerMethod");p(g,e,"aaSorting");p(g,
-e,"aaSortingFixed");p(g,e,"aLengthMenu");p(g,e,"sPaginationType");p(g,e,"sAjaxSource");p(g,e,"sAjaxDataProp");p(g,e,"iCookieDuration");p(g,e,"sCookiePrefix");p(g,e,"sDom");p(g,e,"bSortCellsTop");p(g,e,"iTabIndex");p(g,e,"oSearch","oPreviousSearch");p(g,e,"aoSearchCols","aoPreSearchCols");p(g,e,"iDisplayLength","_iDisplayLength");p(g,e,"bJQueryUI","bJUI");p(g,e,"fnCookieCallback");p(g,e,"fnStateLoad");p(g,e,"fnStateSave");p(g.oLanguage,e,"fnInfoCallback");z(g,"aoDrawCallback",e.fnDrawCallback,"user");
-z(g,"aoServerParams",e.fnServerParams,"user");z(g,"aoStateSaveParams",e.fnStateSaveParams,"user");z(g,"aoStateLoadParams",e.fnStateLoadParams,"user");z(g,"aoStateLoaded",e.fnStateLoaded,"user");z(g,"aoRowCallback",e.fnRowCallback,"user");z(g,"aoRowCreatedCallback",e.fnCreatedRow,"user");z(g,"aoHeaderCallback",e.fnHeaderCallback,"user");z(g,"aoFooterCallback",e.fnFooterCallback,"user");z(g,"aoInitComplete",e.fnInitComplete,"user");z(g,"aoPreDrawCallback",e.fnPreDrawCallback,"user");g.oFeatures.bServerSide&&
-g.oFeatures.bSort&&g.oFeatures.bSortClasses?z(g,"aoDrawCallback",P,"server_side_sort_classes"):g.oFeatures.bDeferRender&&z(g,"aoDrawCallback",P,"defer_sort_classes");e.bJQueryUI?(h.extend(g.oClasses,j.ext.oJUIClasses),e.sDom===j.defaults.sDom&&"lfrtip"===j.defaults.sDom&&(g.sDom='<"H"lfr>t<"F"ip>')):h.extend(g.oClasses,j.ext.oStdClasses);h(this).addClass(g.oClasses.sTable);if(""!==g.oScroll.sX||""!==g.oScroll.sY)g.oScroll.iBarWidth=Qa();g.iInitDisplayStart===n&&(g.iInitDisplayStart=e.iDisplayStart,
-g._iDisplayStart=e.iDisplayStart);e.bStateSave&&(g.oFeatures.bStateSave=!0,Sa(g,e),z(g,"aoDrawCallback",ra,"state_save"));null!==e.iDeferLoading&&(g.bDeferLoading=!0,a=h.isArray(e.iDeferLoading),g._iRecordsDisplay=a?e.iDeferLoading[0]:e.iDeferLoading,g._iRecordsTotal=a?e.iDeferLoading[1]:e.iDeferLoading);null!==e.aaData&&(f=!0);""!==e.oLanguage.sUrl?(g.oLanguage.sUrl=e.oLanguage.sUrl,h.getJSON(g.oLanguage.sUrl,null,function(a){pa(a);h.extend(true,g.oLanguage,e.oLanguage,a);ba(g)}),i=!0):h.extend(!0,
-g.oLanguage,e.oLanguage);null===e.asStripeClasses&&(g.asStripeClasses=[g.oClasses.sStripeOdd,g.oClasses.sStripeEven]);b=g.asStripeClasses.length;g.asDestroyStripes=[];if(b){c=!1;d=h(this).children("tbody").children("tr:lt("+b+")");for(a=0;a<b;a++)d.hasClass(g.asStripeClasses[a])&&(c=!0,g.asDestroyStripes.push(g.asStripeClasses[a]));c&&d.removeClass(g.asStripeClasses.join(" "))}c=[];a=this.getElementsByTagName("thead");0!==a.length&&(V(g.aoHeader,a[0]),c=N(g));if(null===e.aoColumns){d=[];a=0;for(b=
-c.length;a<b;a++)d.push(null)}else d=e.aoColumns;a=0;for(b=d.length;a<b;a++)e.saved_aoColumns!==n&&e.saved_aoColumns.length==b&&(null===d[a]&&(d[a]={}),d[a].bVisible=e.saved_aoColumns[a].bVisible),o(g,c?c[a]:null);ta(g,e.aoColumnDefs,d,function(a,b){m(g,a,b)});a=0;for(b=g.aaSorting.length;a<b;a++){g.aaSorting[a][0]>=g.aoColumns.length&&(g.aaSorting[a][0]=0);var k=g.aoColumns[g.aaSorting[a][0]];g.aaSorting[a][2]===n&&(g.aaSorting[a][2]=0);e.aaSorting===n&&g.saved_aaSorting===n&&(g.aaSorting[a][1]=
-k.asSorting[0]);c=0;for(d=k.asSorting.length;c<d;c++)if(g.aaSorting[a][1]==k.asSorting[c]){g.aaSorting[a][2]=c;break}}P(g);Ua(g);a=h(this).children("caption").each(function(){this._captionSide=h(this).css("caption-side")});b=h(this).children("thead");0===b.length&&(b=[l.createElement("thead")],this.appendChild(b[0]));g.nTHead=b[0];b=h(this).children("tbody");0===b.length&&(b=[l.createElement("tbody")],this.appendChild(b[0]));g.nTBody=b[0];g.nTBody.setAttribute("role","alert");g.nTBody.setAttribute("aria-live",
-"polite");g.nTBody.setAttribute("aria-relevant","all");b=h(this).children("tfoot");if(0===b.length&&0<a.length&&(""!==g.oScroll.sX||""!==g.oScroll.sY))b=[l.createElement("tfoot")],this.appendChild(b[0]);0<b.length&&(g.nTFoot=b[0],V(g.aoFooter,g.nTFoot));if(f)for(a=0;a<e.aaData.length;a++)H(g,e.aaData[a]);else ua(g);g.aiDisplay=g.aiDisplayMaster.slice();g.bInitialised=!0;!1===i&&ba(g)}});ca=null;return this};j.fnVersionCheck=function(e){for(var h=function(e,h){for(;e.length<h;)e+="0";return e},m=j.ext.sVersion.split("."),
-e=e.split("."),k="",n="",l=0,t=e.length;l<t;l++)k+=h(m[l],3),n+=h(e[l],3);return parseInt(k,10)>=parseInt(n,10)};j.fnIsDataTable=function(e){for(var h=j.settings,m=0;m<h.length;m++)if(h[m].nTable===e||h[m].nScrollHead===e||h[m].nScrollFoot===e)return!0;return!1};j.fnTables=function(e){var o=[];jQuery.each(j.settings,function(j,k){(!e||!0===e&&h(k.nTable).is(":visible"))&&o.push(k.nTable)});return o};j.version="1.9.4";j.settings=[];j.models={};j.models.ext={afnFiltering:[],afnSortData:[],aoFeatures:[],
-aTypes:[],fnVersionCheck:j.fnVersionCheck,iApiIndex:0,ofnSearch:{},oApi:{},oStdClasses:{},oJUIClasses:{},oPagination:{},oSort:{},sVersion:j.version,sErrMode:"alert",_oExternConfig:{iNextUnique:0}};j.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0};j.models.oRow={nTr:null,_aData:[],_aSortData:[],_anHidden:[],_sRowStripe:""};j.models.oColumn={aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bUseRendered:null,bVisible:null,_bAutoType:!0,fnCreatedCell:null,fnGetData:null,
-fnRender:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std",sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null};j.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0,
-bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollAutoCss:!0,bScrollCollapse:!1,bScrollInfinite:!1,bServerSide:!1,bSort:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1,fnCookieCallback:null,fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(e){if(1E3>e)return e;for(var h=e+"",e=h.split(""),j="",h=h.length,k=0;k<h;k++)0===k%3&&0!==k&&(j=this.oLanguage.sInfoThousands+j),j=e[h-k-1]+j;return j},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null,
-fnRowCallback:null,fnServerData:function(e,j,m,k){k.jqXHR=h.ajax({url:e,data:j,success:function(e){e.sError&&k.oApi._fnLog(k,0,e.sError);h(k.oInstance).trigger("xhr",[k,e]);m(e)},dataType:"json",cache:!1,type:k.sServerMethod,error:function(e,h){"parsererror"==h&&k.oApi._fnLog(k,0,"DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error.")}})},fnServerParams:null,fnStateLoad:function(e){var e=this.oApi._fnReadCookie(e.sCookiePrefix+e.sInstance),j;try{j=
-"function"===typeof h.parseJSON?h.parseJSON(e):eval("("+e+")")}catch(m){j=null}return j},fnStateLoadParams:null,fnStateLoaded:null,fnStateSave:function(e,h){this.oApi._fnCreateCookie(e.sCookiePrefix+e.sInstance,this.oApi._fnJsonString(h),e.iCookieDuration,e.sCookiePrefix,e.fnCookieCallback)},fnStateSaveParams:null,iCookieDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iScrollLoadGap:100,iTabIndex:0,oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},
-oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"},sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sInfoThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sUrl:"",sZeroRecords:"No matching records found"},oSearch:h.extend({},j.models.oSearch),sAjaxDataProp:"aaData",
-sAjaxSource:null,sCookiePrefix:"SpryMedia_DataTables_",sDom:"lfrtip",sPaginationType:"two_button",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET"};j.defaults.columns={aDataSort:null,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bUseRendered:!0,bVisible:!0,fnCreatedCell:null,fnRender:null,iDataSort:-1,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null};j.models.oSettings={oFeatures:{bAutoWidth:null,
-bDeferRender:null,bFilter:null,bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortClasses:null,bStateSave:null},oScroll:{bAutoCss:null,bCollapse:null,bInfinite:null,iBarWidth:0,iLoadGap:null,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1},aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aoColumns:[],aoHeader:[],aoFooter:[],asDataSearch:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:null,
-asStripeClasses:null,asDestroyStripes:[],sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,sPaginationType:"two_button",iCookieDuration:0,sCookiePrefix:"",fnCookieCallback:null,aoStateSave:[],aoStateLoad:[],
-oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,bAjaxDataGet:!0,jqXHR:null,fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iDisplayEnd:10,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return this.oFeatures.bServerSide?parseInt(this._iRecordsTotal,10):this.aiDisplayMaster.length},
-fnRecordsDisplay:function(){return this.oFeatures.bServerSide?parseInt(this._iRecordsDisplay,10):this.aiDisplay.length},fnDisplayEnd:function(){return this.oFeatures.bServerSide?!1===this.oFeatures.bPaginate||-1==this._iDisplayLength?this._iDisplayStart+this.aiDisplay.length:Math.min(this._iDisplayStart+this._iDisplayLength,this._iRecordsDisplay):this._iDisplayEnd},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null};j.ext=h.extend(!0,{},j.models.ext);h.extend(j.ext.oStdClasses,
-{sTable:"dataTable",sPagePrevEnabled:"paginate_enabled_previous",sPagePrevDisabled:"paginate_disabled_previous",sPageNextEnabled:"paginate_enabled_next",sPageNextDisabled:"paginate_disabled_next",sPageJUINext:"",sPageJUIPrev:"",sPageButton:"paginate_button",sPageButtonActive:"paginate_active",sPageButtonStaticDisabled:"paginate_button paginate_button_disabled",sPageFirst:"first",sPagePrevious:"previous",sPageNext:"next",sPageLast:"last",sStripeOdd:"odd",sStripeEven:"even",sRowEmpty:"dataTables_empty",
-sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",
-sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody",sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sFooterTH:"",sJUIHeader:"",sJUIFooter:""});h.extend(j.ext.oJUIClasses,j.ext.oStdClasses,{sPagePrevEnabled:"fg-button ui-button ui-state-default ui-corner-left",sPagePrevDisabled:"fg-button ui-button ui-state-default ui-corner-left ui-state-disabled",sPageNextEnabled:"fg-button ui-button ui-state-default ui-corner-right",
-sPageNextDisabled:"fg-button ui-button ui-state-default ui-corner-right ui-state-disabled",sPageJUINext:"ui-icon ui-icon-circle-arrow-e",sPageJUIPrev:"ui-icon ui-icon-circle-arrow-w",sPageButton:"fg-button ui-button ui-state-default",sPageButtonActive:"fg-button ui-button ui-state-default ui-state-disabled",sPageButtonStaticDisabled:"fg-button ui-button ui-state-default ui-state-disabled",sPageFirst:"first ui-corner-tl ui-corner-bl",sPageLast:"last ui-corner-tr ui-corner-br",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",
-sSortAsc:"ui-state-default",sSortDesc:"ui-state-default",sSortable:"ui-state-default",sSortableAsc:"ui-state-default",sSortableDesc:"ui-state-default",sSortableNone:"ui-state-default",sSortJUIAsc:"css_right ui-icon ui-icon-triangle-1-n",sSortJUIDesc:"css_right ui-icon ui-icon-triangle-1-s",sSortJUI:"css_right ui-icon ui-icon-carat-2-n-s",sSortJUIAscAllowed:"css_right ui-icon ui-icon-carat-1-n",sSortJUIDescAllowed:"css_right ui-icon ui-icon-carat-1-s",sSortJUIWrapper:"DataTables_sort_wrapper",sSortIcon:"DataTables_sort_icon",
-sScrollHead:"dataTables_scrollHead ui-state-default",sScrollFoot:"dataTables_scrollFoot ui-state-default",sFooterTH:"ui-state-default",sJUIHeader:"fg-toolbar ui-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix",sJUIFooter:"fg-toolbar ui-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"});h.extend(j.ext.oPagination,{two_button:{fnInit:function(e,j,m){var k=e.oLanguage.oPaginate,n=function(h){e.oApi._fnPageChange(e,h.data.action)&&m(e)},k=!e.bJUI?'<a class="'+
-e.oClasses.sPagePrevDisabled+'" tabindex="'+e.iTabIndex+'" role="button">'+k.sPrevious+'</a><a class="'+e.oClasses.sPageNextDisabled+'" tabindex="'+e.iTabIndex+'" role="button">'+k.sNext+"</a>":'<a class="'+e.oClasses.sPagePrevDisabled+'" tabindex="'+e.iTabIndex+'" role="button"><span class="'+e.oClasses.sPageJUIPrev+'"></span></a><a class="'+e.oClasses.sPageNextDisabled+'" tabindex="'+e.iTabIndex+'" role="button"><span class="'+e.oClasses.sPageJUINext+'"></span></a>';h(j).append(k);var l=h("a",j),
-k=l[0],l=l[1];e.oApi._fnBindAction(k,{action:"previous"},n);e.oApi._fnBindAction(l,{action:"next"},n);e.aanFeatures.p||(j.id=e.sTableId+"_paginate",k.id=e.sTableId+"_previous",l.id=e.sTableId+"_next",k.setAttribute("aria-controls",e.sTableId),l.setAttribute("aria-controls",e.sTableId))},fnUpdate:function(e){if(e.aanFeatures.p)for(var h=e.oClasses,j=e.aanFeatures.p,k,l=0,n=j.length;l<n;l++)if(k=j[l].firstChild)k.className=0===e._iDisplayStart?h.sPagePrevDisabled:h.sPagePrevEnabled,k=k.nextSibling,
-k.className=e.fnDisplayEnd()==e.fnRecordsDisplay()?h.sPageNextDisabled:h.sPageNextEnabled}},iFullNumbersShowPages:5,full_numbers:{fnInit:function(e,j,m){var k=e.oLanguage.oPaginate,l=e.oClasses,n=function(h){e.oApi._fnPageChange(e,h.data.action)&&m(e)};h(j).append('<a tabindex="'+e.iTabIndex+'" class="'+l.sPageButton+" "+l.sPageFirst+'">'+k.sFirst+'</a><a tabindex="'+e.iTabIndex+'" class="'+l.sPageButton+" "+l.sPagePrevious+'">'+k.sPrevious+'</a><span></span><a tabindex="'+e.iTabIndex+'" class="'+
-l.sPageButton+" "+l.sPageNext+'">'+k.sNext+'</a><a tabindex="'+e.iTabIndex+'" class="'+l.sPageButton+" "+l.sPageLast+'">'+k.sLast+"</a>");var t=h("a",j),k=t[0],l=t[1],r=t[2],t=t[3];e.oApi._fnBindAction(k,{action:"first"},n);e.oApi._fnBindAction(l,{action:"previous"},n);e.oApi._fnBindAction(r,{action:"next"},n);e.oApi._fnBindAction(t,{action:"last"},n);e.aanFeatures.p||(j.id=e.sTableId+"_paginate",k.id=e.sTableId+"_first",l.id=e.sTableId+"_previous",r.id=e.sTableId+"_next",t.id=e.sTableId+"_last")},
-fnUpdate:function(e,o){if(e.aanFeatures.p){var m=j.ext.oPagination.iFullNumbersShowPages,k=Math.floor(m/2),l=Math.ceil(e.fnRecordsDisplay()/e._iDisplayLength),n=Math.ceil(e._iDisplayStart/e._iDisplayLength)+1,t="",r,B=e.oClasses,u,M=e.aanFeatures.p,L=function(h){e.oApi._fnBindAction(this,{page:h+r-1},function(h){e.oApi._fnPageChange(e,h.data.page);o(e);h.preventDefault()})};-1===e._iDisplayLength?n=k=r=1:l<m?(r=1,k=l):n<=k?(r=1,k=m):n>=l-k?(r=l-m+1,k=l):(r=n-Math.ceil(m/2)+1,k=r+m-1);for(m=r;m<=k;m++)t+=
-n!==m?'<a tabindex="'+e.iTabIndex+'" class="'+B.sPageButton+'">'+e.fnFormatNumber(m)+"</a>":'<a tabindex="'+e.iTabIndex+'" class="'+B.sPageButtonActive+'">'+e.fnFormatNumber(m)+"</a>";m=0;for(k=M.length;m<k;m++)u=M[m],u.hasChildNodes()&&(h("span:eq(0)",u).html(t).children("a").each(L),u=u.getElementsByTagName("a"),u=[u[0],u[1],u[u.length-2],u[u.length-1]],h(u).removeClass(B.sPageButton+" "+B.sPageButtonActive+" "+B.sPageButtonStaticDisabled),h([u[0],u[1]]).addClass(1==n?B.sPageButtonStaticDisabled:
-B.sPageButton),h([u[2],u[3]]).addClass(0===l||n===l||-1===e._iDisplayLength?B.sPageButtonStaticDisabled:B.sPageButton))}}}});h.extend(j.ext.oSort,{"string-pre":function(e){"string"!=typeof e&&(e=null!==e&&e.toString?e.toString():"");return e.toLowerCase()},"string-asc":function(e,h){return e<h?-1:e>h?1:0},"string-desc":function(e,h){return e<h?1:e>h?-1:0},"html-pre":function(e){return e.replace(/<.*?>/g,"").toLowerCase()},"html-asc":function(e,h){return e<h?-1:e>h?1:0},"html-desc":function(e,h){return e<
-h?1:e>h?-1:0},"date-pre":function(e){e=Date.parse(e);if(isNaN(e)||""===e)e=Date.parse("01/01/1970 00:00:00");return e},"date-asc":function(e,h){return e-h},"date-desc":function(e,h){return h-e},"numeric-pre":function(e){return"-"==e||""===e?0:1*e},"numeric-asc":function(e,h){return e-h},"numeric-desc":function(e,h){return h-e}});h.extend(j.ext.aTypes,[function(e){if("number"===typeof e)return"numeric";if("string"!==typeof e)return null;var h,j=!1;h=e.charAt(0);if(-1=="0123456789-".indexOf(h))return null;
-for(var k=1;k<e.length;k++){h=e.charAt(k);if(-1=="0123456789.".indexOf(h))return null;if("."==h){if(j)return null;j=!0}}return"numeric"},function(e){var h=Date.parse(e);return null!==h&&!isNaN(h)||"string"===typeof e&&0===e.length?"date":null},function(e){return"string"===typeof e&&-1!=e.indexOf("<")&&-1!=e.indexOf(">")?"html":null}]);h.fn.DataTable=j;h.fn.dataTable=j;h.fn.dataTableSettings=j.settings;h.fn.dataTableExt=j.ext};"function"===typeof define&&define.amd?define(["jquery"],L):jQuery&&!jQuery.fn.dataTable&&
-L(jQuery)})(window,document);
+(function(Ea,Q,k){var P=function(h){function W(a){var b,c,e={};h.each(a,function(d){if((b=d.match(/^([^A-Z]+?)([A-Z])/))&&-1!=="a aa ai ao as b fn i m o s ".indexOf(b[1]+" "))c=d.replace(b[0],b[2].toLowerCase()),e[c]=d,"o"===b[1]&&W(a[d])});a._hungarianMap=e}function H(a,b,c){a._hungarianMap||W(a);var e;h.each(b,function(d){e=a._hungarianMap[d];if(e!==k&&(c||b[e]===k))"o"===e.charAt(0)?(b[e]||(b[e]={}),h.extend(!0,b[e],b[d]),H(a[e],b[e],c)):b[e]=b[d]})}function P(a){var b=m.defaults.oLanguage,c=a.sZeroRecords;
+!a.sEmptyTable&&(c&&"No data available in table"===b.sEmptyTable)&&E(a,a,"sZeroRecords","sEmptyTable");!a.sLoadingRecords&&(c&&"Loading..."===b.sLoadingRecords)&&E(a,a,"sZeroRecords","sLoadingRecords");a.sInfoThousands&&(a.sThousands=a.sInfoThousands);(a=a.sDecimal)&&db(a)}function eb(a){A(a,"ordering","bSort");A(a,"orderMulti","bSortMulti");A(a,"orderClasses","bSortClasses");A(a,"orderCellsTop","bSortCellsTop");A(a,"order","aaSorting");A(a,"orderFixed","aaSortingFixed");A(a,"paging","bPaginate");
+A(a,"pagingType","sPaginationType");A(a,"pageLength","iDisplayLength");A(a,"searching","bFilter");if(a=a.aoSearchCols)for(var b=0,c=a.length;b<c;b++)a[b]&&H(m.models.oSearch,a[b])}function fb(a){A(a,"orderable","bSortable");A(a,"orderData","aDataSort");A(a,"orderSequence","asSorting");A(a,"orderDataType","sortDataType");var b=a.aDataSort;b&&!h.isArray(b)&&(a.aDataSort=[b])}function gb(a){var a=a.oBrowser,b=h("<div/>").css({position:"absolute",top:0,left:0,height:1,width:1,overflow:"hidden"}).append(h("<div/>").css({position:"absolute",
+top:1,left:1,width:100,overflow:"scroll"}).append(h('<div class="test"/>').css({width:"100%",height:10}))).appendTo("body"),c=b.find(".test");a.bScrollOversize=100===c[0].offsetWidth;a.bScrollbarLeft=1!==Math.round(c.offset().left);b.remove()}function hb(a,b,c,e,d,f){var g,j=!1;c!==k&&(g=c,j=!0);for(;e!==d;)a.hasOwnProperty(e)&&(g=j?b(g,a[e],e,a):a[e],j=!0,e+=f);return g}function Fa(a,b){var c=m.defaults.column,e=a.aoColumns.length,c=h.extend({},m.models.oColumn,c,{nTh:b?b:Q.createElement("th"),sTitle:c.sTitle?
+c.sTitle:b?b.innerHTML:"",aDataSort:c.aDataSort?c.aDataSort:[e],mData:c.mData?c.mData:e,idx:e});a.aoColumns.push(c);c=a.aoPreSearchCols;c[e]=h.extend({},m.models.oSearch,c[e]);ka(a,e,h(b).data())}function ka(a,b,c){var b=a.aoColumns[b],e=a.oClasses,d=h(b.nTh);if(!b.sWidthOrig){b.sWidthOrig=d.attr("width")||null;var f=(d.attr("style")||"").match(/width:\s*(\d+[pxem%]+)/);f&&(b.sWidthOrig=f[1])}c!==k&&null!==c&&(fb(c),H(m.defaults.column,c),c.mDataProp!==k&&!c.mData&&(c.mData=c.mDataProp),c.sType&&
+(b._sManualType=c.sType),c.className&&!c.sClass&&(c.sClass=c.className),h.extend(b,c),E(b,c,"sWidth","sWidthOrig"),c.iDataSort!==k&&(b.aDataSort=[c.iDataSort]),E(b,c,"aDataSort"));var g=b.mData,j=R(g),i=b.mRender?R(b.mRender):null,c=function(a){return"string"===typeof a&&-1!==a.indexOf("@")};b._bAttrSrc=h.isPlainObject(g)&&(c(g.sort)||c(g.type)||c(g.filter));b.fnGetData=function(a,b,c){var e=j(a,b,k,c);return i&&b?i(e,b,a,c):e};b.fnSetData=function(a,b,c){return S(g)(a,b,c)};"number"!==typeof g&&
+(a._rowReadObject=!0);a.oFeatures.bSort||(b.bSortable=!1,d.addClass(e.sSortableNone));a=-1!==h.inArray("asc",b.asSorting);c=-1!==h.inArray("desc",b.asSorting);!b.bSortable||!a&&!c?(b.sSortingClass=e.sSortableNone,b.sSortingClassJUI=""):a&&!c?(b.sSortingClass=e.sSortableAsc,b.sSortingClassJUI=e.sSortJUIAscAllowed):!a&&c?(b.sSortingClass=e.sSortableDesc,b.sSortingClassJUI=e.sSortJUIDescAllowed):(b.sSortingClass=e.sSortable,b.sSortingClassJUI=e.sSortJUI)}function X(a){if(!1!==a.oFeatures.bAutoWidth){var b=
+a.aoColumns;Ga(a);for(var c=0,e=b.length;c<e;c++)b[c].nTh.style.width=b[c].sWidth}b=a.oScroll;(""!==b.sY||""!==b.sX)&&Y(a);w(a,null,"column-sizing",[a])}function la(a,b){var c=Z(a,"bVisible");return"number"===typeof c[b]?c[b]:null}function $(a,b){var c=Z(a,"bVisible"),c=h.inArray(b,c);return-1!==c?c:null}function aa(a){return Z(a,"bVisible").length}function Z(a,b){var c=[];h.map(a.aoColumns,function(a,d){a[b]&&c.push(d)});return c}function Ha(a){var b=a.aoColumns,c=a.aoData,e=m.ext.type.detect,d,
+f,g,j,i,h,l,q,n;d=0;for(f=b.length;d<f;d++)if(l=b[d],n=[],!l.sType&&l._sManualType)l.sType=l._sManualType;else if(!l.sType){g=0;for(j=e.length;g<j;g++){i=0;for(h=c.length;i<h;i++){n[i]===k&&(n[i]=x(a,i,d,"type"));q=e[g](n[i],a);if(!q&&g!==e.length-1)break;if("html"===q)break}if(q){l.sType=q;break}}l.sType||(l.sType="string")}}function ib(a,b,c,e){var d,f,g,j,i,o,l=a.aoColumns;if(b)for(d=b.length-1;0<=d;d--){o=b[d];var q=o.targets!==k?o.targets:o.aTargets;h.isArray(q)||(q=[q]);f=0;for(g=q.length;f<
+g;f++)if("number"===typeof q[f]&&0<=q[f]){for(;l.length<=q[f];)Fa(a);e(q[f],o)}else if("number"===typeof q[f]&&0>q[f])e(l.length+q[f],o);else if("string"===typeof q[f]){j=0;for(i=l.length;j<i;j++)("_all"==q[f]||h(l[j].nTh).hasClass(q[f]))&&e(j,o)}}if(c){d=0;for(a=c.length;d<a;d++)e(d,c[d])}}function K(a,b,c,e){var d=a.aoData.length,f=h.extend(!0,{},m.models.oRow,{src:c?"dom":"data"});f._aData=b;a.aoData.push(f);for(var b=a.aoColumns,f=0,g=b.length;f<g;f++)c&&Ia(a,d,f,x(a,d,f)),b[f].sType=null;a.aiDisplayMaster.push(d);
+(c||!a.oFeatures.bDeferRender)&&Ja(a,d,c,e);return d}function ma(a,b){var c;b instanceof h||(b=h(b));return b.map(function(b,d){c=na(a,d);return K(a,c.data,d,c.cells)})}function x(a,b,c,e){var d=a.iDraw,f=a.aoColumns[c],g=a.aoData[b]._aData,j=f.sDefaultContent,c=f.fnGetData(g,e,{settings:a,row:b,col:c});if(c===k)return a.iDrawError!=d&&null===j&&(I(a,0,"Requested unknown parameter "+("function"==typeof f.mData?"{function}":"'"+f.mData+"'")+" for row "+b,4),a.iDrawError=d),j;if((c===g||null===c)&&
+null!==j)c=j;else if("function"===typeof c)return c.call(g);return null===c&&"display"==e?"":c}function Ia(a,b,c,e){a.aoColumns[c].fnSetData(a.aoData[b]._aData,e,{settings:a,row:b,col:c})}function Ka(a){return h.map(a.match(/(\\.|[^\.])+/g),function(a){return a.replace(/\\./g,".")})}function R(a){if(h.isPlainObject(a)){var b={};h.each(a,function(a,c){c&&(b[a]=R(c))});return function(a,c,f,g){var j=b[c]||b._;return j!==k?j(a,c,f,g):a}}if(null===a)return function(a){return a};if("function"===typeof a)return function(b,
+c,f,g){return a(b,c,f,g)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var c=function(a,b,f){var g,j;if(""!==f){j=Ka(f);for(var i=0,h=j.length;i<h;i++){f=j[i].match(ba);g=j[i].match(T);if(f){j[i]=j[i].replace(ba,"");""!==j[i]&&(a=a[j[i]]);g=[];j.splice(0,i+1);j=j.join(".");i=0;for(h=a.length;i<h;i++)g.push(c(a[i],b,j));a=f[0].substring(1,f[0].length-1);a=""===a?g:g.join(a);break}else if(g){j[i]=j[i].replace(T,"");a=a[j[i]]();continue}if(null===a||a[j[i]]===
+k)return k;a=a[j[i]]}}return a};return function(b,d){return c(b,d,a)}}return function(b){return b[a]}}function S(a){if(h.isPlainObject(a))return S(a._);if(null===a)return function(){};if("function"===typeof a)return function(b,e,d){a(b,"set",e,d)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var b=function(a,e,d){var d=Ka(d),f;f=d[d.length-1];for(var g,j,i=0,h=d.length-1;i<h;i++){g=d[i].match(ba);j=d[i].match(T);if(g){d[i]=d[i].replace(ba,"");a[d[i]]=[];
+f=d.slice();f.splice(0,i+1);g=f.join(".");j=0;for(h=e.length;j<h;j++)f={},b(f,e[j],g),a[d[i]].push(f);return}j&&(d[i]=d[i].replace(T,""),a=a[d[i]](e));if(null===a[d[i]]||a[d[i]]===k)a[d[i]]={};a=a[d[i]]}if(f.match(T))a[f.replace(T,"")](e);else a[f.replace(ba,"")]=e};return function(c,e){return b(c,e,a)}}return function(b,e){b[a]=e}}function La(a){return D(a.aoData,"_aData")}function oa(a){a.aoData.length=0;a.aiDisplayMaster.length=0;a.aiDisplay.length=0}function pa(a,b,c){for(var e=-1,d=0,f=a.length;d<
+f;d++)a[d]==b?e=d:a[d]>b&&a[d]--; -1!=e&&c===k&&a.splice(e,1)}function ca(a,b,c,e){var d=a.aoData[b],f,g=function(c,f){for(;c.childNodes.length;)c.removeChild(c.firstChild);c.innerHTML=x(a,b,f,"display")};if("dom"===c||(!c||"auto"===c)&&"dom"===d.src)d._aData=na(a,d,e,e===k?k:d._aData).data;else{var j=d.anCells;if(j)if(e!==k)g(j[e],e);else{c=0;for(f=j.length;c<f;c++)g(j[c],c)}}d._aSortData=null;d._aFilterData=null;g=a.aoColumns;if(e!==k)g[e].sType=null;else{c=0;for(f=g.length;c<f;c++)g[c].sType=null;
+Ma(d)}}function na(a,b,c,e){var d=[],f=b.firstChild,g,j=0,i,o=a.aoColumns,l=a._rowReadObject,e=e||l?{}:[],q=function(a,b){if("string"===typeof a){var c=a.indexOf("@");-1!==c&&(c=a.substring(c+1),S(a)(e,b.getAttribute(c)))}},a=function(a){if(c===k||c===j)g=o[j],i=h.trim(a.innerHTML),g&&g._bAttrSrc?(S(g.mData._)(e,i),q(g.mData.sort,a),q(g.mData.type,a),q(g.mData.filter,a)):l?(g._setter||(g._setter=S(g.mData)),g._setter(e,i)):e[j]=i;j++};if(f)for(;f;){b=f.nodeName.toUpperCase();if("TD"==b||"TH"==b)a(f),
+d.push(f);f=f.nextSibling}else{d=b.anCells;f=0;for(b=d.length;f<b;f++)a(d[f])}return{data:e,cells:d}}function Ja(a,b,c,e){var d=a.aoData[b],f=d._aData,g=[],j,i,h,l,q;if(null===d.nTr){j=c||Q.createElement("tr");d.nTr=j;d.anCells=g;j._DT_RowIndex=b;Ma(d);l=0;for(q=a.aoColumns.length;l<q;l++){h=a.aoColumns[l];i=c?e[l]:Q.createElement(h.sCellType);g.push(i);if(!c||h.mRender||h.mData!==l)i.innerHTML=x(a,b,l,"display");h.sClass&&(i.className+=" "+h.sClass);h.bVisible&&!c?j.appendChild(i):!h.bVisible&&c&&
+i.parentNode.removeChild(i);h.fnCreatedCell&&h.fnCreatedCell.call(a.oInstance,i,x(a,b,l),f,b,l)}w(a,"aoRowCreatedCallback",null,[j,f,b])}d.nTr.setAttribute("role","row")}function Ma(a){var b=a.nTr,c=a._aData;if(b){c.DT_RowId&&(b.id=c.DT_RowId);if(c.DT_RowClass){var e=c.DT_RowClass.split(" ");a.__rowc=a.__rowc?Na(a.__rowc.concat(e)):e;h(b).removeClass(a.__rowc.join(" ")).addClass(c.DT_RowClass)}c.DT_RowAttr&&h(b).attr(c.DT_RowAttr);c.DT_RowData&&h(b).data(c.DT_RowData)}}function jb(a){var b,c,e,d,
+f,g=a.nTHead,j=a.nTFoot,i=0===h("th, td",g).length,o=a.oClasses,l=a.aoColumns;i&&(d=h("<tr/>").appendTo(g));b=0;for(c=l.length;b<c;b++)f=l[b],e=h(f.nTh).addClass(f.sClass),i&&e.appendTo(d),a.oFeatures.bSort&&(e.addClass(f.sSortingClass),!1!==f.bSortable&&(e.attr("tabindex",a.iTabIndex).attr("aria-controls",a.sTableId),Oa(a,f.nTh,b))),f.sTitle!=e.html()&&e.html(f.sTitle),Pa(a,"header")(a,e,f,o);i&&da(a.aoHeader,g);h(g).find(">tr").attr("role","row");h(g).find(">tr>th, >tr>td").addClass(o.sHeaderTH);
+h(j).find(">tr>th, >tr>td").addClass(o.sFooterTH);if(null!==j){a=a.aoFooter[0];b=0;for(c=a.length;b<c;b++)f=l[b],f.nTf=a[b].cell,f.sClass&&h(f.nTf).addClass(f.sClass)}}function ea(a,b,c){var e,d,f,g=[],j=[],i=a.aoColumns.length,o;if(b){c===k&&(c=!1);e=0;for(d=b.length;e<d;e++){g[e]=b[e].slice();g[e].nTr=b[e].nTr;for(f=i-1;0<=f;f--)!a.aoColumns[f].bVisible&&!c&&g[e].splice(f,1);j.push([])}e=0;for(d=g.length;e<d;e++){if(a=g[e].nTr)for(;f=a.firstChild;)a.removeChild(f);f=0;for(b=g[e].length;f<b;f++)if(o=
+i=1,j[e][f]===k){a.appendChild(g[e][f].cell);for(j[e][f]=1;g[e+i]!==k&&g[e][f].cell==g[e+i][f].cell;)j[e+i][f]=1,i++;for(;g[e][f+o]!==k&&g[e][f].cell==g[e][f+o].cell;){for(c=0;c<i;c++)j[e+c][f+o]=1;o++}h(g[e][f].cell).attr("rowspan",i).attr("colspan",o)}}}}function M(a){var b=w(a,"aoPreDrawCallback","preDraw",[a]);if(-1!==h.inArray(!1,b))C(a,!1);else{var b=[],c=0,e=a.asStripeClasses,d=e.length,f=a.oLanguage,g=a.iInitDisplayStart,j="ssp"==B(a),i=a.aiDisplay;a.bDrawing=!0;g!==k&&-1!==g&&(a._iDisplayStart=
+j?g:g>=a.fnRecordsDisplay()?0:g,a.iInitDisplayStart=-1);var g=a._iDisplayStart,o=a.fnDisplayEnd();if(a.bDeferLoading)a.bDeferLoading=!1,a.iDraw++,C(a,!1);else if(j){if(!a.bDestroying&&!kb(a))return}else a.iDraw++;if(0!==i.length){f=j?a.aoData.length:o;for(j=j?0:g;j<f;j++){var l=i[j],q=a.aoData[l];null===q.nTr&&Ja(a,l);l=q.nTr;if(0!==d){var n=e[c%d];q._sRowStripe!=n&&(h(l).removeClass(q._sRowStripe).addClass(n),q._sRowStripe=n)}w(a,"aoRowCallback",null,[l,q._aData,c,j]);b.push(l);c++}}else c=f.sZeroRecords,
+1==a.iDraw&&"ajax"==B(a)?c=f.sLoadingRecords:f.sEmptyTable&&0===a.fnRecordsTotal()&&(c=f.sEmptyTable),b[0]=h("<tr/>",{"class":d?e[0]:""}).append(h("<td />",{valign:"top",colSpan:aa(a),"class":a.oClasses.sRowEmpty}).html(c))[0];w(a,"aoHeaderCallback","header",[h(a.nTHead).children("tr")[0],La(a),g,o,i]);w(a,"aoFooterCallback","footer",[h(a.nTFoot).children("tr")[0],La(a),g,o,i]);e=h(a.nTBody);e.children().detach();e.append(h(b));w(a,"aoDrawCallback","draw",[a]);a.bSorted=!1;a.bFiltered=!1;a.bDrawing=
+!1}}function N(a,b){var c=a.oFeatures,e=c.bFilter;c.bSort&&lb(a);e?fa(a,a.oPreviousSearch):a.aiDisplay=a.aiDisplayMaster.slice();!0!==b&&(a._iDisplayStart=0);a._drawHold=b;M(a);a._drawHold=!1}function mb(a){var b=a.oClasses,c=h(a.nTable),c=h("<div/>").insertBefore(c),e=a.oFeatures,d=h("<div/>",{id:a.sTableId+"_wrapper","class":b.sWrapper+(a.nTFoot?"":" "+b.sNoFooter)});a.nHolding=c[0];a.nTableWrapper=d[0];a.nTableReinsertBefore=a.nTable.nextSibling;for(var f=a.sDom.split(""),g,j,i,o,l,q,n=0;n<f.length;n++){g=
+null;j=f[n];if("<"==j){i=h("<div/>")[0];o=f[n+1];if("'"==o||'"'==o){l="";for(q=2;f[n+q]!=o;)l+=f[n+q],q++;"H"==l?l=b.sJUIHeader:"F"==l&&(l=b.sJUIFooter);-1!=l.indexOf(".")?(o=l.split("."),i.id=o[0].substr(1,o[0].length-1),i.className=o[1]):"#"==l.charAt(0)?i.id=l.substr(1,l.length-1):i.className=l;n+=q}d.append(i);d=h(i)}else if(">"==j)d=d.parent();else if("l"==j&&e.bPaginate&&e.bLengthChange)g=nb(a);else if("f"==j&&e.bFilter)g=ob(a);else if("r"==j&&e.bProcessing)g=pb(a);else if("t"==j)g=qb(a);else if("i"==
+j&&e.bInfo)g=rb(a);else if("p"==j&&e.bPaginate)g=sb(a);else if(0!==m.ext.feature.length){i=m.ext.feature;q=0;for(o=i.length;q<o;q++)if(j==i[q].cFeature){g=i[q].fnInit(a);break}}g&&(i=a.aanFeatures,i[j]||(i[j]=[]),i[j].push(g),d.append(g))}c.replaceWith(d)}function da(a,b){var c=h(b).children("tr"),e,d,f,g,j,i,o,l,q,n;a.splice(0,a.length);f=0;for(i=c.length;f<i;f++)a.push([]);f=0;for(i=c.length;f<i;f++){e=c[f];for(d=e.firstChild;d;){if("TD"==d.nodeName.toUpperCase()||"TH"==d.nodeName.toUpperCase()){l=
+1*d.getAttribute("colspan");q=1*d.getAttribute("rowspan");l=!l||0===l||1===l?1:l;q=!q||0===q||1===q?1:q;g=0;for(j=a[f];j[g];)g++;o=g;n=1===l?!0:!1;for(j=0;j<l;j++)for(g=0;g<q;g++)a[f+g][o+j]={cell:d,unique:n},a[f+g].nTr=e}d=d.nextSibling}}}function qa(a,b,c){var e=[];c||(c=a.aoHeader,b&&(c=[],da(c,b)));for(var b=0,d=c.length;b<d;b++)for(var f=0,g=c[b].length;f<g;f++)if(c[b][f].unique&&(!e[f]||!a.bSortCellsTop))e[f]=c[b][f].cell;return e}function ra(a,b,c){w(a,"aoServerParams","serverParams",[b]);
+if(b&&h.isArray(b)){var e={},d=/(.*?)\[\]$/;h.each(b,function(a,b){var c=b.name.match(d);c?(c=c[0],e[c]||(e[c]=[]),e[c].push(b.value)):e[b.name]=b.value});b=e}var f,g=a.ajax,j=a.oInstance,i=function(b){w(a,null,"xhr",[a,b,a.jqXHR]);c(b)};if(h.isPlainObject(g)&&g.data){f=g.data;var o=h.isFunction(f)?f(b,a):f,b=h.isFunction(f)&&o?o:h.extend(!0,b,o);delete g.data}o={data:b,success:function(b){var c=b.error||b.sError;c&&I(a,0,c);a.json=b;i(b)},dataType:"json",cache:!1,type:a.sServerMethod,error:function(b,
+c){var f=w(a,null,"xhr",[a,null,a.jqXHR]);-1===h.inArray(!0,f)&&("parsererror"==c?I(a,0,"Invalid JSON response",1):4===b.readyState&&I(a,0,"Ajax error",7));C(a,!1)}};a.oAjaxData=b;w(a,null,"preXhr",[a,b]);a.fnServerData?a.fnServerData.call(j,a.sAjaxSource,h.map(b,function(a,b){return{name:b,value:a}}),i,a):a.sAjaxSource||"string"===typeof g?a.jqXHR=h.ajax(h.extend(o,{url:g||a.sAjaxSource})):h.isFunction(g)?a.jqXHR=g.call(j,b,i,a):(a.jqXHR=h.ajax(h.extend(o,g)),g.data=f)}function kb(a){return a.bAjaxDataGet?
+(a.iDraw++,C(a,!0),ra(a,tb(a),function(b){ub(a,b)}),!1):!0}function tb(a){var b=a.aoColumns,c=b.length,e=a.oFeatures,d=a.oPreviousSearch,f=a.aoPreSearchCols,g,j=[],i,o,l,q=U(a);g=a._iDisplayStart;i=!1!==e.bPaginate?a._iDisplayLength:-1;var n=function(a,b){j.push({name:a,value:b})};n("sEcho",a.iDraw);n("iColumns",c);n("sColumns",D(b,"sName").join(","));n("iDisplayStart",g);n("iDisplayLength",i);var k={draw:a.iDraw,columns:[],order:[],start:g,length:i,search:{value:d.sSearch,regex:d.bRegex}};for(g=
+0;g<c;g++)o=b[g],l=f[g],i="function"==typeof o.mData?"function":o.mData,k.columns.push({data:i,name:o.sName,searchable:o.bSearchable,orderable:o.bSortable,search:{value:l.sSearch,regex:l.bRegex}}),n("mDataProp_"+g,i),e.bFilter&&(n("sSearch_"+g,l.sSearch),n("bRegex_"+g,l.bRegex),n("bSearchable_"+g,o.bSearchable)),e.bSort&&n("bSortable_"+g,o.bSortable);e.bFilter&&(n("sSearch",d.sSearch),n("bRegex",d.bRegex));e.bSort&&(h.each(q,function(a,b){k.order.push({column:b.col,dir:b.dir});n("iSortCol_"+a,b.col);
+n("sSortDir_"+a,b.dir)}),n("iSortingCols",q.length));b=m.ext.legacy.ajax;return null===b?a.sAjaxSource?j:k:b?j:k}function ub(a,b){var c=sa(a,b),e=b.sEcho!==k?b.sEcho:b.draw,d=b.iTotalRecords!==k?b.iTotalRecords:b.recordsTotal,f=b.iTotalDisplayRecords!==k?b.iTotalDisplayRecords:b.recordsFiltered;if(e){if(1*e<a.iDraw)return;a.iDraw=1*e}oa(a);a._iRecordsTotal=parseInt(d,10);a._iRecordsDisplay=parseInt(f,10);e=0;for(d=c.length;e<d;e++)K(a,c[e]);a.aiDisplay=a.aiDisplayMaster.slice();a.bAjaxDataGet=!1;
+M(a);a._bInitComplete||ta(a,b);a.bAjaxDataGet=!0;C(a,!1)}function sa(a,b){var c=h.isPlainObject(a.ajax)&&a.ajax.dataSrc!==k?a.ajax.dataSrc:a.sAjaxDataProp;return"data"===c?b.aaData||b[c]:""!==c?R(c)(b):b}function ob(a){var b=a.oClasses,c=a.sTableId,e=a.oLanguage,d=a.oPreviousSearch,f=a.aanFeatures,g='<input type="search" class="'+b.sFilterInput+'"/>',j=e.sSearch,j=j.match(/_INPUT_/)?j.replace("_INPUT_",g):j+g,b=h("<div/>",{id:!f.f?c+"_filter":null,"class":b.sFilter}).append(h("<label/>").append(j)),
+f=function(){var b=!this.value?"":this.value;b!=d.sSearch&&(fa(a,{sSearch:b,bRegex:d.bRegex,bSmart:d.bSmart,bCaseInsensitive:d.bCaseInsensitive}),a._iDisplayStart=0,M(a))},g=null!==a.searchDelay?a.searchDelay:"ssp"===B(a)?400:0,i=h("input",b).val(d.sSearch).attr("placeholder",e.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT",g?ua(f,g):f).bind("keypress.DT",function(a){if(13==a.keyCode)return!1}).attr("aria-controls",c);h(a.nTable).on("search.dt.DT",function(b,c){if(a===c)try{i[0]!==
+Q.activeElement&&i.val(d.sSearch)}catch(f){}});return b[0]}function fa(a,b,c){var e=a.oPreviousSearch,d=a.aoPreSearchCols,f=function(a){e.sSearch=a.sSearch;e.bRegex=a.bRegex;e.bSmart=a.bSmart;e.bCaseInsensitive=a.bCaseInsensitive};Ha(a);if("ssp"!=B(a)){vb(a,b.sSearch,c,b.bEscapeRegex!==k?!b.bEscapeRegex:b.bRegex,b.bSmart,b.bCaseInsensitive);f(b);for(b=0;b<d.length;b++)wb(a,d[b].sSearch,b,d[b].bEscapeRegex!==k?!d[b].bEscapeRegex:d[b].bRegex,d[b].bSmart,d[b].bCaseInsensitive);xb(a)}else f(b);a.bFiltered=
+!0;w(a,null,"search",[a])}function xb(a){for(var b=m.ext.search,c=a.aiDisplay,e,d,f=0,g=b.length;f<g;f++){for(var j=[],i=0,h=c.length;i<h;i++)d=c[i],e=a.aoData[d],b[f](a,e._aFilterData,d,e._aData,i)&&j.push(d);c.length=0;c.push.apply(c,j)}}function wb(a,b,c,e,d,f){if(""!==b)for(var g=a.aiDisplay,e=Qa(b,e,d,f),d=g.length-1;0<=d;d--)b=a.aoData[g[d]]._aFilterData[c],e.test(b)||g.splice(d,1)}function vb(a,b,c,e,d,f){var e=Qa(b,e,d,f),d=a.oPreviousSearch.sSearch,f=a.aiDisplayMaster,g;0!==m.ext.search.length&&
+(c=!0);g=yb(a);if(0>=b.length)a.aiDisplay=f.slice();else{if(g||c||d.length>b.length||0!==b.indexOf(d)||a.bSorted)a.aiDisplay=f.slice();b=a.aiDisplay;for(c=b.length-1;0<=c;c--)e.test(a.aoData[b[c]]._sFilterRow)||b.splice(c,1)}}function Qa(a,b,c,e){a=b?a:va(a);c&&(a="^(?=.*?"+h.map(a.match(/"[^"]+"|[^ ]+/g)||[""],function(a){if('"'===a.charAt(0))var b=a.match(/^"(.*)"$/),a=b?b[1]:a;return a.replace('"',"")}).join(")(?=.*?")+").*$");return RegExp(a,e?"i":"")}function va(a){return a.replace(Yb,"\\$1")}
+function yb(a){var b=a.aoColumns,c,e,d,f,g,j,i,h,l=m.ext.type.search;c=!1;e=0;for(f=a.aoData.length;e<f;e++)if(h=a.aoData[e],!h._aFilterData){j=[];d=0;for(g=b.length;d<g;d++)c=b[d],c.bSearchable?(i=x(a,e,d,"filter"),l[c.sType]&&(i=l[c.sType](i)),null===i&&(i=""),"string"!==typeof i&&i.toString&&(i=i.toString())):i="",i.indexOf&&-1!==i.indexOf("&")&&(wa.innerHTML=i,i=Zb?wa.textContent:wa.innerText),i.replace&&(i=i.replace(/[\r\n]/g,"")),j.push(i);h._aFilterData=j;h._sFilterRow=j.join(" ");c=!0}return c}
+function zb(a){return{search:a.sSearch,smart:a.bSmart,regex:a.bRegex,caseInsensitive:a.bCaseInsensitive}}function Ab(a){return{sSearch:a.search,bSmart:a.smart,bRegex:a.regex,bCaseInsensitive:a.caseInsensitive}}function rb(a){var b=a.sTableId,c=a.aanFeatures.i,e=h("<div/>",{"class":a.oClasses.sInfo,id:!c?b+"_info":null});c||(a.aoDrawCallback.push({fn:Bb,sName:"information"}),e.attr("role","status").attr("aria-live","polite"),h(a.nTable).attr("aria-describedby",b+"_info"));return e[0]}function Bb(a){var b=
+a.aanFeatures.i;if(0!==b.length){var c=a.oLanguage,e=a._iDisplayStart+1,d=a.fnDisplayEnd(),f=a.fnRecordsTotal(),g=a.fnRecordsDisplay(),j=g?c.sInfo:c.sInfoEmpty;g!==f&&(j+=" "+c.sInfoFiltered);j+=c.sInfoPostFix;j=Cb(a,j);c=c.fnInfoCallback;null!==c&&(j=c.call(a.oInstance,a,e,d,f,g,j));h(b).html(j)}}function Cb(a,b){var c=a.fnFormatNumber,e=a._iDisplayStart+1,d=a._iDisplayLength,f=a.fnRecordsDisplay(),g=-1===d;return b.replace(/_START_/g,c.call(a,e)).replace(/_END_/g,c.call(a,a.fnDisplayEnd())).replace(/_MAX_/g,
+c.call(a,a.fnRecordsTotal())).replace(/_TOTAL_/g,c.call(a,f)).replace(/_PAGE_/g,c.call(a,g?1:Math.ceil(e/d))).replace(/_PAGES_/g,c.call(a,g?1:Math.ceil(f/d)))}function ga(a){var b,c,e=a.iInitDisplayStart,d=a.aoColumns,f;c=a.oFeatures;if(a.bInitialised){mb(a);jb(a);ea(a,a.aoHeader);ea(a,a.aoFooter);C(a,!0);c.bAutoWidth&&Ga(a);b=0;for(c=d.length;b<c;b++)f=d[b],f.sWidth&&(f.nTh.style.width=s(f.sWidth));N(a);d=B(a);"ssp"!=d&&("ajax"==d?ra(a,[],function(c){var f=sa(a,c);for(b=0;b<f.length;b++)K(a,f[b]);
+a.iInitDisplayStart=e;N(a);C(a,!1);ta(a,c)},a):(C(a,!1),ta(a)))}else setTimeout(function(){ga(a)},200)}function ta(a,b){a._bInitComplete=!0;b&&X(a);w(a,"aoInitComplete","init",[a,b])}function Ra(a,b){var c=parseInt(b,10);a._iDisplayLength=c;Sa(a);w(a,null,"length",[a,c])}function nb(a){for(var b=a.oClasses,c=a.sTableId,e=a.aLengthMenu,d=h.isArray(e[0]),f=d?e[0]:e,e=d?e[1]:e,d=h("<select/>",{name:c+"_length","aria-controls":c,"class":b.sLengthSelect}),g=0,j=f.length;g<j;g++)d[0][g]=new Option(e[g],
+f[g]);var i=h("<div><label/></div>").addClass(b.sLength);a.aanFeatures.l||(i[0].id=c+"_length");i.children().append(a.oLanguage.sLengthMenu.replace("_MENU_",d[0].outerHTML));h("select",i).val(a._iDisplayLength).bind("change.DT",function(){Ra(a,h(this).val());M(a)});h(a.nTable).bind("length.dt.DT",function(b,c,f){a===c&&h("select",i).val(f)});return i[0]}function sb(a){var b=a.sPaginationType,c=m.ext.pager[b],e="function"===typeof c,d=function(a){M(a)},b=h("<div/>").addClass(a.oClasses.sPaging+b)[0],
+f=a.aanFeatures;e||c.fnInit(a,b,d);f.p||(b.id=a.sTableId+"_paginate",a.aoDrawCallback.push({fn:function(a){if(e){var b=a._iDisplayStart,i=a._iDisplayLength,h=a.fnRecordsDisplay(),l=-1===i,b=l?0:Math.ceil(b/i),i=l?1:Math.ceil(h/i),h=c(b,i),q,l=0;for(q=f.p.length;l<q;l++)Pa(a,"pageButton")(a,f.p[l],l,h,b,i)}else c.fnUpdate(a,d)},sName:"pagination"}));return b}function Ta(a,b,c){var e=a._iDisplayStart,d=a._iDisplayLength,f=a.fnRecordsDisplay();0===f||-1===d?e=0:"number"===typeof b?(e=b*d,e>f&&(e=0)):
+"first"==b?e=0:"previous"==b?(e=0<=d?e-d:0,0>e&&(e=0)):"next"==b?e+d<f&&(e+=d):"last"==b?e=Math.floor((f-1)/d)*d:I(a,0,"Unknown paging action: "+b,5);b=a._iDisplayStart!==e;a._iDisplayStart=e;b&&(w(a,null,"page",[a]),c&&M(a));return b}function pb(a){return h("<div/>",{id:!a.aanFeatures.r?a.sTableId+"_processing":null,"class":a.oClasses.sProcessing}).html(a.oLanguage.sProcessing).insertBefore(a.nTable)[0]}function C(a,b){a.oFeatures.bProcessing&&h(a.aanFeatures.r).css("display",b?"block":"none");w(a,
+null,"processing",[a,b])}function qb(a){var b=h(a.nTable);b.attr("role","grid");var c=a.oScroll;if(""===c.sX&&""===c.sY)return a.nTable;var e=c.sX,d=c.sY,f=a.oClasses,g=b.children("caption"),j=g.length?g[0]._captionSide:null,i=h(b[0].cloneNode(!1)),o=h(b[0].cloneNode(!1)),l=b.children("tfoot");c.sX&&"100%"===b.attr("width")&&b.removeAttr("width");l.length||(l=null);c=h("<div/>",{"class":f.sScrollWrapper}).append(h("<div/>",{"class":f.sScrollHead}).css({overflow:"hidden",position:"relative",border:0,
+width:e?!e?null:s(e):"100%"}).append(h("<div/>",{"class":f.sScrollHeadInner}).css({"box-sizing":"content-box",width:c.sXInner||"100%"}).append(i.removeAttr("id").css("margin-left",0).append("top"===j?g:null).append(b.children("thead"))))).append(h("<div/>",{"class":f.sScrollBody}).css({overflow:"auto",height:!d?null:s(d),width:!e?null:s(e)}).append(b));l&&c.append(h("<div/>",{"class":f.sScrollFoot}).css({overflow:"hidden",border:0,width:e?!e?null:s(e):"100%"}).append(h("<div/>",{"class":f.sScrollFootInner}).append(o.removeAttr("id").css("margin-left",
+0).append("bottom"===j?g:null).append(b.children("tfoot")))));var b=c.children(),q=b[0],f=b[1],n=l?b[2]:null;if(e)h(f).on("scroll.DT",function(){var a=this.scrollLeft;q.scrollLeft=a;l&&(n.scrollLeft=a)});a.nScrollHead=q;a.nScrollBody=f;a.nScrollFoot=n;a.aoDrawCallback.push({fn:Y,sName:"scrolling"});return c[0]}function Y(a){var b=a.oScroll,c=b.sX,e=b.sXInner,d=b.sY,f=b.iBarWidth,g=h(a.nScrollHead),j=g[0].style,i=g.children("div"),o=i[0].style,l=i.children("table"),i=a.nScrollBody,q=h(i),n=i.style,
+k=h(a.nScrollFoot).children("div"),p=k.children("table"),m=h(a.nTHead),r=h(a.nTable),t=r[0],O=t.style,L=a.nTFoot?h(a.nTFoot):null,ha=a.oBrowser,w=ha.bScrollOversize,v,u,y,x,z,A=[],B=[],C=[],D,E=function(a){a=a.style;a.paddingTop="0";a.paddingBottom="0";a.borderTopWidth="0";a.borderBottomWidth="0";a.height=0};r.children("thead, tfoot").remove();z=m.clone().prependTo(r);v=m.find("tr");y=z.find("tr");z.find("th, td").removeAttr("tabindex");L&&(x=L.clone().prependTo(r),u=L.find("tr"),x=x.find("tr"));
+c||(n.width="100%",g[0].style.width="100%");h.each(qa(a,z),function(b,c){D=la(a,b);c.style.width=a.aoColumns[D].sWidth});L&&G(function(a){a.style.width=""},x);b.bCollapse&&""!==d&&(n.height=q[0].offsetHeight+m[0].offsetHeight+"px");g=r.outerWidth();if(""===c){if(O.width="100%",w&&(r.find("tbody").height()>i.offsetHeight||"scroll"==q.css("overflow-y")))O.width=s(r.outerWidth()-f)}else""!==e?O.width=s(e):g==q.width()&&q.height()<r.height()?(O.width=s(g-f),r.outerWidth()>g-f&&(O.width=s(g))):O.width=
+s(g);g=r.outerWidth();G(E,y);G(function(a){C.push(a.innerHTML);A.push(s(h(a).css("width")))},y);G(function(a,b){a.style.width=A[b]},v);h(y).height(0);L&&(G(E,x),G(function(a){B.push(s(h(a).css("width")))},x),G(function(a,b){a.style.width=B[b]},u),h(x).height(0));G(function(a,b){a.innerHTML='<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+C[b]+"</div>";a.style.width=A[b]},y);L&&G(function(a,b){a.innerHTML="";a.style.width=B[b]},x);if(r.outerWidth()<g){u=i.scrollHeight>i.offsetHeight||
+"scroll"==q.css("overflow-y")?g+f:g;if(w&&(i.scrollHeight>i.offsetHeight||"scroll"==q.css("overflow-y")))O.width=s(u-f);(""===c||""!==e)&&I(a,1,"Possible column misalignment",6)}else u="100%";n.width=s(u);j.width=s(u);L&&(a.nScrollFoot.style.width=s(u));!d&&w&&(n.height=s(t.offsetHeight+f));d&&b.bCollapse&&(n.height=s(d),b=c&&t.offsetWidth>i.offsetWidth?f:0,t.offsetHeight<i.offsetHeight&&(n.height=s(t.offsetHeight+b)));b=r.outerWidth();l[0].style.width=s(b);o.width=s(b);l=r.height()>i.clientHeight||
+"scroll"==q.css("overflow-y");ha="padding"+(ha.bScrollbarLeft?"Left":"Right");o[ha]=l?f+"px":"0px";L&&(p[0].style.width=s(b),k[0].style.width=s(b),k[0].style[ha]=l?f+"px":"0px");q.scroll();if((a.bSorted||a.bFiltered)&&!a._drawHold)i.scrollTop=0}function G(a,b,c){for(var e=0,d=0,f=b.length,g,j;d<f;){g=b[d].firstChild;for(j=c?c[d].firstChild:null;g;)1===g.nodeType&&(c?a(g,j,e):a(g,e),e++),g=g.nextSibling,j=c?j.nextSibling:null;d++}}function Ga(a){var b=a.nTable,c=a.aoColumns,e=a.oScroll,d=e.sY,f=e.sX,
+g=e.sXInner,j=c.length,e=Z(a,"bVisible"),i=h("th",a.nTHead),o=b.getAttribute("width"),l=b.parentNode,k=!1,n,m;(n=b.style.width)&&-1!==n.indexOf("%")&&(o=n);for(n=0;n<e.length;n++)m=c[e[n]],null!==m.sWidth&&(m.sWidth=Db(m.sWidthOrig,l),k=!0);if(!k&&!f&&!d&&j==aa(a)&&j==i.length)for(n=0;n<j;n++)c[n].sWidth=s(i.eq(n).width());else{j=h(b).clone().css("visibility","hidden").removeAttr("id");j.find("tbody tr").remove();var p=h("<tr/>").appendTo(j.find("tbody"));j.find("tfoot th, tfoot td").css("width",
+"");i=qa(a,j.find("thead")[0]);for(n=0;n<e.length;n++)m=c[e[n]],i[n].style.width=null!==m.sWidthOrig&&""!==m.sWidthOrig?s(m.sWidthOrig):"";if(a.aoData.length)for(n=0;n<e.length;n++)k=e[n],m=c[k],h(Eb(a,k)).clone(!1).append(m.sContentPadding).appendTo(p);j.appendTo(l);f&&g?j.width(g):f?(j.css("width","auto"),j.width()<l.offsetWidth&&j.width(l.offsetWidth)):d?j.width(l.offsetWidth):o&&j.width(o);Fb(a,j[0]);if(f){for(n=g=0;n<e.length;n++)m=c[e[n]],d=h(i[n]).outerWidth(),g+=null===m.sWidthOrig?d:parseInt(m.sWidth,
+10)+d-h(i[n]).width();j.width(s(g));b.style.width=s(g)}for(n=0;n<e.length;n++)if(m=c[e[n]],d=h(i[n]).width())m.sWidth=s(d);b.style.width=s(j.css("width"));j.remove()}o&&(b.style.width=s(o));if((o||f)&&!a._reszEvt)b=function(){h(Ea).bind("resize.DT-"+a.sInstance,ua(function(){X(a)}))},a.oBrowser.bScrollOversize?setTimeout(b,1E3):b(),a._reszEvt=!0}function ua(a,b){var c=b!==k?b:200,e,d;return function(){var b=this,g=+new Date,j=arguments;e&&g<e+c?(clearTimeout(d),d=setTimeout(function(){e=k;a.apply(b,
+j)},c)):(e=g,a.apply(b,j))}}function Db(a,b){if(!a)return 0;var c=h("<div/>").css("width",s(a)).appendTo(b||Q.body),e=c[0].offsetWidth;c.remove();return e}function Fb(a,b){var c=a.oScroll;if(c.sX||c.sY)c=!c.sX?c.iBarWidth:0,b.style.width=s(h(b).outerWidth()-c)}function Eb(a,b){var c=Gb(a,b);if(0>c)return null;var e=a.aoData[c];return!e.nTr?h("<td/>").html(x(a,c,b,"display"))[0]:e.anCells[b]}function Gb(a,b){for(var c,e=-1,d=-1,f=0,g=a.aoData.length;f<g;f++)c=x(a,f,b,"display")+"",c=c.replace($b,""),
+c.length>e&&(e=c.length,d=f);return d}function s(a){return null===a?"0px":"number"==typeof a?0>a?"0px":a+"px":a.match(/\d$/)?a+"px":a}function Hb(){var a=m.__scrollbarWidth;if(a===k){var b=h("<p/>").css({position:"absolute",top:0,left:0,width:"100%",height:150,padding:0,overflow:"scroll",visibility:"hidden"}).appendTo("body"),a=b[0].offsetWidth-b[0].clientWidth;m.__scrollbarWidth=a;b.remove()}return a}function U(a){var b,c,e=[],d=a.aoColumns,f,g,j,i;b=a.aaSortingFixed;c=h.isPlainObject(b);var o=[];
+f=function(a){a.length&&!h.isArray(a[0])?o.push(a):o.push.apply(o,a)};h.isArray(b)&&f(b);c&&b.pre&&f(b.pre);f(a.aaSorting);c&&b.post&&f(b.post);for(a=0;a<o.length;a++){i=o[a][0];f=d[i].aDataSort;b=0;for(c=f.length;b<c;b++)g=f[b],j=d[g].sType||"string",o[a]._idx===k&&(o[a]._idx=h.inArray(o[a][1],d[g].asSorting)),e.push({src:i,col:g,dir:o[a][1],index:o[a]._idx,type:j,formatter:m.ext.type.order[j+"-pre"]})}return e}function lb(a){var b,c,e=[],d=m.ext.type.order,f=a.aoData,g=0,j,i=a.aiDisplayMaster,h;
+Ha(a);h=U(a);b=0;for(c=h.length;b<c;b++)j=h[b],j.formatter&&g++,Ib(a,j.col);if("ssp"!=B(a)&&0!==h.length){b=0;for(c=i.length;b<c;b++)e[i[b]]=b;g===h.length?i.sort(function(a,b){var c,d,g,j,i=h.length,k=f[a]._aSortData,m=f[b]._aSortData;for(g=0;g<i;g++)if(j=h[g],c=k[j.col],d=m[j.col],c=c<d?-1:c>d?1:0,0!==c)return"asc"===j.dir?c:-c;c=e[a];d=e[b];return c<d?-1:c>d?1:0}):i.sort(function(a,b){var c,g,j,i,k=h.length,m=f[a]._aSortData,r=f[b]._aSortData;for(j=0;j<k;j++)if(i=h[j],c=m[i.col],g=r[i.col],i=d[i.type+
+"-"+i.dir]||d["string-"+i.dir],c=i(c,g),0!==c)return c;c=e[a];g=e[b];return c<g?-1:c>g?1:0})}a.bSorted=!0}function Jb(a){for(var b,c,e=a.aoColumns,d=U(a),a=a.oLanguage.oAria,f=0,g=e.length;f<g;f++){c=e[f];var j=c.asSorting;b=c.sTitle.replace(/<.*?>/g,"");var i=c.nTh;i.removeAttribute("aria-sort");c.bSortable&&(0<d.length&&d[0].col==f?(i.setAttribute("aria-sort","asc"==d[0].dir?"ascending":"descending"),c=j[d[0].index+1]||j[0]):c=j[0],b+="asc"===c?a.sSortAscending:a.sSortDescending);i.setAttribute("aria-label",
+b)}}function Ua(a,b,c,e){var d=a.aaSorting,f=a.aoColumns[b].asSorting,g=function(a,b){var c=a._idx;c===k&&(c=h.inArray(a[1],f));return c+1<f.length?c+1:b?null:0};"number"===typeof d[0]&&(d=a.aaSorting=[d]);c&&a.oFeatures.bSortMulti?(c=h.inArray(b,D(d,"0")),-1!==c?(b=g(d[c],!0),null===b&&1===d.length&&(b=0),null===b?d.splice(c,1):(d[c][1]=f[b],d[c]._idx=b)):(d.push([b,f[0],0]),d[d.length-1]._idx=0)):d.length&&d[0][0]==b?(b=g(d[0]),d.length=1,d[0][1]=f[b],d[0]._idx=b):(d.length=0,d.push([b,f[0]]),d[0]._idx=
+0);N(a);"function"==typeof e&&e(a)}function Oa(a,b,c,e){var d=a.aoColumns[c];Va(b,{},function(b){!1!==d.bSortable&&(a.oFeatures.bProcessing?(C(a,!0),setTimeout(function(){Ua(a,c,b.shiftKey,e);"ssp"!==B(a)&&C(a,!1)},0)):Ua(a,c,b.shiftKey,e))})}function xa(a){var b=a.aLastSort,c=a.oClasses.sSortColumn,e=U(a),d=a.oFeatures,f,g;if(d.bSort&&d.bSortClasses){d=0;for(f=b.length;d<f;d++)g=b[d].src,h(D(a.aoData,"anCells",g)).removeClass(c+(2>d?d+1:3));d=0;for(f=e.length;d<f;d++)g=e[d].src,h(D(a.aoData,"anCells",
+g)).addClass(c+(2>d?d+1:3))}a.aLastSort=e}function Ib(a,b){var c=a.aoColumns[b],e=m.ext.order[c.sSortDataType],d;e&&(d=e.call(a.oInstance,a,b,$(a,b)));for(var f,g=m.ext.type.order[c.sType+"-pre"],j=0,i=a.aoData.length;j<i;j++)if(c=a.aoData[j],c._aSortData||(c._aSortData=[]),!c._aSortData[b]||e)f=e?d[j]:x(a,j,b,"sort"),c._aSortData[b]=g?g(f):f}function ya(a){if(a.oFeatures.bStateSave&&!a.bDestroying){var b={time:+new Date,start:a._iDisplayStart,length:a._iDisplayLength,order:h.extend(!0,[],a.aaSorting),
+search:zb(a.oPreviousSearch),columns:h.map(a.aoColumns,function(b,e){return{visible:b.bVisible,search:zb(a.aoPreSearchCols[e])}})};w(a,"aoStateSaveParams","stateSaveParams",[a,b]);a.oSavedState=b;a.fnStateSaveCallback.call(a.oInstance,a,b)}}function Kb(a){var b,c,e=a.aoColumns;if(a.oFeatures.bStateSave){var d=a.fnStateLoadCallback.call(a.oInstance,a);if(d&&d.time&&(b=w(a,"aoStateLoadParams","stateLoadParams",[a,d]),-1===h.inArray(!1,b)&&(b=a.iStateDuration,!(0<b&&d.time<+new Date-1E3*b)&&e.length===
+d.columns.length))){a.oLoadedState=h.extend(!0,{},d);d.start!==k&&(a._iDisplayStart=d.start,a.iInitDisplayStart=d.start);d.length!==k&&(a._iDisplayLength=d.length);d.order!==k&&(a.aaSorting=[],h.each(d.order,function(b,c){a.aaSorting.push(c[0]>=e.length?[0,c[1]]:c)}));d.search!==k&&h.extend(a.oPreviousSearch,Ab(d.search));b=0;for(c=d.columns.length;b<c;b++){var f=d.columns[b];f.visible!==k&&(e[b].bVisible=f.visible);f.search!==k&&h.extend(a.aoPreSearchCols[b],Ab(f.search))}w(a,"aoStateLoaded","stateLoaded",
+[a,d])}}}function za(a){var b=m.settings,a=h.inArray(a,D(b,"nTable"));return-1!==a?b[a]:null}function I(a,b,c,e){c="DataTables warning: "+(null!==a?"table id="+a.sTableId+" - ":"")+c;e&&(c+=". For more information about this error, please see http://datatables.net/tn/"+e);if(b)Ea.console&&console.log&&console.log(c);else if(b=m.ext,b=b.sErrMode||b.errMode,w(a,null,"error",[a,e,c]),"alert"==b)alert(c);else{if("throw"==b)throw Error(c);"function"==typeof b&&b(a,e,c)}}function E(a,b,c,e){h.isArray(c)?
+h.each(c,function(c,f){h.isArray(f)?E(a,b,f[0],f[1]):E(a,b,f)}):(e===k&&(e=c),b[c]!==k&&(a[e]=b[c]))}function Lb(a,b,c){var e,d;for(d in b)b.hasOwnProperty(d)&&(e=b[d],h.isPlainObject(e)?(h.isPlainObject(a[d])||(a[d]={}),h.extend(!0,a[d],e)):a[d]=c&&"data"!==d&&"aaData"!==d&&h.isArray(e)?e.slice():e);return a}function Va(a,b,c){h(a).bind("click.DT",b,function(b){a.blur();c(b)}).bind("keypress.DT",b,function(a){13===a.which&&(a.preventDefault(),c(a))}).bind("selectstart.DT",function(){return!1})}function z(a,
+b,c,e){c&&a[b].push({fn:c,sName:e})}function w(a,b,c,e){var d=[];b&&(d=h.map(a[b].slice().reverse(),function(b){return b.fn.apply(a.oInstance,e)}));null!==c&&(b=h.Event(c+".dt"),h(a.nTable).trigger(b,e),d.push(b.result));return d}function Sa(a){var b=a._iDisplayStart,c=a.fnDisplayEnd(),e=a._iDisplayLength;b>=c&&(b=c-e);b-=b%e;if(-1===e||0>b)b=0;a._iDisplayStart=b}function Pa(a,b){var c=a.renderer,e=m.ext.renderer[b];return h.isPlainObject(c)&&c[b]?e[c[b]]||e._:"string"===typeof c?e[c]||e._:e._}function B(a){return a.oFeatures.bServerSide?
+"ssp":a.ajax||a.sAjaxSource?"ajax":"dom"}function Wa(a,b){var c=[],c=Mb.numbers_length,e=Math.floor(c/2);b<=c?c=V(0,b):a<=e?(c=V(0,c-2),c.push("ellipsis"),c.push(b-1)):(a>=b-1-e?c=V(b-(c-2),b):(c=V(a-e+2,a+e-1),c.push("ellipsis"),c.push(b-1)),c.splice(0,0,"ellipsis"),c.splice(0,0,0));c.DT_el="span";return c}function db(a){h.each({num:function(b){return Aa(b,a)},"num-fmt":function(b){return Aa(b,a,Xa)},"html-num":function(b){return Aa(b,a,Ba)},"html-num-fmt":function(b){return Aa(b,a,Ba,Xa)}},function(b,
+c){u.type.order[b+a+"-pre"]=c;b.match(/^html\-/)&&(u.type.search[b+a]=u.type.search.html)})}function Nb(a){return function(){var b=[za(this[m.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return m.ext.internal[a].apply(this,b)}}var m,u,t,r,v,Ya={},Ob=/[\r\n]/g,Ba=/<.*?>/g,ac=/^[\w\+\-]/,bc=/[\w\+\-]$/,Yb=RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\|\\$|\\^|\\-)","g"),Xa=/[',$\u00a3\u20ac\u00a5%\u2009\u202F\u20BD\u20a9\u20BArfk]/gi,J=function(a){return!a||!0===a||
+"-"===a?!0:!1},Pb=function(a){var b=parseInt(a,10);return!isNaN(b)&&isFinite(a)?b:null},Qb=function(a,b){Ya[b]||(Ya[b]=RegExp(va(b),"g"));return"string"===typeof a&&"."!==b?a.replace(/\./g,"").replace(Ya[b],"."):a},Za=function(a,b,c){var e="string"===typeof a;if(J(a))return!0;b&&e&&(a=Qb(a,b));c&&e&&(a=a.replace(Xa,""));return!isNaN(parseFloat(a))&&isFinite(a)},Rb=function(a,b,c){return J(a)?!0:!(J(a)||"string"===typeof a)?null:Za(a.replace(Ba,""),b,c)?!0:null},D=function(a,b,c){var e=[],d=0,f=a.length;
+if(c!==k)for(;d<f;d++)a[d]&&a[d][b]&&e.push(a[d][b][c]);else for(;d<f;d++)a[d]&&e.push(a[d][b]);return e},ia=function(a,b,c,e){var d=[],f=0,g=b.length;if(e!==k)for(;f<g;f++)a[b[f]][c]&&d.push(a[b[f]][c][e]);else for(;f<g;f++)d.push(a[b[f]][c]);return d},V=function(a,b){var c=[],e;b===k?(b=0,e=a):(e=b,b=a);for(var d=b;d<e;d++)c.push(d);return c},Sb=function(a){for(var b=[],c=0,e=a.length;c<e;c++)a[c]&&b.push(a[c]);return b},Na=function(a){var b=[],c,e,d=a.length,f,g=0;e=0;a:for(;e<d;e++){c=a[e];for(f=
+0;f<g;f++)if(b[f]===c)continue a;b.push(c);g++}return b},A=function(a,b,c){a[b]!==k&&(a[c]=a[b])},ba=/\[.*?\]$/,T=/\(\)$/,wa=h("<div>")[0],Zb=wa.textContent!==k,$b=/<.*?>/g;m=function(a){this.$=function(a,b){return this.api(!0).$(a,b)};this._=function(a,b){return this.api(!0).rows(a,b).data()};this.api=function(a){return a?new t(za(this[u.iApiIndex])):new t(this)};this.fnAddData=function(a,b){var c=this.api(!0),e=h.isArray(a)&&(h.isArray(a[0])||h.isPlainObject(a[0]))?c.rows.add(a):c.row.add(a);(b===
+k||b)&&c.draw();return e.flatten().toArray()};this.fnAdjustColumnSizing=function(a){var b=this.api(!0).columns.adjust(),c=b.settings()[0],e=c.oScroll;a===k||a?b.draw(!1):(""!==e.sX||""!==e.sY)&&Y(c)};this.fnClearTable=function(a){var b=this.api(!0).clear();(a===k||a)&&b.draw()};this.fnClose=function(a){this.api(!0).row(a).child.hide()};this.fnDeleteRow=function(a,b,c){var e=this.api(!0),a=e.rows(a),d=a.settings()[0],h=d.aoData[a[0][0]];a.remove();b&&b.call(this,d,h);(c===k||c)&&e.draw();return h};
+this.fnDestroy=function(a){this.api(!0).destroy(a)};this.fnDraw=function(a){this.api(!0).draw(a)};this.fnFilter=function(a,b,c,e,d,h){d=this.api(!0);null===b||b===k?d.search(a,c,e,h):d.column(b).search(a,c,e,h);d.draw()};this.fnGetData=function(a,b){var c=this.api(!0);if(a!==k){var e=a.nodeName?a.nodeName.toLowerCase():"";return b!==k||"td"==e||"th"==e?c.cell(a,b).data():c.row(a).data()||null}return c.data().toArray()};this.fnGetNodes=function(a){var b=this.api(!0);return a!==k?b.row(a).node():b.rows().nodes().flatten().toArray()};
+this.fnGetPosition=function(a){var b=this.api(!0),c=a.nodeName.toUpperCase();return"TR"==c?b.row(a).index():"TD"==c||"TH"==c?(a=b.cell(a).index(),[a.row,a.columnVisible,a.column]):null};this.fnIsOpen=function(a){return this.api(!0).row(a).child.isShown()};this.fnOpen=function(a,b,c){return this.api(!0).row(a).child(b,c).show().child()[0]};this.fnPageChange=function(a,b){var c=this.api(!0).page(a);(b===k||b)&&c.draw(!1)};this.fnSetColumnVis=function(a,b,c){a=this.api(!0).column(a).visible(b);(c===
+k||c)&&a.columns.adjust().draw()};this.fnSettings=function(){return za(this[u.iApiIndex])};this.fnSort=function(a){this.api(!0).order(a).draw()};this.fnSortListener=function(a,b,c){this.api(!0).order.listener(a,b,c)};this.fnUpdate=function(a,b,c,e,d){var h=this.api(!0);c===k||null===c?h.row(b).data(a):h.cell(b,c).data(a);(d===k||d)&&h.columns.adjust();(e===k||e)&&h.draw();return 0};this.fnVersionCheck=u.fnVersionCheck;var b=this,c=a===k,e=this.length;c&&(a={});this.oApi=this.internal=u.internal;for(var d in m.ext.internal)d&&
+(this[d]=Nb(d));this.each(function(){var d={},d=1<e?Lb(d,a,!0):a,g=0,j,i=this.getAttribute("id"),o=!1,l=m.defaults,q=h(this);if("table"!=this.nodeName.toLowerCase())I(null,0,"Non-table node initialisation ("+this.nodeName+")",2);else{eb(l);fb(l.column);H(l,l,!0);H(l.column,l.column,!0);H(l,h.extend(d,q.data()));var n=m.settings,g=0;for(j=n.length;g<j;g++){var r=n[g];if(r.nTable==this||r.nTHead.parentNode==this||r.nTFoot&&r.nTFoot.parentNode==this){g=d.bRetrieve!==k?d.bRetrieve:l.bRetrieve;if(c||g)return r.oInstance;
+if(d.bDestroy!==k?d.bDestroy:l.bDestroy){r.oInstance.fnDestroy();break}else{I(r,0,"Cannot reinitialise DataTable",3);return}}if(r.sTableId==this.id){n.splice(g,1);break}}if(null===i||""===i)this.id=i="DataTables_Table_"+m.ext._unique++;var p=h.extend(!0,{},m.models.oSettings,{sDestroyWidth:q[0].style.width,sInstance:i,sTableId:i});p.nTable=this;p.oApi=b.internal;p.oInit=d;n.push(p);p.oInstance=1===b.length?b:q.dataTable();eb(d);d.oLanguage&&P(d.oLanguage);d.aLengthMenu&&!d.iDisplayLength&&(d.iDisplayLength=
+h.isArray(d.aLengthMenu[0])?d.aLengthMenu[0][0]:d.aLengthMenu[0]);d=Lb(h.extend(!0,{},l),d);E(p.oFeatures,d,"bPaginate bLengthChange bFilter bSort bSortMulti bInfo bProcessing bAutoWidth bSortClasses bServerSide bDeferRender".split(" "));E(p,d,["asStripeClasses","ajax","fnServerData","fnFormatNumber","sServerMethod","aaSorting","aaSortingFixed","aLengthMenu","sPaginationType","sAjaxSource","sAjaxDataProp","iStateDuration","sDom","bSortCellsTop","iTabIndex","fnStateLoadCallback","fnStateSaveCallback",
+"renderer","searchDelay",["iCookieDuration","iStateDuration"],["oSearch","oPreviousSearch"],["aoSearchCols","aoPreSearchCols"],["iDisplayLength","_iDisplayLength"],["bJQueryUI","bJUI"]]);E(p.oScroll,d,[["sScrollX","sX"],["sScrollXInner","sXInner"],["sScrollY","sY"],["bScrollCollapse","bCollapse"]]);E(p.oLanguage,d,"fnInfoCallback");z(p,"aoDrawCallback",d.fnDrawCallback,"user");z(p,"aoServerParams",d.fnServerParams,"user");z(p,"aoStateSaveParams",d.fnStateSaveParams,"user");z(p,"aoStateLoadParams",
+d.fnStateLoadParams,"user");z(p,"aoStateLoaded",d.fnStateLoaded,"user");z(p,"aoRowCallback",d.fnRowCallback,"user");z(p,"aoRowCreatedCallback",d.fnCreatedRow,"user");z(p,"aoHeaderCallback",d.fnHeaderCallback,"user");z(p,"aoFooterCallback",d.fnFooterCallback,"user");z(p,"aoInitComplete",d.fnInitComplete,"user");z(p,"aoPreDrawCallback",d.fnPreDrawCallback,"user");i=p.oClasses;d.bJQueryUI?(h.extend(i,m.ext.oJUIClasses,d.oClasses),d.sDom===l.sDom&&"lfrtip"===l.sDom&&(p.sDom='<"H"lfr>t<"F"ip>'),p.renderer)?
+h.isPlainObject(p.renderer)&&!p.renderer.header&&(p.renderer.header="jqueryui"):p.renderer="jqueryui":h.extend(i,m.ext.classes,d.oClasses);q.addClass(i.sTable);if(""!==p.oScroll.sX||""!==p.oScroll.sY)p.oScroll.iBarWidth=Hb();!0===p.oScroll.sX&&(p.oScroll.sX="100%");p.iInitDisplayStart===k&&(p.iInitDisplayStart=d.iDisplayStart,p._iDisplayStart=d.iDisplayStart);null!==d.iDeferLoading&&(p.bDeferLoading=!0,g=h.isArray(d.iDeferLoading),p._iRecordsDisplay=g?d.iDeferLoading[0]:d.iDeferLoading,p._iRecordsTotal=
+g?d.iDeferLoading[1]:d.iDeferLoading);var t=p.oLanguage;h.extend(!0,t,d.oLanguage);""!==t.sUrl&&(h.ajax({dataType:"json",url:t.sUrl,success:function(a){P(a);H(l.oLanguage,a);h.extend(true,t,a);ga(p)},error:function(){ga(p)}}),o=!0);null===d.asStripeClasses&&(p.asStripeClasses=[i.sStripeOdd,i.sStripeEven]);var g=p.asStripeClasses,s=q.children("tbody").find("tr").eq(0);-1!==h.inArray(!0,h.map(g,function(a){return s.hasClass(a)}))&&(h("tbody tr",this).removeClass(g.join(" ")),p.asDestroyStripes=g.slice());
+n=[];g=this.getElementsByTagName("thead");0!==g.length&&(da(p.aoHeader,g[0]),n=qa(p));if(null===d.aoColumns){r=[];g=0;for(j=n.length;g<j;g++)r.push(null)}else r=d.aoColumns;g=0;for(j=r.length;g<j;g++)Fa(p,n?n[g]:null);ib(p,d.aoColumnDefs,r,function(a,b){ka(p,a,b)});if(s.length){var u=function(a,b){return a.getAttribute("data-"+b)!==null?b:null};h.each(na(p,s[0]).cells,function(a,b){var c=p.aoColumns[a];if(c.mData===a){var d=u(b,"sort")||u(b,"order"),e=u(b,"filter")||u(b,"search");if(d!==null||e!==
+null){c.mData={_:a+".display",sort:d!==null?a+".@data-"+d:k,type:d!==null?a+".@data-"+d:k,filter:e!==null?a+".@data-"+e:k};ka(p,a)}}})}var v=p.oFeatures;d.bStateSave&&(v.bStateSave=!0,Kb(p,d),z(p,"aoDrawCallback",ya,"state_save"));if(d.aaSorting===k){n=p.aaSorting;g=0;for(j=n.length;g<j;g++)n[g][1]=p.aoColumns[g].asSorting[0]}xa(p);v.bSort&&z(p,"aoDrawCallback",function(){if(p.bSorted){var a=U(p),b={};h.each(a,function(a,c){b[c.src]=c.dir});w(p,null,"order",[p,a,b]);Jb(p)}});z(p,"aoDrawCallback",
+function(){(p.bSorted||B(p)==="ssp"||v.bDeferRender)&&xa(p)},"sc");gb(p);g=q.children("caption").each(function(){this._captionSide=q.css("caption-side")});j=q.children("thead");0===j.length&&(j=h("<thead/>").appendTo(this));p.nTHead=j[0];j=q.children("tbody");0===j.length&&(j=h("<tbody/>").appendTo(this));p.nTBody=j[0];j=q.children("tfoot");if(0===j.length&&0<g.length&&(""!==p.oScroll.sX||""!==p.oScroll.sY))j=h("<tfoot/>").appendTo(this);0===j.length||0===j.children().length?q.addClass(i.sNoFooter):
+0<j.length&&(p.nTFoot=j[0],da(p.aoFooter,p.nTFoot));if(d.aaData)for(g=0;g<d.aaData.length;g++)K(p,d.aaData[g]);else(p.bDeferLoading||"dom"==B(p))&&ma(p,h(p.nTBody).children("tr"));p.aiDisplay=p.aiDisplayMaster.slice();p.bInitialised=!0;!1===o&&ga(p)}});b=null;return this};var Tb=[],y=Array.prototype,cc=function(a){var b,c,e=m.settings,d=h.map(e,function(a){return a.nTable});if(a){if(a.nTable&&a.oApi)return[a];if(a.nodeName&&"table"===a.nodeName.toLowerCase())return b=h.inArray(a,d),-1!==b?[e[b]]:
+null;if(a&&"function"===typeof a.settings)return a.settings().toArray();"string"===typeof a?c=h(a):a instanceof h&&(c=a)}else return[];if(c)return c.map(function(){b=h.inArray(this,d);return-1!==b?e[b]:null}).toArray()};t=function(a,b){if(!(this instanceof t))return new t(a,b);var c=[],e=function(a){(a=cc(a))&&c.push.apply(c,a)};if(h.isArray(a))for(var d=0,f=a.length;d<f;d++)e(a[d]);else e(a);this.context=Na(c);b&&this.push.apply(this,b.toArray?b.toArray():b);this.selector={rows:null,cols:null,opts:null};
+t.extend(this,this,Tb)};m.Api=t;t.prototype={any:function(){return 0!==this.flatten().length},concat:y.concat,context:[],each:function(a){for(var b=0,c=this.length;b<c;b++)a.call(this,this[b],b,this);return this},eq:function(a){var b=this.context;return b.length>a?new t(b[a],this[a]):null},filter:function(a){var b=[];if(y.filter)b=y.filter.call(this,a,this);else for(var c=0,e=this.length;c<e;c++)a.call(this,this[c],c,this)&&b.push(this[c]);return new t(this.context,b)},flatten:function(){var a=[];
+return new t(this.context,a.concat.apply(a,this.toArray()))},join:y.join,indexOf:y.indexOf||function(a,b){for(var c=b||0,e=this.length;c<e;c++)if(this[c]===a)return c;return-1},iterator:function(a,b,c,e){var d=[],f,g,h,i,o,l=this.context,q,n,m=this.selector;"string"===typeof a&&(e=c,c=b,b=a,a=!1);g=0;for(h=l.length;g<h;g++){var p=new t(l[g]);if("table"===b)f=c.call(p,l[g],g),f!==k&&d.push(f);else if("columns"===b||"rows"===b)f=c.call(p,l[g],this[g],g),f!==k&&d.push(f);else if("column"===b||"column-rows"===
+b||"row"===b||"cell"===b){n=this[g];"column-rows"===b&&(q=Ca(l[g],m.opts));i=0;for(o=n.length;i<o;i++)f=n[i],f="cell"===b?c.call(p,l[g],f.row,f.column,g,i):c.call(p,l[g],f,g,i,q),f!==k&&d.push(f)}}return d.length||e?(a=new t(l,a?d.concat.apply([],d):d),b=a.selector,b.rows=m.rows,b.cols=m.cols,b.opts=m.opts,a):this},lastIndexOf:y.lastIndexOf||function(a,b){return this.indexOf.apply(this.toArray.reverse(),arguments)},length:0,map:function(a){var b=[];if(y.map)b=y.map.call(this,a,this);else for(var c=
+0,e=this.length;c<e;c++)b.push(a.call(this,this[c],c));return new t(this.context,b)},pluck:function(a){return this.map(function(b){return b[a]})},pop:y.pop,push:y.push,reduce:y.reduce||function(a,b){return hb(this,a,b,0,this.length,1)},reduceRight:y.reduceRight||function(a,b){return hb(this,a,b,this.length-1,-1,-1)},reverse:y.reverse,selector:null,shift:y.shift,sort:y.sort,splice:y.splice,toArray:function(){return y.slice.call(this)},to$:function(){return h(this)},toJQuery:function(){return h(this)},
+unique:function(){return new t(this.context,Na(this))},unshift:y.unshift};t.extend=function(a,b,c){if(c.length&&b&&(b instanceof t||b.__dt_wrapper)){var e,d,f,g=function(a,b,c){return function(){var d=b.apply(a,arguments);t.extend(d,d,c.methodExt);return d}};e=0;for(d=c.length;e<d;e++)f=c[e],b[f.name]="function"===typeof f.val?g(a,f.val,f):h.isPlainObject(f.val)?{}:f.val,b[f.name].__dt_wrapper=!0,t.extend(a,b[f.name],f.propExt)}};t.register=r=function(a,b){if(h.isArray(a))for(var c=0,e=a.length;c<
+e;c++)t.register(a[c],b);else for(var d=a.split("."),f=Tb,g,j,c=0,e=d.length;c<e;c++){g=(j=-1!==d[c].indexOf("()"))?d[c].replace("()",""):d[c];var i;a:{i=0;for(var o=f.length;i<o;i++)if(f[i].name===g){i=f[i];break a}i=null}i||(i={name:g,val:{},methodExt:[],propExt:[]},f.push(i));c===e-1?i.val=b:f=j?i.methodExt:i.propExt}};t.registerPlural=v=function(a,b,c){t.register(a,c);t.register(b,function(){var a=c.apply(this,arguments);return a===this?this:a instanceof t?a.length?h.isArray(a[0])?new t(a.context,
+a[0]):a[0]:k:a})};r("tables()",function(a){var b;if(a){b=t;var c=this.context;if("number"===typeof a)a=[c[a]];else var e=h.map(c,function(a){return a.nTable}),a=h(e).filter(a).map(function(){var a=h.inArray(this,e);return c[a]}).toArray();b=new b(a)}else b=this;return b});r("table()",function(a){var a=this.tables(a),b=a.context;return b.length?new t(b[0]):a});v("tables().nodes()","table().node()",function(){return this.iterator("table",function(a){return a.nTable},1)});v("tables().body()","table().body()",
+function(){return this.iterator("table",function(a){return a.nTBody},1)});v("tables().header()","table().header()",function(){return this.iterator("table",function(a){return a.nTHead},1)});v("tables().footer()","table().footer()",function(){return this.iterator("table",function(a){return a.nTFoot},1)});v("tables().containers()","table().container()",function(){return this.iterator("table",function(a){return a.nTableWrapper},1)});r("draw()",function(a){return this.iterator("table",function(b){N(b,
+!1===a)})});r("page()",function(a){return a===k?this.page.info().page:this.iterator("table",function(b){Ta(b,a)})});r("page.info()",function(){if(0===this.context.length)return k;var a=this.context[0],b=a._iDisplayStart,c=a._iDisplayLength,e=a.fnRecordsDisplay(),d=-1===c;return{page:d?0:Math.floor(b/c),pages:d?1:Math.ceil(e/c),start:b,end:a.fnDisplayEnd(),length:c,recordsTotal:a.fnRecordsTotal(),recordsDisplay:e}});r("page.len()",function(a){return a===k?0!==this.context.length?this.context[0]._iDisplayLength:
+k:this.iterator("table",function(b){Ra(b,a)})});var Ub=function(a,b,c){if(c){var e=new t(a);e.one("draw",function(){c(e.ajax.json())})}"ssp"==B(a)?N(a,b):(C(a,!0),ra(a,[],function(c){oa(a);for(var c=sa(a,c),e=0,g=c.length;e<g;e++)K(a,c[e]);N(a,b);C(a,!1)}))};r("ajax.json()",function(){var a=this.context;if(0<a.length)return a[0].json});r("ajax.params()",function(){var a=this.context;if(0<a.length)return a[0].oAjaxData});r("ajax.reload()",function(a,b){return this.iterator("table",function(c){Ub(c,
+!1===b,a)})});r("ajax.url()",function(a){var b=this.context;if(a===k){if(0===b.length)return k;b=b[0];return b.ajax?h.isPlainObject(b.ajax)?b.ajax.url:b.ajax:b.sAjaxSource}return this.iterator("table",function(b){h.isPlainObject(b.ajax)?b.ajax.url=a:b.ajax=a})});r("ajax.url().load()",function(a,b){return this.iterator("table",function(c){Ub(c,!1===b,a)})});var $a=function(a,b,c,e,d){var f=[],g,j,i,o,l,q;i=typeof b;if(!b||"string"===i||"function"===i||b.length===k)b=[b];i=0;for(o=b.length;i<o;i++){j=
+b[i]&&b[i].split?b[i].split(","):[b[i]];l=0;for(q=j.length;l<q;l++)(g=c("string"===typeof j[l]?h.trim(j[l]):j[l]))&&g.length&&f.push.apply(f,g)}a=u.selector[a];if(a.length){i=0;for(o=a.length;i<o;i++)f=a[i](e,d,f)}return f},ab=function(a){a||(a={});a.filter&&a.search===k&&(a.search=a.filter);return h.extend({search:"none",order:"current",page:"all"},a)},bb=function(a){for(var b=0,c=a.length;b<c;b++)if(0<a[b].length)return a[0]=a[b],a[0].length=1,a.length=1,a.context=[a.context[b]],a;a.length=0;return a},
+Ca=function(a,b){var c,e,d,f=[],g=a.aiDisplay;c=a.aiDisplayMaster;var j=b.search;e=b.order;d=b.page;if("ssp"==B(a))return"removed"===j?[]:V(0,c.length);if("current"==d){c=a._iDisplayStart;for(e=a.fnDisplayEnd();c<e;c++)f.push(g[c])}else if("current"==e||"applied"==e)f="none"==j?c.slice():"applied"==j?g.slice():h.map(c,function(a){return-1===h.inArray(a,g)?a:null});else if("index"==e||"original"==e){c=0;for(e=a.aoData.length;c<e;c++)"none"==j?f.push(c):(d=h.inArray(c,g),(-1===d&&"removed"==j||0<=d&&
+"applied"==j)&&f.push(c))}return f};r("rows()",function(a,b){a===k?a="":h.isPlainObject(a)&&(b=a,a="");var b=ab(b),c=this.iterator("table",function(c){var d=b;return $a("row",a,function(a){var b=Pb(a);if(b!==null&&!d)return[b];var j=Ca(c,d);if(b!==null&&h.inArray(b,j)!==-1)return[b];if(!a)return j;if(typeof a==="function")return h.map(j,function(b){var d=c.aoData[b];return a(b,d._aData,d.nTr)?b:null});b=Sb(ia(c.aoData,j,"nTr"));return a.nodeName&&h.inArray(a,b)!==-1?[a._DT_RowIndex]:h(b).filter(a).map(function(){return this._DT_RowIndex}).toArray()},
+c,d)},1);c.selector.rows=a;c.selector.opts=b;return c});r("rows().nodes()",function(){return this.iterator("row",function(a,b){return a.aoData[b].nTr||k},1)});r("rows().data()",function(){return this.iterator(!0,"rows",function(a,b){return ia(a.aoData,b,"_aData")},1)});v("rows().cache()","row().cache()",function(a){return this.iterator("row",function(b,c){var e=b.aoData[c];return"search"===a?e._aFilterData:e._aSortData},1)});v("rows().invalidate()","row().invalidate()",function(a){return this.iterator("row",
+function(b,c){ca(b,c,a)})});v("rows().indexes()","row().index()",function(){return this.iterator("row",function(a,b){return b},1)});v("rows().remove()","row().remove()",function(){var a=this;return this.iterator("row",function(b,c,e){var d=b.aoData;d.splice(c,1);for(var f=0,g=d.length;f<g;f++)null!==d[f].nTr&&(d[f].nTr._DT_RowIndex=f);h.inArray(c,b.aiDisplay);pa(b.aiDisplayMaster,c);pa(b.aiDisplay,c);pa(a[e],c,!1);Sa(b)})});r("rows.add()",function(a){var b=this.iterator("table",function(b){var c,
+f,g,h=[];f=0;for(g=a.length;f<g;f++)c=a[f],c.nodeName&&"TR"===c.nodeName.toUpperCase()?h.push(ma(b,c)[0]):h.push(K(b,c));return h},1),c=this.rows(-1);c.pop();c.push.apply(c,b.toArray());return c});r("row()",function(a,b){return bb(this.rows(a,b))});r("row().data()",function(a){var b=this.context;if(a===k)return b.length&&this.length?b[0].aoData[this[0]]._aData:k;b[0].aoData[this[0]]._aData=a;ca(b[0],this[0],"data");return this});r("row().node()",function(){var a=this.context;return a.length&&this.length?
+a[0].aoData[this[0]].nTr||null:null});r("row.add()",function(a){a instanceof h&&a.length&&(a=a[0]);var b=this.iterator("table",function(b){return a.nodeName&&"TR"===a.nodeName.toUpperCase()?ma(b,a)[0]:K(b,a)});return this.row(b[0])});var cb=function(a,b){var c=a.context;c.length&&(c=c[0].aoData[b!==k?b:a[0]],c._details&&(c._details.remove(),c._detailsShow=k,c._details=k))},Vb=function(a,b){var c=a.context;if(c.length&&a.length){var e=c[0].aoData[a[0]];if(e._details){(e._detailsShow=b)?e._details.insertAfter(e.nTr):
+e._details.detach();var d=c[0],f=new t(d),g=d.aoData;f.off("draw.dt.DT_details column-visibility.dt.DT_details destroy.dt.DT_details");0<D(g,"_details").length&&(f.on("draw.dt.DT_details",function(a,b){d===b&&f.rows({page:"current"}).eq(0).each(function(a){a=g[a];a._detailsShow&&a._details.insertAfter(a.nTr)})}),f.on("column-visibility.dt.DT_details",function(a,b){if(d===b)for(var c,e=aa(b),f=0,h=g.length;f<h;f++)c=g[f],c._details&&c._details.children("td[colspan]").attr("colspan",e)}),f.on("destroy.dt.DT_details",
+function(a,b){if(d===b)for(var c=0,e=g.length;c<e;c++)g[c]._details&&cb(f,c)}))}}};r("row().child()",function(a,b){var c=this.context;if(a===k)return c.length&&this.length?c[0].aoData[this[0]]._details:k;if(!0===a)this.child.show();else if(!1===a)cb(this);else if(c.length&&this.length){var e=c[0],c=c[0].aoData[this[0]],d=[],f=function(a,b){if(h.isArray(a)||a instanceof h)for(var c=0,k=a.length;c<k;c++)f(a[c],b);else a.nodeName&&"tr"===a.nodeName.toLowerCase()?d.push(a):(c=h("<tr><td/></tr>").addClass(b),
+h("td",c).addClass(b).html(a)[0].colSpan=aa(e),d.push(c[0]))};f(a,b);c._details&&c._details.remove();c._details=h(d);c._detailsShow&&c._details.insertAfter(c.nTr)}return this});r(["row().child.show()","row().child().show()"],function(){Vb(this,!0);return this});r(["row().child.hide()","row().child().hide()"],function(){Vb(this,!1);return this});r(["row().child.remove()","row().child().remove()"],function(){cb(this);return this});r("row().child.isShown()",function(){var a=this.context;return a.length&&
+this.length?a[0].aoData[this[0]]._detailsShow||!1:!1});var dc=/^(.+):(name|visIdx|visible)$/,Wb=function(a,b,c,e,d){for(var c=[],e=0,f=d.length;e<f;e++)c.push(x(a,d[e],b));return c};r("columns()",function(a,b){a===k?a="":h.isPlainObject(a)&&(b=a,a="");var b=ab(b),c=this.iterator("table",function(c){var d=a,f=b,g=c.aoColumns,j=D(g,"sName"),i=D(g,"nTh");return $a("column",d,function(a){var b=Pb(a);if(a==="")return V(g.length);if(b!==null)return[b>=0?b:g.length+b];if(typeof a==="function"){var d=Ca(c,
+f);return h.map(g,function(b,f){return a(f,Wb(c,f,0,0,d),i[f])?f:null})}var k=typeof a==="string"?a.match(dc):"";if(k)switch(k[2]){case "visIdx":case "visible":b=parseInt(k[1],10);if(b<0){var m=h.map(g,function(a,b){return a.bVisible?b:null});return[m[m.length+b]]}return[la(c,b)];case "name":return h.map(j,function(a,b){return a===k[1]?b:null})}else return h(i).filter(a).map(function(){return h.inArray(this,i)}).toArray()},c,f)},1);c.selector.cols=a;c.selector.opts=b;return c});v("columns().header()",
+"column().header()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].nTh},1)});v("columns().footer()","column().footer()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].nTf},1)});v("columns().data()","column().data()",function(){return this.iterator("column-rows",Wb,1)});v("columns().dataSrc()","column().dataSrc()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].mData},1)});v("columns().cache()","column().cache()",
+function(a){return this.iterator("column-rows",function(b,c,e,d,f){return ia(b.aoData,f,"search"===a?"_aFilterData":"_aSortData",c)},1)});v("columns().nodes()","column().nodes()",function(){return this.iterator("column-rows",function(a,b,c,e,d){return ia(a.aoData,d,"anCells",b)},1)});v("columns().visible()","column().visible()",function(a,b){return this.iterator("column",function(c,e){if(a===k)return c.aoColumns[e].bVisible;var d=c.aoColumns,f=d[e],g=c.aoData,j,i,m;if(a!==k&&f.bVisible!==a){if(a){var l=
+h.inArray(!0,D(d,"bVisible"),e+1);j=0;for(i=g.length;j<i;j++)m=g[j].nTr,d=g[j].anCells,m&&m.insertBefore(d[e],d[l]||null)}else h(D(c.aoData,"anCells",e)).detach();f.bVisible=a;ea(c,c.aoHeader);ea(c,c.aoFooter);if(b===k||b)X(c),(c.oScroll.sX||c.oScroll.sY)&&Y(c);w(c,null,"column-visibility",[c,e,a]);ya(c)}})});v("columns().indexes()","column().index()",function(a){return this.iterator("column",function(b,c){return"visible"===a?$(b,c):c},1)});r("columns.adjust()",function(){return this.iterator("table",
+function(a){X(a)},1)});r("column.index()",function(a,b){if(0!==this.context.length){var c=this.context[0];if("fromVisible"===a||"toData"===a)return la(c,b);if("fromData"===a||"toVisible"===a)return $(c,b)}});r("column()",function(a,b){return bb(this.columns(a,b))});r("cells()",function(a,b,c){h.isPlainObject(a)&&(a.row===k?(c=a,a=null):(c=b,b=null));h.isPlainObject(b)&&(c=b,b=null);if(null===b||b===k)return this.iterator("table",function(b){var d=a,e=ab(c),f=b.aoData,g=Ca(b,e),i=Sb(ia(f,g,"anCells")),
+j=h([].concat.apply([],i)),l,m=b.aoColumns.length,o,r,t,s,u,v;return $a("cell",d,function(a){var c=typeof a==="function";if(a===null||a===k||c){o=[];r=0;for(t=g.length;r<t;r++){l=g[r];for(s=0;s<m;s++){u={row:l,column:s};if(c){v=b.aoData[l];a(u,x(b,l,s),v.anCells?v.anCells[s]:null)&&o.push(u)}else o.push(u)}}return o}return h.isPlainObject(a)?[a]:j.filter(a).map(function(a,b){l=b.parentNode._DT_RowIndex;return{row:l,column:h.inArray(b,f[l].anCells)}}).toArray()},b,e)});var e=this.columns(b,c),d=this.rows(a,
+c),f,g,j,i,m,l=this.iterator("table",function(a,b){f=[];g=0;for(j=d[b].length;g<j;g++){i=0;for(m=e[b].length;i<m;i++)f.push({row:d[b][g],column:e[b][i]})}return f},1);h.extend(l.selector,{cols:b,rows:a,opts:c});return l});v("cells().nodes()","cell().node()",function(){return this.iterator("cell",function(a,b,c){return(a=a.aoData[b].anCells)?a[c]:k},1)});r("cells().data()",function(){return this.iterator("cell",function(a,b,c){return x(a,b,c)},1)});v("cells().cache()","cell().cache()",function(a){a=
+"search"===a?"_aFilterData":"_aSortData";return this.iterator("cell",function(b,c,e){return b.aoData[c][a][e]},1)});v("cells().render()","cell().render()",function(a){return this.iterator("cell",function(b,c,e){return x(b,c,e,a)},1)});v("cells().indexes()","cell().index()",function(){return this.iterator("cell",function(a,b,c){return{row:b,column:c,columnVisible:$(a,c)}},1)});v("cells().invalidate()","cell().invalidate()",function(a){return this.iterator("cell",function(b,c,e){ca(b,c,a,e)})});r("cell()",
+function(a,b,c){return bb(this.cells(a,b,c))});r("cell().data()",function(a){var b=this.context,c=this[0];if(a===k)return b.length&&c.length?x(b[0],c[0].row,c[0].column):k;Ia(b[0],c[0].row,c[0].column,a);ca(b[0],c[0].row,"data",c[0].column);return this});r("order()",function(a,b){var c=this.context;if(a===k)return 0!==c.length?c[0].aaSorting:k;"number"===typeof a?a=[[a,b]]:h.isArray(a[0])||(a=Array.prototype.slice.call(arguments));return this.iterator("table",function(b){b.aaSorting=a.slice()})});
+r("order.listener()",function(a,b,c){return this.iterator("table",function(e){Oa(e,a,b,c)})});r(["columns().order()","column().order()"],function(a){var b=this;return this.iterator("table",function(c,e){var d=[];h.each(b[e],function(b,c){d.push([c,a])});c.aaSorting=d})});r("search()",function(a,b,c,e){var d=this.context;return a===k?0!==d.length?d[0].oPreviousSearch.sSearch:k:this.iterator("table",function(d){d.oFeatures.bFilter&&fa(d,h.extend({},d.oPreviousSearch,{sSearch:a+"",bRegex:null===b?!1:
+b,bSmart:null===c?!0:c,bCaseInsensitive:null===e?!0:e}),1)})});v("columns().search()","column().search()",function(a,b,c,e){return this.iterator("column",function(d,f){var g=d.aoPreSearchCols;if(a===k)return g[f].sSearch;d.oFeatures.bFilter&&(h.extend(g[f],{sSearch:a+"",bRegex:null===b?!1:b,bSmart:null===c?!0:c,bCaseInsensitive:null===e?!0:e}),fa(d,d.oPreviousSearch,1))})});r("state()",function(){return this.context.length?this.context[0].oSavedState:null});r("state.clear()",function(){return this.iterator("table",
+function(a){a.fnStateSaveCallback.call(a.oInstance,a,{})})});r("state.loaded()",function(){return this.context.length?this.context[0].oLoadedState:null});r("state.save()",function(){return this.iterator("table",function(a){ya(a)})});m.versionCheck=m.fnVersionCheck=function(a){for(var b=m.version.split("."),a=a.split("."),c,e,d=0,f=a.length;d<f;d++)if(c=parseInt(b[d],10)||0,e=parseInt(a[d],10)||0,c!==e)return c>e;return!0};m.isDataTable=m.fnIsDataTable=function(a){var b=h(a).get(0),c=!1;h.each(m.settings,
+function(a,d){var f=d.nScrollHead?h("table",d.nScrollHead)[0]:null,g=d.nScrollFoot?h("table",d.nScrollFoot)[0]:null;if(d.nTable===b||f===b||g===b)c=!0});return c};m.tables=m.fnTables=function(a){return h.map(m.settings,function(b){if(!a||a&&h(b.nTable).is(":visible"))return b.nTable})};m.util={throttle:ua,escapeRegex:va};m.camelToHungarian=H;r("$()",function(a,b){var c=this.rows(b).nodes(),c=h(c);return h([].concat(c.filter(a).toArray(),c.find(a).toArray()))});h.each(["on","one","off"],function(a,
+b){r(b+"()",function(){var a=Array.prototype.slice.call(arguments);a[0].match(/\.dt\b/)||(a[0]+=".dt");var e=h(this.tables().nodes());e[b].apply(e,a);return this})});r("clear()",function(){return this.iterator("table",function(a){oa(a)})});r("settings()",function(){return new t(this.context,this.context)});r("init()",function(){var a=this.context;return a.length?a[0].oInit:null});r("data()",function(){return this.iterator("table",function(a){return D(a.aoData,"_aData")}).flatten()});r("destroy()",
+function(a){a=a||!1;return this.iterator("table",function(b){var c=b.nTableWrapper.parentNode,e=b.oClasses,d=b.nTable,f=b.nTBody,g=b.nTHead,j=b.nTFoot,i=h(d),f=h(f),k=h(b.nTableWrapper),l=h.map(b.aoData,function(a){return a.nTr}),q;b.bDestroying=!0;w(b,"aoDestroyCallback","destroy",[b]);a||(new t(b)).columns().visible(!0);k.unbind(".DT").find(":not(tbody *)").unbind(".DT");h(Ea).unbind(".DT-"+b.sInstance);d!=g.parentNode&&(i.children("thead").detach(),i.append(g));j&&d!=j.parentNode&&(i.children("tfoot").detach(),
+i.append(j));i.detach();k.detach();b.aaSorting=[];b.aaSortingFixed=[];xa(b);h(l).removeClass(b.asStripeClasses.join(" "));h("th, td",g).removeClass(e.sSortable+" "+e.sSortableAsc+" "+e.sSortableDesc+" "+e.sSortableNone);b.bJUI&&(h("th span."+e.sSortIcon+", td span."+e.sSortIcon,g).detach(),h("th, td",g).each(function(){var a=h("div."+e.sSortJUIWrapper,this);h(this).append(a.contents());a.detach()}));!a&&c&&c.insertBefore(d,b.nTableReinsertBefore);f.children().detach();f.append(l);i.css("width",b.sDestroyWidth).removeClass(e.sTable);
+(q=b.asDestroyStripes.length)&&f.children().each(function(a){h(this).addClass(b.asDestroyStripes[a%q])});c=h.inArray(b,m.settings);-1!==c&&m.settings.splice(c,1)})});h.each(["column","row","cell"],function(a,b){r(b+"s().every()",function(a){return this.iterator(b,function(e,d,f){a.call((new t(e))[b](d,f))})})});r("i18n()",function(a,b,c){var e=this.context[0],a=R(a)(e.oLanguage);a===k&&(a=b);c!==k&&h.isPlainObject(a)&&(a=a[c]!==k?a[c]:a._);return a.replace("%d",c)});m.version="1.10.7";m.settings=
+[];m.models={};m.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0};m.models.oRow={nTr:null,anCells:null,_aData:[],_aSortData:null,_aFilterData:null,_sFilterRow:null,_sRowStripe:"",src:null};m.models.oColumn={idx:null,aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bVisible:null,_sManualType:null,_bAttrSrc:!1,fnCreatedCell:null,fnGetData:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std",
+sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null};m.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:[],ajax:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0,bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollCollapse:!1,bServerSide:!1,bSort:!0,bSortMulti:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1,
+fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(a){return a.toString().replace(/\B(?=(\d{3})+(?!\d))/g,this.oLanguage.sThousands)},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null,fnRowCallback:null,fnServerData:null,fnServerParams:null,fnStateLoadCallback:function(a){try{return JSON.parse((-1===a.iStateDuration?sessionStorage:localStorage).getItem("DataTables_"+a.sInstance+"_"+location.pathname))}catch(b){}},fnStateLoadParams:null,
+fnStateLoaded:null,fnStateSaveCallback:function(a,b){try{(-1===a.iStateDuration?sessionStorage:localStorage).setItem("DataTables_"+a.sInstance+"_"+location.pathname,JSON.stringify(b))}catch(c){}},fnStateSaveParams:null,iStateDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iTabIndex:0,oClasses:{},oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"},
+sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sDecimal:"",sThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sSearchPlaceholder:"",sUrl:"",sZeroRecords:"No matching records found"},oSearch:h.extend({},m.models.oSearch),sAjaxDataProp:"data",sAjaxSource:null,sDom:"lfrtip",searchDelay:null,
+sPaginationType:"simple_numbers",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET",renderer:null};W(m.defaults);m.defaults.column={aDataSort:null,iDataSort:-1,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bVisible:!0,fnCreatedCell:null,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null};W(m.defaults.column);m.models.oSettings={oFeatures:{bAutoWidth:null,bDeferRender:null,bFilter:null,
+bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortMulti:null,bSortClasses:null,bStateSave:null},oScroll:{bCollapse:null,iBarWidth:0,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1,bScrollbarLeft:!1},ajax:null,aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aoColumns:[],aoHeader:[],aoFooter:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:[],asStripeClasses:null,asDestroyStripes:[],
+sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,searchDelay:null,sPaginationType:"two_button",iStateDuration:0,aoStateSave:[],aoStateLoad:[],oSavedState:null,oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,
+bAjaxDataGet:!0,jqXHR:null,json:k,oAjaxData:k,fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return"ssp"==B(this)?1*this._iRecordsTotal:this.aiDisplayMaster.length},fnRecordsDisplay:function(){return"ssp"==B(this)?1*this._iRecordsDisplay:
+this.aiDisplay.length},fnDisplayEnd:function(){var a=this._iDisplayLength,b=this._iDisplayStart,c=b+a,e=this.aiDisplay.length,d=this.oFeatures,f=d.bPaginate;return d.bServerSide?!1===f||-1===a?b+e:Math.min(b+a,this._iRecordsDisplay):!f||c>e||-1===a?e:c},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null,aLastSort:[],oPlugins:{}};m.ext=u={buttons:{},classes:{},errMode:"alert",feature:[],search:[],selector:{cell:[],column:[],row:[]},internal:{},legacy:{ajax:null},pager:{},renderer:{pageButton:{},
+header:{}},order:{},type:{detect:[],search:{},order:{}},_unique:0,fnVersionCheck:m.fnVersionCheck,iApiIndex:0,oJUIClasses:{},sVersion:m.version};h.extend(u,{afnFiltering:u.search,aTypes:u.type.detect,ofnSearch:u.type.search,oSort:u.type.order,afnSortData:u.order,aoFeatures:u.feature,oApi:u.internal,oStdClasses:u.classes,oPagination:u.pager});h.extend(m.ext.classes,{sTable:"dataTable",sNoFooter:"no-footer",sPageButton:"paginate_button",sPageButtonActive:"current",sPageButtonDisabled:"disabled",sStripeOdd:"odd",
+sStripeEven:"even",sRowEmpty:"dataTables_empty",sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sFilterInput:"",sLengthSelect:"",sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",
+sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody",sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sHeaderTH:"",sFooterTH:"",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",sJUIHeader:"",sJUIFooter:""});var Da="",Da="",F=Da+"ui-state-default",ja=Da+"css_right ui-icon ui-icon-",Xb=Da+"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix";h.extend(m.ext.oJUIClasses,
+m.ext.classes,{sPageButton:"fg-button ui-button "+F,sPageButtonActive:"ui-state-disabled",sPageButtonDisabled:"ui-state-disabled",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",sSortAsc:F+" sorting_asc",sSortDesc:F+" sorting_desc",sSortable:F+" sorting",sSortableAsc:F+" sorting_asc_disabled",sSortableDesc:F+" sorting_desc_disabled",sSortableNone:F+" sorting_disabled",sSortJUIAsc:ja+"triangle-1-n",sSortJUIDesc:ja+"triangle-1-s",sSortJUI:ja+"carat-2-n-s",
+sSortJUIAscAllowed:ja+"carat-1-n",sSortJUIDescAllowed:ja+"carat-1-s",sSortJUIWrapper:"DataTables_sort_wrapper",sSortIcon:"DataTables_sort_icon",sScrollHead:"dataTables_scrollHead "+F,sScrollFoot:"dataTables_scrollFoot "+F,sHeaderTH:F,sFooterTH:F,sJUIHeader:Xb+" ui-corner-tl ui-corner-tr",sJUIFooter:Xb+" ui-corner-bl ui-corner-br"});var Mb=m.ext.pager;h.extend(Mb,{simple:function(){return["previous","next"]},full:function(){return["first","previous","next","last"]},simple_numbers:function(a,b){return["previous",
+Wa(a,b),"next"]},full_numbers:function(a,b){return["first","previous",Wa(a,b),"next","last"]},_numbers:Wa,numbers_length:7});h.extend(!0,m.ext.renderer,{pageButton:{_:function(a,b,c,e,d,f){var g=a.oClasses,j=a.oLanguage.oPaginate,i,k,l=0,m=function(b,e){var n,r,t,s,u=function(b){Ta(a,b.data.action,true)};n=0;for(r=e.length;n<r;n++){s=e[n];if(h.isArray(s)){t=h("<"+(s.DT_el||"div")+"/>").appendTo(b);m(t,s)}else{k=i="";switch(s){case "ellipsis":b.append('<span class="ellipsis">&#x2026;</span>');break;
+case "first":i=j.sFirst;k=s+(d>0?"":" "+g.sPageButtonDisabled);break;case "previous":i=j.sPrevious;k=s+(d>0?"":" "+g.sPageButtonDisabled);break;case "next":i=j.sNext;k=s+(d<f-1?"":" "+g.sPageButtonDisabled);break;case "last":i=j.sLast;k=s+(d<f-1?"":" "+g.sPageButtonDisabled);break;default:i=s+1;k=d===s?g.sPageButtonActive:""}if(i){t=h("<a>",{"class":g.sPageButton+" "+k,"aria-controls":a.sTableId,"data-dt-idx":l,tabindex:a.iTabIndex,id:c===0&&typeof s==="string"?a.sTableId+"_"+s:null}).html(i).appendTo(b);
+Va(t,{action:s},u);l++}}}},n;try{n=h(Q.activeElement).data("dt-idx")}catch(r){}m(h(b).empty(),e);n&&h(b).find("[data-dt-idx="+n+"]").focus()}}});h.extend(m.ext.type.detect,[function(a,b){var c=b.oLanguage.sDecimal;return Za(a,c)?"num"+c:null},function(a){if(a&&!(a instanceof Date)&&(!ac.test(a)||!bc.test(a)))return null;var b=Date.parse(a);return null!==b&&!isNaN(b)||J(a)?"date":null},function(a,b){var c=b.oLanguage.sDecimal;return Za(a,c,!0)?"num-fmt"+c:null},function(a,b){var c=b.oLanguage.sDecimal;
+return Rb(a,c)?"html-num"+c:null},function(a,b){var c=b.oLanguage.sDecimal;return Rb(a,c,!0)?"html-num-fmt"+c:null},function(a){return J(a)||"string"===typeof a&&-1!==a.indexOf("<")?"html":null}]);h.extend(m.ext.type.search,{html:function(a){return J(a)?a:"string"===typeof a?a.replace(Ob," ").replace(Ba,""):""},string:function(a){return J(a)?a:"string"===typeof a?a.replace(Ob," "):a}});var Aa=function(a,b,c,e){if(0!==a&&(!a||"-"===a))return-Infinity;b&&(a=Qb(a,b));a.replace&&(c&&(a=a.replace(c,"")),
+e&&(a=a.replace(e,"")));return 1*a};h.extend(u.type.order,{"date-pre":function(a){return Date.parse(a)||0},"html-pre":function(a){return J(a)?"":a.replace?a.replace(/<.*?>/g,"").toLowerCase():a+""},"string-pre":function(a){return J(a)?"":"string"===typeof a?a.toLowerCase():!a.toString?"":a.toString()},"string-asc":function(a,b){return a<b?-1:a>b?1:0},"string-desc":function(a,b){return a<b?1:a>b?-1:0}});db("");h.extend(!0,m.ext.renderer,{header:{_:function(a,b,c,e){h(a.nTable).on("order.dt.DT",function(d,
+f,g,h){if(a===f){d=c.idx;b.removeClass(c.sSortingClass+" "+e.sSortAsc+" "+e.sSortDesc).addClass(h[d]=="asc"?e.sSortAsc:h[d]=="desc"?e.sSortDesc:c.sSortingClass)}})},jqueryui:function(a,b,c,e){h("<div/>").addClass(e.sSortJUIWrapper).append(b.contents()).append(h("<span/>").addClass(e.sSortIcon+" "+c.sSortingClassJUI)).appendTo(b);h(a.nTable).on("order.dt.DT",function(d,f,g,h){if(a===f){d=c.idx;b.removeClass(e.sSortAsc+" "+e.sSortDesc).addClass(h[d]=="asc"?e.sSortAsc:h[d]=="desc"?e.sSortDesc:c.sSortingClass);
+b.find("span."+e.sSortIcon).removeClass(e.sSortJUIAsc+" "+e.sSortJUIDesc+" "+e.sSortJUI+" "+e.sSortJUIAscAllowed+" "+e.sSortJUIDescAllowed).addClass(h[d]=="asc"?e.sSortJUIAsc:h[d]=="desc"?e.sSortJUIDesc:c.sSortingClassJUI)}})}}});m.render={number:function(a,b,c,e){return{display:function(d){if("number"!==typeof d&&"string"!==typeof d)return d;var f=0>d?"-":"",d=Math.abs(parseFloat(d)),g=parseInt(d,10),d=c?b+(d-g).toFixed(c).substring(2):"";return f+(e||"")+g.toString().replace(/\B(?=(\d{3})+(?!\d))/g,
+a)+d}}}};h.extend(m.ext.internal,{_fnExternApiFunc:Nb,_fnBuildAjax:ra,_fnAjaxUpdate:kb,_fnAjaxParameters:tb,_fnAjaxUpdateDraw:ub,_fnAjaxDataSrc:sa,_fnAddColumn:Fa,_fnColumnOptions:ka,_fnAdjustColumnSizing:X,_fnVisibleToColumnIndex:la,_fnColumnIndexToVisible:$,_fnVisbleColumns:aa,_fnGetColumns:Z,_fnColumnTypes:Ha,_fnApplyColumnDefs:ib,_fnHungarianMap:W,_fnCamelToHungarian:H,_fnLanguageCompat:P,_fnBrowserDetect:gb,_fnAddData:K,_fnAddTr:ma,_fnNodeToDataIndex:function(a,b){return b._DT_RowIndex!==k?b._DT_RowIndex:
+null},_fnNodeToColumnIndex:function(a,b,c){return h.inArray(c,a.aoData[b].anCells)},_fnGetCellData:x,_fnSetCellData:Ia,_fnSplitObjNotation:Ka,_fnGetObjectDataFn:R,_fnSetObjectDataFn:S,_fnGetDataMaster:La,_fnClearTable:oa,_fnDeleteIndex:pa,_fnInvalidate:ca,_fnGetRowElements:na,_fnCreateTr:Ja,_fnBuildHead:jb,_fnDrawHead:ea,_fnDraw:M,_fnReDraw:N,_fnAddOptionsHtml:mb,_fnDetectHeader:da,_fnGetUniqueThs:qa,_fnFeatureHtmlFilter:ob,_fnFilterComplete:fa,_fnFilterCustom:xb,_fnFilterColumn:wb,_fnFilter:vb,_fnFilterCreateSearch:Qa,
+_fnEscapeRegex:va,_fnFilterData:yb,_fnFeatureHtmlInfo:rb,_fnUpdateInfo:Bb,_fnInfoMacros:Cb,_fnInitialise:ga,_fnInitComplete:ta,_fnLengthChange:Ra,_fnFeatureHtmlLength:nb,_fnFeatureHtmlPaginate:sb,_fnPageChange:Ta,_fnFeatureHtmlProcessing:pb,_fnProcessingDisplay:C,_fnFeatureHtmlTable:qb,_fnScrollDraw:Y,_fnApplyToChildren:G,_fnCalculateColumnWidths:Ga,_fnThrottle:ua,_fnConvertToWidth:Db,_fnScrollingWidthAdjust:Fb,_fnGetWidestNode:Eb,_fnGetMaxLenString:Gb,_fnStringToCss:s,_fnScrollBarWidth:Hb,_fnSortFlatten:U,
+_fnSort:lb,_fnSortAria:Jb,_fnSortListener:Ua,_fnSortAttachListener:Oa,_fnSortingClasses:xa,_fnSortData:Ib,_fnSaveState:ya,_fnLoadState:Kb,_fnSettingsFromNode:za,_fnLog:I,_fnMap:E,_fnBindAction:Va,_fnCallbackReg:z,_fnCallbackFire:w,_fnLengthOverflow:Sa,_fnRenderer:Pa,_fnDataSource:B,_fnRowAttributes:Ma,_fnCalculateEnd:function(){}});h.fn.dataTable=m;h.fn.dataTableSettings=m.settings;h.fn.dataTableExt=m.ext;h.fn.DataTable=function(a){return h(this).dataTable(a).api()};h.each(m,function(a,b){h.fn.DataTable[a]=
+b});return h.fn.dataTable};"function"===typeof define&&define.amd?define("datatables",["jquery"],P):"object"===typeof exports?module.exports=P(require("jquery")):jQuery&&!jQuery.fn.dataTable&&P(jQuery)})(window,document);
diff --git a/wqflask/wqflask/static/new/packages/DataTables/js/jquery.js b/wqflask/wqflask/static/new/packages/DataTables/js/jquery.js
index 63174a0d..fdd413a6 100755
--- a/wqflask/wqflask/static/new/packages/DataTables/js/jquery.js
+++ b/wqflask/wqflask/static/new/packages/DataTables/js/jquery.js
@@ -1,2 +1,5 @@
-/*! jQuery v1.8.2 jquery.com | jquery.org/license */
-(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bY(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bW.length;while(e--){b=bW[e]+c;if(b in a)return b}return d}function bZ(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function b$(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bZ(c)&&(e[f]=p._data(c,"olddisplay",cc(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b_(a,b,c){var d=bP.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function ca(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bV[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bV[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bV[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bV[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bV[e]+"Width"))||0));return f}function cb(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0||d==null){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bQ.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+ca(a,b,c||(f?"border":"content"),e)+"px"}function cc(a){if(bS[a])return bS[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bS[a]=c,c}function ci(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||ce.test(a)?d(a,e):ci(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ci(a+"["+e+"]",b[e],c,d);else d(a,b)}function cz(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cA(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cv;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cA(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cA(a,c,d,e,"*",g)),h}function cB(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cC(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cD(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cL(){try{return new a.XMLHttpRequest}catch(b){}}function cM(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cU(){return setTimeout(function(){cN=b},0),cN=p.now()}function cV(a,b){p.each(b,function(b,c){var d=(cT[b]||[]).concat(cT["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cW(a,b,c){var d,e=0,f=0,g=cS.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cN||cU(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cN||cU(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cX(k,j.opts.specialEasing);for(;e<g;e++){d=cS[e].call(j,a,k,j.opts);if(d)return d}return cV(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cX(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cY(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bZ(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cc(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cP.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cZ(a,b,c,d,e){return new cZ.prototype.init(a,b,c,d,e)}function c$(a,b){var c,d={height:a},e=0;b=b?1:0;for(;e<4;e+=2-b)c=bV[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function da(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.2",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o&&!o.call(" ")?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":(a+"").replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete")setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){var e=p.type(c);e==="function"&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&e!=="string"&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return a!=null?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||p.guid++:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")||(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.length,e=c.shift(),f=p._queueHooks(a,b),g=function(){p.dequeue(a,b)};e==="inprogress"&&(e=c.shift(),d--),e&&(b==="fx"&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)d=p._data(g[h],a+"queueHooks"),d&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)f.indexOf(" "+b[g]+" ")<0&&(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>=0)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>=0)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,d+""),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=b+""}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,needsContext:f&&p.expr.match.needsContext.test(f),namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=k.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click"))for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){h={},j=[];for(d=0;d<q;d++)l=o[d],m=l.selector,h[m]===b&&(h[m]=l.needsContext?p(m,this).index(f)>=0:p.find(m,this,null,[f]).length),h[m]&&j.push(l);j.length&&u.push({elem:f,matches:j})}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){i=u[d],c.currentTarget=i.elem;for(e=0;e<i.matches.length&&!c.isImmediatePropagationStopped();e++){l=i.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,g=((p.event.special[l.origType]||{}).handle||l.handler).apply(i.elem,r),g!==b&&(c.result=g,g===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),!V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length===1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bc(a,b,c,d){c=c||[],b=b||r;var e,f,i,j,k=b.nodeType;if(!a||typeof a!="string")return c;if(k!==1&&k!==9)return[];i=g(b);if(!i&&!d)if(e=P.exec(a))if(j=e[1]){if(k===9){f=b.getElementById(j);if(!f||!f.parentNode)return c;if(f.id===j)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(j))&&h(b,f)&&f.id===j)return c.push(f),c}else{if(e[2])return w.apply(c,x.call(b.getElementsByTagName(a),0)),c;if((j=e[3])&&_&&b.getElementsByClassName)return w.apply(c,x.call(b.getElementsByClassName(j),0)),c}return bp(a.replace(L,"$1"),b,c,d,i)}function bd(a){return function(b){var c=b.nodeName.toLowerCase();return c==="input"&&b.type===a}}function be(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}}function bf(a){return z(function(b){return b=+b,z(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function bg(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}function bh(a,b){var c,d,f,g,h,i,j,k=C[o][a];if(k)return b?0:k.slice(0);h=a,i=[],j=e.preFilter;while(h){if(!c||(d=M.exec(h)))d&&(h=h.slice(d[0].length)),i.push(f=[]);c=!1;if(d=N.exec(h))f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=d[0].replace(L," ");for(g in e.filter)(d=W[g].exec(h))&&(!j[g]||(d=j[g](d,r,!0)))&&(f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=g,c.matches=d);if(!c)break}return b?h.length:h?bc.error(a):C(a,i).slice(0)}function bi(a,b,d){var e=b.dir,f=d&&b.dir==="parentNode",g=u++;return b.first?function(b,c,d){while(b=b[e])if(f||b.nodeType===1)return a(b,c,d)}:function(b,d,h){if(!h){var i,j=t+" "+g+" ",k=j+c;while(b=b[e])if(f||b.nodeType===1){if((i=b[o])===k)return b.sizset;if(typeof i=="string"&&i.indexOf(j)===0){if(b.sizset)return b}else{b[o]=k;if(a(b,d,h))return b.sizset=!0,b;b.sizset=!1}}}else while(b=b[e])if(f||b.nodeType===1)if(a(b,d,h))return b}}function bj(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function bk(a,b,c,d,e){var f,g=[],h=0,i=a.length,j=b!=null;for(;h<i;h++)if(f=a[h])if(!c||c(f,d,e))g.push(f),j&&b.push(h);return g}function bl(a,b,c,d,e,f){return d&&!d[o]&&(d=bl(d)),e&&!e[o]&&(e=bl(e,f)),z(function(f,g,h,i){if(f&&e)return;var j,k,l,m=[],n=[],o=g.length,p=f||bo(b||"*",h.nodeType?[h]:h,[],f),q=a&&(f||!b)?bk(p,m,a,h,i):p,r=c?e||(f?a:o||d)?[]:g:q;c&&c(q,r,h,i);if(d){l=bk(r,n),d(l,[],h,i),j=l.length;while(j--)if(k=l[j])r[n[j]]=!(q[n[j]]=k)}if(f){j=a&&r.length;while(j--)if(k=r[j])f[m[j]]=!(g[m[j]]=k)}else r=bk(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):w.apply(g,r)})}function bm(a){var b,c,d,f=a.length,g=e.relative[a[0].type],h=g||e.relative[" "],i=g?1:0,j=bi(function(a){return a===b},h,!0),k=bi(function(a){return y.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==l)||((b=c).nodeType?j(a,c,d):k(a,c,d))}];for(;i<f;i++)if(c=e.relative[a[i].type])m=[bi(bj(m),c)];else{c=e.filter[a[i].type].apply(null,a[i].matches);if(c[o]){d=++i;for(;d<f;d++)if(e.relative[a[d].type])break;return bl(i>1&&bj(m),i>1&&a.slice(0,i-1).join("").replace(L,"$1"),c,i<d&&bm(a.slice(i,d)),d<f&&bm(a=a.slice(d)),d<f&&a.join(""))}m.push(c)}return bj(m)}function bn(a,b){var d=b.length>0,f=a.length>0,g=function(h,i,j,k,m){var n,o,p,q=[],s=0,u="0",x=h&&[],y=m!=null,z=l,A=h||f&&e.find.TAG("*",m&&i.parentNode||i),B=t+=z==null?1:Math.E;y&&(l=i!==r&&i,c=g.el);for(;(n=A[u])!=null;u++){if(f&&n){for(o=0;p=a[o];o++)if(p(n,i,j)){k.push(n);break}y&&(t=B,c=++g.el)}d&&((n=!p&&n)&&s--,h&&x.push(n))}s+=u;if(d&&u!==s){for(o=0;p=b[o];o++)p(x,q,i,j);if(h){if(s>0)while(u--)!x[u]&&!q[u]&&(q[u]=v.call(k));q=bk(q)}w.apply(k,q),y&&!h&&q.length>0&&s+b.length>1&&bc.uniqueSort(k)}return y&&(t=B,l=z),x};return g.el=0,d?z(g):g}function bo(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)bc(a,b[e],c,d);return c}function bp(a,b,c,d,f){var g,h,j,k,l,m=bh(a),n=m.length;if(!d&&m.length===1){h=m[0]=m[0].slice(0);if(h.length>2&&(j=h[0]).type==="ID"&&b.nodeType===9&&!f&&e.relative[h[1].type]){b=e.find.ID(j.matches[0].replace(V,""),b,f)[0];if(!b)return c;a=a.slice(h.shift().length)}for(g=W.POS.test(a)?-1:h.length-1;g>=0;g--){j=h[g];if(e.relative[k=j.type])break;if(l=e.find[k])if(d=l(j.matches[0].replace(V,""),R.test(h[0].type)&&b.parentNode||b,f)){h.splice(g,1),a=d.length&&h.join("");if(!a)return w.apply(c,x.call(d,0)),c;break}}}return i(a,m)(d,b,f,c,R.test(a)),c}function bq(){}var c,d,e,f,g,h,i,j,k,l,m=!0,n="undefined",o=("sizcache"+Math.random()).replace(".",""),q=String,r=a.document,s=r.documentElement,t=0,u=0,v=[].pop,w=[].push,x=[].slice,y=[].indexOf||function(a){var b=0,c=this.length;for(;b<c;b++)if(this[b]===a)return b;return-1},z=function(a,b){return a[o]=b==null||b,a},A=function(){var a={},b=[];return z(function(c,d){return b.push(c)>e.cacheLength&&delete a[b.shift()],a[c]=d},a)},B=A(),C=A(),D=A(),E="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",G=F.replace("w","w#"),H="([*^$|!~]?=)",I="\\["+E+"*("+F+")"+E+"*(?:"+H+E+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+G+")|)|)"+E+"*\\]",J=":("+F+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+I+")|[^:]|\\\\.)*|.*))\\)|)",K=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+E+"*((?:-\\d)?\\d*)"+E+"*\\)|)(?=[^-]|$)",L=new RegExp("^"+E+"+|((?:^|[^\\\\])(?:\\\\.)*)"+E+"+$","g"),M=new RegExp("^"+E+"*,"+E+"*"),N=new RegExp("^"+E+"*([\\x20\\t\\r\\n\\f>+~])"+E+"*"),O=new RegExp(J),P=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,Q=/^:not/,R=/[\x20\t\r\n\f]*[+~]/,S=/:not\($/,T=/h\d/i,U=/input|select|textarea|button/i,V=/\\(?!\\)/g,W={ID:new RegExp("^#("+F+")"),CLASS:new RegExp("^\\.("+F+")"),NAME:new RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:new RegExp("^("+F.replace("w","w*")+")"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+J),POS:new RegExp(K,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+E+"*(even|odd|(([+-]|)(\\d*)n|)"+E+"*(?:([+-]|)"+E+"*(\\d+)|))"+E+"*\\)|)","i"),needsContext:new RegExp("^"+E+"*[>+~]|"+K,"i")},X=function(a){var b=r.createElement("div");try{return a(b)}catch(c){return!1}finally{b=null}},Y=X(function(a){return a.appendChild(r.createComment("")),!a.getElementsByTagName("*").length}),Z=X(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==n&&a.firstChild.getAttribute("href")==="#"}),$=X(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),_=X(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||!a.getElementsByClassName("e").length?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length===2)}),ba=X(function(a){a.id=o+0,a.innerHTML="<a name='"+o+"'></a><div name='"+o+"'></div>",s.insertBefore(a,s.firstChild);var b=r.getElementsByName&&r.getElementsByName(o).length===2+r.getElementsByName(o+0).length;return d=!r.getElementById(o),s.removeChild(a),b});try{x.call(s.childNodes,0)[0].nodeType}catch(bb){x=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}bc.matches=function(a,b){return bc(a,null,null,b)},bc.matchesSelector=function(a,b){return bc(b,null,null,[a]).length>0},f=bc.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=f(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=f(b);return c},g=bc.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},h=bc.contains=s.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:s.compareDocumentPosition?function(a,b){return b&&!!(a.compareDocumentPosition(b)&16)}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc.attr=function(a,b){var c,d=g(a);return d||(b=b.toLowerCase()),(c=e.attrHandle[b])?c(a):d||$?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},e=bc.selectors={cacheLength:50,createPseudo:z,match:W,attrHandle:Z?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},find:{ID:d?function(a,b,c){if(typeof b.getElementById!==n&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==n&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==n&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:Y?function(a,b){if(typeof b.getElementsByTagName!==n)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c},NAME:ba&&function(a,b){if(typeof b.getElementsByName!==n)return b.getElementsByName(name)},CLASS:_&&function(a,b,c){if(typeof b.getElementsByClassName!==n&&!c)return b.getElementsByClassName(a)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(V,""),a[3]=(a[4]||a[5]||"").replace(V,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||bc.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&bc.error(a[0]),a},PSEUDO:function(a){var b,c;if(W.CHILD.test(a[0]))return null;if(a[3])a[2]=a[3];else if(b=a[4])O.test(b)&&(c=bh(b,!0))&&(c=b.indexOf(")",b.length-c)-b.length)&&(b=b.slice(0,c),a[0]=a[0].slice(0,c)),a[2]=b;return a.slice(0,3)}},filter:{ID:d?function(a){return a=a.replace(V,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(V,""),function(b){var c=typeof b.getAttributeNode!==n&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(V,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=B[o][a];return b||(b=B(a,new RegExp("(^|"+E+")"+a+"("+E+"|$)"))),function(a){return b.test(a.className||typeof a.getAttribute!==n&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return function(d,e){var f=bc.attr(d,a);return f==null?b==="!=":b?(f+="",b==="="?f===c:b==="!="?f!==c:b==="^="?c&&f.indexOf(c)===0:b==="*="?c&&f.indexOf(c)>-1:b==="$="?c&&f.substr(f.length-c.length)===c:b==="~="?(" "+f+" ").indexOf(c)>-1:b==="|="?f===c||f.substr(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d){return a==="nth"?function(a){var b,e,f=a.parentNode;if(c===1&&d===0)return!0;if(f){e=0;for(b=f.firstChild;b;b=b.nextSibling)if(b.nodeType===1){e++;if(a===b)break}}return e-=d,e===c||e%c===0&&e/c>=0}:function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b){var c,d=e.pseudos[a]||e.setFilters[a.toLowerCase()]||bc.error("unsupported pseudo: "+a);return d[o]?d(b):d.length>1?(c=[a,a,"",b],e.setFilters.hasOwnProperty(a.toLowerCase())?z(function(a,c){var e,f=d(a,b),g=f.length;while(g--)e=y.call(a,f[g]),a[e]=!(c[e]=f[g])}):function(a){return d(a,0,c)}):d}},pseudos:{not:z(function(a){var b=[],c=[],d=i(a.replace(L,"$1"));return d[o]?z(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)if(f=g[h])a[h]=!(b[h]=f)}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:z(function(a){return function(b){return bc(a,b).length>0}}),contains:z(function(a){return function(b){return(b.textContent||b.innerText||f(b)).indexOf(a)>-1}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!e.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},header:function(a){return T.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:bd("radio"),checkbox:bd("checkbox"),file:bd("file"),password:bd("password"),image:bd("image"),submit:be("submit"),reset:be("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return U.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement},first:bf(function(a,b,c){return[0]}),last:bf(function(a,b,c){return[b-1]}),eq:bf(function(a,b,c){return[c<0?c+b:c]}),even:bf(function(a,b,c){for(var d=0;d<b;d+=2)a.push(d);return a}),odd:bf(function(a,b,c){for(var d=1;d<b;d+=2)a.push(d);return a}),lt:bf(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:bf(function(a,b,c){for(var d=c<0?c+b:c;++d<b;)a.push(d);return a})}},j=s.compareDocumentPosition?function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,h=b.parentNode,i=g;if(g===h)return bg(a,b);if(!g)return-1;if(!h)return 1;while(i)e.unshift(i),i=i.parentNode;i=h;while(i)f.unshift(i),i=i.parentNode;c=e.length,d=f.length;for(var j=0;j<c&&j<d;j++)if(e[j]!==f[j])return bg(e[j],f[j]);return j===c?bg(a,f[j],-1):bg(e[j],b,1)},[0,0].sort(j),m=!k,bc.uniqueSort=function(a){var b,c=1;k=m,a.sort(j);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1);return a},bc.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},i=bc.compile=function(a,b){var c,d=[],e=[],f=D[o][a];if(!f){b||(b=bh(a)),c=b.length;while(c--)f=bm(b[c]),f[o]?d.push(f):e.push(f);f=D(a,bn(e,d))}return f},r.querySelectorAll&&function(){var a,b=bp,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[":focus"],f=[":active",":focus"],h=s.matchesSelector||s.mozMatchesSelector||s.webkitMatchesSelector||s.oMatchesSelector||s.msMatchesSelector;X(function(a){a.innerHTML="<select><option selected=''></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+E+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),X(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+E+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'/>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=new RegExp(e.join("|")),bp=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a))){var i,j,k=!0,l=o,m=d,n=d.nodeType===9&&a;if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){i=bh(a),(k=d.getAttribute("id"))?l=k.replace(c,"\\$&"):d.setAttribute("id",l),l="[id='"+l+"'] ",j=i.length;while(j--)i[j]=l+i[j].join("");m=R.test(a)&&d.parentNode||d,n=i.join(",")}if(n)try{return w.apply(f,x.call(m.querySelectorAll(n),0)),f}catch(p){}finally{k||d.removeAttribute("id")}}return b(a,d,f,g,h)},h&&(X(function(b){a=h.call(b,"div");try{h.call(b,"[test!='']:sizzle"),f.push("!=",J)}catch(c){}}),f=new RegExp(f.join("|")),bc.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!g(b)&&!f.test(c)&&(!e||!e.test(c)))try{var i=h.call(b,c);if(i||a||b.document&&b.document.nodeType!==11)return i}catch(j){}return bc(c,null,null,[b]).length>0})}(),e.pseudos.nth=e.pseudos.eq,e.filters=bq.prototype=e.pseudos,e.setFilters=new bq,bc.attr=p.attr,p.find=bc,p.expr=bc.selectors,p.expr[":"]=p.expr.pseudos,p.unique=bc.uniqueSort,p.text=bc.getText,p.isXMLDoc=bc.isXML,p.contains=bc.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=!c.nodeType&&c[0]||c,c=c.ownerDocument||c,a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=b===e&&bA,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(f=0;(h=a[f])!=null;f++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{s=s||bk(b),l=b.createElement("div"),s.appendChild(l),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(g=n.length-1;g>=0;--g)p.nodeName(n[g],"tbody")&&!n[g].childNodes.length&&n[g].parentNode.removeChild(n[g])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l.parentNode.removeChild(l)}h.nodeType?t.push(h):p.merge(t,h)}l&&(h=l=s=null);if(!p.support.appendChecked)for(f=0;(h=t[f])!=null;f++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(f=0;(h=t[f])!=null;f++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[f+1,0].concat(r)),f+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.chrome?b.webkit=!0:b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^(none|table(?!-c[ea]).+)/,bO=/^margin/,bP=new RegExp("^("+q+")(.*)$","i"),bQ=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bR=new RegExp("^([-+])=("+q+")","i"),bS={},bT={position:"absolute",visibility:"hidden",display:"block"},bU={letterSpacing:0,fontWeight:400},bV=["Top","Right","Bottom","Left"],bW=["Webkit","O","Moz","ms"],bX=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return b$(this,!0)},hide:function(){return b$(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bX.apply(this,arguments):this.each(function(){(c?a:bZ(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bY(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bR.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bY(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bU&&(f=bU[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h[c],d===""&&!p.contains(b.ownerDocument,b)&&(d=p.style(b,c)),bQ.test(d)&&bO.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bQ.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth===0&&bN.test(bH(a,"display"))?p.swap(a,bT,function(){return cb(a,b,d)}):cb(a,b,d)},set:function(a,c,d){return b_(a,c,d?ca(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bQ.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bV[d]+b]=e[d]||e[d-2]||e[0];return f}},bO.test(a)||(p.cssHooks[a+b].set=b_)});var cd=/%20/g,ce=/\[\]$/,cf=/\r?\n/g,cg=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ch=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ch.test(this.nodeName)||cg.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(cf,"\r\n")}}):{name:b.name,value:c.replace(cf,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ci(d,a[d],c,f);return e.join("&").replace(cd,"+")};var cj,ck,cl=/#.*$/,cm=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,co=/^(?:GET|HEAD)$/,cp=/^\/\//,cq=/\?/,cr=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cs=/([?&])_=[^&]*/,ct=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,cu=p.fn.load,cv={},cw={},cx=["*/"]+["*"];try{ck=f.href}catch(cy){ck=e.createElement("a"),ck.href="",ck=ck.href}cj=ct.exec(ck.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&cu)return cu.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):c&&typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cr,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cB(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cB(a,b),a},ajaxSettings:{url:ck,isLocal:cn.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cx},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cz(cv),ajaxTransport:cz(cw),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cC(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cD(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=(c||y)+"",k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cm.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(cl,"").replace(cp,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=ct.exec(l.url.toLowerCase())||!1,l.crossDomain=i&&i.join(":")+(i[3]?"":i[1]==="http:"?80:443)!==cj.join(":")+(cj[3]?"":cj[1]==="http:"?80:443)),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cA(cv,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!co.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cq.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cs,"$1_="+z);l.url=A+(A===l.url?(cq.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cx+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cA(cw,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cE=[],cF=/\?/,cG=/(=)\?(?=&|$)|\?\?/,cH=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cE.pop()||p.expando+"_"+cH++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cG.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cG.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cG,"$1"+f):m?c.data=i.replace(cG,"$1"+f):k&&(c.url+=(cF.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cE.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cI,cJ=a.ActiveXObject?function(){for(var a in cI)cI[a](0,1)}:!1,cK=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cL()||cM()}:cL,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cJ&&delete cI[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cK,cJ&&(cI||(cI={},p(a).unload(cJ)),cI[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cN,cO,cP=/^(?:toggle|show|hide)$/,cQ=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cR=/queueHooks$/,cS=[cY],cT={"*":[function(a,b){var c,d,e=this.createTween(a,b),f=cQ.exec(b),g=e.cur(),h=+g||0,i=1,j=20;if(f){c=+f[2],d=f[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&h){h=p.css(e.elem,a,!0)||c||1;do i=i||".5",h=h/i,p.style(e.elem,a,h+d);while(i!==(i=e.cur()/g)&&i!==1&&--j)}e.unit=d,e.start=h,e.end=f[1]?h+(f[1]+1)*c:c}return e}]};p.Animation=p.extend(cW,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cT[c]=cT[c]||[],cT[c].unshift(b)},prefilter:function(a,b){b?cS.unshift(a):cS.push(a)}}),p.Tween=cZ,cZ.prototype={constructor:cZ,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cZ.propHooks[this.prop];return a&&a.get?a.get(this):cZ.propHooks._default.get(this)},run:function(a){var b,c=cZ.propHooks[this.prop];return this.options.duration?this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cZ.propHooks._default.set(this),this}},cZ.prototype.init.prototype=cZ.prototype,cZ.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cZ.propHooks.scrollTop=cZ.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(c$(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bZ).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cW(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cR.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:c$("show"),slideUp:c$("hide"),slideToggle:c$("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cZ.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cO&&(cO=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cO),cO=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c_=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j={top:0,left:0},k=this[0],l=k&&k.ownerDocument;if(!l)return;return(d=l.body)===k?p.offset.bodyOffset(k):(c=l.documentElement,p.contains(c,k)?(typeof k.getBoundingClientRect!="undefined"&&(j=k.getBoundingClientRect()),e=da(l),f=c.clientTop||d.clientTop||0,g=c.clientLeft||d.clientLeft||0,h=e.pageYOffset||c.scrollTop,i=e.pageXOffset||c.scrollLeft,{top:j.top+h-f,left:j.left+i-g}):j)},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c_.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c_.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=da(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g,null)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window); \ No newline at end of file
+/*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */
+!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;
+
+return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?aa:ba):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=ba;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=ba),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function La(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fa(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ua(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qa.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Na.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ia(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Va(this,!0)},hide:function(){return Va(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Za(a,b,c,d,e){
+return new Za.prototype.init(a,b,c,d,e)}m.Tween=Za,Za.prototype={constructor:Za,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Za.propHooks.scrollTop=Za.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ab.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fa(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hb(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$a||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kb,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kb(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lb=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lb,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nb:mb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},ob.id=ob.name=ob.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sb.test(a.nodeName)||tb.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var ub=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mb(a,b,c,d){var e={},f=a===Ib;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nb(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Ob(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cb.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jb+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mb(Ib,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Ob(k,v,c)),u=Pb(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Ub.test(this.nodeName)&&!Tb.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xb[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_b.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m}); \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/packages/noUiSlider/nouislider.css b/wqflask/wqflask/static/new/packages/noUiSlider/nouislider.css
new file mode 100644
index 00000000..d07b87f6
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/noUiSlider/nouislider.css
@@ -0,0 +1,162 @@
+
+/* Functional styling;
+ * These styles are required for noUiSlider to function.
+ * You don't need to change these rules to apply your design.
+ */
+.noUi-target,
+.noUi-target * {
+-webkit-touch-callout: none;
+-webkit-user-select: none;
+-ms-touch-action: none;
+-ms-user-select: none;
+-moz-user-select: none;
+-moz-box-sizing: border-box;
+ box-sizing: border-box;
+}
+.noUi-target {
+ position: relative;
+ direction: ltr;
+}
+.noUi-base {
+ width: 100%;
+ height: 100%;
+ position: relative;
+ z-index: 1; /* Fix 401 */
+}
+.noUi-origin {
+ position: absolute;
+ right: 0;
+ top: 0;
+ left: 0;
+ bottom: 0;
+}
+.noUi-handle {
+ position: relative;
+ z-index: 1;
+}
+.noUi-stacking .noUi-handle {
+/* This class is applied to the lower origin when
+ its values is > 50%. */
+ z-index: 10;
+}
+.noUi-state-tap .noUi-origin {
+-webkit-transition: left 0.3s, top 0.3s;
+ transition: left 0.3s, top 0.3s;
+}
+.noUi-state-drag * {
+ cursor: inherit !important;
+}
+
+/* Painting and performance;
+ * Browsers can paint handles in their own layer.
+ */
+.noUi-base {
+ -webkit-transform: translate3d(0,0,0);
+ transform: translate3d(0,0,0);
+}
+
+/* Slider size and handle placement;
+ */
+.noUi-horizontal {
+ height: 18px;
+}
+.noUi-horizontal .noUi-handle {
+ width: 34px;
+ height: 28px;
+ left: -17px;
+ top: -6px;
+}
+.noUi-vertical {
+ width: 18px;
+}
+.noUi-vertical .noUi-handle {
+ width: 28px;
+ height: 34px;
+ left: -6px;
+ top: -17px;
+}
+
+/* Styling;
+ */
+.noUi-background {
+ background: #FAFAFA;
+ box-shadow: inset 0 1px 1px #f0f0f0;
+}
+.noUi-connect {
+ background: #3FB8AF;
+ box-shadow: inset 0 0 3px rgba(51,51,51,0.45);
+-webkit-transition: background 450ms;
+ transition: background 450ms;
+}
+.noUi-origin {
+ border-radius: 2px;
+}
+.noUi-target {
+ border-radius: 4px;
+ border: 1px solid #D3D3D3;
+ box-shadow: inset 0 1px 1px #F0F0F0, 0 3px 6px -5px #BBB;
+}
+.noUi-target.noUi-connect {
+ box-shadow: inset 0 0 3px rgba(51,51,51,0.45), 0 3px 6px -5px #BBB;
+}
+
+/* Handles and cursors;
+ */
+.noUi-dragable {
+ cursor: w-resize;
+}
+.noUi-vertical .noUi-dragable {
+ cursor: n-resize;
+}
+.noUi-handle {
+ border: 1px solid #D9D9D9;
+ border-radius: 3px;
+ background: #FFF;
+ cursor: default;
+ box-shadow: inset 0 0 1px #FFF,
+ inset 0 1px 7px #EBEBEB,
+ 0 3px 6px -3px #BBB;
+}
+.noUi-active {
+ box-shadow: inset 0 0 1px #FFF,
+ inset 0 1px 7px #DDD,
+ 0 3px 6px -3px #BBB;
+}
+
+/* Handle stripes;
+ */
+.noUi-handle:before,
+.noUi-handle:after {
+ content: "";
+ display: block;
+ position: absolute;
+ height: 14px;
+ width: 1px;
+ background: #E8E7E6;
+ left: 14px;
+ top: 6px;
+}
+.noUi-handle:after {
+ left: 17px;
+}
+.noUi-vertical .noUi-handle:before,
+.noUi-vertical .noUi-handle:after {
+ width: 14px;
+ height: 1px;
+ left: 6px;
+ top: 14px;
+}
+.noUi-vertical .noUi-handle:after {
+ top: 17px;
+}
+
+/* Disabled state;
+ */
+[disabled].noUi-connect,
+[disabled] .noUi-connect {
+ background: #B8B8B8;
+}
+[disabled].noUi-origin,
+[disabled] .noUi-handle {
+ cursor: not-allowed;
+}
diff --git a/wqflask/wqflask/static/new/packages/noUiSlider/nouislider.js b/wqflask/wqflask/static/new/packages/noUiSlider/nouislider.js
new file mode 100644
index 00000000..67ae7549
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/noUiSlider/nouislider.js
@@ -0,0 +1,1629 @@
+/*! nouislider - 8.0.2 - 2015-07-06 13:22:09 */
+
+/*jslint browser: true */
+/*jslint white: true */
+
+(function (factory) {
+
+ if ( typeof define === 'function' && define.amd ) {
+
+ // AMD. Register as an anonymous module.
+ define([], factory);
+
+ } else if ( typeof exports === 'object' ) {
+
+ var fs = require('fs');
+
+ // Node/CommonJS
+ module.exports = factory();
+ module.exports.css = function () {
+ return fs.readFileSync(__dirname + '/nouislider.min.css', 'utf8');
+ };
+
+ } else {
+
+ // Browser globals
+ window.noUiSlider = factory();
+ }
+
+}(function( ){
+
+ 'use strict';
+
+
+ // Removes duplicates from an array.
+ function unique(array) {
+ return array.filter(function(a){
+ return !this[a] ? this[a] = true : false;
+ }, {});
+ }
+
+ // Round a value to the closest 'to'.
+ function closest ( value, to ) {
+ return Math.round(value / to) * to;
+ }
+
+ // Current position of an element relative to the document.
+ function offset ( elem ) {
+
+ var rect = elem.getBoundingClientRect(),
+ doc = elem.ownerDocument,
+ win = doc.defaultView || doc.parentWindow,
+ docElem = doc.documentElement,
+ xOff = win.pageXOffset;
+
+ // getBoundingClientRect contains left scroll in Chrome on Android.
+ // I haven't found a feature detection that proves this. Worst case
+ // scenario on mis-match: the 'tap' feature on horizontal sliders breaks.
+ if ( /webkit.*Chrome.*Mobile/i.test(navigator.userAgent) ) {
+ xOff = 0;
+ }
+
+ return {
+ top: rect.top + win.pageYOffset - docElem.clientTop,
+ left: rect.left + xOff - docElem.clientLeft
+ };
+ }
+
+ // Checks whether a value is numerical.
+ function isNumeric ( a ) {
+ return typeof a === 'number' && !isNaN( a ) && isFinite( a );
+ }
+
+ // Rounds a number to 7 supported decimals.
+ function accurateNumber( number ) {
+ var p = Math.pow(10, 7);
+ return Number((Math.round(number*p)/p).toFixed(7));
+ }
+
+ // Sets a class and removes it after [duration] ms.
+ function addClassFor ( element, className, duration ) {
+ addClass(element, className);
+ setTimeout(function(){
+ removeClass(element, className);
+ }, duration);
+ }
+
+ // Limits a value to 0 - 100
+ function limit ( a ) {
+ return Math.max(Math.min(a, 100), 0);
+ }
+
+ // Wraps a variable as an array, if it isn't one yet.
+ function asArray ( a ) {
+ return Array.isArray(a) ? a : [a];
+ }
+
+ // Counts decimals
+ function countDecimals ( numStr ) {
+ var pieces = numStr.split(".");
+ return pieces.length > 1 ? pieces[1].length : 0;
+ }
+
+ // http://youmightnotneedjquery.com/#add_class
+ function addClass ( el, className ) {
+ if ( el.classList ) {
+ el.classList.add(className);
+ } else {
+ el.className += ' ' + className;
+ }
+ }
+
+ // http://youmightnotneedjquery.com/#remove_class
+ function removeClass ( el, className ) {
+ if ( el.classList ) {
+ el.classList.remove(className);
+ } else {
+ el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
+ }
+ }
+
+ // http://youmightnotneedjquery.com/#has_class
+ function hasClass ( el, className ) {
+ if ( el.classList ) {
+ el.classList.contains(className);
+ } else {
+ new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
+ }
+ }
+
+
+ var
+ // Determine the events to bind. IE11 implements pointerEvents without
+ // a prefix, which breaks compatibility with the IE10 implementation.
+ /** @const */
+ actions = window.navigator.pointerEnabled ? {
+ start: 'pointerdown',
+ move: 'pointermove',
+ end: 'pointerup'
+ } : window.navigator.msPointerEnabled ? {
+ start: 'MSPointerDown',
+ move: 'MSPointerMove',
+ end: 'MSPointerUp'
+ } : {
+ start: 'mousedown touchstart',
+ move: 'mousemove touchmove',
+ end: 'mouseup touchend'
+ },
+ // Re-usable list of classes;
+ /** @const */
+ Classes = [
+/* 0 */ 'noUi-target'
+/* 1 */ ,'noUi-base'
+/* 2 */ ,'noUi-origin'
+/* 3 */ ,'noUi-handle'
+/* 4 */ ,'noUi-horizontal'
+/* 5 */ ,'noUi-vertical'
+/* 6 */ ,'noUi-background'
+/* 7 */ ,'noUi-connect'
+/* 8 */ ,'noUi-ltr'
+/* 9 */ ,'noUi-rtl'
+/* 10 */ ,'noUi-dragable'
+/* 11 */ ,''
+/* 12 */ ,'noUi-state-drag'
+/* 13 */ ,''
+/* 14 */ ,'noUi-state-tap'
+/* 15 */ ,'noUi-active'
+/* 16 */ ,''
+/* 17 */ ,'noUi-stacking'
+ ];
+
+
+// Value calculation
+
+ // Determine the size of a sub-range in relation to a full range.
+ function subRangeRatio ( pa, pb ) {
+ return (100 / (pb - pa));
+ }
+
+ // (percentage) How many percent is this value of this range?
+ function fromPercentage ( range, value ) {
+ return (value * 100) / ( range[1] - range[0] );
+ }
+
+ // (percentage) Where is this value on this range?
+ function toPercentage ( range, value ) {
+ return fromPercentage( range, range[0] < 0 ?
+ value + Math.abs(range[0]) :
+ value - range[0] );
+ }
+
+ // (value) How much is this percentage on this range?
+ function isPercentage ( range, value ) {
+ return ((value * ( range[1] - range[0] )) / 100) + range[0];
+ }
+
+
+// Range conversion
+
+ function getJ ( value, arr ) {
+
+ var j = 1;
+
+ while ( value >= arr[j] ){
+ j += 1;
+ }
+
+ return j;
+ }
+
+ // (percentage) Input a value, find where, on a scale of 0-100, it applies.
+ function toStepping ( xVal, xPct, value ) {
+
+ if ( value >= xVal.slice(-1)[0] ){
+ return 100;
+ }
+
+ var j = getJ( value, xVal ), va, vb, pa, pb;
+
+ va = xVal[j-1];
+ vb = xVal[j];
+ pa = xPct[j-1];
+ pb = xPct[j];
+
+ return pa + (toPercentage([va, vb], value) / subRangeRatio (pa, pb));
+ }
+
+ // (value) Input a percentage, find where it is on the specified range.
+ function fromStepping ( xVal, xPct, value ) {
+
+ // There is no range group that fits 100
+ if ( value >= 100 ){
+ return xVal.slice(-1)[0];
+ }
+
+ var j = getJ( value, xPct ), va, vb, pa, pb;
+
+ va = xVal[j-1];
+ vb = xVal[j];
+ pa = xPct[j-1];
+ pb = xPct[j];
+
+ return isPercentage([va, vb], (value - pa) * subRangeRatio (pa, pb));
+ }
+
+ // (percentage) Get the step that applies at a certain value.
+ function getStep ( xPct, xSteps, snap, value ) {
+
+ if ( value === 100 ) {
+ return value;
+ }
+
+ var j = getJ( value, xPct ), a, b;
+
+ // If 'snap' is set, steps are used as fixed points on the slider.
+ if ( snap ) {
+
+ a = xPct[j-1];
+ b = xPct[j];
+
+ // Find the closest position, a or b.
+ if ((value - a) > ((b-a)/2)){
+ return b;
+ }
+
+ return a;
+ }
+
+ if ( !xSteps[j-1] ){
+ return value;
+ }
+
+ return xPct[j-1] + closest(
+ value - xPct[j-1],
+ xSteps[j-1]
+ );
+ }
+
+
+// Entry parsing
+
+ function handleEntryPoint ( index, value, that ) {
+
+ var percentage;
+
+ // Wrap numerical input in an array.
+ if ( typeof value === "number" ) {
+ value = [value];
+ }
+
+ // Reject any invalid input, by testing whether value is an array.
+ if ( Object.prototype.toString.call( value ) !== '[object Array]' ){
+ throw new Error("noUiSlider: 'range' contains invalid value.");
+ }
+
+ // Covert min/max syntax to 0 and 100.
+ if ( index === 'min' ) {
+ percentage = 0;
+ } else if ( index === 'max' ) {
+ percentage = 100;
+ } else {
+ percentage = parseFloat( index );
+ }
+
+ // Check for correct input.
+ if ( !isNumeric( percentage ) || !isNumeric( value[0] ) ) {
+ throw new Error("noUiSlider: 'range' value isn't numeric.");
+ }
+
+ // Store values.
+ that.xPct.push( percentage );
+ that.xVal.push( value[0] );
+
+ // NaN will evaluate to false too, but to keep
+ // logging clear, set step explicitly. Make sure
+ // not to override the 'step' setting with false.
+ if ( !percentage ) {
+ if ( !isNaN( value[1] ) ) {
+ that.xSteps[0] = value[1];
+ }
+ } else {
+ that.xSteps.push( isNaN(value[1]) ? false : value[1] );
+ }
+ }
+
+ function handleStepPoint ( i, n, that ) {
+
+ // Ignore 'false' stepping.
+ if ( !n ) {
+ return true;
+ }
+
+ // Factor to range ratio
+ that.xSteps[i] = fromPercentage([
+ that.xVal[i]
+ ,that.xVal[i+1]
+ ], n) / subRangeRatio (
+ that.xPct[i],
+ that.xPct[i+1] );
+ }
+
+
+// Interface
+
+ // The interface to Spectrum handles all direction-based
+ // conversions, so the above values are unaware.
+
+ function Spectrum ( entry, snap, direction, singleStep ) {
+
+ this.xPct = [];
+ this.xVal = [];
+ this.xSteps = [ singleStep || false ];
+ this.xNumSteps = [ false ];
+
+ this.snap = snap;
+ this.direction = direction;
+
+ var index, ordered = [ /* [0, 'min'], [1, '50%'], [2, 'max'] */ ];
+
+ // Map the object keys to an array.
+ for ( index in entry ) {
+ if ( entry.hasOwnProperty(index) ) {
+ ordered.push([entry[index], index]);
+ }
+ }
+
+ // Sort all entries by value (numeric sort).
+ ordered.sort(function(a, b) { return a[0] - b[0]; });
+
+ // Convert all entries to subranges.
+ for ( index = 0; index < ordered.length; index++ ) {
+ handleEntryPoint(ordered[index][1], ordered[index][0], this);
+ }
+
+ // Store the actual step values.
+ // xSteps is sorted in the same order as xPct and xVal.
+ this.xNumSteps = this.xSteps.slice(0);
+
+ // Convert all numeric steps to the percentage of the subrange they represent.
+ for ( index = 0; index < this.xNumSteps.length; index++ ) {
+ handleStepPoint(index, this.xNumSteps[index], this);
+ }
+ }
+
+ Spectrum.prototype.getMargin = function ( value ) {
+ return this.xPct.length === 2 ? fromPercentage(this.xVal, value) : false;
+ };
+
+ Spectrum.prototype.toStepping = function ( value ) {
+
+ value = toStepping( this.xVal, this.xPct, value );
+
+ // Invert the value if this is a right-to-left slider.
+ if ( this.direction ) {
+ value = 100 - value;
+ }
+
+ return value;
+ };
+
+ Spectrum.prototype.fromStepping = function ( value ) {
+
+ // Invert the value if this is a right-to-left slider.
+ if ( this.direction ) {
+ value = 100 - value;
+ }
+
+ return accurateNumber(fromStepping( this.xVal, this.xPct, value ));
+ };
+
+ Spectrum.prototype.getStep = function ( value ) {
+
+ // Find the proper step for rtl sliders by search in inverse direction.
+ // Fixes issue #262.
+ if ( this.direction ) {
+ value = 100 - value;
+ }
+
+ value = getStep(this.xPct, this.xSteps, this.snap, value );
+
+ if ( this.direction ) {
+ value = 100 - value;
+ }
+
+ return value;
+ };
+
+ Spectrum.prototype.getApplicableStep = function ( value ) {
+
+ // If the value is 100%, return the negative step twice.
+ var j = getJ(value, this.xPct), offset = value === 100 ? 2 : 1;
+ return [this.xNumSteps[j-2], this.xVal[j-offset], this.xNumSteps[j-offset]];
+ };
+
+ // Outside testing
+ Spectrum.prototype.convert = function ( value ) {
+ return this.getStep(this.toStepping(value));
+ };
+
+/* Every input option is tested and parsed. This'll prevent
+ endless validation in internal methods. These tests are
+ structured with an item for every option available. An
+ option can be marked as required by setting the 'r' flag.
+ The testing function is provided with three arguments:
+ - The provided value for the option;
+ - A reference to the options object;
+ - The name for the option;
+
+ The testing function returns false when an error is detected,
+ or true when everything is OK. It can also modify the option
+ object, to make sure all values can be correctly looped elsewhere. */
+
+ var defaultFormatter = { 'to': function( value ){
+ return value.toFixed(2);
+ }, 'from': Number };
+
+ function testStep ( parsed, entry ) {
+
+ if ( !isNumeric( entry ) ) {
+ throw new Error("noUiSlider: 'step' is not numeric.");
+ }
+
+ // The step option can still be used to set stepping
+ // for linear sliders. Overwritten if set in 'range'.
+ parsed.singleStep = entry;
+ }
+
+ function testRange ( parsed, entry ) {
+
+ // Filter incorrect input.
+ if ( typeof entry !== 'object' || Array.isArray(entry) ) {
+ throw new Error("noUiSlider: 'range' is not an object.");
+ }
+
+ // Catch missing start or end.
+ if ( entry.min === undefined || entry.max === undefined ) {
+ throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");
+ }
+
+ parsed.spectrum = new Spectrum(entry, parsed.snap, parsed.dir, parsed.singleStep);
+ }
+
+ function testStart ( parsed, entry ) {
+
+ entry = asArray(entry);
+
+ // Validate input. Values aren't tested, as the public .val method
+ // will always provide a valid location.
+ if ( !Array.isArray( entry ) || !entry.length || entry.length > 2 ) {
+ throw new Error("noUiSlider: 'start' option is incorrect.");
+ }
+
+ // Store the number of handles.
+ parsed.handles = entry.length;
+
+ // When the slider is initialized, the .val method will
+ // be called with the start options.
+ parsed.start = entry;
+ }
+
+ function testSnap ( parsed, entry ) {
+
+ // Enforce 100% stepping within subranges.
+ parsed.snap = entry;
+
+ if ( typeof entry !== 'boolean' ){
+ throw new Error("noUiSlider: 'snap' option must be a boolean.");
+ }
+ }
+
+ function testAnimate ( parsed, entry ) {
+
+ // Enforce 100% stepping within subranges.
+ parsed.animate = entry;
+
+ if ( typeof entry !== 'boolean' ){
+ throw new Error("noUiSlider: 'animate' option must be a boolean.");
+ }
+ }
+
+ function testConnect ( parsed, entry ) {
+
+ if ( entry === 'lower' && parsed.handles === 1 ) {
+ parsed.connect = 1;
+ } else if ( entry === 'upper' && parsed.handles === 1 ) {
+ parsed.connect = 2;
+ } else if ( entry === true && parsed.handles === 2 ) {
+ parsed.connect = 3;
+ } else if ( entry === false ) {
+ parsed.connect = 0;
+ } else {
+ throw new Error("noUiSlider: 'connect' option doesn't match handle count.");
+ }
+ }
+
+ function testOrientation ( parsed, entry ) {
+
+ // Set orientation to an a numerical value for easy
+ // array selection.
+ switch ( entry ){
+ case 'horizontal':
+ parsed.ort = 0;
+ break;
+ case 'vertical':
+ parsed.ort = 1;
+ break;
+ default:
+ throw new Error("noUiSlider: 'orientation' option is invalid.");
+ }
+ }
+
+ function testMargin ( parsed, entry ) {
+
+ if ( !isNumeric(entry) ){
+ throw new Error("noUiSlider: 'margin' option must be numeric.");
+ }
+
+ parsed.margin = parsed.spectrum.getMargin(entry);
+
+ if ( !parsed.margin ) {
+ throw new Error("noUiSlider: 'margin' option is only supported on linear sliders.");
+ }
+ }
+
+ function testLimit ( parsed, entry ) {
+
+ if ( !isNumeric(entry) ){
+ throw new Error("noUiSlider: 'limit' option must be numeric.");
+ }
+
+ parsed.limit = parsed.spectrum.getMargin(entry);
+
+ if ( !parsed.limit ) {
+ throw new Error("noUiSlider: 'limit' option is only supported on linear sliders.");
+ }
+ }
+
+ function testDirection ( parsed, entry ) {
+
+ // Set direction as a numerical value for easy parsing.
+ // Invert connection for RTL sliders, so that the proper
+ // handles get the connect/background classes.
+ switch ( entry ) {
+ case 'ltr':
+ parsed.dir = 0;
+ break;
+ case 'rtl':
+ parsed.dir = 1;
+ parsed.connect = [0,2,1,3][parsed.connect];
+ break;
+ default:
+ throw new Error("noUiSlider: 'direction' option was not recognized.");
+ }
+ }
+
+ function testBehaviour ( parsed, entry ) {
+
+ // Make sure the input is a string.
+ if ( typeof entry !== 'string' ) {
+ throw new Error("noUiSlider: 'behaviour' must be a string containing options.");
+ }
+
+ // Check if the string contains any keywords.
+ // None are required.
+ var tap = entry.indexOf('tap') >= 0,
+ drag = entry.indexOf('drag') >= 0,
+ fixed = entry.indexOf('fixed') >= 0,
+ snap = entry.indexOf('snap') >= 0;
+
+ parsed.events = {
+ tap: tap || snap,
+ drag: drag,
+ fixed: fixed,
+ snap: snap
+ };
+ }
+
+ function testFormat ( parsed, entry ) {
+
+ parsed.format = entry;
+
+ // Any object with a to and from method is supported.
+ if ( typeof entry.to === 'function' && typeof entry.from === 'function' ) {
+ return true;
+ }
+
+ throw new Error( "noUiSlider: 'format' requires 'to' and 'from' methods.");
+ }
+
+ // Test all developer settings and parse to assumption-safe values.
+ function testOptions ( options ) {
+
+ var parsed = {
+ margin: 0,
+ limit: 0,
+ animate: true,
+ format: defaultFormatter
+ }, tests;
+
+ // Tests are executed in the order they are presented here.
+ tests = {
+ 'step': { r: false, t: testStep },
+ 'start': { r: true, t: testStart },
+ 'connect': { r: true, t: testConnect },
+ 'direction': { r: true, t: testDirection },
+ 'snap': { r: false, t: testSnap },
+ 'animate': { r: false, t: testAnimate },
+ 'range': { r: true, t: testRange },
+ 'orientation': { r: false, t: testOrientation },
+ 'margin': { r: false, t: testMargin },
+ 'limit': { r: false, t: testLimit },
+ 'behaviour': { r: true, t: testBehaviour },
+ 'format': { r: false, t: testFormat }
+ };
+
+ var defaults = {
+ 'connect': false,
+ 'direction': 'ltr',
+ 'behaviour': 'tap',
+ 'orientation': 'horizontal'
+ };
+
+ // Set defaults where applicable.
+ Object.keys(defaults).forEach(function ( name ) {
+ if ( options[name] === undefined ) {
+ options[name] = defaults[name];
+ }
+ });
+
+ // Run all options through a testing mechanism to ensure correct
+ // input. It should be noted that options might get modified to
+ // be handled properly. E.g. wrapping integers in arrays.
+ Object.keys(tests).forEach(function( name ){
+
+ var test = tests[name];
+
+ // If the option isn't set, but it is required, throw an error.
+ if ( options[name] === undefined ) {
+
+ if ( test.r ) {
+ throw new Error("noUiSlider: '" + name + "' is required.");
+ }
+
+ return true;
+ }
+
+ test.t( parsed, options[name] );
+ });
+
+ // Forward pips options
+ parsed.pips = options.pips;
+
+ // Pre-define the styles.
+ parsed.style = parsed.ort ? 'top' : 'left';
+
+ return parsed;
+ }
+
+
+ // Delimit proposed values for handle positions.
+ function getPositions ( a, b, delimit ) {
+
+ // Add movement to current position.
+ var c = a + b[0], d = a + b[1];
+
+ // Only alter the other position on drag,
+ // not on standard sliding.
+ if ( delimit ) {
+ if ( c < 0 ) {
+ d += Math.abs(c);
+ }
+ if ( d > 100 ) {
+ c -= ( d - 100 );
+ }
+
+ // Limit values to 0 and 100.
+ return [limit(c), limit(d)];
+ }
+
+ return [c,d];
+ }
+
+ // Provide a clean event with standardized offset values.
+ function fixEvent ( e ) {
+
+ // Prevent scrolling and panning on touch events, while
+ // attempting to slide. The tap event also depends on this.
+ e.preventDefault();
+
+ // Filter the event to register the type, which can be
+ // touch, mouse or pointer. Offset changes need to be
+ // made on an event specific basis.
+ var touch = e.type.indexOf('touch') === 0,
+ mouse = e.type.indexOf('mouse') === 0,
+ pointer = e.type.indexOf('pointer') === 0,
+ x,y, event = e;
+
+ // IE10 implemented pointer events with a prefix;
+ if ( e.type.indexOf('MSPointer') === 0 ) {
+ pointer = true;
+ }
+
+ if ( touch ) {
+ // noUiSlider supports one movement at a time,
+ // so we can select the first 'changedTouch'.
+ x = e.changedTouches[0].pageX;
+ y = e.changedTouches[0].pageY;
+ }
+
+ if ( mouse || pointer ) {
+ x = e.clientX + window.pageXOffset;
+ y = e.clientY + window.pageYOffset;
+ }
+
+ event.points = [x, y];
+ event.cursor = mouse || pointer; // Fix #435
+
+ return event;
+ }
+
+ // Append a handle to the base.
+ function addHandle ( direction, index ) {
+
+ var origin = document.createElement('div'),
+ handle = document.createElement('div'),
+ additions = [ '-lower', '-upper' ];
+
+ if ( direction ) {
+ additions.reverse();
+ }
+
+ addClass(handle, Classes[3]);
+ addClass(handle, Classes[3] + additions[index]);
+
+ addClass(origin, Classes[2]);
+ origin.appendChild(handle);
+
+ return origin;
+ }
+
+ // Add the proper connection classes.
+ function addConnection ( connect, target, handles ) {
+
+ // Apply the required connection classes to the elements
+ // that need them. Some classes are made up for several
+ // segments listed in the class list, to allow easy
+ // renaming and provide a minor compression benefit.
+ switch ( connect ) {
+ case 1: addClass(target, Classes[7]);
+ addClass(handles[0], Classes[6]);
+ break;
+ case 3: addClass(handles[1], Classes[6]);
+ /* falls through */
+ case 2: addClass(handles[0], Classes[7]);
+ /* falls through */
+ case 0: addClass(target, Classes[6]);
+ break;
+ }
+ }
+
+ // Add handles to the slider base.
+ function addHandles ( nrHandles, direction, base ) {
+
+ var index, handles = [];
+
+ // Append handles.
+ for ( index = 0; index < nrHandles; index += 1 ) {
+
+ // Keep a list of all added handles.
+ handles.push( base.appendChild(addHandle( direction, index )) );
+ }
+
+ return handles;
+ }
+
+ // Initialize a single slider.
+ function addSlider ( direction, orientation, target ) {
+
+ // Apply classes and data to the target.
+ addClass(target, Classes[0]);
+ addClass(target, Classes[8 + direction]);
+ addClass(target, Classes[4 + orientation]);
+
+ var div = document.createElement('div');
+ addClass(div, Classes[1]);
+ target.appendChild(div);
+ return div;
+ }
+
+
+function closure ( target, options ){
+
+ // All variables local to 'closure' are prefixed with 'scope_'
+ var scope_Target = target,
+ scope_Locations = [-1, -1],
+ scope_Base,
+ scope_Handles,
+ scope_Spectrum = options.spectrum,
+ scope_Values = [],
+ scope_Events = {};
+
+
+ function getGroup ( mode, values, stepped ) {
+
+ // Use the range.
+ if ( mode === 'range' || mode === 'steps' ) {
+ return scope_Spectrum.xVal;
+ }
+
+ if ( mode === 'count' ) {
+
+ // Divide 0 - 100 in 'count' parts.
+ var spread = ( 100 / (values-1) ), v, i = 0;
+ values = [];
+
+ // List these parts and have them handled as 'positions'.
+ while ((v=i++*spread) <= 100 ) {
+ values.push(v);
+ }
+
+ mode = 'positions';
+ }
+
+ if ( mode === 'positions' ) {
+
+ // Map all percentages to on-range values.
+ return values.map(function( value ){
+ return scope_Spectrum.fromStepping( stepped ? scope_Spectrum.getStep( value ) : value );
+ });
+ }
+
+ if ( mode === 'values' ) {
+
+ // If the value must be stepped, it needs to be converted to a percentage first.
+ if ( stepped ) {
+
+ return values.map(function( value ){
+
+ // Convert to percentage, apply step, return to value.
+ return scope_Spectrum.fromStepping( scope_Spectrum.getStep( scope_Spectrum.toStepping( value ) ) );
+ });
+
+ }
+
+ // Otherwise, we can simply use the values.
+ return values;
+ }
+ }
+
+ function generateSpread ( density, mode, group ) {
+
+ var originalSpectrumDirection = scope_Spectrum.direction,
+ indexes = {},
+ firstInRange = scope_Spectrum.xVal[0],
+ lastInRange = scope_Spectrum.xVal[scope_Spectrum.xVal.length-1],
+ ignoreFirst = false,
+ ignoreLast = false,
+ prevPct = 0;
+
+ // This function loops the spectrum in an ltr linear fashion,
+ // while the toStepping method is direction aware. Trick it into
+ // believing it is ltr.
+ scope_Spectrum.direction = 0;
+
+ // Create a copy of the group, sort it and filter away all duplicates.
+ group = unique(group.slice().sort(function(a, b){ return a - b; }));
+
+ // Make sure the range starts with the first element.
+ if ( group[0] !== firstInRange ) {
+ group.unshift(firstInRange);
+ ignoreFirst = true;
+ }
+
+ // Likewise for the last one.
+ if ( group[group.length - 1] !== lastInRange ) {
+ group.push(lastInRange);
+ ignoreLast = true;
+ }
+
+ group.forEach(function ( current, index ) {
+
+ // Get the current step and the lower + upper positions.
+ var step, i, q,
+ low = current,
+ high = group[index+1],
+ newPct, pctDifference, pctPos, type,
+ steps, realSteps, stepsize;
+
+ // When using 'steps' mode, use the provided steps.
+ // Otherwise, we'll step on to the next subrange.
+ if ( mode === 'steps' ) {
+ step = scope_Spectrum.xNumSteps[ index ];
+ }
+
+ // Default to a 'full' step.
+ if ( !step ) {
+ step = high-low;
+ }
+
+ // Low can be 0, so test for false. If high is undefined,
+ // we are at the last subrange. Index 0 is already handled.
+ if ( low === false || high === undefined ) {
+ return;
+ }
+
+ // Find all steps in the subrange.
+ for ( i = low; i <= high; i += step ) {
+
+ // Get the percentage value for the current step,
+ // calculate the size for the subrange.
+ newPct = scope_Spectrum.toStepping( i );
+ pctDifference = newPct - prevPct;
+
+ steps = pctDifference / density;
+ realSteps = Math.round(steps);
+
+ // This ratio represents the ammount of percentage-space a point indicates.
+ // For a density 1 the points/percentage = 1. For density 2, that percentage needs to be re-devided.
+ // Round the percentage offset to an even number, then divide by two
+ // to spread the offset on both sides of the range.
+ stepsize = pctDifference/realSteps;
+
+ // Divide all points evenly, adding the correct number to this subrange.
+ // Run up to <= so that 100% gets a point, event if ignoreLast is set.
+ for ( q = 1; q <= realSteps; q += 1 ) {
+
+ // The ratio between the rounded value and the actual size might be ~1% off.
+ // Correct the percentage offset by the number of points
+ // per subrange. density = 1 will result in 100 points on the
+ // full range, 2 for 50, 4 for 25, etc.
+ pctPos = prevPct + ( q * stepsize );
+ indexes[pctPos.toFixed(5)] = ['x', 0];
+ }
+
+ // Determine the point type.
+ type = (group.indexOf(i) > -1) ? 1 : ( mode === 'steps' ? 2 : 0 );
+
+ // Enforce the 'ignoreFirst' option by overwriting the type for 0.
+ if ( !index && ignoreFirst ) {
+ type = 0;
+ }
+
+ if ( !(i === high && ignoreLast)) {
+ // Mark the 'type' of this point. 0 = plain, 1 = real value, 2 = step value.
+ indexes[newPct.toFixed(5)] = [i, type];
+ }
+
+ // Update the percentage count.
+ prevPct = newPct;
+ }
+ });
+
+ // Reset the spectrum.
+ scope_Spectrum.direction = originalSpectrumDirection;
+
+ return indexes;
+ }
+
+ function addMarking ( spread, filterFunc, formatter ) {
+
+ var style = ['horizontal', 'vertical'][options.ort],
+ element = document.createElement('div');
+
+ addClass(element, 'noUi-pips');
+ addClass(element, 'noUi-pips-' + style);
+
+ function getSize( type ){
+ return [ '-normal', '-large', '-sub' ][type];
+ }
+
+ function getTags( offset, source, values ) {
+ return 'class="' + source + ' ' +
+ source + '-' + style + ' ' +
+ source + getSize(values[1]) +
+ '" style="' + options.style + ': ' + offset + '%"';
+ }
+
+ function addSpread ( offset, values ){
+
+ if ( scope_Spectrum.direction ) {
+ offset = 100 - offset;
+ }
+
+ // Apply the filter function, if it is set.
+ values[1] = (values[1] && filterFunc) ? filterFunc(values[0], values[1]) : values[1];
+
+ // Add a marker for every point
+ element.innerHTML += '<div ' + getTags(offset, 'noUi-marker', values) + '></div>';
+
+ // Values are only appended for points marked '1' or '2'.
+ if ( values[1] ) {
+ element.innerHTML += '<div '+getTags(offset, 'noUi-value', values)+'>' + formatter.to(values[0]) + '</div>';
+ }
+ }
+
+ // Append all points.
+ Object.keys(spread).forEach(function(a){
+ addSpread(a, spread[a]);
+ });
+
+ return element;
+ }
+
+ function pips ( grid ) {
+
+ var mode = grid.mode,
+ density = grid.density || 1,
+ filter = grid.filter || false,
+ values = grid.values || false,
+ stepped = grid.stepped || false,
+ group = getGroup( mode, values, stepped ),
+ spread = generateSpread( density, mode, group ),
+ format = grid.format || {
+ to: Math.round
+ };
+
+ return scope_Target.appendChild(addMarking(
+ spread,
+ filter,
+ format
+ ));
+ }
+
+
+ // Shorthand for base dimensions.
+ function baseSize ( ) {
+ return scope_Base['offset' + ['Width', 'Height'][options.ort]];
+ }
+
+ // External event handling
+ function fireEvent ( event, handleNumber ) {
+
+ if ( handleNumber !== undefined ) {
+ handleNumber = Math.abs(handleNumber - options.dir);
+ }
+
+ Object.keys(scope_Events).forEach(function( targetEvent ) {
+
+ var eventType = targetEvent.split('.')[0];
+
+ if ( event === eventType ) {
+ scope_Events[targetEvent].forEach(function( callback ) {
+ // .reverse is in place
+ // Return values as array, so arg_1[arg_2] is always valid.
+ callback( asArray(valueGet()), handleNumber, inSliderOrder(Array.prototype.slice.call(scope_Values)) );
+ });
+ }
+ });
+ }
+
+ // Returns the input array, respecting the slider direction configuration.
+ function inSliderOrder ( values ) {
+
+ // If only one handle is used, return a single value.
+ if ( values.length === 1 ){
+ return values[0];
+ }
+
+ if ( options.dir ) {
+ return values.reverse();
+ }
+
+ return values;
+ }
+
+
+ // Handler for attaching events trough a proxy.
+ function attach ( events, element, callback, data ) {
+
+ // This function can be used to 'filter' events to the slider.
+ // element is a node, not a nodeList
+
+ var method = function ( e ){
+
+ if ( scope_Target.hasAttribute('disabled') ) {
+ return false;
+ }
+
+ // Stop if an active 'tap' transition is taking place.
+ if ( hasClass(scope_Target, Classes[14]) ) {
+ return false;
+ }
+
+ e = fixEvent(e);
+
+ // Ignore right or middle clicks on start #454
+ if ( events === actions.start && e.buttons !== undefined && e.buttons > 1 ) {
+ return false;
+ }
+
+ e.calcPoint = e.points[ options.ort ];
+
+ // Call the event handler with the event [ and additional data ].
+ callback ( e, data );
+
+ }, methods = [];
+
+ // Bind a closure on the target for every event type.
+ events.split(' ').forEach(function( eventName ){
+ element.addEventListener(eventName, method, false);
+ methods.push([eventName, method]);
+ });
+
+ return methods;
+ }
+
+ // Handle movement on document for handle and range drag.
+ function move ( event, data ) {
+
+ var handles = data.handles || scope_Handles, positions, state = false,
+ proposal = ((event.calcPoint - data.start) * 100) / baseSize(),
+ handleNumber = handles[0] === scope_Handles[0] ? 0 : 1, i;
+
+ // Calculate relative positions for the handles.
+ positions = getPositions( proposal, data.positions, handles.length > 1);
+
+ state = setHandle ( handles[0], positions[handleNumber], handles.length === 1 );
+
+ if ( handles.length > 1 ) {
+
+ state = setHandle ( handles[1], positions[handleNumber?0:1], false ) || state;
+
+ if ( state ) {
+ // fire for both handles
+ for ( i = 0; i < data.handles.length; i++ ) {
+ fireEvent('slide', i);
+ }
+ }
+ } else if ( state ) {
+ // Fire for a single handle
+ fireEvent('slide', handleNumber);
+ }
+ }
+
+ // Unbind move events on document, call callbacks.
+ function end ( event, data ) {
+
+ // The handle is no longer active, so remove the class.
+ var active = scope_Base.getElementsByClassName(Classes[15]),
+ handleNumber = data.handles[0] === scope_Handles[0] ? 0 : 1;
+
+ if ( active.length ) {
+ removeClass(active[0], Classes[15]);
+ }
+
+ // Remove cursor styles and text-selection events bound to the body.
+ if ( event.cursor ) {
+ document.body.style.cursor = '';
+ document.body.removeEventListener('selectstart', document.body.noUiListener);
+ }
+
+ var d = document.documentElement;
+
+ // Unbind the move and end events, which are added on 'start'.
+ d.noUiListeners.forEach(function( c ) {
+ d.removeEventListener(c[0], c[1]);
+ });
+
+ // Remove dragging class.
+ removeClass(scope_Target, Classes[12]);
+
+ // Fire the change and set events.
+ fireEvent('set', handleNumber);
+ fireEvent('change', handleNumber);
+ }
+
+ // Bind move events on document.
+ function start ( event, data ) {
+
+ var d = document.documentElement;
+
+ // Mark the handle as 'active' so it can be styled.
+ if ( data.handles.length === 1 ) {
+ addClass(data.handles[0].children[0], Classes[15]);
+
+ // Support 'disabled' handles
+ if ( data.handles[0].hasAttribute('disabled') ) {
+ return false;
+ }
+ }
+
+ // A drag should never propagate up to the 'tap' event.
+ event.stopPropagation();
+
+ // Attach the move and end events.
+ var moveEvent = attach(actions.move, d, move, {
+ start: event.calcPoint,
+ handles: data.handles,
+ positions: [
+ scope_Locations[0],
+ scope_Locations[scope_Handles.length - 1]
+ ]
+ }), endEvent = attach(actions.end, d, end, {
+ handles: data.handles
+ });
+
+ d.noUiListeners = moveEvent.concat(endEvent);
+
+ // Text selection isn't an issue on touch devices,
+ // so adding cursor styles can be skipped.
+ if ( event.cursor ) {
+
+ // Prevent the 'I' cursor and extend the range-drag cursor.
+ document.body.style.cursor = getComputedStyle(event.target).cursor;
+
+ // Mark the target with a dragging state.
+ if ( scope_Handles.length > 1 ) {
+ addClass(scope_Target, Classes[12]);
+ }
+
+ var f = function(){
+ return false;
+ };
+
+ document.body.noUiListener = f;
+
+ // Prevent text selection when dragging the handles.
+ document.body.addEventListener('selectstart', f, false);
+ }
+ }
+
+ // Move closest handle to tapped location.
+ function tap ( event ) {
+
+ var location = event.calcPoint, total = 0, handleNumber, to;
+
+ // The tap event shouldn't propagate up and cause 'edge' to run.
+ event.stopPropagation();
+
+ // Add up the handle offsets.
+ scope_Handles.forEach(function(a){
+ total += offset(a)[ options.style ];
+ });
+
+ // Find the handle closest to the tapped position.
+ handleNumber = ( location < total/2 || scope_Handles.length === 1 ) ? 0 : 1;
+
+ location -= offset(scope_Base)[ options.style ];
+
+ // Calculate the new position.
+ to = ( location * 100 ) / baseSize();
+
+ if ( !options.events.snap ) {
+ // Flag the slider as it is now in a transitional state.
+ // Transition takes 300 ms, so re-enable the slider afterwards.
+ addClassFor( scope_Target, Classes[14], 300 );
+ }
+
+ // Support 'disabled' handles
+ if ( scope_Handles[handleNumber].hasAttribute('disabled') ) {
+ return false;
+ }
+
+ // Find the closest handle and calculate the tapped point.
+ // The set handle to the new position.
+ setHandle( scope_Handles[handleNumber], to );
+
+ fireEvent('slide', handleNumber);
+ fireEvent('set', handleNumber);
+ fireEvent('change', handleNumber);
+
+ if ( options.events.snap ) {
+ start(event, { handles: [scope_Handles[total]] });
+ }
+ }
+
+ // Attach events to several slider parts.
+ function events ( behaviour ) {
+
+ var i, drag;
+
+ // Attach the standard drag event to the handles.
+ if ( !behaviour.fixed ) {
+
+ for ( i = 0; i < scope_Handles.length; i += 1 ) {
+
+ // These events are only bound to the visual handle
+ // element, not the 'real' origin element.
+ attach ( actions.start, scope_Handles[i].children[0], start, {
+ handles: [ scope_Handles[i] ]
+ });
+ }
+ }
+
+ // Attach the tap event to the slider base.
+ if ( behaviour.tap ) {
+
+ attach ( actions.start, scope_Base, tap, {
+ handles: scope_Handles
+ });
+ }
+
+ // Make the range dragable.
+ if ( behaviour.drag ){
+
+ drag = [scope_Base.getElementsByClassName( Classes[7] )[0]];
+ addClass(drag[0], Classes[10]);
+
+ // When the range is fixed, the entire range can
+ // be dragged by the handles. The handle in the first
+ // origin will propagate the start event upward,
+ // but it needs to be bound manually on the other.
+ if ( behaviour.fixed ) {
+ drag.push(scope_Handles[(drag[0] === scope_Handles[0] ? 1 : 0)].children[0]);
+ }
+
+ drag.forEach(function( element ) {
+ attach ( actions.start, element, start, {
+ handles: scope_Handles
+ });
+ });
+ }
+ }
+
+
+ // Test suggested values and apply margin, step.
+ function setHandle ( handle, to, noLimitOption ) {
+
+ var trigger = handle !== scope_Handles[0] ? 1 : 0,
+ lowerMargin = scope_Locations[0] + options.margin,
+ upperMargin = scope_Locations[1] - options.margin,
+ lowerLimit = scope_Locations[0] + options.limit,
+ upperLimit = scope_Locations[1] - options.limit;
+
+ // For sliders with multiple handles,
+ // limit movement to the other handle.
+ // Apply the margin option by adding it to the handle positions.
+ if ( scope_Handles.length > 1 ) {
+ to = trigger ? Math.max( to, lowerMargin ) : Math.min( to, upperMargin );
+ }
+
+ // The limit option has the opposite effect, limiting handles to a
+ // maximum distance from another. Limit must be > 0, as otherwise
+ // handles would be unmoveable. 'noLimitOption' is set to 'false'
+ // for the .val() method, except for pass 4/4.
+ if ( noLimitOption !== false && options.limit && scope_Handles.length > 1 ) {
+ to = trigger ? Math.min ( to, lowerLimit ) : Math.max( to, upperLimit );
+ }
+
+ // Handle the step option.
+ to = scope_Spectrum.getStep( to );
+
+ // Limit to 0/100 for .val input, trim anything beyond 7 digits, as
+ // JavaScript has some issues in its floating point implementation.
+ to = limit(parseFloat(to.toFixed(7)));
+
+ // Return false if handle can't move.
+ if ( to === scope_Locations[trigger] ) {
+ return false;
+ }
+
+ // Set the handle to the new position.
+ handle.style[options.style] = to + '%';
+
+ // Force proper handle stacking
+ if ( !handle.previousSibling ) {
+ removeClass(handle, Classes[17]);
+ if ( to > 50 ) {
+ addClass(handle, Classes[17]);
+ }
+ }
+
+ // Update locations.
+ scope_Locations[trigger] = to;
+
+ // Convert the value to the slider stepping/range.
+ scope_Values[trigger] = scope_Spectrum.fromStepping( to );
+
+ fireEvent('update', trigger);
+
+ return true;
+ }
+
+ // Loop values from value method and apply them.
+ function setValues ( count, values ) {
+
+ var i, trigger, to;
+
+ // With the limit option, we'll need another limiting pass.
+ if ( options.limit ) {
+ count += 1;
+ }
+
+ // If there are multiple handles to be set run the setting
+ // mechanism twice for the first handle, to make sure it
+ // can be bounced of the second one properly.
+ for ( i = 0; i < count; i += 1 ) {
+
+ trigger = i%2;
+
+ // Get the current argument from the array.
+ to = values[trigger];
+
+ // Setting with null indicates an 'ignore'.
+ // Inputting 'false' is invalid.
+ if ( to !== null && to !== false ) {
+
+ // If a formatted number was passed, attemt to decode it.
+ if ( typeof to === 'number' ) {
+ to = String(to);
+ }
+
+ to = options.format.from( to );
+
+ // Request an update for all links if the value was invalid.
+ // Do so too if setting the handle fails.
+ if ( to === false || isNaN(to) || setHandle( scope_Handles[trigger], scope_Spectrum.toStepping( to ), i === (3 - options.dir) ) === false ) {
+ fireEvent('update', trigger);
+ }
+ }
+ }
+ }
+
+ // Set the slider value.
+ function valueSet ( input ) {
+
+ var count, values = asArray( input ), i;
+
+ // The RTL settings is implemented by reversing the front-end,
+ // internal mechanisms are the same.
+ if ( options.dir && options.handles > 1 ) {
+ values.reverse();
+ }
+
+ // Animation is optional.
+ // Make sure the initial values where set before using animated placement.
+ if ( options.animate && scope_Locations[0] !== -1 ) {
+ addClassFor( scope_Target, Classes[14], 300 );
+ }
+
+ // Determine how often to set the handles.
+ count = scope_Handles.length > 1 ? 3 : 1;
+
+ if ( values.length === 1 ) {
+ count = 1;
+ }
+
+ setValues ( count, values );
+
+ // Fire the 'set' event for both handles.
+ for ( i = 0; i < scope_Handles.length; i++ ) {
+ fireEvent('set', i);
+ }
+ }
+
+ // Get the slider value.
+ function valueGet ( ) {
+
+ var i, retour = [];
+
+ // Get the value from all handles.
+ for ( i = 0; i < options.handles; i += 1 ){
+ retour[i] = options.format.to( scope_Values[i] );
+ }
+
+ return inSliderOrder( retour );
+ }
+
+ // Removes classes from the root and empties it.
+ function destroy ( ) {
+ Classes.forEach(function(cls){
+ if ( !cls ) { return; } // Ignore empty classes
+ removeClass(scope_Target, cls);
+ });
+ scope_Target.innerHTML = '';
+ delete scope_Target.noUiSlider;
+ }
+
+ // Get the current step size for the slider.
+ function getCurrentStep ( ) {
+
+ // Check all locations, map them to their stepping point.
+ // Get the step point, then find it in the input list.
+ var retour = scope_Locations.map(function( location, index ){
+
+ var step = scope_Spectrum.getApplicableStep( location ),
+
+ // As per #391, the comparison for the decrement step can have some rounding issues.
+ // Round the value to the precision used in the step.
+ stepDecimals = countDecimals(String(step[2])),
+
+ // Get the current numeric value
+ value = scope_Values[index],
+
+ // To move the slider 'one step up', the current step value needs to be added.
+ // Use null if we are at the maximum slider value.
+ increment = location === 100 ? null : step[2],
+
+ // Going 'one step down' might put the slider in a different sub-range, so we
+ // need to switch between the current or the previous step.
+ prev = Number((value - step[2]).toFixed(stepDecimals)),
+
+ // If the value fits the step, return the current step value. Otherwise, use the
+ // previous step. Return null if the slider is at its minimum value.
+ decrement = location === 0 ? null : (prev >= step[1]) ? step[2] : (step[0] || false);
+
+ return [decrement, increment];
+ });
+
+ // Return values in the proper order.
+ return inSliderOrder( retour );
+ }
+
+ // Attach an event to this slider, possibly including a namespace
+ function bindEvent ( namespacedEvent, callback ) {
+ scope_Events[namespacedEvent] = scope_Events[namespacedEvent] || [];
+ scope_Events[namespacedEvent].push(callback);
+
+ // If the event bound is 'update,' fire it immediately for all handles.
+ if ( namespacedEvent.split('.')[0] === 'update' ) {
+ scope_Handles.forEach(function(a, index){
+ fireEvent('update', index);
+ });
+ }
+ }
+
+ // Undo attachment of event
+ function removeEvent ( namespacedEvent ) {
+
+ var event = namespacedEvent.split('.')[0],
+ namespace = namespacedEvent.substring(event.length);
+
+ Object.keys(scope_Events).forEach(function( bind ){
+
+ var tEvent = bind.split('.')[0],
+ tNamespace = bind.substring(tEvent.length);
+
+ if ( (!event || event === tEvent) && (!namespace || namespace === tNamespace) ) {
+ delete scope_Events[bind];
+ }
+ });
+ }
+
+
+ // Throw an error if the slider was already initialized.
+ if ( scope_Target.noUiSlider ) {
+ throw new Error('Slider was already initialized.');
+ }
+
+
+ // Create the base element, initialise HTML and set classes.
+ // Add handles and links.
+ scope_Base = addSlider( options.dir, options.ort, scope_Target );
+ scope_Handles = addHandles( options.handles, options.dir, scope_Base );
+
+ // Set the connect classes.
+ addConnection ( options.connect, scope_Target, scope_Handles );
+
+ // Attach user events.
+ events( options.events );
+
+ if ( options.pips ) {
+ pips(options.pips);
+ }
+
+ return {
+ destroy: destroy,
+ steps: getCurrentStep,
+ on: bindEvent,
+ off: removeEvent,
+ get: valueGet,
+ set: valueSet
+ };
+
+}
+
+
+ // Run the standard initializer
+ function initialize ( target, originalOptions ) {
+
+ if ( !target.nodeName ) {
+ throw new Error('noUiSlider.create requires a single element.');
+ }
+
+ // Test the options and create the slider environment;
+ var options = testOptions( originalOptions, target ),
+ slider = closure( target, options );
+
+ // Use the public value method to set the start values.
+ slider.set(options.start);
+
+ target.noUiSlider = slider;
+ }
+
+ // Use an object instead of a function for future expansibility;
+ return {
+ create: initialize
+ };
+
+})); \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/packages/noUiSlider/nouislider.pips.css b/wqflask/wqflask/static/new/packages/noUiSlider/nouislider.pips.css
new file mode 100644
index 00000000..d1a93971
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/noUiSlider/nouislider.pips.css
@@ -0,0 +1,98 @@
+
+/* Base;
+ *
+ */
+.noUi-pips,
+.noUi-pips * {
+-moz-box-sizing: border-box;
+ box-sizing: border-box;
+}
+.noUi-pips {
+ position: absolute;
+ font: 400 12px Arial;
+ color: #999;
+}
+
+/* Values;
+ *
+ */
+.noUi-value {
+ width: 40px;
+ position: absolute;
+ text-align: center;
+}
+.noUi-value-sub {
+ color: #ccc;
+ font-size: 10px;
+}
+
+/* Markings;
+ *
+ */
+.noUi-marker {
+ position: absolute;
+ background: #CCC;
+}
+.noUi-marker-sub {
+ background: #AAA;
+}
+.noUi-marker-large {
+ background: #AAA;
+}
+
+/* Horizontal layout;
+ *
+ */
+.noUi-pips-horizontal {
+ padding: 10px 0;
+ height: 50px;
+ top: 100%;
+ left: 0;
+ width: 100%;
+}
+.noUi-value-horizontal {
+ margin-left: -20px;
+ padding-top: 20px;
+}
+.noUi-value-horizontal.noUi-value-sub {
+ padding-top: 15px;
+}
+
+.noUi-marker-horizontal.noUi-marker {
+ margin-left: -1px;
+ width: 2px;
+ height: 5px;
+}
+.noUi-marker-horizontal.noUi-marker-sub {
+ height: 10px;
+}
+.noUi-marker-horizontal.noUi-marker-large {
+ height: 15px;
+}
+
+/* Vertical layout;
+ *
+ */
+.noUi-pips-vertical {
+ padding: 0 10px;
+ height: 100%;
+ top: 0;
+ left: 100%;
+}
+.noUi-value-vertical {
+ width: 15px;
+ margin-left: 20px;
+ margin-top: -5px;
+}
+
+.noUi-marker-vertical.noUi-marker {
+ width: 5px;
+ height: 2px;
+ margin-top: -1px;
+}
+.noUi-marker-vertical.noUi-marker-sub {
+ width: 10px;
+}
+.noUi-marker-vertical.noUi-marker-large {
+ width: 15px;
+}
diff --git a/wqflask/wqflask/static/new/packages/nvd3/nv.d3.css b/wqflask/wqflask/static/new/packages/nvd3/nv.d3.css
new file mode 100644
index 00000000..726f76c3
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/nvd3/nv.d3.css
@@ -0,0 +1,641 @@
+/* nvd3 version 1.8.1 (https://github.com/novus/nvd3) 2015-05-25 */
+.nvd3 .nv-axis {
+ pointer-events:none;
+ opacity: 1;
+}
+
+.nvd3 .nv-axis path {
+ fill: none;
+ stroke: #000;
+ stroke-opacity: .75;
+ shape-rendering: crispEdges;
+}
+
+.nvd3 .nv-axis path.domain {
+ stroke-opacity: .75;
+}
+
+.nvd3 .nv-axis.nv-x path.domain {
+ stroke-opacity: 0;
+}
+
+.nvd3 .nv-axis line {
+ fill: none;
+ stroke: #e5e5e5;
+ shape-rendering: crispEdges;
+}
+
+.nvd3 .nv-axis .zero line,
+ /*this selector may not be necessary*/ .nvd3 .nv-axis line.zero {
+ stroke-opacity: .75;
+}
+
+.nvd3 .nv-axis .nv-axisMaxMin text {
+ font-weight: bold;
+}
+
+.nvd3 .x .nv-axis .nv-axisMaxMin text,
+.nvd3 .x2 .nv-axis .nv-axisMaxMin text,
+.nvd3 .x3 .nv-axis .nv-axisMaxMin text {
+ text-anchor: middle
+}
+
+.nvd3 .nv-axis.nv-disabled {
+ opacity: 0;
+}
+
+.nvd3 .nv-bars rect {
+ fill-opacity: .75;
+
+ transition: fill-opacity 250ms linear;
+ -moz-transition: fill-opacity 250ms linear;
+ -webkit-transition: fill-opacity 250ms linear;
+}
+
+.nvd3 .nv-bars rect.hover {
+ fill-opacity: 1;
+}
+
+.nvd3 .nv-bars .hover rect {
+ fill: lightblue;
+}
+
+.nvd3 .nv-bars text {
+ fill: rgba(0,0,0,0);
+}
+
+.nvd3 .nv-bars .hover text {
+ fill: rgba(0,0,0,1);
+}
+
+.nvd3 .nv-multibar .nv-groups rect,
+.nvd3 .nv-multibarHorizontal .nv-groups rect,
+.nvd3 .nv-discretebar .nv-groups rect {
+ stroke-opacity: 0;
+
+ transition: fill-opacity 250ms linear;
+ -moz-transition: fill-opacity 250ms linear;
+ -webkit-transition: fill-opacity 250ms linear;
+}
+
+.nvd3 .nv-multibar .nv-groups rect:hover,
+.nvd3 .nv-multibarHorizontal .nv-groups rect:hover,
+.nvd3 .nv-candlestickBar .nv-ticks rect:hover,
+.nvd3 .nv-discretebar .nv-groups rect:hover {
+ fill-opacity: 1;
+}
+
+.nvd3 .nv-discretebar .nv-groups text,
+.nvd3 .nv-multibarHorizontal .nv-groups text {
+ font-weight: bold;
+ fill: rgba(0,0,0,1);
+ stroke: rgba(0,0,0,0);
+}
+
+/* boxplot CSS */
+.nvd3 .nv-boxplot circle {
+ fill-opacity: 0.5;
+}
+
+.nvd3 .nv-boxplot circle:hover {
+ fill-opacity: 1;
+}
+
+.nvd3 .nv-boxplot rect:hover {
+ fill-opacity: 1;
+}
+
+.nvd3 line.nv-boxplot-median {
+ stroke: black;
+}
+
+.nv-boxplot-tick:hover {
+ stroke-width: 2.5px;
+}
+/* bullet */
+.nvd3.nv-bullet { font: 10px sans-serif; }
+.nvd3.nv-bullet .nv-measure { fill-opacity: .8; }
+.nvd3.nv-bullet .nv-measure:hover { fill-opacity: 1; }
+.nvd3.nv-bullet .nv-marker { stroke: #000; stroke-width: 2px; }
+.nvd3.nv-bullet .nv-markerTriangle { stroke: #000; fill: #fff; stroke-width: 1.5px; }
+.nvd3.nv-bullet .nv-tick line { stroke: #666; stroke-width: .5px; }
+.nvd3.nv-bullet .nv-range.nv-s0 { fill: #eee; }
+.nvd3.nv-bullet .nv-range.nv-s1 { fill: #ddd; }
+.nvd3.nv-bullet .nv-range.nv-s2 { fill: #ccc; }
+.nvd3.nv-bullet .nv-title { font-size: 14px; font-weight: bold; }
+.nvd3.nv-bullet .nv-subtitle { fill: #999; }
+
+
+.nvd3.nv-bullet .nv-range {
+ fill: #bababa;
+ fill-opacity: .4;
+}
+.nvd3.nv-bullet .nv-range:hover {
+ fill-opacity: .7;
+}
+
+.nvd3.nv-candlestickBar .nv-ticks .nv-tick {
+ stroke-width: 1px;
+}
+
+.nvd3.nv-candlestickBar .nv-ticks .nv-tick.hover {
+ stroke-width: 2px;
+}
+
+.nvd3.nv-candlestickBar .nv-ticks .nv-tick.positive rect {
+ stroke: #2ca02c;
+ fill: #2ca02c;
+}
+
+.nvd3.nv-candlestickBar .nv-ticks .nv-tick.negative rect {
+ stroke: #d62728;
+ fill: #d62728;
+}
+
+.with-transitions .nv-candlestickBar .nv-ticks .nv-tick {
+ transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
+ -moz-transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
+ -webkit-transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
+
+}
+
+.nvd3.nv-candlestickBar .nv-ticks line {
+ stroke: #333;
+}
+
+
+.nvd3 .nv-legend .nv-disabled rect {
+ /*fill-opacity: 0;*/
+}
+
+.nvd3 .nv-check-box .nv-box {
+ fill-opacity:0;
+ stroke-width:2;
+}
+
+.nvd3 .nv-check-box .nv-check {
+ fill-opacity:0;
+ stroke-width:4;
+}
+
+.nvd3 .nv-series.nv-disabled .nv-check-box .nv-check {
+ fill-opacity:0;
+ stroke-opacity:0;
+}
+
+.nvd3 .nv-controlsWrap .nv-legend .nv-check-box .nv-check {
+ opacity: 0;
+}
+
+/* line plus bar */
+.nvd3.nv-linePlusBar .nv-bar rect {
+ fill-opacity: .75;
+}
+
+.nvd3.nv-linePlusBar .nv-bar rect:hover {
+ fill-opacity: 1;
+}
+.nvd3 .nv-groups path.nv-line {
+ fill: none;
+}
+
+.nvd3 .nv-groups path.nv-area {
+ stroke: none;
+}
+
+.nvd3.nv-line .nvd3.nv-scatter .nv-groups .nv-point {
+ fill-opacity: 0;
+ stroke-opacity: 0;
+}
+
+.nvd3.nv-scatter.nv-single-point .nv-groups .nv-point {
+ fill-opacity: .5 !important;
+ stroke-opacity: .5 !important;
+}
+
+
+.with-transitions .nvd3 .nv-groups .nv-point {
+ transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
+ -moz-transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
+ -webkit-transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
+
+}
+
+.nvd3.nv-scatter .nv-groups .nv-point.hover,
+.nvd3 .nv-groups .nv-point.hover {
+ stroke-width: 7px;
+ fill-opacity: .95 !important;
+ stroke-opacity: .95 !important;
+}
+
+
+.nvd3 .nv-point-paths path {
+ stroke: #aaa;
+ stroke-opacity: 0;
+ fill: #eee;
+ fill-opacity: 0;
+}
+
+
+
+.nvd3 .nv-indexLine {
+ cursor: ew-resize;
+}
+
+/********************
+ * SVG CSS
+ */
+
+/********************
+ Default CSS for an svg element nvd3 used
+*/
+svg.nvd3-svg {
+ -webkit-touch-callout: none;
+ -webkit-user-select: none;
+ -khtml-user-select: none;
+ -ms-user-select: none;
+ -moz-user-select: none;
+ user-select: none;
+ display: block;
+ width:100%;
+ height:100%;
+}
+
+/********************
+ Box shadow and border radius styling
+*/
+.nvtooltip.with-3d-shadow, .with-3d-shadow .nvtooltip {
+ -moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
+ -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
+ box-shadow: 0 5px 10px rgba(0,0,0,.2);
+
+ -webkit-border-radius: 5px;
+ -moz-border-radius: 5px;
+ border-radius: 5px;
+}
+
+
+.nvd3 text {
+ font: normal 12px Arial;
+}
+
+.nvd3 .title {
+ font: bold 14px Arial;
+}
+
+.nvd3 .nv-background {
+ fill: white;
+ fill-opacity: 0;
+}
+
+.nvd3.nv-noData {
+ font-size: 18px;
+ font-weight: bold;
+}
+
+
+/**********
+* Brush
+*/
+
+.nv-brush .extent {
+ fill-opacity: .125;
+ shape-rendering: crispEdges;
+}
+
+.nv-brush .resize path {
+ fill: #eee;
+ stroke: #666;
+}
+
+
+/**********
+* Legend
+*/
+
+.nvd3 .nv-legend .nv-series {
+ cursor: pointer;
+}
+
+.nvd3 .nv-legend .nv-disabled circle {
+ fill-opacity: 0;
+}
+
+/* focus */
+.nvd3 .nv-brush .extent {
+ fill-opacity: 0 !important;
+}
+
+.nvd3 .nv-brushBackground rect {
+ stroke: #000;
+ stroke-width: .4;
+ fill: #fff;
+ fill-opacity: .7;
+}
+
+
+.nvd3.nv-ohlcBar .nv-ticks .nv-tick {
+ stroke-width: 1px;
+}
+
+.nvd3.nv-ohlcBar .nv-ticks .nv-tick.hover {
+ stroke-width: 2px;
+}
+
+.nvd3.nv-ohlcBar .nv-ticks .nv-tick.positive {
+ stroke: #2ca02c;
+}
+
+.nvd3.nv-ohlcBar .nv-ticks .nv-tick.negative {
+ stroke: #d62728;
+}
+
+
+.nvd3 .background path {
+ fill: none;
+ stroke: #EEE;
+ stroke-opacity: .4;
+ shape-rendering: crispEdges;
+}
+
+.nvd3 .foreground path {
+ fill: none;
+ stroke-opacity: .7;
+}
+
+.nvd3 .nv-parallelCoordinates-brush .extent
+{
+ fill: #fff;
+ fill-opacity: .6;
+ stroke: gray;
+ shape-rendering: crispEdges;
+}
+
+.nvd3 .nv-parallelCoordinates .hover {
+ fill-opacity: 1;
+ stroke-width: 3px;
+}
+
+
+.nvd3 .missingValuesline line {
+ fill: none;
+ stroke: black;
+ stroke-width: 1;
+ stroke-opacity: 1;
+ stroke-dasharray: 5, 5;
+}
+.nvd3.nv-pie path {
+ stroke-opacity: 0;
+ transition: fill-opacity 250ms linear, stroke-width 250ms linear, stroke-opacity 250ms linear;
+ -moz-transition: fill-opacity 250ms linear, stroke-width 250ms linear, stroke-opacity 250ms linear;
+ -webkit-transition: fill-opacity 250ms linear, stroke-width 250ms linear, stroke-opacity 250ms linear;
+
+}
+
+.nvd3.nv-pie .nv-pie-title {
+ font-size: 24px;
+ fill: rgba(19, 196, 249, 0.59);
+}
+
+.nvd3.nv-pie .nv-slice text {
+ stroke: #000;
+ stroke-width: 0;
+}
+
+.nvd3.nv-pie path {
+ stroke: #fff;
+ stroke-width: 1px;
+ stroke-opacity: 1;
+}
+
+.nvd3.nv-pie .hover path {
+ fill-opacity: .7;
+}
+.nvd3.nv-pie .nv-label {
+ pointer-events: none;
+}
+.nvd3.nv-pie .nv-label rect {
+ fill-opacity: 0;
+ stroke-opacity: 0;
+}
+
+/* scatter */
+.nvd3 .nv-groups .nv-point.hover {
+ stroke-width: 20px;
+ stroke-opacity: .5;
+}
+
+.nvd3 .nv-scatter .nv-point.hover {
+ fill-opacity: 1;
+}
+.nv-noninteractive {
+ pointer-events: none;
+}
+
+.nv-distx, .nv-disty {
+ pointer-events: none;
+}
+
+/* sparkline */
+.nvd3.nv-sparkline path {
+ fill: none;
+}
+
+.nvd3.nv-sparklineplus g.nv-hoverValue {
+ pointer-events: none;
+}
+
+.nvd3.nv-sparklineplus .nv-hoverValue line {
+ stroke: #333;
+ stroke-width: 1.5px;
+}
+
+.nvd3.nv-sparklineplus,
+.nvd3.nv-sparklineplus g {
+ pointer-events: all;
+}
+
+.nvd3 .nv-hoverArea {
+ fill-opacity: 0;
+ stroke-opacity: 0;
+}
+
+.nvd3.nv-sparklineplus .nv-xValue,
+.nvd3.nv-sparklineplus .nv-yValue {
+ stroke-width: 0;
+ font-size: .9em;
+ font-weight: normal;
+}
+
+.nvd3.nv-sparklineplus .nv-yValue {
+ stroke: #f66;
+}
+
+.nvd3.nv-sparklineplus .nv-maxValue {
+ stroke: #2ca02c;
+ fill: #2ca02c;
+}
+
+.nvd3.nv-sparklineplus .nv-minValue {
+ stroke: #d62728;
+ fill: #d62728;
+}
+
+.nvd3.nv-sparklineplus .nv-currentValue {
+ font-weight: bold;
+ font-size: 1.1em;
+}
+/* stacked area */
+.nvd3.nv-stackedarea path.nv-area {
+ fill-opacity: .7;
+ stroke-opacity: 0;
+ transition: fill-opacity 250ms linear, stroke-opacity 250ms linear;
+ -moz-transition: fill-opacity 250ms linear, stroke-opacity 250ms linear;
+ -webkit-transition: fill-opacity 250ms linear, stroke-opacity 250ms linear;
+}
+
+.nvd3.nv-stackedarea path.nv-area.hover {
+ fill-opacity: .9;
+}
+
+
+.nvd3.nv-stackedarea .nv-groups .nv-point {
+ stroke-opacity: 0;
+ fill-opacity: 0;
+}
+
+
+.nvtooltip {
+ position: absolute;
+ background-color: rgba(255,255,255,1.0);
+ color: rgba(0,0,0,1.0);
+ padding: 1px;
+ border: 1px solid rgba(0,0,0,.2);
+ z-index: 10000;
+ display: block;
+
+ font-family: Arial;
+ font-size: 13px;
+ text-align: left;
+ pointer-events: none;
+
+ white-space: nowrap;
+
+ -webkit-touch-callout: none;
+ -webkit-user-select: none;
+ -khtml-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+ user-select: none;
+}
+
+.nvtooltip {
+ background: rgba(255,255,255, 0.8);
+ border: 1px solid rgba(0,0,0,0.5);
+ border-radius: 4px;
+}
+
+/*Give tooltips that old fade in transition by
+ putting a "with-transitions" class on the container div.
+*/
+.nvtooltip.with-transitions, .with-transitions .nvtooltip {
+ transition: opacity 50ms linear;
+ -moz-transition: opacity 50ms linear;
+ -webkit-transition: opacity 50ms linear;
+
+ transition-delay: 200ms;
+ -moz-transition-delay: 200ms;
+ -webkit-transition-delay: 200ms;
+}
+
+.nvtooltip.x-nvtooltip,
+.nvtooltip.y-nvtooltip {
+ padding: 8px;
+}
+
+.nvtooltip h3 {
+ margin: 0;
+ padding: 4px 14px;
+ line-height: 18px;
+ font-weight: normal;
+ background-color: rgba(247,247,247,0.75);
+ color: rgba(0,0,0,1.0);
+ text-align: center;
+
+ border-bottom: 1px solid #ebebeb;
+
+ -webkit-border-radius: 5px 5px 0 0;
+ -moz-border-radius: 5px 5px 0 0;
+ border-radius: 5px 5px 0 0;
+}
+
+.nvtooltip p {
+ margin: 0;
+ padding: 5px 14px;
+ text-align: center;
+}
+
+.nvtooltip span {
+ display: inline-block;
+ margin: 2px 0;
+}
+
+.nvtooltip table {
+ margin: 6px;
+ border-spacing:0;
+}
+
+
+.nvtooltip table td {
+ padding: 2px 9px 2px 0;
+ vertical-align: middle;
+}
+
+.nvtooltip table td.key {
+ font-weight:normal;
+}
+.nvtooltip table td.value {
+ text-align: right;
+ font-weight: bold;
+}
+
+.nvtooltip table tr.highlight td {
+ padding: 1px 9px 1px 0;
+ border-bottom-style: solid;
+ border-bottom-width: 1px;
+ border-top-style: solid;
+ border-top-width: 1px;
+}
+
+.nvtooltip table td.legend-color-guide div {
+ width: 8px;
+ height: 8px;
+ vertical-align: middle;
+}
+
+.nvtooltip table td.legend-color-guide div {
+ width: 12px;
+ height: 12px;
+ border: 1px solid #999;
+}
+
+.nvtooltip .footer {
+ padding: 3px;
+ text-align: center;
+}
+
+.nvtooltip-pending-removal {
+ pointer-events: none;
+ display: none;
+}
+
+
+/****
+Interactive Layer
+*/
+.nvd3 .nv-interactiveGuideLine {
+ pointer-events:none;
+}
+.nvd3 line.nv-guideline {
+ stroke: #ccc;
+} \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/packages/nvd3/nv.d3.js b/wqflask/wqflask/static/new/packages/nvd3/nv.d3.js
new file mode 100644
index 00000000..b11ce58f
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/nvd3/nv.d3.js
@@ -0,0 +1,13362 @@
+/* nvd3 version 1.8.1 (https://github.com/novus/nvd3) 2015-05-25 */
+(function(){
+
+// set up main nv object
+var nv = {};
+
+// the major global objects under the nv namespace
+nv.dev = false; //set false when in production
+nv.tooltip = nv.tooltip || {}; // For the tooltip system
+nv.utils = nv.utils || {}; // Utility subsystem
+nv.models = nv.models || {}; //stores all the possible models/components
+nv.charts = {}; //stores all the ready to use charts
+nv.logs = {}; //stores some statistics and potential error messages
+nv.dom = {}; //DOM manipulation functions
+
+nv.dispatch = d3.dispatch('render_start', 'render_end');
+
+// Function bind polyfill
+// Needed ONLY for phantomJS as it's missing until version 2.0 which is unreleased as of this comment
+// https://github.com/ariya/phantomjs/issues/10522
+// http://kangax.github.io/compat-table/es5/#Function.prototype.bind
+// phantomJS is used for running the test suite
+if (!Function.prototype.bind) {
+ Function.prototype.bind = function (oThis) {
+ if (typeof this !== "function") {
+ // closest thing possible to the ECMAScript 5 internal IsCallable function
+ throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
+ }
+
+ var aArgs = Array.prototype.slice.call(arguments, 1),
+ fToBind = this,
+ fNOP = function () {},
+ fBound = function () {
+ return fToBind.apply(this instanceof fNOP && oThis
+ ? this
+ : oThis,
+ aArgs.concat(Array.prototype.slice.call(arguments)));
+ };
+
+ fNOP.prototype = this.prototype;
+ fBound.prototype = new fNOP();
+ return fBound;
+ };
+}
+
+// Development render timers - disabled if dev = false
+if (nv.dev) {
+ nv.dispatch.on('render_start', function(e) {
+ nv.logs.startTime = +new Date();
+ });
+
+ nv.dispatch.on('render_end', function(e) {
+ nv.logs.endTime = +new Date();
+ nv.logs.totalTime = nv.logs.endTime - nv.logs.startTime;
+ nv.log('total', nv.logs.totalTime); // used for development, to keep track of graph generation times
+ });
+}
+
+// Logs all arguments, and returns the last so you can test things in place
+// Note: in IE8 console.log is an object not a function, and if modernizr is used
+// then calling Function.prototype.bind with with anything other than a function
+// causes a TypeError to be thrown.
+nv.log = function() {
+ if (nv.dev && window.console && console.log && console.log.apply)
+ console.log.apply(console, arguments);
+ else if (nv.dev && window.console && typeof console.log == "function" && Function.prototype.bind) {
+ var log = Function.prototype.bind.call(console.log, console);
+ log.apply(console, arguments);
+ }
+ return arguments[arguments.length - 1];
+};
+
+// print console warning, should be used by deprecated functions
+nv.deprecated = function(name, info) {
+ if (console && console.warn) {
+ console.warn('nvd3 warning: `' + name + '` has been deprecated. ', info || '');
+ }
+};
+
+// The nv.render function is used to queue up chart rendering
+// in non-blocking async functions.
+// When all queued charts are done rendering, nv.dispatch.render_end is invoked.
+nv.render = function render(step) {
+ // number of graphs to generate in each timeout loop
+ step = step || 1;
+
+ nv.render.active = true;
+ nv.dispatch.render_start();
+
+ var renderLoop = function() {
+ var chart, graph;
+
+ for (var i = 0; i < step && (graph = nv.render.queue[i]); i++) {
+ chart = graph.generate();
+ if (typeof graph.callback == typeof(Function)) graph.callback(chart);
+ }
+
+ nv.render.queue.splice(0, i);
+
+ if (nv.render.queue.length) {
+ setTimeout(renderLoop);
+ }
+ else {
+ nv.dispatch.render_end();
+ nv.render.active = false;
+ }
+ };
+
+ setTimeout(renderLoop);
+};
+
+nv.render.active = false;
+nv.render.queue = [];
+
+/*
+Adds a chart to the async rendering queue. This method can take arguments in two forms:
+nv.addGraph({
+ generate: <Function>
+ callback: <Function>
+})
+
+or
+
+nv.addGraph(<generate Function>, <callback Function>)
+
+The generate function should contain code that creates the NVD3 model, sets options
+on it, adds data to an SVG element, and invokes the chart model. The generate function
+should return the chart model. See examples/lineChart.html for a usage example.
+
+The callback function is optional, and it is called when the generate function completes.
+*/
+nv.addGraph = function(obj) {
+ if (typeof arguments[0] === typeof(Function)) {
+ obj = {generate: arguments[0], callback: arguments[1]};
+ }
+
+ nv.render.queue.push(obj);
+
+ if (!nv.render.active) {
+ nv.render();
+ }
+};
+
+// Node/CommonJS exports
+if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined') {
+ module.exports = nv;
+}
+
+if (typeof(window) !== 'undefined') {
+ window.nv = nv;
+}
+/* Facade for queueing DOM write operations
+ * with Fastdom (https://github.com/wilsonpage/fastdom)
+ * if available.
+ * This could easily be extended to support alternate
+ * implementations in the future.
+ */
+nv.dom.write = function(callback) {
+ if (window.fastdom !== undefined) {
+ return fastdom.write(callback);
+ }
+ return callback();
+};
+
+/* Facade for queueing DOM read operations
+ * with Fastdom (https://github.com/wilsonpage/fastdom)
+ * if available.
+ * This could easily be extended to support alternate
+ * implementations in the future.
+ */
+nv.dom.read = function(callback) {
+ if (window.fastdom !== undefined) {
+ return fastdom.read(callback);
+ }
+ return callback();
+};/* Utility class to handle creation of an interactive layer.
+ This places a rectangle on top of the chart. When you mouse move over it, it sends a dispatch
+ containing the X-coordinate. It can also render a vertical line where the mouse is located.
+
+ dispatch.elementMousemove is the important event to latch onto. It is fired whenever the mouse moves over
+ the rectangle. The dispatch is given one object which contains the mouseX/Y location.
+ It also has 'pointXValue', which is the conversion of mouseX to the x-axis scale.
+ */
+nv.interactiveGuideline = function() {
+ "use strict";
+
+ var tooltip = nv.models.tooltip();
+ tooltip.duration(0).hideDelay(0)._isInteractiveLayer(true).hidden(false);
+
+ //Public settings
+ var width = null;
+ var height = null;
+
+ //Please pass in the bounding chart's top and left margins
+ //This is important for calculating the correct mouseX/Y positions.
+ var margin = {left: 0, top: 0}
+ , xScale = d3.scale.linear()
+ , dispatch = d3.dispatch('elementMousemove', 'elementMouseout', 'elementClick', 'elementDblclick')
+ , showGuideLine = true;
+ //Must pass in the bounding chart's <svg> container.
+ //The mousemove event is attached to this container.
+ var svgContainer = null;
+
+ // check if IE by looking for activeX
+ var isMSIE = "ActiveXObject" in window;
+
+
+ function layer(selection) {
+ selection.each(function(data) {
+ var container = d3.select(this);
+ var availableWidth = (width || 960), availableHeight = (height || 400);
+ var wrap = container.selectAll("g.nv-wrap.nv-interactiveLineLayer")
+ .data([data]);
+ var wrapEnter = wrap.enter()
+ .append("g").attr("class", " nv-wrap nv-interactiveLineLayer");
+ wrapEnter.append("g").attr("class","nv-interactiveGuideLine");
+
+ if (!svgContainer) {
+ return;
+ }
+
+ function mouseHandler() {
+ var d3mouse = d3.mouse(this);
+ var mouseX = d3mouse[0];
+ var mouseY = d3mouse[1];
+ var subtractMargin = true;
+ var mouseOutAnyReason = false;
+ if (isMSIE) {
+ /*
+ D3.js (or maybe SVG.getScreenCTM) has a nasty bug in Internet Explorer 10.
+ d3.mouse() returns incorrect X,Y mouse coordinates when mouse moving
+ over a rect in IE 10.
+ However, d3.event.offsetX/Y also returns the mouse coordinates
+ relative to the triggering <rect>. So we use offsetX/Y on IE.
+ */
+ mouseX = d3.event.offsetX;
+ mouseY = d3.event.offsetY;
+
+ /*
+ On IE, if you attach a mouse event listener to the <svg> container,
+ it will actually trigger it for all the child elements (like <path>, <circle>, etc).
+ When this happens on IE, the offsetX/Y is set to where ever the child element
+ is located.
+ As a result, we do NOT need to subtract margins to figure out the mouse X/Y
+ position under this scenario. Removing the line below *will* cause
+ the interactive layer to not work right on IE.
+ */
+ if(d3.event.target.tagName !== "svg") {
+ subtractMargin = false;
+ }
+
+ if (d3.event.target.className.baseVal.match("nv-legend")) {
+ mouseOutAnyReason = true;
+ }
+
+ }
+
+ if(subtractMargin) {
+ mouseX -= margin.left;
+ mouseY -= margin.top;
+ }
+
+ /* If mouseX/Y is outside of the chart's bounds,
+ trigger a mouseOut event.
+ */
+ if (mouseX < 0 || mouseY < 0
+ || mouseX > availableWidth || mouseY > availableHeight
+ || (d3.event.relatedTarget && d3.event.relatedTarget.ownerSVGElement === undefined)
+ || mouseOutAnyReason
+ ) {
+
+ if (isMSIE) {
+ if (d3.event.relatedTarget
+ && d3.event.relatedTarget.ownerSVGElement === undefined
+ && (d3.event.relatedTarget.className === undefined
+ || d3.event.relatedTarget.className.match(tooltip.nvPointerEventsClass))) {
+
+ return;
+ }
+ }
+ dispatch.elementMouseout({
+ mouseX: mouseX,
+ mouseY: mouseY
+ });
+ layer.renderGuideLine(null); //hide the guideline
+ tooltip.hidden(true);
+ return;
+ } else {
+ tooltip.hidden(false);
+ }
+
+ var pointXValue = xScale.invert(mouseX);
+ dispatch.elementMousemove({
+ mouseX: mouseX,
+ mouseY: mouseY,
+ pointXValue: pointXValue
+ });
+
+ //If user double clicks the layer, fire a elementDblclick
+ if (d3.event.type === "dblclick") {
+ dispatch.elementDblclick({
+ mouseX: mouseX,
+ mouseY: mouseY,
+ pointXValue: pointXValue
+ });
+ }
+
+ // if user single clicks the layer, fire elementClick
+ if (d3.event.type === 'click') {
+ dispatch.elementClick({
+ mouseX: mouseX,
+ mouseY: mouseY,
+ pointXValue: pointXValue
+ });
+ }
+ }
+
+ svgContainer
+ .on("touchmove",mouseHandler)
+ .on("mousemove",mouseHandler, true)
+ .on("mouseout" ,mouseHandler,true)
+ .on("dblclick" ,mouseHandler)
+ .on("click", mouseHandler)
+ ;
+
+ layer.guideLine = null;
+ //Draws a vertical guideline at the given X postion.
+ layer.renderGuideLine = function(x) {
+ if (!showGuideLine) return;
+ if (layer.guideLine && layer.guideLine.attr("x1") === x) return;
+ nv.dom.write(function() {
+ var line = wrap.select(".nv-interactiveGuideLine")
+ .selectAll("line")
+ .data((x != null) ? [nv.utils.NaNtoZero(x)] : [], String);
+ line.enter()
+ .append("line")
+ .attr("class", "nv-guideline")
+ .attr("x1", function(d) { return d;})
+ .attr("x2", function(d) { return d;})
+ .attr("y1", availableHeight)
+ .attr("y2",0);
+ line.exit().remove();
+ });
+ }
+ });
+ }
+
+ layer.dispatch = dispatch;
+ layer.tooltip = tooltip;
+
+ layer.margin = function(_) {
+ if (!arguments.length) return margin;
+ margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
+ margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
+ return layer;
+ };
+
+ layer.width = function(_) {
+ if (!arguments.length) return width;
+ width = _;
+ return layer;
+ };
+
+ layer.height = function(_) {
+ if (!arguments.length) return height;
+ height = _;
+ return layer;
+ };
+
+ layer.xScale = function(_) {
+ if (!arguments.length) return xScale;
+ xScale = _;
+ return layer;
+ };
+
+ layer.showGuideLine = function(_) {
+ if (!arguments.length) return showGuideLine;
+ showGuideLine = _;
+ return layer;
+ };
+
+ layer.svgContainer = function(_) {
+ if (!arguments.length) return svgContainer;
+ svgContainer = _;
+ return layer;
+ };
+
+ return layer;
+};
+
+/* Utility class that uses d3.bisect to find the index in a given array, where a search value can be inserted.
+ This is different from normal bisectLeft; this function finds the nearest index to insert the search value.
+
+ For instance, lets say your array is [1,2,3,5,10,30], and you search for 28.
+ Normal d3.bisectLeft will return 4, because 28 is inserted after the number 10. But interactiveBisect will return 5
+ because 28 is closer to 30 than 10.
+
+ Unit tests can be found in: interactiveBisectTest.html
+
+ Has the following known issues:
+ * Will not work if the data points move backwards (ie, 10,9,8,7, etc) or if the data points are in random order.
+ * Won't work if there are duplicate x coordinate values.
+ */
+nv.interactiveBisect = function (values, searchVal, xAccessor) {
+ "use strict";
+ if (! (values instanceof Array)) {
+ return null;
+ }
+ var _xAccessor;
+ if (typeof xAccessor !== 'function') {
+ _xAccessor = function(d) {
+ return d.x;
+ }
+ } else {
+ _xAccessor = xAccessor;
+ }
+ var _cmp = function(d, v) {
+ // Accessors are no longer passed the index of the element along with
+ // the element itself when invoked by d3.bisector.
+ //
+ // Starting at D3 v3.4.4, d3.bisector() started inspecting the
+ // function passed to determine if it should consider it an accessor
+ // or a comparator. This meant that accessors that take two arguments
+ // (expecting an index as the second parameter) are treated as
+ // comparators where the second argument is the search value against
+ // which the first argument is compared.
+ return _xAccessor(d) - v;
+ };
+
+ var bisect = d3.bisector(_cmp).left;
+ var index = d3.max([0, bisect(values,searchVal) - 1]);
+ var currentValue = _xAccessor(values[index]);
+
+ if (typeof currentValue === 'undefined') {
+ currentValue = index;
+ }
+
+ if (currentValue === searchVal) {
+ return index; //found exact match
+ }
+
+ var nextIndex = d3.min([index+1, values.length - 1]);
+ var nextValue = _xAccessor(values[nextIndex]);
+
+ if (typeof nextValue === 'undefined') {
+ nextValue = nextIndex;
+ }
+
+ if (Math.abs(nextValue - searchVal) >= Math.abs(currentValue - searchVal)) {
+ return index;
+ } else {
+ return nextIndex
+ }
+};
+
+/*
+ Returns the index in the array "values" that is closest to searchVal.
+ Only returns an index if searchVal is within some "threshold".
+ Otherwise, returns null.
+ */
+nv.nearestValueIndex = function (values, searchVal, threshold) {
+ "use strict";
+ var yDistMax = Infinity, indexToHighlight = null;
+ values.forEach(function(d,i) {
+ var delta = Math.abs(searchVal - d);
+ if ( d != null && delta <= yDistMax && delta < threshold) {
+ yDistMax = delta;
+ indexToHighlight = i;
+ }
+ });
+ return indexToHighlight;
+};
+/* Tooltip rendering model for nvd3 charts.
+ window.nv.models.tooltip is the updated,new way to render tooltips.
+
+ window.nv.tooltip.show is the old tooltip code.
+ window.nv.tooltip.* also has various helper methods.
+ */
+(function() {
+ "use strict";
+
+ /* Model which can be instantiated to handle tooltip rendering.
+ Example usage:
+ var tip = nv.models.tooltip().gravity('w').distance(23)
+ .data(myDataObject);
+
+ tip(); //just invoke the returned function to render tooltip.
+ */
+ nv.models.tooltip = function() {
+
+ /*
+ Tooltip data. If data is given in the proper format, a consistent tooltip is generated.
+ Example Format of data:
+ {
+ key: "Date",
+ value: "August 2009",
+ series: [
+ {key: "Series 1", value: "Value 1", color: "#000"},
+ {key: "Series 2", value: "Value 2", color: "#00f"}
+ ]
+ }
+ */
+ var data = null;
+ var gravity = 'w' //Can be 'n','s','e','w'. Determines how tooltip is positioned.
+ , distance = 25 //Distance to offset tooltip from the mouse location.
+ , snapDistance = 0 //Tolerance allowed before tooltip is moved from its current position (creates 'snapping' effect)
+ , fixedTop = null //If not null, this fixes the top position of the tooltip.
+ , classes = null //Attaches additional CSS classes to the tooltip DIV that is created.
+ , chartContainer = null //Parent dom element of the SVG that holds the chart.
+ , hidden = true // start off hidden, toggle with hide/show functions below
+ , hideDelay = 400 // delay before the tooltip hides after calling hide()
+ , tooltip = null // d3 select of tooltipElem below
+ , tooltipElem = null //actual DOM element representing the tooltip.
+ , position = {left: null, top: null} //Relative position of the tooltip inside chartContainer.
+ , offset = {left: 0, top: 0} //Offset of tooltip against the pointer
+ , enabled = true //True -> tooltips are rendered. False -> don't render tooltips.
+ , duration = 100 // duration for tooltip movement
+ , headerEnabled = true
+ ;
+
+ // set to true by interactive layer to adjust tooltip positions
+ // eventually we should probably fix interactive layer to get the position better.
+ // for now this is needed if you want to set chartContainer for normal tooltips, else it "fixes" it to broken
+ var isInteractiveLayer = false;
+
+ //Generates a unique id when you create a new tooltip() object
+ var id = "nvtooltip-" + Math.floor(Math.random() * 100000);
+
+ //CSS class to specify whether element should not have mouse events.
+ var nvPointerEventsClass = "nv-pointer-events-none";
+
+ //Format function for the tooltip values column
+ var valueFormatter = function(d,i) {
+ return d;
+ };
+
+ //Format function for the tooltip header value.
+ var headerFormatter = function(d) {
+ return d;
+ };
+
+ var keyFormatter = function(d, i) {
+ return d;
+ };
+
+ //By default, the tooltip model renders a beautiful table inside a DIV.
+ //You can override this function if a custom tooltip is desired.
+ var contentGenerator = function(d) {
+ if (d === null) {
+ return '';
+ }
+
+ var table = d3.select(document.createElement("table"));
+ if (headerEnabled) {
+ var theadEnter = table.selectAll("thead")
+ .data([d])
+ .enter().append("thead");
+
+ theadEnter.append("tr")
+ .append("td")
+ .attr("colspan", 3)
+ .append("strong")
+ .classed("x-value", true)
+ .html(headerFormatter(d.value));
+ }
+
+ var tbodyEnter = table.selectAll("tbody")
+ .data([d])
+ .enter().append("tbody");
+
+ var trowEnter = tbodyEnter.selectAll("tr")
+ .data(function(p) { return p.series})
+ .enter()
+ .append("tr")
+ .classed("highlight", function(p) { return p.highlight});
+
+ trowEnter.append("td")
+ .classed("legend-color-guide",true)
+ .append("div")
+ .style("background-color", function(p) { return p.color});
+
+ trowEnter.append("td")
+ .classed("key",true)
+ .html(function(p, i) {return keyFormatter(p.key, i)});
+
+ trowEnter.append("td")
+ .classed("value",true)
+ .html(function(p, i) { return valueFormatter(p.value, i) });
+
+
+ trowEnter.selectAll("td").each(function(p) {
+ if (p.highlight) {
+ var opacityScale = d3.scale.linear().domain([0,1]).range(["#fff",p.color]);
+ var opacity = 0.6;
+ d3.select(this)
+ .style("border-bottom-color", opacityScale(opacity))
+ .style("border-top-color", opacityScale(opacity))
+ ;
+ }
+ });
+
+ var html = table.node().outerHTML;
+ if (d.footer !== undefined)
+ html += "<div class='footer'>" + d.footer + "</div>";
+ return html;
+
+ };
+
+ var dataSeriesExists = function(d) {
+ if (d && d.series) {
+ if (d.series instanceof Array) {
+ return !!d.series.length;
+ }
+ // if object, it's okay just convert to array of the object
+ if (d.series instanceof Object) {
+ d.series = [d.series];
+ return true;
+ }
+ }
+ return false;
+ };
+
+ var calcTooltipPosition = function(pos) {
+ if (!tooltipElem) return;
+
+ nv.dom.read(function() {
+ var height = parseInt(tooltipElem.offsetHeight, 10),
+ width = parseInt(tooltipElem.offsetWidth, 10),
+ windowWidth = nv.utils.windowSize().width,
+ windowHeight = nv.utils.windowSize().height,
+ scrollTop = window.pageYOffset,
+ scrollLeft = window.pageXOffset,
+ left, top;
+
+ windowHeight = window.innerWidth >= document.body.scrollWidth ? windowHeight : windowHeight - 16;
+ windowWidth = window.innerHeight >= document.body.scrollHeight ? windowWidth : windowWidth - 16;
+
+
+ //Helper functions to find the total offsets of a given DOM element.
+ //Looks up the entire ancestry of an element, up to the first relatively positioned element.
+ var tooltipTop = function ( Elem ) {
+ var offsetTop = top;
+ do {
+ if( !isNaN( Elem.offsetTop ) ) {
+ offsetTop += (Elem.offsetTop);
+ }
+ Elem = Elem.offsetParent;
+ } while( Elem );
+ return offsetTop;
+ };
+ var tooltipLeft = function ( Elem ) {
+ var offsetLeft = left;
+ do {
+ if( !isNaN( Elem.offsetLeft ) ) {
+ offsetLeft += (Elem.offsetLeft);
+ }
+ Elem = Elem.offsetParent;
+ } while( Elem );
+ return offsetLeft;
+ };
+
+ // calculate position based on gravity
+ var tLeft, tTop;
+ switch (gravity) {
+ case 'e':
+ left = pos[0] - width - distance;
+ top = pos[1] - (height / 2);
+ tLeft = tooltipLeft(tooltipElem);
+ tTop = tooltipTop(tooltipElem);
+ if (tLeft < scrollLeft) left = pos[0] + distance > scrollLeft ? pos[0] + distance : scrollLeft - tLeft + left;
+ if (tTop < scrollTop) top = scrollTop - tTop + top;
+ if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height;
+ break;
+ case 'w':
+ left = pos[0] + distance;
+ top = pos[1] - (height / 2);
+ tLeft = tooltipLeft(tooltipElem);
+ tTop = tooltipTop(tooltipElem);
+ if (tLeft + width > windowWidth) left = pos[0] - width - distance;
+ if (tTop < scrollTop) top = scrollTop + 5;
+ if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height;
+ break;
+ case 'n':
+ left = pos[0] - (width / 2) - 5;
+ top = pos[1] + distance;
+ tLeft = tooltipLeft(tooltipElem);
+ tTop = tooltipTop(tooltipElem);
+ if (tLeft < scrollLeft) left = scrollLeft + 5;
+ if (tLeft + width > windowWidth) left = left - width/2 + 5;
+ if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height;
+ break;
+ case 's':
+ left = pos[0] - (width / 2);
+ top = pos[1] - height - distance;
+ tLeft = tooltipLeft(tooltipElem);
+ tTop = tooltipTop(tooltipElem);
+ if (tLeft < scrollLeft) left = scrollLeft + 5;
+ if (tLeft + width > windowWidth) left = left - width/2 + 5;
+ if (scrollTop > tTop) top = scrollTop;
+ break;
+ case 'none':
+ left = pos[0];
+ top = pos[1] - distance;
+ tLeft = tooltipLeft(tooltipElem);
+ tTop = tooltipTop(tooltipElem);
+ break;
+ }
+
+ // adjust tooltip offsets
+ left -= offset.left;
+ top -= offset.top;
+
+ // using tooltip.style('transform') returns values un-usable for tween
+ var box = tooltipElem.getBoundingClientRect();
+ var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
+ var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
+ var old_translate = 'translate(' + (box.left + scrollLeft) + 'px, ' + (box.top + scrollTop) + 'px)';
+ var new_translate = 'translate(' + left + 'px, ' + top + 'px)';
+ var translateInterpolator = d3.interpolateString(old_translate, new_translate);
+
+ var is_hidden = tooltip.style('opacity') < 0.1;
+
+ // delay hiding a bit to avoid flickering
+ if (hidden) {
+ tooltip
+ .transition()
+ .delay(hideDelay)
+ .duration(0)
+ .style('opacity', 0);
+ } else {
+ tooltip
+ .interrupt() // cancel running transitions
+ .transition()
+ .duration(is_hidden ? 0 : duration)
+ // using tween since some versions of d3 can't auto-tween a translate on a div
+ .styleTween('transform', function (d) {
+ return translateInterpolator;
+ }, 'important')
+ // Safari has its own `-webkit-transform` and does not support `transform`
+ // transform tooltip without transition only in Safari
+ .style('-webkit-transform', new_translate)
+ .style('opacity', 1);
+ }
+
+
+
+ });
+ };
+
+ //In situations where the chart is in a 'viewBox', re-position the tooltip based on how far chart is zoomed.
+ function convertViewBoxRatio() {
+ if (chartContainer) {
+ var svg = d3.select(chartContainer);
+ if (svg.node().tagName !== "svg") {
+ svg = svg.select("svg");
+ }
+ var viewBox = (svg.node()) ? svg.attr('viewBox') : null;
+ if (viewBox) {
+ viewBox = viewBox.split(' ');
+ var ratio = parseInt(svg.style('width'), 10) / viewBox[2];
+
+ position.left = position.left * ratio;
+ position.top = position.top * ratio;
+ }
+ }
+ }
+
+ //Creates new tooltip container, or uses existing one on DOM.
+ function initTooltip() {
+ if (!tooltip) {
+ var body;
+ if (chartContainer) {
+ body = chartContainer;
+ } else {
+ body = document.body;
+ }
+ //Create new tooltip div if it doesn't exist on DOM.
+ tooltip = d3.select(body).append("div")
+ .attr("class", "nvtooltip " + (classes ? classes : "xy-tooltip"))
+ .attr("id", id);
+ tooltip.style("top", 0).style("left", 0);
+ tooltip.style('opacity', 0);
+ tooltip.selectAll("div, table, td, tr").classed(nvPointerEventsClass, true);
+ tooltip.classed(nvPointerEventsClass, true);
+ tooltipElem = tooltip.node();
+ }
+ }
+
+ //Draw the tooltip onto the DOM.
+ function nvtooltip() {
+ if (!enabled) return;
+ if (!dataSeriesExists(data)) return;
+
+ convertViewBoxRatio();
+
+ var left = position.left;
+ var top = (fixedTop !== null) ? fixedTop : position.top;
+
+ nv.dom.write(function () {
+ initTooltip();
+ // generate data and set it into tooltip
+ // Bonus - If you override contentGenerator and return falsey you can use something like
+ // React or Knockout to bind the data for your tooltip
+ var newContent = contentGenerator(data);
+ if (newContent) {
+ tooltipElem.innerHTML = newContent;
+ }
+
+ if (chartContainer && isInteractiveLayer) {
+ nv.dom.read(function() {
+ var svgComp = chartContainer.getElementsByTagName("svg")[0];
+ var svgOffset = {left:0,top:0};
+ if (svgComp) {
+ var svgBound = svgComp.getBoundingClientRect();
+ var chartBound = chartContainer.getBoundingClientRect();
+ var svgBoundTop = svgBound.top;
+
+ //Defensive code. Sometimes, svgBoundTop can be a really negative
+ // number, like -134254. That's a bug.
+ // If such a number is found, use zero instead. FireFox bug only
+ if (svgBoundTop < 0) {
+ var containerBound = chartContainer.getBoundingClientRect();
+ svgBoundTop = (Math.abs(svgBoundTop) > containerBound.height) ? 0 : svgBoundTop;
+ }
+ svgOffset.top = Math.abs(svgBoundTop - chartBound.top);
+ svgOffset.left = Math.abs(svgBound.left - chartBound.left);
+ }
+ //If the parent container is an overflow <div> with scrollbars, subtract the scroll offsets.
+ //You need to also add any offset between the <svg> element and its containing <div>
+ //Finally, add any offset of the containing <div> on the whole page.
+ left += chartContainer.offsetLeft + svgOffset.left - 2*chartContainer.scrollLeft;
+ top += chartContainer.offsetTop + svgOffset.top - 2*chartContainer.scrollTop;
+
+ if (snapDistance && snapDistance > 0) {
+ top = Math.floor(top/snapDistance) * snapDistance;
+ }
+ calcTooltipPosition([left,top]);
+ });
+ } else {
+ calcTooltipPosition([left,top]);
+ }
+ });
+
+ return nvtooltip;
+ }
+
+ nvtooltip.nvPointerEventsClass = nvPointerEventsClass;
+ nvtooltip.options = nv.utils.optionsFunc.bind(nvtooltip);
+
+ nvtooltip._options = Object.create({}, {
+ // simple read/write options
+ duration: {get: function(){return duration;}, set: function(_){duration=_;}},
+ gravity: {get: function(){return gravity;}, set: function(_){gravity=_;}},
+ distance: {get: function(){return distance;}, set: function(_){distance=_;}},
+ snapDistance: {get: function(){return snapDistance;}, set: function(_){snapDistance=_;}},
+ classes: {get: function(){return classes;}, set: function(_){classes=_;}},
+ chartContainer: {get: function(){return chartContainer;}, set: function(_){chartContainer=_;}},
+ fixedTop: {get: function(){return fixedTop;}, set: function(_){fixedTop=_;}},
+ enabled: {get: function(){return enabled;}, set: function(_){enabled=_;}},
+ hideDelay: {get: function(){return hideDelay;}, set: function(_){hideDelay=_;}},
+ contentGenerator: {get: function(){return contentGenerator;}, set: function(_){contentGenerator=_;}},
+ valueFormatter: {get: function(){return valueFormatter;}, set: function(_){valueFormatter=_;}},
+ headerFormatter: {get: function(){return headerFormatter;}, set: function(_){headerFormatter=_;}},
+ keyFormatter: {get: function(){return keyFormatter;}, set: function(_){keyFormatter=_;}},
+ headerEnabled: {get: function(){return headerEnabled;}, set: function(_){headerEnabled=_;}},
+
+ // internal use only, set by interactive layer to adjust position.
+ _isInteractiveLayer: {get: function(){return isInteractiveLayer;}, set: function(_){isInteractiveLayer=!!_;}},
+
+ // options with extra logic
+ position: {get: function(){return position;}, set: function(_){
+ position.left = _.left !== undefined ? _.left : position.left;
+ position.top = _.top !== undefined ? _.top : position.top;
+ }},
+ offset: {get: function(){return offset;}, set: function(_){
+ offset.left = _.left !== undefined ? _.left : offset.left;
+ offset.top = _.top !== undefined ? _.top : offset.top;
+ }},
+ hidden: {get: function(){return hidden;}, set: function(_){
+ if (hidden != _) {
+ hidden = !!_;
+ nvtooltip();
+ }
+ }},
+ data: {get: function(){return data;}, set: function(_){
+ // if showing a single data point, adjust data format with that
+ if (_.point) {
+ _.value = _.point.x;
+ _.series = _.series || {};
+ _.series.value = _.point.y;
+ _.series.color = _.point.color || _.series.color;
+ }
+ data = _;
+ }},
+
+ // read only properties
+ tooltipElem: {get: function(){return tooltipElem;}, set: function(_){}},
+ id: {get: function(){return id;}, set: function(_){}}
+ });
+
+ nv.utils.initOptions(nvtooltip);
+ return nvtooltip;
+ };
+
+})();
+
+
+/*
+Gets the browser window size
+
+Returns object with height and width properties
+ */
+nv.utils.windowSize = function() {
+ // Sane defaults
+ var size = {width: 640, height: 480};
+
+ // Most recent browsers use
+ if (window.innerWidth && window.innerHeight) {
+ size.width = window.innerWidth;
+ size.height = window.innerHeight;
+ return (size);
+ }
+
+ // IE can use depending on mode it is in
+ if (document.compatMode=='CSS1Compat' &&
+ document.documentElement &&
+ document.documentElement.offsetWidth ) {
+
+ size.width = document.documentElement.offsetWidth;
+ size.height = document.documentElement.offsetHeight;
+ return (size);
+ }
+
+ // Earlier IE uses Doc.body
+ if (document.body && document.body.offsetWidth) {
+ size.width = document.body.offsetWidth;
+ size.height = document.body.offsetHeight;
+ return (size);
+ }
+
+ return (size);
+};
+
+/*
+Binds callback function to run when window is resized
+ */
+nv.utils.windowResize = function(handler) {
+ if (window.addEventListener) {
+ window.addEventListener('resize', handler);
+ } else {
+ nv.log("ERROR: Failed to bind to window.resize with: ", handler);
+ }
+ // return object with clear function to remove the single added callback.
+ return {
+ callback: handler,
+ clear: function() {
+ window.removeEventListener('resize', handler);
+ }
+ }
+};
+
+
+/*
+Backwards compatible way to implement more d3-like coloring of graphs.
+Can take in nothing, an array, or a function/scale
+To use a normal scale, get the range and pass that because we must be able
+to take two arguments and use the index to keep backward compatibility
+*/
+nv.utils.getColor = function(color) {
+ //if you pass in nothing, get default colors back
+ if (color === undefined) {
+ return nv.utils.defaultColor();
+
+ //if passed an array, turn it into a color scale
+ // use isArray, instanceof fails if d3 range is created in an iframe
+ } else if(Array.isArray(color)) {
+ var color_scale = d3.scale.ordinal().range(color);
+ return function(d, i) {
+ var key = i === undefined ? d : i;
+ return d.color || color_scale(key);
+ };
+
+ //if passed a function or scale, return it, or whatever it may be
+ //external libs, such as angularjs-nvd3-directives use this
+ } else {
+ //can't really help it if someone passes rubbish as color
+ return color;
+ }
+};
+
+
+/*
+Default color chooser uses a color scale of 20 colors from D3
+ https://github.com/mbostock/d3/wiki/Ordinal-Scales#categorical-colors
+ */
+nv.utils.defaultColor = function() {
+ // get range of the scale so we'll turn it into our own function.
+ return nv.utils.getColor(d3.scale.category20().range());
+};
+
+
+/*
+Returns a color function that takes the result of 'getKey' for each series and
+looks for a corresponding color from the dictionary
+*/
+nv.utils.customTheme = function(dictionary, getKey, defaultColors) {
+ // use default series.key if getKey is undefined
+ getKey = getKey || function(series) { return series.key };
+ defaultColors = defaultColors || d3.scale.category20().range();
+
+ // start at end of default color list and walk back to index 0
+ var defIndex = defaultColors.length;
+
+ return function(series, index) {
+ var key = getKey(series);
+ if (typeof dictionary[key] === 'function') {
+ return dictionary[key]();
+ } else if (dictionary[key] !== undefined) {
+ return dictionary[key];
+ } else {
+ // no match in dictionary, use a default color
+ if (!defIndex) {
+ // used all the default colors, start over
+ defIndex = defaultColors.length;
+ }
+ defIndex = defIndex - 1;
+ return defaultColors[defIndex];
+ }
+ };
+};
+
+
+/*
+From the PJAX example on d3js.org, while this is not really directly needed
+it's a very cool method for doing pjax, I may expand upon it a little bit,
+open to suggestions on anything that may be useful
+*/
+nv.utils.pjax = function(links, content) {
+
+ var load = function(href) {
+ d3.html(href, function(fragment) {
+ var target = d3.select(content).node();
+ target.parentNode.replaceChild(
+ d3.select(fragment).select(content).node(),
+ target);
+ nv.utils.pjax(links, content);
+ });
+ };
+
+ d3.selectAll(links).on("click", function() {
+ history.pushState(this.href, this.textContent, this.href);
+ load(this.href);
+ d3.event.preventDefault();
+ });
+
+ d3.select(window).on("popstate", function() {
+ if (d3.event.state) {
+ load(d3.event.state);
+ }
+ });
+};
+
+
+/*
+For when we want to approximate the width in pixels for an SVG:text element.
+Most common instance is when the element is in a display:none; container.
+Forumla is : text.length * font-size * constant_factor
+*/
+nv.utils.calcApproxTextWidth = function (svgTextElem) {
+ if (typeof svgTextElem.style === 'function'
+ && typeof svgTextElem.text === 'function') {
+
+ var fontSize = parseInt(svgTextElem.style("font-size").replace("px",""), 10);
+ var textLength = svgTextElem.text().length;
+ return textLength * fontSize * 0.5;
+ }
+ return 0;
+};
+
+
+/*
+Numbers that are undefined, null or NaN, convert them to zeros.
+*/
+nv.utils.NaNtoZero = function(n) {
+ if (typeof n !== 'number'
+ || isNaN(n)
+ || n === null
+ || n === Infinity
+ || n === -Infinity) {
+
+ return 0;
+ }
+ return n;
+};
+
+/*
+Add a way to watch for d3 transition ends to d3
+*/
+d3.selection.prototype.watchTransition = function(renderWatch){
+ var args = [this].concat([].slice.call(arguments, 1));
+ return renderWatch.transition.apply(renderWatch, args);
+};
+
+
+/*
+Helper object to watch when d3 has rendered something
+*/
+nv.utils.renderWatch = function(dispatch, duration) {
+ if (!(this instanceof nv.utils.renderWatch)) {
+ return new nv.utils.renderWatch(dispatch, duration);
+ }
+
+ var _duration = duration !== undefined ? duration : 250;
+ var renderStack = [];
+ var self = this;
+
+ this.models = function(models) {
+ models = [].slice.call(arguments, 0);
+ models.forEach(function(model){
+ model.__rendered = false;
+ (function(m){
+ m.dispatch.on('renderEnd', function(arg){
+ m.__rendered = true;
+ self.renderEnd('model');
+ });
+ })(model);
+
+ if (renderStack.indexOf(model) < 0) {
+ renderStack.push(model);
+ }
+ });
+ return this;
+ };
+
+ this.reset = function(duration) {
+ if (duration !== undefined) {
+ _duration = duration;
+ }
+ renderStack = [];
+ };
+
+ this.transition = function(selection, args, duration) {
+ args = arguments.length > 1 ? [].slice.call(arguments, 1) : [];
+
+ if (args.length > 1) {
+ duration = args.pop();
+ } else {
+ duration = _duration !== undefined ? _duration : 250;
+ }
+ selection.__rendered = false;
+
+ if (renderStack.indexOf(selection) < 0) {
+ renderStack.push(selection);
+ }
+
+ if (duration === 0) {
+ selection.__rendered = true;
+ selection.delay = function() { return this; };
+ selection.duration = function() { return this; };
+ return selection;
+ } else {
+ if (selection.length === 0) {
+ selection.__rendered = true;
+ } else if (selection.every( function(d){ return !d.length; } )) {
+ selection.__rendered = true;
+ } else {
+ selection.__rendered = false;
+ }
+
+ var n = 0;
+ return selection
+ .transition()
+ .duration(duration)
+ .each(function(){ ++n; })
+ .each('end', function(d, i) {
+ if (--n === 0) {
+ selection.__rendered = true;
+ self.renderEnd.apply(this, args);
+ }
+ });
+ }
+ };
+
+ this.renderEnd = function() {
+ if (renderStack.every( function(d){ return d.__rendered; } )) {
+ renderStack.forEach( function(d){ d.__rendered = false; });
+ dispatch.renderEnd.apply(this, arguments);
+ }
+ }
+
+};
+
+
+/*
+Takes multiple objects and combines them into the first one (dst)
+example: nv.utils.deepExtend({a: 1}, {a: 2, b: 3}, {c: 4});
+gives: {a: 2, b: 3, c: 4}
+*/
+nv.utils.deepExtend = function(dst){
+ var sources = arguments.length > 1 ? [].slice.call(arguments, 1) : [];
+ sources.forEach(function(source) {
+ for (var key in source) {
+ var isArray = dst[key] instanceof Array;
+ var isObject = typeof dst[key] === 'object';
+ var srcObj = typeof source[key] === 'object';
+
+ if (isObject && !isArray && srcObj) {
+ nv.utils.deepExtend(dst[key], source[key]);
+ } else {
+ dst[key] = source[key];
+ }
+ }
+ });
+};
+
+
+/*
+state utility object, used to track d3 states in the models
+*/
+nv.utils.state = function(){
+ if (!(this instanceof nv.utils.state)) {
+ return new nv.utils.state();
+ }
+ var state = {};
+ var _self = this;
+ var _setState = function(){};
+ var _getState = function(){ return {}; };
+ var init = null;
+ var changed = null;
+
+ this.dispatch = d3.dispatch('change', 'set');
+
+ this.dispatch.on('set', function(state){
+ _setState(state, true);
+ });
+
+ this.getter = function(fn){
+ _getState = fn;
+ return this;
+ };
+
+ this.setter = function(fn, callback) {
+ if (!callback) {
+ callback = function(){};
+ }
+ _setState = function(state, update){
+ fn(state);
+ if (update) {
+ callback();
+ }
+ };
+ return this;
+ };
+
+ this.init = function(state){
+ init = init || {};
+ nv.utils.deepExtend(init, state);
+ };
+
+ var _set = function(){
+ var settings = _getState();
+
+ if (JSON.stringify(settings) === JSON.stringify(state)) {
+ return false;
+ }
+
+ for (var key in settings) {
+ if (state[key] === undefined) {
+ state[key] = {};
+ }
+ state[key] = settings[key];
+ changed = true;
+ }
+ return true;
+ };
+
+ this.update = function(){
+ if (init) {
+ _setState(init, false);
+ init = null;
+ }
+ if (_set.call(this)) {
+ this.dispatch.change(state);
+ }
+ };
+
+};
+
+
+/*
+Snippet of code you can insert into each nv.models.* to give you the ability to
+do things like:
+chart.options({
+ showXAxis: true,
+ tooltips: true
+});
+
+To enable in the chart:
+chart.options = nv.utils.optionsFunc.bind(chart);
+*/
+nv.utils.optionsFunc = function(args) {
+ if (args) {
+ d3.map(args).forEach((function(key,value) {
+ if (typeof this[key] === "function") {
+ this[key](value);
+ }
+ }).bind(this));
+ }
+ return this;
+};
+
+
+/*
+numTicks: requested number of ticks
+data: the chart data
+
+returns the number of ticks to actually use on X axis, based on chart data
+to avoid duplicate ticks with the same value
+*/
+nv.utils.calcTicksX = function(numTicks, data) {
+ // find max number of values from all data streams
+ var numValues = 1;
+ var i = 0;
+ for (i; i < data.length; i += 1) {
+ var stream_len = data[i] && data[i].values ? data[i].values.length : 0;
+ numValues = stream_len > numValues ? stream_len : numValues;
+ }
+ nv.log("Requested number of ticks: ", numTicks);
+ nv.log("Calculated max values to be: ", numValues);
+ // make sure we don't have more ticks than values to avoid duplicates
+ numTicks = numTicks > numValues ? numTicks = numValues - 1 : numTicks;
+ // make sure we have at least one tick
+ numTicks = numTicks < 1 ? 1 : numTicks;
+ // make sure it's an integer
+ numTicks = Math.floor(numTicks);
+ nv.log("Calculating tick count as: ", numTicks);
+ return numTicks;
+};
+
+
+/*
+returns number of ticks to actually use on Y axis, based on chart data
+*/
+nv.utils.calcTicksY = function(numTicks, data) {
+ // currently uses the same logic but we can adjust here if needed later
+ return nv.utils.calcTicksX(numTicks, data);
+};
+
+
+/*
+Add a particular option from an options object onto chart
+Options exposed on a chart are a getter/setter function that returns chart
+on set to mimic typical d3 option chaining, e.g. svg.option1('a').option2('b');
+
+option objects should be generated via Object.create() to provide
+the option of manipulating data via get/set functions.
+*/
+nv.utils.initOption = function(chart, name) {
+ // if it's a call option, just call it directly, otherwise do get/set
+ if (chart._calls && chart._calls[name]) {
+ chart[name] = chart._calls[name];
+ } else {
+ chart[name] = function (_) {
+ if (!arguments.length) return chart._options[name];
+ chart._overrides[name] = true;
+ chart._options[name] = _;
+ return chart;
+ };
+ // calling the option as _option will ignore if set by option already
+ // so nvd3 can set options internally but the stop if set manually
+ chart['_' + name] = function(_) {
+ if (!arguments.length) return chart._options[name];
+ if (!chart._overrides[name]) {
+ chart._options[name] = _;
+ }
+ return chart;
+ }
+ }
+};
+
+
+/*
+Add all options in an options object to the chart
+*/
+nv.utils.initOptions = function(chart) {
+ chart._overrides = chart._overrides || {};
+ var ops = Object.getOwnPropertyNames(chart._options || {});
+ var calls = Object.getOwnPropertyNames(chart._calls || {});
+ ops = ops.concat(calls);
+ for (var i in ops) {
+ nv.utils.initOption(chart, ops[i]);
+ }
+};
+
+
+/*
+Inherit options from a D3 object
+d3.rebind makes calling the function on target actually call it on source
+Also use _d3options so we can track what we inherit for documentation and chained inheritance
+*/
+nv.utils.inheritOptionsD3 = function(target, d3_source, oplist) {
+ target._d3options = oplist.concat(target._d3options || []);
+ oplist.unshift(d3_source);
+ oplist.unshift(target);
+ d3.rebind.apply(this, oplist);
+};
+
+
+/*
+Remove duplicates from an array
+*/
+nv.utils.arrayUnique = function(a) {
+ return a.sort().filter(function(item, pos) {
+ return !pos || item != a[pos - 1];
+ });
+};
+
+
+/*
+Keeps a list of custom symbols to draw from in addition to d3.svg.symbol
+Necessary since d3 doesn't let you extend its list -_-
+Add new symbols by doing nv.utils.symbols.set('name', function(size){...});
+*/
+nv.utils.symbolMap = d3.map();
+
+
+/*
+Replaces d3.svg.symbol so that we can look both there and our own map
+ */
+nv.utils.symbol = function() {
+ var type,
+ size = 64;
+ function symbol(d,i) {
+ var t = type.call(this,d,i);
+ var s = size.call(this,d,i);
+ if (d3.svg.symbolTypes.indexOf(t) !== -1) {
+ return d3.svg.symbol().type(t).size(s)();
+ } else {
+ return nv.utils.symbolMap.get(t)(s);
+ }
+ }
+ symbol.type = function(_) {
+ if (!arguments.length) return type;
+ type = d3.functor(_);
+ return symbol;
+ };
+ symbol.size = function(_) {
+ if (!arguments.length) return size;
+ size = d3.functor(_);
+ return symbol;
+ };
+ return symbol;
+};
+
+
+/*
+Inherit option getter/setter functions from source to target
+d3.rebind makes calling the function on target actually call it on source
+Also track via _inherited and _d3options so we can track what we inherit
+for documentation generation purposes and chained inheritance
+*/
+nv.utils.inheritOptions = function(target, source) {
+ // inherit all the things
+ var ops = Object.getOwnPropertyNames(source._options || {});
+ var calls = Object.getOwnPropertyNames(source._calls || {});
+ var inherited = source._inherited || [];
+ var d3ops = source._d3options || [];
+ var args = ops.concat(calls).concat(inherited).concat(d3ops);
+ args.unshift(source);
+ args.unshift(target);
+ d3.rebind.apply(this, args);
+ // pass along the lists to keep track of them, don't allow duplicates
+ target._inherited = nv.utils.arrayUnique(ops.concat(calls).concat(inherited).concat(ops).concat(target._inherited || []));
+ target._d3options = nv.utils.arrayUnique(d3ops.concat(target._d3options || []));
+};
+
+
+/*
+Runs common initialize code on the svg before the chart builds
+*/
+nv.utils.initSVG = function(svg) {
+ svg.classed({'nvd3-svg':true});
+};
+
+
+/*
+Sanitize and provide default for the container height.
+*/
+nv.utils.sanitizeHeight = function(height, container) {
+ return (height || parseInt(container.style('height'), 10) || 400);
+};
+
+
+/*
+Sanitize and provide default for the container width.
+*/
+nv.utils.sanitizeWidth = function(width, container) {
+ return (width || parseInt(container.style('width'), 10) || 960);
+};
+
+
+/*
+Calculate the available height for a chart.
+*/
+nv.utils.availableHeight = function(height, container, margin) {
+ return nv.utils.sanitizeHeight(height, container) - margin.top - margin.bottom;
+};
+
+/*
+Calculate the available width for a chart.
+*/
+nv.utils.availableWidth = function(width, container, margin) {
+ return nv.utils.sanitizeWidth(width, container) - margin.left - margin.right;
+};
+
+/*
+Clear any rendered chart components and display a chart's 'noData' message
+*/
+nv.utils.noData = function(chart, container) {
+ var opt = chart.options(),
+ margin = opt.margin(),
+ noData = opt.noData(),
+ data = (noData == null) ? ["No Data Available."] : [noData],
+ height = nv.utils.availableHeight(opt.height(), container, margin),
+ width = nv.utils.availableWidth(opt.width(), container, margin),
+ x = margin.left + width/2,
+ y = margin.top + height/2;
+
+ //Remove any previously created chart components
+ container.selectAll('g').remove();
+
+ var noDataText = container.selectAll('.nv-noData').data(data);
+
+ noDataText.enter().append('text')
+ .attr('class', 'nvd3 nv-noData')
+ .attr('dy', '-.7em')
+ .style('text-anchor', 'middle');
+
+ noDataText
+ .attr('x', x)
+ .attr('y', y)
+ .text(function(t){ return t; });
+};
+
+nv.models.axis = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var axis = d3.svg.axis();
+ var scale = d3.scale.linear();
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = 75 //only used for tickLabel currently
+ , height = 60 //only used for tickLabel currently
+ , axisLabelText = null
+ , showMaxMin = true //TODO: showMaxMin should be disabled on all ordinal scaled axes
+ , rotateLabels = 0
+ , rotateYLabel = true
+ , staggerLabels = false
+ , isOrdinal = false
+ , ticks = null
+ , axisLabelDistance = 0
+ , duration = 250
+ , dispatch = d3.dispatch('renderEnd')
+ ;
+ axis
+ .scale(scale)
+ .orient('bottom')
+ .tickFormat(function(d) { return d })
+ ;
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var scale0;
+ var renderWatch = nv.utils.renderWatch(dispatch, duration);
+
+ function chart(selection) {
+ renderWatch.reset();
+ selection.each(function(data) {
+ var container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-axis').data([data]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-axis');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ if (ticks !== null)
+ axis.ticks(ticks);
+ else if (axis.orient() == 'top' || axis.orient() == 'bottom')
+ axis.ticks(Math.abs(scale.range()[1] - scale.range()[0]) / 100);
+
+ //TODO: consider calculating width/height based on whether or not label is added, for reference in charts using this component
+ g.watchTransition(renderWatch, 'axis').call(axis);
+
+ scale0 = scale0 || axis.scale();
+
+ var fmt = axis.tickFormat();
+ if (fmt == null) {
+ fmt = scale0.tickFormat();
+ }
+
+ var axisLabel = g.selectAll('text.nv-axislabel')
+ .data([axisLabelText || null]);
+ axisLabel.exit().remove();
+
+ var xLabelMargin;
+ var axisMaxMin;
+ var w;
+ switch (axis.orient()) {
+ case 'top':
+ axisLabel.enter().append('text').attr('class', 'nv-axislabel');
+ if (scale.range().length < 2) {
+ w = 0;
+ } else if (scale.range().length === 2) {
+ w = scale.range()[1];
+ } else {
+ w = scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0]);
+ }
+ axisLabel
+ .attr('text-anchor', 'middle')
+ .attr('y', 0)
+ .attr('x', w/2);
+ if (showMaxMin) {
+ axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
+ .data(scale.domain());
+ axisMaxMin.enter().append('g').attr('class',function(d,i){
+ return ['nv-axisMaxMin','nv-axisMaxMin-x',(i == 0 ? 'nv-axisMin-x':'nv-axisMax-x')].join(' ')
+ }).append('text');
+ axisMaxMin.exit().remove();
+ axisMaxMin
+ .attr('transform', function(d,i) {
+ return 'translate(' + nv.utils.NaNtoZero(scale(d)) + ',0)'
+ })
+ .select('text')
+ .attr('dy', '-0.5em')
+ .attr('y', -axis.tickPadding())
+ .attr('text-anchor', 'middle')
+ .text(function(d,i) {
+ var v = fmt(d);
+ return ('' + v).match('NaN') ? '' : v;
+ });
+ axisMaxMin.watchTransition(renderWatch, 'min-max top')
+ .attr('transform', function(d,i) {
+ return 'translate(' + nv.utils.NaNtoZero(scale.range()[i]) + ',0)'
+ });
+ }
+ break;
+ case 'bottom':
+ xLabelMargin = axisLabelDistance + 36;
+ var maxTextWidth = 30;
+ var textHeight = 0;
+ var xTicks = g.selectAll('g').select("text");
+ var rotateLabelsRule = '';
+ if (rotateLabels%360) {
+ //Calculate the longest xTick width
+ xTicks.each(function(d,i){
+ var box = this.getBoundingClientRect();
+ var width = box.width;
+ textHeight = box.height;
+ if(width > maxTextWidth) maxTextWidth = width;
+ });
+ rotateLabelsRule = 'rotate(' + rotateLabels + ' 0,' + (textHeight/2 + axis.tickPadding()) + ')';
+ //Convert to radians before calculating sin. Add 30 to margin for healthy padding.
+ var sin = Math.abs(Math.sin(rotateLabels*Math.PI/180));
+ xLabelMargin = (sin ? sin*maxTextWidth : maxTextWidth)+30;
+ //Rotate all xTicks
+ xTicks
+ .attr('transform', rotateLabelsRule)
+ .style('text-anchor', rotateLabels%360 > 0 ? 'start' : 'end');
+ }
+ axisLabel.enter().append('text').attr('class', 'nv-axislabel');
+ if (scale.range().length < 2) {
+ w = 0;
+ } else if (scale.range().length === 2) {
+ w = scale.range()[1];
+ } else {
+ w = scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0]);
+ }
+ axisLabel
+ .attr('text-anchor', 'middle')
+ .attr('y', xLabelMargin)
+ .attr('x', w/2);
+ if (showMaxMin) {
+ //if (showMaxMin && !isOrdinal) {
+ axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
+ //.data(scale.domain())
+ .data([scale.domain()[0], scale.domain()[scale.domain().length - 1]]);
+ axisMaxMin.enter().append('g').attr('class',function(d,i){
+ return ['nv-axisMaxMin','nv-axisMaxMin-x',(i == 0 ? 'nv-axisMin-x':'nv-axisMax-x')].join(' ')
+ }).append('text');
+ axisMaxMin.exit().remove();
+ axisMaxMin
+ .attr('transform', function(d,i) {
+ return 'translate(' + nv.utils.NaNtoZero((scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0))) + ',0)'
+ })
+ .select('text')
+ .attr('dy', '.71em')
+ .attr('y', axis.tickPadding())
+ .attr('transform', rotateLabelsRule)
+ .style('text-anchor', rotateLabels ? (rotateLabels%360 > 0 ? 'start' : 'end') : 'middle')
+ .text(function(d,i) {
+ var v = fmt(d);
+ return ('' + v).match('NaN') ? '' : v;
+ });
+ axisMaxMin.watchTransition(renderWatch, 'min-max bottom')
+ .attr('transform', function(d,i) {
+ return 'translate(' + nv.utils.NaNtoZero((scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0))) + ',0)'
+ });
+ }
+ if (staggerLabels)
+ xTicks
+ .attr('transform', function(d,i) {
+ return 'translate(0,' + (i % 2 == 0 ? '0' : '12') + ')'
+ });
+
+ break;
+ case 'right':
+ axisLabel.enter().append('text').attr('class', 'nv-axislabel');
+ axisLabel
+ .style('text-anchor', rotateYLabel ? 'middle' : 'begin')
+ .attr('transform', rotateYLabel ? 'rotate(90)' : '')
+ .attr('y', rotateYLabel ? (-Math.max(margin.right, width) + 12) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart
+ .attr('x', rotateYLabel ? (d3.max(scale.range()) / 2) : axis.tickPadding());
+ if (showMaxMin) {
+ axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
+ .data(scale.domain());
+ axisMaxMin.enter().append('g').attr('class',function(d,i){
+ return ['nv-axisMaxMin','nv-axisMaxMin-y',(i == 0 ? 'nv-axisMin-y':'nv-axisMax-y')].join(' ')
+ }).append('text')
+ .style('opacity', 0);
+ axisMaxMin.exit().remove();
+ axisMaxMin
+ .attr('transform', function(d,i) {
+ return 'translate(0,' + nv.utils.NaNtoZero(scale(d)) + ')'
+ })
+ .select('text')
+ .attr('dy', '.32em')
+ .attr('y', 0)
+ .attr('x', axis.tickPadding())
+ .style('text-anchor', 'start')
+ .text(function(d, i) {
+ var v = fmt(d);
+ return ('' + v).match('NaN') ? '' : v;
+ });
+ axisMaxMin.watchTransition(renderWatch, 'min-max right')
+ .attr('transform', function(d,i) {
+ return 'translate(0,' + nv.utils.NaNtoZero(scale.range()[i]) + ')'
+ })
+ .select('text')
+ .style('opacity', 1);
+ }
+ break;
+ case 'left':
+ /*
+ //For dynamically placing the label. Can be used with dynamically-sized chart axis margins
+ var yTicks = g.selectAll('g').select("text");
+ yTicks.each(function(d,i){
+ var labelPadding = this.getBoundingClientRect().width + axis.tickPadding() + 16;
+ if(labelPadding > width) width = labelPadding;
+ });
+ */
+ axisLabel.enter().append('text').attr('class', 'nv-axislabel');
+ axisLabel
+ .style('text-anchor', rotateYLabel ? 'middle' : 'end')
+ .attr('transform', rotateYLabel ? 'rotate(-90)' : '')
+ .attr('y', rotateYLabel ? (-Math.max(margin.left, width) + 25 - (axisLabelDistance || 0)) : -10)
+ .attr('x', rotateYLabel ? (-d3.max(scale.range()) / 2) : -axis.tickPadding());
+ if (showMaxMin) {
+ axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
+ .data(scale.domain());
+ axisMaxMin.enter().append('g').attr('class',function(d,i){
+ return ['nv-axisMaxMin','nv-axisMaxMin-y',(i == 0 ? 'nv-axisMin-y':'nv-axisMax-y')].join(' ')
+ }).append('text')
+ .style('opacity', 0);
+ axisMaxMin.exit().remove();
+ axisMaxMin
+ .attr('transform', function(d,i) {
+ return 'translate(0,' + nv.utils.NaNtoZero(scale0(d)) + ')'
+ })
+ .select('text')
+ .attr('dy', '.32em')
+ .attr('y', 0)
+ .attr('x', -axis.tickPadding())
+ .attr('text-anchor', 'end')
+ .text(function(d,i) {
+ var v = fmt(d);
+ return ('' + v).match('NaN') ? '' : v;
+ });
+ axisMaxMin.watchTransition(renderWatch, 'min-max right')
+ .attr('transform', function(d,i) {
+ return 'translate(0,' + nv.utils.NaNtoZero(scale.range()[i]) + ')'
+ })
+ .select('text')
+ .style('opacity', 1);
+ }
+ break;
+ }
+ axisLabel.text(function(d) { return d });
+
+ if (showMaxMin && (axis.orient() === 'left' || axis.orient() === 'right')) {
+ //check if max and min overlap other values, if so, hide the values that overlap
+ g.selectAll('g') // the g's wrapping each tick
+ .each(function(d,i) {
+ d3.select(this).select('text').attr('opacity', 1);
+ if (scale(d) < scale.range()[1] + 10 || scale(d) > scale.range()[0] - 10) { // 10 is assuming text height is 16... if d is 0, leave it!
+ if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL
+ d3.select(this).attr('opacity', 0);
+
+ d3.select(this).select('text').attr('opacity', 0); // Don't remove the ZERO line!!
+ }
+ });
+
+ //if Max and Min = 0 only show min, Issue #281
+ if (scale.domain()[0] == scale.domain()[1] && scale.domain()[0] == 0) {
+ wrap.selectAll('g.nv-axisMaxMin').style('opacity', function (d, i) {
+ return !i ? 1 : 0
+ });
+ }
+ }
+
+ if (showMaxMin && (axis.orient() === 'top' || axis.orient() === 'bottom')) {
+ var maxMinRange = [];
+ wrap.selectAll('g.nv-axisMaxMin')
+ .each(function(d,i) {
+ try {
+ if (i) // i== 1, max position
+ maxMinRange.push(scale(d) - this.getBoundingClientRect().width - 4); //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case)
+ else // i==0, min position
+ maxMinRange.push(scale(d) + this.getBoundingClientRect().width + 4)
+ }catch (err) {
+ if (i) // i== 1, max position
+ maxMinRange.push(scale(d) - 4); //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case)
+ else // i==0, min position
+ maxMinRange.push(scale(d) + 4);
+ }
+ });
+ // the g's wrapping each tick
+ g.selectAll('g').each(function(d, i) {
+ if (scale(d) < maxMinRange[0] || scale(d) > maxMinRange[1]) {
+ if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL
+ d3.select(this).remove();
+ else
+ d3.select(this).select('text').remove(); // Don't remove the ZERO line!!
+ }
+ });
+ }
+
+ //Highlight zero tick line
+ g.selectAll('.tick')
+ .filter(function (d) {
+ /*
+ The filter needs to return only ticks at or near zero.
+ Numbers like 0.00001 need to count as zero as well,
+ and the arithmetic trick below solves that.
+ */
+ return !parseFloat(Math.round(d * 100000) / 1000000) && (d !== undefined)
+ })
+ .classed('zero', true);
+
+ //store old scales for use in transitions on update
+ scale0 = scale.copy();
+
+ });
+
+ renderWatch.renderEnd('axis immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ // expose chart's sub-components
+ chart.axis = axis;
+ chart.dispatch = dispatch;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ axisLabelDistance: {get: function(){return axisLabelDistance;}, set: function(_){axisLabelDistance=_;}},
+ staggerLabels: {get: function(){return staggerLabels;}, set: function(_){staggerLabels=_;}},
+ rotateLabels: {get: function(){return rotateLabels;}, set: function(_){rotateLabels=_;}},
+ rotateYLabel: {get: function(){return rotateYLabel;}, set: function(_){rotateYLabel=_;}},
+ showMaxMin: {get: function(){return showMaxMin;}, set: function(_){showMaxMin=_;}},
+ axisLabel: {get: function(){return axisLabelText;}, set: function(_){axisLabelText=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ ticks: {get: function(){return ticks;}, set: function(_){ticks=_;}},
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration=_;
+ renderWatch.reset(duration);
+ }},
+ scale: {get: function(){return scale;}, set: function(_){
+ scale = _;
+ axis.scale(scale);
+ isOrdinal = typeof scale.rangeBands === 'function';
+ nv.utils.inheritOptionsD3(chart, scale, ['domain', 'range', 'rangeBand', 'rangeBands']);
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+ nv.utils.inheritOptionsD3(chart, axis, ['orient', 'tickValues', 'tickSubdivide', 'tickSize', 'tickPadding', 'tickFormat']);
+ nv.utils.inheritOptionsD3(chart, scale, ['domain', 'range', 'rangeBand', 'rangeBands']);
+
+ return chart;
+};
+nv.models.boxPlot = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = 960
+ , height = 500
+ , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
+ , x = d3.scale.ordinal()
+ , y = d3.scale.linear()
+ , getX = function(d) { return d.x }
+ , getY = function(d) { return d.y }
+ , color = nv.utils.defaultColor()
+ , container = null
+ , xDomain
+ , yDomain
+ , xRange
+ , yRange
+ , dispatch = d3.dispatch('elementMouseover', 'elementMouseout', 'elementMousemove', 'renderEnd')
+ , duration = 250
+ , maxBoxWidth = null
+ ;
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var x0, y0;
+ var renderWatch = nv.utils.renderWatch(dispatch, duration);
+
+ function chart(selection) {
+ renderWatch.reset();
+ selection.each(function(data) {
+ var availableWidth = width - margin.left - margin.right,
+ availableHeight = height - margin.top - margin.bottom;
+
+ container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ // Setup Scales
+ x .domain(xDomain || data.map(function(d,i) { return getX(d,i); }))
+ .rangeBands(xRange || [0, availableWidth], .1);
+
+ // if we know yDomain, no need to calculate
+ var yData = []
+ if (!yDomain) {
+ // (y-range is based on quartiles, whiskers and outliers)
+
+ // lower values
+ var yMin = d3.min(data.map(function(d) {
+ var min_arr = [];
+
+ min_arr.push(d.values.Q1);
+ if (d.values.hasOwnProperty('whisker_low') && d.values.whisker_low !== null) { min_arr.push(d.values.whisker_low); }
+ if (d.values.hasOwnProperty('outliers') && d.values.outliers !== null) { min_arr = min_arr.concat(d.values.outliers); }
+
+ return d3.min(min_arr);
+ }));
+
+ // upper values
+ var yMax = d3.max(data.map(function(d) {
+ var max_arr = [];
+
+ max_arr.push(d.values.Q3);
+ if (d.values.hasOwnProperty('whisker_high') && d.values.whisker_high !== null) { max_arr.push(d.values.whisker_high); }
+ if (d.values.hasOwnProperty('outliers') && d.values.outliers !== null) { max_arr = max_arr.concat(d.values.outliers); }
+
+ return d3.max(max_arr);
+ }));
+
+ yData = [ yMin, yMax ] ;
+ }
+
+ y.domain(yDomain || yData);
+ y.range(yRange || [availableHeight, 0]);
+
+ //store old scales if they exist
+ x0 = x0 || x;
+ y0 = y0 || y.copy().range([y(0),y(0)]);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap').data([data]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap');
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ var boxplots = wrap.selectAll('.nv-boxplot').data(function(d) { return d });
+ var boxEnter = boxplots.enter().append('g').style('stroke-opacity', 1e-6).style('fill-opacity', 1e-6);
+ boxplots
+ .attr('class', 'nv-boxplot')
+ .attr('transform', function(d,i,j) { return 'translate(' + (x(getX(d,i)) + x.rangeBand() * .05) + ', 0)'; })
+ .classed('hover', function(d) { return d.hover });
+ boxplots
+ .watchTransition(renderWatch, 'nv-boxplot: boxplots')
+ .style('stroke-opacity', 1)
+ .style('fill-opacity', .75)
+ .delay(function(d,i) { return i * duration / data.length })
+ .attr('transform', function(d,i) {
+ return 'translate(' + (x(getX(d,i)) + x.rangeBand() * .05) + ', 0)';
+ });
+ boxplots.exit().remove();
+
+ // ----- add the SVG elements for each boxPlot -----
+
+ // conditionally append whisker lines
+ boxEnter.each(function(d,i) {
+ var box = d3.select(this);
+
+ ['low', 'high'].forEach(function(key) {
+ if (d.values.hasOwnProperty('whisker_' + key) && d.values['whisker_' + key] !== null) {
+ box.append('line')
+ .style('stroke', (d.color) ? d.color : color(d,i))
+ .attr('class', 'nv-boxplot-whisker nv-boxplot-' + key);
+
+ box.append('line')
+ .style('stroke', (d.color) ? d.color : color(d,i))
+ .attr('class', 'nv-boxplot-tick nv-boxplot-' + key);
+ }
+ });
+ });
+
+ // outliers
+ // TODO: support custom colors here
+ var outliers = boxplots.selectAll('.nv-boxplot-outlier').data(function(d) {
+ if (d.values.hasOwnProperty('outliers') && d.values.outliers !== null) { return d.values.outliers; }
+ else { return []; }
+ });
+ outliers.enter().append('circle')
+ .style('fill', function(d,i,j) { return color(d,j) }).style('stroke', function(d,i,j) { return color(d,j) })
+ .on('mouseover', function(d,i,j) {
+ d3.select(this).classed('hover', true);
+ dispatch.elementMouseover({
+ series: { key: d, color: color(d,j) },
+ e: d3.event
+ });
+ })
+ .on('mouseout', function(d,i,j) {
+ d3.select(this).classed('hover', false);
+ dispatch.elementMouseout({
+ series: { key: d, color: color(d,j) },
+ e: d3.event
+ });
+ })
+ .on('mousemove', function(d,i) {
+ dispatch.elementMousemove({e: d3.event});
+ });
+
+ outliers.attr('class', 'nv-boxplot-outlier');
+ outliers
+ .watchTransition(renderWatch, 'nv-boxplot: nv-boxplot-outlier')
+ .attr('cx', x.rangeBand() * .45)
+ .attr('cy', function(d,i,j) { return y(d); })
+ .attr('r', '3');
+ outliers.exit().remove();
+
+ var box_width = function() { return (maxBoxWidth === null ? x.rangeBand() * .9 : Math.min(75, x.rangeBand() * .9)); };
+ var box_left = function() { return x.rangeBand() * .45 - box_width()/2; };
+ var box_right = function() { return x.rangeBand() * .45 + box_width()/2; };
+
+ // update whisker lines and ticks
+ ['low', 'high'].forEach(function(key) {
+ var endpoint = (key === 'low') ? 'Q1' : 'Q3';
+
+ boxplots.select('line.nv-boxplot-whisker.nv-boxplot-' + key)
+ .watchTransition(renderWatch, 'nv-boxplot: boxplots')
+ .attr('x1', x.rangeBand() * .45 )
+ .attr('y1', function(d,i) { return y(d.values['whisker_' + key]); })
+ .attr('x2', x.rangeBand() * .45 )
+ .attr('y2', function(d,i) { return y(d.values[endpoint]); });
+
+ boxplots.select('line.nv-boxplot-tick.nv-boxplot-' + key)
+ .watchTransition(renderWatch, 'nv-boxplot: boxplots')
+ .attr('x1', box_left )
+ .attr('y1', function(d,i) { return y(d.values['whisker_' + key]); })
+ .attr('x2', box_right )
+ .attr('y2', function(d,i) { return y(d.values['whisker_' + key]); });
+ });
+
+ ['low', 'high'].forEach(function(key) {
+ boxEnter.selectAll('.nv-boxplot-' + key)
+ .on('mouseover', function(d,i,j) {
+ d3.select(this).classed('hover', true);
+ dispatch.elementMouseover({
+ series: { key: d.values['whisker_' + key], color: color(d,j) },
+ e: d3.event
+ });
+ })
+ .on('mouseout', function(d,i,j) {
+ d3.select(this).classed('hover', false);
+ dispatch.elementMouseout({
+ series: { key: d.values['whisker_' + key], color: color(d,j) },
+ e: d3.event
+ });
+ })
+ .on('mousemove', function(d,i) {
+ dispatch.elementMousemove({e: d3.event});
+ });
+ });
+
+ // boxes
+ boxEnter.append('rect')
+ .attr('class', 'nv-boxplot-box')
+ // tooltip events
+ .on('mouseover', function(d,i) {
+ d3.select(this).classed('hover', true);
+ dispatch.elementMouseover({
+ key: d.label,
+ value: d.label,
+ series: [
+ { key: 'Q3', value: d.values.Q3, color: d.color || color(d,i) },
+ { key: 'Q2', value: d.values.Q2, color: d.color || color(d,i) },
+ { key: 'Q1', value: d.values.Q1, color: d.color || color(d,i) }
+ ],
+ data: d,
+ index: i,
+ e: d3.event
+ });
+ })
+ .on('mouseout', function(d,i) {
+ d3.select(this).classed('hover', false);
+ dispatch.elementMouseout({
+ key: d.label,
+ value: d.label,
+ series: [
+ { key: 'Q3', value: d.values.Q3, color: d.color || color(d,i) },
+ { key: 'Q2', value: d.values.Q2, color: d.color || color(d,i) },
+ { key: 'Q1', value: d.values.Q1, color: d.color || color(d,i) }
+ ],
+ data: d,
+ index: i,
+ e: d3.event
+ });
+ })
+ .on('mousemove', function(d,i) {
+ dispatch.elementMousemove({e: d3.event});
+ });
+
+ // box transitions
+ boxplots.select('rect.nv-boxplot-box')
+ .watchTransition(renderWatch, 'nv-boxplot: boxes')
+ .attr('y', function(d,i) { return y(d.values.Q3); })
+ .attr('width', box_width)
+ .attr('x', box_left )
+
+ .attr('height', function(d,i) { return Math.abs(y(d.values.Q3) - y(d.values.Q1)) || 1 })
+ .style('fill', function(d,i) { return d.color || color(d,i) })
+ .style('stroke', function(d,i) { return d.color || color(d,i) });
+
+ // median line
+ boxEnter.append('line').attr('class', 'nv-boxplot-median');
+
+ boxplots.select('line.nv-boxplot-median')
+ .watchTransition(renderWatch, 'nv-boxplot: boxplots line')
+ .attr('x1', box_left)
+ .attr('y1', function(d,i) { return y(d.values.Q2); })
+ .attr('x2', box_right)
+ .attr('y2', function(d,i) { return y(d.values.Q2); });
+
+ //store old scales for use in transitions on update
+ x0 = x.copy();
+ y0 = y.copy();
+ });
+
+ renderWatch.renderEnd('nv-boxplot immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ maxBoxWidth: {get: function(){return maxBoxWidth;}, set: function(_){maxBoxWidth=_;}},
+ x: {get: function(){return getX;}, set: function(_){getX=_;}},
+ y: {get: function(){return getY;}, set: function(_){getY=_;}},
+ xScale: {get: function(){return x;}, set: function(_){x=_;}},
+ yScale: {get: function(){return y;}, set: function(_){y=_;}},
+ xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
+ yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
+ xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
+ yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
+ id: {get: function(){return id;}, set: function(_){id=_;}},
+ // rectClass: {get: function(){return rectClass;}, set: function(_){rectClass=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+nv.models.boxPlotChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var boxplot = nv.models.boxPlot()
+ , xAxis = nv.models.axis()
+ , yAxis = nv.models.axis()
+ ;
+
+ var margin = {top: 15, right: 10, bottom: 50, left: 60}
+ , width = null
+ , height = null
+ , color = nv.utils.getColor()
+ , showXAxis = true
+ , showYAxis = true
+ , rightAlignYAxis = false
+ , staggerLabels = false
+ , tooltip = nv.models.tooltip()
+ , x
+ , y
+ , noData = "No Data Available."
+ , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'beforeUpdate', 'renderEnd')
+ , duration = 250
+ ;
+
+ xAxis
+ .orient('bottom')
+ .showMaxMin(false)
+ .tickFormat(function(d) { return d })
+ ;
+ yAxis
+ .orient((rightAlignYAxis) ? 'right' : 'left')
+ .tickFormat(d3.format(',.1f'))
+ ;
+
+ tooltip.duration(0);
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var renderWatch = nv.utils.renderWatch(dispatch, duration);
+
+ function chart(selection) {
+ renderWatch.reset();
+ renderWatch.models(boxplot);
+ if (showXAxis) renderWatch.models(xAxis);
+ if (showYAxis) renderWatch.models(yAxis);
+
+ selection.each(function(data) {
+ var container = d3.select(this),
+ that = this;
+ nv.utils.initSVG(container);
+ var availableWidth = (width || parseInt(container.style('width')) || 960)
+ - margin.left - margin.right,
+ availableHeight = (height || parseInt(container.style('height')) || 400)
+ - margin.top - margin.bottom;
+
+ chart.update = function() {
+ dispatch.beforeUpdate();
+ container.transition().duration(duration).call(chart);
+ };
+ chart.container = this;
+
+ // Display No Data message if there's nothing to show. (quartiles required at minimum)
+ if (!data || !data.length ||
+ !data.filter(function(d) { return d.values.hasOwnProperty("Q1") && d.values.hasOwnProperty("Q2") && d.values.hasOwnProperty("Q3"); }).length) {
+ var noDataText = container.selectAll('.nv-noData').data([noData]);
+
+ noDataText.enter().append('text')
+ .attr('class', 'nvd3 nv-noData')
+ .attr('dy', '-.7em')
+ .style('text-anchor', 'middle');
+
+ noDataText
+ .attr('x', margin.left + availableWidth / 2)
+ .attr('y', margin.top + availableHeight / 2)
+ .text(function(d) { return d });
+
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ // Setup Scales
+ x = boxplot.xScale();
+ y = boxplot.yScale().clamp(true);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-boxPlotWithAxes').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-boxPlotWithAxes').append('g');
+ var defsEnter = gEnter.append('defs');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-x nv-axis');
+ gEnter.append('g').attr('class', 'nv-y nv-axis')
+ .append('g').attr('class', 'nv-zeroLine')
+ .append('line');
+
+ gEnter.append('g').attr('class', 'nv-barsWrap');
+
+ g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ if (rightAlignYAxis) {
+ g.select(".nv-y.nv-axis")
+ .attr("transform", "translate(" + availableWidth + ",0)");
+ }
+
+ // Main Chart Component(s)
+ boxplot
+ .width(availableWidth)
+ .height(availableHeight);
+
+ var barsWrap = g.select('.nv-barsWrap')
+ .datum(data.filter(function(d) { return !d.disabled }))
+
+ barsWrap.transition().call(boxplot);
+
+
+ defsEnter.append('clipPath')
+ .attr('id', 'nv-x-label-clip-' + boxplot.id())
+ .append('rect');
+
+ g.select('#nv-x-label-clip-' + boxplot.id() + ' rect')
+ .attr('width', x.rangeBand() * (staggerLabels ? 2 : 1))
+ .attr('height', 16)
+ .attr('x', -x.rangeBand() / (staggerLabels ? 1 : 2 ));
+
+ // Setup Axes
+ if (showXAxis) {
+ xAxis
+ .scale(x)
+ .ticks( nv.utils.calcTicksX(availableWidth/100, data) )
+ .tickSize(-availableHeight, 0);
+
+ g.select('.nv-x.nv-axis').attr('transform', 'translate(0,' + y.range()[0] + ')');
+ g.select('.nv-x.nv-axis').call(xAxis);
+
+ var xTicks = g.select('.nv-x.nv-axis').selectAll('g');
+ if (staggerLabels) {
+ xTicks
+ .selectAll('text')
+ .attr('transform', function(d,i,j) { return 'translate(0,' + (j % 2 == 0 ? '5' : '17') + ')' })
+ }
+ }
+
+ if (showYAxis) {
+ yAxis
+ .scale(y)
+ .ticks( Math.floor(availableHeight/36) ) // can't use nv.utils.calcTicksY with Object data
+ .tickSize( -availableWidth, 0);
+
+ g.select('.nv-y.nv-axis').call(yAxis);
+ }
+
+ // Zero line
+ g.select(".nv-zeroLine line")
+ .attr("x1",0)
+ .attr("x2",availableWidth)
+ .attr("y1", y(0))
+ .attr("y2", y(0))
+ ;
+
+ //============================================================
+ // Event Handling/Dispatching (in chart's scope)
+ //------------------------------------------------------------
+ });
+
+ renderWatch.renderEnd('nv-boxplot chart immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (out of chart's scope)
+ //------------------------------------------------------------
+
+ boxplot.dispatch.on('elementMouseover.tooltip', function(evt) {
+ tooltip.data(evt).hidden(false);
+ });
+
+ boxplot.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.data(evt).hidden(true);
+ });
+
+ boxplot.dispatch.on('elementMousemove.tooltip', function(evt) {
+ tooltip.position({top: d3.event.pageY, left: d3.event.pageX})();
+ });
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.boxplot = boxplot;
+ chart.xAxis = xAxis;
+ chart.yAxis = yAxis;
+ chart.tooltip = tooltip;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ staggerLabels: {get: function(){return staggerLabels;}, set: function(_){staggerLabels=_;}},
+ showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
+ showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
+ tooltips: {get: function(){return tooltips;}, set: function(_){tooltips=_;}},
+ tooltipContent: {get: function(){return tooltip;}, set: function(_){tooltip=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ boxplot.duration(duration);
+ xAxis.duration(duration);
+ yAxis.duration(duration);
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ boxplot.color(color);
+ }},
+ rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
+ rightAlignYAxis = _;
+ yAxis.orient( (_) ? 'right' : 'left');
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, boxplot);
+ nv.utils.initOptions(chart);
+
+ return chart;
+}
+// Chart design based on the recommendations of Stephen Few. Implementation
+// based on the work of Clint Ivy, Jamie Love, and Jason Davies.
+// http://projects.instantcognition.com/protovis/bulletchart/
+
+nv.models.bullet = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , orient = 'left' // TODO top & bottom
+ , reverse = false
+ , ranges = function(d) { return d.ranges }
+ , markers = function(d) { return d.markers ? d.markers : [0] }
+ , measures = function(d) { return d.measures }
+ , rangeLabels = function(d) { return d.rangeLabels ? d.rangeLabels : [] }
+ , markerLabels = function(d) { return d.markerLabels ? d.markerLabels : [] }
+ , measureLabels = function(d) { return d.measureLabels ? d.measureLabels : [] }
+ , forceX = [0] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
+ , width = 380
+ , height = 30
+ , container = null
+ , tickFormat = null
+ , color = nv.utils.getColor(['#1f77b4'])
+ , dispatch = d3.dispatch('elementMouseover', 'elementMouseout', 'elementMousemove')
+ ;
+
+ function chart(selection) {
+ selection.each(function(d, i) {
+ var availableWidth = width - margin.left - margin.right,
+ availableHeight = height - margin.top - margin.bottom;
+
+ container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ var rangez = ranges.call(this, d, i).slice().sort(d3.descending),
+ markerz = markers.call(this, d, i).slice().sort(d3.descending),
+ measurez = measures.call(this, d, i).slice().sort(d3.descending),
+ rangeLabelz = rangeLabels.call(this, d, i).slice(),
+ markerLabelz = markerLabels.call(this, d, i).slice(),
+ measureLabelz = measureLabels.call(this, d, i).slice();
+
+ // Setup Scales
+ // Compute the new x-scale.
+ var x1 = d3.scale.linear()
+ .domain( d3.extent(d3.merge([forceX, rangez])) )
+ .range(reverse ? [availableWidth, 0] : [0, availableWidth]);
+
+ // Retrieve the old x-scale, if this is an update.
+ var x0 = this.__chart__ || d3.scale.linear()
+ .domain([0, Infinity])
+ .range(x1.range());
+
+ // Stash the new scale.
+ this.__chart__ = x1;
+
+ var rangeMin = d3.min(rangez), //rangez[2]
+ rangeMax = d3.max(rangez), //rangez[0]
+ rangeAvg = rangez[1];
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-bullet').data([d]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bullet');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('rect').attr('class', 'nv-range nv-rangeMax');
+ gEnter.append('rect').attr('class', 'nv-range nv-rangeAvg');
+ gEnter.append('rect').attr('class', 'nv-range nv-rangeMin');
+ gEnter.append('rect').attr('class', 'nv-measure');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0)
+ w1 = function(d) { return Math.abs(x1(d) - x1(0)) };
+ var xp0 = function(d) { return d < 0 ? x0(d) : x0(0) },
+ xp1 = function(d) { return d < 0 ? x1(d) : x1(0) };
+
+ g.select('rect.nv-rangeMax')
+ .attr('height', availableHeight)
+ .attr('width', w1(rangeMax > 0 ? rangeMax : rangeMin))
+ .attr('x', xp1(rangeMax > 0 ? rangeMax : rangeMin))
+ .datum(rangeMax > 0 ? rangeMax : rangeMin)
+
+ g.select('rect.nv-rangeAvg')
+ .attr('height', availableHeight)
+ .attr('width', w1(rangeAvg))
+ .attr('x', xp1(rangeAvg))
+ .datum(rangeAvg)
+
+ g.select('rect.nv-rangeMin')
+ .attr('height', availableHeight)
+ .attr('width', w1(rangeMax))
+ .attr('x', xp1(rangeMax))
+ .attr('width', w1(rangeMax > 0 ? rangeMin : rangeMax))
+ .attr('x', xp1(rangeMax > 0 ? rangeMin : rangeMax))
+ .datum(rangeMax > 0 ? rangeMin : rangeMax)
+
+ g.select('rect.nv-measure')
+ .style('fill', color)
+ .attr('height', availableHeight / 3)
+ .attr('y', availableHeight / 3)
+ .attr('width', measurez < 0 ?
+ x1(0) - x1(measurez[0])
+ : x1(measurez[0]) - x1(0))
+ .attr('x', xp1(measurez))
+ .on('mouseover', function() {
+ dispatch.elementMouseover({
+ value: measurez[0],
+ label: measureLabelz[0] || 'Current',
+ color: d3.select(this).style("fill")
+ })
+ })
+ .on('mousemove', function() {
+ dispatch.elementMousemove({
+ value: measurez[0],
+ label: measureLabelz[0] || 'Current',
+ color: d3.select(this).style("fill")
+ })
+ })
+ .on('mouseout', function() {
+ dispatch.elementMouseout({
+ value: measurez[0],
+ label: measureLabelz[0] || 'Current',
+ color: d3.select(this).style("fill")
+ })
+ });
+
+ var h3 = availableHeight / 6;
+
+ var markerData = markerz.map( function(marker, index) {
+ return {value: marker, label: markerLabelz[index]}
+ });
+ gEnter
+ .selectAll("path.nv-markerTriangle")
+ .data(markerData)
+ .enter()
+ .append('path')
+ .attr('class', 'nv-markerTriangle')
+ .attr('transform', function(d) { return 'translate(' + x1(d.value) + ',' + (availableHeight / 2) + ')' })
+ .attr('d', 'M0,' + h3 + 'L' + h3 + ',' + (-h3) + ' ' + (-h3) + ',' + (-h3) + 'Z')
+ .on('mouseover', function(d) {
+ dispatch.elementMouseover({
+ value: d.value,
+ label: d.label || 'Previous',
+ color: d3.select(this).style("fill"),
+ pos: [x1(d.value), availableHeight/2]
+ })
+
+ })
+ .on('mousemove', function(d) {
+ dispatch.elementMousemove({
+ value: d.value,
+ label: d.label || 'Previous',
+ color: d3.select(this).style("fill")
+ })
+ })
+ .on('mouseout', function(d, i) {
+ dispatch.elementMouseout({
+ value: d.value,
+ label: d.label || 'Previous',
+ color: d3.select(this).style("fill")
+ })
+ });
+
+ wrap.selectAll('.nv-range')
+ .on('mouseover', function(d,i) {
+ var label = rangeLabelz[i] || (!i ? "Maximum" : i == 1 ? "Mean" : "Minimum");
+ dispatch.elementMouseover({
+ value: d,
+ label: label,
+ color: d3.select(this).style("fill")
+ })
+ })
+ .on('mousemove', function() {
+ dispatch.elementMousemove({
+ value: measurez[0],
+ label: measureLabelz[0] || 'Previous',
+ color: d3.select(this).style("fill")
+ })
+ })
+ .on('mouseout', function(d,i) {
+ var label = rangeLabelz[i] || (!i ? "Maximum" : i == 1 ? "Mean" : "Minimum");
+ dispatch.elementMouseout({
+ value: d,
+ label: label,
+ color: d3.select(this).style("fill")
+ })
+ });
+ });
+
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ ranges: {get: function(){return ranges;}, set: function(_){ranges=_;}}, // ranges (bad, satisfactory, good)
+ markers: {get: function(){return markers;}, set: function(_){markers=_;}}, // markers (previous, goal)
+ measures: {get: function(){return measures;}, set: function(_){measures=_;}}, // measures (actual, forecast)
+ forceX: {get: function(){return forceX;}, set: function(_){forceX=_;}},
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ tickFormat: {get: function(){return tickFormat;}, set: function(_){tickFormat=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ orient: {get: function(){return orient;}, set: function(_){ // left, right, top, bottom
+ orient = _;
+ reverse = orient == 'right' || orient == 'bottom';
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+ return chart;
+};
+
+
+
+// Chart design based on the recommendations of Stephen Few. Implementation
+// based on the work of Clint Ivy, Jamie Love, and Jason Davies.
+// http://projects.instantcognition.com/protovis/bulletchart/
+nv.models.bulletChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var bullet = nv.models.bullet();
+ var tooltip = nv.models.tooltip();
+
+ var orient = 'left' // TODO top & bottom
+ , reverse = false
+ , margin = {top: 5, right: 40, bottom: 20, left: 120}
+ , ranges = function(d) { return d.ranges }
+ , markers = function(d) { return d.markers ? d.markers : [0] }
+ , measures = function(d) { return d.measures }
+ , width = null
+ , height = 55
+ , tickFormat = null
+ , ticks = null
+ , noData = null
+ , dispatch = d3.dispatch('tooltipShow', 'tooltipHide')
+ ;
+
+ tooltip.duration(0).headerEnabled(false);
+
+ function chart(selection) {
+ selection.each(function(d, i) {
+ var container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = height - margin.top - margin.bottom,
+ that = this;
+
+ chart.update = function() { chart(selection) };
+ chart.container = this;
+
+ // Display No Data message if there's nothing to show.
+ if (!d || !ranges.call(this, d, i)) {
+ nv.utils.noData(chart, container)
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ var rangez = ranges.call(this, d, i).slice().sort(d3.descending),
+ markerz = markers.call(this, d, i).slice().sort(d3.descending),
+ measurez = measures.call(this, d, i).slice().sort(d3.descending);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-bulletChart').data([d]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bulletChart');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-bulletWrap');
+ gEnter.append('g').attr('class', 'nv-titles');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ // Compute the new x-scale.
+ var x1 = d3.scale.linear()
+ .domain([0, Math.max(rangez[0], markerz[0], measurez[0])]) // TODO: need to allow forceX and forceY, and xDomain, yDomain
+ .range(reverse ? [availableWidth, 0] : [0, availableWidth]);
+
+ // Retrieve the old x-scale, if this is an update.
+ var x0 = this.__chart__ || d3.scale.linear()
+ .domain([0, Infinity])
+ .range(x1.range());
+
+ // Stash the new scale.
+ this.__chart__ = x1;
+
+ var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0)
+ w1 = function(d) { return Math.abs(x1(d) - x1(0)) };
+
+ var title = gEnter.select('.nv-titles').append('g')
+ .attr('text-anchor', 'end')
+ .attr('transform', 'translate(-6,' + (height - margin.top - margin.bottom) / 2 + ')');
+ title.append('text')
+ .attr('class', 'nv-title')
+ .text(function(d) { return d.title; });
+
+ title.append('text')
+ .attr('class', 'nv-subtitle')
+ .attr('dy', '1em')
+ .text(function(d) { return d.subtitle; });
+
+ bullet
+ .width(availableWidth)
+ .height(availableHeight)
+
+ var bulletWrap = g.select('.nv-bulletWrap');
+ d3.transition(bulletWrap).call(bullet);
+
+ // Compute the tick format.
+ var format = tickFormat || x1.tickFormat( availableWidth / 100 );
+
+ // Update the tick groups.
+ var tick = g.selectAll('g.nv-tick')
+ .data(x1.ticks( ticks ? ticks : (availableWidth / 50) ), function(d) {
+ return this.textContent || format(d);
+ });
+
+ // Initialize the ticks with the old scale, x0.
+ var tickEnter = tick.enter().append('g')
+ .attr('class', 'nv-tick')
+ .attr('transform', function(d) { return 'translate(' + x0(d) + ',0)' })
+ .style('opacity', 1e-6);
+
+ tickEnter.append('line')
+ .attr('y1', availableHeight)
+ .attr('y2', availableHeight * 7 / 6);
+
+ tickEnter.append('text')
+ .attr('text-anchor', 'middle')
+ .attr('dy', '1em')
+ .attr('y', availableHeight * 7 / 6)
+ .text(format);
+
+ // Transition the updating ticks to the new scale, x1.
+ var tickUpdate = d3.transition(tick)
+ .attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' })
+ .style('opacity', 1);
+
+ tickUpdate.select('line')
+ .attr('y1', availableHeight)
+ .attr('y2', availableHeight * 7 / 6);
+
+ tickUpdate.select('text')
+ .attr('y', availableHeight * 7 / 6);
+
+ // Transition the exiting ticks to the new scale, x1.
+ d3.transition(tick.exit())
+ .attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' })
+ .style('opacity', 1e-6)
+ .remove();
+ });
+
+ d3.timer.flush();
+ return chart;
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (out of chart's scope)
+ //------------------------------------------------------------
+
+ bullet.dispatch.on('elementMouseover.tooltip', function(evt) {
+ evt['series'] = {
+ key: evt.label,
+ value: evt.value,
+ color: evt.color
+ };
+ tooltip.data(evt).hidden(false);
+ });
+
+ bullet.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true);
+ });
+
+ bullet.dispatch.on('elementMousemove.tooltip', function(evt) {
+ tooltip.position({top: d3.event.pageY, left: d3.event.pageX})();
+ });
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.bullet = bullet;
+ chart.dispatch = dispatch;
+ chart.tooltip = tooltip;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ ranges: {get: function(){return ranges;}, set: function(_){ranges=_;}}, // ranges (bad, satisfactory, good)
+ markers: {get: function(){return markers;}, set: function(_){markers=_;}}, // markers (previous, goal)
+ measures: {get: function(){return measures;}, set: function(_){measures=_;}}, // measures (actual, forecast)
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ tickFormat: {get: function(){return tickFormat;}, set: function(_){tickFormat=_;}},
+ ticks: {get: function(){return ticks;}, set: function(_){ticks=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+
+ // deprecated options
+ tooltips: {get: function(){return tooltip.enabled();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltips', 'use chart.tooltip.enabled() instead');
+ tooltip.enabled(!!_);
+ }},
+ tooltipContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'use chart.tooltip.contentGenerator() instead');
+ tooltip.contentGenerator(_);
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ orient: {get: function(){return orient;}, set: function(_){ // left, right, top, bottom
+ orient = _;
+ reverse = orient == 'right' || orient == 'bottom';
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, bullet);
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+
+
+
+nv.models.candlestickBar = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = null
+ , height = null
+ , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
+ , container
+ , x = d3.scale.linear()
+ , y = d3.scale.linear()
+ , getX = function(d) { return d.x }
+ , getY = function(d) { return d.y }
+ , getOpen = function(d) { return d.open }
+ , getClose = function(d) { return d.close }
+ , getHigh = function(d) { return d.high }
+ , getLow = function(d) { return d.low }
+ , forceX = []
+ , forceY = []
+ , padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart
+ , clipEdge = true
+ , color = nv.utils.defaultColor()
+ , interactive = false
+ , xDomain
+ , yDomain
+ , xRange
+ , yRange
+ , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState', 'renderEnd', 'chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove')
+ ;
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ function chart(selection) {
+ selection.each(function(data) {
+ container = d3.select(this);
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ nv.utils.initSVG(container);
+
+ // Width of the candlestick bars.
+ var barWidth = (availableWidth / data[0].values.length) * .45;
+
+ // Setup Scales
+ x.domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) ));
+
+ if (padData)
+ x.range(xRange || [availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]);
+ else
+ x.range(xRange || [5 + barWidth / 2, availableWidth - barWidth / 2 - 5]);
+
+ y.domain(yDomain || [
+ d3.min(data[0].values.map(getLow).concat(forceY)),
+ d3.max(data[0].values.map(getHigh).concat(forceY))
+ ]
+ ).range(yRange || [availableHeight, 0]);
+
+ // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
+ if (x.domain()[0] === x.domain()[1])
+ x.domain()[0] ?
+ x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
+ : x.domain([-1,1]);
+
+ if (y.domain()[0] === y.domain()[1])
+ y.domain()[0] ?
+ y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01])
+ : y.domain([-1,1]);
+
+ // Setup containers and skeleton of chart
+ var wrap = d3.select(this).selectAll('g.nv-wrap.nv-candlestickBar').data([data[0].values]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-candlestickBar');
+ var defsEnter = wrapEnter.append('defs');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-ticks');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ container
+ .on('click', function(d,i) {
+ dispatch.chartClick({
+ data: d,
+ index: i,
+ pos: d3.event,
+ id: id
+ });
+ });
+
+ defsEnter.append('clipPath')
+ .attr('id', 'nv-chart-clip-path-' + id)
+ .append('rect');
+
+ wrap.select('#nv-chart-clip-path-' + id + ' rect')
+ .attr('width', availableWidth)
+ .attr('height', availableHeight);
+
+ g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : '');
+
+ var ticks = wrap.select('.nv-ticks').selectAll('.nv-tick')
+ .data(function(d) { return d });
+ ticks.exit().remove();
+
+ // The colors are currently controlled by CSS.
+ var tickGroups = ticks.enter().append('g')
+ .attr('class', function(d, i, j) { return (getOpen(d, i) > getClose(d, i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i});
+
+ var lines = tickGroups.append('line')
+ .attr('class', 'nv-candlestick-lines')
+ .attr('transform', function(d, i) { return 'translate(' + x(getX(d, i)) + ',0)'; })
+ .attr('x1', 0)
+ .attr('y1', function(d, i) { return y(getHigh(d, i)); })
+ .attr('x2', 0)
+ .attr('y2', function(d, i) { return y(getLow(d, i)); });
+
+ var rects = tickGroups.append('rect')
+ .attr('class', 'nv-candlestick-rects nv-bars')
+ .attr('transform', function(d, i) {
+ return 'translate(' + (x(getX(d, i)) - barWidth/2) + ','
+ + (y(getY(d, i)) - (getOpen(d, i) > getClose(d, i) ? (y(getClose(d, i)) - y(getOpen(d, i))) : 0))
+ + ')';
+ })
+ .attr('x', 0)
+ .attr('y', 0)
+ .attr('width', barWidth)
+ .attr('height', function(d, i) {
+ var open = getOpen(d, i);
+ var close = getClose(d, i);
+ return open > close ? y(close) - y(open) : y(open) - y(close);
+ });
+
+ container.selectAll('.nv-candlestick-lines').transition()
+ .attr('transform', function(d, i) { return 'translate(' + x(getX(d, i)) + ',0)'; })
+ .attr('x1', 0)
+ .attr('y1', function(d, i) { return y(getHigh(d, i)); })
+ .attr('x2', 0)
+ .attr('y2', function(d, i) { return y(getLow(d, i)); });
+
+ container.selectAll('.nv-candlestick-rects').transition()
+ .attr('transform', function(d, i) {
+ return 'translate(' + (x(getX(d, i)) - barWidth/2) + ','
+ + (y(getY(d, i)) - (getOpen(d, i) > getClose(d, i) ? (y(getClose(d, i)) - y(getOpen(d, i))) : 0))
+ + ')';
+ })
+ .attr('x', 0)
+ .attr('y', 0)
+ .attr('width', barWidth)
+ .attr('height', function(d, i) {
+ var open = getOpen(d, i);
+ var close = getClose(d, i);
+ return open > close ? y(close) - y(open) : y(open) - y(close);
+ });
+ });
+
+ return chart;
+ }
+
+
+ //Create methods to allow outside functions to highlight a specific bar.
+ chart.highlightPoint = function(pointIndex, isHoverOver) {
+ chart.clearHighlights();
+ container.select(".nv-candlestickBar .nv-tick-0-" + pointIndex)
+ .classed("hover", isHoverOver)
+ ;
+ };
+
+ chart.clearHighlights = function() {
+ container.select(".nv-candlestickBar .nv-tick.hover")
+ .classed("hover", false)
+ ;
+ };
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ xScale: {get: function(){return x;}, set: function(_){x=_;}},
+ yScale: {get: function(){return y;}, set: function(_){y=_;}},
+ xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
+ yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
+ xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
+ yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
+ forceX: {get: function(){return forceX;}, set: function(_){forceX=_;}},
+ forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
+ padData: {get: function(){return padData;}, set: function(_){padData=_;}},
+ clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
+ id: {get: function(){return id;}, set: function(_){id=_;}},
+ interactive: {get: function(){return interactive;}, set: function(_){interactive=_;}},
+
+ x: {get: function(){return getX;}, set: function(_){getX=_;}},
+ y: {get: function(){return getY;}, set: function(_){getY=_;}},
+ open: {get: function(){return getOpen();}, set: function(_){getOpen=_;}},
+ close: {get: function(){return getClose();}, set: function(_){getClose=_;}},
+ high: {get: function(){return getHigh;}, set: function(_){getHigh=_;}},
+ low: {get: function(){return getLow;}, set: function(_){getLow=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top != undefined ? _.top : margin.top;
+ margin.right = _.right != undefined ? _.right : margin.right;
+ margin.bottom = _.bottom != undefined ? _.bottom : margin.bottom;
+ margin.left = _.left != undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+ return chart;
+};
+
+nv.models.cumulativeLineChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var lines = nv.models.line()
+ , xAxis = nv.models.axis()
+ , yAxis = nv.models.axis()
+ , legend = nv.models.legend()
+ , controls = nv.models.legend()
+ , interactiveLayer = nv.interactiveGuideline()
+ , tooltip = nv.models.tooltip()
+ ;
+
+ var margin = {top: 30, right: 30, bottom: 50, left: 60}
+ , color = nv.utils.defaultColor()
+ , width = null
+ , height = null
+ , showLegend = true
+ , showXAxis = true
+ , showYAxis = true
+ , rightAlignYAxis = false
+ , showControls = true
+ , useInteractiveGuideline = false
+ , rescaleY = true
+ , x //can be accessed via chart.xScale()
+ , y //can be accessed via chart.yScale()
+ , id = lines.id()
+ , state = nv.utils.state()
+ , defaultState = null
+ , noData = null
+ , average = function(d) { return d.average }
+ , dispatch = d3.dispatch('stateChange', 'changeState', 'renderEnd')
+ , transitionDuration = 250
+ , duration = 250
+ , noErrorCheck = false //if set to TRUE, will bypass an error check in the indexify function.
+ ;
+
+ state.index = 0;
+ state.rescaleY = rescaleY;
+
+ xAxis.orient('bottom').tickPadding(7);
+ yAxis.orient((rightAlignYAxis) ? 'right' : 'left');
+
+ tooltip.valueFormatter(function(d, i) {
+ return yAxis.tickFormat()(d, i);
+ }).headerFormatter(function(d, i) {
+ return xAxis.tickFormat()(d, i);
+ });
+
+ controls.updateState(false);
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var dx = d3.scale.linear()
+ , index = {i: 0, x: 0}
+ , renderWatch = nv.utils.renderWatch(dispatch, duration)
+ ;
+
+ var stateGetter = function(data) {
+ return function(){
+ return {
+ active: data.map(function(d) { return !d.disabled }),
+ index: index.i,
+ rescaleY: rescaleY
+ };
+ }
+ };
+
+ var stateSetter = function(data) {
+ return function(state) {
+ if (state.index !== undefined)
+ index.i = state.index;
+ if (state.rescaleY !== undefined)
+ rescaleY = state.rescaleY;
+ if (state.active !== undefined)
+ data.forEach(function(series,i) {
+ series.disabled = !state.active[i];
+ });
+ }
+ };
+
+ function chart(selection) {
+ renderWatch.reset();
+ renderWatch.models(lines);
+ if (showXAxis) renderWatch.models(xAxis);
+ if (showYAxis) renderWatch.models(yAxis);
+ selection.each(function(data) {
+ var container = d3.select(this);
+ nv.utils.initSVG(container);
+ container.classed('nv-chart-' + id, true);
+ var that = this;
+
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ chart.update = function() {
+ if (duration === 0)
+ container.call(chart);
+ else
+ container.transition().duration(duration).call(chart)
+ };
+ chart.container = this;
+
+ state
+ .setter(stateSetter(data), chart.update)
+ .getter(stateGetter(data))
+ .update();
+
+ // DEPRECATED set state.disableddisabled
+ state.disabled = data.map(function(d) { return !!d.disabled });
+
+ if (!defaultState) {
+ var key;
+ defaultState = {};
+ for (key in state) {
+ if (state[key] instanceof Array)
+ defaultState[key] = state[key].slice(0);
+ else
+ defaultState[key] = state[key];
+ }
+ }
+
+ var indexDrag = d3.behavior.drag()
+ .on('dragstart', dragStart)
+ .on('drag', dragMove)
+ .on('dragend', dragEnd);
+
+
+ function dragStart(d,i) {
+ d3.select(chart.container)
+ .style('cursor', 'ew-resize');
+ }
+
+ function dragMove(d,i) {
+ index.x = d3.event.x;
+ index.i = Math.round(dx.invert(index.x));
+ updateZero();
+ }
+
+ function dragEnd(d,i) {
+ d3.select(chart.container)
+ .style('cursor', 'auto');
+
+ // update state and send stateChange with new index
+ state.index = index.i;
+ dispatch.stateChange(state);
+ }
+
+ // Display No Data message if there's nothing to show.
+ if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
+ nv.utils.noData(chart, container)
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ // Setup Scales
+ x = lines.xScale();
+ y = lines.yScale();
+
+ if (!rescaleY) {
+ var seriesDomains = data
+ .filter(function(series) { return !series.disabled })
+ .map(function(series,i) {
+ var initialDomain = d3.extent(series.values, lines.y());
+
+ //account for series being disabled when losing 95% or more
+ if (initialDomain[0] < -.95) initialDomain[0] = -.95;
+
+ return [
+ (initialDomain[0] - initialDomain[1]) / (1 + initialDomain[1]),
+ (initialDomain[1] - initialDomain[0]) / (1 + initialDomain[0])
+ ];
+ });
+
+ var completeDomain = [
+ d3.min(seriesDomains, function(d) { return d[0] }),
+ d3.max(seriesDomains, function(d) { return d[1] })
+ ];
+
+ lines.yDomain(completeDomain);
+ } else {
+ lines.yDomain(null);
+ }
+
+ dx.domain([0, data[0].values.length - 1]) //Assumes all series have same length
+ .range([0, availableWidth])
+ .clamp(true);
+
+ var data = indexify(index.i, data);
+
+ // Setup containers and skeleton of chart
+ var interactivePointerEvents = (useInteractiveGuideline) ? "none" : "all";
+ var wrap = container.selectAll('g.nv-wrap.nv-cumulativeLine').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-cumulativeLine').append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-interactive');
+ gEnter.append('g').attr('class', 'nv-x nv-axis').style("pointer-events","none");
+ gEnter.append('g').attr('class', 'nv-y nv-axis');
+ gEnter.append('g').attr('class', 'nv-background');
+ gEnter.append('g').attr('class', 'nv-linesWrap').style("pointer-events",interactivePointerEvents);
+ gEnter.append('g').attr('class', 'nv-avgLinesWrap').style("pointer-events","none");
+ gEnter.append('g').attr('class', 'nv-legendWrap');
+ gEnter.append('g').attr('class', 'nv-controlsWrap');
+
+ // Legend
+ if (showLegend) {
+ legend.width(availableWidth);
+
+ g.select('.nv-legendWrap')
+ .datum(data)
+ .call(legend);
+
+ if ( margin.top != legend.height()) {
+ margin.top = legend.height();
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+ }
+
+ g.select('.nv-legendWrap')
+ .attr('transform', 'translate(0,' + (-margin.top) +')')
+ }
+
+ // Controls
+ if (showControls) {
+ var controlsData = [
+ { key: 'Re-scale y-axis', disabled: !rescaleY }
+ ];
+
+ controls
+ .width(140)
+ .color(['#444', '#444', '#444'])
+ .rightAlign(false)
+ .margin({top: 5, right: 0, bottom: 5, left: 20})
+ ;
+
+ g.select('.nv-controlsWrap')
+ .datum(controlsData)
+ .attr('transform', 'translate(0,' + (-margin.top) +')')
+ .call(controls);
+ }
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ if (rightAlignYAxis) {
+ g.select(".nv-y.nv-axis")
+ .attr("transform", "translate(" + availableWidth + ",0)");
+ }
+
+ // Show error if series goes below 100%
+ var tempDisabled = data.filter(function(d) { return d.tempDisabled });
+
+ wrap.select('.tempDisabled').remove(); //clean-up and prevent duplicates
+ if (tempDisabled.length) {
+ wrap.append('text').attr('class', 'tempDisabled')
+ .attr('x', availableWidth / 2)
+ .attr('y', '-.71em')
+ .style('text-anchor', 'end')
+ .text(tempDisabled.map(function(d) { return d.key }).join(', ') + ' values cannot be calculated for this time period.');
+ }
+
+ //Set up interactive layer
+ if (useInteractiveGuideline) {
+ interactiveLayer
+ .width(availableWidth)
+ .height(availableHeight)
+ .margin({left:margin.left,top:margin.top})
+ .svgContainer(container)
+ .xScale(x);
+ wrap.select(".nv-interactive").call(interactiveLayer);
+ }
+
+ gEnter.select('.nv-background')
+ .append('rect');
+
+ g.select('.nv-background rect')
+ .attr('width', availableWidth)
+ .attr('height', availableHeight);
+
+ lines
+ //.x(function(d) { return d.x })
+ .y(function(d) { return d.display.y })
+ .width(availableWidth)
+ .height(availableHeight)
+ .color(data.map(function(d,i) {
+ return d.color || color(d, i);
+ }).filter(function(d,i) { return !data[i].disabled && !data[i].tempDisabled; }));
+
+ var linesWrap = g.select('.nv-linesWrap')
+ .datum(data.filter(function(d) { return !d.disabled && !d.tempDisabled }));
+
+ linesWrap.call(lines);
+
+ //Store a series index number in the data array.
+ data.forEach(function(d,i) {
+ d.seriesIndex = i;
+ });
+
+ var avgLineData = data.filter(function(d) {
+ return !d.disabled && !!average(d);
+ });
+
+ var avgLines = g.select(".nv-avgLinesWrap").selectAll("line")
+ .data(avgLineData, function(d) { return d.key; });
+
+ var getAvgLineY = function(d) {
+ //If average lines go off the svg element, clamp them to the svg bounds.
+ var yVal = y(average(d));
+ if (yVal < 0) return 0;
+ if (yVal > availableHeight) return availableHeight;
+ return yVal;
+ };
+
+ avgLines.enter()
+ .append('line')
+ .style('stroke-width',2)
+ .style('stroke-dasharray','10,10')
+ .style('stroke',function (d,i) {
+ return lines.color()(d,d.seriesIndex);
+ })
+ .attr('x1',0)
+ .attr('x2',availableWidth)
+ .attr('y1', getAvgLineY)
+ .attr('y2', getAvgLineY);
+
+ avgLines
+ .style('stroke-opacity',function(d){
+ //If average lines go offscreen, make them transparent
+ var yVal = y(average(d));
+ if (yVal < 0 || yVal > availableHeight) return 0;
+ return 1;
+ })
+ .attr('x1',0)
+ .attr('x2',availableWidth)
+ .attr('y1', getAvgLineY)
+ .attr('y2', getAvgLineY);
+
+ avgLines.exit().remove();
+
+ //Create index line
+ var indexLine = linesWrap.selectAll('.nv-indexLine')
+ .data([index]);
+ indexLine.enter().append('rect').attr('class', 'nv-indexLine')
+ .attr('width', 3)
+ .attr('x', -2)
+ .attr('fill', 'red')
+ .attr('fill-opacity', .5)
+ .style("pointer-events","all")
+ .call(indexDrag);
+
+ indexLine
+ .attr('transform', function(d) { return 'translate(' + dx(d.i) + ',0)' })
+ .attr('height', availableHeight);
+
+ // Setup Axes
+ if (showXAxis) {
+ xAxis
+ .scale(x)
+ ._ticks( nv.utils.calcTicksX(availableWidth/70, data) )
+ .tickSize(-availableHeight, 0);
+
+ g.select('.nv-x.nv-axis')
+ .attr('transform', 'translate(0,' + y.range()[0] + ')');
+ g.select('.nv-x.nv-axis')
+ .call(xAxis);
+ }
+
+ if (showYAxis) {
+ yAxis
+ .scale(y)
+ ._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
+ .tickSize( -availableWidth, 0);
+
+ g.select('.nv-y.nv-axis')
+ .call(yAxis);
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (in chart's scope)
+ //------------------------------------------------------------
+
+ function updateZero() {
+ indexLine
+ .data([index]);
+
+ //When dragging the index line, turn off line transitions.
+ // Then turn them back on when done dragging.
+ var oldDuration = chart.duration();
+ chart.duration(0);
+ chart.update();
+ chart.duration(oldDuration);
+ }
+
+ g.select('.nv-background rect')
+ .on('click', function() {
+ index.x = d3.mouse(this)[0];
+ index.i = Math.round(dx.invert(index.x));
+
+ // update state and send stateChange with new index
+ state.index = index.i;
+ dispatch.stateChange(state);
+
+ updateZero();
+ });
+
+ lines.dispatch.on('elementClick', function(e) {
+ index.i = e.pointIndex;
+ index.x = dx(index.i);
+
+ // update state and send stateChange with new index
+ state.index = index.i;
+ dispatch.stateChange(state);
+
+ updateZero();
+ });
+
+ controls.dispatch.on('legendClick', function(d,i) {
+ d.disabled = !d.disabled;
+ rescaleY = !d.disabled;
+
+ state.rescaleY = rescaleY;
+ dispatch.stateChange(state);
+ chart.update();
+ });
+
+ legend.dispatch.on('stateChange', function(newState) {
+ for (var key in newState)
+ state[key] = newState[key];
+ dispatch.stateChange(state);
+ chart.update();
+ });
+
+ interactiveLayer.dispatch.on('elementMousemove', function(e) {
+ lines.clearHighlights();
+ var singlePoint, pointIndex, pointXLocation, allData = [];
+
+ data
+ .filter(function(series, i) {
+ series.seriesIndex = i;
+ return !series.disabled;
+ })
+ .forEach(function(series,i) {
+ pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
+ lines.highlightPoint(i, pointIndex, true);
+ var point = series.values[pointIndex];
+ if (typeof point === 'undefined') return;
+ if (typeof singlePoint === 'undefined') singlePoint = point;
+ if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
+ allData.push({
+ key: series.key,
+ value: chart.y()(point, pointIndex),
+ color: color(series,series.seriesIndex)
+ });
+ });
+
+ //Highlight the tooltip entry based on which point the mouse is closest to.
+ if (allData.length > 2) {
+ var yValue = chart.yScale().invert(e.mouseY);
+ var domainExtent = Math.abs(chart.yScale().domain()[0] - chart.yScale().domain()[1]);
+ var threshold = 0.03 * domainExtent;
+ var indexToHighlight = nv.nearestValueIndex(allData.map(function(d){return d.value}),yValue,threshold);
+ if (indexToHighlight !== null)
+ allData[indexToHighlight].highlight = true;
+ }
+
+ var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex), pointIndex);
+ interactiveLayer.tooltip
+ .position({left: pointXLocation + margin.left, top: e.mouseY + margin.top})
+ .chartContainer(that.parentNode)
+ .valueFormatter(function(d,i) {
+ return yAxis.tickFormat()(d);
+ })
+ .data(
+ {
+ value: xValue,
+ series: allData
+ }
+ )();
+
+ interactiveLayer.renderGuideLine(pointXLocation);
+ });
+
+ interactiveLayer.dispatch.on("elementMouseout",function(e) {
+ lines.clearHighlights();
+ });
+
+ // Update chart from a state object passed to event handler
+ dispatch.on('changeState', function(e) {
+ if (typeof e.disabled !== 'undefined') {
+ data.forEach(function(series,i) {
+ series.disabled = e.disabled[i];
+ });
+
+ state.disabled = e.disabled;
+ }
+
+ if (typeof e.index !== 'undefined') {
+ index.i = e.index;
+ index.x = dx(index.i);
+
+ state.index = e.index;
+
+ indexLine
+ .data([index]);
+ }
+
+ if (typeof e.rescaleY !== 'undefined') {
+ rescaleY = e.rescaleY;
+ }
+
+ chart.update();
+ });
+
+ });
+
+ renderWatch.renderEnd('cumulativeLineChart immediate');
+
+ return chart;
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (out of chart's scope)
+ //------------------------------------------------------------
+
+ lines.dispatch.on('elementMouseover.tooltip', function(evt) {
+ var point = {
+ x: chart.x()(evt.point),
+ y: chart.y()(evt.point),
+ color: evt.point.color
+ };
+ evt.point = point;
+ tooltip.data(evt).position(evt.pos).hidden(false);
+ });
+
+ lines.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true)
+ });
+
+ //============================================================
+ // Functions
+ //------------------------------------------------------------
+
+ var indexifyYGetter = null;
+ /* Normalize the data according to an index point. */
+ function indexify(idx, data) {
+ if (!indexifyYGetter) indexifyYGetter = lines.y();
+ return data.map(function(line, i) {
+ if (!line.values) {
+ return line;
+ }
+ var indexValue = line.values[idx];
+ if (indexValue == null) {
+ return line;
+ }
+ var v = indexifyYGetter(indexValue, idx);
+
+ //TODO: implement check below, and disable series if series loses 100% or more cause divide by 0 issue
+ if (v < -.95 && !noErrorCheck) {
+ //if a series loses more than 100%, calculations fail.. anything close can cause major distortion (but is mathematically correct till it hits 100)
+
+ line.tempDisabled = true;
+ return line;
+ }
+
+ line.tempDisabled = false;
+
+ line.values = line.values.map(function(point, pointIndex) {
+ point.display = {'y': (indexifyYGetter(point, pointIndex) - v) / (1 + v) };
+ return point;
+ });
+
+ return line;
+ })
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ // expose chart's sub-components
+ chart.dispatch = dispatch;
+ chart.lines = lines;
+ chart.legend = legend;
+ chart.controls = controls;
+ chart.xAxis = xAxis;
+ chart.yAxis = yAxis;
+ chart.interactiveLayer = interactiveLayer;
+ chart.state = state;
+ chart.tooltip = tooltip;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ rescaleY: {get: function(){return rescaleY;}, set: function(_){rescaleY=_;}},
+ showControls: {get: function(){return showControls;}, set: function(_){showControls=_;}},
+ showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
+ average: {get: function(){return average;}, set: function(_){average=_;}},
+ defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+ showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
+ showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
+ noErrorCheck: {get: function(){return noErrorCheck;}, set: function(_){noErrorCheck=_;}},
+
+ // deprecated options
+ tooltips: {get: function(){return tooltip.enabled();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltips', 'use chart.tooltip.enabled() instead');
+ tooltip.enabled(!!_);
+ }},
+ tooltipContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'use chart.tooltip.contentGenerator() instead');
+ tooltip.contentGenerator(_);
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ legend.color(color);
+ }},
+ useInteractiveGuideline: {get: function(){return useInteractiveGuideline;}, set: function(_){
+ useInteractiveGuideline = _;
+ if (_ === true) {
+ chart.interactive(false);
+ chart.useVoronoi(false);
+ }
+ }},
+ rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
+ rightAlignYAxis = _;
+ yAxis.orient( (_) ? 'right' : 'left');
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ lines.duration(duration);
+ xAxis.duration(duration);
+ yAxis.duration(duration);
+ renderWatch.reset(duration);
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, lines);
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+//TODO: consider deprecating by adding necessary features to multiBar model
+nv.models.discreteBar = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = 960
+ , height = 500
+ , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
+ , container
+ , x = d3.scale.ordinal()
+ , y = d3.scale.linear()
+ , getX = function(d) { return d.x }
+ , getY = function(d) { return d.y }
+ , forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove
+ , color = nv.utils.defaultColor()
+ , showValues = false
+ , valueFormat = d3.format(',.2f')
+ , xDomain
+ , yDomain
+ , xRange
+ , yRange
+ , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove', 'renderEnd')
+ , rectClass = 'discreteBar'
+ , duration = 250
+ ;
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var x0, y0;
+ var renderWatch = nv.utils.renderWatch(dispatch, duration);
+
+ function chart(selection) {
+ renderWatch.reset();
+ selection.each(function(data) {
+ var availableWidth = width - margin.left - margin.right,
+ availableHeight = height - margin.top - margin.bottom;
+
+ container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ //add series index to each data point for reference
+ data.forEach(function(series, i) {
+ series.values.forEach(function(point) {
+ point.series = i;
+ });
+ });
+
+ // Setup Scales
+ // remap and flatten the data for use in calculating the scales' domains
+ var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate
+ data.map(function(d) {
+ return d.values.map(function(d,i) {
+ return { x: getX(d,i), y: getY(d,i), y0: d.y0 }
+ })
+ });
+
+ x .domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x }))
+ .rangeBands(xRange || [0, availableWidth], .1);
+ y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y }).concat(forceY)));
+
+ // If showValues, pad the Y axis range to account for label height
+ if (showValues) y.range(yRange || [availableHeight - (y.domain()[0] < 0 ? 12 : 0), y.domain()[1] > 0 ? 12 : 0]);
+ else y.range(yRange || [availableHeight, 0]);
+
+ //store old scales if they exist
+ x0 = x0 || x;
+ y0 = y0 || y.copy().range([y(0),y(0)]);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-discretebar').data([data]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discretebar');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-groups');
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ //TODO: by definition, the discrete bar should not have multiple groups, will modify/remove later
+ var groups = wrap.select('.nv-groups').selectAll('.nv-group')
+ .data(function(d) { return d }, function(d) { return d.key });
+ groups.enter().append('g')
+ .style('stroke-opacity', 1e-6)
+ .style('fill-opacity', 1e-6);
+ groups.exit()
+ .watchTransition(renderWatch, 'discreteBar: exit groups')
+ .style('stroke-opacity', 1e-6)
+ .style('fill-opacity', 1e-6)
+ .remove();
+ groups
+ .attr('class', function(d,i) { return 'nv-group nv-series-' + i })
+ .classed('hover', function(d) { return d.hover });
+ groups
+ .watchTransition(renderWatch, 'discreteBar: groups')
+ .style('stroke-opacity', 1)
+ .style('fill-opacity', .75);
+
+ var bars = groups.selectAll('g.nv-bar')
+ .data(function(d) { return d.values });
+ bars.exit().remove();
+
+ var barsEnter = bars.enter().append('g')
+ .attr('transform', function(d,i,j) {
+ return 'translate(' + (x(getX(d,i)) + x.rangeBand() * .05 ) + ', ' + y(0) + ')'
+ })
+ .on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here
+ d3.select(this).classed('hover', true);
+ dispatch.elementMouseover({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ })
+ .on('mouseout', function(d,i) {
+ d3.select(this).classed('hover', false);
+ dispatch.elementMouseout({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ })
+ .on('mousemove', function(d,i) {
+ dispatch.elementMousemove({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ })
+ .on('click', function(d,i) {
+ dispatch.elementClick({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ d3.event.stopPropagation();
+ })
+ .on('dblclick', function(d,i) {
+ dispatch.elementDblClick({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ d3.event.stopPropagation();
+ });
+
+ barsEnter.append('rect')
+ .attr('height', 0)
+ .attr('width', x.rangeBand() * .9 / data.length )
+
+ if (showValues) {
+ barsEnter.append('text')
+ .attr('text-anchor', 'middle')
+ ;
+
+ bars.select('text')
+ .text(function(d,i) { return valueFormat(getY(d,i)) })
+ .watchTransition(renderWatch, 'discreteBar: bars text')
+ .attr('x', x.rangeBand() * .9 / 2)
+ .attr('y', function(d,i) { return getY(d,i) < 0 ? y(getY(d,i)) - y(0) + 12 : -4 })
+
+ ;
+ } else {
+ bars.selectAll('text').remove();
+ }
+
+ bars
+ .attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive' })
+ .style('fill', function(d,i) { return d.color || color(d,i) })
+ .style('stroke', function(d,i) { return d.color || color(d,i) })
+ .select('rect')
+ .attr('class', rectClass)
+ .watchTransition(renderWatch, 'discreteBar: bars rect')
+ .attr('width', x.rangeBand() * .9 / data.length);
+ bars.watchTransition(renderWatch, 'discreteBar: bars')
+ //.delay(function(d,i) { return i * 1200 / data[0].values.length })
+ .attr('transform', function(d,i) {
+ var left = x(getX(d,i)) + x.rangeBand() * .05,
+ top = getY(d,i) < 0 ?
+ y(0) :
+ y(0) - y(getY(d,i)) < 1 ?
+ y(0) - 1 : //make 1 px positive bars show up above y=0
+ y(getY(d,i));
+
+ return 'translate(' + left + ', ' + top + ')'
+ })
+ .select('rect')
+ .attr('height', function(d,i) {
+ return Math.max(Math.abs(y(getY(d,i)) - y((yDomain && yDomain[0]) || 0)) || 1)
+ });
+
+
+ //store old scales for use in transitions on update
+ x0 = x.copy();
+ y0 = y.copy();
+
+ });
+
+ renderWatch.renderEnd('discreteBar immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
+ showValues: {get: function(){return showValues;}, set: function(_){showValues=_;}},
+ x: {get: function(){return getX;}, set: function(_){getX=_;}},
+ y: {get: function(){return getY;}, set: function(_){getY=_;}},
+ xScale: {get: function(){return x;}, set: function(_){x=_;}},
+ yScale: {get: function(){return y;}, set: function(_){y=_;}},
+ xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
+ yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
+ xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
+ yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
+ valueFormat: {get: function(){return valueFormat;}, set: function(_){valueFormat=_;}},
+ id: {get: function(){return id;}, set: function(_){id=_;}},
+ rectClass: {get: function(){return rectClass;}, set: function(_){rectClass=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+
+nv.models.discreteBarChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var discretebar = nv.models.discreteBar()
+ , xAxis = nv.models.axis()
+ , yAxis = nv.models.axis()
+ , tooltip = nv.models.tooltip()
+ ;
+
+ var margin = {top: 15, right: 10, bottom: 50, left: 60}
+ , width = null
+ , height = null
+ , color = nv.utils.getColor()
+ , showXAxis = true
+ , showYAxis = true
+ , rightAlignYAxis = false
+ , staggerLabels = false
+ , x
+ , y
+ , noData = null
+ , dispatch = d3.dispatch('beforeUpdate','renderEnd')
+ , duration = 250
+ ;
+
+ xAxis
+ .orient('bottom')
+ .showMaxMin(false)
+ .tickFormat(function(d) { return d })
+ ;
+ yAxis
+ .orient((rightAlignYAxis) ? 'right' : 'left')
+ .tickFormat(d3.format(',.1f'))
+ ;
+
+ tooltip
+ .duration(0)
+ .headerEnabled(false)
+ .valueFormatter(function(d, i) {
+ return yAxis.tickFormat()(d, i);
+ })
+ .keyFormatter(function(d, i) {
+ return xAxis.tickFormat()(d, i);
+ });
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var renderWatch = nv.utils.renderWatch(dispatch, duration);
+
+ function chart(selection) {
+ renderWatch.reset();
+ renderWatch.models(discretebar);
+ if (showXAxis) renderWatch.models(xAxis);
+ if (showYAxis) renderWatch.models(yAxis);
+
+ selection.each(function(data) {
+ var container = d3.select(this),
+ that = this;
+ nv.utils.initSVG(container);
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ chart.update = function() {
+ dispatch.beforeUpdate();
+ container.transition().duration(duration).call(chart);
+ };
+ chart.container = this;
+
+ // Display No Data message if there's nothing to show.
+ if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
+ nv.utils.noData(chart, container);
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ // Setup Scales
+ x = discretebar.xScale();
+ y = discretebar.yScale().clamp(true);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-discreteBarWithAxes').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discreteBarWithAxes').append('g');
+ var defsEnter = gEnter.append('defs');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-x nv-axis');
+ gEnter.append('g').attr('class', 'nv-y nv-axis')
+ .append('g').attr('class', 'nv-zeroLine')
+ .append('line');
+
+ gEnter.append('g').attr('class', 'nv-barsWrap');
+
+ g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ if (rightAlignYAxis) {
+ g.select(".nv-y.nv-axis")
+ .attr("transform", "translate(" + availableWidth + ",0)");
+ }
+
+ // Main Chart Component(s)
+ discretebar
+ .width(availableWidth)
+ .height(availableHeight);
+
+ var barsWrap = g.select('.nv-barsWrap')
+ .datum(data.filter(function(d) { return !d.disabled }));
+
+ barsWrap.transition().call(discretebar);
+
+
+ defsEnter.append('clipPath')
+ .attr('id', 'nv-x-label-clip-' + discretebar.id())
+ .append('rect');
+
+ g.select('#nv-x-label-clip-' + discretebar.id() + ' rect')
+ .attr('width', x.rangeBand() * (staggerLabels ? 2 : 1))
+ .attr('height', 16)
+ .attr('x', -x.rangeBand() / (staggerLabels ? 1 : 2 ));
+
+ // Setup Axes
+ if (showXAxis) {
+ xAxis
+ .scale(x)
+ ._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
+ .tickSize(-availableHeight, 0);
+
+ g.select('.nv-x.nv-axis')
+ .attr('transform', 'translate(0,' + (y.range()[0] + ((discretebar.showValues() && y.domain()[0] < 0) ? 16 : 0)) + ')');
+ g.select('.nv-x.nv-axis').call(xAxis);
+
+ var xTicks = g.select('.nv-x.nv-axis').selectAll('g');
+ if (staggerLabels) {
+ xTicks
+ .selectAll('text')
+ .attr('transform', function(d,i,j) { return 'translate(0,' + (j % 2 == 0 ? '5' : '17') + ')' })
+ }
+ }
+
+ if (showYAxis) {
+ yAxis
+ .scale(y)
+ ._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
+ .tickSize( -availableWidth, 0);
+
+ g.select('.nv-y.nv-axis').call(yAxis);
+ }
+
+ // Zero line
+ g.select(".nv-zeroLine line")
+ .attr("x1",0)
+ .attr("x2",availableWidth)
+ .attr("y1", y(0))
+ .attr("y2", y(0))
+ ;
+ });
+
+ renderWatch.renderEnd('discreteBar chart immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (out of chart's scope)
+ //------------------------------------------------------------
+
+ discretebar.dispatch.on('elementMouseover.tooltip', function(evt) {
+ evt['series'] = {
+ key: chart.x()(evt.data),
+ value: chart.y()(evt.data),
+ color: evt.color
+ };
+ tooltip.data(evt).hidden(false);
+ });
+
+ discretebar.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true);
+ });
+
+ discretebar.dispatch.on('elementMousemove.tooltip', function(evt) {
+ tooltip.position({top: d3.event.pageY, left: d3.event.pageX})();
+ });
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.discretebar = discretebar;
+ chart.xAxis = xAxis;
+ chart.yAxis = yAxis;
+ chart.tooltip = tooltip;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ staggerLabels: {get: function(){return staggerLabels;}, set: function(_){staggerLabels=_;}},
+ showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
+ showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+
+ // deprecated options
+ tooltips: {get: function(){return tooltip.enabled();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltips', 'use chart.tooltip.enabled() instead');
+ tooltip.enabled(!!_);
+ }},
+ tooltipContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'use chart.tooltip.contentGenerator() instead');
+ tooltip.contentGenerator(_);
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ discretebar.duration(duration);
+ xAxis.duration(duration);
+ yAxis.duration(duration);
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ discretebar.color(color);
+ }},
+ rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
+ rightAlignYAxis = _;
+ yAxis.orient( (_) ? 'right' : 'left');
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, discretebar);
+ nv.utils.initOptions(chart);
+
+ return chart;
+}
+
+nv.models.distribution = function() {
+ "use strict";
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = 400 //technically width or height depending on x or y....
+ , size = 8
+ , axis = 'x' // 'x' or 'y'... horizontal or vertical
+ , getData = function(d) { return d[axis] } // defaults d.x or d.y
+ , color = nv.utils.defaultColor()
+ , scale = d3.scale.linear()
+ , domain
+ , duration = 250
+ , dispatch = d3.dispatch('renderEnd')
+ ;
+
+ //============================================================
+
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var scale0;
+ var renderWatch = nv.utils.renderWatch(dispatch, duration);
+
+ //============================================================
+
+
+ function chart(selection) {
+ renderWatch.reset();
+ selection.each(function(data) {
+ var availableLength = width - (axis === 'x' ? margin.left + margin.right : margin.top + margin.bottom),
+ naxis = axis == 'x' ? 'y' : 'x',
+ container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ //------------------------------------------------------------
+ // Setup Scales
+
+ scale0 = scale0 || scale;
+
+ //------------------------------------------------------------
+
+
+ //------------------------------------------------------------
+ // Setup containers and skeleton of chart
+
+ var wrap = container.selectAll('g.nv-distribution').data([data]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-distribution');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
+
+ //------------------------------------------------------------
+
+
+ var distWrap = g.selectAll('g.nv-dist')
+ .data(function(d) { return d }, function(d) { return d.key });
+
+ distWrap.enter().append('g');
+ distWrap
+ .attr('class', function(d,i) { return 'nv-dist nv-series-' + i })
+ .style('stroke', function(d,i) { return color(d, i) });
+
+ var dist = distWrap.selectAll('line.nv-dist' + axis)
+ .data(function(d) { return d.values })
+ dist.enter().append('line')
+ .attr(axis + '1', function(d,i) { return scale0(getData(d,i)) })
+ .attr(axis + '2', function(d,i) { return scale0(getData(d,i)) })
+ renderWatch.transition(distWrap.exit().selectAll('line.nv-dist' + axis), 'dist exit')
+ // .transition()
+ .attr(axis + '1', function(d,i) { return scale(getData(d,i)) })
+ .attr(axis + '2', function(d,i) { return scale(getData(d,i)) })
+ .style('stroke-opacity', 0)
+ .remove();
+ dist
+ .attr('class', function(d,i) { return 'nv-dist' + axis + ' nv-dist' + axis + '-' + i })
+ .attr(naxis + '1', 0)
+ .attr(naxis + '2', size);
+ renderWatch.transition(dist, 'dist')
+ // .transition()
+ .attr(axis + '1', function(d,i) { return scale(getData(d,i)) })
+ .attr(axis + '2', function(d,i) { return scale(getData(d,i)) })
+
+
+ scale0 = scale.copy();
+
+ });
+ renderWatch.renderEnd('distribution immediate');
+ return chart;
+ }
+
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+ chart.options = nv.utils.optionsFunc.bind(chart);
+ chart.dispatch = dispatch;
+
+ chart.margin = function(_) {
+ if (!arguments.length) return margin;
+ margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
+ margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
+ margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
+ margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
+ return chart;
+ };
+
+ chart.width = function(_) {
+ if (!arguments.length) return width;
+ width = _;
+ return chart;
+ };
+
+ chart.axis = function(_) {
+ if (!arguments.length) return axis;
+ axis = _;
+ return chart;
+ };
+
+ chart.size = function(_) {
+ if (!arguments.length) return size;
+ size = _;
+ return chart;
+ };
+
+ chart.getData = function(_) {
+ if (!arguments.length) return getData;
+ getData = d3.functor(_);
+ return chart;
+ };
+
+ chart.scale = function(_) {
+ if (!arguments.length) return scale;
+ scale = _;
+ return chart;
+ };
+
+ chart.color = function(_) {
+ if (!arguments.length) return color;
+ color = nv.utils.getColor(_);
+ return chart;
+ };
+
+ chart.duration = function(_) {
+ if (!arguments.length) return duration;
+ duration = _;
+ renderWatch.reset(duration);
+ return chart;
+ };
+ //============================================================
+
+
+ return chart;
+}
+nv.models.furiousLegend = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 5, right: 0, bottom: 5, left: 0}
+ , width = 400
+ , height = 20
+ , getKey = function(d) { return d.key }
+ , color = nv.utils.getColor()
+ , align = true
+ , padding = 28 //define how much space between legend items. - recommend 32 for furious version
+ , rightAlign = true
+ , updateState = true //If true, legend will update data.disabled and trigger a 'stateChange' dispatch.
+ , radioButtonMode = false //If true, clicking legend items will cause it to behave like a radio button. (only one can be selected at a time)
+ , expanded = false
+ , dispatch = d3.dispatch('legendClick', 'legendDblclick', 'legendMouseover', 'legendMouseout', 'stateChange')
+ , vers = 'classic' //Options are "classic" and "furious"
+ ;
+
+ function chart(selection) {
+ selection.each(function(data) {
+ var availableWidth = width - margin.left - margin.right,
+ container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-legend').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-legend').append('g');
+ var g = wrap.select('g');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ var series = g.selectAll('.nv-series')
+ .data(function(d) {
+ if(vers != 'furious') return d;
+
+ return d.filter(function(n) {
+ return expanded ? true : !n.disengaged;
+ });
+ });
+ var seriesEnter = series.enter().append('g').attr('class', 'nv-series')
+
+ var seriesShape;
+
+ if(vers == 'classic') {
+ seriesEnter.append('circle')
+ .style('stroke-width', 2)
+ .attr('class','nv-legend-symbol')
+ .attr('r', 5);
+
+ seriesShape = series.select('circle');
+ } else if (vers == 'furious') {
+ seriesEnter.append('rect')
+ .style('stroke-width', 2)
+ .attr('class','nv-legend-symbol')
+ .attr('rx', 3)
+ .attr('ry', 3);
+
+ seriesShape = series.select('rect');
+
+ seriesEnter.append('g')
+ .attr('class', 'nv-check-box')
+ .property('innerHTML','<path d="M0.5,5 L22.5,5 L22.5,26.5 L0.5,26.5 L0.5,5 Z" class="nv-box"></path><path d="M5.5,12.8618467 L11.9185089,19.2803556 L31,0.198864511" class="nv-check"></path>')
+ .attr('transform', 'translate(-10,-8)scale(0.5)');
+
+ var seriesCheckbox = series.select('.nv-check-box');
+
+ seriesCheckbox.each(function(d,i) {
+ d3.select(this).selectAll('path')
+ .attr('stroke', setTextColor(d,i));
+ });
+ }
+
+ seriesEnter.append('text')
+ .attr('text-anchor', 'start')
+ .attr('class','nv-legend-text')
+ .attr('dy', '.32em')
+ .attr('dx', '8');
+
+ var seriesText = series.select('text.nv-legend-text');
+
+ series
+ .on('mouseover', function(d,i) {
+ dispatch.legendMouseover(d,i); //TODO: Make consistent with other event objects
+ })
+ .on('mouseout', function(d,i) {
+ dispatch.legendMouseout(d,i);
+ })
+ .on('click', function(d,i) {
+ dispatch.legendClick(d,i);
+ // make sure we re-get data in case it was modified
+ var data = series.data();
+ if (updateState) {
+ if(vers =='classic') {
+ if (radioButtonMode) {
+ //Radio button mode: set every series to disabled,
+ // and enable the clicked series.
+ data.forEach(function(series) { series.disabled = true});
+ d.disabled = false;
+ }
+ else {
+ d.disabled = !d.disabled;
+ if (data.every(function(series) { return series.disabled})) {
+ //the default behavior of NVD3 legends is, if every single series
+ // is disabled, turn all series' back on.
+ data.forEach(function(series) { series.disabled = false});
+ }
+ }
+ } else if(vers == 'furious') {
+ if(expanded) {
+ d.disengaged = !d.disengaged;
+ d.userDisabled = d.userDisabled == undefined ? !!d.disabled : d.userDisabled;
+ d.disabled = d.disengaged || d.userDisabled;
+ } else if (!expanded) {
+ d.disabled = !d.disabled;
+ d.userDisabled = d.disabled;
+ var engaged = data.filter(function(d) { return !d.disengaged; });
+ if (engaged.every(function(series) { return series.userDisabled })) {
+ //the default behavior of NVD3 legends is, if every single series
+ // is disabled, turn all series' back on.
+ data.forEach(function(series) {
+ series.disabled = series.userDisabled = false;
+ });
+ }
+ }
+ }
+ dispatch.stateChange({
+ disabled: data.map(function(d) { return !!d.disabled }),
+ disengaged: data.map(function(d) { return !!d.disengaged })
+ });
+
+ }
+ })
+ .on('dblclick', function(d,i) {
+ if(vers == 'furious' && expanded) return;
+ dispatch.legendDblclick(d,i);
+ if (updateState) {
+ // make sure we re-get data in case it was modified
+ var data = series.data();
+ //the default behavior of NVD3 legends, when double clicking one,
+ // is to set all other series' to false, and make the double clicked series enabled.
+ data.forEach(function(series) {
+ series.disabled = true;
+ if(vers == 'furious') series.userDisabled = series.disabled;
+ });
+ d.disabled = false;
+ if(vers == 'furious') d.userDisabled = d.disabled;
+ dispatch.stateChange({
+ disabled: data.map(function(d) { return !!d.disabled })
+ });
+ }
+ });
+
+ series.classed('nv-disabled', function(d) { return d.userDisabled });
+ series.exit().remove();
+
+ seriesText
+ .attr('fill', setTextColor)
+ .text(getKey);
+
+ //TODO: implement fixed-width and max-width options (max-width is especially useful with the align option)
+ // NEW ALIGNING CODE, TODO: clean up
+
+ var versPadding;
+ switch(vers) {
+ case 'furious' :
+ versPadding = 23;
+ break;
+ case 'classic' :
+ versPadding = 20;
+ }
+
+ if (align) {
+
+ var seriesWidths = [];
+ series.each(function(d,i) {
+ var legendText = d3.select(this).select('text');
+ var nodeTextLength;
+ try {
+ nodeTextLength = legendText.node().getComputedTextLength();
+ // If the legendText is display:none'd (nodeTextLength == 0), simulate an error so we approximate, instead
+ if(nodeTextLength <= 0) throw Error();
+ }
+ catch(e) {
+ nodeTextLength = nv.utils.calcApproxTextWidth(legendText);
+ }
+
+ seriesWidths.push(nodeTextLength + padding);
+ });
+
+ var seriesPerRow = 0;
+ var legendWidth = 0;
+ var columnWidths = [];
+
+ while ( legendWidth < availableWidth && seriesPerRow < seriesWidths.length) {
+ columnWidths[seriesPerRow] = seriesWidths[seriesPerRow];
+ legendWidth += seriesWidths[seriesPerRow++];
+ }
+ if (seriesPerRow === 0) seriesPerRow = 1; //minimum of one series per row
+
+ while ( legendWidth > availableWidth && seriesPerRow > 1 ) {
+ columnWidths = [];
+ seriesPerRow--;
+
+ for (var k = 0; k < seriesWidths.length; k++) {
+ if (seriesWidths[k] > (columnWidths[k % seriesPerRow] || 0) )
+ columnWidths[k % seriesPerRow] = seriesWidths[k];
+ }
+
+ legendWidth = columnWidths.reduce(function(prev, cur, index, array) {
+ return prev + cur;
+ });
+ }
+
+ var xPositions = [];
+ for (var i = 0, curX = 0; i < seriesPerRow; i++) {
+ xPositions[i] = curX;
+ curX += columnWidths[i];
+ }
+
+ series
+ .attr('transform', function(d, i) {
+ return 'translate(' + xPositions[i % seriesPerRow] + ',' + (5 + Math.floor(i / seriesPerRow) * versPadding) + ')';
+ });
+
+ //position legend as far right as possible within the total width
+ if (rightAlign) {
+ g.attr('transform', 'translate(' + (width - margin.right - legendWidth) + ',' + margin.top + ')');
+ }
+ else {
+ g.attr('transform', 'translate(0' + ',' + margin.top + ')');
+ }
+
+ height = margin.top + margin.bottom + (Math.ceil(seriesWidths.length / seriesPerRow) * versPadding);
+
+ } else {
+
+ var ypos = 5,
+ newxpos = 5,
+ maxwidth = 0,
+ xpos;
+ series
+ .attr('transform', function(d, i) {
+ var length = d3.select(this).select('text').node().getComputedTextLength() + padding;
+ xpos = newxpos;
+
+ if (width < margin.left + margin.right + xpos + length) {
+ newxpos = xpos = 5;
+ ypos += versPadding;
+ }
+
+ newxpos += length;
+ if (newxpos > maxwidth) maxwidth = newxpos;
+
+ return 'translate(' + xpos + ',' + ypos + ')';
+ });
+
+ //position legend as far right as possible within the total width
+ g.attr('transform', 'translate(' + (width - margin.right - maxwidth) + ',' + margin.top + ')');
+
+ height = margin.top + margin.bottom + ypos + 15;
+ }
+
+ if(vers == 'furious') {
+ // Size rectangles after text is placed
+ seriesShape
+ .attr('width', function(d,i) {
+ return seriesText[0][i].getComputedTextLength() + 27;
+ })
+ .attr('height', 18)
+ .attr('y', -9)
+ .attr('x', -15)
+ }
+
+ seriesShape
+ .style('fill', setBGColor)
+ .style('stroke', function(d,i) { return d.color || color(d, i) });
+ });
+
+ function setTextColor(d,i) {
+ if(vers != 'furious') return '#000';
+ if(expanded) {
+ return d.disengaged ? color(d,i) : '#fff';
+ } else if (!expanded) {
+ return !!d.disabled ? color(d,i) : '#fff';
+ }
+ }
+
+ function setBGColor(d,i) {
+ if(expanded && vers == 'furious') {
+ return d.disengaged ? '#fff' : color(d,i);
+ } else {
+ return !!d.disabled ? '#fff' : color(d,i);
+ }
+ }
+
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ key: {get: function(){return getKey;}, set: function(_){getKey=_;}},
+ align: {get: function(){return align;}, set: function(_){align=_;}},
+ rightAlign: {get: function(){return rightAlign;}, set: function(_){rightAlign=_;}},
+ padding: {get: function(){return padding;}, set: function(_){padding=_;}},
+ updateState: {get: function(){return updateState;}, set: function(_){updateState=_;}},
+ radioButtonMode: {get: function(){return radioButtonMode;}, set: function(_){radioButtonMode=_;}},
+ expanded: {get: function(){return expanded;}, set: function(_){expanded=_;}},
+ vers: {get: function(){return vers;}, set: function(_){vers=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+//TODO: consider deprecating and using multibar with single series for this
+nv.models.historicalBar = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = null
+ , height = null
+ , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
+ , container = null
+ , x = d3.scale.linear()
+ , y = d3.scale.linear()
+ , getX = function(d) { return d.x }
+ , getY = function(d) { return d.y }
+ , forceX = []
+ , forceY = [0]
+ , padData = false
+ , clipEdge = true
+ , color = nv.utils.defaultColor()
+ , xDomain
+ , yDomain
+ , xRange
+ , yRange
+ , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove', 'renderEnd')
+ , interactive = true
+ ;
+
+ var renderWatch = nv.utils.renderWatch(dispatch, 0);
+
+ function chart(selection) {
+ selection.each(function(data) {
+ renderWatch.reset();
+
+ container = d3.select(this);
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ nv.utils.initSVG(container);
+
+ // Setup Scales
+ x.domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) ));
+
+ if (padData)
+ x.range(xRange || [availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]);
+ else
+ x.range(xRange || [0, availableWidth]);
+
+ y.domain(yDomain || d3.extent(data[0].values.map(getY).concat(forceY) ))
+ .range(yRange || [availableHeight, 0]);
+
+ // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
+ if (x.domain()[0] === x.domain()[1])
+ x.domain()[0] ?
+ x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
+ : x.domain([-1,1]);
+
+ if (y.domain()[0] === y.domain()[1])
+ y.domain()[0] ?
+ y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01])
+ : y.domain([-1,1]);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-historicalBar-' + id).data([data[0].values]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-historicalBar-' + id);
+ var defsEnter = wrapEnter.append('defs');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-bars');
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ container
+ .on('click', function(d,i) {
+ dispatch.chartClick({
+ data: d,
+ index: i,
+ pos: d3.event,
+ id: id
+ });
+ });
+
+ defsEnter.append('clipPath')
+ .attr('id', 'nv-chart-clip-path-' + id)
+ .append('rect');
+
+ wrap.select('#nv-chart-clip-path-' + id + ' rect')
+ .attr('width', availableWidth)
+ .attr('height', availableHeight);
+
+ g.attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : '');
+
+ var bars = wrap.select('.nv-bars').selectAll('.nv-bar')
+ .data(function(d) { return d }, function(d,i) {return getX(d,i)});
+ bars.exit().remove();
+
+ bars.enter().append('rect')
+ .attr('x', 0 )
+ .attr('y', function(d,i) { return nv.utils.NaNtoZero(y(Math.max(0, getY(d,i)))) })
+ .attr('height', function(d,i) { return nv.utils.NaNtoZero(Math.abs(y(getY(d,i)) - y(0))) })
+ .attr('transform', function(d,i) { return 'translate(' + (x(getX(d,i)) - availableWidth / data[0].values.length * .45) + ',0)'; })
+ .on('mouseover', function(d,i) {
+ if (!interactive) return;
+ d3.select(this).classed('hover', true);
+ dispatch.elementMouseover({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+
+ })
+ .on('mouseout', function(d,i) {
+ if (!interactive) return;
+ d3.select(this).classed('hover', false);
+ dispatch.elementMouseout({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ })
+ .on('mousemove', function(d,i) {
+ if (!interactive) return;
+ dispatch.elementMousemove({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ })
+ .on('click', function(d,i) {
+ if (!interactive) return;
+ dispatch.elementClick({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ d3.event.stopPropagation();
+ })
+ .on('dblclick', function(d,i) {
+ if (!interactive) return;
+ dispatch.elementDblClick({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ d3.event.stopPropagation();
+ });
+
+ bars
+ .attr('fill', function(d,i) { return color(d, i); })
+ .attr('class', function(d,i,j) { return (getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive') + ' nv-bar-' + j + '-' + i })
+ .watchTransition(renderWatch, 'bars')
+ .attr('transform', function(d,i) { return 'translate(' + (x(getX(d,i)) - availableWidth / data[0].values.length * .45) + ',0)'; })
+ //TODO: better width calculations that don't assume always uniform data spacing;w
+ .attr('width', (availableWidth / data[0].values.length) * .9 );
+
+ bars.watchTransition(renderWatch, 'bars')
+ .attr('y', function(d,i) {
+ var rval = getY(d,i) < 0 ?
+ y(0) :
+ y(0) - y(getY(d,i)) < 1 ?
+ y(0) - 1 :
+ y(getY(d,i));
+ return nv.utils.NaNtoZero(rval);
+ })
+ .attr('height', function(d,i) { return nv.utils.NaNtoZero(Math.max(Math.abs(y(getY(d,i)) - y(0)),1)) });
+
+ });
+
+ renderWatch.renderEnd('historicalBar immediate');
+ return chart;
+ }
+
+ //Create methods to allow outside functions to highlight a specific bar.
+ chart.highlightPoint = function(pointIndex, isHoverOver) {
+ container
+ .select(".nv-bars .nv-bar-0-" + pointIndex)
+ .classed("hover", isHoverOver)
+ ;
+ };
+
+ chart.clearHighlights = function() {
+ container
+ .select(".nv-bars .nv-bar.hover")
+ .classed("hover", false)
+ ;
+ };
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ forceX: {get: function(){return forceX;}, set: function(_){forceX=_;}},
+ forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
+ padData: {get: function(){return padData;}, set: function(_){padData=_;}},
+ x: {get: function(){return getX;}, set: function(_){getX=_;}},
+ y: {get: function(){return getY;}, set: function(_){getY=_;}},
+ xScale: {get: function(){return x;}, set: function(_){x=_;}},
+ yScale: {get: function(){return y;}, set: function(_){y=_;}},
+ xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
+ yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
+ xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
+ yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
+ clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
+ id: {get: function(){return id;}, set: function(_){id=_;}},
+ interactive: {get: function(){return interactive;}, set: function(_){interactive=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+
+nv.models.historicalBarChart = function(bar_model) {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var bars = bar_model || nv.models.historicalBar()
+ , xAxis = nv.models.axis()
+ , yAxis = nv.models.axis()
+ , legend = nv.models.legend()
+ , interactiveLayer = nv.interactiveGuideline()
+ , tooltip = nv.models.tooltip()
+ ;
+
+
+ var margin = {top: 30, right: 90, bottom: 50, left: 90}
+ , color = nv.utils.defaultColor()
+ , width = null
+ , height = null
+ , showLegend = false
+ , showXAxis = true
+ , showYAxis = true
+ , rightAlignYAxis = false
+ , useInteractiveGuideline = false
+ , x
+ , y
+ , state = {}
+ , defaultState = null
+ , noData = null
+ , dispatch = d3.dispatch('tooltipHide', 'stateChange', 'changeState', 'renderEnd')
+ , transitionDuration = 250
+ ;
+
+ xAxis.orient('bottom').tickPadding(7);
+ yAxis.orient( (rightAlignYAxis) ? 'right' : 'left');
+ tooltip
+ .duration(0)
+ .headerEnabled(false)
+ .valueFormatter(function(d, i) {
+ return yAxis.tickFormat()(d, i);
+ })
+ .headerFormatter(function(d, i) {
+ return xAxis.tickFormat()(d, i);
+ });
+
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var renderWatch = nv.utils.renderWatch(dispatch, 0);
+
+ function chart(selection) {
+ selection.each(function(data) {
+ renderWatch.reset();
+ renderWatch.models(bars);
+ if (showXAxis) renderWatch.models(xAxis);
+ if (showYAxis) renderWatch.models(yAxis);
+
+ var container = d3.select(this),
+ that = this;
+ nv.utils.initSVG(container);
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ chart.update = function() { container.transition().duration(transitionDuration).call(chart) };
+ chart.container = this;
+
+ //set state.disabled
+ state.disabled = data.map(function(d) { return !!d.disabled });
+
+ if (!defaultState) {
+ var key;
+ defaultState = {};
+ for (key in state) {
+ if (state[key] instanceof Array)
+ defaultState[key] = state[key].slice(0);
+ else
+ defaultState[key] = state[key];
+ }
+ }
+
+ // Display noData message if there's nothing to show.
+ if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
+ nv.utils.noData(chart, container)
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ // Setup Scales
+ x = bars.xScale();
+ y = bars.yScale();
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-historicalBarChart').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-historicalBarChart').append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-x nv-axis');
+ gEnter.append('g').attr('class', 'nv-y nv-axis');
+ gEnter.append('g').attr('class', 'nv-barsWrap');
+ gEnter.append('g').attr('class', 'nv-legendWrap');
+ gEnter.append('g').attr('class', 'nv-interactive');
+
+ // Legend
+ if (showLegend) {
+ legend.width(availableWidth);
+
+ g.select('.nv-legendWrap')
+ .datum(data)
+ .call(legend);
+
+ if ( margin.top != legend.height()) {
+ margin.top = legend.height();
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+ }
+
+ wrap.select('.nv-legendWrap')
+ .attr('transform', 'translate(0,' + (-margin.top) +')')
+ }
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ if (rightAlignYAxis) {
+ g.select(".nv-y.nv-axis")
+ .attr("transform", "translate(" + availableWidth + ",0)");
+ }
+
+ //Set up interactive layer
+ if (useInteractiveGuideline) {
+ interactiveLayer
+ .width(availableWidth)
+ .height(availableHeight)
+ .margin({left:margin.left, top:margin.top})
+ .svgContainer(container)
+ .xScale(x);
+ wrap.select(".nv-interactive").call(interactiveLayer);
+ }
+ bars
+ .width(availableWidth)
+ .height(availableHeight)
+ .color(data.map(function(d,i) {
+ return d.color || color(d, i);
+ }).filter(function(d,i) { return !data[i].disabled }));
+
+ var barsWrap = g.select('.nv-barsWrap')
+ .datum(data.filter(function(d) { return !d.disabled }));
+ barsWrap.transition().call(bars);
+
+ // Setup Axes
+ if (showXAxis) {
+ xAxis
+ .scale(x)
+ ._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
+ .tickSize(-availableHeight, 0);
+
+ g.select('.nv-x.nv-axis')
+ .attr('transform', 'translate(0,' + y.range()[0] + ')');
+ g.select('.nv-x.nv-axis')
+ .transition()
+ .call(xAxis);
+ }
+
+ if (showYAxis) {
+ yAxis
+ .scale(y)
+ ._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
+ .tickSize( -availableWidth, 0);
+
+ g.select('.nv-y.nv-axis')
+ .transition()
+ .call(yAxis);
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (in chart's scope)
+ //------------------------------------------------------------
+
+ interactiveLayer.dispatch.on('elementMousemove', function(e) {
+ bars.clearHighlights();
+
+ var singlePoint, pointIndex, pointXLocation, allData = [];
+ data
+ .filter(function(series, i) {
+ series.seriesIndex = i;
+ return !series.disabled;
+ })
+ .forEach(function(series,i) {
+ pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
+ bars.highlightPoint(pointIndex,true);
+ var point = series.values[pointIndex];
+ if (point === undefined) return;
+ if (singlePoint === undefined) singlePoint = point;
+ if (pointXLocation === undefined) pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
+ allData.push({
+ key: series.key,
+ value: chart.y()(point, pointIndex),
+ color: color(series,series.seriesIndex),
+ data: series.values[pointIndex]
+ });
+ });
+
+ var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex));
+ interactiveLayer.tooltip
+ .position({left: pointXLocation + margin.left, top: e.mouseY + margin.top})
+ .chartContainer(that.parentNode)
+ .valueFormatter(function(d,i) {
+ return yAxis.tickFormat()(d);
+ })
+ .data({
+ value: xValue,
+ index: pointIndex,
+ series: allData
+ })();
+
+ interactiveLayer.renderGuideLine(pointXLocation);
+
+ });
+
+ interactiveLayer.dispatch.on("elementMouseout",function(e) {
+ dispatch.tooltipHide();
+ bars.clearHighlights();
+ });
+
+ legend.dispatch.on('legendClick', function(d,i) {
+ d.disabled = !d.disabled;
+
+ if (!data.filter(function(d) { return !d.disabled }).length) {
+ data.map(function(d) {
+ d.disabled = false;
+ wrap.selectAll('.nv-series').classed('disabled', false);
+ return d;
+ });
+ }
+
+ state.disabled = data.map(function(d) { return !!d.disabled });
+ dispatch.stateChange(state);
+
+ selection.transition().call(chart);
+ });
+
+ legend.dispatch.on('legendDblclick', function(d) {
+ //Double clicking should always enable current series, and disabled all others.
+ data.forEach(function(d) {
+ d.disabled = true;
+ });
+ d.disabled = false;
+
+ state.disabled = data.map(function(d) { return !!d.disabled });
+ dispatch.stateChange(state);
+ chart.update();
+ });
+
+ dispatch.on('changeState', function(e) {
+ if (typeof e.disabled !== 'undefined') {
+ data.forEach(function(series,i) {
+ series.disabled = e.disabled[i];
+ });
+
+ state.disabled = e.disabled;
+ }
+
+ chart.update();
+ });
+ });
+
+ renderWatch.renderEnd('historicalBarChart immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (out of chart's scope)
+ //------------------------------------------------------------
+
+ bars.dispatch.on('elementMouseover.tooltip', function(evt) {
+ evt['series'] = {
+ key: chart.x()(evt.data),
+ value: chart.y()(evt.data),
+ color: evt.color
+ };
+ tooltip.data(evt).hidden(false);
+ });
+
+ bars.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true);
+ });
+
+ bars.dispatch.on('elementMousemove.tooltip', function(evt) {
+ tooltip.position({top: d3.event.pageY, left: d3.event.pageX})();
+ });
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ // expose chart's sub-components
+ chart.dispatch = dispatch;
+ chart.bars = bars;
+ chart.legend = legend;
+ chart.xAxis = xAxis;
+ chart.yAxis = yAxis;
+ chart.interactiveLayer = interactiveLayer;
+ chart.tooltip = tooltip;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
+ showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
+ showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
+ defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+
+ // deprecated options
+ tooltips: {get: function(){return tooltip.enabled();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltips', 'use chart.tooltip.enabled() instead');
+ tooltip.enabled(!!_);
+ }},
+ tooltipContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'use chart.tooltip.contentGenerator() instead');
+ tooltip.contentGenerator(_);
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ legend.color(color);
+ bars.color(color);
+ }},
+ duration: {get: function(){return transitionDuration;}, set: function(_){
+ transitionDuration=_;
+ renderWatch.reset(transitionDuration);
+ yAxis.duration(transitionDuration);
+ xAxis.duration(transitionDuration);
+ }},
+ rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
+ rightAlignYAxis = _;
+ yAxis.orient( (_) ? 'right' : 'left');
+ }},
+ useInteractiveGuideline: {get: function(){return useInteractiveGuideline;}, set: function(_){
+ useInteractiveGuideline = _;
+ if (_ === true) {
+ chart.interactive(false);
+ }
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, bars);
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+
+
+// ohlcChart is just a historical chart with ohlc bars and some tweaks
+nv.models.ohlcBarChart = function() {
+ var chart = nv.models.historicalBarChart(nv.models.ohlcBar());
+
+ // special default tooltip since we show multiple values per x
+ chart.useInteractiveGuideline(true);
+ chart.interactiveLayer.tooltip.contentGenerator(function(data) {
+ // we assume only one series exists for this chart
+ var d = data.series[0].data;
+ // match line colors as defined in nv.d3.css
+ var color = d.open < d.close ? "2ca02c" : "d62728";
+ return '' +
+ '<h3 style="color: #' + color + '">' + data.value + '</h3>' +
+ '<table>' +
+ '<tr><td>open:</td><td>' + chart.yAxis.tickFormat()(d.open) + '</td></tr>' +
+ '<tr><td>close:</td><td>' + chart.yAxis.tickFormat()(d.close) + '</td></tr>' +
+ '<tr><td>high</td><td>' + chart.yAxis.tickFormat()(d.high) + '</td></tr>' +
+ '<tr><td>low:</td><td>' + chart.yAxis.tickFormat()(d.low) + '</td></tr>' +
+ '</table>';
+ });
+ return chart;
+};
+
+// candlestickChart is just a historical chart with candlestick bars and some tweaks
+nv.models.candlestickBarChart = function() {
+ var chart = nv.models.historicalBarChart(nv.models.candlestickBar());
+
+ // special default tooltip since we show multiple values per x
+ chart.useInteractiveGuideline(true);
+ chart.interactiveLayer.tooltip.contentGenerator(function(data) {
+ // we assume only one series exists for this chart
+ var d = data.series[0].data;
+ // match line colors as defined in nv.d3.css
+ var color = d.open < d.close ? "2ca02c" : "d62728";
+ return '' +
+ '<h3 style="color: #' + color + '">' + data.value + '</h3>' +
+ '<table>' +
+ '<tr><td>open:</td><td>' + chart.yAxis.tickFormat()(d.open) + '</td></tr>' +
+ '<tr><td>close:</td><td>' + chart.yAxis.tickFormat()(d.close) + '</td></tr>' +
+ '<tr><td>high</td><td>' + chart.yAxis.tickFormat()(d.high) + '</td></tr>' +
+ '<tr><td>low:</td><td>' + chart.yAxis.tickFormat()(d.low) + '</td></tr>' +
+ '</table>';
+ });
+ return chart;
+};
+nv.models.legend = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 5, right: 0, bottom: 5, left: 0}
+ , width = 400
+ , height = 20
+ , getKey = function(d) { return d.key }
+ , color = nv.utils.getColor()
+ , align = true
+ , padding = 32 //define how much space between legend items. - recommend 32 for furious version
+ , rightAlign = true
+ , updateState = true //If true, legend will update data.disabled and trigger a 'stateChange' dispatch.
+ , radioButtonMode = false //If true, clicking legend items will cause it to behave like a radio button. (only one can be selected at a time)
+ , expanded = false
+ , dispatch = d3.dispatch('legendClick', 'legendDblclick', 'legendMouseover', 'legendMouseout', 'stateChange')
+ , vers = 'classic' //Options are "classic" and "furious"
+ ;
+
+ function chart(selection) {
+ selection.each(function(data) {
+ var availableWidth = width - margin.left - margin.right,
+ container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-legend').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-legend').append('g');
+ var g = wrap.select('g');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ var series = g.selectAll('.nv-series')
+ .data(function(d) {
+ if(vers != 'furious') return d;
+
+ return d.filter(function(n) {
+ return expanded ? true : !n.disengaged;
+ });
+ });
+
+ var seriesEnter = series.enter().append('g').attr('class', 'nv-series');
+ var seriesShape;
+
+ var versPadding;
+ switch(vers) {
+ case 'furious' :
+ versPadding = 23;
+ break;
+ case 'classic' :
+ versPadding = 20;
+ }
+
+ if(vers == 'classic') {
+ seriesEnter.append('circle')
+ .style('stroke-width', 2)
+ .attr('class','nv-legend-symbol')
+ .attr('r', 5);
+
+ seriesShape = series.select('circle');
+ } else if (vers == 'furious') {
+ seriesEnter.append('rect')
+ .style('stroke-width', 2)
+ .attr('class','nv-legend-symbol')
+ .attr('rx', 3)
+ .attr('ry', 3);
+
+ seriesShape = series.select('.nv-legend-symbol');
+
+ seriesEnter.append('g')
+ .attr('class', 'nv-check-box')
+ .property('innerHTML','<path d="M0.5,5 L22.5,5 L22.5,26.5 L0.5,26.5 L0.5,5 Z" class="nv-box"></path><path d="M5.5,12.8618467 L11.9185089,19.2803556 L31,0.198864511" class="nv-check"></path>')
+ .attr('transform', 'translate(-10,-8)scale(0.5)');
+
+ var seriesCheckbox = series.select('.nv-check-box');
+
+ seriesCheckbox.each(function(d,i) {
+ d3.select(this).selectAll('path')
+ .attr('stroke', setTextColor(d,i));
+ });
+ }
+
+ seriesEnter.append('text')
+ .attr('text-anchor', 'start')
+ .attr('class','nv-legend-text')
+ .attr('dy', '.32em')
+ .attr('dx', '8');
+
+ var seriesText = series.select('text.nv-legend-text');
+
+ series
+ .on('mouseover', function(d,i) {
+ dispatch.legendMouseover(d,i); //TODO: Make consistent with other event objects
+ })
+ .on('mouseout', function(d,i) {
+ dispatch.legendMouseout(d,i);
+ })
+ .on('click', function(d,i) {
+ dispatch.legendClick(d,i);
+ // make sure we re-get data in case it was modified
+ var data = series.data();
+ if (updateState) {
+ if(vers =='classic') {
+ if (radioButtonMode) {
+ //Radio button mode: set every series to disabled,
+ // and enable the clicked series.
+ data.forEach(function(series) { series.disabled = true});
+ d.disabled = false;
+ }
+ else {
+ d.disabled = !d.disabled;
+ if (data.every(function(series) { return series.disabled})) {
+ //the default behavior of NVD3 legends is, if every single series
+ // is disabled, turn all series' back on.
+ data.forEach(function(series) { series.disabled = false});
+ }
+ }
+ } else if(vers == 'furious') {
+ if(expanded) {
+ d.disengaged = !d.disengaged;
+ d.userDisabled = d.userDisabled == undefined ? !!d.disabled : d.userDisabled;
+ d.disabled = d.disengaged || d.userDisabled;
+ } else if (!expanded) {
+ d.disabled = !d.disabled;
+ d.userDisabled = d.disabled;
+ var engaged = data.filter(function(d) { return !d.disengaged; });
+ if (engaged.every(function(series) { return series.userDisabled })) {
+ //the default behavior of NVD3 legends is, if every single series
+ // is disabled, turn all series' back on.
+ data.forEach(function(series) {
+ series.disabled = series.userDisabled = false;
+ });
+ }
+ }
+ }
+ dispatch.stateChange({
+ disabled: data.map(function(d) { return !!d.disabled }),
+ disengaged: data.map(function(d) { return !!d.disengaged })
+ });
+
+ }
+ })
+ .on('dblclick', function(d,i) {
+ if(vers == 'furious' && expanded) return;
+ dispatch.legendDblclick(d,i);
+ if (updateState) {
+ // make sure we re-get data in case it was modified
+ var data = series.data();
+ //the default behavior of NVD3 legends, when double clicking one,
+ // is to set all other series' to false, and make the double clicked series enabled.
+ data.forEach(function(series) {
+ series.disabled = true;
+ if(vers == 'furious') series.userDisabled = series.disabled;
+ });
+ d.disabled = false;
+ if(vers == 'furious') d.userDisabled = d.disabled;
+ dispatch.stateChange({
+ disabled: data.map(function(d) { return !!d.disabled })
+ });
+ }
+ });
+
+ series.classed('nv-disabled', function(d) { return d.userDisabled });
+ series.exit().remove();
+
+ seriesText
+ .attr('fill', setTextColor)
+ .text(getKey);
+
+ //TODO: implement fixed-width and max-width options (max-width is especially useful with the align option)
+ // NEW ALIGNING CODE, TODO: clean up
+ var legendWidth = 0;
+ if (align) {
+
+ var seriesWidths = [];
+ series.each(function(d,i) {
+ var legendText = d3.select(this).select('text');
+ var nodeTextLength;
+ try {
+ nodeTextLength = legendText.node().getComputedTextLength();
+ // If the legendText is display:none'd (nodeTextLength == 0), simulate an error so we approximate, instead
+ if(nodeTextLength <= 0) throw Error();
+ }
+ catch(e) {
+ nodeTextLength = nv.utils.calcApproxTextWidth(legendText);
+ }
+
+ seriesWidths.push(nodeTextLength + padding);
+ });
+
+ var seriesPerRow = 0;
+ var columnWidths = [];
+ legendWidth = 0;
+
+ while ( legendWidth < availableWidth && seriesPerRow < seriesWidths.length) {
+ columnWidths[seriesPerRow] = seriesWidths[seriesPerRow];
+ legendWidth += seriesWidths[seriesPerRow++];
+ }
+ if (seriesPerRow === 0) seriesPerRow = 1; //minimum of one series per row
+
+ while ( legendWidth > availableWidth && seriesPerRow > 1 ) {
+ columnWidths = [];
+ seriesPerRow--;
+
+ for (var k = 0; k < seriesWidths.length; k++) {
+ if (seriesWidths[k] > (columnWidths[k % seriesPerRow] || 0) )
+ columnWidths[k % seriesPerRow] = seriesWidths[k];
+ }
+
+ legendWidth = columnWidths.reduce(function(prev, cur, index, array) {
+ return prev + cur;
+ });
+ }
+
+ var xPositions = [];
+ for (var i = 0, curX = 0; i < seriesPerRow; i++) {
+ xPositions[i] = curX;
+ curX += columnWidths[i];
+ }
+
+ series
+ .attr('transform', function(d, i) {
+ return 'translate(' + xPositions[i % seriesPerRow] + ',' + (5 + Math.floor(i / seriesPerRow) * versPadding) + ')';
+ });
+
+ //position legend as far right as possible within the total width
+ if (rightAlign) {
+ g.attr('transform', 'translate(' + (width - margin.right - legendWidth) + ',' + margin.top + ')');
+ }
+ else {
+ g.attr('transform', 'translate(0' + ',' + margin.top + ')');
+ }
+
+ height = margin.top + margin.bottom + (Math.ceil(seriesWidths.length / seriesPerRow) * versPadding);
+
+ } else {
+
+ var ypos = 5,
+ newxpos = 5,
+ maxwidth = 0,
+ xpos;
+ series
+ .attr('transform', function(d, i) {
+ var length = d3.select(this).select('text').node().getComputedTextLength() + padding;
+ xpos = newxpos;
+
+ if (width < margin.left + margin.right + xpos + length) {
+ newxpos = xpos = 5;
+ ypos += versPadding;
+ }
+
+ newxpos += length;
+ if (newxpos > maxwidth) maxwidth = newxpos;
+
+ if(legendWidth < xpos + maxwidth) {
+ legendWidth = xpos + maxwidth;
+ }
+ return 'translate(' + xpos + ',' + ypos + ')';
+ });
+
+ //position legend as far right as possible within the total width
+ g.attr('transform', 'translate(' + (width - margin.right - maxwidth) + ',' + margin.top + ')');
+
+ height = margin.top + margin.bottom + ypos + 15;
+ }
+
+ if(vers == 'furious') {
+ // Size rectangles after text is placed
+ seriesShape
+ .attr('width', function(d,i) {
+ return seriesText[0][i].getComputedTextLength() + 27;
+ })
+ .attr('height', 18)
+ .attr('y', -9)
+ .attr('x', -15);
+
+ // The background for the expanded legend (UI)
+ gEnter.insert('rect',':first-child')
+ .attr('class', 'nv-legend-bg')
+ .attr('fill', '#eee')
+ // .attr('stroke', '#444')
+ .attr('opacity',0);
+
+ var seriesBG = g.select('.nv-legend-bg');
+
+ seriesBG
+ .transition().duration(300)
+ .attr('x', -versPadding )
+ .attr('width', legendWidth + versPadding - 12)
+ .attr('height', height + 10)
+ .attr('y', -margin.top - 10)
+ .attr('opacity', expanded ? 1 : 0);
+
+
+ }
+
+ seriesShape
+ .style('fill', setBGColor)
+ .style('fill-opacity', setBGOpacity)
+ .style('stroke', setBGColor);
+ });
+
+ function setTextColor(d,i) {
+ if(vers != 'furious') return '#000';
+ if(expanded) {
+ return d.disengaged ? '#000' : '#fff';
+ } else if (!expanded) {
+ if(!d.color) d.color = color(d,i);
+ return !!d.disabled ? d.color : '#fff';
+ }
+ }
+
+ function setBGColor(d,i) {
+ if(expanded && vers == 'furious') {
+ return d.disengaged ? '#eee' : d.color || color(d,i);
+ } else {
+ return d.color || color(d,i);
+ }
+ }
+
+
+ function setBGOpacity(d,i) {
+ if(expanded && vers == 'furious') {
+ return 1;
+ } else {
+ return !!d.disabled ? 0 : 1;
+ }
+ }
+
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ key: {get: function(){return getKey;}, set: function(_){getKey=_;}},
+ align: {get: function(){return align;}, set: function(_){align=_;}},
+ rightAlign: {get: function(){return rightAlign;}, set: function(_){rightAlign=_;}},
+ padding: {get: function(){return padding;}, set: function(_){padding=_;}},
+ updateState: {get: function(){return updateState;}, set: function(_){updateState=_;}},
+ radioButtonMode: {get: function(){return radioButtonMode;}, set: function(_){radioButtonMode=_;}},
+ expanded: {get: function(){return expanded;}, set: function(_){expanded=_;}},
+ vers: {get: function(){return vers;}, set: function(_){vers=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+
+nv.models.line = function() {
+ "use strict";
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var scatter = nv.models.scatter()
+ ;
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = 960
+ , height = 500
+ , container = null
+ , strokeWidth = 1.5
+ , color = nv.utils.defaultColor() // a function that returns a color
+ , getX = function(d) { return d.x } // accessor to get the x value from a data point
+ , getY = function(d) { return d.y } // accessor to get the y value from a data point
+ , defined = function(d,i) { return !isNaN(getY(d,i)) && getY(d,i) !== null } // allows a line to be not continuous when it is not defined
+ , isArea = function(d) { return d.area } // decides if a line is an area or just a line
+ , clipEdge = false // if true, masks lines within x and y scale
+ , x //can be accessed via chart.xScale()
+ , y //can be accessed via chart.yScale()
+ , interpolate = "linear" // controls the line interpolation
+ , duration = 250
+ , dispatch = d3.dispatch('elementClick', 'elementMouseover', 'elementMouseout', 'renderEnd')
+ ;
+
+ scatter
+ .pointSize(16) // default size
+ .pointDomain([16,256]) //set to speed up calculation, needs to be unset if there is a custom size accessor
+ ;
+
+ //============================================================
+
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var x0, y0 //used to store previous scales
+ , renderWatch = nv.utils.renderWatch(dispatch, duration)
+ ;
+
+ //============================================================
+
+
+ function chart(selection) {
+ renderWatch.reset();
+ renderWatch.models(scatter);
+ selection.each(function(data) {
+ container = d3.select(this);
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+ nv.utils.initSVG(container);
+
+ // Setup Scales
+ x = scatter.xScale();
+ y = scatter.yScale();
+
+ x0 = x0 || x;
+ y0 = y0 || y;
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-line').data([data]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-line');
+ var defsEnter = wrapEnter.append('defs');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-groups');
+ gEnter.append('g').attr('class', 'nv-scatterWrap');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ scatter
+ .width(availableWidth)
+ .height(availableHeight);
+
+ var scatterWrap = wrap.select('.nv-scatterWrap');
+ scatterWrap.call(scatter);
+
+ defsEnter.append('clipPath')
+ .attr('id', 'nv-edge-clip-' + scatter.id())
+ .append('rect');
+
+ wrap.select('#nv-edge-clip-' + scatter.id() + ' rect')
+ .attr('width', availableWidth)
+ .attr('height', (availableHeight > 0) ? availableHeight : 0);
+
+ g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + scatter.id() + ')' : '');
+ scatterWrap
+ .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + scatter.id() + ')' : '');
+
+ var groups = wrap.select('.nv-groups').selectAll('.nv-group')
+ .data(function(d) { return d }, function(d) { return d.key });
+ groups.enter().append('g')
+ .style('stroke-opacity', 1e-6)
+ .style('stroke-width', function(d) { return d.strokeWidth || strokeWidth })
+ .style('fill-opacity', 1e-6);
+
+ groups.exit().remove();
+
+ groups
+ .attr('class', function(d,i) {
+ return (d.classed || '') + ' nv-group nv-series-' + i;
+ })
+ .classed('hover', function(d) { return d.hover })
+ .style('fill', function(d,i){ return color(d, i) })
+ .style('stroke', function(d,i){ return color(d, i)});
+ groups.watchTransition(renderWatch, 'line: groups')
+ .style('stroke-opacity', 1)
+ .style('fill-opacity', function(d) { return d.fillOpacity || .5});
+
+ var areaPaths = groups.selectAll('path.nv-area')
+ .data(function(d) { return isArea(d) ? [d] : [] }); // this is done differently than lines because I need to check if series is an area
+ areaPaths.enter().append('path')
+ .attr('class', 'nv-area')
+ .attr('d', function(d) {
+ return d3.svg.area()
+ .interpolate(interpolate)
+ .defined(defined)
+ .x(function(d,i) { return nv.utils.NaNtoZero(x0(getX(d,i))) })
+ .y0(function(d,i) { return nv.utils.NaNtoZero(y0(getY(d,i))) })
+ .y1(function(d,i) { return y0( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) })
+ //.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this
+ .apply(this, [d.values])
+ });
+ groups.exit().selectAll('path.nv-area')
+ .remove();
+
+ areaPaths.watchTransition(renderWatch, 'line: areaPaths')
+ .attr('d', function(d) {
+ return d3.svg.area()
+ .interpolate(interpolate)
+ .defined(defined)
+ .x(function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) })
+ .y0(function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) })
+ .y1(function(d,i) { return y( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) })
+ //.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this
+ .apply(this, [d.values])
+ });
+
+ var linePaths = groups.selectAll('path.nv-line')
+ .data(function(d) { return [d.values] });
+
+ linePaths.enter().append('path')
+ .attr('class', 'nv-line')
+ .attr('d',
+ d3.svg.line()
+ .interpolate(interpolate)
+ .defined(defined)
+ .x(function(d,i) { return nv.utils.NaNtoZero(x0(getX(d,i))) })
+ .y(function(d,i) { return nv.utils.NaNtoZero(y0(getY(d,i))) })
+ );
+
+ linePaths.watchTransition(renderWatch, 'line: linePaths')
+ .attr('d',
+ d3.svg.line()
+ .interpolate(interpolate)
+ .defined(defined)
+ .x(function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) })
+ .y(function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) })
+ );
+
+ //store old scales for use in transitions on update
+ x0 = x.copy();
+ y0 = y.copy();
+ });
+ renderWatch.renderEnd('line immediate');
+ return chart;
+ }
+
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.scatter = scatter;
+ // Pass through events
+ scatter.dispatch.on('elementClick', function(){ dispatch.elementClick.apply(this, arguments); });
+ scatter.dispatch.on('elementMouseover', function(){ dispatch.elementMouseover.apply(this, arguments); });
+ scatter.dispatch.on('elementMouseout', function(){ dispatch.elementMouseout.apply(this, arguments); });
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ defined: {get: function(){return defined;}, set: function(_){defined=_;}},
+ interpolate: {get: function(){return interpolate;}, set: function(_){interpolate=_;}},
+ clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ scatter.duration(duration);
+ }},
+ isArea: {get: function(){return isArea;}, set: function(_){
+ isArea = d3.functor(_);
+ }},
+ x: {get: function(){return getX;}, set: function(_){
+ getX = _;
+ scatter.x(_);
+ }},
+ y: {get: function(){return getY;}, set: function(_){
+ getY = _;
+ scatter.y(_);
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ scatter.color(color);
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, scatter);
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+nv.models.lineChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var lines = nv.models.line()
+ , xAxis = nv.models.axis()
+ , yAxis = nv.models.axis()
+ , legend = nv.models.legend()
+ , interactiveLayer = nv.interactiveGuideline()
+ , tooltip = nv.models.tooltip()
+ ;
+
+ var margin = {top: 30, right: 20, bottom: 50, left: 60}
+ , color = nv.utils.defaultColor()
+ , width = null
+ , height = null
+ , showLegend = true
+ , showXAxis = true
+ , showYAxis = true
+ , rightAlignYAxis = false
+ , useInteractiveGuideline = false
+ , x
+ , y
+ , state = nv.utils.state()
+ , defaultState = null
+ , noData = null
+ , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState', 'renderEnd')
+ , duration = 250
+ ;
+
+ // set options on sub-objects for this chart
+ xAxis.orient('bottom').tickPadding(7);
+ yAxis.orient(rightAlignYAxis ? 'right' : 'left');
+ tooltip.valueFormatter(function(d, i) {
+ return yAxis.tickFormat()(d, i);
+ }).headerFormatter(function(d, i) {
+ return xAxis.tickFormat()(d, i);
+ });
+
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var renderWatch = nv.utils.renderWatch(dispatch, duration);
+
+ var stateGetter = function(data) {
+ return function(){
+ return {
+ active: data.map(function(d) { return !d.disabled })
+ };
+ }
+ };
+
+ var stateSetter = function(data) {
+ return function(state) {
+ if (state.active !== undefined)
+ data.forEach(function(series,i) {
+ series.disabled = !state.active[i];
+ });
+ }
+ };
+
+ function chart(selection) {
+ renderWatch.reset();
+ renderWatch.models(lines);
+ if (showXAxis) renderWatch.models(xAxis);
+ if (showYAxis) renderWatch.models(yAxis);
+
+ selection.each(function(data) {
+ var container = d3.select(this),
+ that = this;
+ nv.utils.initSVG(container);
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ chart.update = function() {
+ if (duration === 0)
+ container.call(chart);
+ else
+ container.transition().duration(duration).call(chart)
+ };
+ chart.container = this;
+
+ state
+ .setter(stateSetter(data), chart.update)
+ .getter(stateGetter(data))
+ .update();
+
+ // DEPRECATED set state.disableddisabled
+ state.disabled = data.map(function(d) { return !!d.disabled });
+
+ if (!defaultState) {
+ var key;
+ defaultState = {};
+ for (key in state) {
+ if (state[key] instanceof Array)
+ defaultState[key] = state[key].slice(0);
+ else
+ defaultState[key] = state[key];
+ }
+ }
+
+ // Display noData message if there's nothing to show.
+ if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
+ nv.utils.noData(chart, container)
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+
+ // Setup Scales
+ x = lines.xScale();
+ y = lines.yScale();
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-lineChart').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineChart').append('g');
+ var g = wrap.select('g');
+
+ gEnter.append("rect").style("opacity",0);
+ gEnter.append('g').attr('class', 'nv-x nv-axis');
+ gEnter.append('g').attr('class', 'nv-y nv-axis');
+ gEnter.append('g').attr('class', 'nv-linesWrap');
+ gEnter.append('g').attr('class', 'nv-legendWrap');
+ gEnter.append('g').attr('class', 'nv-interactive');
+
+ g.select("rect")
+ .attr("width",availableWidth)
+ .attr("height",(availableHeight > 0) ? availableHeight : 0);
+
+ // Legend
+ if (showLegend) {
+ legend.width(availableWidth);
+
+ g.select('.nv-legendWrap')
+ .datum(data)
+ .call(legend);
+
+ if ( margin.top != legend.height()) {
+ margin.top = legend.height();
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+ }
+
+ wrap.select('.nv-legendWrap')
+ .attr('transform', 'translate(0,' + (-margin.top) +')')
+ }
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ if (rightAlignYAxis) {
+ g.select(".nv-y.nv-axis")
+ .attr("transform", "translate(" + availableWidth + ",0)");
+ }
+
+ //Set up interactive layer
+ if (useInteractiveGuideline) {
+ interactiveLayer
+ .width(availableWidth)
+ .height(availableHeight)
+ .margin({left:margin.left, top:margin.top})
+ .svgContainer(container)
+ .xScale(x);
+ wrap.select(".nv-interactive").call(interactiveLayer);
+ }
+
+ lines
+ .width(availableWidth)
+ .height(availableHeight)
+ .color(data.map(function(d,i) {
+ return d.color || color(d, i);
+ }).filter(function(d,i) { return !data[i].disabled }));
+
+
+ var linesWrap = g.select('.nv-linesWrap')
+ .datum(data.filter(function(d) { return !d.disabled }));
+
+ linesWrap.call(lines);
+
+ // Setup Axes
+ if (showXAxis) {
+ xAxis
+ .scale(x)
+ ._ticks(nv.utils.calcTicksX(availableWidth/100, data) )
+ .tickSize(-availableHeight, 0);
+
+ g.select('.nv-x.nv-axis')
+ .attr('transform', 'translate(0,' + y.range()[0] + ')');
+ g.select('.nv-x.nv-axis')
+ .call(xAxis);
+ }
+
+ if (showYAxis) {
+ yAxis
+ .scale(y)
+ ._ticks(nv.utils.calcTicksY(availableHeight/36, data) )
+ .tickSize( -availableWidth, 0);
+
+ g.select('.nv-y.nv-axis')
+ .call(yAxis);
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (in chart's scope)
+ //------------------------------------------------------------
+
+ legend.dispatch.on('stateChange', function(newState) {
+ for (var key in newState)
+ state[key] = newState[key];
+ dispatch.stateChange(state);
+ chart.update();
+ });
+
+ interactiveLayer.dispatch.on('elementMousemove', function(e) {
+ lines.clearHighlights();
+ var singlePoint, pointIndex, pointXLocation, allData = [];
+ data
+ .filter(function(series, i) {
+ series.seriesIndex = i;
+ return !series.disabled;
+ })
+ .forEach(function(series,i) {
+ pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
+ var point = series.values[pointIndex];
+ var pointYValue = chart.y()(point, pointIndex);
+ if (pointYValue != null) {
+ lines.highlightPoint(i, pointIndex, true);
+ }
+ if (point === undefined) return;
+ if (singlePoint === undefined) singlePoint = point;
+ if (pointXLocation === undefined) pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
+ allData.push({
+ key: series.key,
+ value: pointYValue,
+ color: color(series,series.seriesIndex)
+ });
+ });
+ //Highlight the tooltip entry based on which point the mouse is closest to.
+ if (allData.length > 2) {
+ var yValue = chart.yScale().invert(e.mouseY);
+ var domainExtent = Math.abs(chart.yScale().domain()[0] - chart.yScale().domain()[1]);
+ var threshold = 0.03 * domainExtent;
+ var indexToHighlight = nv.nearestValueIndex(allData.map(function(d){return d.value}),yValue,threshold);
+ if (indexToHighlight !== null)
+ allData[indexToHighlight].highlight = true;
+ }
+
+ var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex));
+ interactiveLayer.tooltip
+ .position({left: e.mouseX + margin.left, top: e.mouseY + margin.top})
+ .chartContainer(that.parentNode)
+ .valueFormatter(function(d,i) {
+ return d == null ? "N/A" : yAxis.tickFormat()(d);
+ })
+ .data({
+ value: xValue,
+ index: pointIndex,
+ series: allData
+ })();
+
+ interactiveLayer.renderGuideLine(pointXLocation);
+
+ });
+
+ interactiveLayer.dispatch.on('elementClick', function(e) {
+ var pointXLocation, allData = [];
+
+ data.filter(function(series, i) {
+ series.seriesIndex = i;
+ return !series.disabled;
+ }).forEach(function(series) {
+ var pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
+ var point = series.values[pointIndex];
+ if (typeof point === 'undefined') return;
+ if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
+ var yPos = chart.yScale()(chart.y()(point,pointIndex));
+ allData.push({
+ point: point,
+ pointIndex: pointIndex,
+ pos: [pointXLocation, yPos],
+ seriesIndex: series.seriesIndex,
+ series: series
+ });
+ });
+
+ lines.dispatch.elementClick(allData);
+ });
+
+ interactiveLayer.dispatch.on("elementMouseout",function(e) {
+ lines.clearHighlights();
+ });
+
+ dispatch.on('changeState', function(e) {
+ if (typeof e.disabled !== 'undefined' && data.length === e.disabled.length) {
+ data.forEach(function(series,i) {
+ series.disabled = e.disabled[i];
+ });
+
+ state.disabled = e.disabled;
+ }
+
+ chart.update();
+ });
+
+ });
+
+ renderWatch.renderEnd('lineChart immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (out of chart's scope)
+ //------------------------------------------------------------
+
+ lines.dispatch.on('elementMouseover.tooltip', function(evt) {
+ tooltip.data(evt).position(evt.pos).hidden(false);
+ });
+
+ lines.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true)
+ });
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ // expose chart's sub-components
+ chart.dispatch = dispatch;
+ chart.lines = lines;
+ chart.legend = legend;
+ chart.xAxis = xAxis;
+ chart.yAxis = yAxis;
+ chart.interactiveLayer = interactiveLayer;
+ chart.tooltip = tooltip;
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
+ showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
+ showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
+ defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+
+ // deprecated options
+ tooltips: {get: function(){return tooltip.enabled();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltips', 'use chart.tooltip.enabled() instead');
+ tooltip.enabled(!!_);
+ }},
+ tooltipContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'use chart.tooltip.contentGenerator() instead');
+ tooltip.contentGenerator(_);
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ lines.duration(duration);
+ xAxis.duration(duration);
+ yAxis.duration(duration);
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ legend.color(color);
+ lines.color(color);
+ }},
+ rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
+ rightAlignYAxis = _;
+ yAxis.orient( rightAlignYAxis ? 'right' : 'left');
+ }},
+ useInteractiveGuideline: {get: function(){return useInteractiveGuideline;}, set: function(_){
+ useInteractiveGuideline = _;
+ if (useInteractiveGuideline) {
+ lines.interactive(false);
+ lines.useVoronoi(false);
+ }
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, lines);
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+nv.models.linePlusBarChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var lines = nv.models.line()
+ , lines2 = nv.models.line()
+ , bars = nv.models.historicalBar()
+ , bars2 = nv.models.historicalBar()
+ , xAxis = nv.models.axis()
+ , x2Axis = nv.models.axis()
+ , y1Axis = nv.models.axis()
+ , y2Axis = nv.models.axis()
+ , y3Axis = nv.models.axis()
+ , y4Axis = nv.models.axis()
+ , legend = nv.models.legend()
+ , brush = d3.svg.brush()
+ , tooltip = nv.models.tooltip()
+ ;
+
+ var margin = {top: 30, right: 30, bottom: 30, left: 60}
+ , margin2 = {top: 0, right: 30, bottom: 20, left: 60}
+ , width = null
+ , height = null
+ , getX = function(d) { return d.x }
+ , getY = function(d) { return d.y }
+ , color = nv.utils.defaultColor()
+ , showLegend = true
+ , focusEnable = true
+ , focusShowAxisY = false
+ , focusShowAxisX = true
+ , focusHeight = 50
+ , extent
+ , brushExtent = null
+ , x
+ , x2
+ , y1
+ , y2
+ , y3
+ , y4
+ , noData = null
+ , dispatch = d3.dispatch('brush', 'stateChange', 'changeState')
+ , transitionDuration = 0
+ , state = nv.utils.state()
+ , defaultState = null
+ , legendLeftAxisHint = ' (left axis)'
+ , legendRightAxisHint = ' (right axis)'
+ ;
+
+ lines.clipEdge(true);
+ lines2.interactive(false);
+ xAxis.orient('bottom').tickPadding(5);
+ y1Axis.orient('left');
+ y2Axis.orient('right');
+ x2Axis.orient('bottom').tickPadding(5);
+ y3Axis.orient('left');
+ y4Axis.orient('right');
+
+ tooltip.headerEnabled(true).headerFormatter(function(d, i) {
+ return xAxis.tickFormat()(d, i);
+ });
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var stateGetter = function(data) {
+ return function(){
+ return {
+ active: data.map(function(d) { return !d.disabled })
+ };
+ }
+ };
+
+ var stateSetter = function(data) {
+ return function(state) {
+ if (state.active !== undefined)
+ data.forEach(function(series,i) {
+ series.disabled = !state.active[i];
+ });
+ }
+ };
+
+ function chart(selection) {
+ selection.each(function(data) {
+ var container = d3.select(this),
+ that = this;
+ nv.utils.initSVG(container);
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight1 = nv.utils.availableHeight(height, container, margin)
+ - (focusEnable ? focusHeight : 0),
+ availableHeight2 = focusHeight - margin2.top - margin2.bottom;
+
+ chart.update = function() { container.transition().duration(transitionDuration).call(chart); };
+ chart.container = this;
+
+ state
+ .setter(stateSetter(data), chart.update)
+ .getter(stateGetter(data))
+ .update();
+
+ // DEPRECATED set state.disableddisabled
+ state.disabled = data.map(function(d) { return !!d.disabled });
+
+ if (!defaultState) {
+ var key;
+ defaultState = {};
+ for (key in state) {
+ if (state[key] instanceof Array)
+ defaultState[key] = state[key].slice(0);
+ else
+ defaultState[key] = state[key];
+ }
+ }
+
+ // Display No Data message if there's nothing to show.
+ if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
+ nv.utils.noData(chart, container)
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ // Setup Scales
+ var dataBars = data.filter(function(d) { return !d.disabled && d.bar });
+ var dataLines = data.filter(function(d) { return !d.bar }); // removed the !d.disabled clause here to fix Issue #240
+
+ x = bars.xScale();
+ x2 = x2Axis.scale();
+ y1 = bars.yScale();
+ y2 = lines.yScale();
+ y3 = bars2.yScale();
+ y4 = lines2.yScale();
+
+ var series1 = data
+ .filter(function(d) { return !d.disabled && d.bar })
+ .map(function(d) {
+ return d.values.map(function(d,i) {
+ return { x: getX(d,i), y: getY(d,i) }
+ })
+ });
+
+ var series2 = data
+ .filter(function(d) { return !d.disabled && !d.bar })
+ .map(function(d) {
+ return d.values.map(function(d,i) {
+ return { x: getX(d,i), y: getY(d,i) }
+ })
+ });
+
+ x.range([0, availableWidth]);
+
+ x2 .domain(d3.extent(d3.merge(series1.concat(series2)), function(d) { return d.x } ))
+ .range([0, availableWidth]);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-linePlusBar').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-linePlusBar').append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-legendWrap');
+
+ // this is the main chart
+ var focusEnter = gEnter.append('g').attr('class', 'nv-focus');
+ focusEnter.append('g').attr('class', 'nv-x nv-axis');
+ focusEnter.append('g').attr('class', 'nv-y1 nv-axis');
+ focusEnter.append('g').attr('class', 'nv-y2 nv-axis');
+ focusEnter.append('g').attr('class', 'nv-barsWrap');
+ focusEnter.append('g').attr('class', 'nv-linesWrap');
+
+ // context chart is where you can focus in
+ var contextEnter = gEnter.append('g').attr('class', 'nv-context');
+ contextEnter.append('g').attr('class', 'nv-x nv-axis');
+ contextEnter.append('g').attr('class', 'nv-y1 nv-axis');
+ contextEnter.append('g').attr('class', 'nv-y2 nv-axis');
+ contextEnter.append('g').attr('class', 'nv-barsWrap');
+ contextEnter.append('g').attr('class', 'nv-linesWrap');
+ contextEnter.append('g').attr('class', 'nv-brushBackground');
+ contextEnter.append('g').attr('class', 'nv-x nv-brush');
+
+ //============================================================
+ // Legend
+ //------------------------------------------------------------
+
+ if (showLegend) {
+ var legendWidth = legend.align() ? availableWidth / 2 : availableWidth;
+ var legendXPosition = legend.align() ? legendWidth : 0;
+
+ legend.width(legendWidth);
+
+ g.select('.nv-legendWrap')
+ .datum(data.map(function(series) {
+ series.originalKey = series.originalKey === undefined ? series.key : series.originalKey;
+ series.key = series.originalKey + (series.bar ? legendLeftAxisHint : legendRightAxisHint);
+ return series;
+ }))
+ .call(legend);
+
+ if ( margin.top != legend.height()) {
+ margin.top = legend.height();
+ // FIXME: shouldn't this be "- (focusEnabled ? focusHeight : 0)"?
+ availableHeight1 = nv.utils.availableHeight(height, container, margin) - focusHeight;
+ }
+
+ g.select('.nv-legendWrap')
+ .attr('transform', 'translate(' + legendXPosition + ',' + (-margin.top) +')');
+ }
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ //============================================================
+ // Context chart (focus chart) components
+ //------------------------------------------------------------
+
+ // hide or show the focus context chart
+ g.select('.nv-context').style('display', focusEnable ? 'initial' : 'none');
+
+ bars2
+ .width(availableWidth)
+ .height(availableHeight2)
+ .color(data.map(function (d, i) {
+ return d.color || color(d, i);
+ }).filter(function (d, i) {
+ return !data[i].disabled && data[i].bar
+ }));
+ lines2
+ .width(availableWidth)
+ .height(availableHeight2)
+ .color(data.map(function (d, i) {
+ return d.color || color(d, i);
+ }).filter(function (d, i) {
+ return !data[i].disabled && !data[i].bar
+ }));
+
+ var bars2Wrap = g.select('.nv-context .nv-barsWrap')
+ .datum(dataBars.length ? dataBars : [
+ {values: []}
+ ]);
+ var lines2Wrap = g.select('.nv-context .nv-linesWrap')
+ .datum(!dataLines[0].disabled ? dataLines : [
+ {values: []}
+ ]);
+
+ g.select('.nv-context')
+ .attr('transform', 'translate(0,' + ( availableHeight1 + margin.bottom + margin2.top) + ')');
+
+ bars2Wrap.transition().call(bars2);
+ lines2Wrap.transition().call(lines2);
+
+ // context (focus chart) axis controls
+ if (focusShowAxisX) {
+ x2Axis
+ ._ticks( nv.utils.calcTicksX(availableWidth / 100, data))
+ .tickSize(-availableHeight2, 0);
+ g.select('.nv-context .nv-x.nv-axis')
+ .attr('transform', 'translate(0,' + y3.range()[0] + ')');
+ g.select('.nv-context .nv-x.nv-axis').transition()
+ .call(x2Axis);
+ }
+
+ if (focusShowAxisY) {
+ y3Axis
+ .scale(y3)
+ ._ticks( availableHeight2 / 36 )
+ .tickSize( -availableWidth, 0);
+ y4Axis
+ .scale(y4)
+ ._ticks( availableHeight2 / 36 )
+ .tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none
+
+ g.select('.nv-context .nv-y3.nv-axis')
+ .style('opacity', dataBars.length ? 1 : 0)
+ .attr('transform', 'translate(0,' + x2.range()[0] + ')');
+ g.select('.nv-context .nv-y2.nv-axis')
+ .style('opacity', dataLines.length ? 1 : 0)
+ .attr('transform', 'translate(' + x2.range()[1] + ',0)');
+
+ g.select('.nv-context .nv-y1.nv-axis').transition()
+ .call(y3Axis);
+ g.select('.nv-context .nv-y2.nv-axis').transition()
+ .call(y4Axis);
+ }
+
+ // Setup Brush
+ brush.x(x2).on('brush', onBrush);
+
+ if (brushExtent) brush.extent(brushExtent);
+
+ var brushBG = g.select('.nv-brushBackground').selectAll('g')
+ .data([brushExtent || brush.extent()]);
+
+ var brushBGenter = brushBG.enter()
+ .append('g');
+
+ brushBGenter.append('rect')
+ .attr('class', 'left')
+ .attr('x', 0)
+ .attr('y', 0)
+ .attr('height', availableHeight2);
+
+ brushBGenter.append('rect')
+ .attr('class', 'right')
+ .attr('x', 0)
+ .attr('y', 0)
+ .attr('height', availableHeight2);
+
+ var gBrush = g.select('.nv-x.nv-brush')
+ .call(brush);
+ gBrush.selectAll('rect')
+ //.attr('y', -5)
+ .attr('height', availableHeight2);
+ gBrush.selectAll('.resize').append('path').attr('d', resizePath);
+
+ //============================================================
+ // Event Handling/Dispatching (in chart's scope)
+ //------------------------------------------------------------
+
+ legend.dispatch.on('stateChange', function(newState) {
+ for (var key in newState)
+ state[key] = newState[key];
+ dispatch.stateChange(state);
+ chart.update();
+ });
+
+ // Update chart from a state object passed to event handler
+ dispatch.on('changeState', function(e) {
+ if (typeof e.disabled !== 'undefined') {
+ data.forEach(function(series,i) {
+ series.disabled = e.disabled[i];
+ });
+ state.disabled = e.disabled;
+ }
+ chart.update();
+ });
+
+ //============================================================
+ // Functions
+ //------------------------------------------------------------
+
+ // Taken from crossfilter (http://square.github.com/crossfilter/)
+ function resizePath(d) {
+ var e = +(d == 'e'),
+ x = e ? 1 : -1,
+ y = availableHeight2 / 3;
+ return 'M' + (.5 * x) + ',' + y
+ + 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6)
+ + 'V' + (2 * y - 6)
+ + 'A6,6 0 0 ' + e + ' ' + (.5 * x) + ',' + (2 * y)
+ + 'Z'
+ + 'M' + (2.5 * x) + ',' + (y + 8)
+ + 'V' + (2 * y - 8)
+ + 'M' + (4.5 * x) + ',' + (y + 8)
+ + 'V' + (2 * y - 8);
+ }
+
+
+ function updateBrushBG() {
+ if (!brush.empty()) brush.extent(brushExtent);
+ brushBG
+ .data([brush.empty() ? x2.domain() : brushExtent])
+ .each(function(d,i) {
+ var leftWidth = x2(d[0]) - x2.range()[0],
+ rightWidth = x2.range()[1] - x2(d[1]);
+ d3.select(this).select('.left')
+ .attr('width', leftWidth < 0 ? 0 : leftWidth);
+
+ d3.select(this).select('.right')
+ .attr('x', x2(d[1]))
+ .attr('width', rightWidth < 0 ? 0 : rightWidth);
+ });
+ }
+
+ function onBrush() {
+ brushExtent = brush.empty() ? null : brush.extent();
+ extent = brush.empty() ? x2.domain() : brush.extent();
+ dispatch.brush({extent: extent, brush: brush});
+ updateBrushBG();
+
+ // Prepare Main (Focus) Bars and Lines
+ bars
+ .width(availableWidth)
+ .height(availableHeight1)
+ .color(data.map(function(d,i) {
+ return d.color || color(d, i);
+ }).filter(function(d,i) { return !data[i].disabled && data[i].bar }));
+
+ lines
+ .width(availableWidth)
+ .height(availableHeight1)
+ .color(data.map(function(d,i) {
+ return d.color || color(d, i);
+ }).filter(function(d,i) { return !data[i].disabled && !data[i].bar }));
+
+ var focusBarsWrap = g.select('.nv-focus .nv-barsWrap')
+ .datum(!dataBars.length ? [{values:[]}] :
+ dataBars
+ .map(function(d,i) {
+ return {
+ key: d.key,
+ values: d.values.filter(function(d,i) {
+ return bars.x()(d,i) >= extent[0] && bars.x()(d,i) <= extent[1];
+ })
+ }
+ })
+ );
+
+ var focusLinesWrap = g.select('.nv-focus .nv-linesWrap')
+ .datum(dataLines[0].disabled ? [{values:[]}] :
+ dataLines
+ .map(function(d,i) {
+ return {
+ area: d.area,
+ fillOpacity: d.fillOpacity,
+ key: d.key,
+ values: d.values.filter(function(d,i) {
+ return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1];
+ })
+ }
+ })
+ );
+
+ // Update Main (Focus) X Axis
+ if (dataBars.length) {
+ x = bars.xScale();
+ } else {
+ x = lines.xScale();
+ }
+
+ xAxis
+ .scale(x)
+ ._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
+ .tickSize(-availableHeight1, 0);
+
+ xAxis.domain([Math.ceil(extent[0]), Math.floor(extent[1])]);
+
+ g.select('.nv-x.nv-axis').transition().duration(transitionDuration)
+ .call(xAxis);
+
+ // Update Main (Focus) Bars and Lines
+ focusBarsWrap.transition().duration(transitionDuration).call(bars);
+ focusLinesWrap.transition().duration(transitionDuration).call(lines);
+
+ // Setup and Update Main (Focus) Y Axes
+ g.select('.nv-focus .nv-x.nv-axis')
+ .attr('transform', 'translate(0,' + y1.range()[0] + ')');
+
+ y1Axis
+ .scale(y1)
+ ._ticks( nv.utils.calcTicksY(availableHeight1/36, data) )
+ .tickSize(-availableWidth, 0);
+ y2Axis
+ .scale(y2)
+ ._ticks( nv.utils.calcTicksY(availableHeight1/36, data) )
+ .tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none
+
+ g.select('.nv-focus .nv-y1.nv-axis')
+ .style('opacity', dataBars.length ? 1 : 0);
+ g.select('.nv-focus .nv-y2.nv-axis')
+ .style('opacity', dataLines.length && !dataLines[0].disabled ? 1 : 0)
+ .attr('transform', 'translate(' + x.range()[1] + ',0)');
+
+ g.select('.nv-focus .nv-y1.nv-axis').transition().duration(transitionDuration)
+ .call(y1Axis);
+ g.select('.nv-focus .nv-y2.nv-axis').transition().duration(transitionDuration)
+ .call(y2Axis);
+ }
+
+ onBrush();
+
+ });
+
+ return chart;
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (out of chart's scope)
+ //------------------------------------------------------------
+
+ lines.dispatch.on('elementMouseover.tooltip', function(evt) {
+ tooltip
+ .duration(100)
+ .valueFormatter(function(d, i) {
+ return y2Axis.tickFormat()(d, i);
+ })
+ .data(evt)
+ .position(evt.pos)
+ .hidden(false);
+ });
+
+ lines.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true)
+ });
+
+ bars.dispatch.on('elementMouseover.tooltip', function(evt) {
+ evt.value = chart.x()(evt.data);
+ evt['series'] = {
+ value: chart.y()(evt.data),
+ color: evt.color
+ };
+ tooltip
+ .duration(0)
+ .valueFormatter(function(d, i) {
+ return y1Axis.tickFormat()(d, i);
+ })
+ .data(evt)
+ .hidden(false);
+ });
+
+ bars.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true);
+ });
+
+ bars.dispatch.on('elementMousemove.tooltip', function(evt) {
+ tooltip.position({top: d3.event.pageY, left: d3.event.pageX})();
+ });
+
+ //============================================================
+
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ // expose chart's sub-components
+ chart.dispatch = dispatch;
+ chart.legend = legend;
+ chart.lines = lines;
+ chart.lines2 = lines2;
+ chart.bars = bars;
+ chart.bars2 = bars2;
+ chart.xAxis = xAxis;
+ chart.x2Axis = x2Axis;
+ chart.y1Axis = y1Axis;
+ chart.y2Axis = y2Axis;
+ chart.y3Axis = y3Axis;
+ chart.y4Axis = y4Axis;
+ chart.tooltip = tooltip;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
+ brushExtent: {get: function(){return brushExtent;}, set: function(_){brushExtent=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+ focusEnable: {get: function(){return focusEnable;}, set: function(_){focusEnable=_;}},
+ focusHeight: {get: function(){return focusHeight;}, set: function(_){focusHeight=_;}},
+ focusShowAxisX: {get: function(){return focusShowAxisX;}, set: function(_){focusShowAxisX=_;}},
+ focusShowAxisY: {get: function(){return focusShowAxisY;}, set: function(_){focusShowAxisY=_;}},
+ legendLeftAxisHint: {get: function(){return legendLeftAxisHint;}, set: function(_){legendLeftAxisHint=_;}},
+ legendRightAxisHint: {get: function(){return legendRightAxisHint;}, set: function(_){legendRightAxisHint=_;}},
+
+ // deprecated options
+ tooltips: {get: function(){return tooltip.enabled();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltips', 'use chart.tooltip.enabled() instead');
+ tooltip.enabled(!!_);
+ }},
+ tooltipContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'use chart.tooltip.contentGenerator() instead');
+ tooltip.contentGenerator(_);
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ duration: {get: function(){return transitionDuration;}, set: function(_){
+ transitionDuration = _;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ legend.color(color);
+ }},
+ x: {get: function(){return getX;}, set: function(_){
+ getX = _;
+ lines.x(_);
+ lines2.x(_);
+ bars.x(_);
+ bars2.x(_);
+ }},
+ y: {get: function(){return getY;}, set: function(_){
+ getY = _;
+ lines.y(_);
+ lines2.y(_);
+ bars.y(_);
+ bars2.y(_);
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, lines);
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+nv.models.lineWithFocusChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var lines = nv.models.line()
+ , lines2 = nv.models.line()
+ , xAxis = nv.models.axis()
+ , yAxis = nv.models.axis()
+ , x2Axis = nv.models.axis()
+ , y2Axis = nv.models.axis()
+ , legend = nv.models.legend()
+ , brush = d3.svg.brush()
+ , tooltip = nv.models.tooltip()
+ , interactiveLayer = nv.interactiveGuideline()
+ ;
+
+ var margin = {top: 30, right: 30, bottom: 30, left: 60}
+ , margin2 = {top: 0, right: 30, bottom: 20, left: 60}
+ , color = nv.utils.defaultColor()
+ , width = null
+ , height = null
+ , height2 = 50
+ , useInteractiveGuideline = false
+ , x
+ , y
+ , x2
+ , y2
+ , showLegend = true
+ , brushExtent = null
+ , noData = null
+ , dispatch = d3.dispatch('brush', 'stateChange', 'changeState')
+ , transitionDuration = 250
+ , state = nv.utils.state()
+ , defaultState = null
+ ;
+
+ lines.clipEdge(true).duration(0);
+ lines2.interactive(false);
+ xAxis.orient('bottom').tickPadding(5);
+ yAxis.orient('left');
+ x2Axis.orient('bottom').tickPadding(5);
+ y2Axis.orient('left');
+
+ tooltip.valueFormatter(function(d, i) {
+ return yAxis.tickFormat()(d, i);
+ }).headerFormatter(function(d, i) {
+ return xAxis.tickFormat()(d, i);
+ });
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var stateGetter = function(data) {
+ return function(){
+ return {
+ active: data.map(function(d) { return !d.disabled })
+ };
+ }
+ };
+
+ var stateSetter = function(data) {
+ return function(state) {
+ if (state.active !== undefined)
+ data.forEach(function(series,i) {
+ series.disabled = !state.active[i];
+ });
+ }
+ };
+
+ function chart(selection) {
+ selection.each(function(data) {
+ var container = d3.select(this),
+ that = this;
+ nv.utils.initSVG(container);
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight1 = nv.utils.availableHeight(height, container, margin) - height2,
+ availableHeight2 = height2 - margin2.top - margin2.bottom;
+
+ chart.update = function() { container.transition().duration(transitionDuration).call(chart) };
+ chart.container = this;
+
+ state
+ .setter(stateSetter(data), chart.update)
+ .getter(stateGetter(data))
+ .update();
+
+ // DEPRECATED set state.disableddisabled
+ state.disabled = data.map(function(d) { return !!d.disabled });
+
+ if (!defaultState) {
+ var key;
+ defaultState = {};
+ for (key in state) {
+ if (state[key] instanceof Array)
+ defaultState[key] = state[key].slice(0);
+ else
+ defaultState[key] = state[key];
+ }
+ }
+
+ // Display No Data message if there's nothing to show.
+ if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
+ nv.utils.noData(chart, container)
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ // Setup Scales
+ x = lines.xScale();
+ y = lines.yScale();
+ x2 = lines2.xScale();
+ y2 = lines2.yScale();
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-lineWithFocusChart').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineWithFocusChart').append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-legendWrap');
+
+ var focusEnter = gEnter.append('g').attr('class', 'nv-focus');
+ focusEnter.append('g').attr('class', 'nv-x nv-axis');
+ focusEnter.append('g').attr('class', 'nv-y nv-axis');
+ focusEnter.append('g').attr('class', 'nv-linesWrap');
+ focusEnter.append('g').attr('class', 'nv-interactive');
+
+ var contextEnter = gEnter.append('g').attr('class', 'nv-context');
+ contextEnter.append('g').attr('class', 'nv-x nv-axis');
+ contextEnter.append('g').attr('class', 'nv-y nv-axis');
+ contextEnter.append('g').attr('class', 'nv-linesWrap');
+ contextEnter.append('g').attr('class', 'nv-brushBackground');
+ contextEnter.append('g').attr('class', 'nv-x nv-brush');
+
+ // Legend
+ if (showLegend) {
+ legend.width(availableWidth);
+
+ g.select('.nv-legendWrap')
+ .datum(data)
+ .call(legend);
+
+ if ( margin.top != legend.height()) {
+ margin.top = legend.height();
+ availableHeight1 = nv.utils.availableHeight(height, container, margin) - height2;
+ }
+
+ g.select('.nv-legendWrap')
+ .attr('transform', 'translate(0,' + (-margin.top) +')')
+ }
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+
+ //Set up interactive layer
+ if (useInteractiveGuideline) {
+ interactiveLayer
+ .width(availableWidth)
+ .height(availableHeight1)
+ .margin({left:margin.left, top:margin.top})
+ .svgContainer(container)
+ .xScale(x);
+ wrap.select(".nv-interactive").call(interactiveLayer);
+ }
+
+ // Main Chart Component(s)
+ lines
+ .width(availableWidth)
+ .height(availableHeight1)
+ .color(
+ data
+ .map(function(d,i) {
+ return d.color || color(d, i);
+ })
+ .filter(function(d,i) {
+ return !data[i].disabled;
+ })
+ );
+
+ lines2
+ .defined(lines.defined())
+ .width(availableWidth)
+ .height(availableHeight2)
+ .color(
+ data
+ .map(function(d,i) {
+ return d.color || color(d, i);
+ })
+ .filter(function(d,i) {
+ return !data[i].disabled;
+ })
+ );
+
+ g.select('.nv-context')
+ .attr('transform', 'translate(0,' + ( availableHeight1 + margin.bottom + margin2.top) + ')')
+
+ var contextLinesWrap = g.select('.nv-context .nv-linesWrap')
+ .datum(data.filter(function(d) { return !d.disabled }))
+
+ d3.transition(contextLinesWrap).call(lines2);
+
+ // Setup Main (Focus) Axes
+ xAxis
+ .scale(x)
+ ._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
+ .tickSize(-availableHeight1, 0);
+
+ yAxis
+ .scale(y)
+ ._ticks( nv.utils.calcTicksY(availableHeight1/36, data) )
+ .tickSize( -availableWidth, 0);
+
+ g.select('.nv-focus .nv-x.nv-axis')
+ .attr('transform', 'translate(0,' + availableHeight1 + ')');
+
+ // Setup Brush
+ brush
+ .x(x2)
+ .on('brush', function() {
+ onBrush();
+ });
+
+ if (brushExtent) brush.extent(brushExtent);
+
+ var brushBG = g.select('.nv-brushBackground').selectAll('g')
+ .data([brushExtent || brush.extent()])
+
+ var brushBGenter = brushBG.enter()
+ .append('g');
+
+ brushBGenter.append('rect')
+ .attr('class', 'left')
+ .attr('x', 0)
+ .attr('y', 0)
+ .attr('height', availableHeight2);
+
+ brushBGenter.append('rect')
+ .attr('class', 'right')
+ .attr('x', 0)
+ .attr('y', 0)
+ .attr('height', availableHeight2);
+
+ var gBrush = g.select('.nv-x.nv-brush')
+ .call(brush);
+ gBrush.selectAll('rect')
+ .attr('height', availableHeight2);
+ gBrush.selectAll('.resize').append('path').attr('d', resizePath);
+
+ onBrush();
+
+ // Setup Secondary (Context) Axes
+ x2Axis
+ .scale(x2)
+ ._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
+ .tickSize(-availableHeight2, 0);
+
+ g.select('.nv-context .nv-x.nv-axis')
+ .attr('transform', 'translate(0,' + y2.range()[0] + ')');
+ d3.transition(g.select('.nv-context .nv-x.nv-axis'))
+ .call(x2Axis);
+
+ y2Axis
+ .scale(y2)
+ ._ticks( nv.utils.calcTicksY(availableHeight2/36, data) )
+ .tickSize( -availableWidth, 0);
+
+ d3.transition(g.select('.nv-context .nv-y.nv-axis'))
+ .call(y2Axis);
+
+ g.select('.nv-context .nv-x.nv-axis')
+ .attr('transform', 'translate(0,' + y2.range()[0] + ')');
+
+ //============================================================
+ // Event Handling/Dispatching (in chart's scope)
+ //------------------------------------------------------------
+
+ legend.dispatch.on('stateChange', function(newState) {
+ for (var key in newState)
+ state[key] = newState[key];
+ dispatch.stateChange(state);
+ chart.update();
+ });
+
+ interactiveLayer.dispatch.on('elementMousemove', function(e) {
+ lines.clearHighlights();
+ var singlePoint, pointIndex, pointXLocation, allData = [];
+ data
+ .filter(function(series, i) {
+ series.seriesIndex = i;
+ return !series.disabled;
+ })
+ .forEach(function(series,i) {
+ var extent = brush.empty() ? x2.domain() : brush.extent();
+ var currentValues = series.values.filter(function(d,i) {
+ return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1];
+ });
+
+ pointIndex = nv.interactiveBisect(currentValues, e.pointXValue, lines.x());
+ var point = currentValues[pointIndex];
+ var pointYValue = chart.y()(point, pointIndex);
+ if (pointYValue != null) {
+ lines.highlightPoint(i, pointIndex, true);
+ }
+ if (point === undefined) return;
+ if (singlePoint === undefined) singlePoint = point;
+ if (pointXLocation === undefined) pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
+ allData.push({
+ key: series.key,
+ value: chart.y()(point, pointIndex),
+ color: color(series,series.seriesIndex)
+ });
+ });
+ //Highlight the tooltip entry based on which point the mouse is closest to.
+ if (allData.length > 2) {
+ var yValue = chart.yScale().invert(e.mouseY);
+ var domainExtent = Math.abs(chart.yScale().domain()[0] - chart.yScale().domain()[1]);
+ var threshold = 0.03 * domainExtent;
+ var indexToHighlight = nv.nearestValueIndex(allData.map(function(d){return d.value}),yValue,threshold);
+ if (indexToHighlight !== null)
+ allData[indexToHighlight].highlight = true;
+ }
+
+ var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex));
+ interactiveLayer.tooltip
+ .position({left: e.mouseX + margin.left, top: e.mouseY + margin.top})
+ .chartContainer(that.parentNode)
+ .valueFormatter(function(d,i) {
+ return d == null ? "N/A" : yAxis.tickFormat()(d);
+ })
+ .data({
+ value: xValue,
+ index: pointIndex,
+ series: allData
+ })();
+
+ interactiveLayer.renderGuideLine(pointXLocation);
+
+ });
+
+ interactiveLayer.dispatch.on("elementMouseout",function(e) {
+ lines.clearHighlights();
+ });
+
+ dispatch.on('changeState', function(e) {
+ if (typeof e.disabled !== 'undefined') {
+ data.forEach(function(series,i) {
+ series.disabled = e.disabled[i];
+ });
+ }
+ chart.update();
+ });
+
+ //============================================================
+ // Functions
+ //------------------------------------------------------------
+
+ // Taken from crossfilter (http://square.github.com/crossfilter/)
+ function resizePath(d) {
+ var e = +(d == 'e'),
+ x = e ? 1 : -1,
+ y = availableHeight2 / 3;
+ return 'M' + (.5 * x) + ',' + y
+ + 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6)
+ + 'V' + (2 * y - 6)
+ + 'A6,6 0 0 ' + e + ' ' + (.5 * x) + ',' + (2 * y)
+ + 'Z'
+ + 'M' + (2.5 * x) + ',' + (y + 8)
+ + 'V' + (2 * y - 8)
+ + 'M' + (4.5 * x) + ',' + (y + 8)
+ + 'V' + (2 * y - 8);
+ }
+
+
+ function updateBrushBG() {
+ if (!brush.empty()) brush.extent(brushExtent);
+ brushBG
+ .data([brush.empty() ? x2.domain() : brushExtent])
+ .each(function(d,i) {
+ var leftWidth = x2(d[0]) - x.range()[0],
+ rightWidth = availableWidth - x2(d[1]);
+ d3.select(this).select('.left')
+ .attr('width', leftWidth < 0 ? 0 : leftWidth);
+
+ d3.select(this).select('.right')
+ .attr('x', x2(d[1]))
+ .attr('width', rightWidth < 0 ? 0 : rightWidth);
+ });
+ }
+
+
+ function onBrush() {
+ brushExtent = brush.empty() ? null : brush.extent();
+ var extent = brush.empty() ? x2.domain() : brush.extent();
+
+ //The brush extent cannot be less than one. If it is, don't update the line chart.
+ if (Math.abs(extent[0] - extent[1]) <= 1) {
+ return;
+ }
+
+ dispatch.brush({extent: extent, brush: brush});
+
+
+ updateBrushBG();
+
+ // Update Main (Focus)
+ var focusLinesWrap = g.select('.nv-focus .nv-linesWrap')
+ .datum(
+ data
+ .filter(function(d) { return !d.disabled })
+ .map(function(d,i) {
+ return {
+ key: d.key,
+ area: d.area,
+ values: d.values.filter(function(d,i) {
+ return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1];
+ })
+ }
+ })
+ );
+ focusLinesWrap.transition().duration(transitionDuration).call(lines);
+
+
+ // Update Main (Focus) Axes
+ g.select('.nv-focus .nv-x.nv-axis').transition().duration(transitionDuration)
+ .call(xAxis);
+ g.select('.nv-focus .nv-y.nv-axis').transition().duration(transitionDuration)
+ .call(yAxis);
+ }
+ });
+
+ return chart;
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (out of chart's scope)
+ //------------------------------------------------------------
+
+ lines.dispatch.on('elementMouseover.tooltip', function(evt) {
+ tooltip.data(evt).position(evt.pos).hidden(false);
+ });
+
+ lines.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true)
+ });
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ // expose chart's sub-components
+ chart.dispatch = dispatch;
+ chart.legend = legend;
+ chart.lines = lines;
+ chart.lines2 = lines2;
+ chart.xAxis = xAxis;
+ chart.yAxis = yAxis;
+ chart.x2Axis = x2Axis;
+ chart.y2Axis = y2Axis;
+ chart.interactiveLayer = interactiveLayer;
+ chart.tooltip = tooltip;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ focusHeight: {get: function(){return height2;}, set: function(_){height2=_;}},
+ showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
+ brushExtent: {get: function(){return brushExtent;}, set: function(_){brushExtent=_;}},
+ defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+
+ // deprecated options
+ tooltips: {get: function(){return tooltip.enabled();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltips', 'use chart.tooltip.enabled() instead');
+ tooltip.enabled(!!_);
+ }},
+ tooltipContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'use chart.tooltip.contentGenerator() instead');
+ tooltip.contentGenerator(_);
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ legend.color(color);
+ // line color is handled above?
+ }},
+ interpolate: {get: function(){return lines.interpolate();}, set: function(_){
+ lines.interpolate(_);
+ lines2.interpolate(_);
+ }},
+ xTickFormat: {get: function(){return xAxis.tickFormat();}, set: function(_){
+ xAxis.tickFormat(_);
+ x2Axis.tickFormat(_);
+ }},
+ yTickFormat: {get: function(){return yAxis.tickFormat();}, set: function(_){
+ yAxis.tickFormat(_);
+ y2Axis.tickFormat(_);
+ }},
+ duration: {get: function(){return transitionDuration;}, set: function(_){
+ transitionDuration=_;
+ yAxis.duration(transitionDuration);
+ y2Axis.duration(transitionDuration);
+ xAxis.duration(transitionDuration);
+ x2Axis.duration(transitionDuration);
+ }},
+ x: {get: function(){return lines.x();}, set: function(_){
+ lines.x(_);
+ lines2.x(_);
+ }},
+ y: {get: function(){return lines.y();}, set: function(_){
+ lines.y(_);
+ lines2.y(_);
+ }},
+ useInteractiveGuideline: {get: function(){return useInteractiveGuideline;}, set: function(_){
+ useInteractiveGuideline = _;
+ if (useInteractiveGuideline) {
+ lines.interactive(false);
+ lines.useVoronoi(false);
+ }
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, lines);
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+nv.models.multiBar = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = 960
+ , height = 500
+ , x = d3.scale.ordinal()
+ , y = d3.scale.linear()
+ , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
+ , container = null
+ , getX = function(d) { return d.x }
+ , getY = function(d) { return d.y }
+ , getYerr = function(d) { return d.yErr }
+ , forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove
+ , clipEdge = true
+ , stacked = false
+ , stackOffset = 'zero' // options include 'silhouette', 'wiggle', 'expand', 'zero', or a custom function
+ , color = nv.utils.defaultColor()
+ , errorBarColor = nv.utils.defaultColor()
+ , hideable = false
+ , barColor = null // adding the ability to set the color for each rather than the whole group
+ , disabled // used in conjunction with barColor to communicate from multiBarHorizontalChart what series are disabled
+ , duration = 500
+ , xDomain
+ , yDomain
+ , xRange
+ , yRange
+ , groupSpacing = 0.1
+ , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove', 'renderEnd')
+ ;
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var x0, y0 //used to store previous scales
+ , renderWatch = nv.utils.renderWatch(dispatch, duration)
+ ;
+
+ var last_datalength = 0;
+
+ function chart(selection) {
+ renderWatch.reset();
+ selection.each(function(data) {
+ var availableWidth = width - margin.left - margin.right,
+ availableHeight = height - margin.top - margin.bottom;
+
+ container = d3.select(this);
+ nv.utils.initSVG(container);
+ var nonStackableCount = 0;
+ // This function defines the requirements for render complete
+ var endFn = function(d, i) {
+ if (d.series === data.length - 1 && i === data[0].values.length - 1)
+ return true;
+ return false;
+ };
+
+ if(hideable && data.length) hideable = [{
+ values: data[0].values.map(function(d) {
+ return {
+ x: d.x,
+ y: 0,
+ series: d.series,
+ size: 0.01
+ };}
+ )}];
+
+ if (stacked) {
+ var parsed = d3.layout.stack()
+ .offset(stackOffset)
+ .values(function(d){ return d.values })
+ .y(getY)
+ (!data.length && hideable ? hideable : data);
+
+ parsed.forEach(function(series, i){
+ // if series is non-stackable, use un-parsed data
+ if (series.nonStackable) {
+ data[i].nonStackableSeries = nonStackableCount++;
+ parsed[i] = data[i];
+ } else {
+ // don't stack this seires on top of the nonStackable seriees
+ if (i > 0 && parsed[i - 1].nonStackable){
+ parsed[i].values.map(function(d,j){
+ d.y0 -= parsed[i - 1].values[j].y;
+ d.y1 = d.y0 + d.y;
+ });
+ }
+ }
+ });
+ data = parsed;
+ }
+ //add series index and key to each data point for reference
+ data.forEach(function(series, i) {
+ series.values.forEach(function(point) {
+ point.series = i;
+ point.key = series.key;
+ });
+ });
+
+ // HACK for negative value stacking
+ if (stacked) {
+ data[0].values.map(function(d,i) {
+ var posBase = 0, negBase = 0;
+ data.map(function(d, idx) {
+ if (!data[idx].nonStackable) {
+ var f = d.values[i]
+ f.size = Math.abs(f.y);
+ if (f.y<0) {
+ f.y1 = negBase;
+ negBase = negBase - f.size;
+ } else
+ {
+ f.y1 = f.size + posBase;
+ posBase = posBase + f.size;
+ }
+ }
+
+ });
+ });
+ }
+ // Setup Scales
+ // remap and flatten the data for use in calculating the scales' domains
+ var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate
+ data.map(function(d, idx) {
+ return d.values.map(function(d,i) {
+ return { x: getX(d,i), y: getY(d,i), y0: d.y0, y1: d.y1, idx:idx, yErr: getYerr(d,i)}
+ })
+ });
+
+ x.domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x }))
+ .rangeBands(xRange || [0, availableWidth], groupSpacing);
+
+ y.domain(yDomain || d3.extent(d3.merge(
+ d3.merge(seriesData).map(function(d) {
+ var domain = d.y;
+ // increase the domain range if this series is stackable
+ if (stacked && !data[d.idx].nonStackable) {
+ if (d.y > 0){
+ domain = d.y1
+ } else {
+ domain = d.y1 + d.y
+ }
+ }
+ var yerr = d.yErr;
+ if (yerr) {
+ if (yerr.length) {
+ return [domain + yerr[0], domain + yerr[1]];
+ } else {
+ yerr = Math.abs(yerr)
+ return [domain - yerr, domain + yerr];
+ }
+ } else {
+ return [domain];
+ }
+ })).concat(forceY)))
+ .range(yRange || [availableHeight, 0]);
+
+ // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
+ if (x.domain()[0] === x.domain()[1])
+ x.domain()[0] ?
+ x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
+ : x.domain([-1,1]);
+
+ if (y.domain()[0] === y.domain()[1])
+ y.domain()[0] ?
+ y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01])
+ : y.domain([-1,1]);
+
+ x0 = x0 || x;
+ y0 = y0 || y;
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-multibar').data([data]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multibar');
+ var defsEnter = wrapEnter.append('defs');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-groups');
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ defsEnter.append('clipPath')
+ .attr('id', 'nv-edge-clip-' + id)
+ .append('rect');
+ wrap.select('#nv-edge-clip-' + id + ' rect')
+ .attr('width', availableWidth)
+ .attr('height', availableHeight);
+
+ g.attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : '');
+
+ var groups = wrap.select('.nv-groups').selectAll('.nv-group')
+ .data(function(d) { return d }, function(d,i) { return i });
+ groups.enter().append('g')
+ .style('stroke-opacity', 1e-6)
+ .style('fill-opacity', 1e-6);
+
+ var exitTransition = renderWatch
+ .transition(groups.exit().selectAll('g.nv-bar'), 'multibarExit', Math.min(100, duration))
+ .attr('y', function(d, i, j) {
+ var yVal = y0(0) || 0;
+ if (stacked) {
+ if (data[d.series] && !data[d.series].nonStackable) {
+ yVal = y0(d.y0);
+ }
+ }
+ return yVal;
+ })
+ .attr('height', 0)
+ .remove();
+ if (exitTransition.delay)
+ exitTransition.delay(function(d,i) {
+ var delay = i * (duration / (last_datalength + 1)) - i;
+ return delay;
+ });
+ groups
+ .attr('class', function(d,i) { return 'nv-group nv-series-' + i })
+ .classed('hover', function(d) { return d.hover })
+ .style('fill', function(d,i){ return color(d, i) })
+ .style('stroke', function(d,i){ return color(d, i) });
+ groups
+ .style('stroke-opacity', 1)
+ .style('fill-opacity', 0.75);
+
+ var bars = groups.selectAll('g.nv-bar')
+ .data(function(d) { return (hideable && !data.length) ? hideable.values : d.values });
+ bars.exit().remove();
+
+ var barsEnter = bars.enter().append('g')
+ .attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'})
+ .attr('transform', function(d,i,j) {
+ var _x = stacked && !data[j].nonStackable ? 0 : (j * x.rangeBand() / data.length );
+ var _y = y0(stacked && !data[j].nonStackable ? d.y0 : 0) || 0;
+ return 'translate(' + _x + ',' + _y + ')';
+ })
+ ;
+
+ barsEnter.append('rect')
+ .attr('height', 0)
+ .attr('width', function(d,i,j) { return x.rangeBand() / (stacked && !data[j].nonStackable ? 1 : data.length) })
+ .style('fill', function(d,i,j){ return color(d, j, i); })
+ .style('stroke', function(d,i,j){ return color(d, j, i); })
+ ;
+ bars
+ .on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here
+ d3.select(this).classed('hover', true);
+ dispatch.elementMouseover({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ })
+ .on('mouseout', function(d,i) {
+ d3.select(this).classed('hover', false);
+ dispatch.elementMouseout({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ })
+ .on('mousemove', function(d,i) {
+ dispatch.elementMousemove({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ })
+ .on('click', function(d,i) {
+ dispatch.elementClick({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ d3.event.stopPropagation();
+ })
+ .on('dblclick', function(d,i) {
+ dispatch.elementDblClick({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ d3.event.stopPropagation();
+ });
+
+ if (getYerr(data[0].values[0], 0)) {
+ barsEnter.append('polyline');
+
+ bars.select('polyline')
+ .attr('fill', 'none')
+ .attr('stroke', function(d, i, j) { return errorBarColor(d, j, i); })
+ .attr('points', function(d,i) {
+ var yerr = getYerr(d,i)
+ , mid = 0.8 * x.rangeBand() / ((stacked ? 1 : data.length) * 2);
+ yerr = yerr.length ? yerr : [-Math.abs(yerr), Math.abs(yerr)];
+ yerr = yerr.map(function(e) { return y(e) - y(0); });
+ var a = [[-mid, yerr[0]], [mid, yerr[0]], [0, yerr[0]], [0, yerr[1]], [-mid, yerr[1]], [mid, yerr[1]]];
+ return a.map(function (path) { return path.join(',') }).join(' ');
+ })
+ .attr('transform', function(d, i) {
+ var xOffset = x.rangeBand() / ((stacked ? 1 : data.length) * 2);
+ var yOffset = getY(d,i) < 0 ? y(getY(d, i)) - y(0) : 0;
+ return 'translate(' + xOffset + ', ' + yOffset + ')';
+ })
+ }
+
+ bars
+ .attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'})
+
+ if (barColor) {
+ if (!disabled) disabled = data.map(function() { return true });
+ bars.select('rect')
+ .style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); })
+ .style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); });
+ }
+
+ var barSelection =
+ bars.watchTransition(renderWatch, 'multibar', Math.min(250, duration))
+ .delay(function(d,i) {
+ return i * duration / data[0].values.length;
+ });
+ if (stacked){
+ barSelection
+ .attr('transform', function(d,i,j) {
+ var yVal = 0;
+ // if stackable, stack it on top of the previous series
+ if (!data[j].nonStackable) {
+ yVal = y(d.y1);
+ } else {
+ if (getY(d,i) < 0){
+ yVal = y(0);
+ } else {
+ if (y(0) - y(getY(d,i)) < -1){
+ yVal = y(0) - 1;
+ } else {
+ yVal = y(getY(d, i)) || 0;
+ }
+ }
+ }
+ var width = 0;
+ if (data[j].nonStackable) {
+ width = d.series * x.rangeBand() / data.length;
+ if (data.length !== nonStackableCount){
+ width = data[j].nonStackableSeries * x.rangeBand()/(nonStackableCount*2);
+ }
+ }
+ var xVal = width + x(getX(d, i));
+ return 'translate(' + xVal + ',' + yVal + ')';
+ })
+ .select('rect')
+ .attr('height', function(d,i,j) {
+ if (!data[j].nonStackable) {
+ return Math.max(Math.abs(y(d.y+d.y0) - y(d.y0)), 1);
+ } else {
+ return Math.max(Math.abs(y(getY(d,i)) - y(0)),1) || 0;
+ }
+ })
+ .attr('width', function(d,i,j){
+ if (!data[j].nonStackable) {
+ return x.rangeBand();
+ } else {
+ // if all series are nonStacable, take the full width
+ var width = (x.rangeBand() / nonStackableCount);
+ // otherwise, nonStackable graph will be only taking the half-width
+ // of the x rangeBand
+ if (data.length !== nonStackableCount) {
+ width = x.rangeBand()/(nonStackableCount*2);
+ }
+ return width;
+ }
+ });
+ }
+ else {
+ barSelection.attr('transform', function(d,i) {
+ var xVal = d.series * x.rangeBand() / data.length + x(getX(d, i));
+ var yVal = getY(d,i) < 0 ?
+ y(0) :
+ y(0) - y(getY(d,i)) < 1 ?
+ y(0) - 1 :
+ y(getY(d,i)) || 0;
+ return 'translate(' + xVal + ',' + yVal + ')';
+ })
+ .select('rect')
+ .attr('width', x.rangeBand() / data.length)
+ .attr('height', function(d,i) {
+ return Math.max(Math.abs(y(getY(d,i)) - y(0)),1) || 0;
+ });
+ }
+
+ //store old scales for use in transitions on update
+ x0 = x.copy();
+ y0 = y.copy();
+
+ // keep track of the last data value length for transition calculations
+ if (data[0] && data[0].values) {
+ last_datalength = data[0].values.length;
+ }
+
+ });
+
+ renderWatch.renderEnd('multibar immediate');
+
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ x: {get: function(){return getX;}, set: function(_){getX=_;}},
+ y: {get: function(){return getY;}, set: function(_){getY=_;}},
+ yErr: {get: function(){return getYerr;}, set: function(_){getYerr=_;}},
+ xScale: {get: function(){return x;}, set: function(_){x=_;}},
+ yScale: {get: function(){return y;}, set: function(_){y=_;}},
+ xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
+ yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
+ xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
+ yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
+ forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
+ stacked: {get: function(){return stacked;}, set: function(_){stacked=_;}},
+ stackOffset: {get: function(){return stackOffset;}, set: function(_){stackOffset=_;}},
+ clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
+ disabled: {get: function(){return disabled;}, set: function(_){disabled=_;}},
+ id: {get: function(){return id;}, set: function(_){id=_;}},
+ hideable: {get: function(){return hideable;}, set: function(_){hideable=_;}},
+ groupSpacing:{get: function(){return groupSpacing;}, set: function(_){groupSpacing=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }},
+ barColor: {get: function(){return barColor;}, set: function(_){
+ barColor = _ ? nv.utils.getColor(_) : null;
+ }},
+ errorBarColor: {get: function(){return errorBarColor;}, set: function(_){
+ errorBarColor = _ ? nv.utils.getColor(_) : null;
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+
+nv.models.multiBarChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var multibar = nv.models.multiBar()
+ , xAxis = nv.models.axis()
+ , yAxis = nv.models.axis()
+ , legend = nv.models.legend()
+ , controls = nv.models.legend()
+ , tooltip = nv.models.tooltip()
+ ;
+
+ var margin = {top: 30, right: 20, bottom: 50, left: 60}
+ , width = null
+ , height = null
+ , color = nv.utils.defaultColor()
+ , showControls = true
+ , controlLabels = {}
+ , showLegend = true
+ , showXAxis = true
+ , showYAxis = true
+ , rightAlignYAxis = false
+ , reduceXTicks = true // if false a tick will show for every data point
+ , staggerLabels = false
+ , rotateLabels = 0
+ , x //can be accessed via chart.xScale()
+ , y //can be accessed via chart.yScale()
+ , state = nv.utils.state()
+ , defaultState = null
+ , noData = null
+ , dispatch = d3.dispatch('stateChange', 'changeState', 'renderEnd')
+ , controlWidth = function() { return showControls ? 180 : 0 }
+ , duration = 250
+ ;
+
+ state.stacked = false // DEPRECATED Maintained for backward compatibility
+
+ multibar.stacked(false);
+ xAxis
+ .orient('bottom')
+ .tickPadding(7)
+ .showMaxMin(false)
+ .tickFormat(function(d) { return d })
+ ;
+ yAxis
+ .orient((rightAlignYAxis) ? 'right' : 'left')
+ .tickFormat(d3.format(',.1f'))
+ ;
+
+ tooltip
+ .duration(0)
+ .valueFormatter(function(d, i) {
+ return yAxis.tickFormat()(d, i);
+ })
+ .headerFormatter(function(d, i) {
+ return xAxis.tickFormat()(d, i);
+ });
+
+ controls.updateState(false);
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var renderWatch = nv.utils.renderWatch(dispatch);
+ var stacked = false;
+
+ var stateGetter = function(data) {
+ return function(){
+ return {
+ active: data.map(function(d) { return !d.disabled }),
+ stacked: stacked
+ };
+ }
+ };
+
+ var stateSetter = function(data) {
+ return function(state) {
+ if (state.stacked !== undefined)
+ stacked = state.stacked;
+ if (state.active !== undefined)
+ data.forEach(function(series,i) {
+ series.disabled = !state.active[i];
+ });
+ }
+ };
+
+ function chart(selection) {
+ renderWatch.reset();
+ renderWatch.models(multibar);
+ if (showXAxis) renderWatch.models(xAxis);
+ if (showYAxis) renderWatch.models(yAxis);
+
+ selection.each(function(data) {
+ var container = d3.select(this),
+ that = this;
+ nv.utils.initSVG(container);
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ chart.update = function() {
+ if (duration === 0)
+ container.call(chart);
+ else
+ container.transition()
+ .duration(duration)
+ .call(chart);
+ };
+ chart.container = this;
+
+ state
+ .setter(stateSetter(data), chart.update)
+ .getter(stateGetter(data))
+ .update();
+
+ // DEPRECATED set state.disableddisabled
+ state.disabled = data.map(function(d) { return !!d.disabled });
+
+ if (!defaultState) {
+ var key;
+ defaultState = {};
+ for (key in state) {
+ if (state[key] instanceof Array)
+ defaultState[key] = state[key].slice(0);
+ else
+ defaultState[key] = state[key];
+ }
+ }
+
+ // Display noData message if there's nothing to show.
+ if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
+ nv.utils.noData(chart, container)
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ // Setup Scales
+ x = multibar.xScale();
+ y = multibar.yScale();
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-multiBarWithLegend').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multiBarWithLegend').append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-x nv-axis');
+ gEnter.append('g').attr('class', 'nv-y nv-axis');
+ gEnter.append('g').attr('class', 'nv-barsWrap');
+ gEnter.append('g').attr('class', 'nv-legendWrap');
+ gEnter.append('g').attr('class', 'nv-controlsWrap');
+
+ // Legend
+ if (showLegend) {
+ legend.width(availableWidth - controlWidth());
+
+ g.select('.nv-legendWrap')
+ .datum(data)
+ .call(legend);
+
+ if ( margin.top != legend.height()) {
+ margin.top = legend.height();
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+ }
+
+ g.select('.nv-legendWrap')
+ .attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')');
+ }
+
+ // Controls
+ if (showControls) {
+ var controlsData = [
+ { key: controlLabels.grouped || 'Grouped', disabled: multibar.stacked() },
+ { key: controlLabels.stacked || 'Stacked', disabled: !multibar.stacked() }
+ ];
+
+ controls.width(controlWidth()).color(['#444', '#444', '#444']);
+ g.select('.nv-controlsWrap')
+ .datum(controlsData)
+ .attr('transform', 'translate(0,' + (-margin.top) +')')
+ .call(controls);
+ }
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+ if (rightAlignYAxis) {
+ g.select(".nv-y.nv-axis")
+ .attr("transform", "translate(" + availableWidth + ",0)");
+ }
+
+ // Main Chart Component(s)
+ multibar
+ .disabled(data.map(function(series) { return series.disabled }))
+ .width(availableWidth)
+ .height(availableHeight)
+ .color(data.map(function(d,i) {
+ return d.color || color(d, i);
+ }).filter(function(d,i) { return !data[i].disabled }));
+
+
+ var barsWrap = g.select('.nv-barsWrap')
+ .datum(data.filter(function(d) { return !d.disabled }));
+
+ barsWrap.call(multibar);
+
+ // Setup Axes
+ if (showXAxis) {
+ xAxis
+ .scale(x)
+ ._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
+ .tickSize(-availableHeight, 0);
+
+ g.select('.nv-x.nv-axis')
+ .attr('transform', 'translate(0,' + y.range()[0] + ')');
+ g.select('.nv-x.nv-axis')
+ .call(xAxis);
+
+ var xTicks = g.select('.nv-x.nv-axis > g').selectAll('g');
+
+ xTicks
+ .selectAll('line, text')
+ .style('opacity', 1)
+
+ if (staggerLabels) {
+ var getTranslate = function(x,y) {
+ return "translate(" + x + "," + y + ")";
+ };
+
+ var staggerUp = 5, staggerDown = 17; //pixels to stagger by
+ // Issue #140
+ xTicks
+ .selectAll("text")
+ .attr('transform', function(d,i,j) {
+ return getTranslate(0, (j % 2 == 0 ? staggerUp : staggerDown));
+ });
+
+ var totalInBetweenTicks = d3.selectAll(".nv-x.nv-axis .nv-wrap g g text")[0].length;
+ g.selectAll(".nv-x.nv-axis .nv-axisMaxMin text")
+ .attr("transform", function(d,i) {
+ return getTranslate(0, (i === 0 || totalInBetweenTicks % 2 !== 0) ? staggerDown : staggerUp);
+ });
+ }
+
+ if (reduceXTicks)
+ xTicks
+ .filter(function(d,i) {
+ return i % Math.ceil(data[0].values.length / (availableWidth / 100)) !== 0;
+ })
+ .selectAll('text, line')
+ .style('opacity', 0);
+
+ if(rotateLabels)
+ xTicks
+ .selectAll('.tick text')
+ .attr('transform', 'rotate(' + rotateLabels + ' 0,0)')
+ .style('text-anchor', rotateLabels > 0 ? 'start' : 'end');
+
+ g.select('.nv-x.nv-axis').selectAll('g.nv-axisMaxMin text')
+ .style('opacity', 1);
+ }
+
+ if (showYAxis) {
+ yAxis
+ .scale(y)
+ ._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
+ .tickSize( -availableWidth, 0);
+
+ g.select('.nv-y.nv-axis')
+ .call(yAxis);
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (in chart's scope)
+ //------------------------------------------------------------
+
+ legend.dispatch.on('stateChange', function(newState) {
+ for (var key in newState)
+ state[key] = newState[key];
+ dispatch.stateChange(state);
+ chart.update();
+ });
+
+ controls.dispatch.on('legendClick', function(d,i) {
+ if (!d.disabled) return;
+ controlsData = controlsData.map(function(s) {
+ s.disabled = true;
+ return s;
+ });
+ d.disabled = false;
+
+ switch (d.key) {
+ case 'Grouped':
+ case controlLabels.grouped:
+ multibar.stacked(false);
+ break;
+ case 'Stacked':
+ case controlLabels.stacked:
+ multibar.stacked(true);
+ break;
+ }
+
+ state.stacked = multibar.stacked();
+ dispatch.stateChange(state);
+ chart.update();
+ });
+
+ // Update chart from a state object passed to event handler
+ dispatch.on('changeState', function(e) {
+ if (typeof e.disabled !== 'undefined') {
+ data.forEach(function(series,i) {
+ series.disabled = e.disabled[i];
+ });
+ state.disabled = e.disabled;
+ }
+ if (typeof e.stacked !== 'undefined') {
+ multibar.stacked(e.stacked);
+ state.stacked = e.stacked;
+ stacked = e.stacked;
+ }
+ chart.update();
+ });
+ });
+
+ renderWatch.renderEnd('multibarchart immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (out of chart's scope)
+ //------------------------------------------------------------
+
+ multibar.dispatch.on('elementMouseover.tooltip', function(evt) {
+ evt.value = chart.x()(evt.data);
+ evt['series'] = {
+ key: evt.data.key,
+ value: chart.y()(evt.data),
+ color: evt.color
+ };
+ tooltip.data(evt).hidden(false);
+ });
+
+ multibar.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true);
+ });
+
+ multibar.dispatch.on('elementMousemove.tooltip', function(evt) {
+ tooltip.position({top: d3.event.pageY, left: d3.event.pageX})();
+ });
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ // expose chart's sub-components
+ chart.dispatch = dispatch;
+ chart.multibar = multibar;
+ chart.legend = legend;
+ chart.controls = controls;
+ chart.xAxis = xAxis;
+ chart.yAxis = yAxis;
+ chart.state = state;
+ chart.tooltip = tooltip;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
+ showControls: {get: function(){return showControls;}, set: function(_){showControls=_;}},
+ controlLabels: {get: function(){return controlLabels;}, set: function(_){controlLabels=_;}},
+ showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
+ showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
+ defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+ reduceXTicks: {get: function(){return reduceXTicks;}, set: function(_){reduceXTicks=_;}},
+ rotateLabels: {get: function(){return rotateLabels;}, set: function(_){rotateLabels=_;}},
+ staggerLabels: {get: function(){return staggerLabels;}, set: function(_){staggerLabels=_;}},
+
+ // deprecated options
+ tooltips: {get: function(){return tooltip.enabled();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltips', 'use chart.tooltip.enabled() instead');
+ tooltip.enabled(!!_);
+ }},
+ tooltipContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'use chart.tooltip.contentGenerator() instead');
+ tooltip.contentGenerator(_);
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ multibar.duration(duration);
+ xAxis.duration(duration);
+ yAxis.duration(duration);
+ renderWatch.reset(duration);
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ legend.color(color);
+ }},
+ rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
+ rightAlignYAxis = _;
+ yAxis.orient( rightAlignYAxis ? 'right' : 'left');
+ }},
+ barColor: {get: function(){return multibar.barColor;}, set: function(_){
+ multibar.barColor(_);
+ legend.color(function(d,i) {return d3.rgb('#ccc').darker(i * 1.5).toString();})
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, multibar);
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+
+nv.models.multiBarHorizontal = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = 960
+ , height = 500
+ , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
+ , container = null
+ , x = d3.scale.ordinal()
+ , y = d3.scale.linear()
+ , getX = function(d) { return d.x }
+ , getY = function(d) { return d.y }
+ , getYerr = function(d) { return d.yErr }
+ , forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove
+ , color = nv.utils.defaultColor()
+ , barColor = null // adding the ability to set the color for each rather than the whole group
+ , errorBarColor = nv.utils.defaultColor()
+ , disabled // used in conjunction with barColor to communicate from multiBarHorizontalChart what series are disabled
+ , stacked = false
+ , showValues = false
+ , showBarLabels = false
+ , valuePadding = 60
+ , groupSpacing = 0.1
+ , valueFormat = d3.format(',.2f')
+ , delay = 1200
+ , xDomain
+ , yDomain
+ , xRange
+ , yRange
+ , duration = 250
+ , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove', 'renderEnd')
+ ;
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var x0, y0; //used to store previous scales
+ var renderWatch = nv.utils.renderWatch(dispatch, duration);
+
+ function chart(selection) {
+ renderWatch.reset();
+ selection.each(function(data) {
+ var availableWidth = width - margin.left - margin.right,
+ availableHeight = height - margin.top - margin.bottom;
+
+ container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ if (stacked)
+ data = d3.layout.stack()
+ .offset('zero')
+ .values(function(d){ return d.values })
+ .y(getY)
+ (data);
+
+ //add series index and key to each data point for reference
+ data.forEach(function(series, i) {
+ series.values.forEach(function(point) {
+ point.series = i;
+ point.key = series.key;
+ });
+ });
+
+ // HACK for negative value stacking
+ if (stacked)
+ data[0].values.map(function(d,i) {
+ var posBase = 0, negBase = 0;
+ data.map(function(d) {
+ var f = d.values[i]
+ f.size = Math.abs(f.y);
+ if (f.y<0) {
+ f.y1 = negBase - f.size;
+ negBase = negBase - f.size;
+ } else
+ {
+ f.y1 = posBase;
+ posBase = posBase + f.size;
+ }
+ });
+ });
+
+ // Setup Scales
+ // remap and flatten the data for use in calculating the scales' domains
+ var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate
+ data.map(function(d) {
+ return d.values.map(function(d,i) {
+ return { x: getX(d,i), y: getY(d,i), y0: d.y0, y1: d.y1, yErr: getYerr(d,i) }
+ })
+ });
+
+ x.domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x }))
+ .rangeBands(xRange || [0, availableHeight], groupSpacing);
+
+ y.domain(yDomain || d3.extent(d3.merge(
+ d3.merge(seriesData).map(function(d) {
+ var domain = d.y;
+ if (stacked) {
+ if (d.y > 0){
+ domain = d.y1 + d.y
+ } else {
+ domain = d.y1
+ }
+ }
+ var yerr = d.yErr;
+ if (yerr) {
+ if (yerr.length) {
+ return [domain + yerr[0], domain + yerr[1]];
+ } else {
+ yerr = Math.abs(yerr)
+ return [domain - yerr, domain + yerr];
+ }
+ } else {
+ return [domain];
+ }
+ })).concat(forceY)))
+
+ if (showValues && !stacked)
+ y.range(yRange || [(y.domain()[0] < 0 ? valuePadding : 0), availableWidth - (y.domain()[1] > 0 ? valuePadding : 0) ]);
+ else
+ y.range(yRange || [0, availableWidth]);
+
+ x0 = x0 || x;
+ y0 = y0 || d3.scale.linear().domain(y.domain()).range([y(0),y(0)]);
+
+ // Setup containers and skeleton of chart
+ var wrap = d3.select(this).selectAll('g.nv-wrap.nv-multibarHorizontal').data([data]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multibarHorizontal');
+ var defsEnter = wrapEnter.append('defs');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-groups');
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ var groups = wrap.select('.nv-groups').selectAll('.nv-group')
+ .data(function(d) { return d }, function(d,i) { return i });
+ groups.enter().append('g')
+ .style('stroke-opacity', 1e-6)
+ .style('fill-opacity', 1e-6);
+ groups.exit().watchTransition(renderWatch, 'multibarhorizontal: exit groups')
+ .style('stroke-opacity', 1e-6)
+ .style('fill-opacity', 1e-6)
+ .remove();
+ groups
+ .attr('class', function(d,i) { return 'nv-group nv-series-' + i })
+ .classed('hover', function(d) { return d.hover })
+ .style('fill', function(d,i){ return color(d, i) })
+ .style('stroke', function(d,i){ return color(d, i) });
+ groups.watchTransition(renderWatch, 'multibarhorizontal: groups')
+ .style('stroke-opacity', 1)
+ .style('fill-opacity', .75);
+
+ var bars = groups.selectAll('g.nv-bar')
+ .data(function(d) { return d.values });
+ bars.exit().remove();
+
+ var barsEnter = bars.enter().append('g')
+ .attr('transform', function(d,i,j) {
+ return 'translate(' + y0(stacked ? d.y0 : 0) + ',' + (stacked ? 0 : (j * x.rangeBand() / data.length ) + x(getX(d,i))) + ')'
+ });
+
+ barsEnter.append('rect')
+ .attr('width', 0)
+ .attr('height', x.rangeBand() / (stacked ? 1 : data.length) )
+
+ bars
+ .on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here
+ d3.select(this).classed('hover', true);
+ dispatch.elementMouseover({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ })
+ .on('mouseout', function(d,i) {
+ d3.select(this).classed('hover', false);
+ dispatch.elementMouseout({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ })
+ .on('mouseout', function(d,i) {
+ dispatch.elementMouseout({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ })
+ .on('mousemove', function(d,i) {
+ dispatch.elementMousemove({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ })
+ .on('click', function(d,i) {
+ dispatch.elementClick({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ d3.event.stopPropagation();
+ })
+ .on('dblclick', function(d,i) {
+ dispatch.elementDblClick({
+ data: d,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ d3.event.stopPropagation();
+ });
+
+ if (getYerr(data[0].values[0], 0)) {
+ barsEnter.append('polyline');
+
+ bars.select('polyline')
+ .attr('fill', 'none')
+ .attr('stroke', function(d,i,j) { return errorBarColor(d, j, i); })
+ .attr('points', function(d,i) {
+ var xerr = getYerr(d,i)
+ , mid = 0.8 * x.rangeBand() / ((stacked ? 1 : data.length) * 2);
+ xerr = xerr.length ? xerr : [-Math.abs(xerr), Math.abs(xerr)];
+ xerr = xerr.map(function(e) { return y(e) - y(0); });
+ var a = [[xerr[0],-mid], [xerr[0],mid], [xerr[0],0], [xerr[1],0], [xerr[1],-mid], [xerr[1],mid]];
+ return a.map(function (path) { return path.join(',') }).join(' ');
+ })
+ .attr('transform', function(d,i) {
+ var mid = x.rangeBand() / ((stacked ? 1 : data.length) * 2);
+ return 'translate(' + (getY(d,i) < 0 ? 0 : y(getY(d,i)) - y(0)) + ', ' + mid + ')'
+ });
+ }
+
+ barsEnter.append('text');
+
+ if (showValues && !stacked) {
+ bars.select('text')
+ .attr('text-anchor', function(d,i) { return getY(d,i) < 0 ? 'end' : 'start' })
+ .attr('y', x.rangeBand() / (data.length * 2))
+ .attr('dy', '.32em')
+ .text(function(d,i) {
+ var t = valueFormat(getY(d,i))
+ , yerr = getYerr(d,i);
+ if (yerr === undefined)
+ return t;
+ if (!yerr.length)
+ return t + '±' + valueFormat(Math.abs(yerr));
+ return t + '+' + valueFormat(Math.abs(yerr[1])) + '-' + valueFormat(Math.abs(yerr[0]));
+ });
+ bars.watchTransition(renderWatch, 'multibarhorizontal: bars')
+ .select('text')
+ .attr('x', function(d,i) { return getY(d,i) < 0 ? -4 : y(getY(d,i)) - y(0) + 4 })
+ } else {
+ bars.selectAll('text').text('');
+ }
+
+ if (showBarLabels && !stacked) {
+ barsEnter.append('text').classed('nv-bar-label',true);
+ bars.select('text.nv-bar-label')
+ .attr('text-anchor', function(d,i) { return getY(d,i) < 0 ? 'start' : 'end' })
+ .attr('y', x.rangeBand() / (data.length * 2))
+ .attr('dy', '.32em')
+ .text(function(d,i) { return getX(d,i) });
+ bars.watchTransition(renderWatch, 'multibarhorizontal: bars')
+ .select('text.nv-bar-label')
+ .attr('x', function(d,i) { return getY(d,i) < 0 ? y(0) - y(getY(d,i)) + 4 : -4 });
+ }
+ else {
+ bars.selectAll('text.nv-bar-label').text('');
+ }
+
+ bars
+ .attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'})
+
+ if (barColor) {
+ if (!disabled) disabled = data.map(function() { return true });
+ bars
+ .style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); })
+ .style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); });
+ }
+
+ if (stacked)
+ bars.watchTransition(renderWatch, 'multibarhorizontal: bars')
+ .attr('transform', function(d,i) {
+ return 'translate(' + y(d.y1) + ',' + x(getX(d,i)) + ')'
+ })
+ .select('rect')
+ .attr('width', function(d,i) {
+ return Math.abs(y(getY(d,i) + d.y0) - y(d.y0))
+ })
+ .attr('height', x.rangeBand() );
+ else
+ bars.watchTransition(renderWatch, 'multibarhorizontal: bars')
+ .attr('transform', function(d,i) {
+ //TODO: stacked must be all positive or all negative, not both?
+ return 'translate(' +
+ (getY(d,i) < 0 ? y(getY(d,i)) : y(0))
+ + ',' +
+ (d.series * x.rangeBand() / data.length
+ +
+ x(getX(d,i)) )
+ + ')'
+ })
+ .select('rect')
+ .attr('height', x.rangeBand() / data.length )
+ .attr('width', function(d,i) {
+ return Math.max(Math.abs(y(getY(d,i)) - y(0)),1)
+ });
+
+ //store old scales for use in transitions on update
+ x0 = x.copy();
+ y0 = y.copy();
+
+ });
+
+ renderWatch.renderEnd('multibarHorizontal immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ x: {get: function(){return getX;}, set: function(_){getX=_;}},
+ y: {get: function(){return getY;}, set: function(_){getY=_;}},
+ yErr: {get: function(){return getYerr;}, set: function(_){getYerr=_;}},
+ xScale: {get: function(){return x;}, set: function(_){x=_;}},
+ yScale: {get: function(){return y;}, set: function(_){y=_;}},
+ xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
+ yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
+ xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
+ yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
+ forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
+ stacked: {get: function(){return stacked;}, set: function(_){stacked=_;}},
+ showValues: {get: function(){return showValues;}, set: function(_){showValues=_;}},
+ // this shows the group name, seems pointless?
+ //showBarLabels: {get: function(){return showBarLabels;}, set: function(_){showBarLabels=_;}},
+ disabled: {get: function(){return disabled;}, set: function(_){disabled=_;}},
+ id: {get: function(){return id;}, set: function(_){id=_;}},
+ valueFormat: {get: function(){return valueFormat;}, set: function(_){valueFormat=_;}},
+ valuePadding: {get: function(){return valuePadding;}, set: function(_){valuePadding=_;}},
+ groupSpacing:{get: function(){return groupSpacing;}, set: function(_){groupSpacing=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }},
+ barColor: {get: function(){return barColor;}, set: function(_){
+ barColor = _ ? nv.utils.getColor(_) : null;
+ }},
+ errorBarColor: {get: function(){return errorBarColor;}, set: function(_){
+ errorBarColor = _ ? nv.utils.getColor(_) : null;
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+
+nv.models.multiBarHorizontalChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var multibar = nv.models.multiBarHorizontal()
+ , xAxis = nv.models.axis()
+ , yAxis = nv.models.axis()
+ , legend = nv.models.legend().height(30)
+ , controls = nv.models.legend().height(30)
+ , tooltip = nv.models.tooltip()
+ ;
+
+ var margin = {top: 30, right: 20, bottom: 50, left: 60}
+ , width = null
+ , height = null
+ , color = nv.utils.defaultColor()
+ , showControls = true
+ , controlLabels = {}
+ , showLegend = true
+ , showXAxis = true
+ , showYAxis = true
+ , stacked = false
+ , x //can be accessed via chart.xScale()
+ , y //can be accessed via chart.yScale()
+ , state = nv.utils.state()
+ , defaultState = null
+ , noData = null
+ , dispatch = d3.dispatch('stateChange', 'changeState','renderEnd')
+ , controlWidth = function() { return showControls ? 180 : 0 }
+ , duration = 250
+ ;
+
+ state.stacked = false; // DEPRECATED Maintained for backward compatibility
+
+ multibar.stacked(stacked);
+
+ xAxis
+ .orient('left')
+ .tickPadding(5)
+ .showMaxMin(false)
+ .tickFormat(function(d) { return d })
+ ;
+ yAxis
+ .orient('bottom')
+ .tickFormat(d3.format(',.1f'))
+ ;
+
+ tooltip
+ .duration(0)
+ .valueFormatter(function(d, i) {
+ return yAxis.tickFormat()(d, i);
+ })
+ .headerFormatter(function(d, i) {
+ return xAxis.tickFormat()(d, i);
+ });
+
+ controls.updateState(false);
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var stateGetter = function(data) {
+ return function(){
+ return {
+ active: data.map(function(d) { return !d.disabled }),
+ stacked: stacked
+ };
+ }
+ };
+
+ var stateSetter = function(data) {
+ return function(state) {
+ if (state.stacked !== undefined)
+ stacked = state.stacked;
+ if (state.active !== undefined)
+ data.forEach(function(series,i) {
+ series.disabled = !state.active[i];
+ });
+ }
+ };
+
+ var renderWatch = nv.utils.renderWatch(dispatch, duration);
+
+ function chart(selection) {
+ renderWatch.reset();
+ renderWatch.models(multibar);
+ if (showXAxis) renderWatch.models(xAxis);
+ if (showYAxis) renderWatch.models(yAxis);
+
+ selection.each(function(data) {
+ var container = d3.select(this),
+ that = this;
+ nv.utils.initSVG(container);
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ chart.update = function() { container.transition().duration(duration).call(chart) };
+ chart.container = this;
+
+ stacked = multibar.stacked();
+
+ state
+ .setter(stateSetter(data), chart.update)
+ .getter(stateGetter(data))
+ .update();
+
+ // DEPRECATED set state.disableddisabled
+ state.disabled = data.map(function(d) { return !!d.disabled });
+
+ if (!defaultState) {
+ var key;
+ defaultState = {};
+ for (key in state) {
+ if (state[key] instanceof Array)
+ defaultState[key] = state[key].slice(0);
+ else
+ defaultState[key] = state[key];
+ }
+ }
+
+ // Display No Data message if there's nothing to show.
+ if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
+ nv.utils.noData(chart, container)
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ // Setup Scales
+ x = multibar.xScale();
+ y = multibar.yScale();
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-multiBarHorizontalChart').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multiBarHorizontalChart').append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-x nv-axis');
+ gEnter.append('g').attr('class', 'nv-y nv-axis')
+ .append('g').attr('class', 'nv-zeroLine')
+ .append('line');
+ gEnter.append('g').attr('class', 'nv-barsWrap');
+ gEnter.append('g').attr('class', 'nv-legendWrap');
+ gEnter.append('g').attr('class', 'nv-controlsWrap');
+
+ // Legend
+ if (showLegend) {
+ legend.width(availableWidth - controlWidth());
+
+ g.select('.nv-legendWrap')
+ .datum(data)
+ .call(legend);
+
+ if ( margin.top != legend.height()) {
+ margin.top = legend.height();
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+ }
+
+ g.select('.nv-legendWrap')
+ .attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')');
+ }
+
+ // Controls
+ if (showControls) {
+ var controlsData = [
+ { key: controlLabels.grouped || 'Grouped', disabled: multibar.stacked() },
+ { key: controlLabels.stacked || 'Stacked', disabled: !multibar.stacked() }
+ ];
+
+ controls.width(controlWidth()).color(['#444', '#444', '#444']);
+ g.select('.nv-controlsWrap')
+ .datum(controlsData)
+ .attr('transform', 'translate(0,' + (-margin.top) +')')
+ .call(controls);
+ }
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ // Main Chart Component(s)
+ multibar
+ .disabled(data.map(function(series) { return series.disabled }))
+ .width(availableWidth)
+ .height(availableHeight)
+ .color(data.map(function(d,i) {
+ return d.color || color(d, i);
+ }).filter(function(d,i) { return !data[i].disabled }));
+
+ var barsWrap = g.select('.nv-barsWrap')
+ .datum(data.filter(function(d) { return !d.disabled }));
+
+ barsWrap.transition().call(multibar);
+
+ // Setup Axes
+ if (showXAxis) {
+ xAxis
+ .scale(x)
+ ._ticks( nv.utils.calcTicksY(availableHeight/24, data) )
+ .tickSize(-availableWidth, 0);
+
+ g.select('.nv-x.nv-axis').call(xAxis);
+
+ var xTicks = g.select('.nv-x.nv-axis').selectAll('g');
+
+ xTicks
+ .selectAll('line, text');
+ }
+
+ if (showYAxis) {
+ yAxis
+ .scale(y)
+ ._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
+ .tickSize( -availableHeight, 0);
+
+ g.select('.nv-y.nv-axis')
+ .attr('transform', 'translate(0,' + availableHeight + ')');
+ g.select('.nv-y.nv-axis').call(yAxis);
+ }
+
+ // Zero line
+ g.select(".nv-zeroLine line")
+ .attr("x1", y(0))
+ .attr("x2", y(0))
+ .attr("y1", 0)
+ .attr("y2", -availableHeight)
+ ;
+
+ //============================================================
+ // Event Handling/Dispatching (in chart's scope)
+ //------------------------------------------------------------
+
+ legend.dispatch.on('stateChange', function(newState) {
+ for (var key in newState)
+ state[key] = newState[key];
+ dispatch.stateChange(state);
+ chart.update();
+ });
+
+ controls.dispatch.on('legendClick', function(d,i) {
+ if (!d.disabled) return;
+ controlsData = controlsData.map(function(s) {
+ s.disabled = true;
+ return s;
+ });
+ d.disabled = false;
+
+ switch (d.key) {
+ case 'Grouped':
+ multibar.stacked(false);
+ break;
+ case 'Stacked':
+ multibar.stacked(true);
+ break;
+ }
+
+ state.stacked = multibar.stacked();
+ dispatch.stateChange(state);
+ stacked = multibar.stacked();
+
+ chart.update();
+ });
+
+ // Update chart from a state object passed to event handler
+ dispatch.on('changeState', function(e) {
+
+ if (typeof e.disabled !== 'undefined') {
+ data.forEach(function(series,i) {
+ series.disabled = e.disabled[i];
+ });
+
+ state.disabled = e.disabled;
+ }
+
+ if (typeof e.stacked !== 'undefined') {
+ multibar.stacked(e.stacked);
+ state.stacked = e.stacked;
+ stacked = e.stacked;
+ }
+
+ chart.update();
+ });
+ });
+ renderWatch.renderEnd('multibar horizontal chart immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (out of chart's scope)
+ //------------------------------------------------------------
+
+ multibar.dispatch.on('elementMouseover.tooltip', function(evt) {
+ evt.value = chart.x()(evt.data);
+ evt['series'] = {
+ key: evt.data.key,
+ value: chart.y()(evt.data),
+ color: evt.color
+ };
+ tooltip.data(evt).hidden(false);
+ });
+
+ multibar.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true);
+ });
+
+ multibar.dispatch.on('elementMousemove.tooltip', function(evt) {
+ tooltip.position({top: d3.event.pageY, left: d3.event.pageX})();
+ });
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ // expose chart's sub-components
+ chart.dispatch = dispatch;
+ chart.multibar = multibar;
+ chart.legend = legend;
+ chart.controls = controls;
+ chart.xAxis = xAxis;
+ chart.yAxis = yAxis;
+ chart.state = state;
+ chart.tooltip = tooltip;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
+ showControls: {get: function(){return showControls;}, set: function(_){showControls=_;}},
+ controlLabels: {get: function(){return controlLabels;}, set: function(_){controlLabels=_;}},
+ showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
+ showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
+ defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+
+ // deprecated options
+ tooltips: {get: function(){return tooltip.enabled();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltips', 'use chart.tooltip.enabled() instead');
+ tooltip.enabled(!!_);
+ }},
+ tooltipContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'use chart.tooltip.contentGenerator() instead');
+ tooltip.contentGenerator(_);
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ multibar.duration(duration);
+ xAxis.duration(duration);
+ yAxis.duration(duration);
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ legend.color(color);
+ }},
+ barColor: {get: function(){return multibar.barColor;}, set: function(_){
+ multibar.barColor(_);
+ legend.color(function(d,i) {return d3.rgb('#ccc').darker(i * 1.5).toString();})
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, multibar);
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+nv.models.multiChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 30, right: 20, bottom: 50, left: 60},
+ color = nv.utils.defaultColor(),
+ width = null,
+ height = null,
+ showLegend = true,
+ noData = null,
+ yDomain1,
+ yDomain2,
+ getX = function(d) { return d.x },
+ getY = function(d) { return d.y},
+ interpolate = 'monotone',
+ useVoronoi = true
+ ;
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var x = d3.scale.linear(),
+ yScale1 = d3.scale.linear(),
+ yScale2 = d3.scale.linear(),
+
+ lines1 = nv.models.line().yScale(yScale1),
+ lines2 = nv.models.line().yScale(yScale2),
+
+ bars1 = nv.models.multiBar().stacked(false).yScale(yScale1),
+ bars2 = nv.models.multiBar().stacked(false).yScale(yScale2),
+
+ stack1 = nv.models.stackedArea().yScale(yScale1),
+ stack2 = nv.models.stackedArea().yScale(yScale2),
+
+ xAxis = nv.models.axis().scale(x).orient('bottom').tickPadding(5),
+ yAxis1 = nv.models.axis().scale(yScale1).orient('left'),
+ yAxis2 = nv.models.axis().scale(yScale2).orient('right'),
+
+ legend = nv.models.legend().height(30),
+ tooltip = nv.models.tooltip(),
+ dispatch = d3.dispatch();
+
+ function chart(selection) {
+ selection.each(function(data) {
+ var container = d3.select(this),
+ that = this;
+ nv.utils.initSVG(container);
+
+ chart.update = function() { container.transition().call(chart); };
+ chart.container = this;
+
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ var dataLines1 = data.filter(function(d) {return d.type == 'line' && d.yAxis == 1});
+ var dataLines2 = data.filter(function(d) {return d.type == 'line' && d.yAxis == 2});
+ var dataBars1 = data.filter(function(d) {return d.type == 'bar' && d.yAxis == 1});
+ var dataBars2 = data.filter(function(d) {return d.type == 'bar' && d.yAxis == 2});
+ var dataStack1 = data.filter(function(d) {return d.type == 'area' && d.yAxis == 1});
+ var dataStack2 = data.filter(function(d) {return d.type == 'area' && d.yAxis == 2});
+
+ // Display noData message if there's nothing to show.
+ if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
+ nv.utils.noData(chart, container);
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ var series1 = data.filter(function(d) {return !d.disabled && d.yAxis == 1})
+ .map(function(d) {
+ return d.values.map(function(d,i) {
+ return { x: d.x, y: d.y }
+ })
+ });
+
+ var series2 = data.filter(function(d) {return !d.disabled && d.yAxis == 2})
+ .map(function(d) {
+ return d.values.map(function(d,i) {
+ return { x: d.x, y: d.y }
+ })
+ });
+
+ x .domain(d3.extent(d3.merge(series1.concat(series2)), function(d) { return d.x } ))
+ .range([0, availableWidth]);
+
+ var wrap = container.selectAll('g.wrap.multiChart').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'wrap nvd3 multiChart').append('g');
+
+ gEnter.append('g').attr('class', 'nv-x nv-axis');
+ gEnter.append('g').attr('class', 'nv-y1 nv-axis');
+ gEnter.append('g').attr('class', 'nv-y2 nv-axis');
+ gEnter.append('g').attr('class', 'lines1Wrap');
+ gEnter.append('g').attr('class', 'lines2Wrap');
+ gEnter.append('g').attr('class', 'bars1Wrap');
+ gEnter.append('g').attr('class', 'bars2Wrap');
+ gEnter.append('g').attr('class', 'stack1Wrap');
+ gEnter.append('g').attr('class', 'stack2Wrap');
+ gEnter.append('g').attr('class', 'legendWrap');
+
+ var g = wrap.select('g');
+
+ var color_array = data.map(function(d,i) {
+ return data[i].color || color(d, i);
+ });
+
+ if (showLegend) {
+ var legendWidth = legend.align() ? availableWidth / 2 : availableWidth;
+ var legendXPosition = legend.align() ? legendWidth : 0;
+
+ legend.width(legendWidth);
+ legend.color(color_array);
+
+ g.select('.legendWrap')
+ .datum(data.map(function(series) {
+ series.originalKey = series.originalKey === undefined ? series.key : series.originalKey;
+ series.key = series.originalKey + (series.yAxis == 1 ? '' : ' (right axis)');
+ return series;
+ }))
+ .call(legend);
+
+ if ( margin.top != legend.height()) {
+ margin.top = legend.height();
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+ }
+
+ g.select('.legendWrap')
+ .attr('transform', 'translate(' + legendXPosition + ',' + (-margin.top) +')');
+ }
+
+ lines1
+ .width(availableWidth)
+ .height(availableHeight)
+ .interpolate(interpolate)
+ .color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'line'}));
+ lines2
+ .width(availableWidth)
+ .height(availableHeight)
+ .interpolate(interpolate)
+ .color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'line'}));
+ bars1
+ .width(availableWidth)
+ .height(availableHeight)
+ .color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'bar'}));
+ bars2
+ .width(availableWidth)
+ .height(availableHeight)
+ .color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'bar'}));
+ stack1
+ .width(availableWidth)
+ .height(availableHeight)
+ .color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'area'}));
+ stack2
+ .width(availableWidth)
+ .height(availableHeight)
+ .color(color_array.filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'area'}));
+
+ g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ var lines1Wrap = g.select('.lines1Wrap')
+ .datum(dataLines1.filter(function(d){return !d.disabled}));
+ var bars1Wrap = g.select('.bars1Wrap')
+ .datum(dataBars1.filter(function(d){return !d.disabled}));
+ var stack1Wrap = g.select('.stack1Wrap')
+ .datum(dataStack1.filter(function(d){return !d.disabled}));
+ var lines2Wrap = g.select('.lines2Wrap')
+ .datum(dataLines2.filter(function(d){return !d.disabled}));
+ var bars2Wrap = g.select('.bars2Wrap')
+ .datum(dataBars2.filter(function(d){return !d.disabled}));
+ var stack2Wrap = g.select('.stack2Wrap')
+ .datum(dataStack2.filter(function(d){return !d.disabled}));
+
+ var extraValue1 = dataStack1.length ? dataStack1.map(function(a){return a.values}).reduce(function(a,b){
+ return a.map(function(aVal,i){return {x: aVal.x, y: aVal.y + b[i].y}})
+ }).concat([{x:0, y:0}]) : [];
+ var extraValue2 = dataStack2.length ? dataStack2.map(function(a){return a.values}).reduce(function(a,b){
+ return a.map(function(aVal,i){return {x: aVal.x, y: aVal.y + b[i].y}})
+ }).concat([{x:0, y:0}]) : [];
+
+ yScale1 .domain(yDomain1 || d3.extent(d3.merge(series1).concat(extraValue1), function(d) { return d.y } ))
+ .range([0, availableHeight]);
+
+ yScale2 .domain(yDomain2 || d3.extent(d3.merge(series2).concat(extraValue2), function(d) { return d.y } ))
+ .range([0, availableHeight]);
+
+ lines1.yDomain(yScale1.domain());
+ bars1.yDomain(yScale1.domain());
+ stack1.yDomain(yScale1.domain());
+
+ lines2.yDomain(yScale2.domain());
+ bars2.yDomain(yScale2.domain());
+ stack2.yDomain(yScale2.domain());
+
+ if(dataStack1.length){d3.transition(stack1Wrap).call(stack1);}
+ if(dataStack2.length){d3.transition(stack2Wrap).call(stack2);}
+
+ if(dataBars1.length){d3.transition(bars1Wrap).call(bars1);}
+ if(dataBars2.length){d3.transition(bars2Wrap).call(bars2);}
+
+ if(dataLines1.length){d3.transition(lines1Wrap).call(lines1);}
+ if(dataLines2.length){d3.transition(lines2Wrap).call(lines2);}
+
+ xAxis
+ ._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
+ .tickSize(-availableHeight, 0);
+
+ g.select('.nv-x.nv-axis')
+ .attr('transform', 'translate(0,' + availableHeight + ')');
+ d3.transition(g.select('.nv-x.nv-axis'))
+ .call(xAxis);
+
+ yAxis1
+ ._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
+ .tickSize( -availableWidth, 0);
+
+
+ d3.transition(g.select('.nv-y1.nv-axis'))
+ .call(yAxis1);
+
+ yAxis2
+ ._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
+ .tickSize( -availableWidth, 0);
+
+ d3.transition(g.select('.nv-y2.nv-axis'))
+ .call(yAxis2);
+
+ g.select('.nv-y1.nv-axis')
+ .classed('nv-disabled', series1.length ? false : true)
+ .attr('transform', 'translate(' + x.range()[0] + ',0)');
+
+ g.select('.nv-y2.nv-axis')
+ .classed('nv-disabled', series2.length ? false : true)
+ .attr('transform', 'translate(' + x.range()[1] + ',0)');
+
+ legend.dispatch.on('stateChange', function(newState) {
+ chart.update();
+ });
+
+ //============================================================
+ // Event Handling/Dispatching
+ //------------------------------------------------------------
+
+ function mouseover_line(evt) {
+ var yaxis = data[evt.seriesIndex].yAxis === 2 ? yAxis2 : yAxis1;
+ evt.value = evt.point.x;
+ evt.series = {
+ value: evt.point.y,
+ color: evt.point.color
+ };
+ tooltip
+ .duration(100)
+ .valueFormatter(function(d, i) {
+ return yaxis.tickFormat()(d, i);
+ })
+ .data(evt)
+ .position(evt.pos)
+ .hidden(false);
+ }
+
+ function mouseover_stack(evt) {
+ var yaxis = data[evt.seriesIndex].yAxis === 2 ? yAxis2 : yAxis1;
+ evt.point['x'] = stack1.x()(evt.point);
+ evt.point['y'] = stack1.y()(evt.point);
+ tooltip
+ .duration(100)
+ .valueFormatter(function(d, i) {
+ return yaxis.tickFormat()(d, i);
+ })
+ .data(evt)
+ .position(evt.pos)
+ .hidden(false);
+ }
+
+ function mouseover_bar(evt) {
+ var yaxis = data[evt.data.series].yAxis === 2 ? yAxis2 : yAxis1;
+
+ evt.value = bars1.x()(evt.data);
+ evt['series'] = {
+ value: bars1.y()(evt.data),
+ color: evt.color
+ };
+ tooltip
+ .duration(0)
+ .valueFormatter(function(d, i) {
+ return yaxis.tickFormat()(d, i);
+ })
+ .data(evt)
+ .hidden(false);
+ }
+
+ lines1.dispatch.on('elementMouseover.tooltip', mouseover_line);
+ lines2.dispatch.on('elementMouseover.tooltip', mouseover_line);
+ lines1.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true)
+ });
+ lines2.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true)
+ });
+
+ stack1.dispatch.on('elementMouseover.tooltip', mouseover_stack);
+ stack2.dispatch.on('elementMouseover.tooltip', mouseover_stack);
+ stack1.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true)
+ });
+ stack2.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true)
+ });
+
+ bars1.dispatch.on('elementMouseover.tooltip', mouseover_bar);
+ bars2.dispatch.on('elementMouseover.tooltip', mouseover_bar);
+
+ bars1.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true);
+ });
+ bars2.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true);
+ });
+ bars1.dispatch.on('elementMousemove.tooltip', function(evt) {
+ tooltip.position({top: d3.event.pageY, left: d3.event.pageX})();
+ });
+ bars2.dispatch.on('elementMousemove.tooltip', function(evt) {
+ tooltip.position({top: d3.event.pageY, left: d3.event.pageX})();
+ });
+
+ });
+
+ return chart;
+ }
+
+ //============================================================
+ // Global getters and setters
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.lines1 = lines1;
+ chart.lines2 = lines2;
+ chart.bars1 = bars1;
+ chart.bars2 = bars2;
+ chart.stack1 = stack1;
+ chart.stack2 = stack2;
+ chart.xAxis = xAxis;
+ chart.yAxis1 = yAxis1;
+ chart.yAxis2 = yAxis2;
+ chart.tooltip = tooltip;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
+ yDomain1: {get: function(){return yDomain1;}, set: function(_){yDomain1=_;}},
+ yDomain2: {get: function(){return yDomain2;}, set: function(_){yDomain2=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+ interpolate: {get: function(){return interpolate;}, set: function(_){interpolate=_;}},
+
+ // deprecated options
+ tooltips: {get: function(){return tooltip.enabled();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltips', 'use chart.tooltip.enabled() instead');
+ tooltip.enabled(!!_);
+ }},
+ tooltipContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'use chart.tooltip.contentGenerator() instead');
+ tooltip.contentGenerator(_);
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }},
+ x: {get: function(){return getX;}, set: function(_){
+ getX = _;
+ lines1.x(_);
+ lines2.x(_);
+ bars1.x(_);
+ bars2.x(_);
+ stack1.x(_);
+ stack2.x(_);
+ }},
+ y: {get: function(){return getY;}, set: function(_){
+ getY = _;
+ lines1.y(_);
+ lines2.y(_);
+ stack1.y(_);
+ stack2.y(_);
+ bars1.y(_);
+ bars2.y(_);
+ }},
+ useVoronoi: {get: function(){return useVoronoi;}, set: function(_){
+ useVoronoi=_;
+ lines1.useVoronoi(_);
+ lines2.useVoronoi(_);
+ stack1.useVoronoi(_);
+ stack2.useVoronoi(_);
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+
+
+nv.models.ohlcBar = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = null
+ , height = null
+ , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
+ , container = null
+ , x = d3.scale.linear()
+ , y = d3.scale.linear()
+ , getX = function(d) { return d.x }
+ , getY = function(d) { return d.y }
+ , getOpen = function(d) { return d.open }
+ , getClose = function(d) { return d.close }
+ , getHigh = function(d) { return d.high }
+ , getLow = function(d) { return d.low }
+ , forceX = []
+ , forceY = []
+ , padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart
+ , clipEdge = true
+ , color = nv.utils.defaultColor()
+ , interactive = false
+ , xDomain
+ , yDomain
+ , xRange
+ , yRange
+ , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState', 'renderEnd', 'chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove')
+ ;
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ function chart(selection) {
+ selection.each(function(data) {
+ container = d3.select(this);
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ nv.utils.initSVG(container);
+
+ // ohlc bar width.
+ var w = (availableWidth / data[0].values.length) * .9;
+
+ // Setup Scales
+ x.domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) ));
+
+ if (padData)
+ x.range(xRange || [availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]);
+ else
+ x.range(xRange || [5 + w/2, availableWidth - w/2 - 5]);
+
+ y.domain(yDomain || [
+ d3.min(data[0].values.map(getLow).concat(forceY)),
+ d3.max(data[0].values.map(getHigh).concat(forceY))
+ ]
+ ).range(yRange || [availableHeight, 0]);
+
+ // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
+ if (x.domain()[0] === x.domain()[1])
+ x.domain()[0] ?
+ x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
+ : x.domain([-1,1]);
+
+ if (y.domain()[0] === y.domain()[1])
+ y.domain()[0] ?
+ y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01])
+ : y.domain([-1,1]);
+
+ // Setup containers and skeleton of chart
+ var wrap = d3.select(this).selectAll('g.nv-wrap.nv-ohlcBar').data([data[0].values]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-ohlcBar');
+ var defsEnter = wrapEnter.append('defs');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-ticks');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ container
+ .on('click', function(d,i) {
+ dispatch.chartClick({
+ data: d,
+ index: i,
+ pos: d3.event,
+ id: id
+ });
+ });
+
+ defsEnter.append('clipPath')
+ .attr('id', 'nv-chart-clip-path-' + id)
+ .append('rect');
+
+ wrap.select('#nv-chart-clip-path-' + id + ' rect')
+ .attr('width', availableWidth)
+ .attr('height', availableHeight);
+
+ g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : '');
+
+ var ticks = wrap.select('.nv-ticks').selectAll('.nv-tick')
+ .data(function(d) { return d });
+ ticks.exit().remove();
+
+ ticks.enter().append('path')
+ .attr('class', function(d,i,j) { return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i })
+ .attr('d', function(d,i) {
+ return 'm0,0l0,'
+ + (y(getOpen(d,i))
+ - y(getHigh(d,i)))
+ + 'l'
+ + (-w/2)
+ + ',0l'
+ + (w/2)
+ + ',0l0,'
+ + (y(getLow(d,i)) - y(getOpen(d,i)))
+ + 'l0,'
+ + (y(getClose(d,i))
+ - y(getLow(d,i)))
+ + 'l'
+ + (w/2)
+ + ',0l'
+ + (-w/2)
+ + ',0z';
+ })
+ .attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; })
+ .attr('fill', function(d,i) { return color[0]; })
+ .attr('stroke', function(d,i) { return color[0]; })
+ .attr('x', 0 )
+ .attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) })
+ .attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) });
+
+ // the bar colors are controlled by CSS currently
+ ticks.attr('class', function(d,i,j) {
+ return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i;
+ });
+
+ d3.transition(ticks)
+ .attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; })
+ .attr('d', function(d,i) {
+ var w = (availableWidth / data[0].values.length) * .9;
+ return 'm0,0l0,'
+ + (y(getOpen(d,i))
+ - y(getHigh(d,i)))
+ + 'l'
+ + (-w/2)
+ + ',0l'
+ + (w/2)
+ + ',0l0,'
+ + (y(getLow(d,i))
+ - y(getOpen(d,i)))
+ + 'l0,'
+ + (y(getClose(d,i))
+ - y(getLow(d,i)))
+ + 'l'
+ + (w/2)
+ + ',0l'
+ + (-w/2)
+ + ',0z';
+ });
+ });
+
+ return chart;
+ }
+
+
+ //Create methods to allow outside functions to highlight a specific bar.
+ chart.highlightPoint = function(pointIndex, isHoverOver) {
+ chart.clearHighlights();
+ container.select(".nv-ohlcBar .nv-tick-0-" + pointIndex)
+ .classed("hover", isHoverOver)
+ ;
+ };
+
+ chart.clearHighlights = function() {
+ container.select(".nv-ohlcBar .nv-tick.hover")
+ .classed("hover", false)
+ ;
+ };
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ xScale: {get: function(){return x;}, set: function(_){x=_;}},
+ yScale: {get: function(){return y;}, set: function(_){y=_;}},
+ xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
+ yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
+ xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
+ yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
+ forceX: {get: function(){return forceX;}, set: function(_){forceX=_;}},
+ forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
+ padData: {get: function(){return padData;}, set: function(_){padData=_;}},
+ clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
+ id: {get: function(){return id;}, set: function(_){id=_;}},
+ interactive: {get: function(){return interactive;}, set: function(_){interactive=_;}},
+
+ x: {get: function(){return getX;}, set: function(_){getX=_;}},
+ y: {get: function(){return getY;}, set: function(_){getY=_;}},
+ open: {get: function(){return getOpen();}, set: function(_){getOpen=_;}},
+ close: {get: function(){return getClose();}, set: function(_){getClose=_;}},
+ high: {get: function(){return getHigh;}, set: function(_){getHigh=_;}},
+ low: {get: function(){return getLow;}, set: function(_){getLow=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top != undefined ? _.top : margin.top;
+ margin.right = _.right != undefined ? _.right : margin.right;
+ margin.bottom = _.bottom != undefined ? _.bottom : margin.bottom;
+ margin.left = _.left != undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+ return chart;
+};
+// Code adapted from Jason Davies' "Parallel Coordinates"
+// http://bl.ocks.org/jasondavies/1341281
+nv.models.parallelCoordinates = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 30, right: 0, bottom: 10, left: 0}
+ , width = null
+ , height = null
+ , x = d3.scale.ordinal()
+ , y = {}
+ , dimensionNames = []
+ , dimensionFormats = []
+ , color = nv.utils.defaultColor()
+ , filters = []
+ , active = []
+ , dragging = []
+ , lineTension = 1
+ , dispatch = d3.dispatch('brush', 'elementMouseover', 'elementMouseout')
+ ;
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ function chart(selection) {
+ selection.each(function(data) {
+ var container = d3.select(this);
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ nv.utils.initSVG(container);
+
+ active = data; //set all active before first brush call
+
+ // Setup Scales
+ x.rangePoints([0, availableWidth], 1).domain(dimensionNames);
+
+ //Set as true if all values on an axis are missing.
+ var onlyNanValues = {};
+ // Extract the list of dimensions and create a scale for each.
+ dimensionNames.forEach(function(d) {
+ var extent = d3.extent(data, function(p) { return +p[d]; });
+ onlyNanValues[d] = false;
+ //If there is no values to display on an axis, set the extent to 0
+ if (extent[0] === undefined) {
+ onlyNanValues[d] = true;
+ extent[0] = 0;
+ extent[1] = 0;
+ }
+ //Scale axis if there is only one value
+ if (extent[0] === extent[1]) {
+ extent[0] = extent[0] - 1;
+ extent[1] = extent[1] + 1;
+ }
+ //Use 90% of (availableHeight - 12) for the axis range, 12 reprensenting the space necessary to display "undefined values" text.
+ //The remaining 10% are used to display the missingValue line.
+ y[d] = d3.scale.linear()
+ .domain(extent)
+ .range([(availableHeight - 12) * 0.9, 0]);
+
+ y[d].brush = d3.svg.brush().y(y[d]).on('brush', brush);
+
+ return d != 'name';
+ });
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-parallelCoordinates').data([data]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-parallelCoordinates');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-parallelCoordinates background');
+ gEnter.append('g').attr('class', 'nv-parallelCoordinates foreground');
+ gEnter.append('g').attr('class', 'nv-parallelCoordinates missingValuesline');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ var line = d3.svg.line().interpolate('cardinal').tension(lineTension),
+ axis = d3.svg.axis().orient('left'),
+ axisDrag = d3.behavior.drag()
+ .on('dragstart', dragStart)
+ .on('drag', dragMove)
+ .on('dragend', dragEnd);
+
+ //Add missing value line at the bottom of the chart
+ var missingValuesline, missingValueslineText;
+ var step = x.range()[1] - x.range()[0];
+ var axisWithMissingValues = [];
+ var lineData = [0 + step / 2, availableHeight - 12, availableWidth - step / 2, availableHeight - 12];
+ missingValuesline = wrap.select('.missingValuesline').selectAll('line').data([lineData]);
+ missingValuesline.enter().append('line');
+ missingValuesline.exit().remove();
+ missingValuesline.attr("x1", function(d) { return d[0]; })
+ .attr("y1", function(d) { return d[1]; })
+ .attr("x2", function(d) { return d[2]; })
+ .attr("y2", function(d) { return d[3]; });
+
+ //Add the text "undefined values" under the missing value line
+ missingValueslineText = wrap.select('.missingValuesline').selectAll('text').data(["undefined values"]);
+ missingValueslineText.append('text').data(["undefined values"]);
+ missingValueslineText.enter().append('text');
+ missingValueslineText.exit().remove();
+ missingValueslineText.attr("y", availableHeight)
+ //To have the text right align with the missingValues line, substract 92 representing the text size.
+ .attr("x", availableWidth - 92 - step / 2)
+ .text(function(d) { return d; });
+
+ // Add grey background lines for context.
+ var background = wrap.select('.background').selectAll('path').data(data);
+ background.enter().append('path');
+ background.exit().remove();
+ background.attr('d', path);
+
+ // Add blue foreground lines for focus.
+ var foreground = wrap.select('.foreground').selectAll('path').data(data);
+ foreground.enter().append('path')
+ foreground.exit().remove();
+ foreground.attr('d', path).attr('stroke', color);
+ foreground.on("mouseover", function (d, i) {
+ d3.select(this).classed('hover', true);
+ dispatch.elementMouseover({
+ label: d.name,
+ data: d.data,
+ index: i,
+ pos: [d3.mouse(this.parentNode)[0], d3.mouse(this.parentNode)[1]]
+ });
+
+ });
+ foreground.on("mouseout", function (d, i) {
+ d3.select(this).classed('hover', false);
+ dispatch.elementMouseout({
+ label: d.name,
+ data: d.data,
+ index: i
+ });
+ });
+
+ // Add a group element for each dimension.
+ var dimensions = g.selectAll('.dimension').data(dimensionNames);
+ var dimensionsEnter = dimensions.enter().append('g').attr('class', 'nv-parallelCoordinates dimension');
+ dimensionsEnter.append('g').attr('class', 'nv-parallelCoordinates nv-axis');
+ dimensionsEnter.append('g').attr('class', 'nv-parallelCoordinates-brush');
+ dimensionsEnter.append('text').attr('class', 'nv-parallelCoordinates nv-label');
+
+ dimensions.attr('transform', function(d) { return 'translate(' + x(d) + ',0)'; });
+ dimensions.exit().remove();
+
+ // Add an axis and title.
+ dimensions.select('.nv-label')
+ .style("cursor", "move")
+ .attr('dy', '-1em')
+ .attr('text-anchor', 'middle')
+ .text(String)
+ .on("mouseover", function(d, i) {
+ dispatch.elementMouseover({
+ dim: d,
+ pos: [d3.mouse(this.parentNode.parentNode)[0], d3.mouse(this.parentNode.parentNode)[1]]
+ });
+ })
+ .on("mouseout", function(d, i) {
+ dispatch.elementMouseout({
+ dim: d
+ });
+ })
+ .call(axisDrag);
+
+ dimensions.select('.nv-axis')
+ .each(function (d, i) {
+ d3.select(this).call(axis.scale(y[d]).tickFormat(d3.format(dimensionFormats[i])));
+ });
+
+ dimensions.select('.nv-parallelCoordinates-brush')
+ .each(function (d) {
+ d3.select(this).call(y[d].brush);
+ })
+ .selectAll('rect')
+ .attr('x', -8)
+ .attr('width', 16);
+
+ // Returns the path for a given data point.
+ function path(d) {
+ return line(dimensionNames.map(function (p) {
+ //If value if missing, put the value on the missing value line
+ if(isNaN(d[p]) || isNaN(parseFloat(d[p]))) {
+ var domain = y[p].domain();
+ var range = y[p].range();
+ var min = domain[0] - (domain[1] - domain[0]) / 9;
+
+ //If it's not already the case, allow brush to select undefined values
+ if(axisWithMissingValues.indexOf(p) < 0) {
+
+ var newscale = d3.scale.linear().domain([min, domain[1]]).range([availableHeight - 12, range[1]]);
+ y[p].brush.y(newscale);
+ axisWithMissingValues.push(p);
+ }
+
+ return [x(p), y[p](min)];
+ }
+
+ //If parallelCoordinate contain missing values show the missing values line otherwise, hide it.
+ if(axisWithMissingValues.length > 0) {
+ missingValuesline.style("display", "inline");
+ missingValueslineText.style("display", "inline");
+ } else {
+ missingValuesline.style("display", "none");
+ missingValueslineText.style("display", "none");
+ }
+
+ return [x(p), y[p](d[p])];
+ }));
+ }
+
+ // Handles a brush event, toggling the display of foreground lines.
+ function brush() {
+ var actives = dimensionNames.filter(function(p) { return !y[p].brush.empty(); }),
+ extents = actives.map(function(p) { return y[p].brush.extent(); });
+
+ filters = []; //erase current filters
+ actives.forEach(function(d,i) {
+ filters[i] = {
+ dimension: d,
+ extent: extents[i]
+ }
+ });
+
+ active = []; //erase current active list
+ foreground.style('display', function(d) {
+ var isActive = actives.every(function(p, i) {
+ if(isNaN(d[p]) && extents[i][0] == y[p].brush.y().domain()[0]) return true;
+ return extents[i][0] <= d[p] && d[p] <= extents[i][1];
+ });
+ if (isActive) active.push(d);
+ return isActive ? null : 'none';
+ });
+
+ dispatch.brush({
+ filters: filters,
+ active: active
+ });
+ }
+
+ function dragStart(d, i) {
+ dragging[d] = this.parentNode.__origin__ = x(d);
+ background.attr("visibility", "hidden");
+
+ }
+
+ function dragMove(d, i) {
+ dragging[d] = Math.min(availableWidth, Math.max(0, this.parentNode.__origin__ += d3.event.x));
+ foreground.attr("d", path);
+ dimensionNames.sort(function (a, b) { return position(a) - position(b); });
+ x.domain(dimensionNames);
+ dimensions.attr("transform", function(d) { return "translate(" + position(d) + ")"; });
+ }
+
+ function dragEnd(d, i) {
+ delete this.parentNode.__origin__;
+ delete dragging[d];
+ d3.select(this.parentNode).attr("transform", "translate(" + x(d) + ")");
+ foreground
+ .attr("d", path);
+ background
+ .attr("d", path)
+ .attr("visibility", null);
+
+ }
+
+ function position(d) {
+ var v = dragging[d];
+ return v == null ? x(d) : v;
+ }
+ });
+
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width= _;}},
+ height: {get: function(){return height;}, set: function(_){height= _;}},
+ dimensionNames: {get: function() { return dimensionNames;}, set: function(_){dimensionNames= _;}},
+ dimensionFormats : {get: function(){return dimensionFormats;}, set: function (_){dimensionFormats=_;}},
+ lineTension: {get: function(){return lineTension;}, set: function(_){lineTension = _;}},
+
+ // deprecated options
+ dimensions: {get: function (){return dimensionNames;}, set: function(_){
+ // deprecated after 1.8.1
+ nv.deprecated('dimensions', 'use dimensionNames instead');
+ dimensionNames = _;
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+ return chart;
+};
+nv.models.pie = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = 500
+ , height = 500
+ , getX = function(d) { return d.x }
+ , getY = function(d) { return d.y }
+ , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
+ , container = null
+ , color = nv.utils.defaultColor()
+ , valueFormat = d3.format(',.2f')
+ , showLabels = true
+ , labelsOutside = false
+ , labelType = "key"
+ , labelThreshold = .02 //if slice percentage is under this, don't show label
+ , donut = false
+ , title = false
+ , growOnHover = true
+ , titleOffset = 0
+ , labelSunbeamLayout = false
+ , startAngle = false
+ , padAngle = false
+ , endAngle = false
+ , cornerRadius = 0
+ , donutRatio = 0.5
+ , arcsRadius = []
+ , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove', 'renderEnd')
+ ;
+
+ var arcs = [];
+ var arcsOver = [];
+
+ //============================================================
+ // chart function
+ //------------------------------------------------------------
+
+ var renderWatch = nv.utils.renderWatch(dispatch);
+
+ function chart(selection) {
+ renderWatch.reset();
+ selection.each(function(data) {
+ var availableWidth = width - margin.left - margin.right
+ , availableHeight = height - margin.top - margin.bottom
+ , radius = Math.min(availableWidth, availableHeight) / 2
+ , arcsRadiusOuter = []
+ , arcsRadiusInner = []
+ ;
+
+ container = d3.select(this)
+ if (arcsRadius.length === 0) {
+ var outer = radius - radius / 5;
+ var inner = donutRatio * radius;
+ for (var i = 0; i < data[0].length; i++) {
+ arcsRadiusOuter.push(outer);
+ arcsRadiusInner.push(inner);
+ }
+ } else {
+ arcsRadiusOuter = arcsRadius.map(function (d) { return (d.outer - d.outer / 5) * radius; });
+ arcsRadiusInner = arcsRadius.map(function (d) { return (d.inner - d.inner / 5) * radius; });
+ donutRatio = d3.min(arcsRadius.map(function (d) { return (d.inner - d.inner / 5); }));
+ }
+ nv.utils.initSVG(container);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('.nv-wrap.nv-pie').data(data);
+ var wrapEnter = wrap.enter().append('g').attr('class','nvd3 nv-wrap nv-pie nv-chart-' + id);
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+ var g_pie = gEnter.append('g').attr('class', 'nv-pie');
+ gEnter.append('g').attr('class', 'nv-pieLabels');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+ g.select('.nv-pie').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');
+ g.select('.nv-pieLabels').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');
+
+ //
+ container.on('click', function(d,i) {
+ dispatch.chartClick({
+ data: d,
+ index: i,
+ pos: d3.event,
+ id: id
+ });
+ });
+
+ arcs = [];
+ arcsOver = [];
+ for (var i = 0; i < data[0].length; i++) {
+
+ var arc = d3.svg.arc().outerRadius(arcsRadiusOuter[i]);
+ var arcOver = d3.svg.arc().outerRadius(arcsRadiusOuter[i] + 5);
+
+ if (startAngle !== false) {
+ arc.startAngle(startAngle);
+ arcOver.startAngle(startAngle);
+ }
+ if (endAngle !== false) {
+ arc.endAngle(endAngle);
+ arcOver.endAngle(endAngle);
+ }
+ if (donut) {
+ arc.innerRadius(arcsRadiusInner[i]);
+ arcOver.innerRadius(arcsRadiusInner[i]);
+ }
+
+ if (arc.cornerRadius && cornerRadius) {
+ arc.cornerRadius(cornerRadius);
+ arcOver.cornerRadius(cornerRadius);
+ }
+
+ arcs.push(arc);
+ arcsOver.push(arcOver);
+ }
+
+ // Setup the Pie chart and choose the data element
+ var pie = d3.layout.pie()
+ .sort(null)
+ .value(function(d) { return d.disabled ? 0 : getY(d) });
+
+ // padAngle added in d3 3.5
+ if (pie.padAngle && padAngle) {
+ pie.padAngle(padAngle);
+ }
+
+ // if title is specified and donut, put it in the middle
+ if (donut && title) {
+ g_pie.append("text").attr('class', 'nv-pie-title');
+
+ wrap.select('.nv-pie-title')
+ .style("text-anchor", "middle")
+ .text(function (d) {
+ return title;
+ })
+ .style("font-size", (Math.min(availableWidth, availableHeight)) * donutRatio * 2 / (title.length + 2) + "px")
+ .attr("dy", "0.35em") // trick to vertically center text
+ .attr('transform', function(d, i) {
+ return 'translate(0, '+ titleOffset + ')';
+ });
+ }
+
+ var slices = wrap.select('.nv-pie').selectAll('.nv-slice').data(pie);
+ var pieLabels = wrap.select('.nv-pieLabels').selectAll('.nv-label').data(pie);
+
+ slices.exit().remove();
+ pieLabels.exit().remove();
+
+ var ae = slices.enter().append('g');
+ ae.attr('class', 'nv-slice');
+ ae.on('mouseover', function(d, i) {
+ d3.select(this).classed('hover', true);
+ if (growOnHover) {
+ d3.select(this).select("path").transition()
+ .duration(70)
+ .attr("d", arcsOver[i]);
+ }
+ dispatch.elementMouseover({
+ data: d.data,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ });
+ ae.on('mouseout', function(d, i) {
+ d3.select(this).classed('hover', false);
+ if (growOnHover) {
+ d3.select(this).select("path").transition()
+ .duration(50)
+ .attr("d", arcs[i]);
+ }
+ dispatch.elementMouseout({data: d.data, index: i});
+ });
+ ae.on('mousemove', function(d, i) {
+ dispatch.elementMousemove({data: d.data, index: i});
+ });
+ ae.on('click', function(d, i) {
+ dispatch.elementClick({
+ data: d.data,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ });
+ ae.on('dblclick', function(d, i) {
+ dispatch.elementDblClick({
+ data: d.data,
+ index: i,
+ color: d3.select(this).style("fill")
+ });
+ });
+
+ slices.attr('fill', function(d,i) { return color(d.data, i); });
+ slices.attr('stroke', function(d,i) { return color(d.data, i); });
+
+ var paths = ae.append('path').each(function(d) {
+ this._current = d;
+ });
+
+ slices.select('path')
+ .transition()
+ .attr('d', function (d, i) { return arcs[i](d); })
+ .attrTween('d', arcTween);
+
+ if (showLabels) {
+ // This does the normal label
+ var labelsArc = [];
+ for (var i = 0; i < data[0].length; i++) {
+ labelsArc.push(arcs[i]);
+
+ if (labelsOutside) {
+ if (donut) {
+ labelsArc[i] = d3.svg.arc().outerRadius(arcs[i].outerRadius());
+ if (startAngle !== false) labelsArc[i].startAngle(startAngle);
+ if (endAngle !== false) labelsArc[i].endAngle(endAngle);
+ }
+ } else if (!donut) {
+ labelsArc[i].innerRadius(0);
+ }
+ }
+
+ pieLabels.enter().append("g").classed("nv-label",true).each(function(d,i) {
+ var group = d3.select(this);
+
+ group.attr('transform', function (d, i) {
+ if (labelSunbeamLayout) {
+ d.outerRadius = arcsRadiusOuter[i] + 10; // Set Outer Coordinate
+ d.innerRadius = arcsRadiusOuter[i] + 15; // Set Inner Coordinate
+ var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
+ if ((d.startAngle + d.endAngle) / 2 < Math.PI) {
+ rotateAngle -= 90;
+ } else {
+ rotateAngle += 90;
+ }
+ return 'translate(' + labelsArc[i].centroid(d) + ') rotate(' + rotateAngle + ')';
+ } else {
+ d.outerRadius = radius + 10; // Set Outer Coordinate
+ d.innerRadius = radius + 15; // Set Inner Coordinate
+ return 'translate(' + labelsArc[i].centroid(d) + ')'
+ }
+ });
+
+ group.append('rect')
+ .style('stroke', '#fff')
+ .style('fill', '#fff')
+ .attr("rx", 3)
+ .attr("ry", 3);
+
+ group.append('text')
+ .style('text-anchor', labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle') //center the text on it's origin or begin/end if orthogonal aligned
+ .style('fill', '#000')
+ });
+
+ var labelLocationHash = {};
+ var avgHeight = 14;
+ var avgWidth = 140;
+ var createHashKey = function(coordinates) {
+ return Math.floor(coordinates[0]/avgWidth) * avgWidth + ',' + Math.floor(coordinates[1]/avgHeight) * avgHeight;
+ };
+
+ pieLabels.watchTransition(renderWatch, 'pie labels').attr('transform', function (d, i) {
+ if (labelSunbeamLayout) {
+ d.outerRadius = arcsRadiusOuter[i] + 10; // Set Outer Coordinate
+ d.innerRadius = arcsRadiusOuter[i] + 15; // Set Inner Coordinate
+ var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
+ if ((d.startAngle + d.endAngle) / 2 < Math.PI) {
+ rotateAngle -= 90;
+ } else {
+ rotateAngle += 90;
+ }
+ return 'translate(' + labelsArc[i].centroid(d) + ') rotate(' + rotateAngle + ')';
+ } else {
+ d.outerRadius = radius + 10; // Set Outer Coordinate
+ d.innerRadius = radius + 15; // Set Inner Coordinate
+
+ /*
+ Overlapping pie labels are not good. What this attempts to do is, prevent overlapping.
+ Each label location is hashed, and if a hash collision occurs, we assume an overlap.
+ Adjust the label's y-position to remove the overlap.
+ */
+ var center = labelsArc[i].centroid(d);
+ if (d.value) {
+ var hashKey = createHashKey(center);
+ if (labelLocationHash[hashKey]) {
+ center[1] -= avgHeight;
+ }
+ labelLocationHash[createHashKey(center)] = true;
+ }
+ return 'translate(' + center + ')'
+ }
+ });
+
+ pieLabels.select(".nv-label text")
+ .style('text-anchor', function(d,i) {
+ //center the text on it's origin or begin/end if orthogonal aligned
+ return labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle';
+ })
+ .text(function(d, i) {
+ var percent = (d.endAngle - d.startAngle) / (2 * Math.PI);
+ var label = '';
+ if (!d.value || percent < labelThreshold) return '';
+
+ if(typeof labelType === 'function') {
+ label = labelType(d, i, {
+ 'key': getX(d.data),
+ 'value': getY(d.data),
+ 'percent': valueFormat(percent)
+ });
+ } else {
+ switch (labelType) {
+ case 'key':
+ label = getX(d.data);
+ break;
+ case 'value':
+ label = valueFormat(getY(d.data));
+ break;
+ case 'percent':
+ label = d3.format('%')(percent);
+ break;
+ }
+ }
+ return label;
+ })
+ ;
+ }
+
+
+ // Computes the angle of an arc, converting from radians to degrees.
+ function angle(d) {
+ var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
+ return a > 90 ? a - 180 : a;
+ }
+
+ function arcTween(a, idx) {
+ a.endAngle = isNaN(a.endAngle) ? 0 : a.endAngle;
+ a.startAngle = isNaN(a.startAngle) ? 0 : a.startAngle;
+ if (!donut) a.innerRadius = 0;
+ var i = d3.interpolate(this._current, a);
+ this._current = i(0);
+ return function (t) {
+ return arcs[idx](i(t));
+ };
+ }
+ });
+
+ renderWatch.renderEnd('pie immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ arcsRadius: { get: function () { return arcsRadius; }, set: function (_) { arcsRadius = _; } },
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ showLabels: {get: function(){return showLabels;}, set: function(_){showLabels=_;}},
+ title: {get: function(){return title;}, set: function(_){title=_;}},
+ titleOffset: {get: function(){return titleOffset;}, set: function(_){titleOffset=_;}},
+ labelThreshold: {get: function(){return labelThreshold;}, set: function(_){labelThreshold=_;}},
+ valueFormat: {get: function(){return valueFormat;}, set: function(_){valueFormat=_;}},
+ x: {get: function(){return getX;}, set: function(_){getX=_;}},
+ id: {get: function(){return id;}, set: function(_){id=_;}},
+ endAngle: {get: function(){return endAngle;}, set: function(_){endAngle=_;}},
+ startAngle: {get: function(){return startAngle;}, set: function(_){startAngle=_;}},
+ padAngle: {get: function(){return padAngle;}, set: function(_){padAngle=_;}},
+ cornerRadius: {get: function(){return cornerRadius;}, set: function(_){cornerRadius=_;}},
+ donutRatio: {get: function(){return donutRatio;}, set: function(_){donutRatio=_;}},
+ labelsOutside: {get: function(){return labelsOutside;}, set: function(_){labelsOutside=_;}},
+ labelSunbeamLayout: {get: function(){return labelSunbeamLayout;}, set: function(_){labelSunbeamLayout=_;}},
+ donut: {get: function(){return donut;}, set: function(_){donut=_;}},
+ growOnHover: {get: function(){return growOnHover;}, set: function(_){growOnHover=_;}},
+
+ // depreciated after 1.7.1
+ pieLabelsOutside: {get: function(){return labelsOutside;}, set: function(_){
+ labelsOutside=_;
+ nv.deprecated('pieLabelsOutside', 'use labelsOutside instead');
+ }},
+ // depreciated after 1.7.1
+ donutLabelsOutside: {get: function(){return labelsOutside;}, set: function(_){
+ labelsOutside=_;
+ nv.deprecated('donutLabelsOutside', 'use labelsOutside instead');
+ }},
+ // deprecated after 1.7.1
+ labelFormat: {get: function(){ return valueFormat;}, set: function(_) {
+ valueFormat=_;
+ nv.deprecated('labelFormat','use valueFormat instead');
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
+ margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
+ margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
+ margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
+ }},
+ y: {get: function(){return getY;}, set: function(_){
+ getY=d3.functor(_);
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color=nv.utils.getColor(_);
+ }},
+ labelType: {get: function(){return labelType;}, set: function(_){
+ labelType= _ || 'key';
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+ return chart;
+};
+nv.models.pieChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var pie = nv.models.pie();
+ var legend = nv.models.legend();
+ var tooltip = nv.models.tooltip();
+
+ var margin = {top: 30, right: 20, bottom: 20, left: 20}
+ , width = null
+ , height = null
+ , showLegend = true
+ , legendPosition = "top"
+ , color = nv.utils.defaultColor()
+ , state = nv.utils.state()
+ , defaultState = null
+ , noData = null
+ , duration = 250
+ , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState','renderEnd')
+ ;
+
+ tooltip
+ .headerEnabled(false)
+ .duration(0)
+ .valueFormatter(function(d, i) {
+ return pie.valueFormat()(d, i);
+ });
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var renderWatch = nv.utils.renderWatch(dispatch);
+
+ var stateGetter = function(data) {
+ return function(){
+ return {
+ active: data.map(function(d) { return !d.disabled })
+ };
+ }
+ };
+
+ var stateSetter = function(data) {
+ return function(state) {
+ if (state.active !== undefined) {
+ data.forEach(function (series, i) {
+ series.disabled = !state.active[i];
+ });
+ }
+ }
+ };
+
+ //============================================================
+ // Chart function
+ //------------------------------------------------------------
+
+ function chart(selection) {
+ renderWatch.reset();
+ renderWatch.models(pie);
+
+ selection.each(function(data) {
+ var container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ var that = this;
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ chart.update = function() { container.transition().call(chart); };
+ chart.container = this;
+
+ state.setter(stateSetter(data), chart.update)
+ .getter(stateGetter(data))
+ .update();
+
+ //set state.disabled
+ state.disabled = data.map(function(d) { return !!d.disabled });
+
+ if (!defaultState) {
+ var key;
+ defaultState = {};
+ for (key in state) {
+ if (state[key] instanceof Array)
+ defaultState[key] = state[key].slice(0);
+ else
+ defaultState[key] = state[key];
+ }
+ }
+
+ // Display No Data message if there's nothing to show.
+ if (!data || !data.length) {
+ nv.utils.noData(chart, container);
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-pieChart').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-pieChart').append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-pieWrap');
+ gEnter.append('g').attr('class', 'nv-legendWrap');
+
+ // Legend
+ if (showLegend) {
+ if (legendPosition === "top") {
+ legend.width( availableWidth ).key(pie.x());
+
+ wrap.select('.nv-legendWrap')
+ .datum(data)
+ .call(legend);
+
+ if ( margin.top != legend.height()) {
+ margin.top = legend.height();
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+ }
+
+ wrap.select('.nv-legendWrap')
+ .attr('transform', 'translate(0,' + (-margin.top) +')');
+ } else if (legendPosition === "right") {
+ var legendWidth = nv.models.legend().width();
+ if (availableWidth / 2 < legendWidth) {
+ legendWidth = (availableWidth / 2)
+ }
+ legend.height(availableHeight).key(pie.x());
+ legend.width(legendWidth);
+ availableWidth -= legend.width();
+
+ wrap.select('.nv-legendWrap')
+ .datum(data)
+ .call(legend)
+ .attr('transform', 'translate(' + (availableWidth) +',0)');
+ }
+ }
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ // Main Chart Component(s)
+ pie.width(availableWidth).height(availableHeight);
+ var pieWrap = g.select('.nv-pieWrap').datum([data]);
+ d3.transition(pieWrap).call(pie);
+
+ //============================================================
+ // Event Handling/Dispatching (in chart's scope)
+ //------------------------------------------------------------
+
+ legend.dispatch.on('stateChange', function(newState) {
+ for (var key in newState) {
+ state[key] = newState[key];
+ }
+ dispatch.stateChange(state);
+ chart.update();
+ });
+
+ // Update chart from a state object passed to event handler
+ dispatch.on('changeState', function(e) {
+ if (typeof e.disabled !== 'undefined') {
+ data.forEach(function(series,i) {
+ series.disabled = e.disabled[i];
+ });
+ state.disabled = e.disabled;
+ }
+ chart.update();
+ });
+ });
+
+ renderWatch.renderEnd('pieChart immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (out of chart's scope)
+ //------------------------------------------------------------
+
+ pie.dispatch.on('elementMouseover.tooltip', function(evt) {
+ evt['series'] = {
+ key: chart.x()(evt.data),
+ value: chart.y()(evt.data),
+ color: evt.color
+ };
+ tooltip.data(evt).hidden(false);
+ });
+
+ pie.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true);
+ });
+
+ pie.dispatch.on('elementMousemove.tooltip', function(evt) {
+ tooltip.position({top: d3.event.pageY, left: d3.event.pageX})();
+ });
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ // expose chart's sub-components
+ chart.legend = legend;
+ chart.dispatch = dispatch;
+ chart.pie = pie;
+ chart.tooltip = tooltip;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ // use Object get/set functionality to map between vars and chart functions
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+ showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
+ legendPosition: {get: function(){return legendPosition;}, set: function(_){legendPosition=_;}},
+ defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
+
+ // deprecated options
+ tooltips: {get: function(){return tooltip.enabled();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltips', 'use chart.tooltip.enabled() instead');
+ tooltip.enabled(!!_);
+ }},
+ tooltipContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'use chart.tooltip.contentGenerator() instead');
+ tooltip.contentGenerator(_);
+ }},
+
+ // options that require extra logic in the setter
+ color: {get: function(){return color;}, set: function(_){
+ color = _;
+ legend.color(color);
+ pie.color(color);
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ }},
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }}
+ });
+ nv.utils.inheritOptions(chart, pie);
+ nv.utils.initOptions(chart);
+ return chart;
+};
+
+nv.models.scatter = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = null
+ , height = null
+ , color = nv.utils.defaultColor() // chooses color
+ , id = Math.floor(Math.random() * 100000) //Create semi-unique ID incase user doesn't select one
+ , container = null
+ , x = d3.scale.linear()
+ , y = d3.scale.linear()
+ , z = d3.scale.linear() //linear because d3.svg.shape.size is treated as area
+ , getX = function(d) { return d.x } // accessor to get the x value
+ , getY = function(d) { return d.y } // accessor to get the y value
+ , getSize = function(d) { return d.size || 1} // accessor to get the point size
+ , getShape = function(d) { return d.shape || 'circle' } // accessor to get point shape
+ , forceX = [] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
+ , forceY = [] // List of numbers to Force into the Y scale
+ , forceSize = [] // List of numbers to Force into the Size scale
+ , interactive = true // If true, plots a voronoi overlay for advanced point intersection
+ , pointActive = function(d) { return !d.notActive } // any points that return false will be filtered out
+ , padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart
+ , padDataOuter = .1 //outerPadding to imitate ordinal scale outer padding
+ , clipEdge = false // if true, masks points within x and y scale
+ , clipVoronoi = true // if true, masks each point with a circle... can turn off to slightly increase performance
+ , showVoronoi = false // display the voronoi areas
+ , clipRadius = function() { return 25 } // function to get the radius for voronoi point clips
+ , xDomain = null // Override x domain (skips the calculation from data)
+ , yDomain = null // Override y domain
+ , xRange = null // Override x range
+ , yRange = null // Override y range
+ , sizeDomain = null // Override point size domain
+ , sizeRange = null
+ , singlePoint = false
+ , dispatch = d3.dispatch('elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'renderEnd')
+ , useVoronoi = true
+ , duration = 250
+ ;
+
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var x0, y0, z0 // used to store previous scales
+ , timeoutID
+ , needsUpdate = false // Flag for when the points are visually updating, but the interactive layer is behind, to disable tooltips
+ , renderWatch = nv.utils.renderWatch(dispatch, duration)
+ , _sizeRange_def = [16, 256]
+ ;
+
+ function chart(selection) {
+ renderWatch.reset();
+ selection.each(function(data) {
+ container = d3.select(this);
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ nv.utils.initSVG(container);
+
+ //add series index to each data point for reference
+ data.forEach(function(series, i) {
+ series.values.forEach(function(point) {
+ point.series = i;
+ });
+ });
+
+ // Setup Scales
+ // remap and flatten the data for use in calculating the scales' domains
+ var seriesData = (xDomain && yDomain && sizeDomain) ? [] : // if we know xDomain and yDomain and sizeDomain, no need to calculate.... if Size is constant remember to set sizeDomain to speed up performance
+ d3.merge(
+ data.map(function(d) {
+ return d.values.map(function(d,i) {
+ return { x: getX(d,i), y: getY(d,i), size: getSize(d,i) }
+ })
+ })
+ );
+
+ x .domain(xDomain || d3.extent(seriesData.map(function(d) { return d.x; }).concat(forceX)))
+
+ if (padData && data[0])
+ x.range(xRange || [(availableWidth * padDataOuter + availableWidth) / (2 *data[0].values.length), availableWidth - availableWidth * (1 + padDataOuter) / (2 * data[0].values.length) ]);
+ //x.range([availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]);
+ else
+ x.range(xRange || [0, availableWidth]);
+
+ y .domain(yDomain || d3.extent(seriesData.map(function(d) { return d.y }).concat(forceY)))
+ .range(yRange || [availableHeight, 0]);
+
+ z .domain(sizeDomain || d3.extent(seriesData.map(function(d) { return d.size }).concat(forceSize)))
+ .range(sizeRange || _sizeRange_def);
+
+ // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
+ singlePoint = x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1];
+
+ if (x.domain()[0] === x.domain()[1])
+ x.domain()[0] ?
+ x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
+ : x.domain([-1,1]);
+
+ if (y.domain()[0] === y.domain()[1])
+ y.domain()[0] ?
+ y.domain([y.domain()[0] - y.domain()[0] * 0.01, y.domain()[1] + y.domain()[1] * 0.01])
+ : y.domain([-1,1]);
+
+ if ( isNaN(x.domain()[0])) {
+ x.domain([-1,1]);
+ }
+
+ if ( isNaN(y.domain()[0])) {
+ y.domain([-1,1]);
+ }
+
+ x0 = x0 || x;
+ y0 = y0 || y;
+ z0 = z0 || z;
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-scatter').data([data]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatter nv-chart-' + id);
+ var defsEnter = wrapEnter.append('defs');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ wrap.classed('nv-single-point', singlePoint);
+ gEnter.append('g').attr('class', 'nv-groups');
+ gEnter.append('g').attr('class', 'nv-point-paths');
+ wrapEnter.append('g').attr('class', 'nv-point-clips');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ defsEnter.append('clipPath')
+ .attr('id', 'nv-edge-clip-' + id)
+ .append('rect');
+
+ wrap.select('#nv-edge-clip-' + id + ' rect')
+ .attr('width', availableWidth)
+ .attr('height', (availableHeight > 0) ? availableHeight : 0);
+
+ g.attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : '');
+
+ function updateInteractiveLayer() {
+ // Always clear needs-update flag regardless of whether or not
+ // we will actually do anything (avoids needless invocations).
+ needsUpdate = false;
+
+ if (!interactive) return false;
+
+ // inject series and point index for reference into voronoi
+ if (useVoronoi === true) {
+ var vertices = d3.merge(data.map(function(group, groupIndex) {
+ return group.values
+ .map(function(point, pointIndex) {
+ // *Adding noise to make duplicates very unlikely
+ // *Injecting series and point index for reference
+ /* *Adding a 'jitter' to the points, because there's an issue in d3.geom.voronoi.
+ */
+ var pX = getX(point,pointIndex);
+ var pY = getY(point,pointIndex);
+
+ return [x(pX)+ Math.random() * 1e-4,
+ y(pY)+ Math.random() * 1e-4,
+ groupIndex,
+ pointIndex, point]; //temp hack to add noise until I think of a better way so there are no duplicates
+ })
+ .filter(function(pointArray, pointIndex) {
+ return pointActive(pointArray[4], pointIndex); // Issue #237.. move filter to after map, so pointIndex is correct!
+ })
+ })
+ );
+
+ if (vertices.length == 0) return false; // No active points, we're done
+ if (vertices.length < 3) {
+ // Issue #283 - Adding 2 dummy points to the voronoi b/c voronoi requires min 3 points to work
+ vertices.push([x.range()[0] - 20, y.range()[0] - 20, null, null]);
+ vertices.push([x.range()[1] + 20, y.range()[1] + 20, null, null]);
+ vertices.push([x.range()[0] - 20, y.range()[0] + 20, null, null]);
+ vertices.push([x.range()[1] + 20, y.range()[1] - 20, null, null]);
+ }
+
+ // keep voronoi sections from going more than 10 outside of graph
+ // to avoid overlap with other things like legend etc
+ var bounds = d3.geom.polygon([
+ [-10,-10],
+ [-10,height + 10],
+ [width + 10,height + 10],
+ [width + 10,-10]
+ ]);
+
+ var voronoi = d3.geom.voronoi(vertices).map(function(d, i) {
+ return {
+ 'data': bounds.clip(d),
+ 'series': vertices[i][2],
+ 'point': vertices[i][3]
+ }
+ });
+
+ // nuke all voronoi paths on reload and recreate them
+ wrap.select('.nv-point-paths').selectAll('path').remove();
+ var pointPaths = wrap.select('.nv-point-paths').selectAll('path').data(voronoi);
+ var vPointPaths = pointPaths
+ .enter().append("svg:path")
+ .attr("d", function(d) {
+ if (!d || !d.data || d.data.length === 0)
+ return 'M 0 0';
+ else
+ return "M" + d.data.join(",") + "Z";
+ })
+ .attr("id", function(d,i) {
+ return "nv-path-"+i; })
+ .attr("clip-path", function(d,i) { return "url(#nv-clip-"+i+")"; })
+ ;
+
+ // good for debugging point hover issues
+ if (showVoronoi) {
+ vPointPaths.style("fill", d3.rgb(230, 230, 230))
+ .style('fill-opacity', 0.4)
+ .style('stroke-opacity', 1)
+ .style("stroke", d3.rgb(200,200,200));
+ }
+
+ if (clipVoronoi) {
+ // voronoi sections are already set to clip,
+ // just create the circles with the IDs they expect
+ wrap.select('.nv-point-clips').selectAll('clipPath').remove();
+ wrap.select('.nv-point-clips').selectAll("clipPath")
+ .data(vertices)
+ .enter().append("svg:clipPath")
+ .attr("id", function(d, i) { return "nv-clip-"+i;})
+ .append("svg:circle")
+ .attr('cx', function(d) { return d[0]; })
+ .attr('cy', function(d) { return d[1]; })
+ .attr('r', clipRadius);
+ }
+
+ var mouseEventCallback = function(d, mDispatch) {
+ if (needsUpdate) return 0;
+ var series = data[d.series];
+ if (series === undefined) return;
+ var point = series.values[d.point];
+ point['color'] = color(series, d.series);
+
+ // standardize attributes for tooltip.
+ point['x'] = getX(point);
+ point['y'] = getY(point);
+
+ // can't just get box of event node since it's actually a voronoi polygon
+ var box = container.node().getBoundingClientRect();
+ var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
+ var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
+
+ var pos = {
+ left: x(getX(point, d.point)) + box.left + scrollLeft + margin.left + 10,
+ top: y(getY(point, d.point)) + box.top + scrollTop + margin.top + 10
+ };
+
+ mDispatch({
+ point: point,
+ series: series,
+ pos: pos,
+ seriesIndex: d.series,
+ pointIndex: d.point
+ });
+ };
+
+ pointPaths
+ .on('click', function(d) {
+ mouseEventCallback(d, dispatch.elementClick);
+ })
+ .on('dblclick', function(d) {
+ mouseEventCallback(d, dispatch.elementDblClick);
+ })
+ .on('mouseover', function(d) {
+ mouseEventCallback(d, dispatch.elementMouseover);
+ })
+ .on('mouseout', function(d, i) {
+ mouseEventCallback(d, dispatch.elementMouseout);
+ });
+
+ } else {
+ // add event handlers to points instead voronoi paths
+ wrap.select('.nv-groups').selectAll('.nv-group')
+ .selectAll('.nv-point')
+ //.data(dataWithPoints)
+ //.style('pointer-events', 'auto') // recativate events, disabled by css
+ .on('click', function(d,i) {
+ //nv.log('test', d, i);
+ if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
+ var series = data[d.series],
+ point = series.values[i];
+
+ dispatch.elementClick({
+ point: point,
+ series: series,
+ pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],
+ seriesIndex: d.series,
+ pointIndex: i
+ });
+ })
+ .on('dblclick', function(d,i) {
+ if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
+ var series = data[d.series],
+ point = series.values[i];
+
+ dispatch.elementDblClick({
+ point: point,
+ series: series,
+ pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],
+ seriesIndex: d.series,
+ pointIndex: i
+ });
+ })
+ .on('mouseover', function(d,i) {
+ if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
+ var series = data[d.series],
+ point = series.values[i];
+
+ dispatch.elementMouseover({
+ point: point,
+ series: series,
+ pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],
+ seriesIndex: d.series,
+ pointIndex: i,
+ color: color(d, i)
+ });
+ })
+ .on('mouseout', function(d,i) {
+ if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
+ var series = data[d.series],
+ point = series.values[i];
+
+ dispatch.elementMouseout({
+ point: point,
+ series: series,
+ seriesIndex: d.series,
+ pointIndex: i,
+ color: color(d, i)
+ });
+ });
+ }
+ }
+
+ needsUpdate = true;
+ var groups = wrap.select('.nv-groups').selectAll('.nv-group')
+ .data(function(d) { return d }, function(d) { return d.key });
+ groups.enter().append('g')
+ .style('stroke-opacity', 1e-6)
+ .style('fill-opacity', 1e-6);
+ groups.exit()
+ .remove();
+ groups
+ .attr('class', function(d,i) { return 'nv-group nv-series-' + i })
+ .classed('hover', function(d) { return d.hover });
+ groups.watchTransition(renderWatch, 'scatter: groups')
+ .style('fill', function(d,i) { return color(d, i) })
+ .style('stroke', function(d,i) { return color(d, i) })
+ .style('stroke-opacity', 1)
+ .style('fill-opacity', .5);
+
+ // create the points, maintaining their IDs from the original data set
+ var points = groups.selectAll('path.nv-point')
+ .data(function(d) {
+ return d.values.map(
+ function (point, pointIndex) {
+ return [point, pointIndex]
+ }).filter(
+ function(pointArray, pointIndex) {
+ return pointActive(pointArray[0], pointIndex)
+ })
+ });
+ points.enter().append('path')
+ .style('fill', function (d) { return d.color })
+ .style('stroke', function (d) { return d.color })
+ .attr('transform', function(d) {
+ return 'translate(' + x0(getX(d[0],d[1])) + ',' + y0(getY(d[0],d[1])) + ')'
+ })
+ .attr('d',
+ nv.utils.symbol()
+ .type(function(d) { return getShape(d[0]); })
+ .size(function(d) { return z(getSize(d[0],d[1])) })
+ );
+ points.exit().remove();
+ groups.exit().selectAll('path.nv-point')
+ .watchTransition(renderWatch, 'scatter exit')
+ .attr('transform', function(d) {
+ return 'translate(' + x(getX(d[0],d[1])) + ',' + y(getY(d[0],d[1])) + ')'
+ })
+ .remove();
+ points.each(function(d) {
+ d3.select(this)
+ .classed('nv-point', true)
+ .classed('nv-point-' + d[1], true)
+ .classed('nv-noninteractive', !interactive)
+ .classed('hover',false)
+ ;
+ });
+ points
+ .watchTransition(renderWatch, 'scatter points')
+ .attr('transform', function(d) {
+ //nv.log(d, getX(d[0],d[1]), x(getX(d[0],d[1])));
+ return 'translate(' + x(getX(d[0],d[1])) + ',' + y(getY(d[0],d[1])) + ')'
+ })
+ .attr('d',
+ nv.utils.symbol()
+ .type(function(d) { return getShape(d[0]); })
+ .size(function(d) { return z(getSize(d[0],d[1])) })
+ );
+
+ // Delay updating the invisible interactive layer for smoother animation
+ clearTimeout(timeoutID); // stop repeat calls to updateInteractiveLayer
+ timeoutID = setTimeout(updateInteractiveLayer, 300);
+ //updateInteractiveLayer();
+
+ //store old scales for use in transitions on update
+ x0 = x.copy();
+ y0 = y.copy();
+ z0 = z.copy();
+
+ });
+ renderWatch.renderEnd('scatter immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ // utility function calls provided by this chart
+ chart._calls = new function() {
+ this.clearHighlights = function () {
+ nv.dom.write(function() {
+ container.selectAll(".nv-point.hover").classed("hover", false);
+ });
+ return null;
+ };
+ this.highlightPoint = function (seriesIndex, pointIndex, isHoverOver) {
+ nv.dom.write(function() {
+ container.select(" .nv-series-" + seriesIndex + " .nv-point-" + pointIndex)
+ .classed("hover", isHoverOver);
+ });
+ };
+ };
+
+ // trigger calls from events too
+ dispatch.on('elementMouseover.point', function(d) {
+ if (interactive) chart._calls.highlightPoint(d.seriesIndex,d.pointIndex,true);
+ });
+
+ dispatch.on('elementMouseout.point', function(d) {
+ if (interactive) chart._calls.highlightPoint(d.seriesIndex,d.pointIndex,false);
+ });
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ xScale: {get: function(){return x;}, set: function(_){x=_;}},
+ yScale: {get: function(){return y;}, set: function(_){y=_;}},
+ pointScale: {get: function(){return z;}, set: function(_){z=_;}},
+ xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
+ yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
+ pointDomain: {get: function(){return sizeDomain;}, set: function(_){sizeDomain=_;}},
+ xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
+ yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
+ pointRange: {get: function(){return sizeRange;}, set: function(_){sizeRange=_;}},
+ forceX: {get: function(){return forceX;}, set: function(_){forceX=_;}},
+ forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
+ forcePoint: {get: function(){return forceSize;}, set: function(_){forceSize=_;}},
+ interactive: {get: function(){return interactive;}, set: function(_){interactive=_;}},
+ pointActive: {get: function(){return pointActive;}, set: function(_){pointActive=_;}},
+ padDataOuter: {get: function(){return padDataOuter;}, set: function(_){padDataOuter=_;}},
+ padData: {get: function(){return padData;}, set: function(_){padData=_;}},
+ clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
+ clipVoronoi: {get: function(){return clipVoronoi;}, set: function(_){clipVoronoi=_;}},
+ clipRadius: {get: function(){return clipRadius;}, set: function(_){clipRadius=_;}},
+ showVoronoi: {get: function(){return showVoronoi;}, set: function(_){showVoronoi=_;}},
+ id: {get: function(){return id;}, set: function(_){id=_;}},
+
+
+ // simple functor options
+ x: {get: function(){return getX;}, set: function(_){getX = d3.functor(_);}},
+ y: {get: function(){return getY;}, set: function(_){getY = d3.functor(_);}},
+ pointSize: {get: function(){return getSize;}, set: function(_){getSize = d3.functor(_);}},
+ pointShape: {get: function(){return getShape;}, set: function(_){getShape = d3.functor(_);}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }},
+ useVoronoi: {get: function(){return useVoronoi;}, set: function(_){
+ useVoronoi = _;
+ if (useVoronoi === false) {
+ clipVoronoi = false;
+ }
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+ return chart;
+};
+
+nv.models.scatterChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var scatter = nv.models.scatter()
+ , xAxis = nv.models.axis()
+ , yAxis = nv.models.axis()
+ , legend = nv.models.legend()
+ , distX = nv.models.distribution()
+ , distY = nv.models.distribution()
+ , tooltip = nv.models.tooltip()
+ ;
+
+ var margin = {top: 30, right: 20, bottom: 50, left: 75}
+ , width = null
+ , height = null
+ , container = null
+ , color = nv.utils.defaultColor()
+ , x = scatter.xScale()
+ , y = scatter.yScale()
+ , showDistX = false
+ , showDistY = false
+ , showLegend = true
+ , showXAxis = true
+ , showYAxis = true
+ , rightAlignYAxis = false
+ , state = nv.utils.state()
+ , defaultState = null
+ , dispatch = d3.dispatch('stateChange', 'changeState', 'renderEnd')
+ , noData = null
+ , duration = 250
+ ;
+
+ scatter.xScale(x).yScale(y);
+ xAxis.orient('bottom').tickPadding(10);
+ yAxis
+ .orient((rightAlignYAxis) ? 'right' : 'left')
+ .tickPadding(10)
+ ;
+ distX.axis('x');
+ distY.axis('y');
+ tooltip
+ .headerFormatter(function(d, i) {
+ return xAxis.tickFormat()(d, i);
+ })
+ .valueFormatter(function(d, i) {
+ return yAxis.tickFormat()(d, i);
+ });
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var x0, y0
+ , renderWatch = nv.utils.renderWatch(dispatch, duration);
+
+ var stateGetter = function(data) {
+ return function(){
+ return {
+ active: data.map(function(d) { return !d.disabled })
+ };
+ }
+ };
+
+ var stateSetter = function(data) {
+ return function(state) {
+ if (state.active !== undefined)
+ data.forEach(function(series,i) {
+ series.disabled = !state.active[i];
+ });
+ }
+ };
+
+ function chart(selection) {
+ renderWatch.reset();
+ renderWatch.models(scatter);
+ if (showXAxis) renderWatch.models(xAxis);
+ if (showYAxis) renderWatch.models(yAxis);
+ if (showDistX) renderWatch.models(distX);
+ if (showDistY) renderWatch.models(distY);
+
+ selection.each(function(data) {
+ var that = this;
+
+ container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ chart.update = function() {
+ if (duration === 0)
+ container.call(chart);
+ else
+ container.transition().duration(duration).call(chart);
+ };
+ chart.container = this;
+
+ state
+ .setter(stateSetter(data), chart.update)
+ .getter(stateGetter(data))
+ .update();
+
+ // DEPRECATED set state.disableddisabled
+ state.disabled = data.map(function(d) { return !!d.disabled });
+
+ if (!defaultState) {
+ var key;
+ defaultState = {};
+ for (key in state) {
+ if (state[key] instanceof Array)
+ defaultState[key] = state[key].slice(0);
+ else
+ defaultState[key] = state[key];
+ }
+ }
+
+ // Display noData message if there's nothing to show.
+ if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
+ nv.utils.noData(chart, container);
+ renderWatch.renderEnd('scatter immediate');
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ // Setup Scales
+ x = scatter.xScale();
+ y = scatter.yScale();
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-scatterChart').data([data]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatterChart nv-chart-' + scatter.id());
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ // background for pointer events
+ gEnter.append('rect').attr('class', 'nvd3 nv-background').style("pointer-events","none");
+
+ gEnter.append('g').attr('class', 'nv-x nv-axis');
+ gEnter.append('g').attr('class', 'nv-y nv-axis');
+ gEnter.append('g').attr('class', 'nv-scatterWrap');
+ gEnter.append('g').attr('class', 'nv-regressionLinesWrap');
+ gEnter.append('g').attr('class', 'nv-distWrap');
+ gEnter.append('g').attr('class', 'nv-legendWrap');
+
+ if (rightAlignYAxis) {
+ g.select(".nv-y.nv-axis")
+ .attr("transform", "translate(" + availableWidth + ",0)");
+ }
+
+ // Legend
+ if (showLegend) {
+ var legendWidth = availableWidth;
+ legend.width(legendWidth);
+
+ wrap.select('.nv-legendWrap')
+ .datum(data)
+ .call(legend);
+
+ if ( margin.top != legend.height()) {
+ margin.top = legend.height();
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+ }
+
+ wrap.select('.nv-legendWrap')
+ .attr('transform', 'translate(0' + ',' + (-margin.top) +')');
+ }
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ // Main Chart Component(s)
+ scatter
+ .width(availableWidth)
+ .height(availableHeight)
+ .color(data.map(function(d,i) {
+ return d.color || color(d, i);
+ }).filter(function(d,i) { return !data[i].disabled }));
+
+ wrap.select('.nv-scatterWrap')
+ .datum(data.filter(function(d) { return !d.disabled }))
+ .call(scatter);
+
+
+ wrap.select('.nv-regressionLinesWrap')
+ .attr('clip-path', 'url(#nv-edge-clip-' + scatter.id() + ')');
+
+ var regWrap = wrap.select('.nv-regressionLinesWrap').selectAll('.nv-regLines')
+ .data(function (d) {
+ return d;
+ });
+
+ regWrap.enter().append('g').attr('class', 'nv-regLines');
+
+ var regLine = regWrap.selectAll('.nv-regLine')
+ .data(function (d) {
+ return [d]
+ });
+
+ regLine.enter()
+ .append('line').attr('class', 'nv-regLine')
+ .style('stroke-opacity', 0);
+
+ // don't add lines unless we have slope and intercept to use
+ regLine.filter(function(d) {
+ return d.intercept && d.slope;
+ })
+ .watchTransition(renderWatch, 'scatterPlusLineChart: regline')
+ .attr('x1', x.range()[0])
+ .attr('x2', x.range()[1])
+ .attr('y1', function (d, i) {
+ return y(x.domain()[0] * d.slope + d.intercept)
+ })
+ .attr('y2', function (d, i) {
+ return y(x.domain()[1] * d.slope + d.intercept)
+ })
+ .style('stroke', function (d, i, j) {
+ return color(d, j)
+ })
+ .style('stroke-opacity', function (d, i) {
+ return (d.disabled || typeof d.slope === 'undefined' || typeof d.intercept === 'undefined') ? 0 : 1
+ });
+
+ // Setup Axes
+ if (showXAxis) {
+ xAxis
+ .scale(x)
+ ._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
+ .tickSize( -availableHeight , 0);
+
+ g.select('.nv-x.nv-axis')
+ .attr('transform', 'translate(0,' + y.range()[0] + ')')
+ .call(xAxis);
+ }
+
+ if (showYAxis) {
+ yAxis
+ .scale(y)
+ ._ticks( nv.utils.calcTicksY(availableHeight/36, data) )
+ .tickSize( -availableWidth, 0);
+
+ g.select('.nv-y.nv-axis')
+ .call(yAxis);
+ }
+
+
+ if (showDistX) {
+ distX
+ .getData(scatter.x())
+ .scale(x)
+ .width(availableWidth)
+ .color(data.map(function(d,i) {
+ return d.color || color(d, i);
+ }).filter(function(d,i) { return !data[i].disabled }));
+ gEnter.select('.nv-distWrap').append('g')
+ .attr('class', 'nv-distributionX');
+ g.select('.nv-distributionX')
+ .attr('transform', 'translate(0,' + y.range()[0] + ')')
+ .datum(data.filter(function(d) { return !d.disabled }))
+ .call(distX);
+ }
+
+ if (showDistY) {
+ distY
+ .getData(scatter.y())
+ .scale(y)
+ .width(availableHeight)
+ .color(data.map(function(d,i) {
+ return d.color || color(d, i);
+ }).filter(function(d,i) { return !data[i].disabled }));
+ gEnter.select('.nv-distWrap').append('g')
+ .attr('class', 'nv-distributionY');
+ g.select('.nv-distributionY')
+ .attr('transform', 'translate(' + (rightAlignYAxis ? availableWidth : -distY.size() ) + ',0)')
+ .datum(data.filter(function(d) { return !d.disabled }))
+ .call(distY);
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (in chart's scope)
+ //------------------------------------------------------------
+
+ legend.dispatch.on('stateChange', function(newState) {
+ for (var key in newState)
+ state[key] = newState[key];
+ dispatch.stateChange(state);
+ chart.update();
+ });
+
+ // Update chart from a state object passed to event handler
+ dispatch.on('changeState', function(e) {
+ if (typeof e.disabled !== 'undefined') {
+ data.forEach(function(series,i) {
+ series.disabled = e.disabled[i];
+ });
+ state.disabled = e.disabled;
+ }
+ chart.update();
+ });
+
+ // mouseover needs availableHeight so we just keep scatter mouse events inside the chart block
+ scatter.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true);
+ container.select('.nv-chart-' + scatter.id() + ' .nv-series-' + evt.seriesIndex + ' .nv-distx-' + evt.pointIndex)
+ .attr('y1', 0);
+ container.select('.nv-chart-' + scatter.id() + ' .nv-series-' + evt.seriesIndex + ' .nv-disty-' + evt.pointIndex)
+ .attr('x2', distY.size());
+ });
+
+ scatter.dispatch.on('elementMouseover.tooltip', function(evt) {
+ container.select('.nv-series-' + evt.seriesIndex + ' .nv-distx-' + evt.pointIndex)
+ .attr('y1', evt.pos.top - availableHeight - margin.top);
+ container.select('.nv-series-' + evt.seriesIndex + ' .nv-disty-' + evt.pointIndex)
+ .attr('x2', evt.pos.left + distX.size() - margin.left);
+ tooltip.position(evt.pos).data(evt).hidden(false);
+ });
+
+ //store old scales for use in transitions on update
+ x0 = x.copy();
+ y0 = y.copy();
+
+ });
+
+ renderWatch.renderEnd('scatter with line immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ // expose chart's sub-components
+ chart.dispatch = dispatch;
+ chart.scatter = scatter;
+ chart.legend = legend;
+ chart.xAxis = xAxis;
+ chart.yAxis = yAxis;
+ chart.distX = distX;
+ chart.distY = distY;
+ chart.tooltip = tooltip;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ container: {get: function(){return container;}, set: function(_){container=_;}},
+ showDistX: {get: function(){return showDistX;}, set: function(_){showDistX=_;}},
+ showDistY: {get: function(){return showDistY;}, set: function(_){showDistY=_;}},
+ showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
+ showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
+ showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
+ defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+ duration: {get: function(){return duration;}, set: function(_){duration=_;}},
+
+ // deprecated options
+ tooltips: {get: function(){return tooltip.enabled();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltips', 'use chart.tooltip.enabled() instead');
+ tooltip.enabled(!!_);
+ }},
+ tooltipContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'use chart.tooltip.contentGenerator() instead');
+ tooltip.contentGenerator(_);
+ }},
+ tooltipXContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'This option is removed, put values into main tooltip.');
+ }},
+ tooltipYContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'This option is removed, put values into main tooltip.');
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
+ rightAlignYAxis = _;
+ yAxis.orient( (_) ? 'right' : 'left');
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ legend.color(color);
+ distX.color(color);
+ distY.color(color);
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, scatter);
+ nv.utils.initOptions(chart);
+ return chart;
+};
+
+nv.models.sparkline = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 2, right: 0, bottom: 2, left: 0}
+ , width = 400
+ , height = 32
+ , container = null
+ , animate = true
+ , x = d3.scale.linear()
+ , y = d3.scale.linear()
+ , getX = function(d) { return d.x }
+ , getY = function(d) { return d.y }
+ , color = nv.utils.getColor(['#000'])
+ , xDomain
+ , yDomain
+ , xRange
+ , yRange
+ ;
+
+ function chart(selection) {
+ selection.each(function(data) {
+ var availableWidth = width - margin.left - margin.right,
+ availableHeight = height - margin.top - margin.bottom;
+
+ container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ // Setup Scales
+ x .domain(xDomain || d3.extent(data, getX ))
+ .range(xRange || [0, availableWidth]);
+
+ y .domain(yDomain || d3.extent(data, getY ))
+ .range(yRange || [availableHeight, 0]);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-sparkline').data([data]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sparkline');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
+
+ var paths = wrap.selectAll('path')
+ .data(function(d) { return [d] });
+ paths.enter().append('path');
+ paths.exit().remove();
+ paths
+ .style('stroke', function(d,i) { return d.color || color(d, i) })
+ .attr('d', d3.svg.line()
+ .x(function(d,i) { return x(getX(d,i)) })
+ .y(function(d,i) { return y(getY(d,i)) })
+ );
+
+ // TODO: Add CURRENT data point (Need Min, Mac, Current / Most recent)
+ var points = wrap.selectAll('circle.nv-point')
+ .data(function(data) {
+ var yValues = data.map(function(d, i) { return getY(d,i); });
+ function pointIndex(index) {
+ if (index != -1) {
+ var result = data[index];
+ result.pointIndex = index;
+ return result;
+ } else {
+ return null;
+ }
+ }
+ var maxPoint = pointIndex(yValues.lastIndexOf(y.domain()[1])),
+ minPoint = pointIndex(yValues.indexOf(y.domain()[0])),
+ currentPoint = pointIndex(yValues.length - 1);
+ return [minPoint, maxPoint, currentPoint].filter(function (d) {return d != null;});
+ });
+ points.enter().append('circle');
+ points.exit().remove();
+ points
+ .attr('cx', function(d,i) { return x(getX(d,d.pointIndex)) })
+ .attr('cy', function(d,i) { return y(getY(d,d.pointIndex)) })
+ .attr('r', 2)
+ .attr('class', function(d,i) {
+ return getX(d, d.pointIndex) == x.domain()[1] ? 'nv-point nv-currentValue' :
+ getY(d, d.pointIndex) == y.domain()[0] ? 'nv-point nv-minValue' : 'nv-point nv-maxValue'
+ });
+ });
+
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
+ yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
+ xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
+ yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
+ xScale: {get: function(){return x;}, set: function(_){x=_;}},
+ yScale: {get: function(){return y;}, set: function(_){y=_;}},
+ animate: {get: function(){return animate;}, set: function(_){animate=_;}},
+
+ //functor options
+ x: {get: function(){return getX;}, set: function(_){getX=d3.functor(_);}},
+ y: {get: function(){return getY;}, set: function(_){getY=d3.functor(_);}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+ return chart;
+};
+
+nv.models.sparklinePlus = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var sparkline = nv.models.sparkline();
+
+ var margin = {top: 15, right: 100, bottom: 10, left: 50}
+ , width = null
+ , height = null
+ , x
+ , y
+ , index = []
+ , paused = false
+ , xTickFormat = d3.format(',r')
+ , yTickFormat = d3.format(',.2f')
+ , showLastValue = true
+ , alignValue = true
+ , rightAlignValue = false
+ , noData = null
+ ;
+
+ function chart(selection) {
+ selection.each(function(data) {
+ var container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ chart.update = function() { chart(selection) };
+ chart.container = this;
+
+ // Display No Data message if there's nothing to show.
+ if (!data || !data.length) {
+ nv.utils.noData(chart, container)
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ var currentValue = sparkline.y()(data[data.length-1], data.length-1);
+
+ // Setup Scales
+ x = sparkline.xScale();
+ y = sparkline.yScale();
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-sparklineplus').data([data]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sparklineplus');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-sparklineWrap');
+ gEnter.append('g').attr('class', 'nv-valueWrap');
+ gEnter.append('g').attr('class', 'nv-hoverArea');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ // Main Chart Component(s)
+ var sparklineWrap = g.select('.nv-sparklineWrap');
+
+ sparkline.width(availableWidth).height(availableHeight);
+ sparklineWrap.call(sparkline);
+
+ if (showLastValue) {
+ var valueWrap = g.select('.nv-valueWrap');
+ var value = valueWrap.selectAll('.nv-currentValue')
+ .data([currentValue]);
+
+ value.enter().append('text').attr('class', 'nv-currentValue')
+ .attr('dx', rightAlignValue ? -8 : 8)
+ .attr('dy', '.9em')
+ .style('text-anchor', rightAlignValue ? 'end' : 'start');
+
+ value
+ .attr('x', availableWidth + (rightAlignValue ? margin.right : 0))
+ .attr('y', alignValue ? function (d) {
+ return y(d)
+ } : 0)
+ .style('fill', sparkline.color()(data[data.length - 1], data.length - 1))
+ .text(yTickFormat(currentValue));
+ }
+
+ gEnter.select('.nv-hoverArea').append('rect')
+ .on('mousemove', sparklineHover)
+ .on('click', function() { paused = !paused })
+ .on('mouseout', function() { index = []; updateValueLine(); });
+
+ g.select('.nv-hoverArea rect')
+ .attr('transform', function(d) { return 'translate(' + -margin.left + ',' + -margin.top + ')' })
+ .attr('width', availableWidth + margin.left + margin.right)
+ .attr('height', availableHeight + margin.top);
+
+ //index is currently global (within the chart), may or may not keep it that way
+ function updateValueLine() {
+ if (paused) return;
+
+ var hoverValue = g.selectAll('.nv-hoverValue').data(index);
+
+ var hoverEnter = hoverValue.enter()
+ .append('g').attr('class', 'nv-hoverValue')
+ .style('stroke-opacity', 0)
+ .style('fill-opacity', 0);
+
+ hoverValue.exit()
+ .transition().duration(250)
+ .style('stroke-opacity', 0)
+ .style('fill-opacity', 0)
+ .remove();
+
+ hoverValue
+ .attr('transform', function(d) { return 'translate(' + x(sparkline.x()(data[d],d)) + ',0)' })
+ .transition().duration(250)
+ .style('stroke-opacity', 1)
+ .style('fill-opacity', 1);
+
+ if (!index.length) return;
+
+ hoverEnter.append('line')
+ .attr('x1', 0)
+ .attr('y1', -margin.top)
+ .attr('x2', 0)
+ .attr('y2', availableHeight);
+
+ hoverEnter.append('text').attr('class', 'nv-xValue')
+ .attr('x', -6)
+ .attr('y', -margin.top)
+ .attr('text-anchor', 'end')
+ .attr('dy', '.9em');
+
+ g.select('.nv-hoverValue .nv-xValue')
+ .text(xTickFormat(sparkline.x()(data[index[0]], index[0])));
+
+ hoverEnter.append('text').attr('class', 'nv-yValue')
+ .attr('x', 6)
+ .attr('y', -margin.top)
+ .attr('text-anchor', 'start')
+ .attr('dy', '.9em');
+
+ g.select('.nv-hoverValue .nv-yValue')
+ .text(yTickFormat(sparkline.y()(data[index[0]], index[0])));
+ }
+
+ function sparklineHover() {
+ if (paused) return;
+
+ var pos = d3.mouse(this)[0] - margin.left;
+
+ function getClosestIndex(data, x) {
+ var distance = Math.abs(sparkline.x()(data[0], 0) - x);
+ var closestIndex = 0;
+ for (var i = 0; i < data.length; i++){
+ if (Math.abs(sparkline.x()(data[i], i) - x) < distance) {
+ distance = Math.abs(sparkline.x()(data[i], i) - x);
+ closestIndex = i;
+ }
+ }
+ return closestIndex;
+ }
+
+ index = [getClosestIndex(data, Math.round(x.invert(pos)))];
+ updateValueLine();
+ }
+
+ });
+
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ // expose chart's sub-components
+ chart.sparkline = sparkline;
+
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ xTickFormat: {get: function(){return xTickFormat;}, set: function(_){xTickFormat=_;}},
+ yTickFormat: {get: function(){return yTickFormat;}, set: function(_){yTickFormat=_;}},
+ showLastValue: {get: function(){return showLastValue;}, set: function(_){showLastValue=_;}},
+ alignValue: {get: function(){return alignValue;}, set: function(_){alignValue=_;}},
+ rightAlignValue: {get: function(){return rightAlignValue;}, set: function(_){rightAlignValue=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, sparkline);
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+
+nv.models.stackedArea = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = 960
+ , height = 500
+ , color = nv.utils.defaultColor() // a function that computes the color
+ , id = Math.floor(Math.random() * 100000) //Create semi-unique ID incase user doesn't selet one
+ , container = null
+ , getX = function(d) { return d.x } // accessor to get the x value from a data point
+ , getY = function(d) { return d.y } // accessor to get the y value from a data point
+ , style = 'stack'
+ , offset = 'zero'
+ , order = 'default'
+ , interpolate = 'linear' // controls the line interpolation
+ , clipEdge = false // if true, masks lines within x and y scale
+ , x //can be accessed via chart.xScale()
+ , y //can be accessed via chart.yScale()
+ , scatter = nv.models.scatter()
+ , duration = 250
+ , dispatch = d3.dispatch('areaClick', 'areaMouseover', 'areaMouseout','renderEnd', 'elementClick', 'elementMouseover', 'elementMouseout')
+ ;
+
+ scatter
+ .pointSize(2.2) // default size
+ .pointDomain([2.2, 2.2]) // all the same size by default
+ ;
+
+ /************************************
+ * offset:
+ * 'wiggle' (stream)
+ * 'zero' (stacked)
+ * 'expand' (normalize to 100%)
+ * 'silhouette' (simple centered)
+ *
+ * order:
+ * 'inside-out' (stream)
+ * 'default' (input order)
+ ************************************/
+
+ var renderWatch = nv.utils.renderWatch(dispatch, duration);
+
+ function chart(selection) {
+ renderWatch.reset();
+ renderWatch.models(scatter);
+ selection.each(function(data) {
+ var availableWidth = width - margin.left - margin.right,
+ availableHeight = height - margin.top - margin.bottom;
+
+ container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ // Setup Scales
+ x = scatter.xScale();
+ y = scatter.yScale();
+
+ var dataRaw = data;
+ // Injecting point index into each point because d3.layout.stack().out does not give index
+ data.forEach(function(aseries, i) {
+ aseries.seriesIndex = i;
+ aseries.values = aseries.values.map(function(d, j) {
+ d.index = j;
+ d.seriesIndex = i;
+ return d;
+ });
+ });
+
+ var dataFiltered = data.filter(function(series) {
+ return !series.disabled;
+ });
+
+ data = d3.layout.stack()
+ .order(order)
+ .offset(offset)
+ .values(function(d) { return d.values }) //TODO: make values customizeable in EVERY model in this fashion
+ .x(getX)
+ .y(getY)
+ .out(function(d, y0, y) {
+ d.display = {
+ y: y,
+ y0: y0
+ };
+ })
+ (dataFiltered);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-stackedarea').data([data]);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-stackedarea');
+ var defsEnter = wrapEnter.append('defs');
+ var gEnter = wrapEnter.append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-areaWrap');
+ gEnter.append('g').attr('class', 'nv-scatterWrap');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ // If the user has not specified forceY, make sure 0 is included in the domain
+ // Otherwise, use user-specified values for forceY
+ if (scatter.forceY().length == 0) {
+ scatter.forceY().push(0);
+ }
+
+ scatter
+ .width(availableWidth)
+ .height(availableHeight)
+ .x(getX)
+ .y(function(d) { return d.display.y + d.display.y0 })
+ .forceY([0])
+ .color(data.map(function(d,i) {
+ return d.color || color(d, d.seriesIndex);
+ }));
+
+ var scatterWrap = g.select('.nv-scatterWrap')
+ .datum(data);
+
+ scatterWrap.call(scatter);
+
+ defsEnter.append('clipPath')
+ .attr('id', 'nv-edge-clip-' + id)
+ .append('rect');
+
+ wrap.select('#nv-edge-clip-' + id + ' rect')
+ .attr('width', availableWidth)
+ .attr('height', availableHeight);
+
+ g.attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : '');
+
+ var area = d3.svg.area()
+ .x(function(d,i) { return x(getX(d,i)) })
+ .y0(function(d) {
+ return y(d.display.y0)
+ })
+ .y1(function(d) {
+ return y(d.display.y + d.display.y0)
+ })
+ .interpolate(interpolate);
+
+ var zeroArea = d3.svg.area()
+ .x(function(d,i) { return x(getX(d,i)) })
+ .y0(function(d) { return y(d.display.y0) })
+ .y1(function(d) { return y(d.display.y0) });
+
+ var path = g.select('.nv-areaWrap').selectAll('path.nv-area')
+ .data(function(d) { return d });
+
+ path.enter().append('path').attr('class', function(d,i) { return 'nv-area nv-area-' + i })
+ .attr('d', function(d,i){
+ return zeroArea(d.values, d.seriesIndex);
+ })
+ .on('mouseover', function(d,i) {
+ d3.select(this).classed('hover', true);
+ dispatch.areaMouseover({
+ point: d,
+ series: d.key,
+ pos: [d3.event.pageX, d3.event.pageY],
+ seriesIndex: d.seriesIndex
+ });
+ })
+ .on('mouseout', function(d,i) {
+ d3.select(this).classed('hover', false);
+ dispatch.areaMouseout({
+ point: d,
+ series: d.key,
+ pos: [d3.event.pageX, d3.event.pageY],
+ seriesIndex: d.seriesIndex
+ });
+ })
+ .on('click', function(d,i) {
+ d3.select(this).classed('hover', false);
+ dispatch.areaClick({
+ point: d,
+ series: d.key,
+ pos: [d3.event.pageX, d3.event.pageY],
+ seriesIndex: d.seriesIndex
+ });
+ });
+
+ path.exit().remove();
+ path.style('fill', function(d,i){
+ return d.color || color(d, d.seriesIndex)
+ })
+ .style('stroke', function(d,i){ return d.color || color(d, d.seriesIndex) });
+ path.watchTransition(renderWatch,'stackedArea path')
+ .attr('d', function(d,i) {
+ return area(d.values,i)
+ });
+
+ //============================================================
+ // Event Handling/Dispatching (in chart's scope)
+ //------------------------------------------------------------
+
+ scatter.dispatch.on('elementMouseover.area', function(e) {
+ g.select('.nv-chart-' + id + ' .nv-area-' + e.seriesIndex).classed('hover', true);
+ });
+ scatter.dispatch.on('elementMouseout.area', function(e) {
+ g.select('.nv-chart-' + id + ' .nv-area-' + e.seriesIndex).classed('hover', false);
+ });
+
+ //Special offset functions
+ chart.d3_stackedOffset_stackPercent = function(stackData) {
+ var n = stackData.length, //How many series
+ m = stackData[0].length, //how many points per series
+ i,
+ j,
+ o,
+ y0 = [];
+
+ for (j = 0; j < m; ++j) { //Looping through all points
+ for (i = 0, o = 0; i < dataRaw.length; i++) { //looping through all series
+ o += getY(dataRaw[i].values[j]); //total y value of all series at a certian point in time.
+ }
+
+ if (o) for (i = 0; i < n; i++) { //(total y value of all series at point in time i) != 0
+ stackData[i][j][1] /= o;
+ } else { //(total y value of all series at point in time i) == 0
+ for (i = 0; i < n; i++) {
+ stackData[i][j][1] = 0;
+ }
+ }
+ }
+ for (j = 0; j < m; ++j) y0[j] = 0;
+ return y0;
+ };
+
+ });
+
+ renderWatch.renderEnd('stackedArea immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Global getters and setters
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.scatter = scatter;
+
+ scatter.dispatch.on('elementClick', function(){ dispatch.elementClick.apply(this, arguments); });
+ scatter.dispatch.on('elementMouseover', function(){ dispatch.elementMouseover.apply(this, arguments); });
+ scatter.dispatch.on('elementMouseout', function(){ dispatch.elementMouseout.apply(this, arguments); });
+
+ chart.interpolate = function(_) {
+ if (!arguments.length) return interpolate;
+ interpolate = _;
+ return chart;
+ };
+
+ chart.duration = function(_) {
+ if (!arguments.length) return duration;
+ duration = _;
+ renderWatch.reset(duration);
+ scatter.duration(duration);
+ return chart;
+ };
+
+ chart.dispatch = dispatch;
+ chart.scatter = scatter;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
+ offset: {get: function(){return offset;}, set: function(_){offset=_;}},
+ order: {get: function(){return order;}, set: function(_){order=_;}},
+ interpolate: {get: function(){return interpolate;}, set: function(_){interpolate=_;}},
+
+ // simple functor options
+ x: {get: function(){return getX;}, set: function(_){getX = d3.functor(_);}},
+ y: {get: function(){return getY;}, set: function(_){getY = d3.functor(_);}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ }},
+ style: {get: function(){return style;}, set: function(_){
+ style = _;
+ switch (style) {
+ case 'stack':
+ chart.offset('zero');
+ chart.order('default');
+ break;
+ case 'stream':
+ chart.offset('wiggle');
+ chart.order('inside-out');
+ break;
+ case 'stream-center':
+ chart.offset('silhouette');
+ chart.order('inside-out');
+ break;
+ case 'expand':
+ chart.offset('expand');
+ chart.order('default');
+ break;
+ case 'stack_percent':
+ chart.offset(chart.d3_stackedOffset_stackPercent);
+ chart.order('default');
+ break;
+ }
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ scatter.duration(duration);
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, scatter);
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+
+nv.models.stackedAreaChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var stacked = nv.models.stackedArea()
+ , xAxis = nv.models.axis()
+ , yAxis = nv.models.axis()
+ , legend = nv.models.legend()
+ , controls = nv.models.legend()
+ , interactiveLayer = nv.interactiveGuideline()
+ , tooltip = nv.models.tooltip()
+ ;
+
+ var margin = {top: 30, right: 25, bottom: 50, left: 60}
+ , width = null
+ , height = null
+ , color = nv.utils.defaultColor()
+ , showControls = true
+ , showLegend = true
+ , showXAxis = true
+ , showYAxis = true
+ , rightAlignYAxis = false
+ , useInteractiveGuideline = false
+ , x //can be accessed via chart.xScale()
+ , y //can be accessed via chart.yScale()
+ , state = nv.utils.state()
+ , defaultState = null
+ , noData = null
+ , dispatch = d3.dispatch('stateChange', 'changeState','renderEnd')
+ , controlWidth = 250
+ , controlOptions = ['Stacked','Stream','Expanded']
+ , controlLabels = {}
+ , duration = 250
+ ;
+
+ state.style = stacked.style();
+ xAxis.orient('bottom').tickPadding(7);
+ yAxis.orient((rightAlignYAxis) ? 'right' : 'left');
+
+ tooltip
+ .headerFormatter(function(d, i) {
+ return xAxis.tickFormat()(d, i);
+ })
+ .valueFormatter(function(d, i) {
+ return yAxis.tickFormat()(d, i);
+ });
+
+ interactiveLayer.tooltip
+ .headerFormatter(function(d, i) {
+ return xAxis.tickFormat()(d, i);
+ })
+ .valueFormatter(function(d, i) {
+ return yAxis.tickFormat()(d, i);
+ });
+
+ var oldYTickFormat = null,
+ oldValueFormatter = null;
+
+ controls.updateState(false);
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var renderWatch = nv.utils.renderWatch(dispatch);
+ var style = stacked.style();
+
+ var stateGetter = function(data) {
+ return function(){
+ return {
+ active: data.map(function(d) { return !d.disabled }),
+ style: stacked.style()
+ };
+ }
+ };
+
+ var stateSetter = function(data) {
+ return function(state) {
+ if (state.style !== undefined)
+ style = state.style;
+ if (state.active !== undefined)
+ data.forEach(function(series,i) {
+ series.disabled = !state.active[i];
+ });
+ }
+ };
+
+ var percentFormatter = d3.format('%');
+
+ function chart(selection) {
+ renderWatch.reset();
+ renderWatch.models(stacked);
+ if (showXAxis) renderWatch.models(xAxis);
+ if (showYAxis) renderWatch.models(yAxis);
+
+ selection.each(function(data) {
+ var container = d3.select(this),
+ that = this;
+ nv.utils.initSVG(container);
+
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ chart.update = function() { container.transition().duration(duration).call(chart); };
+ chart.container = this;
+
+ state
+ .setter(stateSetter(data), chart.update)
+ .getter(stateGetter(data))
+ .update();
+
+ // DEPRECATED set state.disabled
+ state.disabled = data.map(function(d) { return !!d.disabled });
+
+ if (!defaultState) {
+ var key;
+ defaultState = {};
+ for (key in state) {
+ if (state[key] instanceof Array)
+ defaultState[key] = state[key].slice(0);
+ else
+ defaultState[key] = state[key];
+ }
+ }
+
+ // Display No Data message if there's nothing to show.
+ if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
+ nv.utils.noData(chart, container)
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ // Setup Scales
+ x = stacked.xScale();
+ y = stacked.yScale();
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-stackedAreaChart').data([data]);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-stackedAreaChart').append('g');
+ var g = wrap.select('g');
+
+ gEnter.append("rect").style("opacity",0);
+ gEnter.append('g').attr('class', 'nv-x nv-axis');
+ gEnter.append('g').attr('class', 'nv-y nv-axis');
+ gEnter.append('g').attr('class', 'nv-stackedWrap');
+ gEnter.append('g').attr('class', 'nv-legendWrap');
+ gEnter.append('g').attr('class', 'nv-controlsWrap');
+ gEnter.append('g').attr('class', 'nv-interactive');
+
+ g.select("rect").attr("width",availableWidth).attr("height",availableHeight);
+
+ // Legend
+ if (showLegend) {
+ var legendWidth = (showControls) ? availableWidth - controlWidth : availableWidth;
+
+ legend.width(legendWidth);
+ g.select('.nv-legendWrap').datum(data).call(legend);
+
+ if ( margin.top != legend.height()) {
+ margin.top = legend.height();
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+ }
+
+ g.select('.nv-legendWrap')
+ .attr('transform', 'translate(' + (availableWidth-legendWidth) + ',' + (-margin.top) +')');
+ }
+
+ // Controls
+ if (showControls) {
+ var controlsData = [
+ {
+ key: controlLabels.stacked || 'Stacked',
+ metaKey: 'Stacked',
+ disabled: stacked.style() != 'stack',
+ style: 'stack'
+ },
+ {
+ key: controlLabels.stream || 'Stream',
+ metaKey: 'Stream',
+ disabled: stacked.style() != 'stream',
+ style: 'stream'
+ },
+ {
+ key: controlLabels.expanded || 'Expanded',
+ metaKey: 'Expanded',
+ disabled: stacked.style() != 'expand',
+ style: 'expand'
+ },
+ {
+ key: controlLabels.stack_percent || 'Stack %',
+ metaKey: 'Stack_Percent',
+ disabled: stacked.style() != 'stack_percent',
+ style: 'stack_percent'
+ }
+ ];
+
+ controlWidth = (controlOptions.length/3) * 260;
+ controlsData = controlsData.filter(function(d) {
+ return controlOptions.indexOf(d.metaKey) !== -1;
+ });
+
+ controls
+ .width( controlWidth )
+ .color(['#444', '#444', '#444']);
+
+ g.select('.nv-controlsWrap')
+ .datum(controlsData)
+ .call(controls);
+
+ if ( margin.top != Math.max(controls.height(), legend.height()) ) {
+ margin.top = Math.max(controls.height(), legend.height());
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+ }
+
+ g.select('.nv-controlsWrap')
+ .attr('transform', 'translate(0,' + (-margin.top) +')');
+ }
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ if (rightAlignYAxis) {
+ g.select(".nv-y.nv-axis")
+ .attr("transform", "translate(" + availableWidth + ",0)");
+ }
+
+ //Set up interactive layer
+ if (useInteractiveGuideline) {
+ interactiveLayer
+ .width(availableWidth)
+ .height(availableHeight)
+ .margin({left: margin.left, top: margin.top})
+ .svgContainer(container)
+ .xScale(x);
+ wrap.select(".nv-interactive").call(interactiveLayer);
+ }
+
+ stacked
+ .width(availableWidth)
+ .height(availableHeight);
+
+ var stackedWrap = g.select('.nv-stackedWrap')
+ .datum(data);
+
+ stackedWrap.transition().call(stacked);
+
+ // Setup Axes
+ if (showXAxis) {
+ xAxis.scale(x)
+ ._ticks( nv.utils.calcTicksX(availableWidth/100, data) )
+ .tickSize( -availableHeight, 0);
+
+ g.select('.nv-x.nv-axis')
+ .attr('transform', 'translate(0,' + availableHeight + ')');
+
+ g.select('.nv-x.nv-axis')
+ .transition().duration(0)
+ .call(xAxis);
+ }
+
+ if (showYAxis) {
+ var ticks;
+ if (stacked.offset() === 'wiggle') {
+ ticks = 0;
+ }
+ else {
+ ticks = nv.utils.calcTicksY(availableHeight/36, data);
+ }
+ yAxis.scale(y)
+ ._ticks(ticks)
+ .tickSize(-availableWidth, 0);
+
+ if (stacked.style() === 'expand' || stacked.style() === 'stack_percent') {
+ var currentFormat = yAxis.tickFormat();
+
+ if ( !oldYTickFormat || currentFormat !== percentFormatter )
+ oldYTickFormat = currentFormat;
+
+ //Forces the yAxis to use percentage in 'expand' mode.
+ yAxis.tickFormat(percentFormatter);
+ }
+ else {
+ if (oldYTickFormat) {
+ yAxis.tickFormat(oldYTickFormat);
+ oldYTickFormat = null;
+ }
+ }
+
+ g.select('.nv-y.nv-axis')
+ .transition().duration(0)
+ .call(yAxis);
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (in chart's scope)
+ //------------------------------------------------------------
+
+ stacked.dispatch.on('areaClick.toggle', function(e) {
+ if (data.filter(function(d) { return !d.disabled }).length === 1)
+ data.forEach(function(d) {
+ d.disabled = false;
+ });
+ else
+ data.forEach(function(d,i) {
+ d.disabled = (i != e.seriesIndex);
+ });
+
+ state.disabled = data.map(function(d) { return !!d.disabled });
+ dispatch.stateChange(state);
+
+ chart.update();
+ });
+
+ legend.dispatch.on('stateChange', function(newState) {
+ for (var key in newState)
+ state[key] = newState[key];
+ dispatch.stateChange(state);
+ chart.update();
+ });
+
+ controls.dispatch.on('legendClick', function(d,i) {
+ if (!d.disabled) return;
+
+ controlsData = controlsData.map(function(s) {
+ s.disabled = true;
+ return s;
+ });
+ d.disabled = false;
+
+ stacked.style(d.style);
+
+
+ state.style = stacked.style();
+ dispatch.stateChange(state);
+
+ chart.update();
+ });
+
+ interactiveLayer.dispatch.on('elementMousemove', function(e) {
+ stacked.clearHighlights();
+ var singlePoint, pointIndex, pointXLocation, allData = [];
+ data
+ .filter(function(series, i) {
+ series.seriesIndex = i;
+ return !series.disabled;
+ })
+ .forEach(function(series,i) {
+ pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
+ var point = series.values[pointIndex];
+ var pointYValue = chart.y()(point, pointIndex);
+ if (pointYValue != null) {
+ stacked.highlightPoint(i, pointIndex, true);
+ }
+ if (typeof point === 'undefined') return;
+ if (typeof singlePoint === 'undefined') singlePoint = point;
+ if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
+
+ //If we are in 'expand' mode, use the stacked percent value instead of raw value.
+ var tooltipValue = (stacked.style() == 'expand') ? point.display.y : chart.y()(point,pointIndex);
+ allData.push({
+ key: series.key,
+ value: tooltipValue,
+ color: color(series,series.seriesIndex),
+ stackedValue: point.display
+ });
+ });
+
+ allData.reverse();
+
+ //Highlight the tooltip entry based on which stack the mouse is closest to.
+ if (allData.length > 2) {
+ var yValue = chart.yScale().invert(e.mouseY);
+ var yDistMax = Infinity, indexToHighlight = null;
+ allData.forEach(function(series,i) {
+
+ //To handle situation where the stacked area chart is negative, we need to use absolute values
+ //when checking if the mouse Y value is within the stack area.
+ yValue = Math.abs(yValue);
+ var stackedY0 = Math.abs(series.stackedValue.y0);
+ var stackedY = Math.abs(series.stackedValue.y);
+ if ( yValue >= stackedY0 && yValue <= (stackedY + stackedY0))
+ {
+ indexToHighlight = i;
+ return;
+ }
+ });
+ if (indexToHighlight != null)
+ allData[indexToHighlight].highlight = true;
+ }
+
+ var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex));
+
+ var valueFormatter = interactiveLayer.tooltip.valueFormatter();
+ // Keeps track of the tooltip valueFormatter if the chart changes to expanded view
+ if (stacked.style() === 'expand' || stacked.style() === 'stack_percent') {
+ if ( !oldValueFormatter ) {
+ oldValueFormatter = valueFormatter;
+ }
+ //Forces the tooltip to use percentage in 'expand' mode.
+ valueFormatter = d3.format(".1%");
+ }
+ else {
+ if (oldValueFormatter) {
+ valueFormatter = oldValueFormatter;
+ oldValueFormatter = null;
+ }
+ }
+
+ interactiveLayer.tooltip
+ .position({left: pointXLocation + margin.left, top: e.mouseY + margin.top})
+ .chartContainer(that.parentNode)
+ .valueFormatter(valueFormatter)
+ .data(
+ {
+ value: xValue,
+ series: allData
+ }
+ )();
+
+ interactiveLayer.renderGuideLine(pointXLocation);
+
+ });
+
+ interactiveLayer.dispatch.on("elementMouseout",function(e) {
+ stacked.clearHighlights();
+ });
+
+ // Update chart from a state object passed to event handler
+ dispatch.on('changeState', function(e) {
+
+ if (typeof e.disabled !== 'undefined' && data.length === e.disabled.length) {
+ data.forEach(function(series,i) {
+ series.disabled = e.disabled[i];
+ });
+
+ state.disabled = e.disabled;
+ }
+
+ if (typeof e.style !== 'undefined') {
+ stacked.style(e.style);
+ style = e.style;
+ }
+
+ chart.update();
+ });
+
+ });
+
+ renderWatch.renderEnd('stacked Area chart immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (out of chart's scope)
+ //------------------------------------------------------------
+
+ stacked.dispatch.on('elementMouseover.tooltip', function(evt) {
+ evt.point['x'] = stacked.x()(evt.point);
+ evt.point['y'] = stacked.y()(evt.point);
+ tooltip.data(evt).position(evt.pos).hidden(false);
+ });
+
+ stacked.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true)
+ });
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ // expose chart's sub-components
+ chart.dispatch = dispatch;
+ chart.stacked = stacked;
+ chart.legend = legend;
+ chart.controls = controls;
+ chart.xAxis = xAxis;
+ chart.yAxis = yAxis;
+ chart.interactiveLayer = interactiveLayer;
+ chart.tooltip = tooltip;
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}},
+ showXAxis: {get: function(){return showXAxis;}, set: function(_){showXAxis=_;}},
+ showYAxis: {get: function(){return showYAxis;}, set: function(_){showYAxis=_;}},
+ defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+ showControls: {get: function(){return showControls;}, set: function(_){showControls=_;}},
+ controlLabels: {get: function(){return controlLabels;}, set: function(_){controlLabels=_;}},
+ controlOptions: {get: function(){return controlOptions;}, set: function(_){controlOptions=_;}},
+
+ // deprecated options
+ tooltips: {get: function(){return tooltip.enabled();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltips', 'use chart.tooltip.enabled() instead');
+ tooltip.enabled(!!_);
+ }},
+ tooltipContent: {get: function(){return tooltip.contentGenerator();}, set: function(_){
+ // deprecated after 1.7.1
+ nv.deprecated('tooltipContent', 'use chart.tooltip.contentGenerator() instead');
+ tooltip.contentGenerator(_);
+ }},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ stacked.duration(duration);
+ xAxis.duration(duration);
+ yAxis.duration(duration);
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color = nv.utils.getColor(_);
+ legend.color(color);
+ stacked.color(color);
+ }},
+ rightAlignYAxis: {get: function(){return rightAlignYAxis;}, set: function(_){
+ rightAlignYAxis = _;
+ yAxis.orient( rightAlignYAxis ? 'right' : 'left');
+ }},
+ useInteractiveGuideline: {get: function(){return useInteractiveGuideline;}, set: function(_){
+ useInteractiveGuideline = !!_;
+ chart.interactive(!_);
+ chart.useVoronoi(!_);
+ stacked.scatter.interactive(!_);
+ }}
+ });
+
+ nv.utils.inheritOptions(chart, stacked);
+ nv.utils.initOptions(chart);
+
+ return chart;
+};
+// based on http://bl.ocks.org/kerryrodden/477c1bfb081b783f80ad
+nv.models.sunburst = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var margin = {top: 0, right: 0, bottom: 0, left: 0}
+ , width = null
+ , height = null
+ , mode = "count"
+ , modes = {count: function(d) { return 1; }, size: function(d) { return d.size }}
+ , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
+ , container = null
+ , color = nv.utils.defaultColor()
+ , duration = 500
+ , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMousemove', 'elementMouseover', 'elementMouseout', 'renderEnd')
+ ;
+
+ var x = d3.scale.linear().range([0, 2 * Math.PI]);
+ var y = d3.scale.sqrt();
+
+ var partition = d3.layout.partition()
+ .sort(null)
+ .value(function(d) { return 1; });
+
+ var arc = d3.svg.arc()
+ .startAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); })
+ .endAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); })
+ .innerRadius(function(d) { return Math.max(0, y(d.y)); })
+ .outerRadius(function(d) { return Math.max(0, y(d.y + d.dy)); });
+
+ // Keep track of the current and previous node being displayed as the root.
+ var node, prevNode;
+ // Keep track of the root node
+ var rootNode;
+
+ //============================================================
+ // chart function
+ //------------------------------------------------------------
+
+ var renderWatch = nv.utils.renderWatch(dispatch);
+
+ function chart(selection) {
+ renderWatch.reset();
+ selection.each(function(data) {
+ container = d3.select(this);
+ var availableWidth = nv.utils.availableWidth(width, container, margin);
+ var availableHeight = nv.utils.availableHeight(height, container, margin);
+ var radius = Math.min(availableWidth, availableHeight) / 2;
+ var path;
+
+ nv.utils.initSVG(container);
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('.nv-wrap.nv-sunburst').data(data);
+ var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sunburst nv-chart-' + id);
+
+ var g = wrapEnter.selectAll('nv-sunburst');
+
+ wrap.attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');
+
+ container.on('click', function (d, i) {
+ dispatch.chartClick({
+ data: d,
+ index: i,
+ pos: d3.event,
+ id: id
+ });
+ });
+
+ y.range([0, radius]);
+
+ node = node || data;
+ rootNode = data[0];
+ partition.value(modes[mode] || modes["count"]);
+ path = g.data(partition.nodes).enter()
+ .append("path")
+ .attr("d", arc)
+ .style("fill", function (d) {
+ return color((d.children ? d : d.parent).name);
+ })
+ .style("stroke", "#FFF")
+ .on("click", function(d) {
+ if (prevNode !== node && node !== d) prevNode = node;
+ node = d;
+ path.transition()
+ .duration(duration)
+ .attrTween("d", arcTweenZoom(d));
+ })
+ .each(stash)
+ .on("dblclick", function(d) {
+ if (prevNode.parent == d) {
+ path.transition()
+ .duration(duration)
+ .attrTween("d", arcTweenZoom(rootNode));
+ }
+ })
+ .each(stash)
+ .on('mouseover', function(d,i){
+ d3.select(this).classed('hover', true).style('opacity', 0.8);
+ dispatch.elementMouseover({
+ data: d,
+ color: d3.select(this).style("fill")
+ });
+ })
+ .on('mouseout', function(d,i){
+ d3.select(this).classed('hover', false).style('opacity', 1);
+ dispatch.elementMouseout({
+ data: d
+ });
+ })
+ .on('mousemove', function(d,i){
+ dispatch.elementMousemove({
+ data: d
+ });
+ });
+
+
+
+ // Setup for switching data: stash the old values for transition.
+ function stash(d) {
+ d.x0 = d.x;
+ d.dx0 = d.dx;
+ }
+
+ // When switching data: interpolate the arcs in data space.
+ function arcTweenData(a, i) {
+ var oi = d3.interpolate({x: a.x0, dx: a.dx0}, a);
+
+ function tween(t) {
+ var b = oi(t);
+ a.x0 = b.x;
+ a.dx0 = b.dx;
+ return arc(b);
+ }
+
+ if (i == 0) {
+ // If we are on the first arc, adjust the x domain to match the root node
+ // at the current zoom level. (We only need to do this once.)
+ var xd = d3.interpolate(x.domain(), [node.x, node.x + node.dx]);
+ return function (t) {
+ x.domain(xd(t));
+ return tween(t);
+ };
+ } else {
+ return tween;
+ }
+ }
+
+ // When zooming: interpolate the scales.
+ function arcTweenZoom(d) {
+ var xd = d3.interpolate(x.domain(), [d.x, d.x + d.dx]),
+ yd = d3.interpolate(y.domain(), [d.y, 1]),
+ yr = d3.interpolate(y.range(), [d.y ? 20 : 0, radius]);
+ return function (d, i) {
+ return i
+ ? function (t) {
+ return arc(d);
+ }
+ : function (t) {
+ x.domain(xd(t));
+ y.domain(yd(t)).range(yr(t));
+ return arc(d);
+ };
+ };
+ }
+
+ });
+
+ renderWatch.renderEnd('sunburst immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ chart.dispatch = dispatch;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ width: {get: function(){return width;}, set: function(_){width=_;}},
+ height: {get: function(){return height;}, set: function(_){height=_;}},
+ mode: {get: function(){return mode;}, set: function(_){mode=_;}},
+ id: {get: function(){return id;}, set: function(_){id=_;}},
+ duration: {get: function(){return duration;}, set: function(_){duration=_;}},
+
+ // options that require extra logic in the setter
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top != undefined ? _.top : margin.top;
+ margin.right = _.right != undefined ? _.right : margin.right;
+ margin.bottom = _.bottom != undefined ? _.bottom : margin.bottom;
+ margin.left = _.left != undefined ? _.left : margin.left;
+ }},
+ color: {get: function(){return color;}, set: function(_){
+ color=nv.utils.getColor(_);
+ }}
+ });
+
+ nv.utils.initOptions(chart);
+ return chart;
+};
+nv.models.sunburstChart = function() {
+ "use strict";
+
+ //============================================================
+ // Public Variables with Default Settings
+ //------------------------------------------------------------
+
+ var sunburst = nv.models.sunburst();
+ var tooltip = nv.models.tooltip();
+
+ var margin = {top: 30, right: 20, bottom: 20, left: 20}
+ , width = null
+ , height = null
+ , color = nv.utils.defaultColor()
+ , id = Math.round(Math.random() * 100000)
+ , defaultState = null
+ , noData = null
+ , duration = 250
+ , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState','renderEnd')
+ ;
+
+ //============================================================
+ // Private Variables
+ //------------------------------------------------------------
+
+ var renderWatch = nv.utils.renderWatch(dispatch);
+ tooltip.headerEnabled(false).duration(0).valueFormatter(function(d, i) {
+ return d;
+ });
+
+ //============================================================
+ // Chart function
+ //------------------------------------------------------------
+
+ function chart(selection) {
+ renderWatch.reset();
+ renderWatch.models(sunburst);
+
+ selection.each(function(data) {
+ var container = d3.select(this);
+ nv.utils.initSVG(container);
+
+ var that = this;
+ var availableWidth = nv.utils.availableWidth(width, container, margin),
+ availableHeight = nv.utils.availableHeight(height, container, margin);
+
+ chart.update = function() {
+ if (duration === 0)
+ container.call(chart);
+ else
+ container.transition().duration(duration).call(chart)
+ };
+ chart.container = this;
+
+ // Display No Data message if there's nothing to show.
+ if (!data || !data.length) {
+ nv.utils.noData(chart, container);
+ return chart;
+ } else {
+ container.selectAll('.nv-noData').remove();
+ }
+
+ // Setup containers and skeleton of chart
+ var wrap = container.selectAll('g.nv-wrap.nv-sunburstChart').data(data);
+ var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sunburstChart').append('g');
+ var g = wrap.select('g');
+
+ gEnter.append('g').attr('class', 'nv-sunburstWrap');
+
+ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ // Main Chart Component(s)
+ sunburst.width(availableWidth).height(availableHeight);
+ var sunWrap = g.select('.nv-sunburstWrap').datum(data);
+ d3.transition(sunWrap).call(sunburst);
+
+ });
+
+ renderWatch.renderEnd('sunburstChart immediate');
+ return chart;
+ }
+
+ //============================================================
+ // Event Handling/Dispatching (out of chart's scope)
+ //------------------------------------------------------------
+
+ sunburst.dispatch.on('elementMouseover.tooltip', function(evt) {
+ evt['series'] = {
+ key: evt.data.name,
+ value: evt.data.size,
+ color: evt.color
+ };
+ tooltip.data(evt).hidden(false);
+ });
+
+ sunburst.dispatch.on('elementMouseout.tooltip', function(evt) {
+ tooltip.hidden(true);
+ });
+
+ sunburst.dispatch.on('elementMousemove.tooltip', function(evt) {
+ tooltip.position({top: d3.event.pageY, left: d3.event.pageX})();
+ });
+
+ //============================================================
+ // Expose Public Variables
+ //------------------------------------------------------------
+
+ // expose chart's sub-components
+ chart.dispatch = dispatch;
+ chart.sunburst = sunburst;
+ chart.tooltip = tooltip;
+ chart.options = nv.utils.optionsFunc.bind(chart);
+
+ // use Object get/set functionality to map between vars and chart functions
+ chart._options = Object.create({}, {
+ // simple options, just get/set the necessary values
+ noData: {get: function(){return noData;}, set: function(_){noData=_;}},
+ defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}},
+
+ // options that require extra logic in the setter
+ color: {get: function(){return color;}, set: function(_){
+ color = _;
+ sunburst.color(color);
+ }},
+ duration: {get: function(){return duration;}, set: function(_){
+ duration = _;
+ renderWatch.reset(duration);
+ sunburst.duration(duration);
+ }},
+ margin: {get: function(){return margin;}, set: function(_){
+ margin.top = _.top !== undefined ? _.top : margin.top;
+ margin.right = _.right !== undefined ? _.right : margin.right;
+ margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom;
+ margin.left = _.left !== undefined ? _.left : margin.left;
+ }}
+ });
+ nv.utils.inheritOptions(chart, sunburst);
+ nv.utils.initOptions(chart);
+ return chart;
+};
+
+nv.version = "1.8.1";
+})(); \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/packages/nvd3/nv.d3.min.css b/wqflask/wqflask/static/new/packages/nvd3/nv.d3.min.css
new file mode 100644
index 00000000..7a6f7fe9
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/nvd3/nv.d3.min.css
@@ -0,0 +1 @@
+.nvd3 .nv-axis{pointer-events:none;opacity:1}.nvd3 .nv-axis path{fill:none;stroke:#000;stroke-opacity:.75;shape-rendering:crispEdges}.nvd3 .nv-axis path.domain{stroke-opacity:.75}.nvd3 .nv-axis.nv-x path.domain{stroke-opacity:0}.nvd3 .nv-axis line{fill:none;stroke:#e5e5e5;shape-rendering:crispEdges}.nvd3 .nv-axis .zero line,.nvd3 .nv-axis line.zero{stroke-opacity:.75}.nvd3 .nv-axis .nv-axisMaxMin text{font-weight:700}.nvd3 .x .nv-axis .nv-axisMaxMin text,.nvd3 .x2 .nv-axis .nv-axisMaxMin text,.nvd3 .x3 .nv-axis .nv-axisMaxMin text{text-anchor:middle}.nvd3 .nv-axis.nv-disabled{opacity:0}.nvd3 .nv-bars rect{fill-opacity:.75;transition:fill-opacity 250ms linear;-moz-transition:fill-opacity 250ms linear;-webkit-transition:fill-opacity 250ms linear}.nvd3 .nv-bars rect.hover{fill-opacity:1}.nvd3 .nv-bars .hover rect{fill:#add8e6}.nvd3 .nv-bars text{fill:rgba(0,0,0,0)}.nvd3 .nv-bars .hover text{fill:rgba(0,0,0,1)}.nvd3 .nv-multibar .nv-groups rect,.nvd3 .nv-multibarHorizontal .nv-groups rect,.nvd3 .nv-discretebar .nv-groups rect{stroke-opacity:0;transition:fill-opacity 250ms linear;-moz-transition:fill-opacity 250ms linear;-webkit-transition:fill-opacity 250ms linear}.nvd3 .nv-multibar .nv-groups rect:hover,.nvd3 .nv-multibarHorizontal .nv-groups rect:hover,.nvd3 .nv-candlestickBar .nv-ticks rect:hover,.nvd3 .nv-discretebar .nv-groups rect:hover{fill-opacity:1}.nvd3 .nv-discretebar .nv-groups text,.nvd3 .nv-multibarHorizontal .nv-groups text{font-weight:700;fill:rgba(0,0,0,1);stroke:rgba(0,0,0,0)}.nvd3 .nv-boxplot circle{fill-opacity:.5}.nvd3 .nv-boxplot circle:hover{fill-opacity:1}.nvd3 .nv-boxplot rect:hover{fill-opacity:1}.nvd3 line.nv-boxplot-median{stroke:#000}.nv-boxplot-tick:hover{stroke-width:2.5px}.nvd3.nv-bullet{font:10px sans-serif}.nvd3.nv-bullet .nv-measure{fill-opacity:.8}.nvd3.nv-bullet .nv-measure:hover{fill-opacity:1}.nvd3.nv-bullet .nv-marker{stroke:#000;stroke-width:2px}.nvd3.nv-bullet .nv-markerTriangle{stroke:#000;fill:#fff;stroke-width:1.5px}.nvd3.nv-bullet .nv-tick line{stroke:#666;stroke-width:.5px}.nvd3.nv-bullet .nv-range.nv-s0{fill:#eee}.nvd3.nv-bullet .nv-range.nv-s1{fill:#ddd}.nvd3.nv-bullet .nv-range.nv-s2{fill:#ccc}.nvd3.nv-bullet .nv-title{font-size:14px;font-weight:700}.nvd3.nv-bullet .nv-subtitle{fill:#999}.nvd3.nv-bullet .nv-range{fill:#bababa;fill-opacity:.4}.nvd3.nv-bullet .nv-range:hover{fill-opacity:.7}.nvd3.nv-candlestickBar .nv-ticks .nv-tick{stroke-width:1px}.nvd3.nv-candlestickBar .nv-ticks .nv-tick.hover{stroke-width:2px}.nvd3.nv-candlestickBar .nv-ticks .nv-tick.positive rect{stroke:#2ca02c;fill:#2ca02c}.nvd3.nv-candlestickBar .nv-ticks .nv-tick.negative rect{stroke:#d62728;fill:#d62728}.with-transitions .nv-candlestickBar .nv-ticks .nv-tick{transition:stroke-width 250ms linear,stroke-opacity 250ms linear;-moz-transition:stroke-width 250ms linear,stroke-opacity 250ms linear;-webkit-transition:stroke-width 250ms linear,stroke-opacity 250ms linear}.nvd3.nv-candlestickBar .nv-ticks line{stroke:#333}.nvd3 .nv-legend .nv-disabled rect{}.nvd3 .nv-check-box .nv-box{fill-opacity:0;stroke-width:2}.nvd3 .nv-check-box .nv-check{fill-opacity:0;stroke-width:4}.nvd3 .nv-series.nv-disabled .nv-check-box .nv-check{fill-opacity:0;stroke-opacity:0}.nvd3 .nv-controlsWrap .nv-legend .nv-check-box .nv-check{opacity:0}.nvd3.nv-linePlusBar .nv-bar rect{fill-opacity:.75}.nvd3.nv-linePlusBar .nv-bar rect:hover{fill-opacity:1}.nvd3 .nv-groups path.nv-line{fill:none}.nvd3 .nv-groups path.nv-area{stroke:none}.nvd3.nv-line .nvd3.nv-scatter .nv-groups .nv-point{fill-opacity:0;stroke-opacity:0}.nvd3.nv-scatter.nv-single-point .nv-groups .nv-point{fill-opacity:.5!important;stroke-opacity:.5!important}.with-transitions .nvd3 .nv-groups .nv-point{transition:stroke-width 250ms linear,stroke-opacity 250ms linear;-moz-transition:stroke-width 250ms linear,stroke-opacity 250ms linear;-webkit-transition:stroke-width 250ms linear,stroke-opacity 250ms linear}.nvd3.nv-scatter .nv-groups .nv-point.hover,.nvd3 .nv-groups .nv-point.hover{stroke-width:7px;fill-opacity:.95!important;stroke-opacity:.95!important}.nvd3 .nv-point-paths path{stroke:#aaa;stroke-opacity:0;fill:#eee;fill-opacity:0}.nvd3 .nv-indexLine{cursor:ew-resize}svg.nvd3-svg{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-ms-user-select:none;-moz-user-select:none;user-select:none;display:block;width:100%;height:100%}.nvtooltip.with-3d-shadow,.with-3d-shadow .nvtooltip{-moz-box-shadow:0 5px 10px rgba(0,0,0,.2);-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2);-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.nvd3 text{font:400 12px Arial}.nvd3 .title{font:700 14px Arial}.nvd3 .nv-background{fill:#fff;fill-opacity:0}.nvd3.nv-noData{font-size:18px;font-weight:700}.nv-brush .extent{fill-opacity:.125;shape-rendering:crispEdges}.nv-brush .resize path{fill:#eee;stroke:#666}.nvd3 .nv-legend .nv-series{cursor:pointer}.nvd3 .nv-legend .nv-disabled circle{fill-opacity:0}.nvd3 .nv-brush .extent{fill-opacity:0!important}.nvd3 .nv-brushBackground rect{stroke:#000;stroke-width:.4;fill:#fff;fill-opacity:.7}.nvd3.nv-ohlcBar .nv-ticks .nv-tick{stroke-width:1px}.nvd3.nv-ohlcBar .nv-ticks .nv-tick.hover{stroke-width:2px}.nvd3.nv-ohlcBar .nv-ticks .nv-tick.positive{stroke:#2ca02c}.nvd3.nv-ohlcBar .nv-ticks .nv-tick.negative{stroke:#d62728}.nvd3 .background path{fill:none;stroke:#EEE;stroke-opacity:.4;shape-rendering:crispEdges}.nvd3 .foreground path{fill:none;stroke-opacity:.7}.nvd3 .nv-parallelCoordinates-brush .extent{fill:#fff;fill-opacity:.6;stroke:gray;shape-rendering:crispEdges}.nvd3 .nv-parallelCoordinates .hover{fill-opacity:1;stroke-width:3px}.nvd3 .missingValuesline line{fill:none;stroke:#000;stroke-width:1;stroke-opacity:1;stroke-dasharray:5,5}.nvd3.nv-pie path{stroke-opacity:0;transition:fill-opacity 250ms linear,stroke-width 250ms linear,stroke-opacity 250ms linear;-moz-transition:fill-opacity 250ms linear,stroke-width 250ms linear,stroke-opacity 250ms linear;-webkit-transition:fill-opacity 250ms linear,stroke-width 250ms linear,stroke-opacity 250ms linear}.nvd3.nv-pie .nv-pie-title{font-size:24px;fill:rgba(19,196,249,.59)}.nvd3.nv-pie .nv-slice text{stroke:#000;stroke-width:0}.nvd3.nv-pie path{stroke:#fff;stroke-width:1px;stroke-opacity:1}.nvd3.nv-pie .hover path{fill-opacity:.7}.nvd3.nv-pie .nv-label{pointer-events:none}.nvd3.nv-pie .nv-label rect{fill-opacity:0;stroke-opacity:0}.nvd3 .nv-groups .nv-point.hover{stroke-width:20px;stroke-opacity:.5}.nvd3 .nv-scatter .nv-point.hover{fill-opacity:1}.nv-noninteractive{pointer-events:none}.nv-distx,.nv-disty{pointer-events:none}.nvd3.nv-sparkline path{fill:none}.nvd3.nv-sparklineplus g.nv-hoverValue{pointer-events:none}.nvd3.nv-sparklineplus .nv-hoverValue line{stroke:#333;stroke-width:1.5px}.nvd3.nv-sparklineplus,.nvd3.nv-sparklineplus g{pointer-events:all}.nvd3 .nv-hoverArea{fill-opacity:0;stroke-opacity:0}.nvd3.nv-sparklineplus .nv-xValue,.nvd3.nv-sparklineplus .nv-yValue{stroke-width:0;font-size:.9em;font-weight:400}.nvd3.nv-sparklineplus .nv-yValue{stroke:#f66}.nvd3.nv-sparklineplus .nv-maxValue{stroke:#2ca02c;fill:#2ca02c}.nvd3.nv-sparklineplus .nv-minValue{stroke:#d62728;fill:#d62728}.nvd3.nv-sparklineplus .nv-currentValue{font-weight:700;font-size:1.1em}.nvd3.nv-stackedarea path.nv-area{fill-opacity:.7;stroke-opacity:0;transition:fill-opacity 250ms linear,stroke-opacity 250ms linear;-moz-transition:fill-opacity 250ms linear,stroke-opacity 250ms linear;-webkit-transition:fill-opacity 250ms linear,stroke-opacity 250ms linear}.nvd3.nv-stackedarea path.nv-area.hover{fill-opacity:.9}.nvd3.nv-stackedarea .nv-groups .nv-point{stroke-opacity:0;fill-opacity:0}.nvtooltip{position:absolute;background-color:rgba(255,255,255,1);color:rgba(0,0,0,1);padding:1px;border:1px solid rgba(0,0,0,.2);z-index:10000;display:block;font-family:Arial;font-size:13px;text-align:left;pointer-events:none;white-space:nowrap;-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.nvtooltip{background:rgba(255,255,255,.8);border:1px solid rgba(0,0,0,.5);border-radius:4px}.nvtooltip.with-transitions,.with-transitions .nvtooltip{transition:opacity 50ms linear;-moz-transition:opacity 50ms linear;-webkit-transition:opacity 50ms linear;transition-delay:200ms;-moz-transition-delay:200ms;-webkit-transition-delay:200ms}.nvtooltip.x-nvtooltip,.nvtooltip.y-nvtooltip{padding:8px}.nvtooltip h3{margin:0;padding:4px 14px;line-height:18px;font-weight:400;background-color:rgba(247,247,247,.75);color:rgba(0,0,0,1);text-align:center;border-bottom:1px solid #ebebeb;-webkit-border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0}.nvtooltip p{margin:0;padding:5px 14px;text-align:center}.nvtooltip span{display:inline-block;margin:2px 0}.nvtooltip table{margin:6px;border-spacing:0}.nvtooltip table td{padding:2px 9px 2px 0;vertical-align:middle}.nvtooltip table td.key{font-weight:400}.nvtooltip table td.value{text-align:right;font-weight:700}.nvtooltip table tr.highlight td{padding:1px 9px 1px 0;border-bottom-style:solid;border-bottom-width:1px;border-top-style:solid;border-top-width:1px}.nvtooltip table td.legend-color-guide div{width:8px;height:8px;vertical-align:middle}.nvtooltip table td.legend-color-guide div{width:12px;height:12px;border:1px solid #999}.nvtooltip .footer{padding:3px;text-align:center}.nvtooltip-pending-removal{pointer-events:none;display:none}.nvd3 .nv-interactiveGuideLine{pointer-events:none}.nvd3 line.nv-guideline{stroke:#ccc} \ No newline at end of file
diff --git a/wqflask/wqflask/static/new/packages/nvd3/nv.d3.min.js b/wqflask/wqflask/static/new/packages/nvd3/nv.d3.min.js
new file mode 100644
index 00000000..ab17e9fe
--- /dev/null
+++ b/wqflask/wqflask/static/new/packages/nvd3/nv.d3.min.js
@@ -0,0 +1,8 @@
+/* nvd3 version 1.8.1 (https://github.com/novus/nvd3) 2015-05-25 */
+!function(){var a={};a.dev=!1,a.tooltip=a.tooltip||{},a.utils=a.utils||{},a.models=a.models||{},a.charts={},a.logs={},a.dom={},a.dispatch=d3.dispatch("render_start","render_end"),Function.prototype.bind||(Function.prototype.bind=function(a){if("function"!=typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var b=Array.prototype.slice.call(arguments,1),c=this,d=function(){},e=function(){return c.apply(this instanceof d&&a?this:a,b.concat(Array.prototype.slice.call(arguments)))};return d.prototype=this.prototype,e.prototype=new d,e}),a.dev&&(a.dispatch.on("render_start",function(b){a.logs.startTime=+new Date}),a.dispatch.on("render_end",function(b){a.logs.endTime=+new Date,a.logs.totalTime=a.logs.endTime-a.logs.startTime,a.log("total",a.logs.totalTime)})),a.log=function(){if(a.dev&&window.console&&console.log&&console.log.apply)console.log.apply(console,arguments);else if(a.dev&&window.console&&"function"==typeof console.log&&Function.prototype.bind){var b=Function.prototype.bind.call(console.log,console);b.apply(console,arguments)}return arguments[arguments.length-1]},a.deprecated=function(a,b){console&&console.warn&&console.warn("nvd3 warning: `"+a+"` has been deprecated. ",b||"")},a.render=function(b){b=b||1,a.render.active=!0,a.dispatch.render_start();var c=function(){for(var d,e,f=0;b>f&&(e=a.render.queue[f]);f++)d=e.generate(),typeof e.callback==typeof Function&&e.callback(d);a.render.queue.splice(0,f),a.render.queue.length?setTimeout(c):(a.dispatch.render_end(),a.render.active=!1)};setTimeout(c)},a.render.active=!1,a.render.queue=[],a.addGraph=function(b){typeof arguments[0]==typeof Function&&(b={generate:arguments[0],callback:arguments[1]}),a.render.queue.push(b),a.render.active||a.render()},"undefined"!=typeof module&&"undefined"!=typeof exports&&(module.exports=a),"undefined"!=typeof window&&(window.nv=a),a.dom.write=function(a){return void 0!==window.fastdom?fastdom.write(a):a()},a.dom.read=function(a){return void 0!==window.fastdom?fastdom.read(a):a()},a.interactiveGuideline=function(){"use strict";function b(l){l.each(function(l){function m(){var a=d3.mouse(this),d=a[0],e=a[1],i=!0,j=!1;if(k&&(d=d3.event.offsetX,e=d3.event.offsetY,"svg"!==d3.event.target.tagName&&(i=!1),d3.event.target.className.baseVal.match("nv-legend")&&(j=!0)),i&&(d-=f.left,e-=f.top),0>d||0>e||d>o||e>p||d3.event.relatedTarget&&void 0===d3.event.relatedTarget.ownerSVGElement||j){if(k&&d3.event.relatedTarget&&void 0===d3.event.relatedTarget.ownerSVGElement&&(void 0===d3.event.relatedTarget.className||d3.event.relatedTarget.className.match(c.nvPointerEventsClass)))return;return h.elementMouseout({mouseX:d,mouseY:e}),b.renderGuideLine(null),void c.hidden(!0)}c.hidden(!1);var l=g.invert(d);h.elementMousemove({mouseX:d,mouseY:e,pointXValue:l}),"dblclick"===d3.event.type&&h.elementDblclick({mouseX:d,mouseY:e,pointXValue:l}),"click"===d3.event.type&&h.elementClick({mouseX:d,mouseY:e,pointXValue:l})}var n=d3.select(this),o=d||960,p=e||400,q=n.selectAll("g.nv-wrap.nv-interactiveLineLayer").data([l]),r=q.enter().append("g").attr("class"," nv-wrap nv-interactiveLineLayer");r.append("g").attr("class","nv-interactiveGuideLine"),j&&(j.on("touchmove",m).on("mousemove",m,!0).on("mouseout",m,!0).on("dblclick",m).on("click",m),b.guideLine=null,b.renderGuideLine=function(c){i&&(b.guideLine&&b.guideLine.attr("x1")===c||a.dom.write(function(){var b=q.select(".nv-interactiveGuideLine").selectAll("line").data(null!=c?[a.utils.NaNtoZero(c)]:[],String);b.enter().append("line").attr("class","nv-guideline").attr("x1",function(a){return a}).attr("x2",function(a){return a}).attr("y1",p).attr("y2",0),b.exit().remove()}))})})}var c=a.models.tooltip();c.duration(0).hideDelay(0)._isInteractiveLayer(!0).hidden(!1);var d=null,e=null,f={left:0,top:0},g=d3.scale.linear(),h=d3.dispatch("elementMousemove","elementMouseout","elementClick","elementDblclick"),i=!0,j=null,k="ActiveXObject"in window;return b.dispatch=h,b.tooltip=c,b.margin=function(a){return arguments.length?(f.top="undefined"!=typeof a.top?a.top:f.top,f.left="undefined"!=typeof a.left?a.left:f.left,b):f},b.width=function(a){return arguments.length?(d=a,b):d},b.height=function(a){return arguments.length?(e=a,b):e},b.xScale=function(a){return arguments.length?(g=a,b):g},b.showGuideLine=function(a){return arguments.length?(i=a,b):i},b.svgContainer=function(a){return arguments.length?(j=a,b):j},b},a.interactiveBisect=function(a,b,c){"use strict";if(!(a instanceof Array))return null;var d;d="function"!=typeof c?function(a){return a.x}:c;var e=function(a,b){return d(a)-b},f=d3.bisector(e).left,g=d3.max([0,f(a,b)-1]),h=d(a[g]);if("undefined"==typeof h&&(h=g),h===b)return g;var i=d3.min([g+1,a.length-1]),j=d(a[i]);return"undefined"==typeof j&&(j=i),Math.abs(j-b)>=Math.abs(h-b)?g:i},a.nearestValueIndex=function(a,b,c){"use strict";var d=1/0,e=null;return a.forEach(function(a,f){var g=Math.abs(b-a);null!=a&&d>=g&&c>g&&(d=g,e=f)}),e},function(){"use strict";a.models.tooltip=function(){function b(){if(k){var a=d3.select(k);"svg"!==a.node().tagName&&(a=a.select("svg"));var b=a.node()?a.attr("viewBox"):null;if(b){b=b.split(" ");var c=parseInt(a.style("width"),10)/b[2];p.left=p.left*c,p.top=p.top*c}}}function c(){if(!n){var a;a=k?k:document.body,n=d3.select(a).append("div").attr("class","nvtooltip "+(j?j:"xy-tooltip")).attr("id",v),n.style("top",0).style("left",0),n.style("opacity",0),n.selectAll("div, table, td, tr").classed(w,!0),n.classed(w,!0),o=n.node()}}function d(){if(r&&B(e)){b();var f=p.left,g=null!==i?i:p.top;return a.dom.write(function(){c();var b=A(e);b&&(o.innerHTML=b),k&&u?a.dom.read(function(){var a=k.getElementsByTagName("svg")[0],b={left:0,top:0};if(a){var c=a.getBoundingClientRect(),d=k.getBoundingClientRect(),e=c.top;if(0>e){var i=k.getBoundingClientRect();e=Math.abs(e)>i.height?0:e}b.top=Math.abs(e-d.top),b.left=Math.abs(c.left-d.left)}f+=k.offsetLeft+b.left-2*k.scrollLeft,g+=k.offsetTop+b.top-2*k.scrollTop,h&&h>0&&(g=Math.floor(g/h)*h),C([f,g])}):C([f,g])}),d}}var e=null,f="w",g=25,h=0,i=null,j=null,k=null,l=!0,m=400,n=null,o=null,p={left:null,top:null},q={left:0,top:0},r=!0,s=100,t=!0,u=!1,v="nvtooltip-"+Math.floor(1e5*Math.random()),w="nv-pointer-events-none",x=function(a,b){return a},y=function(a){return a},z=function(a,b){return a},A=function(a){if(null===a)return"";var b=d3.select(document.createElement("table"));if(t){var c=b.selectAll("thead").data([a]).enter().append("thead");c.append("tr").append("td").attr("colspan",3).append("strong").classed("x-value",!0).html(y(a.value))}var d=b.selectAll("tbody").data([a]).enter().append("tbody"),e=d.selectAll("tr").data(function(a){return a.series}).enter().append("tr").classed("highlight",function(a){return a.highlight});e.append("td").classed("legend-color-guide",!0).append("div").style("background-color",function(a){return a.color}),e.append("td").classed("key",!0).html(function(a,b){return z(a.key,b)}),e.append("td").classed("value",!0).html(function(a,b){return x(a.value,b)}),e.selectAll("td").each(function(a){if(a.highlight){var b=d3.scale.linear().domain([0,1]).range(["#fff",a.color]),c=.6;d3.select(this).style("border-bottom-color",b(c)).style("border-top-color",b(c))}});var f=b.node().outerHTML;return void 0!==a.footer&&(f+="<div class='footer'>"+a.footer+"</div>"),f},B=function(a){if(a&&a.series){if(a.series instanceof Array)return!!a.series.length;if(a.series instanceof Object)return a.series=[a.series],!0}return!1},C=function(b){o&&a.dom.read(function(){var c,d,e=parseInt(o.offsetHeight,10),h=parseInt(o.offsetWidth,10),i=a.utils.windowSize().width,j=a.utils.windowSize().height,k=window.pageYOffset,p=window.pageXOffset;j=window.innerWidth>=document.body.scrollWidth?j:j-16,i=window.innerHeight>=document.body.scrollHeight?i:i-16;var r,t,u=function(a){var b=d;do isNaN(a.offsetTop)||(b+=a.offsetTop),a=a.offsetParent;while(a);return b},v=function(a){var b=c;do isNaN(a.offsetLeft)||(b+=a.offsetLeft),a=a.offsetParent;while(a);return b};switch(f){case"e":c=b[0]-h-g,d=b[1]-e/2,r=v(o),t=u(o),p>r&&(c=b[0]+g>p?b[0]+g:p-r+c),k>t&&(d=k-t+d),t+e>k+j&&(d=k+j-t+d-e);break;case"w":c=b[0]+g,d=b[1]-e/2,r=v(o),t=u(o),r+h>i&&(c=b[0]-h-g),k>t&&(d=k+5),t+e>k+j&&(d=k+j-t+d-e);break;case"n":c=b[0]-h/2-5,d=b[1]+g,r=v(o),t=u(o),p>r&&(c=p+5),r+h>i&&(c=c-h/2+5),t+e>k+j&&(d=k+j-t+d-e);break;case"s":c=b[0]-h/2,d=b[1]-e-g,r=v(o),t=u(o),p>r&&(c=p+5),r+h>i&&(c=c-h/2+5),k>t&&(d=k);break;case"none":c=b[0],d=b[1]-g,r=v(o),t=u(o)}c-=q.left,d-=q.top;var w=o.getBoundingClientRect(),k=window.pageYOffset||document.documentElement.scrollTop,p=window.pageXOffset||document.documentElement.scrollLeft,x="translate("+(w.left+p)+"px, "+(w.top+k)+"px)",y="translate("+c+"px, "+d+"px)",z=d3.interpolateString(x,y),A=n.style("opacity")<.1;l?n.transition().delay(m).duration(0).style("opacity",0):n.interrupt().transition().duration(A?0:s).styleTween("transform",function(a){return z},"important").style("-webkit-transform",y).style("opacity",1)})};return d.nvPointerEventsClass=w,d.options=a.utils.optionsFunc.bind(d),d._options=Object.create({},{duration:{get:function(){return s},set:function(a){s=a}},gravity:{get:function(){return f},set:function(a){f=a}},distance:{get:function(){return g},set:function(a){g=a}},snapDistance:{get:function(){return h},set:function(a){h=a}},classes:{get:function(){return j},set:function(a){j=a}},chartContainer:{get:function(){return k},set:function(a){k=a}},fixedTop:{get:function(){return i},set:function(a){i=a}},enabled:{get:function(){return r},set:function(a){r=a}},hideDelay:{get:function(){return m},set:function(a){m=a}},contentGenerator:{get:function(){return A},set:function(a){A=a}},valueFormatter:{get:function(){return x},set:function(a){x=a}},headerFormatter:{get:function(){return y},set:function(a){y=a}},keyFormatter:{get:function(){return z},set:function(a){z=a}},headerEnabled:{get:function(){return t},set:function(a){t=a}},_isInteractiveLayer:{get:function(){return u},set:function(a){u=!!a}},position:{get:function(){return p},set:function(a){p.left=void 0!==a.left?a.left:p.left,p.top=void 0!==a.top?a.top:p.top}},offset:{get:function(){return q},set:function(a){q.left=void 0!==a.left?a.left:q.left,q.top=void 0!==a.top?a.top:q.top}},hidden:{get:function(){return l},set:function(a){l!=a&&(l=!!a,d())}},data:{get:function(){return e},set:function(a){a.point&&(a.value=a.point.x,a.series=a.series||{},a.series.value=a.point.y,a.series.color=a.point.color||a.series.color),e=a}},tooltipElem:{get:function(){return o},set:function(a){}},id:{get:function(){return v},set:function(a){}}}),a.utils.initOptions(d),d}}(),a.utils.windowSize=function(){var a={width:640,height:480};return window.innerWidth&&window.innerHeight?(a.width=window.innerWidth,a.height=window.innerHeight,a):"CSS1Compat"==document.compatMode&&document.documentElement&&document.documentElement.offsetWidth?(a.width=document.documentElement.offsetWidth,a.height=document.documentElement.offsetHeight,a):document.body&&document.body.offsetWidth?(a.width=document.body.offsetWidth,a.height=document.body.offsetHeight,a):a},a.utils.windowResize=function(b){return window.addEventListener?window.addEventListener("resize",b):a.log("ERROR: Failed to bind to window.resize with: ",b),{callback:b,clear:function(){window.removeEventListener("resize",b)}}},a.utils.getColor=function(b){if(void 0===b)return a.utils.defaultColor();if(Array.isArray(b)){var c=d3.scale.ordinal().range(b);return function(a,b){var d=void 0===b?a:b;return a.color||c(d)}}return b},a.utils.defaultColor=function(){return a.utils.getColor(d3.scale.category20().range())},a.utils.customTheme=function(a,b,c){b=b||function(a){return a.key},c=c||d3.scale.category20().range();var d=c.length;return function(e,f){var g=b(e);return"function"==typeof a[g]?a[g]():void 0!==a[g]?a[g]:(d||(d=c.length),d-=1,c[d])}},a.utils.pjax=function(b,c){var d=function(d){d3.html(d,function(d){var e=d3.select(c).node();e.parentNode.replaceChild(d3.select(d).select(c).node(),e),a.utils.pjax(b,c)})};d3.selectAll(b).on("click",function(){history.pushState(this.href,this.textContent,this.href),d(this.href),d3.event.preventDefault()}),d3.select(window).on("popstate",function(){d3.event.state&&d(d3.event.state)})},a.utils.calcApproxTextWidth=function(a){if("function"==typeof a.style&&"function"==typeof a.text){var b=parseInt(a.style("font-size").replace("px",""),10),c=a.text().length;return c*b*.5}return 0},a.utils.NaNtoZero=function(a){return"number"!=typeof a||isNaN(a)||null===a||a===1/0||a===-(1/0)?0:a},d3.selection.prototype.watchTransition=function(a){var b=[this].concat([].slice.call(arguments,1));return a.transition.apply(a,b)},a.utils.renderWatch=function(b,c){if(!(this instanceof a.utils.renderWatch))return new a.utils.renderWatch(b,c);var d=void 0!==c?c:250,e=[],f=this;this.models=function(a){return a=[].slice.call(arguments,0),a.forEach(function(a){a.__rendered=!1,function(a){a.dispatch.on("renderEnd",function(b){a.__rendered=!0,f.renderEnd("model")})}(a),e.indexOf(a)<0&&e.push(a)}),this},this.reset=function(a){void 0!==a&&(d=a),e=[]},this.transition=function(a,b,c){if(b=arguments.length>1?[].slice.call(arguments,1):[],c=b.length>1?b.pop():void 0!==d?d:250,a.__rendered=!1,e.indexOf(a)<0&&e.push(a),0===c)return a.__rendered=!0,a.delay=function(){return this},a.duration=function(){return this},a;0===a.length?a.__rendered=!0:a.every(function(a){return!a.length})?a.__rendered=!0:a.__rendered=!1;var g=0;return a.transition().duration(c).each(function(){++g}).each("end",function(c,d){0===--g&&(a.__rendered=!0,f.renderEnd.apply(this,b))})},this.renderEnd=function(){e.every(function(a){return a.__rendered})&&(e.forEach(function(a){a.__rendered=!1}),b.renderEnd.apply(this,arguments))}},a.utils.deepExtend=function(b){var c=arguments.length>1?[].slice.call(arguments,1):[];c.forEach(function(c){for(var d in c){var e=b[d]instanceof Array,f="object"==typeof b[d],g="object"==typeof c[d];f&&!e&&g?a.utils.deepExtend(b[d],c[d]):b[d]=c[d]}})},a.utils.state=function(){if(!(this instanceof a.utils.state))return new a.utils.state;var b={},c=function(){},d=function(){return{}},e=null,f=null;this.dispatch=d3.dispatch("change","set"),this.dispatch.on("set",function(a){c(a,!0)}),this.getter=function(a){return d=a,this},this.setter=function(a,b){return b||(b=function(){}),c=function(c,d){a(c),d&&b()},this},this.init=function(b){e=e||{},a.utils.deepExtend(e,b)};var g=function(){var a=d();if(JSON.stringify(a)===JSON.stringify(b))return!1;for(var c in a)void 0===b[c]&&(b[c]={}),b[c]=a[c],f=!0;return!0};this.update=function(){e&&(c(e,!1),e=null),g.call(this)&&this.dispatch.change(b)}},a.utils.optionsFunc=function(a){return a&&d3.map(a).forEach(function(a,b){"function"==typeof this[a]&&this[a](b)}.bind(this)),this},a.utils.calcTicksX=function(b,c){var d=1,e=0;for(e;e<c.length;e+=1){var f=c[e]&&c[e].values?c[e].values.length:0;d=f>d?f:d}return a.log("Requested number of ticks: ",b),a.log("Calculated max values to be: ",d),b=b>d?b=d-1:b,b=1>b?1:b,b=Math.floor(b),a.log("Calculating tick count as: ",b),b},a.utils.calcTicksY=function(b,c){return a.utils.calcTicksX(b,c)},a.utils.initOption=function(a,b){a._calls&&a._calls[b]?a[b]=a._calls[b]:(a[b]=function(c){return arguments.length?(a._overrides[b]=!0,a._options[b]=c,a):a._options[b]},a["_"+b]=function(c){return arguments.length?(a._overrides[b]||(a._options[b]=c),a):a._options[b]})},a.utils.initOptions=function(b){b._overrides=b._overrides||{};var c=Object.getOwnPropertyNames(b._options||{}),d=Object.getOwnPropertyNames(b._calls||{});c=c.concat(d);for(var e in c)a.utils.initOption(b,c[e])},a.utils.inheritOptionsD3=function(a,b,c){a._d3options=c.concat(a._d3options||[]),c.unshift(b),c.unshift(a),d3.rebind.apply(this,c)},a.utils.arrayUnique=function(a){return a.sort().filter(function(b,c){return!c||b!=a[c-1]})},a.utils.symbolMap=d3.map(),a.utils.symbol=function(){function b(b,e){var f=c.call(this,b,e),g=d.call(this,b,e);return-1!==d3.svg.symbolTypes.indexOf(f)?d3.svg.symbol().type(f).size(g)():a.utils.symbolMap.get(f)(g)}var c,d=64;return b.type=function(a){return arguments.length?(c=d3.functor(a),b):c},b.size=function(a){return arguments.length?(d=d3.functor(a),b):d},b},a.utils.inheritOptions=function(b,c){var d=Object.getOwnPropertyNames(c._options||{}),e=Object.getOwnPropertyNames(c._calls||{}),f=c._inherited||[],g=c._d3options||[],h=d.concat(e).concat(f).concat(g);h.unshift(c),h.unshift(b),d3.rebind.apply(this,h),b._inherited=a.utils.arrayUnique(d.concat(e).concat(f).concat(d).concat(b._inherited||[])),b._d3options=a.utils.arrayUnique(g.concat(b._d3options||[]))},a.utils.initSVG=function(a){a.classed({"nvd3-svg":!0})},a.utils.sanitizeHeight=function(a,b){return a||parseInt(b.style("height"),10)||400},a.utils.sanitizeWidth=function(a,b){return a||parseInt(b.style("width"),10)||960},a.utils.availableHeight=function(b,c,d){return a.utils.sanitizeHeight(b,c)-d.top-d.bottom},a.utils.availableWidth=function(b,c,d){return a.utils.sanitizeWidth(b,c)-d.left-d.right},a.utils.noData=function(b,c){var d=b.options(),e=d.margin(),f=d.noData(),g=null==f?["No Data Available."]:[f],h=a.utils.availableHeight(d.height(),c,e),i=a.utils.availableWidth(d.width(),c,e),j=e.left+i/2,k=e.top+h/2;c.selectAll("g").remove();var l=c.selectAll(".nv-noData").data(g);l.enter().append("text").attr("class","nvd3 nv-noData").attr("dy","-.7em").style("text-anchor","middle"),l.attr("x",j).attr("y",k).text(function(a){return a})},a.models.axis=function(){"use strict";function b(g){return s.reset(),g.each(function(b){var g=d3.select(this);a.utils.initSVG(g);var p=g.selectAll("g.nv-wrap.nv-axis").data([b]),q=p.enter().append("g").attr("class","nvd3 nv-wrap nv-axis"),t=(q.append("g"),p.select("g"));null!==n?c.ticks(n):("top"==c.orient()||"bottom"==c.orient())&&c.ticks(Math.abs(d.range()[1]-d.range()[0])/100),t.watchTransition(s,"axis").call(c),r=r||c.scale();var u=c.tickFormat();null==u&&(u=r.tickFormat());var v=t.selectAll("text.nv-axislabel").data([h||null]);v.exit().remove();var w,x,y;switch(c.orient()){case"top":v.enter().append("text").attr("class","nv-axislabel"),y=d.range().length<2?0:2===d.range().length?d.range()[1]:d.range()[d.range().length-1]+(d.range()[1]-d.range()[0]),v.attr("text-anchor","middle").attr("y",0).attr("x",y/2),i&&(x=p.selectAll("g.nv-axisMaxMin").data(d.domain()),x.enter().append("g").attr("class",function(a,b){return["nv-axisMaxMin","nv-axisMaxMin-x",0==b?"nv-axisMin-x":"nv-axisMax-x"].join(" ")}).append("text"),x.exit().remove(),x.attr("transform",function(b,c){return"translate("+a.utils.NaNtoZero(d(b))+",0)"}).select("text").attr("dy","-0.5em").attr("y",-c.tickPadding()).attr("text-anchor","middle").text(function(a,b){var c=u(a);return(""+c).match("NaN")?"":c}),x.watchTransition(s,"min-max top").attr("transform",function(b,c){return"translate("+a.utils.NaNtoZero(d.range()[c])+",0)"}));break;case"bottom":w=o+36;var z=30,A=0,B=t.selectAll("g").select("text"),C="";if(j%360){B.each(function(a,b){var c=this.getBoundingClientRect(),d=c.width;A=c.height,d>z&&(z=d)}),C="rotate("+j+" 0,"+(A/2+c.tickPadding())+")";var D=Math.abs(Math.sin(j*Math.PI/180));w=(D?D*z:z)+30,B.attr("transform",C).style("text-anchor",j%360>0?"start":"end")}v.enter().append("text").attr("class","nv-axislabel"),y=d.range().length<2?0:2===d.range().length?d.range()[1]:d.range()[d.range().length-1]+(d.range()[1]-d.range()[0]),v.attr("text-anchor","middle").attr("y",w).attr("x",y/2),i&&(x=p.selectAll("g.nv-axisMaxMin").data([d.domain()[0],d.domain()[d.domain().length-1]]),x.enter().append("g").attr("class",function(a,b){return["nv-axisMaxMin","nv-axisMaxMin-x",0==b?"nv-axisMin-x":"nv-axisMax-x"].join(" ")}).append("text"),x.exit().remove(),x.attr("transform",function(b,c){return"translate("+a.utils.NaNtoZero(d(b)+(m?d.rangeBand()/2:0))+",0)"}).select("text").attr("dy",".71em").attr("y",c.tickPadding()).attr("transform",C).style("text-anchor",j?j%360>0?"start":"end":"middle").text(function(a,b){var c=u(a);return(""+c).match("NaN")?"":c}),x.watchTransition(s,"min-max bottom").attr("transform",function(b,c){return"translate("+a.utils.NaNtoZero(d(b)+(m?d.rangeBand()/2:0))+",0)"})),l&&B.attr("transform",function(a,b){return"translate(0,"+(b%2==0?"0":"12")+")"});break;case"right":v.enter().append("text").attr("class","nv-axislabel"),v.style("text-anchor",k?"middle":"begin").attr("transform",k?"rotate(90)":"").attr("y",k?-Math.max(e.right,f)+12:-10).attr("x",k?d3.max(d.range())/2:c.tickPadding()),i&&(x=p.selectAll("g.nv-axisMaxMin").data(d.domain()),x.enter().append("g").attr("class",function(a,b){return["nv-axisMaxMin","nv-axisMaxMin-y",0==b?"nv-axisMin-y":"nv-axisMax-y"].join(" ")}).append("text").style("opacity",0),x.exit().remove(),x.attr("transform",function(b,c){return"translate(0,"+a.utils.NaNtoZero(d(b))+")"}).select("text").attr("dy",".32em").attr("y",0).attr("x",c.tickPadding()).style("text-anchor","start").text(function(a,b){var c=u(a);return(""+c).match("NaN")?"":c}),x.watchTransition(s,"min-max right").attr("transform",function(b,c){return"translate(0,"+a.utils.NaNtoZero(d.range()[c])+")"}).select("text").style("opacity",1));break;case"left":v.enter().append("text").attr("class","nv-axislabel"),v.style("text-anchor",k?"middle":"end").attr("transform",k?"rotate(-90)":"").attr("y",k?-Math.max(e.left,f)+25-(o||0):-10).attr("x",k?-d3.max(d.range())/2:-c.tickPadding()),i&&(x=p.selectAll("g.nv-axisMaxMin").data(d.domain()),x.enter().append("g").attr("class",function(a,b){return["nv-axisMaxMin","nv-axisMaxMin-y",0==b?"nv-axisMin-y":"nv-axisMax-y"].join(" ")}).append("text").style("opacity",0),x.exit().remove(),x.attr("transform",function(b,c){return"translate(0,"+a.utils.NaNtoZero(r(b))+")"}).select("text").attr("dy",".32em").attr("y",0).attr("x",-c.tickPadding()).attr("text-anchor","end").text(function(a,b){var c=u(a);return(""+c).match("NaN")?"":c}),x.watchTransition(s,"min-max right").attr("transform",function(b,c){return"translate(0,"+a.utils.NaNtoZero(d.range()[c])+")"}).select("text").style("opacity",1))}if(v.text(function(a){return a}),!i||"left"!==c.orient()&&"right"!==c.orient()||(t.selectAll("g").each(function(a,b){d3.select(this).select("text").attr("opacity",1),(d(a)<d.range()[1]+10||d(a)>d.range()[0]-10)&&((a>1e-10||-1e-10>a)&&d3.select(this).attr("opacity",0),d3.select(this).select("text").attr("opacity",0))}),d.domain()[0]==d.domain()[1]&&0==d.domain()[0]&&p.selectAll("g.nv-axisMaxMin").style("opacity",function(a,b){return b?0:1})),i&&("top"===c.orient()||"bottom"===c.orient())){var E=[];p.selectAll("g.nv-axisMaxMin").each(function(a,b){try{b?E.push(d(a)-this.getBoundingClientRect().width-4):E.push(d(a)+this.getBoundingClientRect().width+4)}catch(c){b?E.push(d(a)-4):E.push(d(a)+4)}}),t.selectAll("g").each(function(a,b){(d(a)<E[0]||d(a)>E[1])&&(a>1e-10||-1e-10>a?d3.select(this).remove():d3.select(this).select("text").remove())})}t.selectAll(".tick").filter(function(a){return!parseFloat(Math.round(1e5*a)/1e6)&&void 0!==a}).classed("zero",!0),r=d.copy()}),s.renderEnd("axis immediate"),b}var c=d3.svg.axis(),d=d3.scale.linear(),e={top:0,right:0,bottom:0,left:0},f=75,g=60,h=null,i=!0,j=0,k=!0,l=!1,m=!1,n=null,o=0,p=250,q=d3.dispatch("renderEnd");c.scale(d).orient("bottom").tickFormat(function(a){return a});var r,s=a.utils.renderWatch(q,p);return b.axis=c,b.dispatch=q,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{axisLabelDistance:{get:function(){return o},set:function(a){o=a}},staggerLabels:{get:function(){return l},set:function(a){l=a}},rotateLabels:{get:function(){return j},set:function(a){j=a}},rotateYLabel:{get:function(){return k},set:function(a){k=a}},showMaxMin:{get:function(){return i},set:function(a){i=a}},axisLabel:{get:function(){return h},set:function(a){h=a}},height:{get:function(){return g},set:function(a){g=a}},ticks:{get:function(){return n},set:function(a){n=a}},width:{get:function(){return f},set:function(a){f=a}},margin:{get:function(){return e},set:function(a){e.top=void 0!==a.top?a.top:e.top,e.right=void 0!==a.right?a.right:e.right,e.bottom=void 0!==a.bottom?a.bottom:e.bottom,e.left=void 0!==a.left?a.left:e.left}},duration:{get:function(){return p},set:function(a){p=a,s.reset(p)}},scale:{get:function(){return d},set:function(e){d=e,c.scale(d),m="function"==typeof d.rangeBands,a.utils.inheritOptionsD3(b,d,["domain","range","rangeBand","rangeBands"])}}}),a.utils.initOptions(b),a.utils.inheritOptionsD3(b,c,["orient","tickValues","tickSubdivide","tickSize","tickPadding","tickFormat"]),a.utils.inheritOptionsD3(b,d,["domain","range","rangeBand","rangeBands"]),b},a.models.boxPlot=function(){"use strict";function b(l){return v.reset(),l.each(function(b){var l=j-i.left-i.right,p=k-i.top-i.bottom;r=d3.select(this),a.utils.initSVG(r),m.domain(c||b.map(function(a,b){return o(a,b)})).rangeBands(e||[0,l],.1);var w=[];if(!d){var x=d3.min(b.map(function(a){var b=[];return b.push(a.values.Q1),a.values.hasOwnProperty("whisker_low")&&null!==a.values.whisker_low&&b.push(a.values.whisker_low),a.values.hasOwnProperty("outliers")&&null!==a.values.outliers&&(b=b.concat(a.values.outliers)),d3.min(b)})),y=d3.max(b.map(function(a){var b=[];return b.push(a.values.Q3),a.values.hasOwnProperty("whisker_high")&&null!==a.values.whisker_high&&b.push(a.values.whisker_high),a.values.hasOwnProperty("outliers")&&null!==a.values.outliers&&(b=b.concat(a.values.outliers)),d3.max(b)}));w=[x,y]}n.domain(d||w),n.range(f||[p,0]),g=g||m,h=h||n.copy().range([n(0),n(0)]);var z=r.selectAll("g.nv-wrap").data([b]);z.enter().append("g").attr("class","nvd3 nv-wrap");z.attr("transform","translate("+i.left+","+i.top+")");var A=z.selectAll(".nv-boxplot").data(function(a){return a}),B=A.enter().append("g").style("stroke-opacity",1e-6).style("fill-opacity",1e-6);A.attr("class","nv-boxplot").attr("transform",function(a,b,c){return"translate("+(m(o(a,b))+.05*m.rangeBand())+", 0)"}).classed("hover",function(a){return a.hover}),A.watchTransition(v,"nv-boxplot: boxplots").style("stroke-opacity",1).style("fill-opacity",.75).delay(function(a,c){return c*t/b.length}).attr("transform",function(a,b){return"translate("+(m(o(a,b))+.05*m.rangeBand())+", 0)"}),A.exit().remove(),B.each(function(a,b){var c=d3.select(this);["low","high"].forEach(function(d){a.values.hasOwnProperty("whisker_"+d)&&null!==a.values["whisker_"+d]&&(c.append("line").style("stroke",a.color?a.color:q(a,b)).attr("class","nv-boxplot-whisker nv-boxplot-"+d),c.append("line").style("stroke",a.color?a.color:q(a,b)).attr("class","nv-boxplot-tick nv-boxplot-"+d))})});var C=A.selectAll(".nv-boxplot-outlier").data(function(a){return a.values.hasOwnProperty("outliers")&&null!==a.values.outliers?a.values.outliers:[]});C.enter().append("circle").style("fill",function(a,b,c){return q(a,c)}).style("stroke",function(a,b,c){return q(a,c)}).on("mouseover",function(a,b,c){d3.select(this).classed("hover",!0),s.elementMouseover({series:{key:a,color:q(a,c)},e:d3.event})}).on("mouseout",function(a,b,c){d3.select(this).classed("hover",!1),s.elementMouseout({series:{key:a,color:q(a,c)},e:d3.event})}).on("mousemove",function(a,b){s.elementMousemove({e:d3.event})}),C.attr("class","nv-boxplot-outlier"),C.watchTransition(v,"nv-boxplot: nv-boxplot-outlier").attr("cx",.45*m.rangeBand()).attr("cy",function(a,b,c){return n(a)}).attr("r","3"),C.exit().remove();var D=function(){return null===u?.9*m.rangeBand():Math.min(75,.9*m.rangeBand())},E=function(){return.45*m.rangeBand()-D()/2},F=function(){return.45*m.rangeBand()+D()/2};["low","high"].forEach(function(a){var b="low"===a?"Q1":"Q3";A.select("line.nv-boxplot-whisker.nv-boxplot-"+a).watchTransition(v,"nv-boxplot: boxplots").attr("x1",.45*m.rangeBand()).attr("y1",function(b,c){return n(b.values["whisker_"+a])}).attr("x2",.45*m.rangeBand()).attr("y2",function(a,c){return n(a.values[b])}),A.select("line.nv-boxplot-tick.nv-boxplot-"+a).watchTransition(v,"nv-boxplot: boxplots").attr("x1",E).attr("y1",function(b,c){return n(b.values["whisker_"+a])}).attr("x2",F).attr("y2",function(b,c){return n(b.values["whisker_"+a])})}),["low","high"].forEach(function(a){B.selectAll(".nv-boxplot-"+a).on("mouseover",function(b,c,d){d3.select(this).classed("hover",!0),s.elementMouseover({series:{key:b.values["whisker_"+a],color:q(b,d)},e:d3.event})}).on("mouseout",function(b,c,d){d3.select(this).classed("hover",!1),s.elementMouseout({series:{key:b.values["whisker_"+a],color:q(b,d)},e:d3.event})}).on("mousemove",function(a,b){s.elementMousemove({e:d3.event})})}),B.append("rect").attr("class","nv-boxplot-box").on("mouseover",function(a,b){d3.select(this).classed("hover",!0),s.elementMouseover({key:a.label,value:a.label,series:[{key:"Q3",value:a.values.Q3,color:a.color||q(a,b)},{key:"Q2",value:a.values.Q2,color:a.color||q(a,b)},{key:"Q1",value:a.values.Q1,color:a.color||q(a,b)}],data:a,index:b,e:d3.event})}).on("mouseout",function(a,b){d3.select(this).classed("hover",!1),s.elementMouseout({key:a.label,value:a.label,series:[{key:"Q3",value:a.values.Q3,color:a.color||q(a,b)},{key:"Q2",value:a.values.Q2,color:a.color||q(a,b)},{key:"Q1",value:a.values.Q1,color:a.color||q(a,b)}],data:a,index:b,e:d3.event})}).on("mousemove",function(a,b){s.elementMousemove({e:d3.event})}),A.select("rect.nv-boxplot-box").watchTransition(v,"nv-boxplot: boxes").attr("y",function(a,b){return n(a.values.Q3)}).attr("width",D).attr("x",E).attr("height",function(a,b){return Math.abs(n(a.values.Q3)-n(a.values.Q1))||1}).style("fill",function(a,b){return a.color||q(a,b)}).style("stroke",function(a,b){return a.color||q(a,b)}),B.append("line").attr("class","nv-boxplot-median"),A.select("line.nv-boxplot-median").watchTransition(v,"nv-boxplot: boxplots line").attr("x1",E).attr("y1",function(a,b){return n(a.values.Q2)}).attr("x2",F).attr("y2",function(a,b){return n(a.values.Q2)}),g=m.copy(),h=n.copy()}),v.renderEnd("nv-boxplot immediate"),b}var c,d,e,f,g,h,i={top:0,right:0,bottom:0,left:0},j=960,k=500,l=Math.floor(1e4*Math.random()),m=d3.scale.ordinal(),n=d3.scale.linear(),o=function(a){return a.x},p=function(a){return a.y},q=a.utils.defaultColor(),r=null,s=d3.dispatch("elementMouseover","elementMouseout","elementMousemove","renderEnd"),t=250,u=null,v=a.utils.renderWatch(s,t);return b.dispatch=s,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return j},set:function(a){j=a}},height:{get:function(){return k},set:function(a){k=a}},maxBoxWidth:{get:function(){return u},set:function(a){u=a}},x:{get:function(){return o},set:function(a){o=a}},y:{get:function(){return p},set:function(a){p=a}},xScale:{get:function(){return m},set:function(a){m=a}},yScale:{get:function(){return n},set:function(a){n=a}},xDomain:{get:function(){return c},set:function(a){c=a}},yDomain:{get:function(){return d},set:function(a){d=a}},xRange:{get:function(){return e},set:function(a){e=a}},yRange:{get:function(){return f},set:function(a){f=a}},id:{get:function(){return l},set:function(a){l=a}},margin:{get:function(){return i},set:function(a){i.top=void 0!==a.top?a.top:i.top,i.right=void 0!==a.right?a.right:i.right,i.bottom=void 0!==a.bottom?a.bottom:i.bottom,i.left=void 0!==a.left?a.left:i.left}},color:{get:function(){return q},set:function(b){q=a.utils.getColor(b)}},duration:{get:function(){return t},set:function(a){t=a,v.reset(t)}}}),a.utils.initOptions(b),b},a.models.boxPlotChart=function(){"use strict";function b(k){return t.reset(),t.models(e),l&&t.models(f),m&&t.models(g),k.each(function(k){var p=d3.select(this);a.utils.initSVG(p);var t=(i||parseInt(p.style("width"))||960)-h.left-h.right,u=(j||parseInt(p.style("height"))||400)-h.top-h.bottom;if(b.update=function(){r.beforeUpdate(),p.transition().duration(s).call(b)},b.container=this,!(k&&k.length&&k.filter(function(a){return a.values.hasOwnProperty("Q1")&&a.values.hasOwnProperty("Q2")&&a.values.hasOwnProperty("Q3")}).length)){var v=p.selectAll(".nv-noData").data([q]);return v.enter().append("text").attr("class","nvd3 nv-noData").attr("dy","-.7em").style("text-anchor","middle"),v.attr("x",h.left+t/2).attr("y",h.top+u/2).text(function(a){return a}),b}p.selectAll(".nv-noData").remove(),
+c=e.xScale(),d=e.yScale().clamp(!0);var w=p.selectAll("g.nv-wrap.nv-boxPlotWithAxes").data([k]),x=w.enter().append("g").attr("class","nvd3 nv-wrap nv-boxPlotWithAxes").append("g"),y=x.append("defs"),z=w.select("g");x.append("g").attr("class","nv-x nv-axis"),x.append("g").attr("class","nv-y nv-axis").append("g").attr("class","nv-zeroLine").append("line"),x.append("g").attr("class","nv-barsWrap"),z.attr("transform","translate("+h.left+","+h.top+")"),n&&z.select(".nv-y.nv-axis").attr("transform","translate("+t+",0)"),e.width(t).height(u);var A=z.select(".nv-barsWrap").datum(k.filter(function(a){return!a.disabled}));if(A.transition().call(e),y.append("clipPath").attr("id","nv-x-label-clip-"+e.id()).append("rect"),z.select("#nv-x-label-clip-"+e.id()+" rect").attr("width",c.rangeBand()*(o?2:1)).attr("height",16).attr("x",-c.rangeBand()/(o?1:2)),l){f.scale(c).ticks(a.utils.calcTicksX(t/100,k)).tickSize(-u,0),z.select(".nv-x.nv-axis").attr("transform","translate(0,"+d.range()[0]+")"),z.select(".nv-x.nv-axis").call(f);var B=z.select(".nv-x.nv-axis").selectAll("g");o&&B.selectAll("text").attr("transform",function(a,b,c){return"translate(0,"+(c%2==0?"5":"17")+")"})}m&&(g.scale(d).ticks(Math.floor(u/36)).tickSize(-t,0),z.select(".nv-y.nv-axis").call(g)),z.select(".nv-zeroLine line").attr("x1",0).attr("x2",t).attr("y1",d(0)).attr("y2",d(0))}),t.renderEnd("nv-boxplot chart immediate"),b}var c,d,e=a.models.boxPlot(),f=a.models.axis(),g=a.models.axis(),h={top:15,right:10,bottom:50,left:60},i=null,j=null,k=a.utils.getColor(),l=!0,m=!0,n=!1,o=!1,p=a.models.tooltip(),q="No Data Available.",r=d3.dispatch("tooltipShow","tooltipHide","beforeUpdate","renderEnd"),s=250;f.orient("bottom").showMaxMin(!1).tickFormat(function(a){return a}),g.orient(n?"right":"left").tickFormat(d3.format(",.1f")),p.duration(0);var t=a.utils.renderWatch(r,s);return e.dispatch.on("elementMouseover.tooltip",function(a){p.data(a).hidden(!1)}),e.dispatch.on("elementMouseout.tooltip",function(a){p.data(a).hidden(!0)}),e.dispatch.on("elementMousemove.tooltip",function(a){p.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.dispatch=r,b.boxplot=e,b.xAxis=f,b.yAxis=g,b.tooltip=p,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return i},set:function(a){i=a}},height:{get:function(){return j},set:function(a){j=a}},staggerLabels:{get:function(){return o},set:function(a){o=a}},showXAxis:{get:function(){return l},set:function(a){l=a}},showYAxis:{get:function(){return m},set:function(a){m=a}},tooltips:{get:function(){return tooltips},set:function(a){tooltips=a}},tooltipContent:{get:function(){return p},set:function(a){p=a}},noData:{get:function(){return q},set:function(a){q=a}},margin:{get:function(){return h},set:function(a){h.top=void 0!==a.top?a.top:h.top,h.right=void 0!==a.right?a.right:h.right,h.bottom=void 0!==a.bottom?a.bottom:h.bottom,h.left=void 0!==a.left?a.left:h.left}},duration:{get:function(){return s},set:function(a){s=a,t.reset(s),e.duration(s),f.duration(s),g.duration(s)}},color:{get:function(){return k},set:function(b){k=a.utils.getColor(b),e.color(k)}},rightAlignYAxis:{get:function(){return n},set:function(a){n=a,g.orient(a?"right":"left")}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.bullet=function(){"use strict";function b(d){return d.each(function(b,d){var p=m-c.left-c.right,s=n-c.top-c.bottom;o=d3.select(this),a.utils.initSVG(o);var t=f.call(this,b,d).slice().sort(d3.descending),u=g.call(this,b,d).slice().sort(d3.descending),v=h.call(this,b,d).slice().sort(d3.descending),w=i.call(this,b,d).slice(),x=j.call(this,b,d).slice(),y=k.call(this,b,d).slice(),z=d3.scale.linear().domain(d3.extent(d3.merge([l,t]))).range(e?[p,0]:[0,p]);this.__chart__||d3.scale.linear().domain([0,1/0]).range(z.range());this.__chart__=z;var A=d3.min(t),B=d3.max(t),C=t[1],D=o.selectAll("g.nv-wrap.nv-bullet").data([b]),E=D.enter().append("g").attr("class","nvd3 nv-wrap nv-bullet"),F=E.append("g"),G=D.select("g");F.append("rect").attr("class","nv-range nv-rangeMax"),F.append("rect").attr("class","nv-range nv-rangeAvg"),F.append("rect").attr("class","nv-range nv-rangeMin"),F.append("rect").attr("class","nv-measure"),D.attr("transform","translate("+c.left+","+c.top+")");var H=function(a){return Math.abs(z(a)-z(0))},I=function(a){return z(0>a?a:0)};G.select("rect.nv-rangeMax").attr("height",s).attr("width",H(B>0?B:A)).attr("x",I(B>0?B:A)).datum(B>0?B:A),G.select("rect.nv-rangeAvg").attr("height",s).attr("width",H(C)).attr("x",I(C)).datum(C),G.select("rect.nv-rangeMin").attr("height",s).attr("width",H(B)).attr("x",I(B)).attr("width",H(B>0?A:B)).attr("x",I(B>0?A:B)).datum(B>0?A:B),G.select("rect.nv-measure").style("fill",q).attr("height",s/3).attr("y",s/3).attr("width",0>v?z(0)-z(v[0]):z(v[0])-z(0)).attr("x",I(v)).on("mouseover",function(){r.elementMouseover({value:v[0],label:y[0]||"Current",color:d3.select(this).style("fill")})}).on("mousemove",function(){r.elementMousemove({value:v[0],label:y[0]||"Current",color:d3.select(this).style("fill")})}).on("mouseout",function(){r.elementMouseout({value:v[0],label:y[0]||"Current",color:d3.select(this).style("fill")})});var J=s/6,K=u.map(function(a,b){return{value:a,label:x[b]}});F.selectAll("path.nv-markerTriangle").data(K).enter().append("path").attr("class","nv-markerTriangle").attr("transform",function(a){return"translate("+z(a.value)+","+s/2+")"}).attr("d","M0,"+J+"L"+J+","+-J+" "+-J+","+-J+"Z").on("mouseover",function(a){r.elementMouseover({value:a.value,label:a.label||"Previous",color:d3.select(this).style("fill"),pos:[z(a.value),s/2]})}).on("mousemove",function(a){r.elementMousemove({value:a.value,label:a.label||"Previous",color:d3.select(this).style("fill")})}).on("mouseout",function(a,b){r.elementMouseout({value:a.value,label:a.label||"Previous",color:d3.select(this).style("fill")})}),D.selectAll(".nv-range").on("mouseover",function(a,b){var c=w[b]||(b?1==b?"Mean":"Minimum":"Maximum");r.elementMouseover({value:a,label:c,color:d3.select(this).style("fill")})}).on("mousemove",function(){r.elementMousemove({value:v[0],label:y[0]||"Previous",color:d3.select(this).style("fill")})}).on("mouseout",function(a,b){var c=w[b]||(b?1==b?"Mean":"Minimum":"Maximum");r.elementMouseout({value:a,label:c,color:d3.select(this).style("fill")})})}),b}var c={top:0,right:0,bottom:0,left:0},d="left",e=!1,f=function(a){return a.ranges},g=function(a){return a.markers?a.markers:[0]},h=function(a){return a.measures},i=function(a){return a.rangeLabels?a.rangeLabels:[]},j=function(a){return a.markerLabels?a.markerLabels:[]},k=function(a){return a.measureLabels?a.measureLabels:[]},l=[0],m=380,n=30,o=null,p=null,q=a.utils.getColor(["#1f77b4"]),r=d3.dispatch("elementMouseover","elementMouseout","elementMousemove");return b.dispatch=r,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{ranges:{get:function(){return f},set:function(a){f=a}},markers:{get:function(){return g},set:function(a){g=a}},measures:{get:function(){return h},set:function(a){h=a}},forceX:{get:function(){return l},set:function(a){l=a}},width:{get:function(){return m},set:function(a){m=a}},height:{get:function(){return n},set:function(a){n=a}},tickFormat:{get:function(){return p},set:function(a){p=a}},margin:{get:function(){return c},set:function(a){c.top=void 0!==a.top?a.top:c.top,c.right=void 0!==a.right?a.right:c.right,c.bottom=void 0!==a.bottom?a.bottom:c.bottom,c.left=void 0!==a.left?a.left:c.left}},orient:{get:function(){return d},set:function(a){d=a,e="right"==d||"bottom"==d}},color:{get:function(){return q},set:function(b){q=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.bulletChart=function(){"use strict";function b(d){return d.each(function(e,o){var p=d3.select(this);a.utils.initSVG(p);var q=a.utils.availableWidth(k,p,g),r=l-g.top-g.bottom;if(b.update=function(){b(d)},b.container=this,!e||!h.call(this,e,o))return a.utils.noData(b,p),b;p.selectAll(".nv-noData").remove();var s=h.call(this,e,o).slice().sort(d3.descending),t=i.call(this,e,o).slice().sort(d3.descending),u=j.call(this,e,o).slice().sort(d3.descending),v=p.selectAll("g.nv-wrap.nv-bulletChart").data([e]),w=v.enter().append("g").attr("class","nvd3 nv-wrap nv-bulletChart"),x=w.append("g"),y=v.select("g");x.append("g").attr("class","nv-bulletWrap"),x.append("g").attr("class","nv-titles"),v.attr("transform","translate("+g.left+","+g.top+")");var z=d3.scale.linear().domain([0,Math.max(s[0],t[0],u[0])]).range(f?[q,0]:[0,q]),A=this.__chart__||d3.scale.linear().domain([0,1/0]).range(z.range());this.__chart__=z;var B=x.select(".nv-titles").append("g").attr("text-anchor","end").attr("transform","translate(-6,"+(l-g.top-g.bottom)/2+")");B.append("text").attr("class","nv-title").text(function(a){return a.title}),B.append("text").attr("class","nv-subtitle").attr("dy","1em").text(function(a){return a.subtitle}),c.width(q).height(r);var C=y.select(".nv-bulletWrap");d3.transition(C).call(c);var D=m||z.tickFormat(q/100),E=y.selectAll("g.nv-tick").data(z.ticks(n?n:q/50),function(a){return this.textContent||D(a)}),F=E.enter().append("g").attr("class","nv-tick").attr("transform",function(a){return"translate("+A(a)+",0)"}).style("opacity",1e-6);F.append("line").attr("y1",r).attr("y2",7*r/6),F.append("text").attr("text-anchor","middle").attr("dy","1em").attr("y",7*r/6).text(D);var G=d3.transition(E).attr("transform",function(a){return"translate("+z(a)+",0)"}).style("opacity",1);G.select("line").attr("y1",r).attr("y2",7*r/6),G.select("text").attr("y",7*r/6),d3.transition(E.exit()).attr("transform",function(a){return"translate("+z(a)+",0)"}).style("opacity",1e-6).remove()}),d3.timer.flush(),b}var c=a.models.bullet(),d=a.models.tooltip(),e="left",f=!1,g={top:5,right:40,bottom:20,left:120},h=function(a){return a.ranges},i=function(a){return a.markers?a.markers:[0]},j=function(a){return a.measures},k=null,l=55,m=null,n=null,o=null,p=d3.dispatch("tooltipShow","tooltipHide");return d.duration(0).headerEnabled(!1),c.dispatch.on("elementMouseover.tooltip",function(a){a.series={key:a.label,value:a.value,color:a.color},d.data(a).hidden(!1)}),c.dispatch.on("elementMouseout.tooltip",function(a){d.hidden(!0)}),c.dispatch.on("elementMousemove.tooltip",function(a){d.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.bullet=c,b.dispatch=p,b.tooltip=d,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{ranges:{get:function(){return h},set:function(a){h=a}},markers:{get:function(){return i},set:function(a){i=a}},measures:{get:function(){return j},set:function(a){j=a}},width:{get:function(){return k},set:function(a){k=a}},height:{get:function(){return l},set:function(a){l=a}},tickFormat:{get:function(){return m},set:function(a){m=a}},ticks:{get:function(){return n},set:function(a){n=a}},noData:{get:function(){return o},set:function(a){o=a}},tooltips:{get:function(){return d.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),d.enabled(!!b)}},tooltipContent:{get:function(){return d.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),d.contentGenerator(b)}},margin:{get:function(){return g},set:function(a){g.top=void 0!==a.top?a.top:g.top,g.right=void 0!==a.right?a.right:g.right,g.bottom=void 0!==a.bottom?a.bottom:g.bottom,g.left=void 0!==a.left?a.left:g.left}},orient:{get:function(){return e},set:function(a){e=a,f="right"==e||"bottom"==e}}}),a.utils.inheritOptions(b,c),a.utils.initOptions(b),b},a.models.candlestickBar=function(){"use strict";function b(x){return x.each(function(b){c=d3.select(this);var x=a.utils.availableWidth(i,c,h),y=a.utils.availableHeight(j,c,h);a.utils.initSVG(c);var A=x/b[0].values.length*.45;l.domain(d||d3.extent(b[0].values.map(n).concat(t))),v?l.range(f||[.5*x/b[0].values.length,x*(b[0].values.length-.5)/b[0].values.length]):l.range(f||[5+A/2,x-A/2-5]),m.domain(e||[d3.min(b[0].values.map(s).concat(u)),d3.max(b[0].values.map(r).concat(u))]).range(g||[y,0]),l.domain()[0]===l.domain()[1]&&(l.domain()[0]?l.domain([l.domain()[0]-.01*l.domain()[0],l.domain()[1]+.01*l.domain()[1]]):l.domain([-1,1])),m.domain()[0]===m.domain()[1]&&(m.domain()[0]?m.domain([m.domain()[0]+.01*m.domain()[0],m.domain()[1]-.01*m.domain()[1]]):m.domain([-1,1]));var B=d3.select(this).selectAll("g.nv-wrap.nv-candlestickBar").data([b[0].values]),C=B.enter().append("g").attr("class","nvd3 nv-wrap nv-candlestickBar"),D=C.append("defs"),E=C.append("g"),F=B.select("g");E.append("g").attr("class","nv-ticks"),B.attr("transform","translate("+h.left+","+h.top+")"),c.on("click",function(a,b){z.chartClick({data:a,index:b,pos:d3.event,id:k})}),D.append("clipPath").attr("id","nv-chart-clip-path-"+k).append("rect"),B.select("#nv-chart-clip-path-"+k+" rect").attr("width",x).attr("height",y),F.attr("clip-path",w?"url(#nv-chart-clip-path-"+k+")":"");var G=B.select(".nv-ticks").selectAll(".nv-tick").data(function(a){return a});G.exit().remove();var H=G.enter().append("g").attr("class",function(a,b,c){return(p(a,b)>q(a,b)?"nv-tick negative":"nv-tick positive")+" nv-tick-"+c+"-"+b});H.append("line").attr("class","nv-candlestick-lines").attr("transform",function(a,b){return"translate("+l(n(a,b))+",0)"}).attr("x1",0).attr("y1",function(a,b){return m(r(a,b))}).attr("x2",0).attr("y2",function(a,b){return m(s(a,b))}),H.append("rect").attr("class","nv-candlestick-rects nv-bars").attr("transform",function(a,b){return"translate("+(l(n(a,b))-A/2)+","+(m(o(a,b))-(p(a,b)>q(a,b)?m(q(a,b))-m(p(a,b)):0))+")"}).attr("x",0).attr("y",0).attr("width",A).attr("height",function(a,b){var c=p(a,b),d=q(a,b);return c>d?m(d)-m(c):m(c)-m(d)});c.selectAll(".nv-candlestick-lines").transition().attr("transform",function(a,b){return"translate("+l(n(a,b))+",0)"}).attr("x1",0).attr("y1",function(a,b){return m(r(a,b))}).attr("x2",0).attr("y2",function(a,b){return m(s(a,b))}),c.selectAll(".nv-candlestick-rects").transition().attr("transform",function(a,b){return"translate("+(l(n(a,b))-A/2)+","+(m(o(a,b))-(p(a,b)>q(a,b)?m(q(a,b))-m(p(a,b)):0))+")"}).attr("x",0).attr("y",0).attr("width",A).attr("height",function(a,b){var c=p(a,b),d=q(a,b);return c>d?m(d)-m(c):m(c)-m(d)})}),b}var c,d,e,f,g,h={top:0,right:0,bottom:0,left:0},i=null,j=null,k=Math.floor(1e4*Math.random()),l=d3.scale.linear(),m=d3.scale.linear(),n=function(a){return a.x},o=function(a){return a.y},p=function(a){return a.open},q=function(a){return a.close},r=function(a){return a.high},s=function(a){return a.low},t=[],u=[],v=!1,w=!0,x=a.utils.defaultColor(),y=!1,z=d3.dispatch("tooltipShow","tooltipHide","stateChange","changeState","renderEnd","chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove");return b.highlightPoint=function(a,d){b.clearHighlights(),c.select(".nv-candlestickBar .nv-tick-0-"+a).classed("hover",d)},b.clearHighlights=function(){c.select(".nv-candlestickBar .nv-tick.hover").classed("hover",!1)},b.dispatch=z,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return i},set:function(a){i=a}},height:{get:function(){return j},set:function(a){j=a}},xScale:{get:function(){return l},set:function(a){l=a}},yScale:{get:function(){return m},set:function(a){m=a}},xDomain:{get:function(){return d},set:function(a){d=a}},yDomain:{get:function(){return e},set:function(a){e=a}},xRange:{get:function(){return f},set:function(a){f=a}},yRange:{get:function(){return g},set:function(a){g=a}},forceX:{get:function(){return t},set:function(a){t=a}},forceY:{get:function(){return u},set:function(a){u=a}},padData:{get:function(){return v},set:function(a){v=a}},clipEdge:{get:function(){return w},set:function(a){w=a}},id:{get:function(){return k},set:function(a){k=a}},interactive:{get:function(){return y},set:function(a){y=a}},x:{get:function(){return n},set:function(a){n=a}},y:{get:function(){return o},set:function(a){o=a}},open:{get:function(){return p()},set:function(a){p=a}},close:{get:function(){return q()},set:function(a){q=a}},high:{get:function(){return r},set:function(a){r=a}},low:{get:function(){return s},set:function(a){s=a}},margin:{get:function(){return h},set:function(a){h.top=void 0!=a.top?a.top:h.top,h.right=void 0!=a.right?a.right:h.right,h.bottom=void 0!=a.bottom?a.bottom:h.bottom,h.left=void 0!=a.left?a.left:h.left}},color:{get:function(){return x},set:function(b){x=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.cumulativeLineChart=function(){"use strict";function b(l){return H.reset(),H.models(f),r&&H.models(g),s&&H.models(h),l.each(function(l){function A(a,c){d3.select(b.container).style("cursor","ew-resize")}function E(a,b){G.x=d3.event.x,G.i=Math.round(F.invert(G.x)),K()}function H(a,c){d3.select(b.container).style("cursor","auto"),y.index=G.i,C.stateChange(y)}function K(){ba.data([G]);var a=b.duration();b.duration(0),b.update(),b.duration(a)}var L=d3.select(this);a.utils.initSVG(L),L.classed("nv-chart-"+x,!0);var M=this,N=a.utils.availableWidth(o,L,m),O=a.utils.availableHeight(p,L,m);if(b.update=function(){0===D?L.call(b):L.transition().duration(D).call(b)},b.container=this,y.setter(J(l),b.update).getter(I(l)).update(),y.disabled=l.map(function(a){return!!a.disabled}),!z){var P;z={};for(P in y)y[P]instanceof Array?z[P]=y[P].slice(0):z[P]=y[P]}var Q=d3.behavior.drag().on("dragstart",A).on("drag",E).on("dragend",H);if(!(l&&l.length&&l.filter(function(a){return a.values.length}).length))return a.utils.noData(b,L),b;if(L.selectAll(".nv-noData").remove(),d=f.xScale(),e=f.yScale(),w)f.yDomain(null);else{var R=l.filter(function(a){return!a.disabled}).map(function(a,b){var c=d3.extent(a.values,f.y());return c[0]<-.95&&(c[0]=-.95),[(c[0]-c[1])/(1+c[1]),(c[1]-c[0])/(1+c[0])]}),S=[d3.min(R,function(a){return a[0]}),d3.max(R,function(a){return a[1]})];f.yDomain(S)}F.domain([0,l[0].values.length-1]).range([0,N]).clamp(!0);var l=c(G.i,l),T=v?"none":"all",U=L.selectAll("g.nv-wrap.nv-cumulativeLine").data([l]),V=U.enter().append("g").attr("class","nvd3 nv-wrap nv-cumulativeLine").append("g"),W=U.select("g");if(V.append("g").attr("class","nv-interactive"),V.append("g").attr("class","nv-x nv-axis").style("pointer-events","none"),V.append("g").attr("class","nv-y nv-axis"),V.append("g").attr("class","nv-background"),V.append("g").attr("class","nv-linesWrap").style("pointer-events",T),V.append("g").attr("class","nv-avgLinesWrap").style("pointer-events","none"),V.append("g").attr("class","nv-legendWrap"),V.append("g").attr("class","nv-controlsWrap"),q&&(i.width(N),W.select(".nv-legendWrap").datum(l).call(i),m.top!=i.height()&&(m.top=i.height(),O=a.utils.availableHeight(p,L,m)),W.select(".nv-legendWrap").attr("transform","translate(0,"+-m.top+")")),u){var X=[{key:"Re-scale y-axis",disabled:!w}];j.width(140).color(["#444","#444","#444"]).rightAlign(!1).margin({top:5,right:0,bottom:5,left:20}),W.select(".nv-controlsWrap").datum(X).attr("transform","translate(0,"+-m.top+")").call(j)}U.attr("transform","translate("+m.left+","+m.top+")"),t&&W.select(".nv-y.nv-axis").attr("transform","translate("+N+",0)");var Y=l.filter(function(a){return a.tempDisabled});U.select(".tempDisabled").remove(),Y.length&&U.append("text").attr("class","tempDisabled").attr("x",N/2).attr("y","-.71em").style("text-anchor","end").text(Y.map(function(a){return a.key}).join(", ")+" values cannot be calculated for this time period."),v&&(k.width(N).height(O).margin({left:m.left,top:m.top}).svgContainer(L).xScale(d),U.select(".nv-interactive").call(k)),V.select(".nv-background").append("rect"),W.select(".nv-background rect").attr("width",N).attr("height",O),f.y(function(a){return a.display.y}).width(N).height(O).color(l.map(function(a,b){return a.color||n(a,b)}).filter(function(a,b){return!l[b].disabled&&!l[b].tempDisabled}));var Z=W.select(".nv-linesWrap").datum(l.filter(function(a){return!a.disabled&&!a.tempDisabled}));Z.call(f),l.forEach(function(a,b){a.seriesIndex=b});var $=l.filter(function(a){return!a.disabled&&!!B(a)}),_=W.select(".nv-avgLinesWrap").selectAll("line").data($,function(a){return a.key}),aa=function(a){var b=e(B(a));return 0>b?0:b>O?O:b};_.enter().append("line").style("stroke-width",2).style("stroke-dasharray","10,10").style("stroke",function(a,b){return f.color()(a,a.seriesIndex)}).attr("x1",0).attr("x2",N).attr("y1",aa).attr("y2",aa),_.style("stroke-opacity",function(a){var b=e(B(a));return 0>b||b>O?0:1}).attr("x1",0).attr("x2",N).attr("y1",aa).attr("y2",aa),_.exit().remove();var ba=Z.selectAll(".nv-indexLine").data([G]);ba.enter().append("rect").attr("class","nv-indexLine").attr("width",3).attr("x",-2).attr("fill","red").attr("fill-opacity",.5).style("pointer-events","all").call(Q),ba.attr("transform",function(a){return"translate("+F(a.i)+",0)"}).attr("height",O),r&&(g.scale(d)._ticks(a.utils.calcTicksX(N/70,l)).tickSize(-O,0),W.select(".nv-x.nv-axis").attr("transform","translate(0,"+e.range()[0]+")"),W.select(".nv-x.nv-axis").call(g)),s&&(h.scale(e)._ticks(a.utils.calcTicksY(O/36,l)).tickSize(-N,0),W.select(".nv-y.nv-axis").call(h)),W.select(".nv-background rect").on("click",function(){G.x=d3.mouse(this)[0],G.i=Math.round(F.invert(G.x)),y.index=G.i,C.stateChange(y),K()}),f.dispatch.on("elementClick",function(a){G.i=a.pointIndex,G.x=F(G.i),y.index=G.i,C.stateChange(y),K()}),j.dispatch.on("legendClick",function(a,c){a.disabled=!a.disabled,w=!a.disabled,y.rescaleY=w,C.stateChange(y),b.update()}),i.dispatch.on("stateChange",function(a){for(var c in a)y[c]=a[c];C.stateChange(y),b.update()}),k.dispatch.on("elementMousemove",function(c){f.clearHighlights();var d,e,i,j=[];if(l.filter(function(a,b){return a.seriesIndex=b,!a.disabled}).forEach(function(g,h){e=a.interactiveBisect(g.values,c.pointXValue,b.x()),f.highlightPoint(h,e,!0);var k=g.values[e];"undefined"!=typeof k&&("undefined"==typeof d&&(d=k),"undefined"==typeof i&&(i=b.xScale()(b.x()(k,e))),j.push({key:g.key,value:b.y()(k,e),color:n(g,g.seriesIndex)}))}),j.length>2){var o=b.yScale().invert(c.mouseY),p=Math.abs(b.yScale().domain()[0]-b.yScale().domain()[1]),q=.03*p,r=a.nearestValueIndex(j.map(function(a){return a.value}),o,q);null!==r&&(j[r].highlight=!0)}var s=g.tickFormat()(b.x()(d,e),e);k.tooltip.position({left:i+m.left,top:c.mouseY+m.top}).chartContainer(M.parentNode).valueFormatter(function(a,b){return h.tickFormat()(a)}).data({value:s,series:j})(),k.renderGuideLine(i)}),k.dispatch.on("elementMouseout",function(a){f.clearHighlights()}),C.on("changeState",function(a){"undefined"!=typeof a.disabled&&(l.forEach(function(b,c){b.disabled=a.disabled[c]}),y.disabled=a.disabled),"undefined"!=typeof a.index&&(G.i=a.index,G.x=F(G.i),y.index=a.index,ba.data([G])),"undefined"!=typeof a.rescaleY&&(w=a.rescaleY),b.update()})}),H.renderEnd("cumulativeLineChart immediate"),b}function c(a,b){return K||(K=f.y()),b.map(function(b,c){if(!b.values)return b;var d=b.values[a];if(null==d)return b;var e=K(d,a);return-.95>e&&!E?(b.tempDisabled=!0,b):(b.tempDisabled=!1,b.values=b.values.map(function(a,b){return a.display={y:(K(a,b)-e)/(1+e)},a}),b)})}var d,e,f=a.models.line(),g=a.models.axis(),h=a.models.axis(),i=a.models.legend(),j=a.models.legend(),k=a.interactiveGuideline(),l=a.models.tooltip(),m={top:30,right:30,bottom:50,left:60},n=a.utils.defaultColor(),o=null,p=null,q=!0,r=!0,s=!0,t=!1,u=!0,v=!1,w=!0,x=f.id(),y=a.utils.state(),z=null,A=null,B=function(a){return a.average},C=d3.dispatch("stateChange","changeState","renderEnd"),D=250,E=!1;y.index=0,y.rescaleY=w,g.orient("bottom").tickPadding(7),h.orient(t?"right":"left"),l.valueFormatter(function(a,b){return h.tickFormat()(a,b)}).headerFormatter(function(a,b){return g.tickFormat()(a,b)}),j.updateState(!1);var F=d3.scale.linear(),G={i:0,x:0},H=a.utils.renderWatch(C,D),I=function(a){return function(){return{active:a.map(function(a){return!a.disabled}),index:G.i,rescaleY:w}}},J=function(a){return function(b){void 0!==b.index&&(G.i=b.index),void 0!==b.rescaleY&&(w=b.rescaleY),void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};f.dispatch.on("elementMouseover.tooltip",function(a){var c={x:b.x()(a.point),y:b.y()(a.point),color:a.point.color};a.point=c,l.data(a).position(a.pos).hidden(!1)}),f.dispatch.on("elementMouseout.tooltip",function(a){l.hidden(!0)});var K=null;return b.dispatch=C,b.lines=f,b.legend=i,b.controls=j,b.xAxis=g,b.yAxis=h,b.interactiveLayer=k,b.state=y,b.tooltip=l,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return o},set:function(a){o=a}},height:{get:function(){return p},set:function(a){p=a}},rescaleY:{get:function(){return w},set:function(a){w=a}},showControls:{get:function(){return u},set:function(a){u=a}},showLegend:{get:function(){return q},set:function(a){q=a}},average:{get:function(){return B},set:function(a){B=a}},defaultState:{get:function(){return z},set:function(a){z=a}},noData:{get:function(){return A},set:function(a){A=a}},showXAxis:{get:function(){return r},set:function(a){r=a}},showYAxis:{get:function(){return s},set:function(a){s=a}},noErrorCheck:{get:function(){return E},set:function(a){E=a}},tooltips:{get:function(){return l.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),l.enabled(!!b)}},tooltipContent:{get:function(){return l.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),l.contentGenerator(b)}},margin:{get:function(){return m},set:function(a){m.top=void 0!==a.top?a.top:m.top,m.right=void 0!==a.right?a.right:m.right,m.bottom=void 0!==a.bottom?a.bottom:m.bottom,m.left=void 0!==a.left?a.left:m.left}},color:{get:function(){return n},set:function(b){n=a.utils.getColor(b),i.color(n)}},useInteractiveGuideline:{get:function(){return v},set:function(a){v=a,a===!0&&(b.interactive(!1),b.useVoronoi(!1))}},rightAlignYAxis:{get:function(){return t},set:function(a){t=a,h.orient(a?"right":"left")}},duration:{get:function(){return D},set:function(a){D=a,f.duration(D),g.duration(D),h.duration(D),H.reset(D)}}}),a.utils.inheritOptions(b,f),a.utils.initOptions(b),b},a.models.discreteBar=function(){"use strict";function b(m){return y.reset(),m.each(function(b){var m=k-j.left-j.right,x=l-j.top-j.bottom;c=d3.select(this),a.utils.initSVG(c),b.forEach(function(a,b){a.values.forEach(function(a){a.series=b})});var z=d&&e?[]:b.map(function(a){return a.values.map(function(a,b){return{x:p(a,b),y:q(a,b),y0:a.y0}})});n.domain(d||d3.merge(z).map(function(a){return a.x})).rangeBands(f||[0,m],.1),o.domain(e||d3.extent(d3.merge(z).map(function(a){return a.y}).concat(r))),t?o.range(g||[x-(o.domain()[0]<0?12:0),o.domain()[1]>0?12:0]):o.range(g||[x,0]),h=h||n,i=i||o.copy().range([o(0),o(0)]);var A=c.selectAll("g.nv-wrap.nv-discretebar").data([b]),B=A.enter().append("g").attr("class","nvd3 nv-wrap nv-discretebar"),C=B.append("g");A.select("g");C.append("g").attr("class","nv-groups"),A.attr("transform","translate("+j.left+","+j.top+")");var D=A.select(".nv-groups").selectAll(".nv-group").data(function(a){return a},function(a){return a.key});D.enter().append("g").style("stroke-opacity",1e-6).style("fill-opacity",1e-6),D.exit().watchTransition(y,"discreteBar: exit groups").style("stroke-opacity",1e-6).style("fill-opacity",1e-6).remove(),D.attr("class",function(a,b){return"nv-group nv-series-"+b}).classed("hover",function(a){return a.hover}),D.watchTransition(y,"discreteBar: groups").style("stroke-opacity",1).style("fill-opacity",.75);var E=D.selectAll("g.nv-bar").data(function(a){return a.values});E.exit().remove();var F=E.enter().append("g").attr("transform",function(a,b,c){return"translate("+(n(p(a,b))+.05*n.rangeBand())+", "+o(0)+")"}).on("mouseover",function(a,b){d3.select(this).classed("hover",!0),v.elementMouseover({data:a,index:b,color:d3.select(this).style("fill")})}).on("mouseout",function(a,b){d3.select(this).classed("hover",!1),v.elementMouseout({data:a,index:b,color:d3.select(this).style("fill")})}).on("mousemove",function(a,b){v.elementMousemove({data:a,index:b,color:d3.select(this).style("fill")})}).on("click",function(a,b){v.elementClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation()}).on("dblclick",function(a,b){v.elementDblClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation()});F.append("rect").attr("height",0).attr("width",.9*n.rangeBand()/b.length),t?(F.append("text").attr("text-anchor","middle"),E.select("text").text(function(a,b){return u(q(a,b))}).watchTransition(y,"discreteBar: bars text").attr("x",.9*n.rangeBand()/2).attr("y",function(a,b){return q(a,b)<0?o(q(a,b))-o(0)+12:-4})):E.selectAll("text").remove(),E.attr("class",function(a,b){return q(a,b)<0?"nv-bar negative":"nv-bar positive"}).style("fill",function(a,b){return a.color||s(a,b)}).style("stroke",function(a,b){return a.color||s(a,b)}).select("rect").attr("class",w).watchTransition(y,"discreteBar: bars rect").attr("width",.9*n.rangeBand()/b.length),E.watchTransition(y,"discreteBar: bars").attr("transform",function(a,b){var c=n(p(a,b))+.05*n.rangeBand(),d=q(a,b)<0?o(0):o(0)-o(q(a,b))<1?o(0)-1:o(q(a,b));return"translate("+c+", "+d+")"}).select("rect").attr("height",function(a,b){return Math.max(Math.abs(o(q(a,b))-o(e&&e[0]||0))||1)}),h=n.copy(),i=o.copy()}),y.renderEnd("discreteBar immediate"),b}var c,d,e,f,g,h,i,j={top:0,right:0,bottom:0,left:0},k=960,l=500,m=Math.floor(1e4*Math.random()),n=d3.scale.ordinal(),o=d3.scale.linear(),p=function(a){return a.x},q=function(a){return a.y},r=[0],s=a.utils.defaultColor(),t=!1,u=d3.format(",.2f"),v=d3.dispatch("chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove","renderEnd"),w="discreteBar",x=250,y=a.utils.renderWatch(v,x);return b.dispatch=v,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return k},set:function(a){k=a}},height:{get:function(){return l},set:function(a){l=a}},forceY:{get:function(){return r},set:function(a){r=a}},showValues:{get:function(){return t},set:function(a){t=a}},x:{get:function(){return p},set:function(a){p=a}},y:{get:function(){return q},set:function(a){q=a}},xScale:{get:function(){return n},set:function(a){n=a}},yScale:{get:function(){return o},set:function(a){o=a}},xDomain:{get:function(){return d},set:function(a){d=a}},yDomain:{get:function(){return e},set:function(a){e=a}},xRange:{get:function(){return f},set:function(a){f=a}},yRange:{get:function(){return g},set:function(a){g=a}},valueFormat:{get:function(){return u},set:function(a){u=a}},id:{get:function(){return m},set:function(a){m=a}},rectClass:{get:function(){return w},set:function(a){w=a}},margin:{get:function(){return j},set:function(a){j.top=void 0!==a.top?a.top:j.top,j.right=void 0!==a.right?a.right:j.right,j.bottom=void 0!==a.bottom?a.bottom:j.bottom,j.left=void 0!==a.left?a.left:j.left}},color:{get:function(){return s},set:function(b){s=a.utils.getColor(b)}},duration:{get:function(){return x},set:function(a){x=a,y.reset(x)}}}),a.utils.initOptions(b),b},a.models.discreteBarChart=function(){"use strict";function b(h){return t.reset(),t.models(e),m&&t.models(f),n&&t.models(g),h.each(function(h){var l=d3.select(this);a.utils.initSVG(l);var q=a.utils.availableWidth(j,l,i),t=a.utils.availableHeight(k,l,i);if(b.update=function(){r.beforeUpdate(),l.transition().duration(s).call(b)},b.container=this,!(h&&h.length&&h.filter(function(a){return a.values.length}).length))return a.utils.noData(b,l),b;l.selectAll(".nv-noData").remove(),c=e.xScale(),d=e.yScale().clamp(!0);var u=l.selectAll("g.nv-wrap.nv-discreteBarWithAxes").data([h]),v=u.enter().append("g").attr("class","nvd3 nv-wrap nv-discreteBarWithAxes").append("g"),w=v.append("defs"),x=u.select("g");v.append("g").attr("class","nv-x nv-axis"),v.append("g").attr("class","nv-y nv-axis").append("g").attr("class","nv-zeroLine").append("line"),v.append("g").attr("class","nv-barsWrap"),x.attr("transform","translate("+i.left+","+i.top+")"),o&&x.select(".nv-y.nv-axis").attr("transform","translate("+q+",0)"),e.width(q).height(t);var y=x.select(".nv-barsWrap").datum(h.filter(function(a){return!a.disabled}));if(y.transition().call(e),w.append("clipPath").attr("id","nv-x-label-clip-"+e.id()).append("rect"),
+x.select("#nv-x-label-clip-"+e.id()+" rect").attr("width",c.rangeBand()*(p?2:1)).attr("height",16).attr("x",-c.rangeBand()/(p?1:2)),m){f.scale(c)._ticks(a.utils.calcTicksX(q/100,h)).tickSize(-t,0),x.select(".nv-x.nv-axis").attr("transform","translate(0,"+(d.range()[0]+(e.showValues()&&d.domain()[0]<0?16:0))+")"),x.select(".nv-x.nv-axis").call(f);var z=x.select(".nv-x.nv-axis").selectAll("g");p&&z.selectAll("text").attr("transform",function(a,b,c){return"translate(0,"+(c%2==0?"5":"17")+")"})}n&&(g.scale(d)._ticks(a.utils.calcTicksY(t/36,h)).tickSize(-q,0),x.select(".nv-y.nv-axis").call(g)),x.select(".nv-zeroLine line").attr("x1",0).attr("x2",q).attr("y1",d(0)).attr("y2",d(0))}),t.renderEnd("discreteBar chart immediate"),b}var c,d,e=a.models.discreteBar(),f=a.models.axis(),g=a.models.axis(),h=a.models.tooltip(),i={top:15,right:10,bottom:50,left:60},j=null,k=null,l=a.utils.getColor(),m=!0,n=!0,o=!1,p=!1,q=null,r=d3.dispatch("beforeUpdate","renderEnd"),s=250;f.orient("bottom").showMaxMin(!1).tickFormat(function(a){return a}),g.orient(o?"right":"left").tickFormat(d3.format(",.1f")),h.duration(0).headerEnabled(!1).valueFormatter(function(a,b){return g.tickFormat()(a,b)}).keyFormatter(function(a,b){return f.tickFormat()(a,b)});var t=a.utils.renderWatch(r,s);return e.dispatch.on("elementMouseover.tooltip",function(a){a.series={key:b.x()(a.data),value:b.y()(a.data),color:a.color},h.data(a).hidden(!1)}),e.dispatch.on("elementMouseout.tooltip",function(a){h.hidden(!0)}),e.dispatch.on("elementMousemove.tooltip",function(a){h.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.dispatch=r,b.discretebar=e,b.xAxis=f,b.yAxis=g,b.tooltip=h,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return j},set:function(a){j=a}},height:{get:function(){return k},set:function(a){k=a}},staggerLabels:{get:function(){return p},set:function(a){p=a}},showXAxis:{get:function(){return m},set:function(a){m=a}},showYAxis:{get:function(){return n},set:function(a){n=a}},noData:{get:function(){return q},set:function(a){q=a}},tooltips:{get:function(){return h.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),h.enabled(!!b)}},tooltipContent:{get:function(){return h.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),h.contentGenerator(b)}},margin:{get:function(){return i},set:function(a){i.top=void 0!==a.top?a.top:i.top,i.right=void 0!==a.right?a.right:i.right,i.bottom=void 0!==a.bottom?a.bottom:i.bottom,i.left=void 0!==a.left?a.left:i.left}},duration:{get:function(){return s},set:function(a){s=a,t.reset(s),e.duration(s),f.duration(s),g.duration(s)}},color:{get:function(){return l},set:function(b){l=a.utils.getColor(b),e.color(l)}},rightAlignYAxis:{get:function(){return o},set:function(a){o=a,g.orient(a?"right":"left")}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.distribution=function(){"use strict";function b(k){return m.reset(),k.each(function(b){var k=(e-("x"===g?d.left+d.right:d.top+d.bottom),"x"==g?"y":"x"),l=d3.select(this);a.utils.initSVG(l),c=c||j;var n=l.selectAll("g.nv-distribution").data([b]),o=n.enter().append("g").attr("class","nvd3 nv-distribution"),p=(o.append("g"),n.select("g"));n.attr("transform","translate("+d.left+","+d.top+")");var q=p.selectAll("g.nv-dist").data(function(a){return a},function(a){return a.key});q.enter().append("g"),q.attr("class",function(a,b){return"nv-dist nv-series-"+b}).style("stroke",function(a,b){return i(a,b)});var r=q.selectAll("line.nv-dist"+g).data(function(a){return a.values});r.enter().append("line").attr(g+"1",function(a,b){return c(h(a,b))}).attr(g+"2",function(a,b){return c(h(a,b))}),m.transition(q.exit().selectAll("line.nv-dist"+g),"dist exit").attr(g+"1",function(a,b){return j(h(a,b))}).attr(g+"2",function(a,b){return j(h(a,b))}).style("stroke-opacity",0).remove(),r.attr("class",function(a,b){return"nv-dist"+g+" nv-dist"+g+"-"+b}).attr(k+"1",0).attr(k+"2",f),m.transition(r,"dist").attr(g+"1",function(a,b){return j(h(a,b))}).attr(g+"2",function(a,b){return j(h(a,b))}),c=j.copy()}),m.renderEnd("distribution immediate"),b}var c,d={top:0,right:0,bottom:0,left:0},e=400,f=8,g="x",h=function(a){return a[g]},i=a.utils.defaultColor(),j=d3.scale.linear(),k=250,l=d3.dispatch("renderEnd"),m=a.utils.renderWatch(l,k);return b.options=a.utils.optionsFunc.bind(b),b.dispatch=l,b.margin=function(a){return arguments.length?(d.top="undefined"!=typeof a.top?a.top:d.top,d.right="undefined"!=typeof a.right?a.right:d.right,d.bottom="undefined"!=typeof a.bottom?a.bottom:d.bottom,d.left="undefined"!=typeof a.left?a.left:d.left,b):d},b.width=function(a){return arguments.length?(e=a,b):e},b.axis=function(a){return arguments.length?(g=a,b):g},b.size=function(a){return arguments.length?(f=a,b):f},b.getData=function(a){return arguments.length?(h=d3.functor(a),b):h},b.scale=function(a){return arguments.length?(j=a,b):j},b.color=function(c){return arguments.length?(i=a.utils.getColor(c),b):i},b.duration=function(a){return arguments.length?(k=a,m.reset(k),b):k},b},a.models.furiousLegend=function(){"use strict";function b(p){function q(a,b){return"furious"!=o?"#000":m?a.disengaged?g(a,b):"#fff":m?void 0:a.disabled?g(a,b):"#fff"}function r(a,b){return m&&"furious"==o?a.disengaged?"#fff":g(a,b):a.disabled?"#fff":g(a,b)}return p.each(function(b){var p=d-c.left-c.right,s=d3.select(this);a.utils.initSVG(s);var t=s.selectAll("g.nv-legend").data([b]),u=(t.enter().append("g").attr("class","nvd3 nv-legend").append("g"),t.select("g"));t.attr("transform","translate("+c.left+","+c.top+")");var v,w=u.selectAll(".nv-series").data(function(a){return"furious"!=o?a:a.filter(function(a){return m?!0:!a.disengaged})}),x=w.enter().append("g").attr("class","nv-series");if("classic"==o)x.append("circle").style("stroke-width",2).attr("class","nv-legend-symbol").attr("r",5),v=w.select("circle");else if("furious"==o){x.append("rect").style("stroke-width",2).attr("class","nv-legend-symbol").attr("rx",3).attr("ry",3),v=w.select("rect"),x.append("g").attr("class","nv-check-box").property("innerHTML",'<path d="M0.5,5 L22.5,5 L22.5,26.5 L0.5,26.5 L0.5,5 Z" class="nv-box"></path><path d="M5.5,12.8618467 L11.9185089,19.2803556 L31,0.198864511" class="nv-check"></path>').attr("transform","translate(-10,-8)scale(0.5)");var y=w.select(".nv-check-box");y.each(function(a,b){d3.select(this).selectAll("path").attr("stroke",q(a,b))})}x.append("text").attr("text-anchor","start").attr("class","nv-legend-text").attr("dy",".32em").attr("dx","8");var z=w.select("text.nv-legend-text");w.on("mouseover",function(a,b){n.legendMouseover(a,b)}).on("mouseout",function(a,b){n.legendMouseout(a,b)}).on("click",function(a,b){n.legendClick(a,b);var c=w.data();if(k){if("classic"==o)l?(c.forEach(function(a){a.disabled=!0}),a.disabled=!1):(a.disabled=!a.disabled,c.every(function(a){return a.disabled})&&c.forEach(function(a){a.disabled=!1}));else if("furious"==o)if(m)a.disengaged=!a.disengaged,a.userDisabled=void 0==a.userDisabled?!!a.disabled:a.userDisabled,a.disabled=a.disengaged||a.userDisabled;else if(!m){a.disabled=!a.disabled,a.userDisabled=a.disabled;var d=c.filter(function(a){return!a.disengaged});d.every(function(a){return a.userDisabled})&&c.forEach(function(a){a.disabled=a.userDisabled=!1})}n.stateChange({disabled:c.map(function(a){return!!a.disabled}),disengaged:c.map(function(a){return!!a.disengaged})})}}).on("dblclick",function(a,b){if(("furious"!=o||!m)&&(n.legendDblclick(a,b),k)){var c=w.data();c.forEach(function(a){a.disabled=!0,"furious"==o&&(a.userDisabled=a.disabled)}),a.disabled=!1,"furious"==o&&(a.userDisabled=a.disabled),n.stateChange({disabled:c.map(function(a){return!!a.disabled})})}}),w.classed("nv-disabled",function(a){return a.userDisabled}),w.exit().remove(),z.attr("fill",q).text(f);var A;switch(o){case"furious":A=23;break;case"classic":A=20}if(h){var B=[];w.each(function(b,c){var d,e=d3.select(this).select("text");try{if(d=e.node().getComputedTextLength(),0>=d)throw Error()}catch(f){d=a.utils.calcApproxTextWidth(e)}B.push(d+i)});for(var C=0,D=0,E=[];p>D&&C<B.length;)E[C]=B[C],D+=B[C++];for(0===C&&(C=1);D>p&&C>1;){E=[],C--;for(var F=0;F<B.length;F++)B[F]>(E[F%C]||0)&&(E[F%C]=B[F]);D=E.reduce(function(a,b,c,d){return a+b})}for(var G=[],H=0,I=0;C>H;H++)G[H]=I,I+=E[H];w.attr("transform",function(a,b){return"translate("+G[b%C]+","+(5+Math.floor(b/C)*A)+")"}),j?u.attr("transform","translate("+(d-c.right-D)+","+c.top+")"):u.attr("transform","translate(0,"+c.top+")"),e=c.top+c.bottom+Math.ceil(B.length/C)*A}else{var J,K=5,L=5,M=0;w.attr("transform",function(a,b){var e=d3.select(this).select("text").node().getComputedTextLength()+i;return J=L,d<c.left+c.right+J+e&&(L=J=5,K+=A),L+=e,L>M&&(M=L),"translate("+J+","+K+")"}),u.attr("transform","translate("+(d-c.right-M)+","+c.top+")"),e=c.top+c.bottom+K+15}"furious"==o&&v.attr("width",function(a,b){return z[0][b].getComputedTextLength()+27}).attr("height",18).attr("y",-9).attr("x",-15),v.style("fill",r).style("stroke",function(a,b){return a.color||g(a,b)})}),b}var c={top:5,right:0,bottom:5,left:0},d=400,e=20,f=function(a){return a.key},g=a.utils.getColor(),h=!0,i=28,j=!0,k=!0,l=!1,m=!1,n=d3.dispatch("legendClick","legendDblclick","legendMouseover","legendMouseout","stateChange"),o="classic";return b.dispatch=n,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return d},set:function(a){d=a}},height:{get:function(){return e},set:function(a){e=a}},key:{get:function(){return f},set:function(a){f=a}},align:{get:function(){return h},set:function(a){h=a}},rightAlign:{get:function(){return j},set:function(a){j=a}},padding:{get:function(){return i},set:function(a){i=a}},updateState:{get:function(){return k},set:function(a){k=a}},radioButtonMode:{get:function(){return l},set:function(a){l=a}},expanded:{get:function(){return m},set:function(a){m=a}},vers:{get:function(){return o},set:function(a){o=a}},margin:{get:function(){return c},set:function(a){c.top=void 0!==a.top?a.top:c.top,c.right=void 0!==a.right?a.right:c.right,c.bottom=void 0!==a.bottom?a.bottom:c.bottom,c.left=void 0!==a.left?a.left:c.left}},color:{get:function(){return g},set:function(b){g=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.historicalBar=function(){"use strict";function b(x){return x.each(function(b){w.reset(),k=d3.select(this);var x=a.utils.availableWidth(h,k,g),y=a.utils.availableHeight(i,k,g);a.utils.initSVG(k),l.domain(c||d3.extent(b[0].values.map(n).concat(p))),r?l.range(e||[.5*x/b[0].values.length,x*(b[0].values.length-.5)/b[0].values.length]):l.range(e||[0,x]),m.domain(d||d3.extent(b[0].values.map(o).concat(q))).range(f||[y,0]),l.domain()[0]===l.domain()[1]&&(l.domain()[0]?l.domain([l.domain()[0]-.01*l.domain()[0],l.domain()[1]+.01*l.domain()[1]]):l.domain([-1,1])),m.domain()[0]===m.domain()[1]&&(m.domain()[0]?m.domain([m.domain()[0]+.01*m.domain()[0],m.domain()[1]-.01*m.domain()[1]]):m.domain([-1,1]));var z=k.selectAll("g.nv-wrap.nv-historicalBar-"+j).data([b[0].values]),A=z.enter().append("g").attr("class","nvd3 nv-wrap nv-historicalBar-"+j),B=A.append("defs"),C=A.append("g"),D=z.select("g");C.append("g").attr("class","nv-bars"),z.attr("transform","translate("+g.left+","+g.top+")"),k.on("click",function(a,b){u.chartClick({data:a,index:b,pos:d3.event,id:j})}),B.append("clipPath").attr("id","nv-chart-clip-path-"+j).append("rect"),z.select("#nv-chart-clip-path-"+j+" rect").attr("width",x).attr("height",y),D.attr("clip-path",s?"url(#nv-chart-clip-path-"+j+")":"");var E=z.select(".nv-bars").selectAll(".nv-bar").data(function(a){return a},function(a,b){return n(a,b)});E.exit().remove(),E.enter().append("rect").attr("x",0).attr("y",function(b,c){return a.utils.NaNtoZero(m(Math.max(0,o(b,c))))}).attr("height",function(b,c){return a.utils.NaNtoZero(Math.abs(m(o(b,c))-m(0)))}).attr("transform",function(a,c){return"translate("+(l(n(a,c))-x/b[0].values.length*.45)+",0)"}).on("mouseover",function(a,b){v&&(d3.select(this).classed("hover",!0),u.elementMouseover({data:a,index:b,color:d3.select(this).style("fill")}))}).on("mouseout",function(a,b){v&&(d3.select(this).classed("hover",!1),u.elementMouseout({data:a,index:b,color:d3.select(this).style("fill")}))}).on("mousemove",function(a,b){v&&u.elementMousemove({data:a,index:b,color:d3.select(this).style("fill")})}).on("click",function(a,b){v&&(u.elementClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation())}).on("dblclick",function(a,b){v&&(u.elementDblClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation())}),E.attr("fill",function(a,b){return t(a,b)}).attr("class",function(a,b,c){return(o(a,b)<0?"nv-bar negative":"nv-bar positive")+" nv-bar-"+c+"-"+b}).watchTransition(w,"bars").attr("transform",function(a,c){return"translate("+(l(n(a,c))-x/b[0].values.length*.45)+",0)"}).attr("width",x/b[0].values.length*.9),E.watchTransition(w,"bars").attr("y",function(b,c){var d=o(b,c)<0?m(0):m(0)-m(o(b,c))<1?m(0)-1:m(o(b,c));return a.utils.NaNtoZero(d)}).attr("height",function(b,c){return a.utils.NaNtoZero(Math.max(Math.abs(m(o(b,c))-m(0)),1))})}),w.renderEnd("historicalBar immediate"),b}var c,d,e,f,g={top:0,right:0,bottom:0,left:0},h=null,i=null,j=Math.floor(1e4*Math.random()),k=null,l=d3.scale.linear(),m=d3.scale.linear(),n=function(a){return a.x},o=function(a){return a.y},p=[],q=[0],r=!1,s=!0,t=a.utils.defaultColor(),u=d3.dispatch("chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove","renderEnd"),v=!0,w=a.utils.renderWatch(u,0);return b.highlightPoint=function(a,b){k.select(".nv-bars .nv-bar-0-"+a).classed("hover",b)},b.clearHighlights=function(){k.select(".nv-bars .nv-bar.hover").classed("hover",!1)},b.dispatch=u,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return h},set:function(a){h=a}},height:{get:function(){return i},set:function(a){i=a}},forceX:{get:function(){return p},set:function(a){p=a}},forceY:{get:function(){return q},set:function(a){q=a}},padData:{get:function(){return r},set:function(a){r=a}},x:{get:function(){return n},set:function(a){n=a}},y:{get:function(){return o},set:function(a){o=a}},xScale:{get:function(){return l},set:function(a){l=a}},yScale:{get:function(){return m},set:function(a){m=a}},xDomain:{get:function(){return c},set:function(a){c=a}},yDomain:{get:function(){return d},set:function(a){d=a}},xRange:{get:function(){return e},set:function(a){e=a}},yRange:{get:function(){return f},set:function(a){f=a}},clipEdge:{get:function(){return s},set:function(a){s=a}},id:{get:function(){return j},set:function(a){j=a}},interactive:{get:function(){return v},set:function(a){v=a}},margin:{get:function(){return g},set:function(a){g.top=void 0!==a.top?a.top:g.top,g.right=void 0!==a.right?a.right:g.right,g.bottom=void 0!==a.bottom?a.bottom:g.bottom,g.left=void 0!==a.left?a.left:g.left}},color:{get:function(){return t},set:function(b){t=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.historicalBarChart=function(b){"use strict";function c(b){return b.each(function(k){z.reset(),z.models(f),q&&z.models(g),r&&z.models(h);var w=d3.select(this),A=this;a.utils.initSVG(w);var B=a.utils.availableWidth(n,w,l),C=a.utils.availableHeight(o,w,l);if(c.update=function(){w.transition().duration(y).call(c)},c.container=this,u.disabled=k.map(function(a){return!!a.disabled}),!v){var D;v={};for(D in u)u[D]instanceof Array?v[D]=u[D].slice(0):v[D]=u[D]}if(!(k&&k.length&&k.filter(function(a){return a.values.length}).length))return a.utils.noData(c,w),c;w.selectAll(".nv-noData").remove(),d=f.xScale(),e=f.yScale();var E=w.selectAll("g.nv-wrap.nv-historicalBarChart").data([k]),F=E.enter().append("g").attr("class","nvd3 nv-wrap nv-historicalBarChart").append("g"),G=E.select("g");F.append("g").attr("class","nv-x nv-axis"),F.append("g").attr("class","nv-y nv-axis"),F.append("g").attr("class","nv-barsWrap"),F.append("g").attr("class","nv-legendWrap"),F.append("g").attr("class","nv-interactive"),p&&(i.width(B),G.select(".nv-legendWrap").datum(k).call(i),l.top!=i.height()&&(l.top=i.height(),C=a.utils.availableHeight(o,w,l)),E.select(".nv-legendWrap").attr("transform","translate(0,"+-l.top+")")),E.attr("transform","translate("+l.left+","+l.top+")"),s&&G.select(".nv-y.nv-axis").attr("transform","translate("+B+",0)"),t&&(j.width(B).height(C).margin({left:l.left,top:l.top}).svgContainer(w).xScale(d),E.select(".nv-interactive").call(j)),f.width(B).height(C).color(k.map(function(a,b){return a.color||m(a,b)}).filter(function(a,b){return!k[b].disabled}));var H=G.select(".nv-barsWrap").datum(k.filter(function(a){return!a.disabled}));H.transition().call(f),q&&(g.scale(d)._ticks(a.utils.calcTicksX(B/100,k)).tickSize(-C,0),G.select(".nv-x.nv-axis").attr("transform","translate(0,"+e.range()[0]+")"),G.select(".nv-x.nv-axis").transition().call(g)),r&&(h.scale(e)._ticks(a.utils.calcTicksY(C/36,k)).tickSize(-B,0),G.select(".nv-y.nv-axis").transition().call(h)),j.dispatch.on("elementMousemove",function(b){f.clearHighlights();var d,e,i,n=[];k.filter(function(a,b){return a.seriesIndex=b,!a.disabled}).forEach(function(g,h){e=a.interactiveBisect(g.values,b.pointXValue,c.x()),f.highlightPoint(e,!0);var j=g.values[e];void 0!==j&&(void 0===d&&(d=j),void 0===i&&(i=c.xScale()(c.x()(j,e))),n.push({key:g.key,value:c.y()(j,e),color:m(g,g.seriesIndex),data:g.values[e]}))});var o=g.tickFormat()(c.x()(d,e));j.tooltip.position({left:i+l.left,top:b.mouseY+l.top}).chartContainer(A.parentNode).valueFormatter(function(a,b){return h.tickFormat()(a)}).data({value:o,index:e,series:n})(),j.renderGuideLine(i)}),j.dispatch.on("elementMouseout",function(a){x.tooltipHide(),f.clearHighlights()}),i.dispatch.on("legendClick",function(a,d){a.disabled=!a.disabled,k.filter(function(a){return!a.disabled}).length||k.map(function(a){return a.disabled=!1,E.selectAll(".nv-series").classed("disabled",!1),a}),u.disabled=k.map(function(a){return!!a.disabled}),x.stateChange(u),b.transition().call(c)}),i.dispatch.on("legendDblclick",function(a){k.forEach(function(a){a.disabled=!0}),a.disabled=!1,u.disabled=k.map(function(a){return!!a.disabled}),x.stateChange(u),c.update()}),x.on("changeState",function(a){"undefined"!=typeof a.disabled&&(k.forEach(function(b,c){b.disabled=a.disabled[c]}),u.disabled=a.disabled),c.update()})}),z.renderEnd("historicalBarChart immediate"),c}var d,e,f=b||a.models.historicalBar(),g=a.models.axis(),h=a.models.axis(),i=a.models.legend(),j=a.interactiveGuideline(),k=a.models.tooltip(),l={top:30,right:90,bottom:50,left:90},m=a.utils.defaultColor(),n=null,o=null,p=!1,q=!0,r=!0,s=!1,t=!1,u={},v=null,w=null,x=d3.dispatch("tooltipHide","stateChange","changeState","renderEnd"),y=250;g.orient("bottom").tickPadding(7),h.orient(s?"right":"left"),k.duration(0).headerEnabled(!1).valueFormatter(function(a,b){return h.tickFormat()(a,b)}).headerFormatter(function(a,b){return g.tickFormat()(a,b)});var z=a.utils.renderWatch(x,0);return f.dispatch.on("elementMouseover.tooltip",function(a){a.series={key:c.x()(a.data),value:c.y()(a.data),color:a.color},k.data(a).hidden(!1)}),f.dispatch.on("elementMouseout.tooltip",function(a){k.hidden(!0)}),f.dispatch.on("elementMousemove.tooltip",function(a){k.position({top:d3.event.pageY,left:d3.event.pageX})()}),c.dispatch=x,c.bars=f,c.legend=i,c.xAxis=g,c.yAxis=h,c.interactiveLayer=j,c.tooltip=k,c.options=a.utils.optionsFunc.bind(c),c._options=Object.create({},{width:{get:function(){return n},set:function(a){n=a}},height:{get:function(){return o},set:function(a){o=a}},showLegend:{get:function(){return p},set:function(a){p=a}},showXAxis:{get:function(){return q},set:function(a){q=a}},showYAxis:{get:function(){return r},set:function(a){r=a}},defaultState:{get:function(){return v},set:function(a){v=a}},noData:{get:function(){return w},set:function(a){w=a}},tooltips:{get:function(){return k.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),k.enabled(!!b)}},tooltipContent:{get:function(){return k.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),k.contentGenerator(b)}},margin:{get:function(){return l},set:function(a){l.top=void 0!==a.top?a.top:l.top,l.right=void 0!==a.right?a.right:l.right,l.bottom=void 0!==a.bottom?a.bottom:l.bottom,l.left=void 0!==a.left?a.left:l.left}},color:{get:function(){return m},set:function(b){m=a.utils.getColor(b),i.color(m),f.color(m)}},duration:{get:function(){return y},set:function(a){y=a,z.reset(y),h.duration(y),g.duration(y)}},rightAlignYAxis:{get:function(){return s},set:function(a){s=a,h.orient(a?"right":"left")}},useInteractiveGuideline:{get:function(){return t},set:function(a){t=a,a===!0&&c.interactive(!1)}}}),a.utils.inheritOptions(c,f),a.utils.initOptions(c),c},a.models.ohlcBarChart=function(){var b=a.models.historicalBarChart(a.models.ohlcBar());return b.useInteractiveGuideline(!0),b.interactiveLayer.tooltip.contentGenerator(function(a){var c=a.series[0].data,d=c.open<c.close?"2ca02c":"d62728";return'<h3 style="color: #'+d+'">'+a.value+"</h3><table><tr><td>open:</td><td>"+b.yAxis.tickFormat()(c.open)+"</td></tr><tr><td>close:</td><td>"+b.yAxis.tickFormat()(c.close)+"</td></tr><tr><td>high</td><td>"+b.yAxis.tickFormat()(c.high)+"</td></tr><tr><td>low:</td><td>"+b.yAxis.tickFormat()(c.low)+"</td></tr></table>"}),b},a.models.candlestickBarChart=function(){var b=a.models.historicalBarChart(a.models.candlestickBar());return b.useInteractiveGuideline(!0),b.interactiveLayer.tooltip.contentGenerator(function(a){var c=a.series[0].data,d=c.open<c.close?"2ca02c":"d62728";return'<h3 style="color: #'+d+'">'+a.value+"</h3><table><tr><td>open:</td><td>"+b.yAxis.tickFormat()(c.open)+"</td></tr><tr><td>close:</td><td>"+b.yAxis.tickFormat()(c.close)+"</td></tr><tr><td>high</td><td>"+b.yAxis.tickFormat()(c.high)+"</td></tr><tr><td>low:</td><td>"+b.yAxis.tickFormat()(c.low)+"</td></tr></table>"}),b},a.models.legend=function(){"use strict";function b(p){function q(a,b){return"furious"!=o?"#000":m?a.disengaged?"#000":"#fff":m?void 0:(a.color||(a.color=g(a,b)),a.disabled?a.color:"#fff")}function r(a,b){return m&&"furious"==o&&a.disengaged?"#eee":a.color||g(a,b)}function s(a,b){return m&&"furious"==o?1:a.disabled?0:1}return p.each(function(b){var g=d-c.left-c.right,p=d3.select(this);a.utils.initSVG(p);var t=p.selectAll("g.nv-legend").data([b]),u=t.enter().append("g").attr("class","nvd3 nv-legend").append("g"),v=t.select("g");t.attr("transform","translate("+c.left+","+c.top+")");var w,x,y=v.selectAll(".nv-series").data(function(a){return"furious"!=o?a:a.filter(function(a){return m?!0:!a.disengaged})}),z=y.enter().append("g").attr("class","nv-series");switch(o){case"furious":x=23;break;case"classic":x=20}if("classic"==o)z.append("circle").style("stroke-width",2).attr("class","nv-legend-symbol").attr("r",5),w=y.select("circle");else if("furious"==o){z.append("rect").style("stroke-width",2).attr("class","nv-legend-symbol").attr("rx",3).attr("ry",3),w=y.select(".nv-legend-symbol"),z.append("g").attr("class","nv-check-box").property("innerHTML",'<path d="M0.5,5 L22.5,5 L22.5,26.5 L0.5,26.5 L0.5,5 Z" class="nv-box"></path><path d="M5.5,12.8618467 L11.9185089,19.2803556 L31,0.198864511" class="nv-check"></path>').attr("transform","translate(-10,-8)scale(0.5)");var A=y.select(".nv-check-box");A.each(function(a,b){d3.select(this).selectAll("path").attr("stroke",q(a,b))})}z.append("text").attr("text-anchor","start").attr("class","nv-legend-text").attr("dy",".32em").attr("dx","8");var B=y.select("text.nv-legend-text");y.on("mouseover",function(a,b){n.legendMouseover(a,b)}).on("mouseout",function(a,b){n.legendMouseout(a,b)}).on("click",function(a,b){n.legendClick(a,b);var c=y.data();if(k){if("classic"==o)l?(c.forEach(function(a){a.disabled=!0}),a.disabled=!1):(a.disabled=!a.disabled,c.every(function(a){return a.disabled})&&c.forEach(function(a){a.disabled=!1}));else if("furious"==o)if(m)a.disengaged=!a.disengaged,a.userDisabled=void 0==a.userDisabled?!!a.disabled:a.userDisabled,a.disabled=a.disengaged||a.userDisabled;else if(!m){a.disabled=!a.disabled,a.userDisabled=a.disabled;var d=c.filter(function(a){return!a.disengaged});d.every(function(a){return a.userDisabled})&&c.forEach(function(a){a.disabled=a.userDisabled=!1})}n.stateChange({disabled:c.map(function(a){return!!a.disabled}),disengaged:c.map(function(a){return!!a.disengaged})})}}).on("dblclick",function(a,b){if(("furious"!=o||!m)&&(n.legendDblclick(a,b),k)){var c=y.data();c.forEach(function(a){a.disabled=!0,"furious"==o&&(a.userDisabled=a.disabled)}),a.disabled=!1,"furious"==o&&(a.userDisabled=a.disabled),n.stateChange({disabled:c.map(function(a){return!!a.disabled})})}}),y.classed("nv-disabled",function(a){return a.userDisabled}),y.exit().remove(),B.attr("fill",q).text(f);var C=0;if(h){var D=[];y.each(function(b,c){var d,e=d3.select(this).select("text");try{if(d=e.node().getComputedTextLength(),0>=d)throw Error()}catch(f){d=a.utils.calcApproxTextWidth(e)}D.push(d+i)});var E=0,F=[];for(C=0;g>C&&E<D.length;)F[E]=D[E],C+=D[E++];for(0===E&&(E=1);C>g&&E>1;){F=[],E--;for(var G=0;G<D.length;G++)D[G]>(F[G%E]||0)&&(F[G%E]=D[G]);C=F.reduce(function(a,b,c,d){return a+b})}for(var H=[],I=0,J=0;E>I;I++)H[I]=J,J+=F[I];y.attr("transform",function(a,b){return"translate("+H[b%E]+","+(5+Math.floor(b/E)*x)+")"}),j?v.attr("transform","translate("+(d-c.right-C)+","+c.top+")"):v.attr("transform","translate(0,"+c.top+")"),e=c.top+c.bottom+Math.ceil(D.length/E)*x}else{var K,L=5,M=5,N=0;y.attr("transform",function(a,b){var e=d3.select(this).select("text").node().getComputedTextLength()+i;return K=M,d<c.left+c.right+K+e&&(M=K=5,L+=x),M+=e,M>N&&(N=M),K+N>C&&(C=K+N),"translate("+K+","+L+")"}),v.attr("transform","translate("+(d-c.right-N)+","+c.top+")"),e=c.top+c.bottom+L+15}if("furious"==o){w.attr("width",function(a,b){return B[0][b].getComputedTextLength()+27}).attr("height",18).attr("y",-9).attr("x",-15),u.insert("rect",":first-child").attr("class","nv-legend-bg").attr("fill","#eee").attr("opacity",0);var O=v.select(".nv-legend-bg");O.transition().duration(300).attr("x",-x).attr("width",C+x-12).attr("height",e+10).attr("y",-c.top-10).attr("opacity",m?1:0)}w.style("fill",r).style("fill-opacity",s).style("stroke",r)}),b}var c={top:5,right:0,bottom:5,left:0},d=400,e=20,f=function(a){return a.key},g=a.utils.getColor(),h=!0,i=32,j=!0,k=!0,l=!1,m=!1,n=d3.dispatch("legendClick","legendDblclick","legendMouseover","legendMouseout","stateChange"),o="classic";return b.dispatch=n,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return d},set:function(a){d=a}},height:{get:function(){return e},set:function(a){e=a}},key:{get:function(){return f},set:function(a){f=a}},align:{get:function(){return h},set:function(a){h=a}},rightAlign:{get:function(){return j},set:function(a){j=a}},padding:{get:function(){return i},set:function(a){i=a}},updateState:{get:function(){return k},set:function(a){k=a}},radioButtonMode:{get:function(){return l},set:function(a){l=a}},expanded:{get:function(){return m},set:function(a){m=a}},vers:{get:function(){return o},set:function(a){o=a}},margin:{get:function(){return c},set:function(a){c.top=void 0!==a.top?a.top:c.top,c.right=void 0!==a.right?a.right:c.right,c.bottom=void 0!==a.bottom?a.bottom:c.bottom,c.left=void 0!==a.left?a.left:c.left}},color:{get:function(){return g},set:function(b){g=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.line=function(){"use strict";function b(r){return v.reset(),v.models(e),r.each(function(b){i=d3.select(this);var r=a.utils.availableWidth(g,i,f),s=a.utils.availableHeight(h,i,f);a.utils.initSVG(i),c=e.xScale(),d=e.yScale(),t=t||c,u=u||d;var w=i.selectAll("g.nv-wrap.nv-line").data([b]),x=w.enter().append("g").attr("class","nvd3 nv-wrap nv-line"),y=x.append("defs"),z=x.append("g"),A=w.select("g");z.append("g").attr("class","nv-groups"),z.append("g").attr("class","nv-scatterWrap"),w.attr("transform","translate("+f.left+","+f.top+")"),e.width(r).height(s);var B=w.select(".nv-scatterWrap");B.call(e),y.append("clipPath").attr("id","nv-edge-clip-"+e.id()).append("rect"),w.select("#nv-edge-clip-"+e.id()+" rect").attr("width",r).attr("height",s>0?s:0),A.attr("clip-path",p?"url(#nv-edge-clip-"+e.id()+")":""),B.attr("clip-path",p?"url(#nv-edge-clip-"+e.id()+")":"");var C=w.select(".nv-groups").selectAll(".nv-group").data(function(a){return a},function(a){return a.key});C.enter().append("g").style("stroke-opacity",1e-6).style("stroke-width",function(a){return a.strokeWidth||j}).style("fill-opacity",1e-6),C.exit().remove(),C.attr("class",function(a,b){return(a.classed||"")+" nv-group nv-series-"+b}).classed("hover",function(a){return a.hover}).style("fill",function(a,b){return k(a,b)}).style("stroke",function(a,b){return k(a,b)}),C.watchTransition(v,"line: groups").style("stroke-opacity",1).style("fill-opacity",function(a){return a.fillOpacity||.5});var D=C.selectAll("path.nv-area").data(function(a){return o(a)?[a]:[]});D.enter().append("path").attr("class","nv-area").attr("d",function(b){return d3.svg.area().interpolate(q).defined(n).x(function(b,c){return a.utils.NaNtoZero(t(l(b,c)))}).y0(function(b,c){return a.utils.NaNtoZero(u(m(b,c)))}).y1(function(a,b){return u(d.domain()[0]<=0?d.domain()[1]>=0?0:d.domain()[1]:d.domain()[0])}).apply(this,[b.values])}),C.exit().selectAll("path.nv-area").remove(),D.watchTransition(v,"line: areaPaths").attr("d",function(b){return d3.svg.area().interpolate(q).defined(n).x(function(b,d){return a.utils.NaNtoZero(c(l(b,d)))}).y0(function(b,c){return a.utils.NaNtoZero(d(m(b,c)))}).y1(function(a,b){return d(d.domain()[0]<=0?d.domain()[1]>=0?0:d.domain()[1]:d.domain()[0])}).apply(this,[b.values])});var E=C.selectAll("path.nv-line").data(function(a){return[a.values]});E.enter().append("path").attr("class","nv-line").attr("d",d3.svg.line().interpolate(q).defined(n).x(function(b,c){return a.utils.NaNtoZero(t(l(b,c)))}).y(function(b,c){return a.utils.NaNtoZero(u(m(b,c)))})),E.watchTransition(v,"line: linePaths").attr("d",d3.svg.line().interpolate(q).defined(n).x(function(b,d){return a.utils.NaNtoZero(c(l(b,d)))}).y(function(b,c){return a.utils.NaNtoZero(d(m(b,c)))})),t=c.copy(),u=d.copy()}),v.renderEnd("line immediate"),b}var c,d,e=a.models.scatter(),f={top:0,right:0,bottom:0,left:0},g=960,h=500,i=null,j=1.5,k=a.utils.defaultColor(),l=function(a){return a.x},m=function(a){return a.y},n=function(a,b){return!isNaN(m(a,b))&&null!==m(a,b)},o=function(a){return a.area},p=!1,q="linear",r=250,s=d3.dispatch("elementClick","elementMouseover","elementMouseout","renderEnd");e.pointSize(16).pointDomain([16,256]);var t,u,v=a.utils.renderWatch(s,r);return b.dispatch=s,b.scatter=e,e.dispatch.on("elementClick",function(){s.elementClick.apply(this,arguments)}),e.dispatch.on("elementMouseover",function(){s.elementMouseover.apply(this,arguments)}),e.dispatch.on("elementMouseout",function(){s.elementMouseout.apply(this,arguments)}),b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return g},set:function(a){g=a}},height:{get:function(){return h},set:function(a){h=a}},defined:{get:function(){return n},set:function(a){n=a}},interpolate:{get:function(){return q},set:function(a){q=a}},clipEdge:{get:function(){return p},set:function(a){p=a}},margin:{get:function(){return f},set:function(a){f.top=void 0!==a.top?a.top:f.top,f.right=void 0!==a.right?a.right:f.right,f.bottom=void 0!==a.bottom?a.bottom:f.bottom,f.left=void 0!==a.left?a.left:f.left}},duration:{get:function(){return r},set:function(a){r=a,v.reset(r),e.duration(r)}},isArea:{get:function(){return o},set:function(a){o=d3.functor(a)}},x:{get:function(){return l},set:function(a){l=a,e.x(a)}},y:{get:function(){return m},set:function(a){m=a,e.y(a)}},color:{get:function(){return k},set:function(b){k=a.utils.getColor(b),e.color(k)}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.lineChart=function(){"use strict";function b(j){return y.reset(),y.models(e),
+p&&y.models(f),q&&y.models(g),j.each(function(j){var v=d3.select(this),y=this;a.utils.initSVG(v);var B=a.utils.availableWidth(m,v,k),C=a.utils.availableHeight(n,v,k);if(b.update=function(){0===x?v.call(b):v.transition().duration(x).call(b)},b.container=this,t.setter(A(j),b.update).getter(z(j)).update(),t.disabled=j.map(function(a){return!!a.disabled}),!u){var D;u={};for(D in t)t[D]instanceof Array?u[D]=t[D].slice(0):u[D]=t[D]}if(!(j&&j.length&&j.filter(function(a){return a.values.length}).length))return a.utils.noData(b,v),b;v.selectAll(".nv-noData").remove(),c=e.xScale(),d=e.yScale();var E=v.selectAll("g.nv-wrap.nv-lineChart").data([j]),F=E.enter().append("g").attr("class","nvd3 nv-wrap nv-lineChart").append("g"),G=E.select("g");F.append("rect").style("opacity",0),F.append("g").attr("class","nv-x nv-axis"),F.append("g").attr("class","nv-y nv-axis"),F.append("g").attr("class","nv-linesWrap"),F.append("g").attr("class","nv-legendWrap"),F.append("g").attr("class","nv-interactive"),G.select("rect").attr("width",B).attr("height",C>0?C:0),o&&(h.width(B),G.select(".nv-legendWrap").datum(j).call(h),k.top!=h.height()&&(k.top=h.height(),C=a.utils.availableHeight(n,v,k)),E.select(".nv-legendWrap").attr("transform","translate(0,"+-k.top+")")),E.attr("transform","translate("+k.left+","+k.top+")"),r&&G.select(".nv-y.nv-axis").attr("transform","translate("+B+",0)"),s&&(i.width(B).height(C).margin({left:k.left,top:k.top}).svgContainer(v).xScale(c),E.select(".nv-interactive").call(i)),e.width(B).height(C).color(j.map(function(a,b){return a.color||l(a,b)}).filter(function(a,b){return!j[b].disabled}));var H=G.select(".nv-linesWrap").datum(j.filter(function(a){return!a.disabled}));H.call(e),p&&(f.scale(c)._ticks(a.utils.calcTicksX(B/100,j)).tickSize(-C,0),G.select(".nv-x.nv-axis").attr("transform","translate(0,"+d.range()[0]+")"),G.select(".nv-x.nv-axis").call(f)),q&&(g.scale(d)._ticks(a.utils.calcTicksY(C/36,j)).tickSize(-B,0),G.select(".nv-y.nv-axis").call(g)),h.dispatch.on("stateChange",function(a){for(var c in a)t[c]=a[c];w.stateChange(t),b.update()}),i.dispatch.on("elementMousemove",function(c){e.clearHighlights();var d,h,m,n=[];if(j.filter(function(a,b){return a.seriesIndex=b,!a.disabled}).forEach(function(f,g){h=a.interactiveBisect(f.values,c.pointXValue,b.x());var i=f.values[h],j=b.y()(i,h);null!=j&&e.highlightPoint(g,h,!0),void 0!==i&&(void 0===d&&(d=i),void 0===m&&(m=b.xScale()(b.x()(i,h))),n.push({key:f.key,value:j,color:l(f,f.seriesIndex)}))}),n.length>2){var o=b.yScale().invert(c.mouseY),p=Math.abs(b.yScale().domain()[0]-b.yScale().domain()[1]),q=.03*p,r=a.nearestValueIndex(n.map(function(a){return a.value}),o,q);null!==r&&(n[r].highlight=!0)}var s=f.tickFormat()(b.x()(d,h));i.tooltip.position({left:c.mouseX+k.left,top:c.mouseY+k.top}).chartContainer(y.parentNode).valueFormatter(function(a,b){return null==a?"N/A":g.tickFormat()(a)}).data({value:s,index:h,series:n})(),i.renderGuideLine(m)}),i.dispatch.on("elementClick",function(c){var d,f=[];j.filter(function(a,b){return a.seriesIndex=b,!a.disabled}).forEach(function(e){var g=a.interactiveBisect(e.values,c.pointXValue,b.x()),h=e.values[g];if("undefined"!=typeof h){"undefined"==typeof d&&(d=b.xScale()(b.x()(h,g)));var i=b.yScale()(b.y()(h,g));f.push({point:h,pointIndex:g,pos:[d,i],seriesIndex:e.seriesIndex,series:e})}}),e.dispatch.elementClick(f)}),i.dispatch.on("elementMouseout",function(a){e.clearHighlights()}),w.on("changeState",function(a){"undefined"!=typeof a.disabled&&j.length===a.disabled.length&&(j.forEach(function(b,c){b.disabled=a.disabled[c]}),t.disabled=a.disabled),b.update()})}),y.renderEnd("lineChart immediate"),b}var c,d,e=a.models.line(),f=a.models.axis(),g=a.models.axis(),h=a.models.legend(),i=a.interactiveGuideline(),j=a.models.tooltip(),k={top:30,right:20,bottom:50,left:60},l=a.utils.defaultColor(),m=null,n=null,o=!0,p=!0,q=!0,r=!1,s=!1,t=a.utils.state(),u=null,v=null,w=d3.dispatch("tooltipShow","tooltipHide","stateChange","changeState","renderEnd"),x=250;f.orient("bottom").tickPadding(7),g.orient(r?"right":"left"),j.valueFormatter(function(a,b){return g.tickFormat()(a,b)}).headerFormatter(function(a,b){return f.tickFormat()(a,b)});var y=a.utils.renderWatch(w,x),z=function(a){return function(){return{active:a.map(function(a){return!a.disabled})}}},A=function(a){return function(b){void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};return e.dispatch.on("elementMouseover.tooltip",function(a){j.data(a).position(a.pos).hidden(!1)}),e.dispatch.on("elementMouseout.tooltip",function(a){j.hidden(!0)}),b.dispatch=w,b.lines=e,b.legend=h,b.xAxis=f,b.yAxis=g,b.interactiveLayer=i,b.tooltip=j,b.dispatch=w,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return m},set:function(a){m=a}},height:{get:function(){return n},set:function(a){n=a}},showLegend:{get:function(){return o},set:function(a){o=a}},showXAxis:{get:function(){return p},set:function(a){p=a}},showYAxis:{get:function(){return q},set:function(a){q=a}},defaultState:{get:function(){return u},set:function(a){u=a}},noData:{get:function(){return v},set:function(a){v=a}},tooltips:{get:function(){return j.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),j.enabled(!!b)}},tooltipContent:{get:function(){return j.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),j.contentGenerator(b)}},margin:{get:function(){return k},set:function(a){k.top=void 0!==a.top?a.top:k.top,k.right=void 0!==a.right?a.right:k.right,k.bottom=void 0!==a.bottom?a.bottom:k.bottom,k.left=void 0!==a.left?a.left:k.left}},duration:{get:function(){return x},set:function(a){x=a,y.reset(x),e.duration(x),f.duration(x),g.duration(x)}},color:{get:function(){return l},set:function(b){l=a.utils.getColor(b),h.color(l),e.color(l)}},rightAlignYAxis:{get:function(){return r},set:function(a){r=a,g.orient(r?"right":"left")}},useInteractiveGuideline:{get:function(){return s},set:function(a){s=a,s&&(e.interactive(!1),e.useVoronoi(!1))}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.linePlusBarChart=function(){"use strict";function b(v){return v.each(function(v){function J(a){var b=+("e"==a),c=b?1:-1,d=X/3;return"M"+.5*c+","+d+"A6,6 0 0 "+b+" "+6.5*c+","+(d+6)+"V"+(2*d-6)+"A6,6 0 0 "+b+" "+.5*c+","+2*d+"ZM"+2.5*c+","+(d+8)+"V"+(2*d-8)+"M"+4.5*c+","+(d+8)+"V"+(2*d-8)}function S(){u.empty()||u.extent(I),ka.data([u.empty()?e.domain():I]).each(function(a,b){var c=e(a[0])-e.range()[0],d=e.range()[1]-e(a[1]);d3.select(this).select(".left").attr("width",0>c?0:c),d3.select(this).select(".right").attr("x",e(a[1])).attr("width",0>d?0:d)})}function T(){I=u.empty()?null:u.extent(),c=u.empty()?e.domain():u.extent(),K.brush({extent:c,brush:u}),S(),l.width(V).height(W).color(v.map(function(a,b){return a.color||C(a,b)}).filter(function(a,b){return!v[b].disabled&&v[b].bar})),j.width(V).height(W).color(v.map(function(a,b){return a.color||C(a,b)}).filter(function(a,b){return!v[b].disabled&&!v[b].bar}));var b=da.select(".nv-focus .nv-barsWrap").datum(Z.length?Z.map(function(a,b){return{key:a.key,values:a.values.filter(function(a,b){return l.x()(a,b)>=c[0]&&l.x()(a,b)<=c[1]})}}):[{values:[]}]),h=da.select(".nv-focus .nv-linesWrap").datum($[0].disabled?[{values:[]}]:$.map(function(a,b){return{area:a.area,fillOpacity:a.fillOpacity,key:a.key,values:a.values.filter(function(a,b){return j.x()(a,b)>=c[0]&&j.x()(a,b)<=c[1]})}}));d=Z.length?l.xScale():j.xScale(),n.scale(d)._ticks(a.utils.calcTicksX(V/100,v)).tickSize(-W,0),n.domain([Math.ceil(c[0]),Math.floor(c[1])]),da.select(".nv-x.nv-axis").transition().duration(L).call(n),b.transition().duration(L).call(l),h.transition().duration(L).call(j),da.select(".nv-focus .nv-x.nv-axis").attr("transform","translate(0,"+f.range()[0]+")"),p.scale(f)._ticks(a.utils.calcTicksY(W/36,v)).tickSize(-V,0),q.scale(g)._ticks(a.utils.calcTicksY(W/36,v)).tickSize(Z.length?0:-V,0),da.select(".nv-focus .nv-y1.nv-axis").style("opacity",Z.length?1:0),da.select(".nv-focus .nv-y2.nv-axis").style("opacity",$.length&&!$[0].disabled?1:0).attr("transform","translate("+d.range()[1]+",0)"),da.select(".nv-focus .nv-y1.nv-axis").transition().duration(L).call(p),da.select(".nv-focus .nv-y2.nv-axis").transition().duration(L).call(q)}var U=d3.select(this);a.utils.initSVG(U);var V=a.utils.availableWidth(y,U,w),W=a.utils.availableHeight(z,U,w)-(E?H:0),X=H-x.top-x.bottom;if(b.update=function(){U.transition().duration(L).call(b)},b.container=this,M.setter(R(v),b.update).getter(Q(v)).update(),M.disabled=v.map(function(a){return!!a.disabled}),!N){var Y;N={};for(Y in M)M[Y]instanceof Array?N[Y]=M[Y].slice(0):N[Y]=M[Y]}if(!(v&&v.length&&v.filter(function(a){return a.values.length}).length))return a.utils.noData(b,U),b;U.selectAll(".nv-noData").remove();var Z=v.filter(function(a){return!a.disabled&&a.bar}),$=v.filter(function(a){return!a.bar});d=l.xScale(),e=o.scale(),f=l.yScale(),g=j.yScale(),h=m.yScale(),i=k.yScale();var _=v.filter(function(a){return!a.disabled&&a.bar}).map(function(a){return a.values.map(function(a,b){return{x:A(a,b),y:B(a,b)}})}),aa=v.filter(function(a){return!a.disabled&&!a.bar}).map(function(a){return a.values.map(function(a,b){return{x:A(a,b),y:B(a,b)}})});d.range([0,V]),e.domain(d3.extent(d3.merge(_.concat(aa)),function(a){return a.x})).range([0,V]);var ba=U.selectAll("g.nv-wrap.nv-linePlusBar").data([v]),ca=ba.enter().append("g").attr("class","nvd3 nv-wrap nv-linePlusBar").append("g"),da=ba.select("g");ca.append("g").attr("class","nv-legendWrap");var ea=ca.append("g").attr("class","nv-focus");ea.append("g").attr("class","nv-x nv-axis"),ea.append("g").attr("class","nv-y1 nv-axis"),ea.append("g").attr("class","nv-y2 nv-axis"),ea.append("g").attr("class","nv-barsWrap"),ea.append("g").attr("class","nv-linesWrap");var fa=ca.append("g").attr("class","nv-context");if(fa.append("g").attr("class","nv-x nv-axis"),fa.append("g").attr("class","nv-y1 nv-axis"),fa.append("g").attr("class","nv-y2 nv-axis"),fa.append("g").attr("class","nv-barsWrap"),fa.append("g").attr("class","nv-linesWrap"),fa.append("g").attr("class","nv-brushBackground"),fa.append("g").attr("class","nv-x nv-brush"),D){var ga=t.align()?V/2:V,ha=t.align()?ga:0;t.width(ga),da.select(".nv-legendWrap").datum(v.map(function(a){return a.originalKey=void 0===a.originalKey?a.key:a.originalKey,a.key=a.originalKey+(a.bar?O:P),a})).call(t),w.top!=t.height()&&(w.top=t.height(),W=a.utils.availableHeight(z,U,w)-H),da.select(".nv-legendWrap").attr("transform","translate("+ha+","+-w.top+")")}ba.attr("transform","translate("+w.left+","+w.top+")"),da.select(".nv-context").style("display",E?"initial":"none"),m.width(V).height(X).color(v.map(function(a,b){return a.color||C(a,b)}).filter(function(a,b){return!v[b].disabled&&v[b].bar})),k.width(V).height(X).color(v.map(function(a,b){return a.color||C(a,b)}).filter(function(a,b){return!v[b].disabled&&!v[b].bar}));var ia=da.select(".nv-context .nv-barsWrap").datum(Z.length?Z:[{values:[]}]),ja=da.select(".nv-context .nv-linesWrap").datum($[0].disabled?[{values:[]}]:$);da.select(".nv-context").attr("transform","translate(0,"+(W+w.bottom+x.top)+")"),ia.transition().call(m),ja.transition().call(k),G&&(o._ticks(a.utils.calcTicksX(V/100,v)).tickSize(-X,0),da.select(".nv-context .nv-x.nv-axis").attr("transform","translate(0,"+h.range()[0]+")"),da.select(".nv-context .nv-x.nv-axis").transition().call(o)),F&&(r.scale(h)._ticks(X/36).tickSize(-V,0),s.scale(i)._ticks(X/36).tickSize(Z.length?0:-V,0),da.select(".nv-context .nv-y3.nv-axis").style("opacity",Z.length?1:0).attr("transform","translate(0,"+e.range()[0]+")"),da.select(".nv-context .nv-y2.nv-axis").style("opacity",$.length?1:0).attr("transform","translate("+e.range()[1]+",0)"),da.select(".nv-context .nv-y1.nv-axis").transition().call(r),da.select(".nv-context .nv-y2.nv-axis").transition().call(s)),u.x(e).on("brush",T),I&&u.extent(I);var ka=da.select(".nv-brushBackground").selectAll("g").data([I||u.extent()]),la=ka.enter().append("g");la.append("rect").attr("class","left").attr("x",0).attr("y",0).attr("height",X),la.append("rect").attr("class","right").attr("x",0).attr("y",0).attr("height",X);var ma=da.select(".nv-x.nv-brush").call(u);ma.selectAll("rect").attr("height",X),ma.selectAll(".resize").append("path").attr("d",J),t.dispatch.on("stateChange",function(a){for(var c in a)M[c]=a[c];K.stateChange(M),b.update()}),K.on("changeState",function(a){"undefined"!=typeof a.disabled&&(v.forEach(function(b,c){b.disabled=a.disabled[c]}),M.disabled=a.disabled),b.update()}),T()}),b}var c,d,e,f,g,h,i,j=a.models.line(),k=a.models.line(),l=a.models.historicalBar(),m=a.models.historicalBar(),n=a.models.axis(),o=a.models.axis(),p=a.models.axis(),q=a.models.axis(),r=a.models.axis(),s=a.models.axis(),t=a.models.legend(),u=d3.svg.brush(),v=a.models.tooltip(),w={top:30,right:30,bottom:30,left:60},x={top:0,right:30,bottom:20,left:60},y=null,z=null,A=function(a){return a.x},B=function(a){return a.y},C=a.utils.defaultColor(),D=!0,E=!0,F=!1,G=!0,H=50,I=null,J=null,K=d3.dispatch("brush","stateChange","changeState"),L=0,M=a.utils.state(),N=null,O=" (left axis)",P=" (right axis)";j.clipEdge(!0),k.interactive(!1),n.orient("bottom").tickPadding(5),p.orient("left"),q.orient("right"),o.orient("bottom").tickPadding(5),r.orient("left"),s.orient("right"),v.headerEnabled(!0).headerFormatter(function(a,b){return n.tickFormat()(a,b)});var Q=function(a){return function(){return{active:a.map(function(a){return!a.disabled})}}},R=function(a){return function(b){void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};return j.dispatch.on("elementMouseover.tooltip",function(a){v.duration(100).valueFormatter(function(a,b){return q.tickFormat()(a,b)}).data(a).position(a.pos).hidden(!1)}),j.dispatch.on("elementMouseout.tooltip",function(a){v.hidden(!0)}),l.dispatch.on("elementMouseover.tooltip",function(a){a.value=b.x()(a.data),a.series={value:b.y()(a.data),color:a.color},v.duration(0).valueFormatter(function(a,b){return p.tickFormat()(a,b)}).data(a).hidden(!1)}),l.dispatch.on("elementMouseout.tooltip",function(a){v.hidden(!0)}),l.dispatch.on("elementMousemove.tooltip",function(a){v.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.dispatch=K,b.legend=t,b.lines=j,b.lines2=k,b.bars=l,b.bars2=m,b.xAxis=n,b.x2Axis=o,b.y1Axis=p,b.y2Axis=q,b.y3Axis=r,b.y4Axis=s,b.tooltip=v,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return y},set:function(a){y=a}},height:{get:function(){return z},set:function(a){z=a}},showLegend:{get:function(){return D},set:function(a){D=a}},brushExtent:{get:function(){return I},set:function(a){I=a}},noData:{get:function(){return J},set:function(a){J=a}},focusEnable:{get:function(){return E},set:function(a){E=a}},focusHeight:{get:function(){return H},set:function(a){H=a}},focusShowAxisX:{get:function(){return G},set:function(a){G=a}},focusShowAxisY:{get:function(){return F},set:function(a){F=a}},legendLeftAxisHint:{get:function(){return O},set:function(a){O=a}},legendRightAxisHint:{get:function(){return P},set:function(a){P=a}},tooltips:{get:function(){return v.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),v.enabled(!!b)}},tooltipContent:{get:function(){return v.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),v.contentGenerator(b)}},margin:{get:function(){return w},set:function(a){w.top=void 0!==a.top?a.top:w.top,w.right=void 0!==a.right?a.right:w.right,w.bottom=void 0!==a.bottom?a.bottom:w.bottom,w.left=void 0!==a.left?a.left:w.left}},duration:{get:function(){return L},set:function(a){L=a}},color:{get:function(){return C},set:function(b){C=a.utils.getColor(b),t.color(C)}},x:{get:function(){return A},set:function(a){A=a,j.x(a),k.x(a),l.x(a),m.x(a)}},y:{get:function(){return B},set:function(a){B=a,j.y(a),k.y(a),l.y(a),m.y(a)}}}),a.utils.inheritOptions(b,j),a.utils.initOptions(b),b},a.models.lineWithFocusChart=function(){"use strict";function b(o){return o.each(function(o){function z(a){var b=+("e"==a),c=b?1:-1,d=M/3;return"M"+.5*c+","+d+"A6,6 0 0 "+b+" "+6.5*c+","+(d+6)+"V"+(2*d-6)+"A6,6 0 0 "+b+" "+.5*c+","+2*d+"ZM"+2.5*c+","+(d+8)+"V"+(2*d-8)+"M"+4.5*c+","+(d+8)+"V"+(2*d-8)}function G(){n.empty()||n.extent(y),U.data([n.empty()?e.domain():y]).each(function(a,b){var d=e(a[0])-c.range()[0],f=K-e(a[1]);d3.select(this).select(".left").attr("width",0>d?0:d),d3.select(this).select(".right").attr("x",e(a[1])).attr("width",0>f?0:f)})}function H(){y=n.empty()?null:n.extent();var a=n.empty()?e.domain():n.extent();if(!(Math.abs(a[0]-a[1])<=1)){A.brush({extent:a,brush:n}),G();var b=Q.select(".nv-focus .nv-linesWrap").datum(o.filter(function(a){return!a.disabled}).map(function(b,c){return{key:b.key,area:b.area,values:b.values.filter(function(b,c){return g.x()(b,c)>=a[0]&&g.x()(b,c)<=a[1]})}}));b.transition().duration(B).call(g),Q.select(".nv-focus .nv-x.nv-axis").transition().duration(B).call(i),Q.select(".nv-focus .nv-y.nv-axis").transition().duration(B).call(j)}}var I=d3.select(this),J=this;a.utils.initSVG(I);var K=a.utils.availableWidth(t,I,q),L=a.utils.availableHeight(u,I,q)-v,M=v-r.top-r.bottom;if(b.update=function(){I.transition().duration(B).call(b)},b.container=this,C.setter(F(o),b.update).getter(E(o)).update(),C.disabled=o.map(function(a){return!!a.disabled}),!D){var N;D={};for(N in C)C[N]instanceof Array?D[N]=C[N].slice(0):D[N]=C[N]}if(!(o&&o.length&&o.filter(function(a){return a.values.length}).length))return a.utils.noData(b,I),b;I.selectAll(".nv-noData").remove(),c=g.xScale(),d=g.yScale(),e=h.xScale(),f=h.yScale();var O=I.selectAll("g.nv-wrap.nv-lineWithFocusChart").data([o]),P=O.enter().append("g").attr("class","nvd3 nv-wrap nv-lineWithFocusChart").append("g"),Q=O.select("g");P.append("g").attr("class","nv-legendWrap");var R=P.append("g").attr("class","nv-focus");R.append("g").attr("class","nv-x nv-axis"),R.append("g").attr("class","nv-y nv-axis"),R.append("g").attr("class","nv-linesWrap"),R.append("g").attr("class","nv-interactive");var S=P.append("g").attr("class","nv-context");S.append("g").attr("class","nv-x nv-axis"),S.append("g").attr("class","nv-y nv-axis"),S.append("g").attr("class","nv-linesWrap"),S.append("g").attr("class","nv-brushBackground"),S.append("g").attr("class","nv-x nv-brush"),x&&(m.width(K),Q.select(".nv-legendWrap").datum(o).call(m),q.top!=m.height()&&(q.top=m.height(),L=a.utils.availableHeight(u,I,q)-v),Q.select(".nv-legendWrap").attr("transform","translate(0,"+-q.top+")")),O.attr("transform","translate("+q.left+","+q.top+")"),w&&(p.width(K).height(L).margin({left:q.left,top:q.top}).svgContainer(I).xScale(c),O.select(".nv-interactive").call(p)),g.width(K).height(L).color(o.map(function(a,b){return a.color||s(a,b)}).filter(function(a,b){return!o[b].disabled})),h.defined(g.defined()).width(K).height(M).color(o.map(function(a,b){return a.color||s(a,b)}).filter(function(a,b){return!o[b].disabled})),Q.select(".nv-context").attr("transform","translate(0,"+(L+q.bottom+r.top)+")");var T=Q.select(".nv-context .nv-linesWrap").datum(o.filter(function(a){return!a.disabled}));d3.transition(T).call(h),i.scale(c)._ticks(a.utils.calcTicksX(K/100,o)).tickSize(-L,0),j.scale(d)._ticks(a.utils.calcTicksY(L/36,o)).tickSize(-K,0),Q.select(".nv-focus .nv-x.nv-axis").attr("transform","translate(0,"+L+")"),n.x(e).on("brush",function(){H()}),y&&n.extent(y);var U=Q.select(".nv-brushBackground").selectAll("g").data([y||n.extent()]),V=U.enter().append("g");V.append("rect").attr("class","left").attr("x",0).attr("y",0).attr("height",M),V.append("rect").attr("class","right").attr("x",0).attr("y",0).attr("height",M);var W=Q.select(".nv-x.nv-brush").call(n);W.selectAll("rect").attr("height",M),W.selectAll(".resize").append("path").attr("d",z),H(),k.scale(e)._ticks(a.utils.calcTicksX(K/100,o)).tickSize(-M,0),Q.select(".nv-context .nv-x.nv-axis").attr("transform","translate(0,"+f.range()[0]+")"),d3.transition(Q.select(".nv-context .nv-x.nv-axis")).call(k),l.scale(f)._ticks(a.utils.calcTicksY(M/36,o)).tickSize(-K,0),d3.transition(Q.select(".nv-context .nv-y.nv-axis")).call(l),Q.select(".nv-context .nv-x.nv-axis").attr("transform","translate(0,"+f.range()[0]+")"),m.dispatch.on("stateChange",function(a){for(var c in a)C[c]=a[c];A.stateChange(C),b.update()}),p.dispatch.on("elementMousemove",function(c){g.clearHighlights();var d,f,h,k=[];if(o.filter(function(a,b){return a.seriesIndex=b,!a.disabled}).forEach(function(i,j){var l=n.empty()?e.domain():n.extent(),m=i.values.filter(function(a,b){return g.x()(a,b)>=l[0]&&g.x()(a,b)<=l[1]});f=a.interactiveBisect(m,c.pointXValue,g.x());var o=m[f],p=b.y()(o,f);null!=p&&g.highlightPoint(j,f,!0),void 0!==o&&(void 0===d&&(d=o),void 0===h&&(h=b.xScale()(b.x()(o,f))),k.push({key:i.key,value:b.y()(o,f),color:s(i,i.seriesIndex)}))}),k.length>2){var l=b.yScale().invert(c.mouseY),m=Math.abs(b.yScale().domain()[0]-b.yScale().domain()[1]),r=.03*m,t=a.nearestValueIndex(k.map(function(a){return a.value}),l,r);null!==t&&(k[t].highlight=!0)}var u=i.tickFormat()(b.x()(d,f));p.tooltip.position({left:c.mouseX+q.left,top:c.mouseY+q.top}).chartContainer(J.parentNode).valueFormatter(function(a,b){return null==a?"N/A":j.tickFormat()(a)}).data({value:u,index:f,series:k})(),p.renderGuideLine(h)}),p.dispatch.on("elementMouseout",function(a){g.clearHighlights()}),A.on("changeState",function(a){"undefined"!=typeof a.disabled&&o.forEach(function(b,c){b.disabled=a.disabled[c]}),b.update()})}),b}var c,d,e,f,g=a.models.line(),h=a.models.line(),i=a.models.axis(),j=a.models.axis(),k=a.models.axis(),l=a.models.axis(),m=a.models.legend(),n=d3.svg.brush(),o=a.models.tooltip(),p=a.interactiveGuideline(),q={top:30,right:30,bottom:30,left:60},r={top:0,right:30,bottom:20,left:60},s=a.utils.defaultColor(),t=null,u=null,v=50,w=!1,x=!0,y=null,z=null,A=d3.dispatch("brush","stateChange","changeState"),B=250,C=a.utils.state(),D=null;g.clipEdge(!0).duration(0),h.interactive(!1),i.orient("bottom").tickPadding(5),j.orient("left"),k.orient("bottom").tickPadding(5),l.orient("left"),o.valueFormatter(function(a,b){return j.tickFormat()(a,b)}).headerFormatter(function(a,b){return i.tickFormat()(a,b)});var E=function(a){return function(){return{active:a.map(function(a){return!a.disabled})}}},F=function(a){return function(b){void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};return g.dispatch.on("elementMouseover.tooltip",function(a){o.data(a).position(a.pos).hidden(!1)}),g.dispatch.on("elementMouseout.tooltip",function(a){o.hidden(!0)}),b.dispatch=A,b.legend=m,b.lines=g,b.lines2=h,b.xAxis=i,b.yAxis=j,b.x2Axis=k,b.y2Axis=l,b.interactiveLayer=p,b.tooltip=o,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return t},set:function(a){t=a}},height:{get:function(){return u},set:function(a){u=a}},focusHeight:{get:function(){return v},set:function(a){v=a}},showLegend:{get:function(){return x},set:function(a){x=a}},brushExtent:{get:function(){return y},set:function(a){y=a}},defaultState:{get:function(){return D},set:function(a){D=a}},noData:{get:function(){return z},set:function(a){z=a}},tooltips:{get:function(){return o.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),o.enabled(!!b)}},tooltipContent:{get:function(){return o.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),o.contentGenerator(b)}},margin:{get:function(){return q},set:function(a){q.top=void 0!==a.top?a.top:q.top,q.right=void 0!==a.right?a.right:q.right,q.bottom=void 0!==a.bottom?a.bottom:q.bottom,q.left=void 0!==a.left?a.left:q.left}},color:{get:function(){return s},set:function(b){s=a.utils.getColor(b),m.color(s)}},interpolate:{get:function(){return g.interpolate()},set:function(a){g.interpolate(a),h.interpolate(a)}},xTickFormat:{get:function(){return i.tickFormat()},set:function(a){i.tickFormat(a),k.tickFormat(a)}},yTickFormat:{get:function(){return j.tickFormat()},set:function(a){j.tickFormat(a),l.tickFormat(a)}},duration:{get:function(){return B},set:function(a){B=a,j.duration(B),l.duration(B),i.duration(B),k.duration(B)}},x:{get:function(){return g.x()},set:function(a){g.x(a),h.x(a)}},y:{get:function(){return g.y()},set:function(a){g.y(a),h.y(a)}},useInteractiveGuideline:{get:function(){return w},set:function(a){w=a,w&&(g.interactive(!1),g.useVoronoi(!1))}}}),a.utils.inheritOptions(b,g),a.utils.initOptions(b),b},a.models.multiBar=function(){"use strict";function b(G){return E.reset(),G.each(function(b){var G=k-j.left-j.right,H=l-j.top-j.bottom;p=d3.select(this),a.utils.initSVG(p);var I=0;if(z&&b.length&&(z=[{values:b[0].values.map(function(a){return{x:a.x,y:0,series:a.series,size:.01}})}]),v){var J=d3.layout.stack().offset(w).values(function(a){return a.values}).y(r)(!b.length&&z?z:b);J.forEach(function(a,c){a.nonStackable?(b[c].nonStackableSeries=I++,J[c]=b[c]):c>0&&J[c-1].nonStackable&&J[c].values.map(function(a,b){a.y0-=J[c-1].values[b].y,a.y1=a.y0+a.y})}),b=J}b.forEach(function(a,b){a.values.forEach(function(c){c.series=b,c.key=a.key})}),v&&b[0].values.map(function(a,c){var d=0,e=0;b.map(function(a,f){if(!b[f].nonStackable){var g=a.values[c];g.size=Math.abs(g.y),g.y<0?(g.y1=e,e-=g.size):(g.y1=g.size+d,d+=g.size)}})});var K=d&&e?[]:b.map(function(a,b){return a.values.map(function(a,c){return{x:q(a,c),y:r(a,c),y0:a.y0,y1:a.y1,idx:b,yErr:s(a,c)}})});m.domain(d||d3.merge(K).map(function(a){return a.x})).rangeBands(f||[0,G],C),n.domain(e||d3.extent(d3.merge(d3.merge(K).map(function(a){var c=a.y;v&&!b[a.idx].nonStackable&&(c=a.y>0?a.y1:a.y1+a.y);var d=a.yErr;return d?d.length?[c+d[0],c+d[1]]:(d=Math.abs(d),[c-d,c+d]):[c]})).concat(t))).range(g||[H,0]),m.domain()[0]===m.domain()[1]&&(m.domain()[0]?m.domain([m.domain()[0]-.01*m.domain()[0],m.domain()[1]+.01*m.domain()[1]]):m.domain([-1,1])),n.domain()[0]===n.domain()[1]&&(n.domain()[0]?n.domain([n.domain()[0]+.01*n.domain()[0],n.domain()[1]-.01*n.domain()[1]]):n.domain([-1,1])),h=h||m,i=i||n;var L=p.selectAll("g.nv-wrap.nv-multibar").data([b]),M=L.enter().append("g").attr("class","nvd3 nv-wrap nv-multibar"),N=M.append("defs"),O=M.append("g"),P=L.select("g");O.append("g").attr("class","nv-groups"),L.attr("transform","translate("+j.left+","+j.top+")"),N.append("clipPath").attr("id","nv-edge-clip-"+o).append("rect"),L.select("#nv-edge-clip-"+o+" rect").attr("width",G).attr("height",H),P.attr("clip-path",u?"url(#nv-edge-clip-"+o+")":"");var Q=L.select(".nv-groups").selectAll(".nv-group").data(function(a){return a},function(a,b){return b});Q.enter().append("g").style("stroke-opacity",1e-6).style("fill-opacity",1e-6);var R=E.transition(Q.exit().selectAll("g.nv-bar"),"multibarExit",Math.min(100,B)).attr("y",function(a,c,d){var e=i(0)||0;return v&&b[a.series]&&!b[a.series].nonStackable&&(e=i(a.y0)),e}).attr("height",0).remove();R.delay&&R.delay(function(a,b){var c=b*(B/(F+1))-b;return c}),Q.attr("class",function(a,b){return"nv-group nv-series-"+b}).classed("hover",function(a){return a.hover}).style("fill",function(a,b){return x(a,b)}).style("stroke",function(a,b){return x(a,b)}),Q.style("stroke-opacity",1).style("fill-opacity",.75);var S=Q.selectAll("g.nv-bar").data(function(a){return z&&!b.length?z.values:a.values});S.exit().remove();var T=S.enter().append("g").attr("class",function(a,b){return r(a,b)<0?"nv-bar negative":"nv-bar positive"}).attr("transform",function(a,c,d){var e=v&&!b[d].nonStackable?0:d*m.rangeBand()/b.length,f=i(v&&!b[d].nonStackable?a.y0:0)||0;return"translate("+e+","+f+")"});T.append("rect").attr("height",0).attr("width",function(a,c,d){return m.rangeBand()/(v&&!b[d].nonStackable?1:b.length)}).style("fill",function(a,b,c){return x(a,c,b)}).style("stroke",function(a,b,c){return x(a,c,b)}),S.on("mouseover",function(a,b){d3.select(this).classed("hover",!0),D.elementMouseover({data:a,index:b,color:d3.select(this).style("fill")})}).on("mouseout",function(a,b){d3.select(this).classed("hover",!1),D.elementMouseout({data:a,index:b,color:d3.select(this).style("fill")})}).on("mousemove",function(a,b){D.elementMousemove({data:a,index:b,color:d3.select(this).style("fill")})}).on("click",function(a,b){D.elementClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation()}).on("dblclick",function(a,b){D.elementDblClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation()}),s(b[0].values[0],0)&&(T.append("polyline"),S.select("polyline").attr("fill","none").attr("stroke",function(a,b,c){return y(a,c,b)}).attr("points",function(a,c){var d=s(a,c),e=.8*m.rangeBand()/(2*(v?1:b.length));d=d.length?d:[-Math.abs(d),Math.abs(d)],d=d.map(function(a){return n(a)-n(0)});var f=[[-e,d[0]],[e,d[0]],[0,d[0]],[0,d[1]],[-e,d[1]],[e,d[1]]];return f.map(function(a){return a.join(",")}).join(" ")}).attr("transform",function(a,c){var d=m.rangeBand()/(2*(v?1:b.length)),e=r(a,c)<0?n(r(a,c))-n(0):0;return"translate("+d+", "+e+")"})),S.attr("class",function(a,b){return r(a,b)<0?"nv-bar negative":"nv-bar positive"}),A&&(c||(c=b.map(function(){return!0})),S.select("rect").style("fill",function(a,b,d){return d3.rgb(A(a,b)).darker(c.map(function(a,b){return b}).filter(function(a,b){return!c[b]})[d]).toString()}).style("stroke",function(a,b,d){return d3.rgb(A(a,b)).darker(c.map(function(a,b){return b}).filter(function(a,b){return!c[b]})[d]).toString()}));var U=S.watchTransition(E,"multibar",Math.min(250,B)).delay(function(a,c){return c*B/b[0].values.length});v?U.attr("transform",function(a,c,d){var e=0;e=b[d].nonStackable?r(a,c)<0?n(0):n(0)-n(r(a,c))<-1?n(0)-1:n(r(a,c))||0:n(a.y1);var f=0;b[d].nonStackable&&(f=a.series*m.rangeBand()/b.length,b.length!==I&&(f=b[d].nonStackableSeries*m.rangeBand()/(2*I)));var g=f+m(q(a,c));return"translate("+g+","+e+")"}).select("rect").attr("height",function(a,c,d){return b[d].nonStackable?Math.max(Math.abs(n(r(a,c))-n(0)),1)||0:Math.max(Math.abs(n(a.y+a.y0)-n(a.y0)),1)}).attr("width",function(a,c,d){if(b[d].nonStackable){var e=m.rangeBand()/I;return b.length!==I&&(e=m.rangeBand()/(2*I)),e}return m.rangeBand()}):U.attr("transform",function(a,c){var d=a.series*m.rangeBand()/b.length+m(q(a,c)),e=r(a,c)<0?n(0):n(0)-n(r(a,c))<1?n(0)-1:n(r(a,c))||0;return"translate("+d+","+e+")"}).select("rect").attr("width",m.rangeBand()/b.length).attr("height",function(a,b){return Math.max(Math.abs(n(r(a,b))-n(0)),1)||0}),h=m.copy(),i=n.copy(),b[0]&&b[0].values&&(F=b[0].values.length)}),E.renderEnd("multibar immediate"),b}var c,d,e,f,g,h,i,j={top:0,right:0,bottom:0,left:0},k=960,l=500,m=d3.scale.ordinal(),n=d3.scale.linear(),o=Math.floor(1e4*Math.random()),p=null,q=function(a){return a.x},r=function(a){return a.y},s=function(a){return a.yErr},t=[0],u=!0,v=!1,w="zero",x=a.utils.defaultColor(),y=a.utils.defaultColor(),z=!1,A=null,B=500,C=.1,D=d3.dispatch("chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove","renderEnd"),E=a.utils.renderWatch(D,B),F=0;return b.dispatch=D,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return k},set:function(a){k=a}},height:{get:function(){return l},set:function(a){l=a}},x:{get:function(){return q},set:function(a){q=a}},y:{get:function(){return r},set:function(a){r=a}},yErr:{get:function(){return s},set:function(a){s=a}},xScale:{get:function(){return m},set:function(a){m=a}},yScale:{get:function(){return n},set:function(a){n=a}},xDomain:{get:function(){return d},set:function(a){d=a}},yDomain:{get:function(){return e},set:function(a){e=a}},xRange:{get:function(){return f},set:function(a){f=a}},yRange:{get:function(){return g},set:function(a){g=a}},forceY:{get:function(){return t},set:function(a){t=a}},stacked:{get:function(){return v},set:function(a){v=a}},stackOffset:{get:function(){return w},set:function(a){w=a}},clipEdge:{get:function(){return u},set:function(a){u=a}},disabled:{get:function(){return c},set:function(a){c=a}},id:{get:function(){return o},set:function(a){o=a}},hideable:{get:function(){
+return z},set:function(a){z=a}},groupSpacing:{get:function(){return C},set:function(a){C=a}},margin:{get:function(){return j},set:function(a){j.top=void 0!==a.top?a.top:j.top,j.right=void 0!==a.right?a.right:j.right,j.bottom=void 0!==a.bottom?a.bottom:j.bottom,j.left=void 0!==a.left?a.left:j.left}},duration:{get:function(){return B},set:function(a){B=a,E.reset(B)}},color:{get:function(){return x},set:function(b){x=a.utils.getColor(b)}},barColor:{get:function(){return A},set:function(b){A=b?a.utils.getColor(b):null}},errorBarColor:{get:function(){return y},set:function(b){y=b?a.utils.getColor(b):null}}}),a.utils.initOptions(b),b},a.models.multiBarChart=function(){"use strict";function b(j){return D.reset(),D.models(e),r&&D.models(f),s&&D.models(g),j.each(function(j){var z=d3.select(this);a.utils.initSVG(z);var D=a.utils.availableWidth(l,z,k),H=a.utils.availableHeight(m,z,k);if(b.update=function(){0===C?z.call(b):z.transition().duration(C).call(b)},b.container=this,x.setter(G(j),b.update).getter(F(j)).update(),x.disabled=j.map(function(a){return!!a.disabled}),!y){var I;y={};for(I in x)x[I]instanceof Array?y[I]=x[I].slice(0):y[I]=x[I]}if(!(j&&j.length&&j.filter(function(a){return a.values.length}).length))return a.utils.noData(b,z),b;z.selectAll(".nv-noData").remove(),c=e.xScale(),d=e.yScale();var J=z.selectAll("g.nv-wrap.nv-multiBarWithLegend").data([j]),K=J.enter().append("g").attr("class","nvd3 nv-wrap nv-multiBarWithLegend").append("g"),L=J.select("g");if(K.append("g").attr("class","nv-x nv-axis"),K.append("g").attr("class","nv-y nv-axis"),K.append("g").attr("class","nv-barsWrap"),K.append("g").attr("class","nv-legendWrap"),K.append("g").attr("class","nv-controlsWrap"),q&&(h.width(D-B()),L.select(".nv-legendWrap").datum(j).call(h),k.top!=h.height()&&(k.top=h.height(),H=a.utils.availableHeight(m,z,k)),L.select(".nv-legendWrap").attr("transform","translate("+B()+","+-k.top+")")),o){var M=[{key:p.grouped||"Grouped",disabled:e.stacked()},{key:p.stacked||"Stacked",disabled:!e.stacked()}];i.width(B()).color(["#444","#444","#444"]),L.select(".nv-controlsWrap").datum(M).attr("transform","translate(0,"+-k.top+")").call(i)}J.attr("transform","translate("+k.left+","+k.top+")"),t&&L.select(".nv-y.nv-axis").attr("transform","translate("+D+",0)"),e.disabled(j.map(function(a){return a.disabled})).width(D).height(H).color(j.map(function(a,b){return a.color||n(a,b)}).filter(function(a,b){return!j[b].disabled}));var N=L.select(".nv-barsWrap").datum(j.filter(function(a){return!a.disabled}));if(N.call(e),r){f.scale(c)._ticks(a.utils.calcTicksX(D/100,j)).tickSize(-H,0),L.select(".nv-x.nv-axis").attr("transform","translate(0,"+d.range()[0]+")"),L.select(".nv-x.nv-axis").call(f);var O=L.select(".nv-x.nv-axis > g").selectAll("g");if(O.selectAll("line, text").style("opacity",1),v){var P=function(a,b){return"translate("+a+","+b+")"},Q=5,R=17;O.selectAll("text").attr("transform",function(a,b,c){return P(0,c%2==0?Q:R)});var S=d3.selectAll(".nv-x.nv-axis .nv-wrap g g text")[0].length;L.selectAll(".nv-x.nv-axis .nv-axisMaxMin text").attr("transform",function(a,b){return P(0,0===b||S%2!==0?R:Q)})}u&&O.filter(function(a,b){return b%Math.ceil(j[0].values.length/(D/100))!==0}).selectAll("text, line").style("opacity",0),w&&O.selectAll(".tick text").attr("transform","rotate("+w+" 0,0)").style("text-anchor",w>0?"start":"end"),L.select(".nv-x.nv-axis").selectAll("g.nv-axisMaxMin text").style("opacity",1)}s&&(g.scale(d)._ticks(a.utils.calcTicksY(H/36,j)).tickSize(-D,0),L.select(".nv-y.nv-axis").call(g)),h.dispatch.on("stateChange",function(a){for(var c in a)x[c]=a[c];A.stateChange(x),b.update()}),i.dispatch.on("legendClick",function(a,c){if(a.disabled){switch(M=M.map(function(a){return a.disabled=!0,a}),a.disabled=!1,a.key){case"Grouped":case p.grouped:e.stacked(!1);break;case"Stacked":case p.stacked:e.stacked(!0)}x.stacked=e.stacked(),A.stateChange(x),b.update()}}),A.on("changeState",function(a){"undefined"!=typeof a.disabled&&(j.forEach(function(b,c){b.disabled=a.disabled[c]}),x.disabled=a.disabled),"undefined"!=typeof a.stacked&&(e.stacked(a.stacked),x.stacked=a.stacked,E=a.stacked),b.update()})}),D.renderEnd("multibarchart immediate"),b}var c,d,e=a.models.multiBar(),f=a.models.axis(),g=a.models.axis(),h=a.models.legend(),i=a.models.legend(),j=a.models.tooltip(),k={top:30,right:20,bottom:50,left:60},l=null,m=null,n=a.utils.defaultColor(),o=!0,p={},q=!0,r=!0,s=!0,t=!1,u=!0,v=!1,w=0,x=a.utils.state(),y=null,z=null,A=d3.dispatch("stateChange","changeState","renderEnd"),B=function(){return o?180:0},C=250;x.stacked=!1,e.stacked(!1),f.orient("bottom").tickPadding(7).showMaxMin(!1).tickFormat(function(a){return a}),g.orient(t?"right":"left").tickFormat(d3.format(",.1f")),j.duration(0).valueFormatter(function(a,b){return g.tickFormat()(a,b)}).headerFormatter(function(a,b){return f.tickFormat()(a,b)}),i.updateState(!1);var D=a.utils.renderWatch(A),E=!1,F=function(a){return function(){return{active:a.map(function(a){return!a.disabled}),stacked:E}}},G=function(a){return function(b){void 0!==b.stacked&&(E=b.stacked),void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};return e.dispatch.on("elementMouseover.tooltip",function(a){a.value=b.x()(a.data),a.series={key:a.data.key,value:b.y()(a.data),color:a.color},j.data(a).hidden(!1)}),e.dispatch.on("elementMouseout.tooltip",function(a){j.hidden(!0)}),e.dispatch.on("elementMousemove.tooltip",function(a){j.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.dispatch=A,b.multibar=e,b.legend=h,b.controls=i,b.xAxis=f,b.yAxis=g,b.state=x,b.tooltip=j,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return l},set:function(a){l=a}},height:{get:function(){return m},set:function(a){m=a}},showLegend:{get:function(){return q},set:function(a){q=a}},showControls:{get:function(){return o},set:function(a){o=a}},controlLabels:{get:function(){return p},set:function(a){p=a}},showXAxis:{get:function(){return r},set:function(a){r=a}},showYAxis:{get:function(){return s},set:function(a){s=a}},defaultState:{get:function(){return y},set:function(a){y=a}},noData:{get:function(){return z},set:function(a){z=a}},reduceXTicks:{get:function(){return u},set:function(a){u=a}},rotateLabels:{get:function(){return w},set:function(a){w=a}},staggerLabels:{get:function(){return v},set:function(a){v=a}},tooltips:{get:function(){return j.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),j.enabled(!!b)}},tooltipContent:{get:function(){return j.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),j.contentGenerator(b)}},margin:{get:function(){return k},set:function(a){k.top=void 0!==a.top?a.top:k.top,k.right=void 0!==a.right?a.right:k.right,k.bottom=void 0!==a.bottom?a.bottom:k.bottom,k.left=void 0!==a.left?a.left:k.left}},duration:{get:function(){return C},set:function(a){C=a,e.duration(C),f.duration(C),g.duration(C),D.reset(C)}},color:{get:function(){return n},set:function(b){n=a.utils.getColor(b),h.color(n)}},rightAlignYAxis:{get:function(){return t},set:function(a){t=a,g.orient(t?"right":"left")}},barColor:{get:function(){return e.barColor},set:function(a){e.barColor(a),h.color(function(a,b){return d3.rgb("#ccc").darker(1.5*b).toString()})}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.multiBarHorizontal=function(){"use strict";function b(m){return F.reset(),m.each(function(b){var m=k-j.left-j.right,D=l-j.top-j.bottom;n=d3.select(this),a.utils.initSVG(n),x&&(b=d3.layout.stack().offset("zero").values(function(a){return a.values}).y(r)(b)),b.forEach(function(a,b){a.values.forEach(function(c){c.series=b,c.key=a.key})}),x&&b[0].values.map(function(a,c){var d=0,e=0;b.map(function(a){var b=a.values[c];b.size=Math.abs(b.y),b.y<0?(b.y1=e-b.size,e-=b.size):(b.y1=d,d+=b.size)})});var G=d&&e?[]:b.map(function(a){return a.values.map(function(a,b){return{x:q(a,b),y:r(a,b),y0:a.y0,y1:a.y1,yErr:s(a,b)}})});o.domain(d||d3.merge(G).map(function(a){return a.x})).rangeBands(f||[0,D],B),p.domain(e||d3.extent(d3.merge(d3.merge(G).map(function(a){var b=a.y;x&&(b=a.y>0?a.y1+a.y:a.y1);var c=a.yErr;return c?c.length?[b+c[0],b+c[1]]:(c=Math.abs(c),[b-c,b+c]):[b]})).concat(t))),y&&!x?p.range(g||[p.domain()[0]<0?A:0,m-(p.domain()[1]>0?A:0)]):p.range(g||[0,m]),h=h||o,i=i||d3.scale.linear().domain(p.domain()).range([p(0),p(0)]);var H=d3.select(this).selectAll("g.nv-wrap.nv-multibarHorizontal").data([b]),I=H.enter().append("g").attr("class","nvd3 nv-wrap nv-multibarHorizontal"),J=(I.append("defs"),I.append("g"));H.select("g");J.append("g").attr("class","nv-groups"),H.attr("transform","translate("+j.left+","+j.top+")");var K=H.select(".nv-groups").selectAll(".nv-group").data(function(a){return a},function(a,b){return b});K.enter().append("g").style("stroke-opacity",1e-6).style("fill-opacity",1e-6),K.exit().watchTransition(F,"multibarhorizontal: exit groups").style("stroke-opacity",1e-6).style("fill-opacity",1e-6).remove(),K.attr("class",function(a,b){return"nv-group nv-series-"+b}).classed("hover",function(a){return a.hover}).style("fill",function(a,b){return u(a,b)}).style("stroke",function(a,b){return u(a,b)}),K.watchTransition(F,"multibarhorizontal: groups").style("stroke-opacity",1).style("fill-opacity",.75);var L=K.selectAll("g.nv-bar").data(function(a){return a.values});L.exit().remove();var M=L.enter().append("g").attr("transform",function(a,c,d){return"translate("+i(x?a.y0:0)+","+(x?0:d*o.rangeBand()/b.length+o(q(a,c)))+")"});M.append("rect").attr("width",0).attr("height",o.rangeBand()/(x?1:b.length)),L.on("mouseover",function(a,b){d3.select(this).classed("hover",!0),E.elementMouseover({data:a,index:b,color:d3.select(this).style("fill")})}).on("mouseout",function(a,b){d3.select(this).classed("hover",!1),E.elementMouseout({data:a,index:b,color:d3.select(this).style("fill")})}).on("mouseout",function(a,b){E.elementMouseout({data:a,index:b,color:d3.select(this).style("fill")})}).on("mousemove",function(a,b){E.elementMousemove({data:a,index:b,color:d3.select(this).style("fill")})}).on("click",function(a,b){E.elementClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation()}).on("dblclick",function(a,b){E.elementDblClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation()}),s(b[0].values[0],0)&&(M.append("polyline"),L.select("polyline").attr("fill","none").attr("stroke",function(a,b,c){return w(a,c,b)}).attr("points",function(a,c){var d=s(a,c),e=.8*o.rangeBand()/(2*(x?1:b.length));d=d.length?d:[-Math.abs(d),Math.abs(d)],d=d.map(function(a){return p(a)-p(0)});var f=[[d[0],-e],[d[0],e],[d[0],0],[d[1],0],[d[1],-e],[d[1],e]];return f.map(function(a){return a.join(",")}).join(" ")}).attr("transform",function(a,c){var d=o.rangeBand()/(2*(x?1:b.length));return"translate("+(r(a,c)<0?0:p(r(a,c))-p(0))+", "+d+")"})),M.append("text"),y&&!x?(L.select("text").attr("text-anchor",function(a,b){return r(a,b)<0?"end":"start"}).attr("y",o.rangeBand()/(2*b.length)).attr("dy",".32em").text(function(a,b){var c=C(r(a,b)),d=s(a,b);return void 0===d?c:d.length?c+"+"+C(Math.abs(d[1]))+"-"+C(Math.abs(d[0])):c+"±"+C(Math.abs(d))}),L.watchTransition(F,"multibarhorizontal: bars").select("text").attr("x",function(a,b){return r(a,b)<0?-4:p(r(a,b))-p(0)+4})):L.selectAll("text").text(""),z&&!x?(M.append("text").classed("nv-bar-label",!0),L.select("text.nv-bar-label").attr("text-anchor",function(a,b){return r(a,b)<0?"start":"end"}).attr("y",o.rangeBand()/(2*b.length)).attr("dy",".32em").text(function(a,b){return q(a,b)}),L.watchTransition(F,"multibarhorizontal: bars").select("text.nv-bar-label").attr("x",function(a,b){return r(a,b)<0?p(0)-p(r(a,b))+4:-4})):L.selectAll("text.nv-bar-label").text(""),L.attr("class",function(a,b){return r(a,b)<0?"nv-bar negative":"nv-bar positive"}),v&&(c||(c=b.map(function(){return!0})),L.style("fill",function(a,b,d){return d3.rgb(v(a,b)).darker(c.map(function(a,b){return b}).filter(function(a,b){return!c[b]})[d]).toString()}).style("stroke",function(a,b,d){return d3.rgb(v(a,b)).darker(c.map(function(a,b){return b}).filter(function(a,b){return!c[b]})[d]).toString()})),x?L.watchTransition(F,"multibarhorizontal: bars").attr("transform",function(a,b){return"translate("+p(a.y1)+","+o(q(a,b))+")"}).select("rect").attr("width",function(a,b){return Math.abs(p(r(a,b)+a.y0)-p(a.y0))}).attr("height",o.rangeBand()):L.watchTransition(F,"multibarhorizontal: bars").attr("transform",function(a,c){return"translate("+p(r(a,c)<0?r(a,c):0)+","+(a.series*o.rangeBand()/b.length+o(q(a,c)))+")"}).select("rect").attr("height",o.rangeBand()/b.length).attr("width",function(a,b){return Math.max(Math.abs(p(r(a,b))-p(0)),1)}),h=o.copy(),i=p.copy()}),F.renderEnd("multibarHorizontal immediate"),b}var c,d,e,f,g,h,i,j={top:0,right:0,bottom:0,left:0},k=960,l=500,m=Math.floor(1e4*Math.random()),n=null,o=d3.scale.ordinal(),p=d3.scale.linear(),q=function(a){return a.x},r=function(a){return a.y},s=function(a){return a.yErr},t=[0],u=a.utils.defaultColor(),v=null,w=a.utils.defaultColor(),x=!1,y=!1,z=!1,A=60,B=.1,C=d3.format(",.2f"),D=250,E=d3.dispatch("chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove","renderEnd"),F=a.utils.renderWatch(E,D);return b.dispatch=E,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return k},set:function(a){k=a}},height:{get:function(){return l},set:function(a){l=a}},x:{get:function(){return q},set:function(a){q=a}},y:{get:function(){return r},set:function(a){r=a}},yErr:{get:function(){return s},set:function(a){s=a}},xScale:{get:function(){return o},set:function(a){o=a}},yScale:{get:function(){return p},set:function(a){p=a}},xDomain:{get:function(){return d},set:function(a){d=a}},yDomain:{get:function(){return e},set:function(a){e=a}},xRange:{get:function(){return f},set:function(a){f=a}},yRange:{get:function(){return g},set:function(a){g=a}},forceY:{get:function(){return t},set:function(a){t=a}},stacked:{get:function(){return x},set:function(a){x=a}},showValues:{get:function(){return y},set:function(a){y=a}},disabled:{get:function(){return c},set:function(a){c=a}},id:{get:function(){return m},set:function(a){m=a}},valueFormat:{get:function(){return C},set:function(a){C=a}},valuePadding:{get:function(){return A},set:function(a){A=a}},groupSpacing:{get:function(){return B},set:function(a){B=a}},margin:{get:function(){return j},set:function(a){j.top=void 0!==a.top?a.top:j.top,j.right=void 0!==a.right?a.right:j.right,j.bottom=void 0!==a.bottom?a.bottom:j.bottom,j.left=void 0!==a.left?a.left:j.left}},duration:{get:function(){return D},set:function(a){D=a,F.reset(D)}},color:{get:function(){return u},set:function(b){u=a.utils.getColor(b)}},barColor:{get:function(){return v},set:function(b){v=b?a.utils.getColor(b):null}},errorBarColor:{get:function(){return w},set:function(b){w=b?a.utils.getColor(b):null}}}),a.utils.initOptions(b),b},a.models.multiBarHorizontalChart=function(){"use strict";function b(j){return C.reset(),C.models(e),r&&C.models(f),s&&C.models(g),j.each(function(j){var w=d3.select(this);a.utils.initSVG(w);var C=a.utils.availableWidth(l,w,k),D=a.utils.availableHeight(m,w,k);if(b.update=function(){w.transition().duration(z).call(b)},b.container=this,t=e.stacked(),u.setter(B(j),b.update).getter(A(j)).update(),u.disabled=j.map(function(a){return!!a.disabled}),!v){var E;v={};for(E in u)u[E]instanceof Array?v[E]=u[E].slice(0):v[E]=u[E]}if(!(j&&j.length&&j.filter(function(a){return a.values.length}).length))return a.utils.noData(b,w),b;w.selectAll(".nv-noData").remove(),c=e.xScale(),d=e.yScale();var F=w.selectAll("g.nv-wrap.nv-multiBarHorizontalChart").data([j]),G=F.enter().append("g").attr("class","nvd3 nv-wrap nv-multiBarHorizontalChart").append("g"),H=F.select("g");if(G.append("g").attr("class","nv-x nv-axis"),G.append("g").attr("class","nv-y nv-axis").append("g").attr("class","nv-zeroLine").append("line"),G.append("g").attr("class","nv-barsWrap"),G.append("g").attr("class","nv-legendWrap"),G.append("g").attr("class","nv-controlsWrap"),q&&(h.width(C-y()),H.select(".nv-legendWrap").datum(j).call(h),k.top!=h.height()&&(k.top=h.height(),D=a.utils.availableHeight(m,w,k)),H.select(".nv-legendWrap").attr("transform","translate("+y()+","+-k.top+")")),o){var I=[{key:p.grouped||"Grouped",disabled:e.stacked()},{key:p.stacked||"Stacked",disabled:!e.stacked()}];i.width(y()).color(["#444","#444","#444"]),H.select(".nv-controlsWrap").datum(I).attr("transform","translate(0,"+-k.top+")").call(i)}F.attr("transform","translate("+k.left+","+k.top+")"),e.disabled(j.map(function(a){return a.disabled})).width(C).height(D).color(j.map(function(a,b){return a.color||n(a,b)}).filter(function(a,b){return!j[b].disabled}));var J=H.select(".nv-barsWrap").datum(j.filter(function(a){return!a.disabled}));if(J.transition().call(e),r){f.scale(c)._ticks(a.utils.calcTicksY(D/24,j)).tickSize(-C,0),H.select(".nv-x.nv-axis").call(f);var K=H.select(".nv-x.nv-axis").selectAll("g");K.selectAll("line, text")}s&&(g.scale(d)._ticks(a.utils.calcTicksX(C/100,j)).tickSize(-D,0),H.select(".nv-y.nv-axis").attr("transform","translate(0,"+D+")"),H.select(".nv-y.nv-axis").call(g)),H.select(".nv-zeroLine line").attr("x1",d(0)).attr("x2",d(0)).attr("y1",0).attr("y2",-D),h.dispatch.on("stateChange",function(a){for(var c in a)u[c]=a[c];x.stateChange(u),b.update()}),i.dispatch.on("legendClick",function(a,c){if(a.disabled){switch(I=I.map(function(a){return a.disabled=!0,a}),a.disabled=!1,a.key){case"Grouped":e.stacked(!1);break;case"Stacked":e.stacked(!0)}u.stacked=e.stacked(),x.stateChange(u),t=e.stacked(),b.update()}}),x.on("changeState",function(a){"undefined"!=typeof a.disabled&&(j.forEach(function(b,c){b.disabled=a.disabled[c]}),u.disabled=a.disabled),"undefined"!=typeof a.stacked&&(e.stacked(a.stacked),u.stacked=a.stacked,t=a.stacked),b.update()})}),C.renderEnd("multibar horizontal chart immediate"),b}var c,d,e=a.models.multiBarHorizontal(),f=a.models.axis(),g=a.models.axis(),h=a.models.legend().height(30),i=a.models.legend().height(30),j=a.models.tooltip(),k={top:30,right:20,bottom:50,left:60},l=null,m=null,n=a.utils.defaultColor(),o=!0,p={},q=!0,r=!0,s=!0,t=!1,u=a.utils.state(),v=null,w=null,x=d3.dispatch("stateChange","changeState","renderEnd"),y=function(){return o?180:0},z=250;u.stacked=!1,e.stacked(t),f.orient("left").tickPadding(5).showMaxMin(!1).tickFormat(function(a){return a}),g.orient("bottom").tickFormat(d3.format(",.1f")),j.duration(0).valueFormatter(function(a,b){return g.tickFormat()(a,b)}).headerFormatter(function(a,b){return f.tickFormat()(a,b)}),i.updateState(!1);var A=function(a){return function(){return{active:a.map(function(a){return!a.disabled}),stacked:t}}},B=function(a){return function(b){void 0!==b.stacked&&(t=b.stacked),void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}},C=a.utils.renderWatch(x,z);return e.dispatch.on("elementMouseover.tooltip",function(a){a.value=b.x()(a.data),a.series={key:a.data.key,value:b.y()(a.data),color:a.color},j.data(a).hidden(!1)}),e.dispatch.on("elementMouseout.tooltip",function(a){j.hidden(!0)}),e.dispatch.on("elementMousemove.tooltip",function(a){j.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.dispatch=x,b.multibar=e,b.legend=h,b.controls=i,b.xAxis=f,b.yAxis=g,b.state=u,b.tooltip=j,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return l},set:function(a){l=a}},height:{get:function(){return m},set:function(a){m=a}},showLegend:{get:function(){return q},set:function(a){q=a}},showControls:{get:function(){return o},set:function(a){o=a}},controlLabels:{get:function(){return p},set:function(a){p=a}},showXAxis:{get:function(){return r},set:function(a){r=a}},showYAxis:{get:function(){return s},set:function(a){s=a}},defaultState:{get:function(){return v},set:function(a){v=a}},noData:{get:function(){return w},set:function(a){w=a}},tooltips:{get:function(){return j.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),j.enabled(!!b)}},tooltipContent:{get:function(){return j.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),j.contentGenerator(b)}},margin:{get:function(){return k},set:function(a){k.top=void 0!==a.top?a.top:k.top,k.right=void 0!==a.right?a.right:k.right,k.bottom=void 0!==a.bottom?a.bottom:k.bottom,k.left=void 0!==a.left?a.left:k.left}},duration:{get:function(){return z},set:function(a){z=a,C.reset(z),e.duration(z),f.duration(z),g.duration(z)}},color:{get:function(){return n},set:function(b){n=a.utils.getColor(b),h.color(n)}},barColor:{get:function(){return e.barColor},set:function(a){e.barColor(a),h.color(function(a,b){return d3.rgb("#ccc").darker(1.5*b).toString()})}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.multiChart=function(){"use strict";function b(j){return j.each(function(j){function k(a){var b=2===j[a.seriesIndex].yAxis?z:y;a.value=a.point.x,a.series={value:a.point.y,color:a.point.color},B.duration(100).valueFormatter(function(a,c){return b.tickFormat()(a,c)}).data(a).position(a.pos).hidden(!1)}function l(a){var b=2===j[a.seriesIndex].yAxis?z:y;a.point.x=v.x()(a.point),a.point.y=v.y()(a.point),B.duration(100).valueFormatter(function(a,c){return b.tickFormat()(a,c)}).data(a).position(a.pos).hidden(!1)}function n(a){var b=2===j[a.data.series].yAxis?z:y;a.value=t.x()(a.data),a.series={value:t.y()(a.data),color:a.color},B.duration(0).valueFormatter(function(a,c){return b.tickFormat()(a,c)}).data(a).hidden(!1)}var C=d3.select(this);a.utils.initSVG(C),b.update=function(){C.transition().call(b)},b.container=this;var D=a.utils.availableWidth(g,C,e),E=a.utils.availableHeight(h,C,e),F=j.filter(function(a){return"line"==a.type&&1==a.yAxis}),G=j.filter(function(a){return"line"==a.type&&2==a.yAxis}),H=j.filter(function(a){return"bar"==a.type&&1==a.yAxis}),I=j.filter(function(a){return"bar"==a.type&&2==a.yAxis}),J=j.filter(function(a){return"area"==a.type&&1==a.yAxis}),K=j.filter(function(a){return"area"==a.type&&2==a.yAxis});if(!(j&&j.length&&j.filter(function(a){return a.values.length}).length))return a.utils.noData(b,C),b;C.selectAll(".nv-noData").remove();var L=j.filter(function(a){return!a.disabled&&1==a.yAxis}).map(function(a){return a.values.map(function(a,b){return{x:a.x,y:a.y}})}),M=j.filter(function(a){return!a.disabled&&2==a.yAxis}).map(function(a){return a.values.map(function(a,b){return{x:a.x,y:a.y}})});o.domain(d3.extent(d3.merge(L.concat(M)),function(a){return a.x})).range([0,D]);var N=C.selectAll("g.wrap.multiChart").data([j]),O=N.enter().append("g").attr("class","wrap nvd3 multiChart").append("g");O.append("g").attr("class","nv-x nv-axis"),O.append("g").attr("class","nv-y1 nv-axis"),O.append("g").attr("class","nv-y2 nv-axis"),O.append("g").attr("class","lines1Wrap"),O.append("g").attr("class","lines2Wrap"),O.append("g").attr("class","bars1Wrap"),O.append("g").attr("class","bars2Wrap"),O.append("g").attr("class","stack1Wrap"),O.append("g").attr("class","stack2Wrap"),O.append("g").attr("class","legendWrap");var P=N.select("g"),Q=j.map(function(a,b){return j[b].color||f(a,b)});if(i){var R=A.align()?D/2:D,S=A.align()?R:0;A.width(R),A.color(Q),P.select(".legendWrap").datum(j.map(function(a){return a.originalKey=void 0===a.originalKey?a.key:a.originalKey,a.key=a.originalKey+(1==a.yAxis?"":" (right axis)"),a})).call(A),e.top!=A.height()&&(e.top=A.height(),E=a.utils.availableHeight(h,C,e)),P.select(".legendWrap").attr("transform","translate("+S+","+-e.top+")")}r.width(D).height(E).interpolate(m).color(Q.filter(function(a,b){return!j[b].disabled&&1==j[b].yAxis&&"line"==j[b].type})),s.width(D).height(E).interpolate(m).color(Q.filter(function(a,b){return!j[b].disabled&&2==j[b].yAxis&&"line"==j[b].type})),t.width(D).height(E).color(Q.filter(function(a,b){return!j[b].disabled&&1==j[b].yAxis&&"bar"==j[b].type})),u.width(D).height(E).color(Q.filter(function(a,b){return!j[b].disabled&&2==j[b].yAxis&&"bar"==j[b].type})),v.width(D).height(E).color(Q.filter(function(a,b){return!j[b].disabled&&1==j[b].yAxis&&"area"==j[b].type})),w.width(D).height(E).color(Q.filter(function(a,b){return!j[b].disabled&&2==j[b].yAxis&&"area"==j[b].type})),P.attr("transform","translate("+e.left+","+e.top+")");var T=P.select(".lines1Wrap").datum(F.filter(function(a){return!a.disabled})),U=P.select(".bars1Wrap").datum(H.filter(function(a){return!a.disabled})),V=P.select(".stack1Wrap").datum(J.filter(function(a){return!a.disabled})),W=P.select(".lines2Wrap").datum(G.filter(function(a){return!a.disabled})),X=P.select(".bars2Wrap").datum(I.filter(function(a){return!a.disabled})),Y=P.select(".stack2Wrap").datum(K.filter(function(a){return!a.disabled})),Z=J.length?J.map(function(a){return a.values}).reduce(function(a,b){return a.map(function(a,c){return{x:a.x,y:a.y+b[c].y}})}).concat([{x:0,y:0}]):[],$=K.length?K.map(function(a){return a.values}).reduce(function(a,b){return a.map(function(a,c){return{x:a.x,y:a.y+b[c].y}})}).concat([{x:0,y:0}]):[];p.domain(c||d3.extent(d3.merge(L).concat(Z),function(a){return a.y})).range([0,E]),q.domain(d||d3.extent(d3.merge(M).concat($),function(a){return a.y})).range([0,E]),r.yDomain(p.domain()),t.yDomain(p.domain()),v.yDomain(p.domain()),s.yDomain(q.domain()),u.yDomain(q.domain()),w.yDomain(q.domain()),J.length&&d3.transition(V).call(v),K.length&&d3.transition(Y).call(w),H.length&&d3.transition(U).call(t),I.length&&d3.transition(X).call(u),F.length&&d3.transition(T).call(r),G.length&&d3.transition(W).call(s),x._ticks(a.utils.calcTicksX(D/100,j)).tickSize(-E,0),P.select(".nv-x.nv-axis").attr("transform","translate(0,"+E+")"),d3.transition(P.select(".nv-x.nv-axis")).call(x),y._ticks(a.utils.calcTicksY(E/36,j)).tickSize(-D,0),d3.transition(P.select(".nv-y1.nv-axis")).call(y),z._ticks(a.utils.calcTicksY(E/36,j)).tickSize(-D,0),d3.transition(P.select(".nv-y2.nv-axis")).call(z),P.select(".nv-y1.nv-axis").classed("nv-disabled",L.length?!1:!0).attr("transform","translate("+o.range()[0]+",0)"),P.select(".nv-y2.nv-axis").classed("nv-disabled",M.length?!1:!0).attr("transform","translate("+o.range()[1]+",0)"),A.dispatch.on("stateChange",function(a){b.update()}),r.dispatch.on("elementMouseover.tooltip",k),s.dispatch.on("elementMouseover.tooltip",k),r.dispatch.on("elementMouseout.tooltip",function(a){B.hidden(!0)}),s.dispatch.on("elementMouseout.tooltip",function(a){B.hidden(!0)}),v.dispatch.on("elementMouseover.tooltip",l),w.dispatch.on("elementMouseover.tooltip",l),v.dispatch.on("elementMouseout.tooltip",function(a){B.hidden(!0)}),w.dispatch.on("elementMouseout.tooltip",function(a){B.hidden(!0)}),t.dispatch.on("elementMouseover.tooltip",n),u.dispatch.on("elementMouseover.tooltip",n),t.dispatch.on("elementMouseout.tooltip",function(a){B.hidden(!0)}),u.dispatch.on("elementMouseout.tooltip",function(a){B.hidden(!0)}),t.dispatch.on("elementMousemove.tooltip",function(a){B.position({top:d3.event.pageY,left:d3.event.pageX})()}),u.dispatch.on("elementMousemove.tooltip",function(a){B.position({top:d3.event.pageY,left:d3.event.pageX})()})}),b}var c,d,e={top:30,right:20,bottom:50,left:60},f=a.utils.defaultColor(),g=null,h=null,i=!0,j=null,k=function(a){return a.x},l=function(a){return a.y},m="monotone",n=!0,o=d3.scale.linear(),p=d3.scale.linear(),q=d3.scale.linear(),r=a.models.line().yScale(p),s=a.models.line().yScale(q),t=a.models.multiBar().stacked(!1).yScale(p),u=a.models.multiBar().stacked(!1).yScale(q),v=a.models.stackedArea().yScale(p),w=a.models.stackedArea().yScale(q),x=a.models.axis().scale(o).orient("bottom").tickPadding(5),y=a.models.axis().scale(p).orient("left"),z=a.models.axis().scale(q).orient("right"),A=a.models.legend().height(30),B=a.models.tooltip(),C=d3.dispatch();return b.dispatch=C,b.lines1=r,b.lines2=s,b.bars1=t,b.bars2=u,b.stack1=v,b.stack2=w,b.xAxis=x,b.yAxis1=y,b.yAxis2=z,b.tooltip=B,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return g},set:function(a){g=a}},height:{get:function(){return h},set:function(a){h=a}},showLegend:{get:function(){return i},set:function(a){i=a}},yDomain1:{get:function(){return c},set:function(a){c=a}},yDomain2:{get:function(){return d},set:function(a){d=a}},noData:{get:function(){return j},set:function(a){j=a}},interpolate:{get:function(){return m},set:function(a){m=a}},tooltips:{get:function(){return B.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),B.enabled(!!b)}},tooltipContent:{get:function(){return B.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),B.contentGenerator(b)}},margin:{get:function(){return e},set:function(a){e.top=void 0!==a.top?a.top:e.top,e.right=void 0!==a.right?a.right:e.right,e.bottom=void 0!==a.bottom?a.bottom:e.bottom,e.left=void 0!==a.left?a.left:e.left}},color:{get:function(){return f},set:function(b){f=a.utils.getColor(b)}},x:{get:function(){return k},set:function(a){k=a,r.x(a),s.x(a),t.x(a),u.x(a),v.x(a),w.x(a)}},y:{get:function(){return l},set:function(a){l=a,r.y(a),s.y(a),v.y(a),w.y(a),t.y(a),u.y(a)}},useVoronoi:{get:function(){return n},set:function(a){n=a,r.useVoronoi(a),s.useVoronoi(a),v.useVoronoi(a),w.useVoronoi(a)}}}),a.utils.initOptions(b),b},a.models.ohlcBar=function(){"use strict";function b(y){return y.each(function(b){k=d3.select(this);var y=a.utils.availableWidth(h,k,g),A=a.utils.availableHeight(i,k,g);a.utils.initSVG(k);var B=y/b[0].values.length*.9;l.domain(c||d3.extent(b[0].values.map(n).concat(t))),v?l.range(e||[.5*y/b[0].values.length,y*(b[0].values.length-.5)/b[0].values.length]):l.range(e||[5+B/2,y-B/2-5]),m.domain(d||[d3.min(b[0].values.map(s).concat(u)),d3.max(b[0].values.map(r).concat(u))]).range(f||[A,0]),l.domain()[0]===l.domain()[1]&&(l.domain()[0]?l.domain([l.domain()[0]-.01*l.domain()[0],l.domain()[1]+.01*l.domain()[1]]):l.domain([-1,1])),m.domain()[0]===m.domain()[1]&&(m.domain()[0]?m.domain([m.domain()[0]+.01*m.domain()[0],m.domain()[1]-.01*m.domain()[1]]):m.domain([-1,1]));var C=d3.select(this).selectAll("g.nv-wrap.nv-ohlcBar").data([b[0].values]),D=C.enter().append("g").attr("class","nvd3 nv-wrap nv-ohlcBar"),E=D.append("defs"),F=D.append("g"),G=C.select("g");F.append("g").attr("class","nv-ticks"),C.attr("transform","translate("+g.left+","+g.top+")"),k.on("click",function(a,b){z.chartClick({data:a,index:b,pos:d3.event,id:j})}),E.append("clipPath").attr("id","nv-chart-clip-path-"+j).append("rect"),C.select("#nv-chart-clip-path-"+j+" rect").attr("width",y).attr("height",A),G.attr("clip-path",w?"url(#nv-chart-clip-path-"+j+")":"");var H=C.select(".nv-ticks").selectAll(".nv-tick").data(function(a){return a});H.exit().remove(),H.enter().append("path").attr("class",function(a,b,c){return(p(a,b)>q(a,b)?"nv-tick negative":"nv-tick positive")+" nv-tick-"+c+"-"+b}).attr("d",function(a,b){return"m0,0l0,"+(m(p(a,b))-m(r(a,b)))+"l"+-B/2+",0l"+B/2+",0l0,"+(m(s(a,b))-m(p(a,b)))+"l0,"+(m(q(a,b))-m(s(a,b)))+"l"+B/2+",0l"+-B/2+",0z"}).attr("transform",function(a,b){return"translate("+l(n(a,b))+","+m(r(a,b))+")"}).attr("fill",function(a,b){return x[0]}).attr("stroke",function(a,b){return x[0]}).attr("x",0).attr("y",function(a,b){return m(Math.max(0,o(a,b)))}).attr("height",function(a,b){return Math.abs(m(o(a,b))-m(0))}),H.attr("class",function(a,b,c){return(p(a,b)>q(a,b)?"nv-tick negative":"nv-tick positive")+" nv-tick-"+c+"-"+b}),d3.transition(H).attr("transform",function(a,b){return"translate("+l(n(a,b))+","+m(r(a,b))+")"}).attr("d",function(a,c){var d=y/b[0].values.length*.9;return"m0,0l0,"+(m(p(a,c))-m(r(a,c)))+"l"+-d/2+",0l"+d/2+",0l0,"+(m(s(a,c))-m(p(a,c)))+"l0,"+(m(q(a,c))-m(s(a,c)))+"l"+d/2+",0l"+-d/2+",0z"})}),b}var c,d,e,f,g={top:0,right:0,bottom:0,left:0},h=null,i=null,j=Math.floor(1e4*Math.random()),k=null,l=d3.scale.linear(),m=d3.scale.linear(),n=function(a){return a.x},o=function(a){return a.y},p=function(a){return a.open},q=function(a){return a.close},r=function(a){return a.high},s=function(a){return a.low;
+},t=[],u=[],v=!1,w=!0,x=a.utils.defaultColor(),y=!1,z=d3.dispatch("tooltipShow","tooltipHide","stateChange","changeState","renderEnd","chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove");return b.highlightPoint=function(a,c){b.clearHighlights(),k.select(".nv-ohlcBar .nv-tick-0-"+a).classed("hover",c)},b.clearHighlights=function(){k.select(".nv-ohlcBar .nv-tick.hover").classed("hover",!1)},b.dispatch=z,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return h},set:function(a){h=a}},height:{get:function(){return i},set:function(a){i=a}},xScale:{get:function(){return l},set:function(a){l=a}},yScale:{get:function(){return m},set:function(a){m=a}},xDomain:{get:function(){return c},set:function(a){c=a}},yDomain:{get:function(){return d},set:function(a){d=a}},xRange:{get:function(){return e},set:function(a){e=a}},yRange:{get:function(){return f},set:function(a){f=a}},forceX:{get:function(){return t},set:function(a){t=a}},forceY:{get:function(){return u},set:function(a){u=a}},padData:{get:function(){return v},set:function(a){v=a}},clipEdge:{get:function(){return w},set:function(a){w=a}},id:{get:function(){return j},set:function(a){j=a}},interactive:{get:function(){return y},set:function(a){y=a}},x:{get:function(){return n},set:function(a){n=a}},y:{get:function(){return o},set:function(a){o=a}},open:{get:function(){return p()},set:function(a){p=a}},close:{get:function(){return q()},set:function(a){q=a}},high:{get:function(){return r},set:function(a){r=a}},low:{get:function(){return s},set:function(a){s=a}},margin:{get:function(){return g},set:function(a){g.top=void 0!=a.top?a.top:g.top,g.right=void 0!=a.right?a.right:g.right,g.bottom=void 0!=a.bottom?a.bottom:g.bottom,g.left=void 0!=a.left?a.left:g.left}},color:{get:function(){return x},set:function(b){x=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.parallelCoordinates=function(){"use strict";function b(p){return p.each(function(b){function p(a){return F(h.map(function(b){if(isNaN(a[b])||isNaN(parseFloat(a[b]))){var c=g[b].domain(),d=g[b].range(),e=c[0]-(c[1]-c[0])/9;if(J.indexOf(b)<0){var h=d3.scale.linear().domain([e,c[1]]).range([x-12,d[1]]);g[b].brush.y(h),J.push(b)}return[f(b),g[b](e)]}return J.length>0?(D.style("display","inline"),E.style("display","inline")):(D.style("display","none"),E.style("display","none")),[f(b),g[b](a[b])]}))}function q(){var a=h.filter(function(a){return!g[a].brush.empty()}),b=a.map(function(a){return g[a].brush.extent()});k=[],a.forEach(function(a,c){k[c]={dimension:a,extent:b[c]}}),l=[],M.style("display",function(c){var d=a.every(function(a,d){return isNaN(c[a])&&b[d][0]==g[a].brush.y().domain()[0]?!0:b[d][0]<=c[a]&&c[a]<=b[d][1]});return d&&l.push(c),d?null:"none"}),o.brush({filters:k,active:l})}function r(a,b){m[a]=this.parentNode.__origin__=f(a),L.attr("visibility","hidden")}function s(a,b){m[a]=Math.min(w,Math.max(0,this.parentNode.__origin__+=d3.event.x)),M.attr("d",p),h.sort(function(a,b){return u(a)-u(b)}),f.domain(h),N.attr("transform",function(a){return"translate("+u(a)+")"})}function t(a,b){delete this.parentNode.__origin__,delete m[a],d3.select(this.parentNode).attr("transform","translate("+f(a)+")"),M.attr("d",p),L.attr("d",p).attr("visibility",null)}function u(a){var b=m[a];return null==b?f(a):b}var v=d3.select(this),w=a.utils.availableWidth(d,v,c),x=a.utils.availableHeight(e,v,c);a.utils.initSVG(v),l=b,f.rangePoints([0,w],1).domain(h);var y={};h.forEach(function(a){var c=d3.extent(b,function(b){return+b[a]});return y[a]=!1,void 0===c[0]&&(y[a]=!0,c[0]=0,c[1]=0),c[0]===c[1]&&(c[0]=c[0]-1,c[1]=c[1]+1),g[a]=d3.scale.linear().domain(c).range([.9*(x-12),0]),g[a].brush=d3.svg.brush().y(g[a]).on("brush",q),"name"!=a});var z=v.selectAll("g.nv-wrap.nv-parallelCoordinates").data([b]),A=z.enter().append("g").attr("class","nvd3 nv-wrap nv-parallelCoordinates"),B=A.append("g"),C=z.select("g");B.append("g").attr("class","nv-parallelCoordinates background"),B.append("g").attr("class","nv-parallelCoordinates foreground"),B.append("g").attr("class","nv-parallelCoordinates missingValuesline"),z.attr("transform","translate("+c.left+","+c.top+")");var D,E,F=d3.svg.line().interpolate("cardinal").tension(n),G=d3.svg.axis().orient("left"),H=d3.behavior.drag().on("dragstart",r).on("drag",s).on("dragend",t),I=f.range()[1]-f.range()[0],J=[],K=[0+I/2,x-12,w-I/2,x-12];D=z.select(".missingValuesline").selectAll("line").data([K]),D.enter().append("line"),D.exit().remove(),D.attr("x1",function(a){return a[0]}).attr("y1",function(a){return a[1]}).attr("x2",function(a){return a[2]}).attr("y2",function(a){return a[3]}),E=z.select(".missingValuesline").selectAll("text").data(["undefined values"]),E.append("text").data(["undefined values"]),E.enter().append("text"),E.exit().remove(),E.attr("y",x).attr("x",w-92-I/2).text(function(a){return a});var L=z.select(".background").selectAll("path").data(b);L.enter().append("path"),L.exit().remove(),L.attr("d",p);var M=z.select(".foreground").selectAll("path").data(b);M.enter().append("path"),M.exit().remove(),M.attr("d",p).attr("stroke",j),M.on("mouseover",function(a,b){d3.select(this).classed("hover",!0),o.elementMouseover({label:a.name,data:a.data,index:b,pos:[d3.mouse(this.parentNode)[0],d3.mouse(this.parentNode)[1]]})}),M.on("mouseout",function(a,b){d3.select(this).classed("hover",!1),o.elementMouseout({label:a.name,data:a.data,index:b})});var N=C.selectAll(".dimension").data(h),O=N.enter().append("g").attr("class","nv-parallelCoordinates dimension");O.append("g").attr("class","nv-parallelCoordinates nv-axis"),O.append("g").attr("class","nv-parallelCoordinates-brush"),O.append("text").attr("class","nv-parallelCoordinates nv-label"),N.attr("transform",function(a){return"translate("+f(a)+",0)"}),N.exit().remove(),N.select(".nv-label").style("cursor","move").attr("dy","-1em").attr("text-anchor","middle").text(String).on("mouseover",function(a,b){o.elementMouseover({dim:a,pos:[d3.mouse(this.parentNode.parentNode)[0],d3.mouse(this.parentNode.parentNode)[1]]})}).on("mouseout",function(a,b){o.elementMouseout({dim:a})}).call(H),N.select(".nv-axis").each(function(a,b){d3.select(this).call(G.scale(g[a]).tickFormat(d3.format(i[b])))}),N.select(".nv-parallelCoordinates-brush").each(function(a){d3.select(this).call(g[a].brush)}).selectAll("rect").attr("x",-8).attr("width",16)}),b}var c={top:30,right:0,bottom:10,left:0},d=null,e=null,f=d3.scale.ordinal(),g={},h=[],i=[],j=a.utils.defaultColor(),k=[],l=[],m=[],n=1,o=d3.dispatch("brush","elementMouseover","elementMouseout");return b.dispatch=o,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return d},set:function(a){d=a}},height:{get:function(){return e},set:function(a){e=a}},dimensionNames:{get:function(){return h},set:function(a){h=a}},dimensionFormats:{get:function(){return i},set:function(a){i=a}},lineTension:{get:function(){return n},set:function(a){n=a}},dimensions:{get:function(){return h},set:function(b){a.deprecated("dimensions","use dimensionNames instead"),h=b}},margin:{get:function(){return c},set:function(a){c.top=void 0!==a.top?a.top:c.top,c.right=void 0!==a.right?a.right:c.right,c.bottom=void 0!==a.bottom?a.bottom:c.bottom,c.left=void 0!==a.left?a.left:c.left}},color:{get:function(){return j},set:function(b){j=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.pie=function(){"use strict";function b(E){return D.reset(),E.each(function(b){function E(a,b){a.endAngle=isNaN(a.endAngle)?0:a.endAngle,a.startAngle=isNaN(a.startAngle)?0:a.startAngle,p||(a.innerRadius=0);var c=d3.interpolate(this._current,a);return this._current=c(0),function(a){return B[b](c(a))}}var F=d-c.left-c.right,G=e-c.top-c.bottom,H=Math.min(F,G)/2,I=[],J=[];if(i=d3.select(this),0===z.length)for(var K=H-H/5,L=y*H,M=0;M<b[0].length;M++)I.push(K),J.push(L);else I=z.map(function(a){return(a.outer-a.outer/5)*H}),J=z.map(function(a){return(a.inner-a.inner/5)*H}),y=d3.min(z.map(function(a){return a.inner-a.inner/5}));a.utils.initSVG(i);var N=i.selectAll(".nv-wrap.nv-pie").data(b),O=N.enter().append("g").attr("class","nvd3 nv-wrap nv-pie nv-chart-"+h),P=O.append("g"),Q=N.select("g"),R=P.append("g").attr("class","nv-pie");P.append("g").attr("class","nv-pieLabels"),N.attr("transform","translate("+c.left+","+c.top+")"),Q.select(".nv-pie").attr("transform","translate("+F/2+","+G/2+")"),Q.select(".nv-pieLabels").attr("transform","translate("+F/2+","+G/2+")"),i.on("click",function(a,b){A.chartClick({data:a,index:b,pos:d3.event,id:h})}),B=[],C=[];for(var M=0;M<b[0].length;M++){var S=d3.svg.arc().outerRadius(I[M]),T=d3.svg.arc().outerRadius(I[M]+5);u!==!1&&(S.startAngle(u),T.startAngle(u)),w!==!1&&(S.endAngle(w),T.endAngle(w)),p&&(S.innerRadius(J[M]),T.innerRadius(J[M])),S.cornerRadius&&x&&(S.cornerRadius(x),T.cornerRadius(x)),B.push(S),C.push(T)}var U=d3.layout.pie().sort(null).value(function(a){return a.disabled?0:g(a)});U.padAngle&&v&&U.padAngle(v),p&&q&&(R.append("text").attr("class","nv-pie-title"),N.select(".nv-pie-title").style("text-anchor","middle").text(function(a){return q}).style("font-size",Math.min(F,G)*y*2/(q.length+2)+"px").attr("dy","0.35em").attr("transform",function(a,b){return"translate(0, "+s+")"}));var V=N.select(".nv-pie").selectAll(".nv-slice").data(U),W=N.select(".nv-pieLabels").selectAll(".nv-label").data(U);V.exit().remove(),W.exit().remove();var X=V.enter().append("g");X.attr("class","nv-slice"),X.on("mouseover",function(a,b){d3.select(this).classed("hover",!0),r&&d3.select(this).select("path").transition().duration(70).attr("d",C[b]),A.elementMouseover({data:a.data,index:b,color:d3.select(this).style("fill")})}),X.on("mouseout",function(a,b){d3.select(this).classed("hover",!1),r&&d3.select(this).select("path").transition().duration(50).attr("d",B[b]),A.elementMouseout({data:a.data,index:b})}),X.on("mousemove",function(a,b){A.elementMousemove({data:a.data,index:b})}),X.on("click",function(a,b){A.elementClick({data:a.data,index:b,color:d3.select(this).style("fill")})}),X.on("dblclick",function(a,b){A.elementDblClick({data:a.data,index:b,color:d3.select(this).style("fill")})}),V.attr("fill",function(a,b){return j(a.data,b)}),V.attr("stroke",function(a,b){return j(a.data,b)});X.append("path").each(function(a){this._current=a});if(V.select("path").transition().attr("d",function(a,b){return B[b](a)}).attrTween("d",E),l){for(var Y=[],M=0;M<b[0].length;M++)Y.push(B[M]),m?p&&(Y[M]=d3.svg.arc().outerRadius(B[M].outerRadius()),u!==!1&&Y[M].startAngle(u),w!==!1&&Y[M].endAngle(w)):p||Y[M].innerRadius(0);W.enter().append("g").classed("nv-label",!0).each(function(a,b){var c=d3.select(this);c.attr("transform",function(a,b){if(t){a.outerRadius=I[b]+10,a.innerRadius=I[b]+15;var c=(a.startAngle+a.endAngle)/2*(180/Math.PI);return(a.startAngle+a.endAngle)/2<Math.PI?c-=90:c+=90,"translate("+Y[b].centroid(a)+") rotate("+c+")"}return a.outerRadius=H+10,a.innerRadius=H+15,"translate("+Y[b].centroid(a)+")"}),c.append("rect").style("stroke","#fff").style("fill","#fff").attr("rx",3).attr("ry",3),c.append("text").style("text-anchor",t?(a.startAngle+a.endAngle)/2<Math.PI?"start":"end":"middle").style("fill","#000")});var Z={},$=14,_=140,aa=function(a){return Math.floor(a[0]/_)*_+","+Math.floor(a[1]/$)*$};W.watchTransition(D,"pie labels").attr("transform",function(a,b){if(t){a.outerRadius=I[b]+10,a.innerRadius=I[b]+15;var c=(a.startAngle+a.endAngle)/2*(180/Math.PI);return(a.startAngle+a.endAngle)/2<Math.PI?c-=90:c+=90,"translate("+Y[b].centroid(a)+") rotate("+c+")"}a.outerRadius=H+10,a.innerRadius=H+15;var d=Y[b].centroid(a);if(a.value){var e=aa(d);Z[e]&&(d[1]-=$),Z[aa(d)]=!0}return"translate("+d+")"}),W.select(".nv-label text").style("text-anchor",function(a,b){return t?(a.startAngle+a.endAngle)/2<Math.PI?"start":"end":"middle"}).text(function(a,b){var c=(a.endAngle-a.startAngle)/(2*Math.PI),d="";if(!a.value||o>c)return"";if("function"==typeof n)d=n(a,b,{key:f(a.data),value:g(a.data),percent:k(c)});else switch(n){case"key":d=f(a.data);break;case"value":d=k(g(a.data));break;case"percent":d=d3.format("%")(c)}return d})}}),D.renderEnd("pie immediate"),b}var c={top:0,right:0,bottom:0,left:0},d=500,e=500,f=function(a){return a.x},g=function(a){return a.y},h=Math.floor(1e4*Math.random()),i=null,j=a.utils.defaultColor(),k=d3.format(",.2f"),l=!0,m=!1,n="key",o=.02,p=!1,q=!1,r=!0,s=0,t=!1,u=!1,v=!1,w=!1,x=0,y=.5,z=[],A=d3.dispatch("chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove","renderEnd"),B=[],C=[],D=a.utils.renderWatch(A);return b.dispatch=A,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{arcsRadius:{get:function(){return z},set:function(a){z=a}},width:{get:function(){return d},set:function(a){d=a}},height:{get:function(){return e},set:function(a){e=a}},showLabels:{get:function(){return l},set:function(a){l=a}},title:{get:function(){return q},set:function(a){q=a}},titleOffset:{get:function(){return s},set:function(a){s=a}},labelThreshold:{get:function(){return o},set:function(a){o=a}},valueFormat:{get:function(){return k},set:function(a){k=a}},x:{get:function(){return f},set:function(a){f=a}},id:{get:function(){return h},set:function(a){h=a}},endAngle:{get:function(){return w},set:function(a){w=a}},startAngle:{get:function(){return u},set:function(a){u=a}},padAngle:{get:function(){return v},set:function(a){v=a}},cornerRadius:{get:function(){return x},set:function(a){x=a}},donutRatio:{get:function(){return y},set:function(a){y=a}},labelsOutside:{get:function(){return m},set:function(a){m=a}},labelSunbeamLayout:{get:function(){return t},set:function(a){t=a}},donut:{get:function(){return p},set:function(a){p=a}},growOnHover:{get:function(){return r},set:function(a){r=a}},pieLabelsOutside:{get:function(){return m},set:function(b){m=b,a.deprecated("pieLabelsOutside","use labelsOutside instead")}},donutLabelsOutside:{get:function(){return m},set:function(b){m=b,a.deprecated("donutLabelsOutside","use labelsOutside instead")}},labelFormat:{get:function(){return k},set:function(b){k=b,a.deprecated("labelFormat","use valueFormat instead")}},margin:{get:function(){return c},set:function(a){c.top="undefined"!=typeof a.top?a.top:c.top,c.right="undefined"!=typeof a.right?a.right:c.right,c.bottom="undefined"!=typeof a.bottom?a.bottom:c.bottom,c.left="undefined"!=typeof a.left?a.left:c.left}},y:{get:function(){return g},set:function(a){g=d3.functor(a)}},color:{get:function(){return j},set:function(b){j=a.utils.getColor(b)}},labelType:{get:function(){return n},set:function(a){n=a||"key"}}}),a.utils.initOptions(b),b},a.models.pieChart=function(){"use strict";function b(e){return q.reset(),q.models(c),e.each(function(e){var k=d3.select(this);a.utils.initSVG(k);var n=a.utils.availableWidth(g,k,f),o=a.utils.availableHeight(h,k,f);if(b.update=function(){k.transition().call(b)},b.container=this,l.setter(s(e),b.update).getter(r(e)).update(),l.disabled=e.map(function(a){return!!a.disabled}),!m){var q;m={};for(q in l)l[q]instanceof Array?m[q]=l[q].slice(0):m[q]=l[q]}if(!e||!e.length)return a.utils.noData(b,k),b;k.selectAll(".nv-noData").remove();var t=k.selectAll("g.nv-wrap.nv-pieChart").data([e]),u=t.enter().append("g").attr("class","nvd3 nv-wrap nv-pieChart").append("g"),v=t.select("g");if(u.append("g").attr("class","nv-pieWrap"),u.append("g").attr("class","nv-legendWrap"),i)if("top"===j)d.width(n).key(c.x()),t.select(".nv-legendWrap").datum(e).call(d),f.top!=d.height()&&(f.top=d.height(),o=a.utils.availableHeight(h,k,f)),t.select(".nv-legendWrap").attr("transform","translate(0,"+-f.top+")");else if("right"===j){var w=a.models.legend().width();w>n/2&&(w=n/2),d.height(o).key(c.x()),d.width(w),n-=d.width(),t.select(".nv-legendWrap").datum(e).call(d).attr("transform","translate("+n+",0)")}t.attr("transform","translate("+f.left+","+f.top+")"),c.width(n).height(o);var x=v.select(".nv-pieWrap").datum([e]);d3.transition(x).call(c),d.dispatch.on("stateChange",function(a){for(var c in a)l[c]=a[c];p.stateChange(l),b.update()}),p.on("changeState",function(a){"undefined"!=typeof a.disabled&&(e.forEach(function(b,c){b.disabled=a.disabled[c]}),l.disabled=a.disabled),b.update()})}),q.renderEnd("pieChart immediate"),b}var c=a.models.pie(),d=a.models.legend(),e=a.models.tooltip(),f={top:30,right:20,bottom:20,left:20},g=null,h=null,i=!0,j="top",k=a.utils.defaultColor(),l=a.utils.state(),m=null,n=null,o=250,p=d3.dispatch("tooltipShow","tooltipHide","stateChange","changeState","renderEnd");e.headerEnabled(!1).duration(0).valueFormatter(function(a,b){return c.valueFormat()(a,b)});var q=a.utils.renderWatch(p),r=function(a){return function(){return{active:a.map(function(a){return!a.disabled})}}},s=function(a){return function(b){void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};return c.dispatch.on("elementMouseover.tooltip",function(a){a.series={key:b.x()(a.data),value:b.y()(a.data),color:a.color},e.data(a).hidden(!1)}),c.dispatch.on("elementMouseout.tooltip",function(a){e.hidden(!0)}),c.dispatch.on("elementMousemove.tooltip",function(a){e.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.legend=d,b.dispatch=p,b.pie=c,b.tooltip=e,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{noData:{get:function(){return n},set:function(a){n=a}},showLegend:{get:function(){return i},set:function(a){i=a}},legendPosition:{get:function(){return j},set:function(a){j=a}},defaultState:{get:function(){return m},set:function(a){m=a}},tooltips:{get:function(){return e.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),e.enabled(!!b)}},tooltipContent:{get:function(){return e.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),e.contentGenerator(b)}},color:{get:function(){return k},set:function(a){k=a,d.color(k),c.color(k)}},duration:{get:function(){return o},set:function(a){o=a,q.reset(o)}},margin:{get:function(){return f},set:function(a){f.top=void 0!==a.top?a.top:f.top,f.right=void 0!==a.right?a.right:f.right,f.bottom=void 0!==a.bottom?a.bottom:f.bottom,f.left=void 0!==a.left?a.left:f.left}}}),a.utils.inheritOptions(b,c),a.utils.initOptions(b),b},a.models.scatter=function(){"use strict";function b(N){return P.reset(),N.each(function(b){function N(){if(O=!1,!w)return!1;if(M===!0){var a=d3.merge(b.map(function(a,b){return a.values.map(function(a,c){var d=p(a,c),e=q(a,c);return[m(d)+1e-4*Math.random(),n(e)+1e-4*Math.random(),b,c,a]}).filter(function(a,b){return x(a[4],b)})}));if(0==a.length)return!1;a.length<3&&(a.push([m.range()[0]-20,n.range()[0]-20,null,null]),a.push([m.range()[1]+20,n.range()[1]+20,null,null]),a.push([m.range()[0]-20,n.range()[0]+20,null,null]),a.push([m.range()[1]+20,n.range()[1]-20,null,null]));var c=d3.geom.polygon([[-10,-10],[-10,i+10],[h+10,i+10],[h+10,-10]]),d=d3.geom.voronoi(a).map(function(b,d){return{data:c.clip(b),series:a[d][2],point:a[d][3]}});U.select(".nv-point-paths").selectAll("path").remove();var e=U.select(".nv-point-paths").selectAll("path").data(d),f=e.enter().append("svg:path").attr("d",function(a){return a&&a.data&&0!==a.data.length?"M"+a.data.join(",")+"Z":"M 0 0"}).attr("id",function(a,b){return"nv-path-"+b}).attr("clip-path",function(a,b){return"url(#nv-clip-"+b+")"});C&&f.style("fill",d3.rgb(230,230,230)).style("fill-opacity",.4).style("stroke-opacity",1).style("stroke",d3.rgb(200,200,200)),B&&(U.select(".nv-point-clips").selectAll("clipPath").remove(),U.select(".nv-point-clips").selectAll("clipPath").data(a).enter().append("svg:clipPath").attr("id",function(a,b){return"nv-clip-"+b}).append("svg:circle").attr("cx",function(a){return a[0]}).attr("cy",function(a){return a[1]}).attr("r",D));var k=function(a,c){if(O)return 0;var d=b[a.series];if(void 0!==d){var e=d.values[a.point];e.color=j(d,a.series),e.x=p(e),e.y=q(e);var f=l.node().getBoundingClientRect(),h=window.pageYOffset||document.documentElement.scrollTop,i=window.pageXOffset||document.documentElement.scrollLeft,k={left:m(p(e,a.point))+f.left+i+g.left+10,top:n(q(e,a.point))+f.top+h+g.top+10};c({point:e,series:d,pos:k,seriesIndex:a.series,pointIndex:a.point})}};e.on("click",function(a){k(a,L.elementClick)}).on("dblclick",function(a){k(a,L.elementDblClick)}).on("mouseover",function(a){k(a,L.elementMouseover)}).on("mouseout",function(a,b){k(a,L.elementMouseout)})}else U.select(".nv-groups").selectAll(".nv-group").selectAll(".nv-point").on("click",function(a,c){if(O||!b[a.series])return 0;var d=b[a.series],e=d.values[c];L.elementClick({point:e,series:d,pos:[m(p(e,c))+g.left,n(q(e,c))+g.top],seriesIndex:a.series,pointIndex:c})}).on("dblclick",function(a,c){if(O||!b[a.series])return 0;var d=b[a.series],e=d.values[c];L.elementDblClick({point:e,series:d,pos:[m(p(e,c))+g.left,n(q(e,c))+g.top],seriesIndex:a.series,pointIndex:c})}).on("mouseover",function(a,c){if(O||!b[a.series])return 0;var d=b[a.series],e=d.values[c];L.elementMouseover({point:e,series:d,pos:[m(p(e,c))+g.left,n(q(e,c))+g.top],seriesIndex:a.series,pointIndex:c,color:j(a,c)})}).on("mouseout",function(a,c){if(O||!b[a.series])return 0;var d=b[a.series],e=d.values[c];L.elementMouseout({point:e,series:d,seriesIndex:a.series,pointIndex:c,color:j(a,c)})})}l=d3.select(this);var R=a.utils.availableWidth(h,l,g),S=a.utils.availableHeight(i,l,g);a.utils.initSVG(l),b.forEach(function(a,b){a.values.forEach(function(a){a.series=b})});var T=E&&F&&I?[]:d3.merge(b.map(function(a){return a.values.map(function(a,b){return{x:p(a,b),y:q(a,b),size:r(a,b)}})}));m.domain(E||d3.extent(T.map(function(a){return a.x}).concat(t))),y&&b[0]?m.range(G||[(R*z+R)/(2*b[0].values.length),R-R*(1+z)/(2*b[0].values.length)]):m.range(G||[0,R]),n.domain(F||d3.extent(T.map(function(a){return a.y}).concat(u))).range(H||[S,0]),o.domain(I||d3.extent(T.map(function(a){return a.size}).concat(v))).range(J||Q),K=m.domain()[0]===m.domain()[1]||n.domain()[0]===n.domain()[1],m.domain()[0]===m.domain()[1]&&(m.domain()[0]?m.domain([m.domain()[0]-.01*m.domain()[0],m.domain()[1]+.01*m.domain()[1]]):m.domain([-1,1])),n.domain()[0]===n.domain()[1]&&(n.domain()[0]?n.domain([n.domain()[0]-.01*n.domain()[0],n.domain()[1]+.01*n.domain()[1]]):n.domain([-1,1])),isNaN(m.domain()[0])&&m.domain([-1,1]),isNaN(n.domain()[0])&&n.domain([-1,1]),c=c||m,d=d||n,e=e||o;var U=l.selectAll("g.nv-wrap.nv-scatter").data([b]),V=U.enter().append("g").attr("class","nvd3 nv-wrap nv-scatter nv-chart-"+k),W=V.append("defs"),X=V.append("g"),Y=U.select("g");U.classed("nv-single-point",K),X.append("g").attr("class","nv-groups"),X.append("g").attr("class","nv-point-paths"),V.append("g").attr("class","nv-point-clips"),U.attr("transform","translate("+g.left+","+g.top+")"),W.append("clipPath").attr("id","nv-edge-clip-"+k).append("rect"),U.select("#nv-edge-clip-"+k+" rect").attr("width",R).attr("height",S>0?S:0),Y.attr("clip-path",A?"url(#nv-edge-clip-"+k+")":""),O=!0;var Z=U.select(".nv-groups").selectAll(".nv-group").data(function(a){return a},function(a){return a.key});Z.enter().append("g").style("stroke-opacity",1e-6).style("fill-opacity",1e-6),Z.exit().remove(),Z.attr("class",function(a,b){return"nv-group nv-series-"+b}).classed("hover",function(a){return a.hover}),Z.watchTransition(P,"scatter: groups").style("fill",function(a,b){return j(a,b)}).style("stroke",function(a,b){return j(a,b)}).style("stroke-opacity",1).style("fill-opacity",.5);var $=Z.selectAll("path.nv-point").data(function(a){return a.values.map(function(a,b){return[a,b]}).filter(function(a,b){return x(a[0],b)})});$.enter().append("path").style("fill",function(a){return a.color}).style("stroke",function(a){return a.color}).attr("transform",function(a){return"translate("+c(p(a[0],a[1]))+","+d(q(a[0],a[1]))+")"}).attr("d",a.utils.symbol().type(function(a){return s(a[0])}).size(function(a){return o(r(a[0],a[1]))})),$.exit().remove(),Z.exit().selectAll("path.nv-point").watchTransition(P,"scatter exit").attr("transform",function(a){return"translate("+m(p(a[0],a[1]))+","+n(q(a[0],a[1]))+")"}).remove(),$.each(function(a){d3.select(this).classed("nv-point",!0).classed("nv-point-"+a[1],!0).classed("nv-noninteractive",!w).classed("hover",!1)}),$.watchTransition(P,"scatter points").attr("transform",function(a){return"translate("+m(p(a[0],a[1]))+","+n(q(a[0],a[1]))+")"}).attr("d",a.utils.symbol().type(function(a){return s(a[0])}).size(function(a){return o(r(a[0],a[1]))})),clearTimeout(f),f=setTimeout(N,300),c=m.copy(),d=n.copy(),e=o.copy()}),P.renderEnd("scatter immediate"),b}var c,d,e,f,g={top:0,right:0,bottom:0,left:0},h=null,i=null,j=a.utils.defaultColor(),k=Math.floor(1e5*Math.random()),l=null,m=d3.scale.linear(),n=d3.scale.linear(),o=d3.scale.linear(),p=function(a){return a.x},q=function(a){return a.y},r=function(a){return a.size||1},s=function(a){return a.shape||"circle"},t=[],u=[],v=[],w=!0,x=function(a){return!a.notActive},y=!1,z=.1,A=!1,B=!0,C=!1,D=function(){return 25},E=null,F=null,G=null,H=null,I=null,J=null,K=!1,L=d3.dispatch("elementClick","elementDblClick","elementMouseover","elementMouseout","renderEnd"),M=!0,N=250,O=!1,P=a.utils.renderWatch(L,N),Q=[16,256];return b.dispatch=L,b.options=a.utils.optionsFunc.bind(b),b._calls=new function(){this.clearHighlights=function(){return a.dom.write(function(){l.selectAll(".nv-point.hover").classed("hover",!1)}),null},this.highlightPoint=function(b,c,d){a.dom.write(function(){l.select(" .nv-series-"+b+" .nv-point-"+c).classed("hover",d)})}},L.on("elementMouseover.point",function(a){w&&b._calls.highlightPoint(a.seriesIndex,a.pointIndex,!0)}),L.on("elementMouseout.point",function(a){w&&b._calls.highlightPoint(a.seriesIndex,a.pointIndex,!1)}),b._options=Object.create({},{width:{get:function(){return h},set:function(a){h=a}},height:{get:function(){return i},set:function(a){i=a}},xScale:{get:function(){return m},set:function(a){m=a}},yScale:{get:function(){return n},set:function(a){n=a}},pointScale:{get:function(){return o},set:function(a){o=a}},xDomain:{get:function(){return E},set:function(a){E=a}},yDomain:{get:function(){return F},set:function(a){F=a}},pointDomain:{get:function(){return I},set:function(a){I=a}},xRange:{get:function(){return G},set:function(a){G=a}},yRange:{get:function(){return H},set:function(a){H=a}},pointRange:{get:function(){return J},set:function(a){J=a}},forceX:{get:function(){return t},set:function(a){t=a}},forceY:{get:function(){return u},set:function(a){u=a}},forcePoint:{get:function(){return v},set:function(a){v=a}},interactive:{get:function(){return w},set:function(a){w=a}},pointActive:{get:function(){return x},set:function(a){x=a}},padDataOuter:{get:function(){return z},set:function(a){z=a}},padData:{get:function(){return y},set:function(a){y=a}},clipEdge:{get:function(){return A},set:function(a){A=a}},clipVoronoi:{get:function(){return B},set:function(a){B=a}},clipRadius:{get:function(){return D},set:function(a){D=a}},showVoronoi:{get:function(){return C},set:function(a){C=a}},id:{get:function(){return k},set:function(a){k=a}},x:{get:function(){return p},set:function(a){p=d3.functor(a)}},y:{get:function(){return q},set:function(a){q=d3.functor(a)}},pointSize:{get:function(){return r},set:function(a){r=d3.functor(a)}},pointShape:{get:function(){return s},set:function(a){s=d3.functor(a)}},margin:{get:function(){return g},set:function(a){g.top=void 0!==a.top?a.top:g.top,g.right=void 0!==a.right?a.right:g.right,g.bottom=void 0!==a.bottom?a.bottom:g.bottom,g.left=void 0!==a.left?a.left:g.left}},duration:{get:function(){return N},set:function(a){N=a,P.reset(N)}},color:{get:function(){return j},set:function(b){j=a.utils.getColor(b)}},useVoronoi:{get:function(){return M},set:function(a){M=a,M===!1&&(B=!1)}}}),a.utils.initOptions(b),b},a.models.scatterChart=function(){"use strict";function b(z){return D.reset(),D.models(c),t&&D.models(d),u&&D.models(e),q&&D.models(g),r&&D.models(h),z.each(function(z){m=d3.select(this),a.utils.initSVG(m);var G=a.utils.availableWidth(k,m,j),H=a.utils.availableHeight(l,m,j);if(b.update=function(){0===A?m.call(b):m.transition().duration(A).call(b)},b.container=this,w.setter(F(z),b.update).getter(E(z)).update(),w.disabled=z.map(function(a){return!!a.disabled}),!x){var I;x={};for(I in w)w[I]instanceof Array?x[I]=w[I].slice(0):x[I]=w[I]}if(!(z&&z.length&&z.filter(function(a){return a.values.length}).length))return a.utils.noData(b,m),D.renderEnd("scatter immediate"),b;m.selectAll(".nv-noData").remove(),o=c.xScale(),p=c.yScale();var J=m.selectAll("g.nv-wrap.nv-scatterChart").data([z]),K=J.enter().append("g").attr("class","nvd3 nv-wrap nv-scatterChart nv-chart-"+c.id()),L=K.append("g"),M=J.select("g");if(L.append("rect").attr("class","nvd3 nv-background").style("pointer-events","none"),L.append("g").attr("class","nv-x nv-axis"),L.append("g").attr("class","nv-y nv-axis"),L.append("g").attr("class","nv-scatterWrap"),L.append("g").attr("class","nv-regressionLinesWrap"),L.append("g").attr("class","nv-distWrap"),L.append("g").attr("class","nv-legendWrap"),v&&M.select(".nv-y.nv-axis").attr("transform","translate("+G+",0)"),s){var N=G;f.width(N),J.select(".nv-legendWrap").datum(z).call(f),j.top!=f.height()&&(j.top=f.height(),H=a.utils.availableHeight(l,m,j)),J.select(".nv-legendWrap").attr("transform","translate(0,"+-j.top+")")}J.attr("transform","translate("+j.left+","+j.top+")"),c.width(G).height(H).color(z.map(function(a,b){return a.color||n(a,b)}).filter(function(a,b){return!z[b].disabled})),J.select(".nv-scatterWrap").datum(z.filter(function(a){return!a.disabled})).call(c),J.select(".nv-regressionLinesWrap").attr("clip-path","url(#nv-edge-clip-"+c.id()+")");var O=J.select(".nv-regressionLinesWrap").selectAll(".nv-regLines").data(function(a){return a});O.enter().append("g").attr("class","nv-regLines");var P=O.selectAll(".nv-regLine").data(function(a){return[a]});P.enter().append("line").attr("class","nv-regLine").style("stroke-opacity",0),P.filter(function(a){return a.intercept&&a.slope}).watchTransition(D,"scatterPlusLineChart: regline").attr("x1",o.range()[0]).attr("x2",o.range()[1]).attr("y1",function(a,b){return p(o.domain()[0]*a.slope+a.intercept)}).attr("y2",function(a,b){return p(o.domain()[1]*a.slope+a.intercept)}).style("stroke",function(a,b,c){return n(a,c)}).style("stroke-opacity",function(a,b){return a.disabled||"undefined"==typeof a.slope||"undefined"==typeof a.intercept?0:1}),t&&(d.scale(o)._ticks(a.utils.calcTicksX(G/100,z)).tickSize(-H,0),M.select(".nv-x.nv-axis").attr("transform","translate(0,"+p.range()[0]+")").call(d)),u&&(e.scale(p)._ticks(a.utils.calcTicksY(H/36,z)).tickSize(-G,0),M.select(".nv-y.nv-axis").call(e)),q&&(g.getData(c.x()).scale(o).width(G).color(z.map(function(a,b){return a.color||n(a,b)}).filter(function(a,b){return!z[b].disabled})),L.select(".nv-distWrap").append("g").attr("class","nv-distributionX"),M.select(".nv-distributionX").attr("transform","translate(0,"+p.range()[0]+")").datum(z.filter(function(a){return!a.disabled})).call(g)),r&&(h.getData(c.y()).scale(p).width(H).color(z.map(function(a,b){return a.color||n(a,b)}).filter(function(a,b){return!z[b].disabled})),L.select(".nv-distWrap").append("g").attr("class","nv-distributionY"),M.select(".nv-distributionY").attr("transform","translate("+(v?G:-h.size())+",0)").datum(z.filter(function(a){return!a.disabled})).call(h)),f.dispatch.on("stateChange",function(a){for(var c in a)w[c]=a[c];y.stateChange(w),b.update()}),y.on("changeState",function(a){"undefined"!=typeof a.disabled&&(z.forEach(function(b,c){b.disabled=a.disabled[c]}),w.disabled=a.disabled),b.update()}),c.dispatch.on("elementMouseout.tooltip",function(a){i.hidden(!0),m.select(".nv-chart-"+c.id()+" .nv-series-"+a.seriesIndex+" .nv-distx-"+a.pointIndex).attr("y1",0),m.select(".nv-chart-"+c.id()+" .nv-series-"+a.seriesIndex+" .nv-disty-"+a.pointIndex).attr("x2",h.size())}),c.dispatch.on("elementMouseover.tooltip",function(a){m.select(".nv-series-"+a.seriesIndex+" .nv-distx-"+a.pointIndex).attr("y1",a.pos.top-H-j.top),m.select(".nv-series-"+a.seriesIndex+" .nv-disty-"+a.pointIndex).attr("x2",a.pos.left+g.size()-j.left),i.position(a.pos).data(a).hidden(!1);
+}),B=o.copy(),C=p.copy()}),D.renderEnd("scatter with line immediate"),b}var c=a.models.scatter(),d=a.models.axis(),e=a.models.axis(),f=a.models.legend(),g=a.models.distribution(),h=a.models.distribution(),i=a.models.tooltip(),j={top:30,right:20,bottom:50,left:75},k=null,l=null,m=null,n=a.utils.defaultColor(),o=c.xScale(),p=c.yScale(),q=!1,r=!1,s=!0,t=!0,u=!0,v=!1,w=a.utils.state(),x=null,y=d3.dispatch("stateChange","changeState","renderEnd"),z=null,A=250;c.xScale(o).yScale(p),d.orient("bottom").tickPadding(10),e.orient(v?"right":"left").tickPadding(10),g.axis("x"),h.axis("y"),i.headerFormatter(function(a,b){return d.tickFormat()(a,b)}).valueFormatter(function(a,b){return e.tickFormat()(a,b)});var B,C,D=a.utils.renderWatch(y,A),E=function(a){return function(){return{active:a.map(function(a){return!a.disabled})}}},F=function(a){return function(b){void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};return b.dispatch=y,b.scatter=c,b.legend=f,b.xAxis=d,b.yAxis=e,b.distX=g,b.distY=h,b.tooltip=i,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return k},set:function(a){k=a}},height:{get:function(){return l},set:function(a){l=a}},container:{get:function(){return m},set:function(a){m=a}},showDistX:{get:function(){return q},set:function(a){q=a}},showDistY:{get:function(){return r},set:function(a){r=a}},showLegend:{get:function(){return s},set:function(a){s=a}},showXAxis:{get:function(){return t},set:function(a){t=a}},showYAxis:{get:function(){return u},set:function(a){u=a}},defaultState:{get:function(){return x},set:function(a){x=a}},noData:{get:function(){return z},set:function(a){z=a}},duration:{get:function(){return A},set:function(a){A=a}},tooltips:{get:function(){return i.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),i.enabled(!!b)}},tooltipContent:{get:function(){return i.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),i.contentGenerator(b)}},tooltipXContent:{get:function(){return i.contentGenerator()},set:function(b){a.deprecated("tooltipContent","This option is removed, put values into main tooltip.")}},tooltipYContent:{get:function(){return i.contentGenerator()},set:function(b){a.deprecated("tooltipContent","This option is removed, put values into main tooltip.")}},margin:{get:function(){return j},set:function(a){j.top=void 0!==a.top?a.top:j.top,j.right=void 0!==a.right?a.right:j.right,j.bottom=void 0!==a.bottom?a.bottom:j.bottom,j.left=void 0!==a.left?a.left:j.left}},rightAlignYAxis:{get:function(){return v},set:function(a){v=a,e.orient(a?"right":"left")}},color:{get:function(){return n},set:function(b){n=a.utils.getColor(b),f.color(n),g.color(n),h.color(n)}}}),a.utils.inheritOptions(b,c),a.utils.initOptions(b),b},a.models.sparkline=function(){"use strict";function b(k){return k.each(function(b){var k=h-g.left-g.right,q=i-g.top-g.bottom;j=d3.select(this),a.utils.initSVG(j),l.domain(c||d3.extent(b,n)).range(e||[0,k]),m.domain(d||d3.extent(b,o)).range(f||[q,0]);var r=j.selectAll("g.nv-wrap.nv-sparkline").data([b]),s=r.enter().append("g").attr("class","nvd3 nv-wrap nv-sparkline");s.append("g"),r.select("g");r.attr("transform","translate("+g.left+","+g.top+")");var t=r.selectAll("path").data(function(a){return[a]});t.enter().append("path"),t.exit().remove(),t.style("stroke",function(a,b){return a.color||p(a,b)}).attr("d",d3.svg.line().x(function(a,b){return l(n(a,b))}).y(function(a,b){return m(o(a,b))}));var u=r.selectAll("circle.nv-point").data(function(a){function b(b){if(-1!=b){var c=a[b];return c.pointIndex=b,c}return null}var c=a.map(function(a,b){return o(a,b)}),d=b(c.lastIndexOf(m.domain()[1])),e=b(c.indexOf(m.domain()[0])),f=b(c.length-1);return[e,d,f].filter(function(a){return null!=a})});u.enter().append("circle"),u.exit().remove(),u.attr("cx",function(a,b){return l(n(a,a.pointIndex))}).attr("cy",function(a,b){return m(o(a,a.pointIndex))}).attr("r",2).attr("class",function(a,b){return n(a,a.pointIndex)==l.domain()[1]?"nv-point nv-currentValue":o(a,a.pointIndex)==m.domain()[0]?"nv-point nv-minValue":"nv-point nv-maxValue"})}),b}var c,d,e,f,g={top:2,right:0,bottom:2,left:0},h=400,i=32,j=null,k=!0,l=d3.scale.linear(),m=d3.scale.linear(),n=function(a){return a.x},o=function(a){return a.y},p=a.utils.getColor(["#000"]);return b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return h},set:function(a){h=a}},height:{get:function(){return i},set:function(a){i=a}},xDomain:{get:function(){return c},set:function(a){c=a}},yDomain:{get:function(){return d},set:function(a){d=a}},xRange:{get:function(){return e},set:function(a){e=a}},yRange:{get:function(){return f},set:function(a){f=a}},xScale:{get:function(){return l},set:function(a){l=a}},yScale:{get:function(){return m},set:function(a){m=a}},animate:{get:function(){return k},set:function(a){k=a}},x:{get:function(){return n},set:function(a){n=d3.functor(a)}},y:{get:function(){return o},set:function(a){o=d3.functor(a)}},margin:{get:function(){return g},set:function(a){g.top=void 0!==a.top?a.top:g.top,g.right=void 0!==a.right?a.right:g.right,g.bottom=void 0!==a.bottom?a.bottom:g.bottom,g.left=void 0!==a.left?a.left:g.left}},color:{get:function(){return p},set:function(b){p=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.sparklinePlus=function(){"use strict";function b(p){return p.each(function(q){function r(){if(!j){var a=A.selectAll(".nv-hoverValue").data(i),b=a.enter().append("g").attr("class","nv-hoverValue").style("stroke-opacity",0).style("fill-opacity",0);a.exit().transition().duration(250).style("stroke-opacity",0).style("fill-opacity",0).remove(),a.attr("transform",function(a){return"translate("+c(e.x()(q[a],a))+",0)"}).transition().duration(250).style("stroke-opacity",1).style("fill-opacity",1),i.length&&(b.append("line").attr("x1",0).attr("y1",-f.top).attr("x2",0).attr("y2",v),b.append("text").attr("class","nv-xValue").attr("x",-6).attr("y",-f.top).attr("text-anchor","end").attr("dy",".9em"),A.select(".nv-hoverValue .nv-xValue").text(k(e.x()(q[i[0]],i[0]))),b.append("text").attr("class","nv-yValue").attr("x",6).attr("y",-f.top).attr("text-anchor","start").attr("dy",".9em"),A.select(".nv-hoverValue .nv-yValue").text(l(e.y()(q[i[0]],i[0]))))}}function s(){function a(a,b){for(var c=Math.abs(e.x()(a[0],0)-b),d=0,f=0;f<a.length;f++)Math.abs(e.x()(a[f],f)-b)<c&&(c=Math.abs(e.x()(a[f],f)-b),d=f);return d}if(!j){var b=d3.mouse(this)[0]-f.left;i=[a(q,Math.round(c.invert(b)))],r()}}var t=d3.select(this);a.utils.initSVG(t);var u=a.utils.availableWidth(g,t,f),v=a.utils.availableHeight(h,t,f);if(b.update=function(){b(p)},b.container=this,!q||!q.length)return a.utils.noData(b,t),b;t.selectAll(".nv-noData").remove();var w=e.y()(q[q.length-1],q.length-1);c=e.xScale(),d=e.yScale();var x=t.selectAll("g.nv-wrap.nv-sparklineplus").data([q]),y=x.enter().append("g").attr("class","nvd3 nv-wrap nv-sparklineplus"),z=y.append("g"),A=x.select("g");z.append("g").attr("class","nv-sparklineWrap"),z.append("g").attr("class","nv-valueWrap"),z.append("g").attr("class","nv-hoverArea"),x.attr("transform","translate("+f.left+","+f.top+")");var B=A.select(".nv-sparklineWrap");if(e.width(u).height(v),B.call(e),m){var C=A.select(".nv-valueWrap"),D=C.selectAll(".nv-currentValue").data([w]);D.enter().append("text").attr("class","nv-currentValue").attr("dx",o?-8:8).attr("dy",".9em").style("text-anchor",o?"end":"start"),D.attr("x",u+(o?f.right:0)).attr("y",n?function(a){return d(a)}:0).style("fill",e.color()(q[q.length-1],q.length-1)).text(l(w))}z.select(".nv-hoverArea").append("rect").on("mousemove",s).on("click",function(){j=!j}).on("mouseout",function(){i=[],r()}),A.select(".nv-hoverArea rect").attr("transform",function(a){return"translate("+-f.left+","+-f.top+")"}).attr("width",u+f.left+f.right).attr("height",v+f.top)}),b}var c,d,e=a.models.sparkline(),f={top:15,right:100,bottom:10,left:50},g=null,h=null,i=[],j=!1,k=d3.format(",r"),l=d3.format(",.2f"),m=!0,n=!0,o=!1,p=null;return b.sparkline=e,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return g},set:function(a){g=a}},height:{get:function(){return h},set:function(a){h=a}},xTickFormat:{get:function(){return k},set:function(a){k=a}},yTickFormat:{get:function(){return l},set:function(a){l=a}},showLastValue:{get:function(){return m},set:function(a){m=a}},alignValue:{get:function(){return n},set:function(a){n=a}},rightAlignValue:{get:function(){return o},set:function(a){o=a}},noData:{get:function(){return p},set:function(a){p=a}},margin:{get:function(){return f},set:function(a){f.top=void 0!==a.top?a.top:f.top,f.right=void 0!==a.right?a.right:f.right,f.bottom=void 0!==a.bottom?a.bottom:f.bottom,f.left=void 0!==a.left?a.left:f.left}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.stackedArea=function(){"use strict";function b(m){return u.reset(),u.models(r),m.each(function(m){var s=f-e.left-e.right,v=g-e.top-e.bottom;j=d3.select(this),a.utils.initSVG(j),c=r.xScale(),d=r.yScale();var w=m;m.forEach(function(a,b){a.seriesIndex=b,a.values=a.values.map(function(a,c){return a.index=c,a.seriesIndex=b,a})});var x=m.filter(function(a){return!a.disabled});m=d3.layout.stack().order(o).offset(n).values(function(a){return a.values}).x(k).y(l).out(function(a,b,c){a.display={y:c,y0:b}})(x);var y=j.selectAll("g.nv-wrap.nv-stackedarea").data([m]),z=y.enter().append("g").attr("class","nvd3 nv-wrap nv-stackedarea"),A=z.append("defs"),B=z.append("g"),C=y.select("g");B.append("g").attr("class","nv-areaWrap"),B.append("g").attr("class","nv-scatterWrap"),y.attr("transform","translate("+e.left+","+e.top+")"),0==r.forceY().length&&r.forceY().push(0),r.width(s).height(v).x(k).y(function(a){return a.display.y+a.display.y0}).forceY([0]).color(m.map(function(a,b){return a.color||h(a,a.seriesIndex)}));var D=C.select(".nv-scatterWrap").datum(m);D.call(r),A.append("clipPath").attr("id","nv-edge-clip-"+i).append("rect"),y.select("#nv-edge-clip-"+i+" rect").attr("width",s).attr("height",v),C.attr("clip-path",q?"url(#nv-edge-clip-"+i+")":"");var E=d3.svg.area().x(function(a,b){return c(k(a,b))}).y0(function(a){return d(a.display.y0)}).y1(function(a){return d(a.display.y+a.display.y0)}).interpolate(p),F=d3.svg.area().x(function(a,b){return c(k(a,b))}).y0(function(a){return d(a.display.y0)}).y1(function(a){return d(a.display.y0)}),G=C.select(".nv-areaWrap").selectAll("path.nv-area").data(function(a){return a});G.enter().append("path").attr("class",function(a,b){return"nv-area nv-area-"+b}).attr("d",function(a,b){return F(a.values,a.seriesIndex)}).on("mouseover",function(a,b){d3.select(this).classed("hover",!0),t.areaMouseover({point:a,series:a.key,pos:[d3.event.pageX,d3.event.pageY],seriesIndex:a.seriesIndex})}).on("mouseout",function(a,b){d3.select(this).classed("hover",!1),t.areaMouseout({point:a,series:a.key,pos:[d3.event.pageX,d3.event.pageY],seriesIndex:a.seriesIndex})}).on("click",function(a,b){d3.select(this).classed("hover",!1),t.areaClick({point:a,series:a.key,pos:[d3.event.pageX,d3.event.pageY],seriesIndex:a.seriesIndex})}),G.exit().remove(),G.style("fill",function(a,b){return a.color||h(a,a.seriesIndex)}).style("stroke",function(a,b){return a.color||h(a,a.seriesIndex)}),G.watchTransition(u,"stackedArea path").attr("d",function(a,b){return E(a.values,b)}),r.dispatch.on("elementMouseover.area",function(a){C.select(".nv-chart-"+i+" .nv-area-"+a.seriesIndex).classed("hover",!0)}),r.dispatch.on("elementMouseout.area",function(a){C.select(".nv-chart-"+i+" .nv-area-"+a.seriesIndex).classed("hover",!1)}),b.d3_stackedOffset_stackPercent=function(a){var b,c,d,e=a.length,f=a[0].length,g=[];for(c=0;f>c;++c){for(b=0,d=0;b<w.length;b++)d+=l(w[b].values[c]);if(d)for(b=0;e>b;b++)a[b][c][1]/=d;else for(b=0;e>b;b++)a[b][c][1]=0}for(c=0;f>c;++c)g[c]=0;return g}}),u.renderEnd("stackedArea immediate"),b}var c,d,e={top:0,right:0,bottom:0,left:0},f=960,g=500,h=a.utils.defaultColor(),i=Math.floor(1e5*Math.random()),j=null,k=function(a){return a.x},l=function(a){return a.y},m="stack",n="zero",o="default",p="linear",q=!1,r=a.models.scatter(),s=250,t=d3.dispatch("areaClick","areaMouseover","areaMouseout","renderEnd","elementClick","elementMouseover","elementMouseout");r.pointSize(2.2).pointDomain([2.2,2.2]);var u=a.utils.renderWatch(t,s);return b.dispatch=t,b.scatter=r,r.dispatch.on("elementClick",function(){t.elementClick.apply(this,arguments)}),r.dispatch.on("elementMouseover",function(){t.elementMouseover.apply(this,arguments)}),r.dispatch.on("elementMouseout",function(){t.elementMouseout.apply(this,arguments)}),b.interpolate=function(a){return arguments.length?(p=a,b):p},b.duration=function(a){return arguments.length?(s=a,u.reset(s),r.duration(s),b):s},b.dispatch=t,b.scatter=r,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return f},set:function(a){f=a}},height:{get:function(){return g},set:function(a){g=a}},clipEdge:{get:function(){return q},set:function(a){q=a}},offset:{get:function(){return n},set:function(a){n=a}},order:{get:function(){return o},set:function(a){o=a}},interpolate:{get:function(){return p},set:function(a){p=a}},x:{get:function(){return k},set:function(a){k=d3.functor(a)}},y:{get:function(){return l},set:function(a){l=d3.functor(a)}},margin:{get:function(){return e},set:function(a){e.top=void 0!==a.top?a.top:e.top,e.right=void 0!==a.right?a.right:e.right,e.bottom=void 0!==a.bottom?a.bottom:e.bottom,e.left=void 0!==a.left?a.left:e.left}},color:{get:function(){return h},set:function(b){h=a.utils.getColor(b)}},style:{get:function(){return m},set:function(a){switch(m=a){case"stack":b.offset("zero"),b.order("default");break;case"stream":b.offset("wiggle"),b.order("inside-out");break;case"stream-center":b.offset("silhouette"),b.order("inside-out");break;case"expand":b.offset("expand"),b.order("default");break;case"stack_percent":b.offset(b.d3_stackedOffset_stackPercent),b.order("default")}}},duration:{get:function(){return s},set:function(a){s=a,u.reset(s),r.duration(s)}}}),a.utils.inheritOptions(b,r),a.utils.initOptions(b),b},a.models.stackedAreaChart=function(){"use strict";function b(k){return F.reset(),F.models(e),r&&F.models(f),s&&F.models(g),k.each(function(k){var x=d3.select(this),F=this;a.utils.initSVG(x);var K=a.utils.availableWidth(m,x,l),L=a.utils.availableHeight(n,x,l);if(b.update=function(){x.transition().duration(C).call(b)},b.container=this,v.setter(I(k),b.update).getter(H(k)).update(),v.disabled=k.map(function(a){return!!a.disabled}),!w){var M;w={};for(M in v)v[M]instanceof Array?w[M]=v[M].slice(0):w[M]=v[M]}if(!(k&&k.length&&k.filter(function(a){return a.values.length}).length))return a.utils.noData(b,x),b;x.selectAll(".nv-noData").remove(),c=e.xScale(),d=e.yScale();var N=x.selectAll("g.nv-wrap.nv-stackedAreaChart").data([k]),O=N.enter().append("g").attr("class","nvd3 nv-wrap nv-stackedAreaChart").append("g"),P=N.select("g");if(O.append("rect").style("opacity",0),O.append("g").attr("class","nv-x nv-axis"),O.append("g").attr("class","nv-y nv-axis"),O.append("g").attr("class","nv-stackedWrap"),O.append("g").attr("class","nv-legendWrap"),O.append("g").attr("class","nv-controlsWrap"),O.append("g").attr("class","nv-interactive"),P.select("rect").attr("width",K).attr("height",L),q){var Q=p?K-z:K;h.width(Q),P.select(".nv-legendWrap").datum(k).call(h),l.top!=h.height()&&(l.top=h.height(),L=a.utils.availableHeight(n,x,l)),P.select(".nv-legendWrap").attr("transform","translate("+(K-Q)+","+-l.top+")")}if(p){var R=[{key:B.stacked||"Stacked",metaKey:"Stacked",disabled:"stack"!=e.style(),style:"stack"},{key:B.stream||"Stream",metaKey:"Stream",disabled:"stream"!=e.style(),style:"stream"},{key:B.expanded||"Expanded",metaKey:"Expanded",disabled:"expand"!=e.style(),style:"expand"},{key:B.stack_percent||"Stack %",metaKey:"Stack_Percent",disabled:"stack_percent"!=e.style(),style:"stack_percent"}];z=A.length/3*260,R=R.filter(function(a){return-1!==A.indexOf(a.metaKey)}),i.width(z).color(["#444","#444","#444"]),P.select(".nv-controlsWrap").datum(R).call(i),l.top!=Math.max(i.height(),h.height())&&(l.top=Math.max(i.height(),h.height()),L=a.utils.availableHeight(n,x,l)),P.select(".nv-controlsWrap").attr("transform","translate(0,"+-l.top+")")}N.attr("transform","translate("+l.left+","+l.top+")"),t&&P.select(".nv-y.nv-axis").attr("transform","translate("+K+",0)"),u&&(j.width(K).height(L).margin({left:l.left,top:l.top}).svgContainer(x).xScale(c),N.select(".nv-interactive").call(j)),e.width(K).height(L);var S=P.select(".nv-stackedWrap").datum(k);if(S.transition().call(e),r&&(f.scale(c)._ticks(a.utils.calcTicksX(K/100,k)).tickSize(-L,0),P.select(".nv-x.nv-axis").attr("transform","translate(0,"+L+")"),P.select(".nv-x.nv-axis").transition().duration(0).call(f)),s){var T;if(T="wiggle"===e.offset()?0:a.utils.calcTicksY(L/36,k),g.scale(d)._ticks(T).tickSize(-K,0),"expand"===e.style()||"stack_percent"===e.style()){var U=g.tickFormat();D&&U===J||(D=U),g.tickFormat(J)}else D&&(g.tickFormat(D),D=null);P.select(".nv-y.nv-axis").transition().duration(0).call(g)}e.dispatch.on("areaClick.toggle",function(a){1===k.filter(function(a){return!a.disabled}).length?k.forEach(function(a){a.disabled=!1}):k.forEach(function(b,c){b.disabled=c!=a.seriesIndex}),v.disabled=k.map(function(a){return!!a.disabled}),y.stateChange(v),b.update()}),h.dispatch.on("stateChange",function(a){for(var c in a)v[c]=a[c];y.stateChange(v),b.update()}),i.dispatch.on("legendClick",function(a,c){a.disabled&&(R=R.map(function(a){return a.disabled=!0,a}),a.disabled=!1,e.style(a.style),v.style=e.style(),y.stateChange(v),b.update())}),j.dispatch.on("elementMousemove",function(c){e.clearHighlights();var d,g,h,i=[];if(k.filter(function(a,b){return a.seriesIndex=b,!a.disabled}).forEach(function(f,j){g=a.interactiveBisect(f.values,c.pointXValue,b.x());var k=f.values[g],l=b.y()(k,g);if(null!=l&&e.highlightPoint(j,g,!0),"undefined"!=typeof k){"undefined"==typeof d&&(d=k),"undefined"==typeof h&&(h=b.xScale()(b.x()(k,g)));var m="expand"==e.style()?k.display.y:b.y()(k,g);i.push({key:f.key,value:m,color:o(f,f.seriesIndex),stackedValue:k.display})}}),i.reverse(),i.length>2){var m=b.yScale().invert(c.mouseY),n=null;i.forEach(function(a,b){m=Math.abs(m);var c=Math.abs(a.stackedValue.y0),d=Math.abs(a.stackedValue.y);return m>=c&&d+c>=m?void(n=b):void 0}),null!=n&&(i[n].highlight=!0)}var p=f.tickFormat()(b.x()(d,g)),q=j.tooltip.valueFormatter();"expand"===e.style()||"stack_percent"===e.style()?(E||(E=q),q=d3.format(".1%")):E&&(q=E,E=null),j.tooltip.position({left:h+l.left,top:c.mouseY+l.top}).chartContainer(F.parentNode).valueFormatter(q).data({value:p,series:i})(),j.renderGuideLine(h)}),j.dispatch.on("elementMouseout",function(a){e.clearHighlights()}),y.on("changeState",function(a){"undefined"!=typeof a.disabled&&k.length===a.disabled.length&&(k.forEach(function(b,c){b.disabled=a.disabled[c]}),v.disabled=a.disabled),"undefined"!=typeof a.style&&(e.style(a.style),G=a.style),b.update()})}),F.renderEnd("stacked Area chart immediate"),b}var c,d,e=a.models.stackedArea(),f=a.models.axis(),g=a.models.axis(),h=a.models.legend(),i=a.models.legend(),j=a.interactiveGuideline(),k=a.models.tooltip(),l={top:30,right:25,bottom:50,left:60},m=null,n=null,o=a.utils.defaultColor(),p=!0,q=!0,r=!0,s=!0,t=!1,u=!1,v=a.utils.state(),w=null,x=null,y=d3.dispatch("stateChange","changeState","renderEnd"),z=250,A=["Stacked","Stream","Expanded"],B={},C=250;v.style=e.style(),f.orient("bottom").tickPadding(7),g.orient(t?"right":"left"),k.headerFormatter(function(a,b){return f.tickFormat()(a,b)}).valueFormatter(function(a,b){return g.tickFormat()(a,b)}),j.tooltip.headerFormatter(function(a,b){return f.tickFormat()(a,b)}).valueFormatter(function(a,b){return g.tickFormat()(a,b)});var D=null,E=null;i.updateState(!1);var F=a.utils.renderWatch(y),G=e.style(),H=function(a){return function(){return{active:a.map(function(a){return!a.disabled}),style:e.style()}}},I=function(a){return function(b){void 0!==b.style&&(G=b.style),void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}},J=d3.format("%");return e.dispatch.on("elementMouseover.tooltip",function(a){a.point.x=e.x()(a.point),a.point.y=e.y()(a.point),k.data(a).position(a.pos).hidden(!1)}),e.dispatch.on("elementMouseout.tooltip",function(a){k.hidden(!0)}),b.dispatch=y,b.stacked=e,b.legend=h,b.controls=i,b.xAxis=f,b.yAxis=g,b.interactiveLayer=j,b.tooltip=k,b.dispatch=y,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return m},set:function(a){m=a}},height:{get:function(){return n},set:function(a){n=a}},showLegend:{get:function(){return q},set:function(a){q=a}},showXAxis:{get:function(){return r},set:function(a){r=a}},showYAxis:{get:function(){return s},set:function(a){s=a}},defaultState:{get:function(){return w},set:function(a){w=a}},noData:{get:function(){return x},set:function(a){x=a}},showControls:{get:function(){return p},set:function(a){p=a}},controlLabels:{get:function(){return B},set:function(a){B=a}},controlOptions:{get:function(){return A},set:function(a){A=a}},tooltips:{get:function(){return k.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),k.enabled(!!b)}},tooltipContent:{get:function(){return k.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),k.contentGenerator(b)}},margin:{get:function(){return l},set:function(a){l.top=void 0!==a.top?a.top:l.top,l.right=void 0!==a.right?a.right:l.right,l.bottom=void 0!==a.bottom?a.bottom:l.bottom,l.left=void 0!==a.left?a.left:l.left}},duration:{get:function(){return C},set:function(a){C=a,F.reset(C),e.duration(C),f.duration(C),g.duration(C)}},color:{get:function(){return o},set:function(b){o=a.utils.getColor(b),h.color(o),e.color(o)}},rightAlignYAxis:{get:function(){return t},set:function(a){t=a,g.orient(t?"right":"left")}},useInteractiveGuideline:{get:function(){return u},set:function(a){u=!!a,b.interactive(!a),b.useVoronoi(!a),e.scatter.interactive(!a)}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.sunburst=function(){"use strict";function b(u){return t.reset(),u.each(function(b){function t(a){a.x0=a.x,a.dx0=a.dx}function u(a){var b=d3.interpolate(p.domain(),[a.x,a.x+a.dx]),c=d3.interpolate(q.domain(),[a.y,1]),d=d3.interpolate(q.range(),[a.y?20:0,y]);return function(a,e){return e?function(b){return s(a)}:function(e){return p.domain(b(e)),q.domain(c(e)).range(d(e)),s(a)}}}l=d3.select(this);var v,w=a.utils.availableWidth(g,l,f),x=a.utils.availableHeight(h,l,f),y=Math.min(w,x)/2;a.utils.initSVG(l);var z=l.selectAll(".nv-wrap.nv-sunburst").data(b),A=z.enter().append("g").attr("class","nvd3 nv-wrap nv-sunburst nv-chart-"+k),B=A.selectAll("nv-sunburst");z.attr("transform","translate("+w/2+","+x/2+")"),l.on("click",function(a,b){o.chartClick({data:a,index:b,pos:d3.event,id:k})}),q.range([0,y]),c=c||b,e=b[0],r.value(j[i]||j.count),v=B.data(r.nodes).enter().append("path").attr("d",s).style("fill",function(a){return m((a.children?a:a.parent).name)}).style("stroke","#FFF").on("click",function(a){d!==c&&c!==a&&(d=c),c=a,v.transition().duration(n).attrTween("d",u(a))}).each(t).on("dblclick",function(a){d.parent==a&&v.transition().duration(n).attrTween("d",u(e))}).each(t).on("mouseover",function(a,b){d3.select(this).classed("hover",!0).style("opacity",.8),o.elementMouseover({data:a,color:d3.select(this).style("fill")})}).on("mouseout",function(a,b){d3.select(this).classed("hover",!1).style("opacity",1),o.elementMouseout({data:a})}).on("mousemove",function(a,b){o.elementMousemove({data:a})})}),t.renderEnd("sunburst immediate"),b}var c,d,e,f={top:0,right:0,bottom:0,left:0},g=null,h=null,i="count",j={count:function(a){return 1},size:function(a){return a.size}},k=Math.floor(1e4*Math.random()),l=null,m=a.utils.defaultColor(),n=500,o=d3.dispatch("chartClick","elementClick","elementDblClick","elementMousemove","elementMouseover","elementMouseout","renderEnd"),p=d3.scale.linear().range([0,2*Math.PI]),q=d3.scale.sqrt(),r=d3.layout.partition().sort(null).value(function(a){return 1}),s=d3.svg.arc().startAngle(function(a){return Math.max(0,Math.min(2*Math.PI,p(a.x)))}).endAngle(function(a){return Math.max(0,Math.min(2*Math.PI,p(a.x+a.dx)))}).innerRadius(function(a){return Math.max(0,q(a.y))}).outerRadius(function(a){return Math.max(0,q(a.y+a.dy))}),t=a.utils.renderWatch(o);return b.dispatch=o,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return g},set:function(a){g=a}},height:{get:function(){return h},set:function(a){h=a}},mode:{get:function(){return i},set:function(a){i=a}},id:{get:function(){return k},set:function(a){k=a}},duration:{get:function(){return n},set:function(a){n=a}},margin:{get:function(){return f},set:function(a){f.top=void 0!=a.top?a.top:f.top,f.right=void 0!=a.right?a.right:f.right,f.bottom=void 0!=a.bottom?a.bottom:f.bottom,f.left=void 0!=a.left?a.left:f.left}},color:{get:function(){return m},set:function(b){m=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.sunburstChart=function(){"use strict";function b(d){return m.reset(),m.models(c),d.each(function(d){var h=d3.select(this);a.utils.initSVG(h);var i=a.utils.availableWidth(f,h,e),j=a.utils.availableHeight(g,h,e);if(b.update=function(){0===k?h.call(b):h.transition().duration(k).call(b)},b.container=this,!d||!d.length)return a.utils.noData(b,h),b;h.selectAll(".nv-noData").remove();var l=h.selectAll("g.nv-wrap.nv-sunburstChart").data(d),m=l.enter().append("g").attr("class","nvd3 nv-wrap nv-sunburstChart").append("g"),n=l.select("g");m.append("g").attr("class","nv-sunburstWrap"),l.attr("transform","translate("+e.left+","+e.top+")"),c.width(i).height(j);var o=n.select(".nv-sunburstWrap").datum(d);d3.transition(o).call(c)}),m.renderEnd("sunburstChart immediate"),b}var c=a.models.sunburst(),d=a.models.tooltip(),e={top:30,right:20,bottom:20,left:20},f=null,g=null,h=a.utils.defaultColor(),i=(Math.round(1e5*Math.random()),null),j=null,k=250,l=d3.dispatch("tooltipShow","tooltipHide","stateChange","changeState","renderEnd"),m=a.utils.renderWatch(l);return d.headerEnabled(!1).duration(0).valueFormatter(function(a,b){return a}),c.dispatch.on("elementMouseover.tooltip",function(a){a.series={key:a.data.name,value:a.data.size,color:a.color},d.data(a).hidden(!1)}),c.dispatch.on("elementMouseout.tooltip",function(a){d.hidden(!0)}),c.dispatch.on("elementMousemove.tooltip",function(a){d.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.dispatch=l,b.sunburst=c,b.tooltip=d,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{noData:{get:function(){return j},set:function(a){j=a}},defaultState:{get:function(){return i},set:function(a){i=a}},color:{get:function(){return h},set:function(a){h=a,c.color(h)}},duration:{get:function(){return k},set:function(a){k=a,m.reset(k),c.duration(k)}},margin:{get:function(){return e},set:function(a){e.top=void 0!==a.top?a.top:e.top,e.right=void 0!==a.right?a.right:e.right,e.bottom=void 0!==a.bottom?a.bottom:e.bottom,e.left=void 0!==a.left?a.left:e.left}}}),a.utils.inheritOptions(b,c),a.utils.initOptions(b),b},a.version="1.8.1"}(); \ No newline at end of file
diff --git a/wqflask/wqflask/static/packages/TableTools/media/css/TableTools.css b/wqflask/wqflask/static/packages/TableTools/media/css/TableTools.css
index 705008b0..ffa2af34 100755
--- a/wqflask/wqflask/static/packages/TableTools/media/css/TableTools.css
+++ b/wqflask/wqflask/static/packages/TableTools/media/css/TableTools.css
@@ -319,3 +319,8 @@ div.DTTT_collection a.DTTT_button {
line-height: 20px;
}
+.no-sort::after { display: none!important; }
+.no-sort { pointer-events: none!important;
+ cursor: default!important;
+}
+
diff --git a/wqflask/wqflask/static/packages/bootstrap/css/bootstrap.css b/wqflask/wqflask/static/packages/bootstrap/css/bootstrap.css
index 8326e83f..461fd089 100755
--- a/wqflask/wqflask/static/packages/bootstrap/css/bootstrap.css
+++ b/wqflask/wqflask/static/packages/bootstrap/css/bootstrap.css
@@ -903,7 +903,7 @@ body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.42857143;
- color: #333;
+ color: #000;
background-color: #fff;
}
input,
@@ -1215,7 +1215,7 @@ a.bg-danger:hover {
}
.page-header {
padding-bottom: 9px;
- margin: 20px 0 20px;
+ margin: 10px 0 10px;
border-bottom: 1px solid #eee;
}
ul,
@@ -2072,8 +2072,8 @@ th {
text-align: left;
}
.table {
- width: 100%;
- max-width: 100%;
+ //width: 100%;
+ //max-width: 100%;
margin-bottom: 20px;
}
.table > thead > tr > th,
@@ -2365,7 +2365,7 @@ output {
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
- color: #555;
+ color: #000;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
@@ -4674,7 +4674,7 @@ a.list-group-item.active > .badge,
margin-left: 3px;
}
.jumbotron {
- margin-bottom: 30px;
+ margin-bottom: 10px;
color: inherit;
background-color: #eee;
}
@@ -5133,6 +5133,7 @@ a.list-group-item-danger.active:focus {
border-bottom: 1px solid transparent;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
+ cursor: pointer;
}
.panel-heading > .dropdown .dropdown-toggle {
color: inherit;
diff --git a/wqflask/wqflask/templates/base.html b/wqflask/wqflask/templates/base.html
index 462a59a2..4d44642b 100755
--- a/wqflask/wqflask/templates/base.html
+++ b/wqflask/wqflask/templates/base.html
@@ -1,3 +1,4 @@
+{% from "base_macro.html" import header, flash_me, timeago %}
<!DOCTYPE HTML>
<html lang="en">
<html xmlns="http://www.w3.org/1999/xhtml">
@@ -10,12 +11,6 @@
<link REL="stylesheet" TYPE="text/css" href="/static/packages/bootstrap/css/bootstrap.css" />
<link REL="stylesheet" TYPE="text/css" href="/static/packages/bootstrap/css/non-responsive.css" />
<link REL="stylesheet" TYPE="text/css" href="/static/packages/bootstrap/css/docs.css" />
-
- <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
- <!--[if lt IE 9]>
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
- <![endif]-->
-
<link rel="stylesheet" type="text/css" href="/static/packages/colorbox/example4/colorbox.css" />
<link rel="stylesheet" type="text/css" href="/static/new/css/main.css" />
<link rel="stylesheet" type="text/css" href="/static/new/css/parsley.css" />
@@ -25,37 +20,6 @@
</head>
-{% macro header(main, second) %}
- <header class="jumbotron subhead" id="overview" >
- <div class="container">
- <h1>{{ main }}</h1>
- <p class="lead">
- {{ second }}
- </p>
- </div>
- </header>
-
- {{ flash_me() }}
-{% endmacro %}
-
-
-{% macro flash_me() -%}
- {% with messages = get_flashed_messages(with_categories=true) %}
- {% if messages %}
- <div class="container">
- {% for category, message in messages %}
- <div class="alert {{ category }}">{{ message }}</div>
- {% endfor %}
- </div>
- {% endif %}
- {% endwith %}
-{% endmacro %}
-
-{% macro timeago(timestamp) %}
-<time class="timeago" datetime="{{ timestamp }}">{{ timestamp }}</time>
-{% endmacro %}
-
-
<body style="width: 1500px !important;">
<!-- Navbar ================================================== -->
@@ -105,10 +69,27 @@
<a id="login_in" href="/n/login">Sign in</a>
{% endif %}
</li>
+ <li style="margin-left: 20px;">
+ <a href="http://www.genenetwork.org" style="font-weight: bold;" >Use GeneNetwork 1</a>
+ </li
</ul>
</div>
</div>
</div>
+
+ <div class="container-fluid" style="background-color: #d5d5d5; height: 95px;">
+
+ <form method="get" action="/gsearch">
+ <div class="row">
+ <select class="form-control col-xs-2" style="width: 170px; margin-top: 15px; margin-left: 10px;" name="type">
+ <option value="gene">Genes / Molecules</option>
+ <option value="phenotype" {% if type=="phenotype" %}selected{% endif %}>Phenotypes</option>
+ </select>
+ <input class="btn btn-primary form-control col-xs-2" style="width: 100px; margin-top: 15px; margin-left: 10px;" type="submit" value="Search All">
+ <input class="form-control col-xs-6" style="width: 600px; margin-top: 15px; margin-left: 10px;" type="text" name="terms" required>
+ </div>
+ </form>
+ </div>
{% block content %}{% endblock %}
diff --git a/wqflask/wqflask/templates/base_macro.html b/wqflask/wqflask/templates/base_macro.html
new file mode 100644
index 00000000..c2905ebe
--- /dev/null
+++ b/wqflask/wqflask/templates/base_macro.html
@@ -0,0 +1,28 @@
+{% macro flash_me() -%}
+ {% with messages = get_flashed_messages(with_categories=true) %}
+ {% if messages %}
+ <div class="container">
+ {% for category, message in messages %}
+ <div class="alert {{ category }}">{{ message }}</div>
+ {% endfor %}
+ </div>
+ {% endif %}
+ {% endwith %}
+{% endmacro %}
+
+{% macro header(main, second) %}
+ <header class="jumbotron subhead" id="overview" >
+ <div class="container">
+ <h1>{{ main }}</h1>
+ <p class="lead">
+ {{ second }}
+ </p>
+ </div>
+ </header>
+
+ {{ flash_me() }}
+{% endmacro %}
+
+{% macro timeago(timestamp) %}
+<time class="timeago" datetime="{{ timestamp }}">{{ timestamp }}</time>
+{% endmacro %}
diff --git a/wqflask/wqflask/templates/collections/add.html b/wqflask/wqflask/templates/collections/add.html
index faee4f78..07fcba22 100755
--- a/wqflask/wqflask/templates/collections/add.html
+++ b/wqflask/wqflask/templates/collections/add.html
@@ -1,11 +1,12 @@
<div id="myModal">
<div class="modal-header">
<h3>Add to collection</h3>
- <p>You have three choices: Use your default collection, create a new named collection,
+ <p>You have two choices: Create and name a collection,
or add the traits to an existing collection.</p>
</div>
<div class="modal-body">
<form action="/collections/new" data-validate="parsley" id="add_form">
+<!--
<fieldset>
<legend>Use your default collection</legend>
<span class="help-block">Choose this if you're in a hurry or don't plan on using the collection again.</span>
@@ -13,11 +14,12 @@
<button type="submit" name="Default" class="btn">Continue</button>
</fieldset>
<hr />
+-->
<input type="hidden" name="traits" value="{{ traits }}" />
<fieldset>
- <legend>Or create a new named collection</legend>
+ <legend>Create a new named collection</legend>
<label>New collection name</label>
<input type="text" name="new_collection" placeholder="Name of new collection..."
data-trigger="change" data-minlength="5" data-maxlength="50">
diff --git a/wqflask/wqflask/templates/collections/list.html b/wqflask/wqflask/templates/collections/list.html
index 354723d0..52106eae 100755
--- a/wqflask/wqflask/templates/collections/list.html
+++ b/wqflask/wqflask/templates/collections/list.html
@@ -1,5 +1,10 @@
{% extends "base.html" %}
{% block title %}Your Collections{% endblock %}
+{% block css %}
+ <link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/css/jquery.dataTables.css" />
+ <link rel="stylesheet" type="text/css" href="/static/packages/DT_bootstrap/DT_bootstrap.css" />
+ <link rel="stylesheet" type="text/css" href="/static/packages/TableTools/media/css/TableTools.css" />
+{% endblock %}
{% block content %}
<!-- Start of body -->
{{ header("Your Collections",
@@ -11,10 +16,11 @@
<h1>Collections owned by {{ g.user_session.user_ob.full_name }}</h1>
</div>
- <div class="bs-docs-example" id="collections_list">
- <table class="table table-hover" id='trait_table'>
+ <div id="collections_list">
+ <table class="table table-hover table-striped" id='trait_table'>
<thead>
<tr>
+ <th>Index</th>
<th>Name</th>
<th>Created</th>
<th>Last Changed</th>
@@ -25,6 +31,7 @@
<tbody>
{% for uc in user_collections %}
<tr class="collection_line">
+ <td>{{ loop.index }}
<td><a class="collection_name" href="{{ url_for('view_collection', uc_id=uc.id) }}">{{ uc.name }}</a></td>
<td>{{ timeago(uc.created_timestamp.isoformat() + "Z") }}</td>
<td>{{ timeago(uc.changed_timestamp.isoformat() + "Z") }}</td>
@@ -35,7 +42,7 @@
</table>
{# if "color_by_trait" in params #}
-<!-- <script type="text/javascript" src="/static/new/javascript/get_traits_from_collection.js"></script>-->
+ <script type="text/javascript" src="/static/new/javascript/get_traits_from_collection.js"></script>
{# endif #}
</div>
@@ -47,7 +54,23 @@
{% block js %}
<script type="text/javascript" src="/static/packages/smart-time-ago/lib/timeago.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.dataTables.min.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/dataTables.naturalSort.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colResize.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colReorder.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/packages/DT_bootstrap/DT_bootstrap.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/packages/TableTools/media/js/TableTools.min.js"></script>
<script>
- $('body').timeago();
+ $('#trait_table').dataTable( {
+ "sDom": "RZtir",
+ "iDisplayLength": -1,
+ "autoWidth": true,
+ "bDeferRender": true,
+ "bSortClasses": false,
+ "scrollY": "600px",
+ "scrollCollapse": true,
+ "paging": false
+ } );
+
</script>
{% endblock %}
diff --git a/wqflask/wqflask/templates/collections/view.html b/wqflask/wqflask/templates/collections/view.html
index fc1edf2a..5450f903 100755
--- a/wqflask/wqflask/templates/collections/view.html
+++ b/wqflask/wqflask/templates/collections/view.html
@@ -38,6 +38,18 @@
<input type="submit" class="btn btn-primary" value="Correlation Matrix" />
</div>
</form>
+ <form action="/wgcna_setup" method="post">
+ {% if uc %}
+ <input type="hidden" name="uc_id" id="uc_id" value="{{ uc.id }}" />
+ {% endif %}
+ <input type="hidden" name="trait_list" id="trait_list" value= "
+ {% for this_trait in trait_obs %}
+ {{ this_trait.name }}:{{ this_trait.dataset.name }},
+ {% endfor %}" >
+ <div class="col-xs-2 controls">
+ <input type="submit" class="btn btn-primary" value="WGCNA Analysis" />
+ </div>
+ </form>
<form action="/heatmap" method="post">
{% if uc %}
<input type="hidden" name="uc_id" id="uc_id" value="{{ uc.id }}" />
@@ -59,12 +71,15 @@
<button class="btn btn-default" id="select_all"><span class="glyphicon glyphicon-ok"></span> Select All</button>
<button class="btn btn-default" id="deselect_all"><span class="glyphicon glyphicon-remove"></span> Deselect All</button>
<button class="btn btn-default" id="invert"><span class="glyphicon glyphicon-resize-vertical"></span> Invert</button>
+ <button class="btn" id="add" disabled="disabled"><i class="icon-plus-sign"></i> Add Record to Other Collection</button>
+ <button class="btn" id="remove" disabled="disabled"><i class="icon-minus-sign"></i> Remove Record</button>
+ <button class="btn btn-primary pull-right"><i class="icon-download icon-white"></i> Download Table</button>
<br />
<br />
<table class="table table-hover table-striped" id='trait_table'>
<thead>
<tr>
- <th></th>
+ <th>Index</th>
<th>Record</th>
<th>Description</th>
<th>Location</th>
@@ -78,7 +93,7 @@
<tbody>
{% for this_trait in trait_obs %}
<TR id="trait:{{ this_trait.name }}:{{ this_trait.dataset.name }}">
- <TD>
+ <TD>{{ loop.index }}
<INPUT TYPE="checkbox" NAME="searchResult" class="checkbox trait_checkbox"
VALUE="{{ data_hmac('{}:{}'.format(this_trait.name, this_trait.dataset.name)) }}">
</TD>
@@ -99,7 +114,7 @@
<TD>{{ this_trait.additive }}</TD>
</TR>
- {% endfor %}
+ {% endfor %}
</tbody>
</table>
@@ -115,8 +130,12 @@
<script type="text/javascript" src="/static/new/javascript/search_results.js"></script>
<script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.dataTables.min.js"></script>
<script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/dataTables.naturalSort.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colResize.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colReorder.js"></script>
<script language="javascript" type="text/javascript" src="/static/packages/DT_bootstrap/DT_bootstrap.js"></script>
<script language="javascript" type="text/javascript" src="/static/packages/TableTools/media/js/TableTools.min.js"></script>
+
+
<script language="javascript" type="text/javascript">
$(document).ready( function () {
@@ -128,36 +147,31 @@
console.time("Creating table");
$('#trait_table').dataTable( {
- "aoColumns": [
- { "bSortable": false },
- { "sType": "natural" },
- { "sType": "natural",
- "sWidth": "35%" },
- { "sType": "natural",
- "sWidth": "15%" },
- { "sType": "cust-txt" },
- { "sType": "natural",
- "sWidth": "12%" },
- { "sType": "natural",
- "sWidth": "15%" },
- { "sType": "cust-txt" }
- ],
"columns": [
- { "width": "50%" },
- null,
- null,
- null,
- null,
- null
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural",
+ "width": "35%" },
+ { "type": "natural",
+ "width": "15%" },
+ { "type": "cust-txt" },
+ { "type": "natural",
+ "width": "12%" },
+ { "type": "natural",
+ "width": "15%" },
+ { "type": "natural" }
],
- "sDom": "tir",
+ "sDom": "ZRtir",
"iDisplayLength": -1,
"autoWidth": true,
- "bLengthChange": true,
"bDeferRender": true,
- "bSortClasses": false
+ "bSortClasses": false,
+ "scrollY": "600px",
+ "scrollCollapse": true,
+ "paging": false
} );
console.timeEnd("Creating table");
+
});
</script>
diff --git a/wqflask/wqflask/templates/correlation_matrix.html b/wqflask/wqflask/templates/correlation_matrix.html
index 403d2a98..c822b8bc 100755
--- a/wqflask/wqflask/templates/correlation_matrix.html
+++ b/wqflask/wqflask/templates/correlation_matrix.html
@@ -1,76 +1,71 @@
-{% extends "base.html" %}
-{% block css %}
- <link rel="stylesheet" type="text/css" href="/static/packages/jqplot/jquery.jqplot.min.css" />
- <link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/css/jquery.dataTables.css" />
- <link rel="stylesheet" type="text/css" href="/static/packages/DT_bootstrap/DT_bootstrap.css" />
- <link rel="stylesheet" type="text/css" href="/static/packages/TableTools/media/css/TableTools.css" />
- <link rel="stylesheet" type="text/css" href="/static/new/css/corr_matrix.css" />
- <link rel="stylesheet" type="text/css" href="/static/new/css/panelutil.css" />
- <link rel="stylesheet" type="text/css" href="/static/new/css/d3-tip.min.css" />
-{% endblock %}
-{% block content %}
-
- {{ header("Correlation Matrix") }}
-
- <div class="container">
- <div id="chart"></div>
-<!-- <div class="row-fluid show-grid">
- <div class="col-md-12"> Pearon's R </div>
- </div>
- <div class="row-fluid show-grid">
- <div class="col-md-1 col-md-pull-11">
- Spearman's Rho
- </div>
- <div class="col-md-11 col-md-push-1">
-
- <div class="table-responsive">
- <table class="table">
- <th>
- {% for key in corr_results %}
- <td>
- <b>{{ key }}</b>
- </td>
- {% endfor %}
- </th>
- {% for key in corr_results %}
- <tr>
- <td><b>{{ key }}</b></td>
- {% for trait in corr_results[key] %}
- {% if corr_results[key][trait].sample_r != 1 %}
- <td><a target="_blank" href="corr_scatter_plot?dataset_1={{corr_results[key][trait].this_db}}&dataset_2={{corr_results[key][trait].target_db}}&trait_1={{corr_results[key][trait].this_trait}}&trait_2={{corr_results[key][trait].target_trait}}">{{ corr_results[key][trait].sample_r }}</a>
- <br>
- {{ corr_results[key][trait].num_overlap }}</td>
-
- {% else %}
- <td bgcolor="#E6E6E6"> 1 </td>
- {% endif %}
- {% endfor %}
- {% endfor %}
- </tr>
- </table>
- </div>
-
- </div>
- </div>-->
- </div>
-
-{% endblock %}
-
-{% block js %}
-
- <script>
- js_data = {{ js_data | safe }}
- </script>
-
- <script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
- <script type="text/javascript" src="/static/new/js_external/d3-tip.min.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.dataTables.min.js"></script>
- <script language="javascript" type="text/javascript" src="/static/packages/DT_bootstrap/DT_bootstrap.js"></script>
- <script language="javascript" type="text/javascript" src="/static/packages/TableTools/media/js/TableTools.min.js"></script>
- <script language="javascript" type="text/javascript" src="/static/packages/underscore/underscore-min.js"></script>
- <script type="text/javascript" src="/static/new/javascript/panelutil.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/javascript/corr_matrix.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/javascript/create_corr_matrix.js"></script>
-
-{% endblock %}
+{% extends "base.html" %}
+{% block css %}
+ <link rel="stylesheet" type="text/css" href="/static/packages/jqplot/jquery.jqplot.min.css" />
+ <link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/css/jquery.dataTables.css" />
+ <link rel="stylesheet" type="text/css" href="/static/packages/DT_bootstrap/DT_bootstrap.css" />
+ <link rel="stylesheet" type="text/css" href="/static/packages/TableTools/media/css/TableTools.css" />
+ <link rel="stylesheet" type="text/css" href="/static/new/css/corr_matrix.css" />
+ <link rel="stylesheet" type="text/css" href="/static/new/css/panelutil.css" />
+ <link rel="stylesheet" type="text/css" href="/static/new/css/d3-tip.min.css" />
+{% endblock %}
+{% block content %}
+
+ {{ header("Correlation Matrix") }}
+
+
+
+<table class="matrix" border="1" cellpadding="5" cellspacing="1" style="margin: 20px;" width="80%">
+ <tbody>
+ <tr>
+ <td style="background-color: royalblue;" ></td>
+ <td align="center" colspan="{{traits|length + 1 }}" style="font-weight: Bold; border: 1px solid #999999; padding: 3px; color: #fff; background-color: royalblue;">Spearman Rank Correlation (rho)</td>
+ </tr>
+ <tr>
+ <td align="center" rowspan="{{traits|length + 1 }}" width="10" style="font-weight: Bold; border: 1px solid #999999; padding: 3px; color: #fff; background-color: royalblue;">P e a r s o n &nbsp;&nbsp;&nbsp; r</td>
+ <td width="300"></td>
+ {% for trait in traits %}
+ <td align="center"><a href="/show_trait?trait_id={{ trait.name }}&dataset={{ trait.dataset.name }}" style="font-weight: Bold;">Trait{{ loop.index }}</a></td>
+ {% endfor %}
+ </tr>
+ {% for trait in traits %}
+ <tr>
+ <td><a href="/show_trait?trait_id={{ trait.name }}&dataset={{ trait.dataset.name }}" style="font-weight: Bold;">Trait {{ loop.index }}: {{ trait.dataset.name }}::{{ trait.name }}</a><div id="shortName_0" style="display:none">Symbol: {{ trait.symbol }} </div><div id="verboseName_0" style="display:none">{{ trait_symbol }} on Chr {{ trait.chr }} @ {{ trait.mb }} Mb</div><div id="verboseName2_0" style="display:none">{{ trait.description }}</div><div id="verboseName3_0" style="display:none">{{ trait.probe_target_description }}</div></td>
+ {% for result in corr_results[loop.index-1] %}
+ {% if result[0].name == trait.name %}
+ <td nowrap="ON" align="center" bgcolor="#cccccc"><a href="/show_trait?trait_id={{ trait.name }}&dataset={{ trait.dataset.name }}"><font style="font-size: 11px; color: #000000;" ><em>n</em><br>{{ result[2] }}</font></a></td>
+ {% else %}
+ <td nowrap="ON" align="middle" class="corr_cell"><a href="/corr_scatter_plot?dataset_1={{ trait.dataset.name }}&dataset_2={{ result[0].dataset.name }}&trait_1={{ trait.name }}&trait_2={{ result[0].name }}"><font style="font-size: 11px; color: #000000;" ><span class="corr_value">{{ '%0.3f' % result[1] }}</span><br>{{ result[2] }}</font></a></td>
+ {% endif %}
+ {% endfor %}
+ </tr>
+ {% endfor %}
+ </tbody>
+</table>
+
+<!--
+<div class="container">
+ <div id="chart"></div>
+</div>
+-->
+
+{% endblock %}
+
+{% block js %}
+
+ <script>
+ js_data = {{ js_data | safe }}
+ </script>
+
+ <script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
+ <script type="text/javascript" src="/static/new/js_external/d3-tip.min.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.dataTables.min.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/packages/DT_bootstrap/DT_bootstrap.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/packages/TableTools/media/js/TableTools.min.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/packages/underscore/underscore-min.js"></script>
+ <script type="text/javascript" src="/static/new/javascript/panelutil.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/js_external/chroma.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/javascript/corr_matrix.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/javascript/create_corr_matrix.js"></script>
+
+{% endblock %}
diff --git a/wqflask/wqflask/templates/correlation_page.html b/wqflask/wqflask/templates/correlation_page.html
index 169371be..b2d17b62 100755
--- a/wqflask/wqflask/templates/correlation_page.html
+++ b/wqflask/wqflask/templates/correlation_page.html
@@ -3,6 +3,8 @@
<link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/css/jquery.dataTables.css" />
<link rel="stylesheet" type="text/css" href="/static/packages/DT_bootstrap/DT_bootstrap.css" />
<link rel="stylesheet" type="text/css" href="/static/packages/TableTools/media/css/TableTools.css" />
+ <link href="//cdn.datatables.net/fixedheader/2.1.2/css/dataTables.fixedHeader.css" rel="stylesheet">
+ <link href="//cdn.datatables.net/fixedcolumns/3.0.4/css/dataTables.fixedColumns.css" rel="stylesheet">
{% endblock %}
{% block content %}
@@ -20,18 +22,32 @@
and analysis page.
</p>
+ <br />
+ <button class="btn btn-default" id="select_all"><span class="glyphicon glyphicon-ok"></span> Select All</button>
+ <button class="btn btn-default" id="deselect_all"><span class="glyphicon glyphicon-remove"></span> Deselect All</button>
+ <button class="btn btn-default" id="invert"><span class="glyphicon glyphicon-resize-vertical"></span> Invert</button>
+ <button class="btn btn-default" id="add" disabled><span class="glyphicon glyphicon-plus-sign"></span> Add</button>
+ <button id="redraw" class="btn btn-default">Reset Columns</button>
+ <input type="text" id="searchbox" class="form-control" style="width: 200px; display: inline;" placeholder="Search This Table For ...">
+ <input type="text" id="select_top" class="form-control" style="width: 200px; display: inline;" placeholder="Select Top ...">
+ <br />
+ <br />
+
<div>
- <table id="corr_results" class="table table-hover table-striped table-bordered">
+ <table id="trait_table" class="table table-hover table-striped">
<thead>
<tr>
- {% if target_dataset.type == 'ProbeSet' %}
- <th>Trait</th>
- <th>Symbol</th>
- <th>Description</th>
- <th>Location</th>
- <th>Mean Expr</th>
- <th>Max LRS</th>
- <th>Max LRS Location</th>
+ <th style="width: 30px;"></th>
+ {% for header in target_dataset.header_fields %}
+ {% if header == 'Max LRS' %}
+ <th style="text-align: right;">Max&nbsp;&nbsp;<br>LRS<a href="http://genenetwork.org//glossary.html#L" target="_blank"><sup style="color:#f00"> ?</sup></a></th>
+ {% elif header == 'Additive Effect' %}
+ <th style="text-align: right;">Additive<br>Effect<a href="http://genenetwork.org//glossary.html#A" target="_blank"><sup style="color:#f00"> ?</sup></a></th>
+ {% else %}
+ <th>{{header}}</th>
+ {% endif %}
+ {% endfor %}
+ {% if target_dataset.type == "ProbeSet" %}
{% if corr_method == 'pearson' %}
<th>Sample r</th>
<th>N Cases</th>
@@ -48,10 +64,6 @@
<th>Tissue p(rho)</th>
{% endif %}
{% elif target_dataset.type == "Publish" %}
- <th>Record ID</th>
- <th>Phenotype</th>
- <th>Authors</th>
- <th>Year</th>
{% if corr_method == 'pearson' %}
<th>Sample r</th>
<th>N Cases</th>
@@ -62,8 +74,6 @@
<th>Sample p(rho)</th>
{% endif %}
{% elif target_dataset.type == "Geno" %}
- <th>Record ID</th>
- <th>Location</th>
{% if corr_method == 'pearson' %}
<th>Sample r</th>
<th>N Cases</th>
@@ -76,38 +86,63 @@
{% endif %}
</tr>
</thead>
+
<tbody>
{% for trait in correlation_results %}
<tr>
- {% if target_dataset.type == 'ProbeSet' %}
- <td><a href="/show_trait?trait_id={{trait.name}}&amp;dataset={{trait.dataset.name}}">{{ trait.name }}</a></td>
- <td>{{ trait.symbol }}</td>
- <td>{{ trait.description }} <br><br> <b>Aliases</b>: {{ trait.alias }}</td>
- <td>Chr{{ trait.chr }}: {{'%0.6f'|format(trait.mb) if trait.mb != None }}</td>
- <td>{{'%0.3f'|format(trait.mean)}}</td>
- <td>{{'%0.3f'|format(trait.lrs)}}</td>
- <td>Chr{{ trait.locus_chr }}: {{'%0.3f'|format(trait.locus_mb) }}</td>
- <td><a target="_blank" href="corr_scatter_plot?dataset_1={{dataset.name}}&dataset_2={{trait.dataset.name}}&trait_1={{this_trait.name}}&trait_2={{trait.name}}">{{'%0.3f'|format(trait.sample_r)}}</a></td>
- <td>{{ trait.num_overlap }}</td>
- <td>{{'%0.3e'|format(trait.sample_p)}}</td>
- <td>{{'%0.3f'|format(trait.lit_corr)}}</td>
- <td>{{'%0.3f'|format(trait.tissue_corr)}}</td>
- <td>{{'%0.3e'|format(trait.tissue_pvalue)}}</td>
- {% elif target_dataset.type == "Publish" %}
- <td><a href="/show_trait?trait_id={{trait.name}}&amp;dataset={{trait.dataset.name}}">{{ trait.name }}</a></td>
- <td>{{ trait.post_publication_description }}</td>
- <td>{{ trait.authors }}</td>
- <td>{{ trait.year }}</td>
- <td><a target="_blank" href="corr_scatter_plot?dataset_1={{dataset.name}}&dataset_2={{trait.dataset.name}}&trait_1={{this_trait.name}}&trait_2={{trait.name}}">{{'%0.3f'|format(trait.sample_r)}}</a></td>
- <td>{{ trait.num_overlap }}</td>
- <td>{{'%0.3e'|format(trait.sample_p)}}</td>
- {% elif target_dataset.type == "Geno" %}
- <td><a href="/show_trait?trait_id={{trait.name}}&amp;dataset={{trait.dataset.name}}">{{ trait.name }}</a></td>
- <td>Chr{{ trait.chr }}: {{'%0.6f'|format(trait.mb) }}</td>
- <td><a target="_blank" href="corr_scatter_plot?dataset_1={{dataset.name}}&dataset_2={{trait.dataset.name}}&trait_1={{this_trait.name}}&trait_2={{trait.name}}">{{'%0.3f'|format(trait.sample_r)}}</a></td>
- <td>{{ trait.num_overlap }}</td>
- <td>{{'%0.3e'|format(trait.sample_p)}}</td>
- {% endif %}
+ <TD><INPUT TYPE="checkbox" NAME="searchResult" class="checkbox trait_checkbox" style="transform: scale(1.5);" VALUE="{{ data_hmac('{}:{}'.format(trait.name, trait.dataset.name)) }}">
+ </TD>
+ <TD align="right">{{ loop.index }}</TD>
+ <TD>
+ <a href="{{ url_for('show_trait_page',
+ trait_id = trait.name,
+ dataset = dataset.name
+ )}}">
+ {{ trait.name }}
+ </a>
+ </TD>
+ {% if target_dataset.type == 'ProbeSet' %}
+ <TD>{{ trait.symbol }}</TD>
+ <TD>{{ trait.description_display }}</TD>
+ <TD style="white-space: nowrap;">{{ trait.location_repr }}</TD>
+ <TD align="right">{{ '%0.3f' % trait.mean|float }}</TD>
+ <TD align="right">{{ '%0.3f' % trait.LRS_score_repr|float }}</TD>
+ <TD style="white-space: nowrap;">{{ trait.LRS_location_repr }}</TD>
+ <TD align="right">{{ '%0.3f' % trait.additive|float }}</TD>
+ <TD><a target="_blank" href="corr_scatter_plot?dataset_1={{dataset.name}}&dataset_2={{trait.dataset.name}}&trait_1={{this_trait.name}}&trait_2={{trait.name}}">{{'%0.3f'|format(trait.sample_r)}}</a></TD>
+ <TD>{{ trait.num_overlap }}</TD>
+ <TD>{{'%0.3e'|format(trait.sample_p)}}</TD>
+ {% if trait.lit_corr == "" or trait.lit_corr == 0.000 %}
+ <TD>--</TD>
+ {% else %}
+ <TD>{{'%0.3f'|format(trait.lit_corr)}}</TD>
+ {% endif %}
+ {% if trait.tissue_corr == "" or trait.tissue_corr == 0.000 %}
+ <TD>--</TD>
+ {% else %}
+ <TD>{{'%0.3f'|format(trait.tissue_corr)}}</TD>
+ {% endif %}
+ <TD>{{'%0.3e'|format(trait.tissue_pvalue)}}</TD>
+ {% elif target_dataset.type == "Publish" %}
+ <TD>{{ trait.description_display }}</TD>
+ <TD>{{ trait.authors }}</TD>
+ <TD>
+ <a href="{{ trait.pubmed_link }}">
+ {{ trait.pubmed_text }}
+ </a>
+ </TD>
+ <TD>{{ trait.LRS_score_repr }}</TD>
+ <TD>{{ trait.LRS_location_repr }}</TD>
+ <TD>{{ '%0.3f' % trait.additive|float }}</TD>
+ <TD><a target="_blank" href="corr_scatter_plot?dataset_1={{dataset.name}}&dataset_2={{trait.dataset.name}}&trait_1={{this_trait.name}}&trait_2={{trait.name}}">{{'%0.3f'|format(trait.sample_r)}}</a></TD>
+ <TD>{{ trait.num_overlap }}</TD>
+ <TD>{{'%0.3e'|format(trait.sample_p)}}</TD>
+ {% elif target_dataset.type == "Geno" %}
+ <TD>{{ trait.location_repr }}</TD>
+ <TD><a target="_blank" href="corr_scatter_plot?dataset_1={{dataset.name}}&dataset_2={{trait.dataset.name}}&trait_1={{this_trait.name}}&trait_2={{trait.name}}">{{'%0.3f'|format(trait.sample_r)}}</a></TD>
+ <TD>{{ trait.num_overlap }}</TD>
+ <TD>{{'%0.3e'|format(trait.sample_p)}}</TD>
+ {% endif %}
</tr>
{% endfor %}
</tbody>
@@ -117,35 +152,168 @@
{% endblock %}
{% block js %}
- <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.dataTables.min.js"></script>
+ <script type="text/javascript" src="/static/new/javascript/search_results.js"></script>
+
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.dataTables.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/dataTables.naturalSort.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colResize.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colReorder.js"></script>
<script language="javascript" type="text/javascript" src="/static/packages/DT_bootstrap/DT_bootstrap.js"></script>
<script language="javascript" type="text/javascript" src="/static/packages/TableTools/media/js/TableTools.min.js"></script>
+ <script language="javascript" type="text/javascript" src="//cdn.datatables.net/fixedheader/2.1.2/js/dataTables.fixedHeader.min.js"></script>
+ <script language="javascript" type="text/javascript" src="//cdn.datatables.net/fixedcolumns/3.0.4/js/dataTables.fixedColumns.min.js"></script>
<script language="javascript" type="text/javascript" src="/static/packages/underscore/underscore-min.js"></script>
<script type="text/javascript" charset="utf-8">
+ function getValue(x) {
+ if (x.indexOf('input') >= 0) {
+ if ($(x).val() == 'x') {
+ return 0;
+ }
+ else {
+ return parseFloat($(x).val());
+ }
+ }
+ else if (isNaN(x)) {
+ return x;
+ }
+ return parseFloat(x);
+ }
+
+ jQuery.fn.dataTableExt.oSort['numeric-html-asc'] = function(a,b) {
+ a = Math.abs(parseFloat($(a).text()));
+ b = Math.abs(parseFloat($(b).text()));
+ return ((a < b) ? -1 : ((a > b) ? 1 : 0));
+ };
+
+ jQuery.fn.dataTableExt.oSort['numeric-html-desc'] = function(a,b) {
+ a = Math.abs(parseFloat($(a).text()));
+ b = Math.abs(parseFloat($(b).text()));
+ return ((a < b) ? 1 : ((a > b) ? -1 : 0));
+ };
+
+ jQuery.fn.dataTableExt.oSort['cust-txt-asc'] = function (a, b) {
+ var x = getValue(a);
+ var y = getValue(b);
+
+ if (x == 'N/A' || x == '') {
+ return 1;
+ }
+ else if (y == 'N/A' || y == '') {
+ return -1;
+ }
+ else {
+ return ((x < y) ? -1 : ((x > y) ? 1 : 0));
+ }
+ };
+
+ jQuery.fn.dataTableExt.oSort['cust-txt-desc'] = function (a, b) {
+ var x = getValue(a);
+ var y = getValue(b);
+ return ((x < y) ? 1 : ((x > y) ? -1 : 0));
+ };
+
+
$(document).ready( function () {
+
+ $('#trait_table tr').click(function(event) {
+ if (event.target.type !== 'checkbox') {
+ $(':checkbox', this).trigger('click');
+ }
+ });
+
console.time("Creating table");
- $('#corr_results').dataTable( {
- //"sDom": "<<'span3'l><'span3'T><'span4'f>'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
- "sDom": "lTftipr",
- "oTableTools": {
- "aButtons": [
- "copy",
- "print",
- {
- "sExtends": "collection",
- "sButtonText": 'Save <span class="caret" />',
- "aButtons": [ "csv", "xls", "pdf" ]
- }
- ],
- "sSwfPath": "/static/packages/TableTools/media/swf/copy_csv_xls_pdf.swf"
+
+ {% if target_dataset.type == "ProbeSet" %}
+
+
+ $('#trait_table').dataTable( {
+ "columns": [
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "numeric-html" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" }
+ ],
+ "sDom": "RZtir",
+ "iDisplayLength": -1,
+ "bDeferRender": true,
+ "bSortClasses": false,
+ //"scrollY": "700px",
+ //"scrollCollapse": false,
+ "paging": false
+ } );
+
+ var table = $('#trait_table').DataTable();
+ new $.fn.dataTable.FixedHeader( table );
+
+ {% elif target_dataset.type == "Publish" %}
+ $('#trait_table').dataTable( {
+ "columns": [
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "numeric-html" },
+ { "type": "natural" },
+ { "type": "natural" }
+ ],
+ "sDom": "RZtir",
+ "iDisplayLength": -1,
+ "autoWidth": true,
+ "bLengthChange": true,
+ "bDeferRender": true,
+ "bSortClasses": false,
+ "scrollY": "700px",
+ "scrollCollapse": false,
+ "colResize": {
+ "tableWidthFixed": false
},
- "iDisplayLength": 50,
+ "paging": false
+ } );
+ {% elif target_dataset.type == "Geno" %}
+ $('#trait_table').dataTable( {
+ "columns": [
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "numeric-html" },
+ { "type": "natural" },
+ { "type": "natural" }
+ ],
+ "sDom": "RZtir",
+ "iDisplayLength": -1,
+ "autoWidth": true,
"bLengthChange": true,
"bDeferRender": true,
- "bSortClasses": false
+ "bSortClasses": false,
+ "scrollY": "700px",
+ "scrollCollapse": false,
+ "colResize": {
+ "tableWidthFixed": false
+ },
+ "paging": false
} );
+ {% endif %}
console.timeEnd("Creating table");
+
+
});
</script>
{% endblock %}
diff --git a/wqflask/wqflask/templates/empty_collection.html b/wqflask/wqflask/templates/empty_collection.html
new file mode 100644
index 00000000..3f2b3786
--- /dev/null
+++ b/wqflask/wqflask/templates/empty_collection.html
@@ -0,0 +1,15 @@
+{% extends "base.html" %}
+{% block title %}{{ tool }}{% endblock %}
+{% block content %}
+<!-- Start of body -->
+ {{ header("Error") }}
+
+ <div class="container">
+ <input type="hidden" name="uc_id" id="uc_id" value="{{ uc_id }}">
+ <p>You must select at least one trait to use the {{ tool }}.</p>
+ </div>
+
+
+<!-- End of body -->
+
+{% endblock %}
diff --git a/wqflask/wqflask/templates/gsearch_gene.html b/wqflask/wqflask/templates/gsearch_gene.html
new file mode 100755
index 00000000..0a1839a1
--- /dev/null
+++ b/wqflask/wqflask/templates/gsearch_gene.html
@@ -0,0 +1,188 @@
+{% extends "base.html" %}
+{% block title %}Search Results{% endblock %}
+{% block css %}
+ <link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/css/jquery.dataTables.css" />
+ <link rel="stylesheet" type="text/css" href="/static/packages/DT_bootstrap/DT_bootstrap.css" />
+ <link rel="stylesheet" type="text/css" href="/static/packages/TableTools/media/css/TableTools.css" />
+ <link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/extensions/dataTables.fixedHeader.css" >
+ <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/fixedcolumns/3.0.4/css/dataTables.fixedColumns.css">
+{% endblock %}
+{% block content %}
+<!-- Start of body -->
+
+ <div class="container">
+
+ <p>To study a record, click on its ID below.<br />Check records below and click Add button to add to selection.</p>
+
+ <div>
+ <br />
+ <button class="btn btn-default" id="select_all"><span class="glyphicon glyphicon-ok"></span> Select All</button>
+ <button class="btn btn-default" id="deselect_all"><span class="glyphicon glyphicon-remove"></span> Deselect All</button>
+ <button class="btn btn-default" id="invert"><span class="glyphicon glyphicon-resize-vertical"></span> Invert</button>
+ <button class="btn btn-default" id="add" disabled ><span class="glyphicon glyphicon-plus-sign"></span> Add</button>
+ <button class="btn btn-primary pull-right"><span class="glyphicon glyphicon-download"></span> Download Table</button>
+ <input type="text" id="searchbox" class="form-control" style="width: 180px; display: inline;" placeholder="Search This Table For ...">
+ <input type="text" id="select_top" class="form-control" style="width: 120px; display: inline;" placeholder="Select Top ...">
+
+ <br />
+ <br />
+ <table width="2000px" class="table table-hover table-striped" id="trait_table">
+ <thead>
+ <tr>
+ <th style="width: 30px;"></th>
+ <th>Index</th>
+ <th>Species</th>
+ <th>Group</th>
+ <th>Tissue</th>
+ <th>Dataset</th>
+ <th>Record</th>
+ <th>Symbol</th>
+ <th>Description</th>
+ <th>Location</th>
+ <th>Mean</th>
+ <th style="text-align: right;">Max&nbsp;&nbsp;<br>LRS<a href="http://genenetwork.org//glossary.html#L" target="_blank"><sup style="color:#f00"> ?</sup></a></th>
+ <th>Max LRS Location</th>
+ <th style="text-align: right;">Additive<br>Effect<a href="http://genenetwork.org//glossary.html#A" target="_blank"><sup style="color:#f00"> ?</sup></a></th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for this_trait in trait_list %}
+ <TR id="trait:{{ this_trait.name }}:{{ this_trait.dataset.name }}">
+ <TD><INPUT TYPE="checkbox" NAME="searchResult" class="checkbox trait_checkbox" style="transform: scale(1.5);" VALUE="{{ data_hmac('{}:{}'.format(this_trait.name, this_trait.dataset.name)) }}"></TD>
+ <TD>{{ loop.index }}</TD>
+ <TD>{{ this_trait.dataset.group.species }}</TD>
+ <TD>{{ this_trait.dataset.group.name }}</TD>
+ <TD>{{ this_trait.dataset.tissue }}</TD>
+ <TD>{{ this_trait.dataset.fullname }}</TD>
+ <TD><a href="{{ url_for('show_trait_page', trait_id = this_trait.name, dataset = this_trait.dataset.name)}}">{{ this_trait.name }}</a></TD>
+ <TD>{{ this_trait.symbol }}</TD>
+ <TD>{{ this_trait.description_display }}</TD>
+ <TD>{{ this_trait.location_repr }}</TD>
+ <TD align="right">{{ '%0.3f' % this_trait.mean|float }}</TD>
+ <TD align="right">{{ '%0.3f' % this_trait.LRS_score_repr|float }}</TD>
+ <TD>{{ this_trait.LRS_location_repr }}</TD>
+ <TD align="right">{{ '%0.3f' % this_trait.additive|float }}</TD>
+ </TR>
+ {% endfor %}
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+<!-- End of body -->
+
+{% endblock %}
+
+{% block js %}
+ <script language="javascript" type="text/javascript" src="/static/new/javascript/search_results.js"></script>
+
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.dataTables.min.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/dataTables.naturalSort.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colReorder.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colResize.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/packages/DT_bootstrap/DT_bootstrap.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/packages/TableTools/media/js/TableTools.min.js"></script>
+
+ <script type="text/javascript" charset="utf-8">
+ function getValue(x) {
+ if (x.indexOf('input') >= 0) {
+ if ($(x).val() == 'x') {
+ return 0;
+ }
+ else {
+ return parseFloat($(x).val());
+ }
+ }
+ else if (isNaN(x)) {
+ return x;
+ }
+ return parseFloat(x);
+ }
+
+ jQuery.fn.dataTableExt.oSort['cust-txt-asc'] = function (a, b) {
+ var x = getValue(a);
+ var y = getValue(b);
+
+ if (x == 'N/A' || x == '') {
+ return 1;
+ }
+ else if (y == 'N/A' || y == '') {
+ return -1;
+ }
+ else {
+ return ((x < y) ? -1 : ((x > y) ? 1 : 0));
+ }
+ };
+
+ jQuery.fn.dataTableExt.oSort['cust-txt-asc'] = function (a, b) {
+ var x = getValue(a);
+ var y = getValue(b);
+
+ if (x == 'N/A' || x == '') {
+ return 1;
+ }
+ else if (y == 'N/A' || y == '') {
+ return -1;
+ }
+ else {
+ return ((x < y) ? -1 : ((x > y) ? 1 : 0));
+ }
+ };
+
+ jQuery.fn.dataTableExt.oSort['cust-txt-desc'] = function (a, b) {
+ var x = getValue(a);
+ var y = getValue(b);
+ return ((x < y) ? 1 : ((x > y) ? -1 : 0));
+ };
+
+ $.fn.dataTable.ext.order['dom-checkbox'] = function ( settings, col )
+ {
+ return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
+ return $('input', td).prop('checked') ? '1' : '0';
+ } );
+ }
+
+ $(document).ready( function () {
+
+ $('#trait_table tr').click(function(event) {
+ if (event.target.type !== 'checkbox') {
+ $(':checkbox', this).trigger('click');
+ }
+ });
+
+ console.time("Creating table");
+ $('#trait_table').DataTable( {
+ "columns": [
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "cust-txt" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural", "width": "15%" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "cust-txt" }
+ ],
+ "order": [[ 1, "asc" ]],
+ "sDom": "RZtir",
+ "autoWidth": false,
+ "bLengthChange": true,
+ "bDeferRender": true,
+ "scrollCollapse": false,
+ "colResize": {
+ "tableWidthFixed": false,
+ },
+ "paging": false
+ } );
+
+ console.timeEnd("Creating table");
+
+ });
+
+ </script>
+{% endblock %}
diff --git a/wqflask/wqflask/templates/gsearch_pheno.html b/wqflask/wqflask/templates/gsearch_pheno.html
new file mode 100755
index 00000000..2527bebf
--- /dev/null
+++ b/wqflask/wqflask/templates/gsearch_pheno.html
@@ -0,0 +1,154 @@
+{% extends "base.html" %}
+{% block title %}Search Results{% endblock %}
+{% block css %}
+ <link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/css/jquery.dataTables.css" />
+ <link rel="stylesheet" type="text/css" href="/static/packages/DT_bootstrap/DT_bootstrap.css" />
+ <link rel="stylesheet" type="text/css" href="/static/packages/TableTools/media/css/TableTools.css" />
+ <link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/extensions/dataTables.fixedHeader.css" >
+ <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/fixedcolumns/3.0.4/css/dataTables.fixedColumns.css">
+{% endblock %}
+{% block content %}
+<!-- Start of body -->
+
+ <div class="container">
+
+ <p>To study a record, click on its ID below.<br />Check records below and click Add button to add to selection.</p>
+
+ <div>
+ <br />
+ <button class="btn btn-default" id="select_all"><span class="glyphicon glyphicon-ok"></span> Select All</button>
+ <button class="btn btn-default" id="deselect_all"><span class="glyphicon glyphicon-remove"></span> Deselect All</button>
+ <button class="btn btn-default" id="invert"><span class="glyphicon glyphicon-resize-vertical"></span> Invert</button>
+ <button class="btn btn-default" id="add" disabled ><span class="glyphicon glyphicon-plus-sign"></span> Add</button>
+ <button class="btn btn-primary pull-right"><span class="glyphicon glyphicon-download"></span> Download Table</button>
+ <input type="text" id="searchbox" class="form-control" style="width: 200px; display: inline;" placeholder="Search This Table For ...">
+ <input type="text" id="select_top" class="form-control" style="width: 200px; display: inline;" placeholder="Select Top ...">
+ <br />
+ <br />
+ <table class="table table-hover table-striped" id='trait_table' style="float: left;">
+ <thead>
+ <tr>
+ <th style="width: 30px;"></th>
+ <th>Index</th>
+ <th>Species</th>
+ <th>Group</th>
+ <th>Record</th>
+ <th>Description</th>
+ <th>Authors</th>
+ <th>Year</th>
+ <th style="text-align: right;">Max&nbsp;&nbsp;<br>LRS<a href="http://genenetwork.org//glossary.html#L" target="_blank"><sup style="color:#f00"> ?</sup></a></th>
+ <th>Max LRS Location</th>
+ <th style="text-align: right;">Additive<br>Effect<a href="http://genenetwork.org//glossary.html#A" target="_blank"><sup style="color:#f00"> ?</sup></a></th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for this_trait in trait_list %}
+ <TR id="trait:{{ this_trait.name }}:{{ this_trait.dataset.name }}">
+ <TD><INPUT TYPE="checkbox" NAME="searchResult" class="checkbox trait_checkbox" style="transform: scale(1.5);" VALUE="{{ data_hmac('{}:{}'.format(this_trait.name, this_trait.dataset.name)) }}"></TD>
+ <TD>{{ loop.index }}</TD>
+ <TD>{{ this_trait.dataset.group.species }}</TD>
+ <TD>{{ this_trait.dataset.group.name }}</TD>
+ <TD><a href="{{ url_for('show_trait_page', trait_id = this_trait.name, dataset = this_trait.dataset.name)}}">{{ this_trait.name }}</a></TD>
+ <TD>{{ this_trait.description_display }}</TD>
+ <TD>{{ this_trait.authors }}</TD>
+ <TD><a href="{{ this_trait.pubmed_link }}">{{ this_trait.pubmed_text }}</a></TD>
+ <TD>{{ this_trait.LRS_score_repr }}</TD>
+ <TD>{{ this_trait.LRS_location_repr }}</TD>
+ <TD>{{ '%0.3f' % this_trait.additive|float }}</TD>
+ </TR>
+ {% endfor %}
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+<!-- End of body -->
+
+{% endblock %}
+
+{% block js %}
+ <script language="javascript" type="text/javascript" src="/static/new/javascript/search_results.js"></script>
+
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.dataTables.min.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/dataTables.naturalSort.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colReorder.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colResize.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/packages/DT_bootstrap/DT_bootstrap.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/packages/TableTools/media/js/TableTools.min.js"></script>
+
+ <script type="text/javascript" charset="utf-8">
+ function getValue(x) {
+ if (x.indexOf('input') >= 0) {
+ if ($(x).val() == 'x') {
+ return 0;
+ }
+ else {
+ return parseFloat($(x).val());
+ }
+ }
+ else if (isNaN(x)) {
+ return x;
+ }
+ return parseFloat(x);
+ }
+
+ jQuery.fn.dataTableExt.oSort['cust-txt-asc'] = function (a, b) {
+ var x = getValue(a);
+ var y = getValue(b);
+
+ if (x == 'N/A' || x == '') {
+ return 1;
+ }
+ else if (y == 'N/A' || y == '') {
+ return -1;
+ }
+ else {
+ return ((x < y) ? -1 : ((x > y) ? 1 : 0));
+ }
+ };
+
+ jQuery.fn.dataTableExt.oSort['cust-txt-desc'] = function (a, b) {
+ var x = getValue(a);
+ var y = getValue(b);
+ return ((x < y) ? 1 : ((x > y) ? -1 : 0));
+ };
+
+ $(document).ready( function () {
+
+ $('#trait_table tr').click(function(event) {
+ if (event.target.type !== 'checkbox') {
+ $(':checkbox', this).trigger('click');
+ }
+ });
+
+ console.time("Creating table");
+ $('#trait_table').DataTable( {
+ "columns": [
+ { "bSortClasses": false },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural", "width": "20%"},
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" }
+ ],
+ "order": [[ 1, "asc" ]],
+ "sDom": "RZtir",
+ "autoWidth": false,
+ "bLengthChange": true,
+ "bDeferRender": true,
+ "scrollCollapse": false,
+ "colResize": {
+ "tableWidthFixed": false,
+ },
+ "paging": false
+ } );
+ console.timeEnd("Creating table");
+ });
+
+ </script>
+{% endblock %}
diff --git a/wqflask/wqflask/templates/index_page.html b/wqflask/wqflask/templates/index_page.html
index 5e0a92e3..6c630344 100755
--- a/wqflask/wqflask/templates/index_page.html
+++ b/wqflask/wqflask/templates/index_page.html
@@ -31,10 +31,10 @@
<label for="species" class="col-xs-1 control-label" style="width: 65px !important;">Species:</label>
<div class="col-xs-10 controls input-append" style="padding-right: 0px;">
<div class="col-xs-8">
- <select name="species" id="species" class="form-control selectpicker span3" style="width: 280px !important;"></select>
+ <select name="species" id="species" class="form-control span3" style="width: 280px !important;"></select>
</div>
<div class="col-xs-4">
- <input id="make_default" class="btn btn-primary form-control" value="Make Default">
+ <button type="button" id="make_default" class="btn btn-primary form-control">Make Default</button>
</div>
</div>
</div>
@@ -43,7 +43,7 @@
<label for="group" class="col-xs-1 control-label" style="width: 65px !important;">Group:</label>
<div class="col-xs-10 controls input-append">
<div class="col-xs-8">
- <select name="group" id="group" class="form-control selectpicker span3" style="width: 280px !important;"></select>
+ <select name="group" id="group" class="form-control span3" style="width: 280px !important;"></select>
<i class="icon-question-sign"></i>
</div>
</div>
@@ -53,7 +53,7 @@
<label for="tissue" class="col-xs-1 control-label" style="width: 65px !important;">Type:</label>
<div class="col-xs-10 controls">
<div class="col-xs-8">
- <select name="type" id="type" class="form-control selectpicker span3" style="width: 280px !important;"></select>
+ <select name="type" id="type" class="form-control span3" style="width: 280px !important;"></select>
</div>
</div>
</div>
@@ -62,7 +62,7 @@
<label for="dataset" class="col-xs-1 control-label" style="width: 65px !important;">Dataset:</label>
<div class="col-xs-10 controls input-append">
<div class="col-xs-8">
- <select name="dataset" id="dataset" class="form-control selectpicker span5" style="width: 450px !important;"></select>
+ <select name="dataset" id="dataset" class="form-control span5" style="width: 450px !important;"></select>
<i class="icon-question-sign"></i>
</div>
</div>
@@ -76,10 +76,10 @@
<!-- GET ANY SEARCH -->
<div class="form-group">
- <label for="tfor" class="col-xs-1 control-label" style="padding-left: 0px; padding-right: 0px; width: 65px !important;">Search for:</label>
+ <label for="or_search" class="col-xs-1 control-label" style="padding-left: 0px; padding-right: 0px; width: 65px !important;">Get Any:</label>
<div class="col-xs-10 controls">
<div class="col-xs-8">
- <textarea name="search_terms" rows="2" class="form-control search-query" style="max-width: 550px; width: 450px !important;" id="tfor"></textarea>
+ <textarea onkeydown="pressed(event)" name="search_terms_or" rows="1" class="form-control search-query" style="max-width: 550px; width: 450px !important;" id="or_search"></textarea>
</div>
</div>
</div>
@@ -87,19 +87,33 @@
<!-- GET ANY HELP -->
<div class="form-group">
<label for="btsearch" class="col-xs-1 control-label" style="width: 65px !important;"></label>
+ <div class="col-xs-10 controls">
+ <div class="col-xs-12 controls">
+ Enter terms, genes, ID numbers in the <b>Search</b> field.<br>
+ Use <b>*</b> or <b>?</b> wildcards (Cyp*a?, synap*).<br>
+ Use <b>quotes</b> for terms such as <i>"tyrosine kinase"</i>.
+ </div>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <label for="and_search" class="col-xs-1 control-label" style="padding-left: 0px; padding-right: 0px; width: 65px !important;">Combined:</label>
+ <div class="col-xs-10 controls">
+ <div class="col-xs-8">
+ <textarea onkeydown="pressed(event)" name="search_terms_and" rows="1" class="form-control search-query" style="max-width: 550px; width: 450px !important;" id="and_search"></textarea>
+ </div>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <label for="btsearch" class="col-xs-1 control-label" style="width: 65px !important;"></label>
<div class="col-xs-10 controls">
<div class="col-xs-2 controls" style="width: 100px !important;">
<input id="btsearch" type="submit" class="btn btn-primary form-control" value="Search">
</div>
- <div class="col-xs-9 controls">
- Enter terms, genes, ID numbers in the <b>Search</b> field
- Use <b>*</b> or <b>?</b> wildcards (Cyp*a?, synap*)
- Use <b>quotes</b> for terms such as <i>"tyrosine kinase"</i>
- </div>
</div>
</div>
-
<!-- SEARCH, MAKE DEFAULT -->
<div class="form-group">
@@ -116,21 +130,15 @@
<h2>Advanced commands</h2>
</div>
- <p>GeneNetwork supports a variety of advanced searches.</p>
-
- <p>To try them out copy these examples into the search field:</p>
+ <p>You can also use advanced commands. Copy these simple examples into the Get Any or Combined search fields:</p>
<ul>
- <!--<li><b>POSITION=(chr1 25 30)</b> finds genes, markers, or transcripts on
+ <li><b>POSITION=(chr1 25 30)</b> finds genes, markers, or transcripts on
chromosome 1 between 25 and 30 Mb.</li>
<li><b>MEAN=(15 16) LRS=(23 46)</b> in the <b>Combined</b> field finds
highly expressed genes (15 to 16 log2 units) AND with peak <a href="http://www.genenetwork.org/glossary.html#L" target="_blank">LRS</a>
- linkage between 23 and 46.</li>-->
-
- <li><b>MEAN=(15 16)</b> finds highly expressed genes (15 to 16 log2 units).</li>
-
- <li><b>LRS=(23 46)</b> finds genes with peak <a href="http://www.genenetwork.org/glossary.html#L" target="_blank">LRS</a> linkage between 23 and 46.</li>
+ linkage between 23 and 46.</li>
<li><b>RIF=mitochondrial</b> searches RNA databases for <a href="http://www.ncbi.nlm.nih.gov/projects/GeneRIF/GeneRIFhelp.html" target="_blank">
GeneRIF</a> links.</li>
@@ -139,7 +147,7 @@
GeneWiki</a> for genes that you or other users have annotated
with the word <i>nicotine</i>.</li>
- <!--<li><b>GO:0045202</b> searches for synapse-associated genes listed in the
+ <li><b>GO:0045202</b> searches for synapse-associated genes listed in the
<a href="http://www.godatabase.org/cgi-bin/amigo/go.cgi" target="_blank">
Gene Ontology</a>.</li>
@@ -151,7 +159,7 @@
<li><b>RIF=diabetes LRS=(9 999 Chr2 100 105) transLRS=(9 999 10)</b>
finds diabetes-associated transcripts with peak <a href="http://www.genenetwork.org/glossary.html#E" target="_blank">
trans eQTLs</a> on Chr 2 between 100 and 105 Mb with LRS
- scores between 9 and 999.</li>-->
+ scores between 9 and 999.</li>
</ul>
</section>
</div>
@@ -206,12 +214,9 @@
<h3>GN1 Mirror and development sites</h3>
<ul>
- <li><a href="http://www.genenetwork.org/" target="_blank" style="font-size:12px;font-family:verdana;color:blue">Main GN1 site at UTHSC</a> (main site)</li>
- <li><a href="http://www.genenetwork.waimr.uwa.edu.au/" target="_blank" style="font-size:12px;font-family:verdana;color:blue">Australia at the UWA</a></li>
- <li><a href="http://gn.genetics.ucla.edu/" target="_blank" style="font-size:12px;font-family:verdana;color:blue">California at UCLA</a></li>
- <li><a href="http://genenetwork.helmholtz-hzi.de/" target="_blank" style="font-size:12px;font-family:verdana;color:blue">Germany at the HZI</a></li>
- <li><a href="http://genenetwork.memphis.edu/" target="_blank" style="font-size:12px;font-family:verdana;color:blue">Memphis at the U of M</a></li>
- <li><a href="http://genenetwork.epfl.ch/" target="_blank" style="font-size:12px;font-family:verdana;color:blue">Switzerland at the EPFL</a></li>
+ <li><a href="http://www.genenetwork.org/" target="_blank">Main GN1 site at UTHSC</a> (main site)</li>
+ <li><a href="http://genenetwork.helmholtz-hzi.de/" target="_blank">Germany at the HZI</a></li>
+ <li><a href="http://genenetwork.memphis.edu/" target="_blank">Memphis at the U of M</a></li>
</ul>
</section>
@@ -260,4 +265,15 @@
{% block js %}
<script src="/static/new/javascript/dataset_select_menu.js"></script>
+
+ <script>
+ function pressed(e) {
+ // Has the enter key been pressed?
+ if ( (window.event ? event.keyCode : e.which) == 13) {
+ // If it has been so, manually submit the <form>
+ document.forms[1].submit();
+ }
+ }
+ </script>
+
{% endblock %} \ No newline at end of file
diff --git a/wqflask/wqflask/templates/interval_mapping.html b/wqflask/wqflask/templates/interval_mapping.html
deleted file mode 100755
index 82a96ba1..00000000
--- a/wqflask/wqflask/templates/interval_mapping.html
+++ /dev/null
@@ -1,116 +0,0 @@
-{% block css %}
-<!-- <link rel="stylesheet" type="text/css" href="/static/new/css/interval_mapping.css" />-->
- <link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/css/jquery.dataTables.css" />
- <link rel="stylesheet" type="text/css" href="/static/packages/DT_bootstrap/DT_bootstrap.css" />
- <link rel="stylesheet" type="text/css" href="/static/packages/TableTools/media/css/TableTools.css" />
- <link rel="stylesheet" type="text/css" href="/static/new/css/d3-tip.min.css" />
- <link rel="stylesheet" type="text/css" href="/static/new/css/panelutil.css" />
-{% endblock %}
-{% block content %} <!-- Start of body -->
-
-
- <div id="mapping_results" class="container">
- <div>
- <h2>
- Whole Genome Mapping
- </h2>
- <form style ='float: left; padding: 5px;' id="exportform" action="export" method="post">
- <input type="hidden" id="data" name="data" value="">
- <input type="hidden" id="filename" name="filename" value="">
- <input type="submit" id="export" value="Download SVG">
- </form>
- <form style ='float: left; padding: 5px;' id="exportpdfform" action="export_pdf" method="post">
- <input type="hidden" id="data" name="data" value="">
- <input type="hidden" id="filename" name="filename" value="">
- <input type="submit" id="export_pdf" value="Download PDF">
- </form>
- </div>
- <div id="chart_container">
- <div class="qtlcharts" id="topchart">
-
- </div>
- </div>
- <div>
- <h2>
- Results
- </h2>
- </div>
- <table cellpadding="0" cellspacing="0" border="0" id="qtl_results" class="table table-hover table-striped table-bordered">
- <thead>
- <tr>
- <td>Index</td>
- <td>LRS Score</td>
- <td>Chr</td>
- <td>Mb</td>
- <td>Locus</td>
- <td>Additive Effect</td>
- </tr>
- </thead>
- <tbody>
- {% for marker in qtl_results %}
- <tr>
- <td>{{ loop.index }}</td>
- <td>{{ marker.lrs_value|float }}</td>
- <td>{{ marker.chr|int }}</td>
- <td>{{ marker.Mb|float }}</td>
- <td>{{ marker.name }}</td>
- <td>{{ marker.additive|float }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
-
- </div>
-
- <!-- End of body -->
-
-{% endblock %}
-
-{% block js %}
- <script>
- js_data = {{ js_data | safe }}
- </script>
-
- <!--[if lt IE 9]>
-<!-- <script language="javascript" type="text/javascript" src="/static/packages/jqplot/excanvas.js"></script>-->
- <![endif]-->
- <script language="javascript" type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/js_external/d3-tip.min.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/javascript/panelutil.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/javascript/chr_interval_map.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/javascript/lod_chart.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/javascript/create_lodchart.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.dataTables.min.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/dataTables.scientific.js"></script>
- <script language="javascript" type="text/javascript" src="/static/packages/DT_bootstrap/DT_bootstrap.js"></script>
- <script language="javascript" type="text/javascript" src="/static/packages/TableTools/media/js/TableTools.min.js"></script>
- <script language="javascript" type="text/javascript" src="/static/packages/underscore/underscore-min.js"></script>
-
- <script type="text/javascript" charset="utf-8">
- $(document).ready( function () {
- console.time("Creating table");
- $('#qtl_results').dataTable( {
- //"sDom": "<<'span3'l><'span3'T><'span4'f>'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
- "sDom": "lTftipr",
- "oTableTools": {
- "aButtons": [
- "copy",
- "print",
- {
- "sExtends": "collection",
- "sButtonText": 'Save <span class="caret" />',
- "aButtons": [ "csv", "xls", "pdf" ]
- }
- ],
- "sSwfPath": "/static/packages/TableTools/media/swf/copy_csv_xls_pdf.swf"
- },
- "iDisplayLength": 50,
- "bLengthChange": true,
- "bDeferRender": true,
- "bSortClasses": false
- } );
- console.timeEnd("Creating table");
- });
- </script>
-{% endblock %} \ No newline at end of file
diff --git a/wqflask/wqflask/templates/marker_regression.html b/wqflask/wqflask/templates/marker_regression.html
index 6aed69d5..2d0b6256 100755
--- a/wqflask/wqflask/templates/marker_regression.html
+++ b/wqflask/wqflask/templates/marker_regression.html
@@ -1,15 +1,5 @@
-{% extends "base.html" %}
-{% block title %}Interval Mapping{% endblock %}
-{% block css %}
-<!-- <link rel="stylesheet" type="text/css" href="/static/new/css/interval_mapping.css" />-->
- <link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/css/jquery.dataTables.css" />
- <link rel="stylesheet" type="text/css" href="/static/packages/DT_bootstrap/DT_bootstrap.css" />
- <link rel="stylesheet" type="text/css" href="/static/packages/TableTools/media/css/TableTools.css" />
- <link rel="stylesheet" type="text/css" href="/static/new/css/d3-tip.min.css" />
- <link rel="stylesheet" type="text/css" href="/static/new/css/panelutil.css" />
-{% endblock %}
-{% block content %} <!-- Start of body -->
-
+{% from "base_macro.html" import header %}
+{% block content %}
{{ header("Mapping",
'{}: {}'.format(this_trait.name, this_trait.description_fmt)) }}
@@ -28,35 +18,46 @@
<input type="hidden" id="filename" name="filename" value="">
<input type="submit" id="export_pdf" value="Download PDF">
</form>
-<!-- <button id="export_pdf" class="btn">Export PDF</button>-->
+ <button id="return_to_full_view" class="btn" style="display:none">Return to full view</button>
</div>
<div id="chart_container">
<div class="qtlcharts" id="topchart">
</div>
</div>
- <div>
+ <div style="width:60%;">
<h2>
Results
</h2>
- <table cellpadding="0" cellspacing="0" border="0" id="qtl_results" class="table table-hover table-striped table-bordered">
+ <table id="qtl_results" class="table table-hover table-striped">
<thead>
<tr>
- <td>Index</td>
- <td>LOD Score</td>
- <td>Chr</td>
- <td>Mb</td>
- <td>Locus</td>
+ <th></th>
+ <th>Index</th>
+ <th>{{ score_type }}</th>
+ <th>Chr</th>
+ <th>Mb</th>
+ <th>Locus</th>
</tr>
</thead>
<tbody>
- {% for marker in filtered_markers %}
- {% if marker.lod_score > lod_cutoff %}
+ {% for marker in qtl_results %}
+ {% if (score_type == "LOD" and marker.lod_score > cutoff) or
+ (score_type == "LRS" and marker.lrs_value > cutoff) %}
<tr>
- <td>{{loop.index}}</td>
- <td>{{marker.lod_score}}</td>
+ <td>
+ <input type="checkbox" name="selectCheck"
+ class="checkbox edit_sample_checkbox"
+ value="{{ marker.name }}" checked="checked">
+ </td>
+ <Td align="right">{{ loop.index }}</Td>
+ {% if score_type == "LOD" %}
+ <td>{{ '%0.2f' | format(marker.lod_score|float) }}</td>
+ {% else %}
+ <td>{{ '%0.2f' | format(marker.lrs_value|float) }}</td>
+ {% endif %}
<td>{{marker.chr}}</td>
- <td>{{marker.Mb}}</td>
+ <td>{{ '%0.6f' | format(marker.Mb|float) }}</td>
<td>{{marker.name}}</td>
</tr>
{% endif %}
@@ -75,52 +76,32 @@
js_data = {{ js_data | safe }}
</script>
- <!--[if lt IE 9]>
-<!-- <script language="javascript" type="text/javascript" src="/static/packages/jqplot/excanvas.js"></script>-->
- <![endif]-->
- <script language="javascript" type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/js_external/d3-tip.min.js"></script>
-<!-- <script language="javascript" type="text/javascript" src="/static/new/packages/jsPDF/jspdf.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/jsPDF/libs/FileSaver.js/FileSaver.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/jsPDF/libs/Blob.js/BlobBuilder.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/jsPDF/jspdf.plugin.standard_fonts_metrics.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/jsPDF/jspdf.plugin.from_html.js"></script>-->
- <script language="javascript" type="text/javascript" src="/static/new/javascript/panelutil.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/javascript/chr_lod_chart.js"></script>
-<!-- <script language="javascript" type="text/javascript" src="/static/new/javascript/manhattan_plot.js"></script>-->
- <script language="javascript" type="text/javascript" src="/static/new/javascript/lod_chart.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/javascript/create_lodchart.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.dataTables.min.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/dataTables.scientific.js"></script>
- <script language="javascript" type="text/javascript" src="/static/packages/DT_bootstrap/DT_bootstrap.js"></script>
- <script language="javascript" type="text/javascript" src="/static/packages/TableTools/media/js/TableTools.min.js"></script>
- <script language="javascript" type="text/javascript" src="/static/packages/underscore/underscore-min.js"></script>
-
<script type="text/javascript" charset="utf-8">
$(document).ready( function () {
console.time("Creating table");
$('#qtl_results').dataTable( {
- //"sDom": "<<'span3'l><'span3'T><'span4'f>'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
- "sDom": "lTftipr",
- "oTableTools": {
- "aButtons": [
- "copy",
- "print",
- {
- "sExtends": "collection",
- "sButtonText": 'Save <span class="caret" />',
- "aButtons": [ "csv", "xls", "pdf" ]
- }
+ "columns": [
+ { "type": "natural", "bSortable": false },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" }
],
- "sSwfPath": "/static/packages/TableTools/media/swf/copy_csv_xls_pdf.swf"
- },
- "iDisplayLength": 50,
- "bLengthChange": true,
+ "buttons": [
+ 'csv'
+ ],
+ "sDom": "RZBtir",
+ "iDisplayLength": -1,
+ "autoWidth": true,
"bDeferRender": true,
- "bSortClasses": false
+ "bSortClasses": false,
+ "scrollY": "700px",
+ "scrollCollapse": true,
+ "paging": false
} );
console.timeEnd("Creating table");
+
});
</script>
-{% endblock %} \ No newline at end of file
+{% endblock %}
diff --git a/wqflask/wqflask/templates/new_security/login_user.html b/wqflask/wqflask/templates/new_security/login_user.html
index 81e8b53a..a66a85d6 100755
--- a/wqflask/wqflask/templates/new_security/login_user.html
+++ b/wqflask/wqflask/templates/new_security/login_user.html
@@ -24,18 +24,18 @@
<h4>Already have an account? Sign in here.</h4>
- <form class="form-horizontal" action="/n/login" method="POST" name="login_user_form">
+ <form class="form-horizontal" action="/n/login" method="POST" name="login_user_form" id="loginUserForm">
<fieldset>
<div class="form-group">
<label style="text-align:left;" class="col-xs-1 control-label" for="email_address">Email&nbsp;Address</label>
- <div style="margin-left:20px;" class="col-xs-10">
+ <div style="margin-left:20px;" class="col-xs-4">
<input id="email_address" class="focused" name="email_address" type="text" value="">
</div>
</div>
<div class="form-group">
<label style="text-align:left;" class="col-xs-1 control-label" for="password">Password</label>
- <div style="margin-left:20px;" class="col-xs-3 controls">
+ <div style="margin-left:20px;" class="col-xs-4 controls">
<input id="password" name="password" type="password" value="">
<br />
<a href="/n/forgot_password">Forgot your password?</a><br/>
@@ -45,14 +45,14 @@
<div class="form-group">
<label class="col-xs-1 control-label" for="remember"></label>
- <div style="margin-left:20px;" class="col-xs-3 controls">
+ <div style="margin-left:20px;" class="col-xs-4 controls">
<input id="remember" name="remember" type="checkbox" value="y"> <b>Remember me</b>
</div>
</div>
<div class="form-group">
<label class="col-xs-1 control-label" for="submit"></label>
- <div style="margin-left:20px;" class="col-xs-3 controls">
+ <div style="margin-left:20px;" class="col-xs-4 controls">
<input id="next" name="next" type="hidden" value="">
<input class="btn btn-primary" id="submit" name="submit" type="submit" value="Sign in">
</div>
@@ -66,9 +66,42 @@
{% endblock %}
+{% block css %}
+<style type="text/css">
+input.error{
+ border:1px solid #FF0000 !important;
+}
+
+label.error,div.error{
+ font-weight:normal;
+ color:#FF0000 !important;
+}
+</style>
+{% endblock %}
+
{% block js %}
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>-->
+ <script type="text/javascript" src="/static/new/packages/ValidationPlugin/dist/jquery.validate.min.js"></script>
+ <script>
+ $(document).ready(function () {
+ $("#loginUserForm").validate({
+ onkeyup: false,
+ onsubmit: true,
+ onfocusout: function(element) { $(element).valid(); },
+ rules: {
+ email_address: {
+ required: true,
+ email: true
+ },
+ password: {
+ required: true
+ }
+ }
+ });
+ });
+ </script>
+
{% include "new_security/_scripts.html" %}
{% endblock %}
diff --git a/wqflask/wqflask/templates/old_index_page.html b/wqflask/wqflask/templates/old_index_page.html
deleted file mode 100755
index db0b2d9e..00000000
--- a/wqflask/wqflask/templates/old_index_page.html
+++ /dev/null
@@ -1,320 +0,0 @@
-{% extends "base.html" %}
-{% block title %}GeneNetwork{% endblock %}
-{% block content %}
- <!-- Start of body -->
- <tr>
- <td bgcolor="#EEEEEE" class="solidBorder">
- <table width="100%" cellspacing="0" cellpadding="5">
- <tr>
- <td valign="top" width="40%" align="left" height="10" bgcolor="#EEEEEE">
- <p style="font-size:18px;font-family:verdana;color:black"><b>Select and
- Search</b></p>
-
- <form method="get" action="/search" class="form-search" name="SEARCHFORM">
- <table width="100%">
- <!-- SPECIES SELECTION -->
-
- <tr>
- <td align="right" height="35" style=
- "font-size:14px;font-family:verdana;color:black" width="16%">
- <b>Species:</b></td>
-
- <td width="3%"></td>
-
- <td nowrap width="85%" align="left">
- <div id="menu0">
- <select name="species" size="1" id="species" onchange=
- "fillOptions('species');">
- </select>
- </div>
- </td>
- </tr><!-- GROUP SELECTION -->
-
- <tr>
- <td align="right" height="35" style=
- "font-size:14px;font-family:verdana;color:black"><b>Group:</b></td>
-
- <td width="3%"></td>
-
- <td nowrap width="85%" align="left">
- <div id="menu1">
- <select name="cross" size="1" id="cross" onchange="fillOptions('cross');">
- </select> <input type="button" class="btn" value="Info" onclick=
- "javascript:crossinfo();">
- </div>
- </td>
- </tr><!-- TYPE SELECTION -->
-
- <tr>
- <td align="right" height="35" style=
- "font-size:14px;font-family:verdana;color:black"><b>Type:</b></td>
-
- <td width="3%"></td>
-
- <td nowrap width="85%" align="left">
- <div id="menu2">
- <select name="tissue" size="1" id="tissue" onchange=
- "fillOptions('tissue');">
- </select>
- </div>
- </td>
- </tr><!-- DATABASE SELECTION -->
-
- <tr>
- <td align="right" height="35" style=
- "font-size:14px;font-family:verdana;color:black"><b>Database:</b></td>
-
- <td width="3%"></td>
-
- <td nowrap width="85%" align="left">
- <div id="menu3">
- <select name="database" size="1" id="database">
- </select> <input type="submit" class="btn" value="Info" name=
- "info_database">
- </div>
- </td>
- </tr><!-- USER HELP -->
-
- <tr>
- <td align="right" height="20" width="10%"></td>
-
- <td width="3%"></td>
-
- <td align="left" width="85%">
- <p class="fs12">&nbsp;&nbsp;&nbsp;&nbsp;Databases marked with <b>**</b>
- suffix are not public yet.<br>
- &nbsp;&nbsp;&nbsp;&nbsp;Access requires <a href="/account.html" target=
- "_blank" class="fs14"><small>user login</small></a>.</p>
- </td>
- </tr><!-- GET ANY SEARCH -->
-
- <tr>
- <td align="right" height="35" nowrap="on" style=
- "font-size:14px;font-family:verdana;color:black" width="10%">
- <b>Search:</b></td>
-
- <td width="3%"></td>
-
- <td nowrap width="85%" align="left"><input class="input-medium search-query"
- id="tfor" name="search_terms" style=
- "width:420px; background-color:white; font-family:verdana; font-size:14px"
- type="text" maxlength="500"></td>
- </tr><!-- GET ANY HELP -->
-
- <tr>
- <td align="right" height="20" width="10%"></td>
-
- <td width="3%"></td>
-
- <td width="85%" align="left">
- <p class="fs12">&nbsp;&nbsp;&nbsp;&nbsp;Enter terms, genes, ID numbers in the
- <b>Search</b> field.<br>
- &nbsp;&nbsp;&nbsp;&nbsp;Use <b>*</b> or <b>?</b> wildcards (Cyp*a?,
- synap*).<br>
- &nbsp;&nbsp;&nbsp;&nbsp;Use <b>quotes</b> for terms such as <i>"tyrosine
- kinase"</i>.</p>
- </td>
- </tr><!-- SEARCH, MAKE DEFAULT, ADVANCED SEARCH -->
-
- <tr align="center">
- <td width="3%"></td>
-
- <td width="3%"></td>
-
- <td align="left" height="40" colspan="3"><input id="btsearch" type="submit"
- class="btn btn-primary" value="Search">&nbsp;&nbsp;&nbsp;&nbsp; <input type=
- "button" class="btn" value="Make Default" onclick=
- "setDefault(this.form);">&nbsp;&nbsp;&nbsp;&nbsp; <input type="button" class=
- "btn" value="Advanced Search" onclick=
- "javascript:window.open('/index3.html', '_self');"></td>
- </tr>
- </table><input type="hidden" name="FormID" value="searchResult"> <input type=
- "hidden" name="RISet" value="BXD"> <script src="/javascript/selectDatasetMenu.js"
- type="text/javascript">
-</script>
- </form><!-- QUICK HELP -->
-
- <p>&nbsp;______________________________________________________</p>
-
- <p style="font-size:13px;font-family:verdana;color:black"><b>&nbsp; Quick HELP
- Examples and</b> <a href="http://www.genenetwork.org/index4.html" target="_blank"
- class="fs14"><b>User's Guide</b></a></p>&nbsp;&nbsp;You can also use advanced
- commands. Copy these simple examples<br>
- &nbsp;&nbsp;into the <b>Get Any</b> or <b>Combined</b> search fields:
-
- <ul style="font-size:12px;font-family:verdana;color:black">
- <li><b><i>POSITION=(chr1 25 30)</i></b> finds genes, markers, or transcripts on
- chromosome 1 between 25 and 30 Mb.</li>
-
- <li><b><i>MEAN=(15 16) LRS=(23 46)</i></b> in the <b>Combined</b> field finds
- highly expressed genes (15 to 16 log2 units) AND with peak <a href=
- "http://www.genenetwork.org/glossary.html#L" target="_blank" class=
- "fs14"><small>LRS</small></a> linkage between 23 and 46.</li>
-
- <li><b><i>RIF=mitochondrial</i></b> searches RNA databases for <a href=
- "http://www.ncbi.nlm.nih.gov/projects/GeneRIF/GeneRIFhelp.html" target="_blank"
- class="fs14"><small>GeneRIF</small></a> links.</li>
-
- <li><b><i>WIKI=nicotine</i></b> searches <a href=
- "http://www.genenetwork.org/webqtl/main.py?FormID=geneWiki" target="_blank" class=
- "fs14"><small>GeneWiki</small></a> for genes that you or other users have annotated
- with the word <i>nicotine</i>.</li>
-
- <li><b><i>GO:0045202</i></b> searches for synapse-associated genes listed in the
- <a href="http://www.godatabase.org/cgi-bin/amigo/go.cgi" target="_blank" class=
- "fs14"><small>Gene Ontology</small></a>.</li>
-
- <li><b><i>GO:0045202 LRS=(9 99 Chr4 122 155) cisLRS=(9 999 10)</i></b><br>
- in <b>Combined</b> finds synapse-associated genes with <a href=
- "http://www.genenetwork.org/glossary.html#E" target="_blank" class=
- "fs14"><small>cis eQTL</small></a> on Chr 4 from 122 and 155 Mb with LRS scores
- between 9 and 999.</li>
-
- <li><b><i>RIF=diabetes LRS=(9 999 Chr2 100 105) transLRS=(9 999 10)</i></b><br>
- in <b>Combined</b> finds diabetes-associated transcripts with peak <a href=
- "http://www.genenetwork.org/glossary.html#E" target="_blank" class=
- "fs14"><small>trans eQTLs</small></a> on Chr 2 between 100 and 105 Mb with LRS
- scores between 9 and 999.</li>
- </ul>
- </td><!-- END OF FIND SELECTOR PULL-DOWN PANEL (LEFT SIDE) -->
- <!-- START OF TOP RIGHT PANEL -->
-
- <td valign="top" width="40%" bgcolor="#FFFFFF">
- <p style="font-size:15px;font-family:verdana;color:black"><b>Websites Affiliated with
- GeneNetwork</b></p>
-
- <p style="font-size:12px;font-family:verdana;color:black"></p>
-
- <ul>
- <li><a href="http://ucscbrowser.genenetwork.org/" target="_blank">Genome
- Browser</a> at UTHSC</li>
-
- <li><a href="http://galaxy.genenetwork.org/" target="_blank">Galaxy</a> at
- UTHSC</li>
-
- <li>GeneNetwork at <a href="http://ec2.genenetwork.org/" target="_blank">Amazon
- Cloud (EC2)</a></li>
-
- <li>GeneNetwork Source Codes at <a href=
- "http://sourceforge.net/projects/genenetwork/" target="_blank">SourceForge</a></li>
-
- <li>GeneNetwork Source Codes at <a href=
- "https://github.com/genenetwork/genenetwork" target="_blank">GitHub</a></li>
- </ul>
-
- <p>____________________________</p>
-
- <p style="font-size:15px;font-family:verdana;color:black"><b>Getting Started</b>
- &nbsp;&nbsp;</p>
-
- <ol style="font-size:12px;font-family:verdana;color:black">
- <li>Select <b>Species</b> (or select All)</li>
-
- <li>Select <b>Group</b> (a specific sample)</li>
-
- <li>Select <b>Type</b> of data:
-
- <ul>
- <li>Phenotype (traits)</li>
-
- <li>Genotype (markers)</li>
-
- <li>Expression (mRNAs)</li>
- </ul>
- </li>
-
- <li>Select a <b>Database</b></li>
-
- <li>Enter search terms in the <b>Get Any</b> or <b>Combined</b> field: words,
- genes, ID numbers, probes, advanced search commands</li>
-
- <li>Click on the <b>Search</b> button</li>
-
- <li>Optional: Use the <b>Make Default</b> button to save your preferences</li>
- </ol>
-
- <p>____________________________</p>
-
- <p style="font-size:14px;font-family:verdana;color:black"><b>How to Use
- GeneNetwork</b></p>
-
- <blockquote>
- <p style="font-size:12px;font-family:verdana;color:black">Take a 20-40 minute
- GeneNetwork <a href="http://www.genenetwork.org/tutorial/WebQTLTour/" target=
- "_blank" class="fs14"><small>Tour</small></a> that includes screen shots and
- typical steps in the analysis.</p>
- </blockquote>
-
- <blockquote>
- <p style="font-size:12px;font-family:verdana;color:black">For information about
- resources and methods, select the <img src=
- "http://www.genenetwork.org/images/upload/Info.png" alt="INFO" border="0" valign=
- "middle"> buttons.</p>
-
- <p style="font-size:12px;font-family:verdana;color:black">Try the <a href=
- "http://alexandria.uthsc.edu/" target="_blank" class=
- "fs14"><small>Workstation</small></a> site to explore data and features that are
- being implemented.</p>
-
- <p style="font-size:12px;font-family:verdana;color:black">Review the <a href=
- "/conditionsofUse.html" target="_blank" class="fs14"><small>Conditions</small></a>
- and <a href="/statusandContact.html" target="_blank" class=
- "fs14"><small>Contacts</small></a> pages for information on the status of data sets
- and advice on their use and citation.</p>
- </blockquote>
-
- <p style="font-size:14px;font-family:verdana;color:black"><b>Mirror and Development
- Sites</b></p>
-
- <ul>
- <li><a href="http://www.genenetwork.org/" target="_blank" style=
- "font-size:12px;font-family:verdana;color:blue">Main GN site at UTHSC</a> (main
- site)</li>
-
- <li><a href="http://www.genenetwork.waimr.uwa.edu.au/" target="_blank" style=
- "font-size:12px;font-family:verdana;color:blue">Australia at the UWA</a></li>
-
- <li><a href="http://gn.genetics.ucla.edu/" target="_blank" style=
- "font-size:12px;font-family:verdana;color:blue">California at UCLA</a></li>
-
- <li><a href="http://genenetwork.helmholtz-hzi.de/" target="_blank" style=
- "font-size:12px;font-family:verdana;color:blue">Germany at the HZI</a></li>
-
- <li><a href="https://genenetwork.hubrecht.eu/" target="_blank" style=
- "font-size:12px;font-family:verdana;color:blue">Netherlands at the Hubrecht</a>
- (Development)</li>
-
- <li><a href="http://genenetwork.memphis.edu/" target="_blank" style=
- "font-size:12px;font-family:verdana;color:blue">Memphis at the U of M</a></li>
-
- <li><a href="http://webqtl.bic.nus.edu.sg/" target="_blank" style=
- "font-size:12px;font-family:verdana;color:blue">Singapore at the NUS</a></li>
-
- <li><a href="http://genenetwork.epfl.ch/" target="_blank" style=
- "font-size:12px;font-family:verdana;color:blue">Switzerland at the EPFL</a></li>
- </ul>
-
- <p style="font-size:14px;font-family:verdana;color:black"><b>History and
- Archive</b></p>
-
- <blockquote>
- <p style="font-size:12px;font-family:verdana;color:black">GeneNetwork's <a href=
- "http://artemis.uthsc.edu" target="_blank" class="fs14"><small>Time
- Machine</small></a> links to earlier versions that correspond to specific
- publication dates.</p>
- </blockquote>
- </td>
- </tr>
- </table>
- </td>
- </tr>
- <!-- End of body -->
- <script src="/javascript/searchtip.js" type="text/javascript">
- </script>
- <script type="text/javascript">
- $(document).ready(function () {
- initialDatasetSelection();
- });
- </script>
-{% endblock %}
-
diff --git a/wqflask/wqflask/templates/pair_scan_results.html b/wqflask/wqflask/templates/pair_scan_results.html
index 869dabed..ab4a36bb 100644
--- a/wqflask/wqflask/templates/pair_scan_results.html
+++ b/wqflask/wqflask/templates/pair_scan_results.html
@@ -33,6 +33,28 @@
<h2>
Results
</h2>
+ <table cellpadding="0" cellspacing="0" border="0" id="pair_scan_results" class="table table-hover table-striped table-bordered">
+ <thead>
+ <tr>
+ <td>Index</td>
+ <td>Locus</td>
+ <td>Chr 1</td>
+ <td>Mb</td>
+ <td>Chr 2</td>
+ </tr>
+ </thead>
+ <tbody>
+ {% for marker in filtered_markers %}
+ <tr>
+ <td>{{loop.index}}</td>
+ <td>{{marker.name}}</td>
+ <td>{{marker.chr1}}</td>
+ <td>{{marker.Mb}}</td>
+ <td>{{marker.chr2}}</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
</div>
</div>
diff --git a/wqflask/wqflask/templates/search_error.html b/wqflask/wqflask/templates/search_error.html
new file mode 100644
index 00000000..22416580
--- /dev/null
+++ b/wqflask/wqflask/templates/search_error.html
@@ -0,0 +1,21 @@
+{% extends "base.html" %}
+{% block title %}Search Results{% endblock %}
+{% block css %}
+ <link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/css/jquery.dataTables.css" />
+ <link rel="stylesheet" type="text/css" href="/static/packages/DT_bootstrap/DT_bootstrap.css" />
+ <link rel="stylesheet" type="text/css" href="/static/packages/TableTools/media/css/TableTools.css" />
+{% endblock %}
+{% block content %}
+<!-- Start of body -->
+ {{ header("Error") }}
+
+ <div class="container">
+ <input type="hidden" name="uc_id" id="uc_id" value="{{ uc_id }}">
+ <p>You entered at least one incorrect search command.</p>
+ </div>
+
+ <div id="myModal"></div>
+
+<!-- End of body -->
+
+{% endblock %}
diff --git a/wqflask/wqflask/templates/search_result_page.html b/wqflask/wqflask/templates/search_result_page.html
index 731f6fbd..f29b907d 100755
--- a/wqflask/wqflask/templates/search_result_page.html
+++ b/wqflask/wqflask/templates/search_result_page.html
@@ -2,8 +2,9 @@
{% block title %}Search Results{% endblock %}
{% block css %}
<link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/css/jquery.dataTables.css" />
- <link rel="stylesheet" type="text/css" href="/static/packages/DT_bootstrap/DT_bootstrap.css" />
- <link rel="stylesheet" type="text/css" href="/static/packages/TableTools/media/css/TableTools.css" />
+ <link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/extensions/dataTables.fixedHeader.css" >
+ <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/fixedcolumns/3.0.4/css/dataTables.fixedColumns.css">
+ <link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/extensions/buttons.bootstrap.css" />
{% endblock %}
{% block content %}
<!-- Start of body -->
@@ -37,22 +38,38 @@
<p>To study a record, click on its ID below. Check records below and click Add button to add to selection.</p>
<div>
- <br />
- <button class="btn btn-default" id="select_all"><span class="glyphicon glyphicon-ok"></span> Select All</button>
- <button class="btn btn-default" id="deselect_all"><span class="glyphicon glyphicon-remove"></span> Deselect All</button>
- <button class="btn btn-default" id="invert"><span class="glyphicon glyphicon-resize-vertical"></span> Invert</button>
- <button class="btn btn-default" id="add"><span class="glyphicon glyphicon-plus-sign"></span> Add</button>
- <button class="btn btn-primary pull-right"><span class="glyphicon glyphicon-download"></span> Download Table</button>
- <br />
- <br />
- <table class="table table-hover table-striped" id='trait_table'>
+ <br />
+ <button class="btn btn-default" id="select_all"><span class="glyphicon glyphicon-ok"></span> Select All</button>
+ <button class="btn btn-default" id="deselect_all"><span class="glyphicon glyphicon-remove"></span> Deselect All</button>
+ <button class="btn btn-default" id="invert"><span class="glyphicon glyphicon-resize-vertical"></span> Invert</button>
+ <button class="btn btn-default" id="add" disabled><span class="glyphicon glyphicon-plus-sign"></span> Add</button>
+ <!--<button class="btn btn-default"><span class="glyphicon glyphicon-download"></span> Download Table</button>-->
+ <button id="redraw" class="btn btn-default">Reset Columns</button>
+ <input type="text" id="searchbox" class="form-control" style="width: 200px; display: inline;" placeholder="Search This Table For ...">
+ <input type="text" id="select_top" class="form-control" style="width: 200px; display: inline;" placeholder="Select Top ...">
+ <br />
+ <br />
+ {% if dataset.type == 'ProbeSet' %}
+ <button class="btn btn-default" id="open_options">Open Extra Options</button>
+ <br />
+ <br />
+ <div id="extra_options" style="display:none;">
+ Min LRS <input type="text" id="min" class="form-control" style="width: 60px; display: inline;">
+ Max LRS <input type="text" id="max" class="form-control" style="width: 60px; display: inline;">
+ </div>
+ <br />
+ <br />
+ {% endif %}
+ <div id="table_container">
+ <table class="table table-hover table-striped" id='trait_table' {% if dataset.type == 'Geno' %}width="400px"{% endif %} style="float: left;">
<thead>
<tr>
+ <th style="width: 30px;"></th>
{% for header in header_fields %}
{% if header == 'Max LRS' %}
- <th>{{header}}<a href="http://genenetwork.org//glossary.html#L" target="_blank"><sup style="color:#f00"> ?</sup></a></th>
+ <th style="text-align: right;">Max&nbsp;&nbsp;<br>LRS</th>
{% elif header == 'Additive Effect' %}
- <th>{{header}}<a href="http://genenetwork.org//glossary.html#A" target="_blank"><sup style="color:#f00"> ?</sup></a></th>
+ <th style="text-align: right;">Additive<br>Effect<a href="http://genenetwork.org//glossary.html#A" target="_blank"><sup style="color:#f00"> ?</sup></a></th>
{% else %}
<th>{{header}}</th>
{% endif %}
@@ -63,10 +80,9 @@
<tbody>
{% for this_trait in trait_list %}
<TR id="trait:{{ this_trait.name }}:{{ this_trait.dataset.name }}">
- <TD>
- <INPUT TYPE="checkbox" NAME="searchResult" class="checkbox trait_checkbox"
- VALUE="{{ data_hmac('{}:{}'.format(this_trait.name, this_trait.dataset.name)) }}">
+ <TD><INPUT TYPE="checkbox" NAME="searchResult" class="checkbox trait_checkbox" style="transform: scale(1.5);" VALUE="{{ data_hmac('{}:{}'.format(this_trait.name, this_trait.dataset.name)) }}">
</TD>
+ <TD align="right">{{ loop.index }}</TD>
<TD>
<a href="{{ url_for('show_trait_page',
trait_id = this_trait.name,
@@ -79,10 +95,10 @@
<TD>{{ this_trait.symbol }}</TD>
<TD>{{ this_trait.description_display }}</TD>
<TD>{{ this_trait.location_repr }}</TD>
- <TD>{{ this_trait.mean }}</TD>
- <TD align="right">{{ this_trait.LRS_score_repr }}</TD>
+ <TD align="right">{{ '%0.3f' % this_trait.mean|float }}</TD>
+ <TD align="right">{{ '%0.3f' % this_trait.LRS_score_repr|float }}</TD>
<TD>{{ this_trait.LRS_location_repr }}</TD>
- <TD>{{ this_trait.additive }}</TD>
+ <TD align="right">{{ '%0.3f' % this_trait.additive|float }}</TD>
{% elif dataset.type == 'Publish' %}
<TD>{{ this_trait.description_display }}</TD>
<TD>{{ this_trait.authors }}</TD>
@@ -93,7 +109,7 @@
</TD>
<TD>{{ this_trait.LRS_score_repr }}</TD>
<TD>{{ this_trait.LRS_location_repr }}</TD>
- <TD>{{ this_trait.additive }}</TD>
+ <TD>{{ '%0.3f' % this_trait.additive|float }}</TD>
{% elif dataset.type == 'Geno' %}
<TD>{{ this_trait.location_repr }}</TD>
{% endif %}
@@ -102,6 +118,7 @@
</tbody>
</table>
+ </div>
</div>
</div>
@@ -114,27 +131,80 @@
{% block js %}
<script type="text/javascript" src="/static/new/javascript/search_results.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.dataTables.min.js"></script>
+ <script language="javascript" type="text/javascript" src="https://cdn.datatables.net/1.10.8/js/jquery.dataTables.min.js"></script>
+ <script language="javascript" type="text/javascript" src="https://cdn.datatables.net/buttons/1.0.0/js/dataTables.buttons.min.js"></script>
+ <script language="javascript" type="text/javascript" src="https://cdn.datatables.net/buttons/1.0.0/js/buttons.html5.min.js"></script>
+ <script language="javascript" type="text/javascript" src="https://cdn.datatables.net/buttons/1.0.0/js/buttons.bootstrap.min.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/js_external/jszip.min.js"></script>
<script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/dataTables.naturalSort.js"></script>
- <script language="javascript" type="text/javascript" src="/static/packages/DT_bootstrap/DT_bootstrap.js"></script>
- <script language="javascript" type="text/javascript" src="/static/packages/TableTools/media/js/TableTools.min.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colResize.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colReorder.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.fixedHeader.js"></script>
+ <script language="javascript" type="text/javascript" src="//cdn.datatables.net/fixedcolumns/3.0.4/js/dataTables.fixedColumns.min.js"></script>
+
<script type="text/javascript" charset="utf-8">
function getValue(x) {
if (x.indexOf('input') >= 0) {
if ($(x).val() == 'x') {
- return 0
+ return 0;
}
else {
return parseFloat($(x).val());
}
}
+ else if (isNaN(x)) {
+ return x;
+ }
return parseFloat(x);
}
-
+
+
+ function filtering( oSettings, aData, iDataIndex, column) {
+ var iColumn = column;
+ if (document.getElementById('min').value){
+ var iMin = document.getElementById('min').value * 1;
+ } else {
+ var iMin = 0
+ }
+ if (document.getElementById('max').value){
+ var iMax = document.getElementById('max').value * 1;
+ } else {
+ var iMax = 10000
+ }
+
+ var iVersion = aData[iColumn] == "-" ? 0 : aData[iColumn]*1;
+ if ( iMin === "" && iMax === "" )
+ {
+ return true;
+ }
+ else if ( iMin === "" && iVersion < iMax )
+ {
+ return true;
+ }
+ else if ( iMin < iVersion && "" === iMax )
+ {
+ return true;
+ }
+ else if ( iMin < iVersion && iVersion < iMax )
+ {
+ return true;
+ }
+ return false;
+ }
+
jQuery.fn.dataTableExt.oSort['cust-txt-asc'] = function (a, b) {
var x = getValue(a);
- var y = getValue(b);
- return ((x < y) ? -1 : ((x > y) ? 1 : 0));
+ var y = getValue(b);
+
+ if (x == 'N/A' || x == '') {
+ return 1;
+ }
+ else if (y == 'N/A' || y == '') {
+ return -1;
+ }
+ else {
+ return ((x < y) ? -1 : ((x > y) ? 1 : 0));
+ }
};
jQuery.fn.dataTableExt.oSort['cust-txt-desc'] = function (a, b) {
@@ -154,74 +224,95 @@
console.time("Creating table");
{% if dataset.type == 'ProbeSet' %}
- $('#trait_table').dataTable( {
- //"sDom": "<<'span3'l><'span3'T><'span4'f>'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
- "aoColumns": [
- { "bSortable": false },
- { "sType": "natural" },
- { "sType": "natural" },
- { "sType": "natural",
- "sWidth": "35%" },
- { "sType": "natural",
- "sWidth": "15%" },
- { "sType": "cust-txt" },
- { "sType": "natural",
- "sWidth": "12%" },
- { "sType": "natural",
- "sWidth": "15%" },
- { "sType": "cust-txt" }
- ],
+ $('#trait_table').DataTable( {
"columns": [
- { "width": "50%" },
- null,
- null,
- null,
- null,
- null,
- null
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural", "width": "40%" },
+ { "type": "natural", "width": "15%" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural", "width": "15%" },
+ { "type": "natural" }
+ ],
+ "order": [[1, "asc" ]],
+ "buttons": [
+ 'csv'
],
- "sDom": "tir",
+ "sDom": "RZBtir",
"iDisplayLength": -1,
- "autoWidth": true,
- "bLengthChange": true,
"bDeferRender": true,
- "bSortClasses": false
+ "bSortClasses": false,
+ "scrollY": "700px",
+ "scrollCollapse": false,
+ "paging": false
} );
{% elif dataset.type == 'Publish' %}
- $('#trait_table').dataTable( {
- //"sDom": "<<'span3'l><'span3'T><'span4'f>'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
- "aoColumns": [
- { "bSortable": false },
- { "sType": "natural" },
- { "sType": "natural",
- "sWidth": "35%" },
- { "sType": "natural",
- "sWidth": "20%" },
- { "sType": "natural" },
- { "sType": "cust-txt" },
- { "sType": "natural" }
+ $('#trait_table').DataTable( {
+ "columns": [
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural", "width": "15%"},
+ { "type": "natural" }
],
+ "order": [[1, "asc" ]],
+ "buttons": [
+ 'csv'
+ ],
+ "sDom": "RZBtir",
+ "iDisplayLength": -1,
+ "autoWidth": false,
+ "bDeferRender": true,
+ "bSortClasses": false,
+ "scrollY": "700px",
+ "scrollCollapse": false,
+ "paging": false
+ } );
+ {% elif dataset.type == 'Geno' %}
+ $('#trait_table').DataTable( {
"columns": [
- { "width": "50%" },
- null,
- null,
- null,
- null,
- null,
- null
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "natural", "width": "40%"}
],
- "sDom": "tir",
+ "order": [[1, "asc" ]],
+ "buttons": [
+ 'csv'
+ ],
+ "sDom": "RZBtir",
"iDisplayLength": -1,
"autoWidth": true,
- "bLengthChange": true,
"bDeferRender": true,
- "bSortClasses": false
+ "bSortClasses": false,
+ "scrollY": "700px",
+ "scrollCollapse": false,
+ "paging": false
} );
{% endif %}
console.timeEnd("Creating table");
+
+ var table = $('#trait_table').DataTable();
+ $('#redraw').click(function() {
+ var table = $('#trait_table').DataTable();
+ table.colReorder.reset()
+ });
+
+ $('#min').keyup( function() { table.draw(); } );
+ $('#max').keyup( function() { table.draw(); } );
+
+ $('#open_options').click( function () {
+ $('#extra_options').toggle();
+ });
+
});
-
</script>
-
{% endblock %}
diff --git a/wqflask/wqflask/templates/show_trait.html b/wqflask/wqflask/templates/show_trait.html
index a1723ef8..a86a149d 100755
--- a/wqflask/wqflask/templates/show_trait.html
+++ b/wqflask/wqflask/templates/show_trait.html
@@ -5,21 +5,32 @@
<link rel="stylesheet" type="text/css" href="/static/new/css/show_trait.css" />
<link rel="stylesheet" type="text/css" href="/static/new/css/bar_chart.css" />
<link rel="stylesheet" type="text/css" href="/static/new/css/box_plot.css" />
+ <link rel="stylesheet" type="text/css" href="/static/new/css/prob_plot.css" />
<link rel="stylesheet" type="text/css" href="/static/new/css/panelutil.css" />
<link rel="stylesheet" type="text/css" href="/static/new/css/scatter-matrix.css" />
<link rel="stylesheet" type="text/css" href="/static/new/css/d3-tip.min.css" />
+ <link rel="stylesheet" type="text/css" href="/static/new/packages/nvd3/nv.d3.min.css" />
<link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/css/jquery.dataTables.css" />
+ <link rel="stylesheet" type="text/css" href="/static/new/packages/DataTables/extensions/buttons.bootstrap.css" />
+ <link rel="stylesheet" type="text/css" href="/static/new/packages/noUiSlider/nouislider.css" />
+ <link rel="stylesheet" type="text/css" href="/static/new/packages/noUiSlider/nouislider.pips.css" />
<link rel="stylesheet" type="text/css" href="/static/packages/DT_bootstrap/DT_bootstrap.css" />
+
{% endblock %}
{% block content %} <!-- Start of body -->
- {{ header("{}".format(this_trait.symbol),
- '{}: {}'.format(this_trait.name, this_trait.description_fmt)) }}
+ {% if this_trait.dataset.type != 'Geno' %}
+ {{ header("{}".format(this_trait.name_header_fmt),
+ '{}: {}'.format(this_trait.name, this_trait.description_fmt)) }}
+ {% else %}
+ {{ header("{}".format(this_trait.name_header_fmt)) }}
+ {% endif %}
<form method="post" action="/corr_compute" name="trait_page" id="trait_data_form"
class="form-horizontal">
<div id="hidden_inputs">
+ <input type="hidden" name="trait_hmac" value="{{ data_hmac('{}:{}'.format(this_trait.name, dataset.name)) }}">
{% for key in hddn %}
<input type="hidden" name="{{ key }}" value="{{ hddn[key] }}">
{% endfor %}
@@ -28,21 +39,13 @@
<input type="hidden" name="temp_uuid" id="temp_uuid" value="{{ temp_uuid }}">
<div class="container">
- <div class="page-header">
- <h1>{{ dataset.group.species.capitalize() }} -
- {{ dataset.group.name }} -
- {{ this_trait.symbol }}
- </h1>
- </div>
{% include 'show_trait_details.html' %}
<div class="panel-group" id="accordion">
<div class="panel panel-default">
- <div class="panel-heading">
+ <div class="panel-heading" data-toggle="collapse" data-parent="#accordion" data-target="#collapseOne">
<h3 class="panel-title">
- <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
- <span class="glyphicon glyphicon-chevron-down"></span> Statistics
- </a>
+ <span class="glyphicon glyphicon-chevron-down"></span> Statistics
</h3>
</div>
<div id="collapseOne" class="panel-collapse collapse in">
@@ -52,11 +55,9 @@
</div>
</div>
<div class="panel panel-default">
- <div class="panel-heading">
+ <div class="panel-heading" data-toggle="collapse" data-parent="#accordion" data-target="#collapseTwo">
<h3 class="panel-title">
- <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
- <span class="glyphicon glyphicon-chevron-down"></span> Calculate Correlations
- </a>
+ <span class="glyphicon glyphicon-chevron-down"></span> Calculate Correlations
</h3>
</div>
<div id="collapseTwo" class="panel-collapse collapse in">
@@ -66,25 +67,22 @@
</div>
</div>
<div class="panel panel-default">
- <div class="panel-heading">
+ <div class="panel-heading" data-toggle="collapse" data-parent="#accordion" data-target="#collapseThree">
<h3 class="panel-title">
- <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
- <span class="glyphicon glyphicon-chevron-down"></span> Mapping Tools
- </a>
+ <span class="glyphicon glyphicon-chevron-down"></span> Mapping Tools
</h3>
</div>
<div id="collapseThree" class="panel-collapse collapse in">
<div class="panel-body">
{% include 'show_trait_mapping_tools.html' %}
</div>
+ <div id="alert_placeholder"></div>
</div>
</div>
<div class="panel panel-default">
- <div class="panel-heading">
+ <div class="panel-heading" data-toggle="collapse" data-parent="#accordion" data-target="#collapseFour" aria-expanded="true">
<h3 class="panel-title">
- <a data-toggle="collapse" data-parent="#accordion" href="#collapseFour" aria-expanded="true">
- <span class="glyphicon glyphicon-chevron-up"></span> Review and Edit Data
- </a>
+ <span class="glyphicon glyphicon-chevron-up"></span> Review and Edit Data
</h3>
</div>
<div id="collapseFour" class="panel-collapse collapse" aria-expanded="true">
@@ -110,9 +108,12 @@
</script>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
+ <script type="text/javascript" src="/static/new/packages/nvd3/nv.d3.js"></script>
<script type="text/javascript" src="/static/new/js_external/underscore-min.js"></script>
<script type="text/javascript" src="/static/new/js_external/underscore.string.min.js"></script>
<script type="text/javascript" src="/static/new/js_external/d3-tip.min.js"></script>
+ <script type="text/javascript" src="/static/new/js_external/jstat.min.js"></script>
+ <script type="text/javascript" src="/static/new/js_external/shapiro-wilk.js"></script>
<script type="text/javascript" src="/static/new/javascript/colorbrewer.js"></script>
<script type="text/javascript" src="/static/new/packages/ValidationPlugin/dist/jquery.validate.min.js"></script>
<script type="text/javascript" src="/static/new/javascript/panelutil.js"></script>
@@ -131,18 +132,30 @@
<script type="text/javascript" src="/static/new/javascript/show_trait.js"></script>
<script type="text/javascript" src="/static/new/javascript/get_traits_from_collection.js"></script>
<script type="text/javascript" src="/static/new/javascript/validation.js"></script>
-
- <script language="javascript" type="text/javascript" src="/static/packages/bootstrap/js/bootstrap.min.js"></script>
- <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.dataTables.min.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/jsPDF/libs/FileSaver.js/FileSaver.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/jsPDF/libs/Blob.js/BlobBuilder.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/jsPDF/jspdf.plugin.standard_fonts_metrics.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/jsPDF/jspdf.plugin.from_html.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/javascript/chr_lod_chart.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/javascript/create_lodchart.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/javascript/lod_chart.js"></script>
+
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/jquery.dataTables.js"></script>
+ <script language="javascript" type="text/javascript" src="https://cdn.datatables.net/buttons/1.0.0/js/dataTables.buttons.min.js"></script>
+ <script language="javascript" type="text/javascript" src="https://cdn.datatables.net/buttons/1.0.0/js/buttons.html5.min.js"></script>
+ <script language="javascript" type="text/javascript" src="https://cdn.datatables.net/buttons/1.0.0/js/buttons.bootstrap.min.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/js_external/jszip.min.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/dataTables.scientific.js"></script>
<script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/js/dataTables.naturalSort.js"></script>
- <script language="javascript" type="text/javascript" src="/static/packages/DT_bootstrap/DT_bootstrap.js"></script>
- <script language="javascript" type="text/javascript" src="/static/packages/TableTools/media/js/TableTools.min.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colResize.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/DataTables/extensions/dataTables.colReorder.js"></script>
+ <script language="javascript" type="text/javascript" src="/static/new/packages/noUiSlider/nouislider.js"></script>
<script type="text/javascript" charset="utf-8">
function getValue(x) {
if (x.indexOf('input') >= 0) {
if ($(x).val() == 'x') {
- return 0
+ return 'x'
}
else {
return parseFloat($(x).val());
@@ -160,12 +173,21 @@
jQuery.fn.dataTableExt.oSort['cust-txt-desc'] = function (a, b) {
var x = getValue(a);
var y = getValue(b);
- return ((x < y) ? 1 : ((x > y) ? -1 : 0));
+
+ if (x == 'x') {
+ return 1;
+ }
+ else if (y == 'x') {
+ return -1;
+ }
+ else {
+ return ((x < y) ? 1 : ((x > y) ? -1 : 0));
+ }
};
$(document).ready( function () {
- $('.panel-heading').find('a').click(function () {
+ $('.panel-heading').click(function () {
if ($(this).hasClass('collapsed')){
$(this).find('.glyphicon-chevron-down').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
}
@@ -175,70 +197,127 @@
});
console.time("Creating table");
-
- {% if sample_groups[0].se_exists() %}
- $('#samples_primary, #samples_other').find("tr.outlier").css('background-color', 'yellow')
- $('#samples_primary, #samples_other').dataTable( {
- //"sDom": "<<'span3'l><'span3'T><'span4'f>'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
- "aoColumns": [
- { "sType": "natural" },
- null,
- { "sType": "cust-txt" },
- { "bSortable": false },
- { "sType": "cust-txt" }
+
+ $('#samples_primary, #samples_other').find("tr.outlier").css('background-color', 'yellow')
+ {% if sample_groups[0].se_exists() %}
+ $('#samples_primary, #samples_other').DataTable( {
+ "columns": [
+ { "bSortable": false },
+ { "type": "natural" },
+ { "type": "natural" },
+ { "type": "cust-txt" },
+ { "bSortable": false },
+ { "type": "cust-txt" }
],
- "sDom": "ftr",
- "oTableTools": {
- "aButtons": [
- "copy",
- "print",
- {
- "sExtends": "collection",
- "sButtonText": 'Save <span class="caret" />',
- "aButtons": [ "csv", "xls", "pdf" ]
- }
- ],
- "sSwfPath": "/static/packages/TableTools/media/swf/copy_csv_xls_pdf.swf"
- },
- "bPaginate": false,
- "bLengthChange": true,
- "bDeferRender": true,
- "bSortClasses": false
- } );
- console.timeEnd("Creating table");
+ "buttons": [
+ 'csv'
+ ],
+ "sDom": "RZBtr",
+ "iDisplayLength": -1,
+ "autoWidth": false,
+ "bLengthChange": true,
+ "bDeferRender": true,
+ "bSortClasses": false,
+ "scrollY": "600px",
+ "scrollCollapse": false,
+ "colResize": {
+ "tableWidthFixed": false
+ },
+ "paging": false
+ } );
+ console.timeEnd("Creating table");
{% else %}
-
-
- console.time("Creating table");
+ console.time("Creating table");
- $('#samples_primary, #samples_other').dataTable( {
- //"sDom": "<<'span3'l><'span3'T><'span4'f>'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
- "aoColumns": [
- { "sType": "natural" },
- null,
- { "sType": "cust-txt" }
+ $('#samples_primary, #samples_other').DataTable( {
+ "columns": [
+ { "bSortable": false },
+ { "type": "natural" },
+ null,
+ { "type": "cust-txt" }
+ ],
+ "buttons": [
+ 'csv'
+ ],
+ "sDom": "RZBtr",
+ "iDisplayLength": -1,
+ "autoWidth": false,
+ "bLengthChange": true,
+ "bDeferRender": true,
+ "bSortClasses": false,
+ "scrollY": "600px",
+ "scrollCollapse": false,
+ "colResize": {
+ "tableWidthFixed": false
+ },
+ "paging": false
+ } );
+ {% endif %}
+
+ console.log("SAMPLE GROUP TYPES:", js_data.sample_group_types)
+ if (Object.keys(js_data.sample_group_types).length > 1) {
+ $('#stats_table').DataTable( {
+ "columns": [
+ { "bSortable": false },
+ { "bSortable": false },
+ { "bSortable": false },
+ { "bSortable": false }
],
- "sDom": "ftr",
- "oTableTools": {
- "aButtons": [
- "copy",
- "print",
- {
- "sExtends": "collection",
- "sButtonText": 'Save <span class="caret" />',
- "aButtons": [ "csv", "xls", "pdf" ]
- }
- ],
- "sSwfPath": "/static/packages/TableTools/media/swf/copy_csv_xls_pdf.swf"
+ "sDom": "RZtr",
+ "iDisplayLength": -1,
+ "autoWidth": false,
+ "bLengthChange": true,
+ "bDeferRender": true,
+ "bSortClasses": false,
+ "colResize": {
+ "tableWidthFixed": false
},
- "bPaginate": false,
+ "paging": false
+ } );
+ }
+ else {
+ $('#stats_table').DataTable( {
+ "columns": [
+ { "bSortable": false },
+ { "bSortable": false }
+ ],
+ "sDom": "RZtr",
+ "iDisplayLength": -1,
+ "autoWidth": false,
"bLengthChange": true,
"bDeferRender": true,
- "bSortClasses": false
+ "bSortClasses": false,
+ "colResize": {
+ "tableWidthFixed": false
+ },
+ "paging": false
} );
- console.timeEnd("Creating table");
- {% endif %}
+
+ }
+
+ var slider = document.getElementById('p_range_slider');
+ noUiSlider.create(slider, {
+ start: [-1.0, 1.0],
+ range: {
+ 'min': [-1.0],
+ 'max': [1.0]
+ }
+ });
+
+ var slider_display = [
+ document.getElementById('p_range_lower'),
+ document.getElementById('p_range_upper')
+ ];
+ var slider_values = [
+ $('input[name=p_range_lower]'),
+ $('input[name=p_range_upper]')
+ ];
+
+ slider.noUiSlider.on('update', function( values, handle ) {
+ slider_display[handle].innerHTML = values[handle];
+ slider_values[handle].val(values[handle]);
+ });
});
</script>
diff --git a/wqflask/wqflask/templates/show_trait_calculate_correlations.html b/wqflask/wqflask/templates/show_trait_calculate_correlations.html
index f02d1705..68cc8b18 100755
--- a/wqflask/wqflask/templates/show_trait_calculate_correlations.html
+++ b/wqflask/wqflask/templates/show_trait_calculate_correlations.html
@@ -72,6 +72,34 @@
</select>
</div>
</div>
+ {% if this_trait.dataset.type == 'ProbeSet' %}
+ <div class="form-group">
+ <label class="col-xs-1 control-label">Min Expr</label>
+ <div class="col-xs-2 controls">
+ <input name="min_expr" value="" type="text" class="form-control" style="width: 50px;">
+ </div>
+ </div>
+ <div class="form-group">
+ <label class="col-xs-1 control-label">Location</label>
+ <div class="col-xs-4 controls">
+ <span>
+ Chr: <input name="loc_chr" value="" type="text" class="form-control" style="width: 50px; display: inline;">&nbsp;&nbsp;&nbsp;
+ Mb: <input name="min_loc_mb" value="" type="text" class="form-control" style="width: 50px; display: inline;"> &nbsp;to&nbsp; <input name="max_loc_mb" value="" type="text" class="form-control" style="width: 50px; display: inline;">
+ </span>
+ <br>
+ </div>
+ </div>
+ {% endif %}
+ <div class="form-group">
+ <label class="col-xs-1 control-label">Range</label>
+ <div class="col-xs-3 controls">
+ <input name="p_range_lower" value="" type="hidden">
+ <input name="p_range_upper" value="" type="hidden">
+ <div id="p_range_slider" ></div>
+ <span style="font: 400 12px Arial; color: #888; display: block; margin: 15px 0;" id="p_range_lower"></span>
+ <span style="font: 400 12px Arial; color: #888; display: block; margin: 15px 0;" id="p_range_upper"></span>
+ </div>
+ </div>
<div class="form-group">
<label for="corr_sample_method" class="col-xs-1 control-label"></label>
diff --git a/wqflask/wqflask/templates/show_trait_details.html b/wqflask/wqflask/templates/show_trait_details.html
index 0afac1f7..cdaa919e 100755
--- a/wqflask/wqflask/templates/show_trait_details.html
+++ b/wqflask/wqflask/templates/show_trait_details.html
@@ -1,9 +1,19 @@
<dl class="dl-horizontal">
+ <dt>Species</dt>
+ <dd>{{ this_trait.dataset.group.species }}</dd>
+ <dt>Group</dt>
+ <dd>{{ this_trait.dataset.group.name }}</dd>
+ <dt>Tissue</dt>
+ <dd>{{ this_trait.dataset.tissue }}</dd>
+ {% if this_trait.dataset.type == 'ProbeSet' %}
<dt>Aliases</dt>
<dd>{{ this_trait.alias_fmt }}</dd>
+ {% endif %}
+ {% if this_trait.dataset.type != 'Publish' %}
<dt>Location</dt>
<dd>{{ this_trait.location_fmt }}</dd>
+ {% endif %}
<dt>Database</dt>
<dd>
@@ -16,7 +26,7 @@
<dt>
<a href="/blatInfo.html" target="_blank"
title="Values higher than 2 for the specificity are good">
- BLAT Specifity
+ BLAT Specificity
</a>
</dt>
<dd>{{ "%0.3f" | format(this_trait.probe_set_specificity|float) }}</dd>
@@ -25,42 +35,87 @@
<dt>BLAT Score</dt>
<dd>{{ "%0.3f" | format(this_trait.probe_set_blat_score|float) }}</dd>
{% endif %}
+ <dt>Resource Links</dt>
+ {% if this_trait.dataset.type == 'ProbeSet' %}
+ <dd>
+ {% if this_trait.geneid != None %}
+ <a href="http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=gene&cmd=Retrieve&dopt=Graphics&list_uids={{ this_trait.geneid }}" target="_blank" title="Info from NCBI Entrez Gene">
+ Gene
+ </a>
+ &nbsp;&nbsp;
+ {% endif %}
+ {% if this_trait.omim != None %}
+ <a href="http://www.ncbi.nlm.nih.gov/omim/{{ this_trait.omim }}" target="_blank" title="Summary from On Mendelion Inheritance in Man">
+ OMIM
+ </a>
+ &nbsp;&nbsp;
+ {% endif %}
+ {% if this_trait.genbankid != None %}
+ <a href="http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=Nucleotide&cmd=search&doptcmdl=DocSum&term={{ this_trait.genbankid }}" target="_blank" title="Find the original GenBank sequence used to design the probes">
+ GenBank
+ </a>
+ &nbsp;&nbsp;
+ {% endif %}
+ {% if this_trait.symbol != None %}
+ <a href="http://www.genotation.org/Getd2g.pl?gene_list={{ this_trait.symbol }}" target="_blank" title="Related descriptive, genomic, clinical, functional and drug-therapy information">
+ Genotation
+ </a>
+ &nbsp;&nbsp;
+ {% endif %}
+ </dd>
+ {% endif %}
</dl>
-
-<!--<div class="btn-toolbar">
+<div style="margin-bottom:15px;" class="btn-toolbar">
<div class="btn-group">
- <button class="btn btn-primary" title="Add to collection">
+ <a href="#redirect">
+ <button type="button" id="add_to_collection" class="btn btn-primary" title="Add to collection">
<i class="icon-plus-sign icon-white"></i> Add
</button>
-
- <button class="btn" title="Find similar expression data">
+ </a>
+ {% if this_trait.dataset.type == 'ProbeSet' %}
+ {% if this_trait.symbol != None %}
+ <a href="#redirect" onclick="window.open('http://www.genenetwork.org/webqtl/main.py?cmd=sch&amp;gene={{ this_trait.symbol }}&amp;alias=1&amp;species={{ species_name }}')">
+ <button type="button" class="btn btn-default" title="Find similar expression data">
<i class="icon-search"></i> Find
</button>
-
- <button class="btn" title="Check probe locations at UCSC">
+ </a>
+ {% endif %}
+ {% if UCSC_BLAT_URL != "" %}
+ <a href="#redirect" onclick="window.open('{{ UCSC_BLAT_URL }}')">
+ <button type="button" class="btn btn-default" title="Check probe locations at UCSC">
<i class="icon-ok"></i> Verify
</button>
- </div>
-
- <div class="btn-group">
-
- <button class="btn" title="Write or review comments about this gene">
+ </a>
+ {% endif %}
+ {% if this_trait.symbol != None %}
+ <a href="#redirect" onclick="window.open('http://genenetwork.org/webqtl/main.py?FormID=geneWiki&symbol={{ this_trait.symbol }}')">
+ <button type="button" class="btn btn-default" title="Write or review comments about this gene">
<i class="icon-edit"></i> GeneWiki
</button>
-
- <button class="btn" title="View SNPs and Indels">
+ </a>
+ <a href="#redirect" onclick="window.open('http://genenetwork.org/webqtl/main.py?FormID=SnpBrowserResultPage&submitStatus=1&diffAlleles=True&customStrain=True&geneName={{ this_trait.symbol }}')">
+ <button type="button" class="btn btn-default" title="View SNPs and Indels">
<i class="icon-road"></i> SNPs
</button>
-
- <button class="btn" title="View probes, SNPs, and RNA-seq at UTHSC">
+ </a>
+ {% endif %}
+ {% if UTHSC_BLAT_URL != "" %}
+ <a href="#redirect" onclick="window.open('{{ UTHSC_BLAT_URL }}')">
+ <button type="button" class="btn btn-default" title="View probes, SNPs, and RNA-seq at UTHSC">
<i class="icon-eye-close"></i> RNA-seq
</button>
-
- <button class="btn" title="Check sequence of probes">
+ </a>
+ {% endif %}
+ {% if show_probes == "True" %}
+ <a href="#redirect" onclick="window.open('http://genenetwork.org/webqtl/main.py?FormID=showProbeInfo&database={{ this_trait.dataset.name }}&ProbeSetID={{ this_trait.name }}&CellID={{ this_trait.cellid }}&RISet={{ dataset.group.name }}&incparentsf1=ON')">
+ <button type="button" class="btn btn-default" title="Check sequence of probes">
<i class="icon-list"></i> Probes
</button>
-
+ </a>
+ {% endif %}
+ {% endif %}
</div>
-</div>-->
+</div>
+
diff --git a/wqflask/wqflask/templates/show_trait_edit_data.html b/wqflask/wqflask/templates/show_trait_edit_data.html
index 12a6a48e..d39df976 100755
--- a/wqflask/wqflask/templates/show_trait_edit_data.html
+++ b/wqflask/wqflask/templates/show_trait_edit_data.html
@@ -14,10 +14,10 @@
<input type="text" id="remove_samples_field">
<select id="block_group" size="1">
<option value="primary">
- {{ sample_group_types['primary_only'] }}
+ {{ sample_group_types['samples_primary'] }}
</option>
<option value="other">
- {{ sample_group_types['other_only'] }}
+ {{ sample_group_types['samples_other'] }}
</option>
</select>
<input type="button" id="block_by_index" class="btn" value="Block">
@@ -44,11 +44,11 @@
{% endif %}
<br>
<div>
- <input type="button" id="hide_no_value" class="btn" value="Hide No Value">
- <input type="button" id="block_outliers" class="btn" value="Block Outliers">
- <input type="button" id="reset" class="btn btn-inverse" value="Reset">
+ <input type="button" id="hide_no_value" class="btn btn-default" value="Hide No Value">
+ <input type="button" id="block_outliers" class="btn btn-default" value="Block Outliers">
+ <input type="button" id="reset" class="btn btn-primary" value="Reset">
<span class="input-append">
- <input type="button" id="export" class="btn" value="Export">
+ <input type="button" id="export" class="btn btn-default" value="Export">
<select id="export_format" class="select optional span2">
<option value="excel">Excel</option>
<option value="csv">CSV</option>
@@ -73,39 +73,35 @@
<br>
- <div id="edit_sample_lists">
+ <!--<div id="edit_sample_lists">-->
{% for sample_type in sample_groups %}
- <div>
+ <div class="sample_group" style="width:50%;">
<h3>{{ sample_type.header }}</h3>
- <table cellpadding="0" cellspacing="0" border="0" class="table table-hover table-striped table-bordered"
- id="samples_{{ sample_type.sample_group_type }}">
+ <table class="table-hover table-striped" id="samples_{{ sample_type.sample_group_type }}" style="float: left;">
<thead>
<tr>
- <td>Index</td>
- <td>Sample</td>
- <td>Value</td>
+ <th></th>
+ <th>Index</th>
+ <th>Sample</th>
+ <th>Value</th>
{% if sample_type.se_exists() %}
- <td>&nbsp;</td>
- <td>SE</td>
+ <th>&nbsp;</th>
+ <th>SE</th>
{% endif %}
{% for attribute in sample_type.attributes|sort() %}
- <td>
+ <th>
{{ sample_type.attributes[attribute].name }}
- </td>
+ </th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for sample in sample_type.sample_list %}
<tr class="{{ sample.class_outlier }} value_se" id="{{ sample.this_id }}">
- <td class="column_name-Index">
- {{ loop.index }}
- <input type="checkbox" name="selectCheck"
- class="checkbox edit_sample_checkbox"
- value="{{ sample.name }}" checked="checked">
+ <td class="column_name-"><input type="checkbox" name="selectCheck" class="checkbox edit_sample_checkbox" style="transform: scale(1.5);" value="{{ sample.name }}" checked="checked">
</td>
-
+ <td class="column_name-Index" align="right">{{ loop.index }}</td>
<td class="column_name-Sample">
<span class="edit_sample_sample_name">
{{ sample.name }}
@@ -150,7 +146,7 @@
</table>
</div>
{% endfor %}
- </div>
+ <!--</div>-->
<input type="hidden" name="Default_Name">
diff --git a/wqflask/wqflask/templates/show_trait_mapping_tools.html b/wqflask/wqflask/templates/show_trait_mapping_tools.html
index 426a5c5d..de25f4ee 100755
--- a/wqflask/wqflask/templates/show_trait_mapping_tools.html
+++ b/wqflask/wqflask/templates/show_trait_mapping_tools.html
@@ -1,18 +1,21 @@
<div>
- <div class="col-xs-6">
+ {% if (use_pylmm_rqtl and dataset.group.species != "human") or use_plink_gemma %}
+ <div class="col-xs-4">
<div class="tabbable"> <!-- Only required for left/right tabs -->
<ul class="nav nav-pills">
+ {% if use_pylmm_rqtl and not use_plink_gemma and dataset.group.species != "human" %}
<li class="active">
- <a href="#interval_mapping" data-toggle="tab">Interval Mapping</a>
+ <a href="#pylmm" data-toggle="tab">pyLMM</a>
</li>
<li>
- <a href="#pylmm" data-toggle="tab">pyLMM</a>
+ <a href="#rqtl_geno" data-toggle="tab">R/qtl</a>
</li>
<li>
- <a href="#rqtl_geno" data-toggle="tab">rqtl</a>
+ <a href="#interval_mapping" data-toggle="tab">Interval Mapping</a>
</li>
- {% if dataset.group.species == 'human' %}
+ {% endif %}
+ {% if use_plink_gemma %}
<li>
<a href="#plink" data-toggle="tab">PLINK</a>
</li>
@@ -26,81 +29,38 @@
</ul>
<div class="tab-content">
- <div class="tab-pane active" id="interval_mapping">
- <div style="padding: 20px" class="form-horizontal">
- <div class="mapping_method_fields form-group">
- <label for="mapping_permutations" class="col-xs-2 control-label">Permutations</label>
- <div style="margin-left: 20px;" class="col-xs-4 controls">
- <input name="num_perm_reaper" value="2000" type="text" class="form-control">
- </div>
- </div>
-
- <div class="mapping_method_fields form-group">
- <label for="mapping_bootstraps" class="col-xs-2 control-label" title="Bootstrapping Resamples">Bootstrap</label>
- <div style="margin-left: 20px;" class="col-xs-4 controls">
- <input name="mapping_bootstraps" value="2000" type="text" class="form-control">
- </div>
- </div>
-
- <div class="mapping_method_fields form-group">
- <label style="text-align:left;" class="col-xs-12 control-label">Display Additive Effect</label>
- <div class="col-xs-12 controls" id="display_additive_effect">
- <label class="radio-inline">
- <input type="radio" name="display_additive" id="display_additive" value="yes" checked="">
- Yes
- </label>
- <label class="radio-inline">
- <input type="radio" name="display_additive" id="display_additive" value="no">
- No
- </label>
- </div>
- </div>
-
+ {% if use_pylmm_rqtl and not use_plink_gemma and dataset.group.species != "human" %}
+ <div class="tab-pane active" id="pylmm">
+ <div style="margin-top: 20px" class="form-horizontal">
<div class="mapping_method_fields form-group">
- <label style="text-align:left;" class="col-xs-12 control-label">Manhattan Plot</label>
- <div class="col-xs-12 controls">
- <label class="radio-inline">
- <input type="radio" name="manhattan_plot_reaper" value="true">
- Yes
- </label>
- <label class="radio-inline">
- <input type="radio" name="manhattan_plot_reaper" value="false" checked="">
- No
- </label>
- </div>
- </div>
- <div class="form-group">
- <div style="padding-left:15px;" class="controls">
- <button id="interval_mapping_compute" class="btn submit_special btn-primary" data-url="/interval_mapping" title="Compute Interval Mapping">
- <i class="icon-ok-circle icon-white"></i> Open Mapping Tool
- </button>
- </div>
- </div>
- </div>
- </div>
-
- <div class="tab-pane" id="pylmm">
-
- <div style="padding: 20px" class="form-horizontal">
- <div class="mapping_method_fields form-group">
- <label for="mapping_permutations" class="col-xs-2 control-label">Permutations</label>
+ <label for="mapping_permutations" class="col-xs-3 control-label">Permutations</label>
<div style="margin-left: 20px;" class="col-xs-4 controls">
- <input name="num_pylmm" value="2000" type="text" class="form-control">
+ <input name="num_perm_pylmm" value="" type="text" class="form-control">
</div>
</div>
<div id="permutations_alert" class="alert alert-error alert-warning" style="display:none;">
Please be aware that permutations can take a very long time (~20 minutes for 500 permutations)
</div>
+<!--
<div class="mapping_method_fields form-group">
- <label for="control_for" class="col-xs-2 control-label">Control&nbsp;for</label>
+ <label for="control_for" class="col-xs-3 control-label">Control&nbsp;for</label>
<div style="margin-left: 20px;" class="col-xs-4 controls">
{% if dataset.type == 'ProbeSet' and this_trait.locus_chr != "" %}
- <input name="control_pylmm" value="{{ nearest_marker1+","+nearest_marker2 }}" type="text" />
+ <input name="control_pylmm" value="{{ nearest_marker }}" type="text" />
{% else %}
<input name="control_pylmm" value="" type="text" />
{% endif %}
+ <label class="radio-inline">
+ <input type="radio" name="do_control_pylmm" value="true">
+ Yes
+ </label>
+ <label class="radio-inline">
+ <input type="radio" name="do_control_pylmm" value="false" checked="">
+ No
+ </label>
</div>
</div>
+-->
<div class="mapping_method_fields form-group">
<label style="text-align:left;" class="col-xs-12 control-label">Manhattan Plot</label>
@@ -117,8 +77,8 @@
</div>
<div class="form-group">
<div style="padding-left:15px;" class="controls">
- <button id="pylmm_compute" class="btn submit_special btn-primary" data-url="/marker_regression" title="Compute Marker Regression">
- <i class="icon-ok-circle icon-white"></i> Open Mapping Tool
+ <button id="pylmm_compute" class="btn submit_special btn-primary" title="Compute Marker Regression">
+ <i class="icon-ok-circle icon-white"></i> Compute
</button>
</div>
</div>
@@ -126,29 +86,37 @@
</div>
<div class="tab-pane" id="rqtl_geno">
- <div style="padding: 20px" class="form-horizontal">
+ <div style="margin-top: 20px" class="form-horizontal">
<div class="mapping_method_fields form-group">
- <label for="mapping_permutations" class="col-xs-2 control-label">Permutations</label>
+ <label for="mapping_permutations" class="col-xs-3 control-label">Permutations</label>
<div style="margin-left: 20px;" class="col-xs-4 controls">
- <input name="num_perm_rqtl_geno" value="2000" type="text" class="form-control">
+ <input name="num_perm_rqtl_geno" value="" type="text" class="form-control">
</div>
</div>
<div id="permutations_alert" class="alert alert-error alert-warning" style="display:none;">
Please be aware that permutations can take a very long time (~20 minutes for 500 permutations)
</div>
<div class="mapping_method_fields form-group">
- <label for="control_for" class="col-xs-2 control-label">Control&nbsp;for</label>
+ <label for="control_for" class="col-xs-3 control-label">Control&nbsp;for</label>
<div style="margin-left: 20px;" class="col-xs-4 controls">
{% if dataset.type == 'ProbeSet' and this_trait.locus_chr != "" %}
- <input name="control_rqtl_geno" value="{{ nearest_marker1+","+nearest_marker2 }}" type="text" style="width: 160px;" class="form-control" />
+ <input name="control_rqtl_geno" value="{{ nearest_marker }}" type="text" style="width: 160px;" class="form-control" />
{% else %}
<input name="control_rqtl_geno" value="" type="text" class="form-control" />
{% endif %}
+ <label class="radio-inline">
+ <input type="radio" name="do_control_rqtl" value="true">
+ Yes
+ </label>
+ <label class="radio-inline">
+ <input type="radio" name="do_control_rqtl" value="false" checked="">
+ No
+ </label>
</div>
</div>
<div class="mapping_method_fields form-group">
- <label for="mapmethod_rqtl_geno" style="text-align:left;" class="col-xs-2 control-label">Method</label>
+ <label for="mapmethod_rqtl_geno" style="text-align:left;" class="col-xs-3 control-label">Method</label>
<div class="col-xs-4 controls">
<select name="mapmethod_rqtl_geno" class="form-control">
<option value="em">em</option>
@@ -163,7 +131,7 @@
</div>
<div class="mapping_method_fields form-group">
- <label for="mapmodel_rqtl_geno" style="text-align:left;" class="col-xs-2 control-label">Model</label>
+ <label for="mapmodel_rqtl_geno" style="text-align:left;" class="col-xs-3 control-label">Model</label>
<div class="col-xs-4 controls">
<select name="mapmodel_rqtl_geno" class="form-control">
<option value="normal">normal</option>
@@ -205,28 +173,82 @@
<div class="form-group">
<div style="padding-left:15px;" class="controls">
<button id="rqtl_geno_compute" class="btn submit_special btn-primary" data-url="/marker_regression" title="Compute Marker Regression">
- <i class="icon-ok-circle icon-white"></i> Open Mapping Tool
+ <i class="icon-ok-circle icon-white"></i> Compute
</button>
</div>
</div>
</div>
</div>
-
- {% if dataset.group.species == 'human' %}
+ <div class="tab-pane" id="interval_mapping">
+ <div style="margin-top: 20px" class="form-horizontal">
+ <div class="mapping_method_fields form-group">
+ <label for="mapping_permutations" class="col-xs-3 control-label">Permutations</label>
+ <div style="margin-left: 20px;" class="col-xs-4 controls">
+ <input name="num_perm_reaper" value="2000" type="text" class="form-control">
+ </div>
+ </div>
+<!--
+ <div class="mapping_method_fields form-group">
+ <label for="mapping_bootstraps" class="col-xs-3 control-label" title="Bootstrapping Resamples">Bootstrap</label>
+ <div style="margin-left: 20px;" class="col-xs-4 controls">
+ <input name="mapping_bootstraps" value="2000" type="text" class="form-control">
+ </div>
+ </div>
+
+ <div class="mapping_method_fields form-group">
+ <label style="text-align:left;" class="col-xs-12 control-label">Display Additive Effect</label>
+ <div class="col-xs-12 controls" id="display_additive_effect">
+ <label class="radio-inline">
+ <input type="radio" name="display_additive" id="display_additive" value="yes" checked="">
+ Yes
+ </label>
+ <label class="radio-inline">
+ <input type="radio" name="display_additive" id="display_additive" value="no">
+ No
+ </label>
+ </div>
+ </div>
+-->
+
+ <div class="mapping_method_fields form-group">
+ <label style="text-align:left;" class="col-xs-12 control-label">Manhattan Plot</label>
+ <div class="col-xs-12 controls">
+ <label class="radio-inline">
+ <input type="radio" name="manhattan_plot_reaper" value="true">
+ Yes
+ </label>
+ <label class="radio-inline">
+ <input type="radio" name="manhattan_plot_reaper" value="false" checked="">
+ No
+ </label>
+ </div>
+ </div>
+ <div class="form-group">
+ <div style="padding-left:15px;" class="controls">
+ <button id="interval_mapping_compute" class="btn submit_special btn-primary" data-url="/interval_mapping" title="Compute Interval Mapping">
+ <i class="icon-ok-circle icon-white"></i> Compute
+ </button>
+ </div>
+ </div>
+ <!--<div id="alert_placeholder"></div>-->
+ </div>
+ </div>
+ {% endif %}
+ {% if use_plink_gemma %}
<div class="tab-pane" id="plink">
<div style="padding: 20px" class="form-horizontal">
<div class="mapping_method_fields form-group">
<label for="maf_plink" class="col-xs-2 control-label">Minor allele threshold</label>
- <div style="margin-left: 20px;" class="col-xs-1 controls">
+ <div style="margin-left: 20px;" class="col-xs-2 controls">
<input name="maf_plink" value="0.01" type="text" class="form-control">
</div>
</div>
</div>
<div class="form-group">
- <label for="gemma_compute" class="col-xs-1 control-label"></label>
+ <label for="plink_compute" class="col-xs-1 control-label"></label>
<div style="margin-left:20px;" class="col-xs-4 controls">
- <button id="gemma_compute" class="btn submit_special btn-primary" data-url="/marker_regression" title="Compute Marker Regression">
+ <button id="plink_compute" class="btn submit_special btn-primary" data-url="/marker_regression" title="Compute Marker Regression">
Compute
</button>
</div>
@@ -237,16 +259,16 @@
<div style="padding: 20px" class="form-horizontal">
<div class="mapping_method_fields form-group">
<label for="maf_gemma" class="col-xs-2 control-label">Minor allele threshold</label>
- <div style="margin-left: 20px;" class="col-xs-1 controls">
+ <div style="margin-left: 20px;" class="col-xs-2 controls">
<input name="maf_gemma" value="0.01" type="text" class="form-control">
</div>
</div>
</div>
<div class="form-group">
- <label for="plink_compute" class="col-xs-1 control-label"></label>
+ <label for="gemma_compute" class="col-xs-1 control-label"></label>
<div style="margin-left:20px;" class="col-xs-4 controls">
- <button id="plink_compute" class="btn submit_special btn-primary" data-url="/marker_regression" title="Compute Marker Regression">
+ <button id="gemma_compute" class="btn submit_special btn-primary" data-url="/marker_regression" title="Compute Marker Regression">
Compute
</button>
</div>
@@ -266,8 +288,10 @@
<dd>R/qtl is an extensible, interactive environment for mapping quantitative trait loci (QTL) in experimental crosses.</dd>
</dl>
</div>
- <div id="alert_placeholder"></div>
<div id="mapping_result_holder_wrapper" style="display:none;">
<div id="mapping_result_holder"></div>
</div>
+ {% else %}
+ Mapping options are disabled for data not matched with genotypes.
+ {% endif %}
</div>
diff --git a/wqflask/wqflask/templates/show_trait_progress_bar.html b/wqflask/wqflask/templates/show_trait_progress_bar.html
index 99906338..f9a34070 100755
--- a/wqflask/wqflask/templates/show_trait_progress_bar.html
+++ b/wqflask/wqflask/templates/show_trait_progress_bar.html
@@ -32,17 +32,4 @@
</div>
</div>
</div>
-</div>
-
-<!--<div id="static_progress_bar_container" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="progress_bar" aria-hidden="true">
- <div class="modal-header">
- <h3 id="progress_bar">Loading... (Estimated time ~10-15m)</h3>
- </div>
- <div class="modal-body">
- <div class="progress progress-striped active">
- <div id="marker_regression_progress" class="bar" style="width: 100%"></div>
- </div>
- <div id="time_remaining">
- </div>
- </div>
-</div>--> \ No newline at end of file
+</div> \ No newline at end of file
diff --git a/wqflask/wqflask/templates/show_trait_statistics_new.html b/wqflask/wqflask/templates/show_trait_statistics_new.html
index f2ebbbef..1932d968 100755
--- a/wqflask/wqflask/templates/show_trait_statistics_new.html
+++ b/wqflask/wqflask/templates/show_trait_statistics_new.html
@@ -24,15 +24,13 @@
<div class="tab-content">
<div class="tab-pane active" id="stats_tab">
<div style="padding: 20px" class="form-horizontal">
- <div class="well">
- <h3>Stats</h3>
- <table id="stats_table" class="table table-hover"></table>
- </div>
+ <table id="stats_table" style="width: 300px; float: left;" class="table table-hover table-striped"></table>
+
</div>
</div>
<div class="tab-pane" id="histogram_tab">
<div style="padding: 20px" class="form-horizontal">
- {% if sample_groups|length == 1 %}
+ {% if sample_groups|length != 1 %}
<select class="histogram_samples_group">
{% for group, pretty_group in sample_group_types.items() %}
<option value="{{ group }}">{{ pretty_group }}</option>
@@ -47,7 +45,7 @@
</div>
<div class="tab-pane" id="bar_chart_tab">
<div style="padding: 20px" class="form-horizontal">
- {% if sample_groups|length == 1 %}
+ {% if sample_groups|length != 1 %}
<select class="bar_chart_samples_group">
{% for group, pretty_group in sample_group_types.items() %}
<option value="{{ group }}">{{ pretty_group }}</option>
@@ -73,38 +71,48 @@
<i class="icon-signal"></i> Sort By Value
</button>
</div>
+ {% if g.user_session.user_ob %}
<div class="btn-group">
<button type="button" class="btn btn-default" id="color_by_trait">
<i class="icon-tint"></i> Color by Trait
</button>
</div>
+ {% endif %}
</div>
- <div class="row" style="height: 0px">
- <div id="bar_chart_legend" style="margin-left: 900px; margin-top:50px; positive: relative;">
+ <div class="row" style="position:relative">
+ <div id="bar_chart_legend" style="margin-left: 150px; margin-top:20px; position: absolute;">
<span id="legend-left"></span>
- <span id="legend-colors">
- <!--
- <svg height="10" width="90">
- <rect x="0" width="15" height="10" style="fill: rgb(0, 0, 0);"></rect>
- <rect x="15" width="15" height="10" style="fill: rgb(50, 0, 0);"></rect>
- <rect x="30" width="15" height="10" style="fill: rgb(100, 0, 0);"></rect>
- <rect x="45" width="15" height="10" style="fill: rgb(150, 0, 0);"></rect>
- <rect x="60" width="15" height="10" style="fill: rgb(200, 0, 0);"></rect>
- <rect x="75" width="15" height="10" style="fill: rgb(255, 0, 0);"></rect>
- </svg>
- -->
- </span>
+ <span id="legend-colors"></span>
<span id="legend-right"></span>
</div>
</div>
<div style="margin-left: 20px; margin-right: 20px;" class="row" id="bar_chart_container">
- <div id="bar_chart" class="barchart"></div>
+ <svg></svg>
</div>
</div>
<div class="tab-pane" id="probability_plot">
- <div id="probability_plot_container">
- <div id="prob_plot" class="qtlcharts"></div>
+ <div style="padding: 20px" class="form-horizontal">
+ {% if sample_groups|length != 1 %}
+ <select class="prob_plot_samples_group">
+ {% for group, pretty_group in sample_group_types.items() %}
+ <option value="{{ group }}">{{ pretty_group }}</option>
+ {% endfor %}
+ </select>
+ <br><br>
+ {% endif %}
+
+ <div id="prob_plot_container">
+ <div id="prob_plot_title"></div>
+ <svg></svg>
+ </div>
+
+ <div>
+ More about <a href="http://en.wikipedia.org/wiki/Normal_probability_plot" target="_blank">Normal Probability Plots</a> and more
+ about interpreting these plots from the <a href="/glossary.html#normal_probability" target="_blank">glossary</a></td>
+ </div>
+
</div>
+
</div>
<!-- <div class="tab-pane" id="box_plot_tab">
{% if sample_groups|length > 1 %}
@@ -140,4 +148,4 @@
<div id="collections_holder"></div>
</div>
-</div> \ No newline at end of file
+</div>
diff --git a/wqflask/wqflask/templates/wgcna_results.html b/wqflask/wqflask/templates/wgcna_results.html
new file mode 100644
index 00000000..0dc030b1
--- /dev/null
+++ b/wqflask/wqflask/templates/wgcna_results.html
@@ -0,0 +1,76 @@
+{% extends "base.html" %}
+{% block title %}WCGNA results{% endblock %}
+
+{% block content %} <!-- Start of body -->
+ <div class="container">
+ <h1>WGCNA Results</h1>
+ Analysis found {{results['nmod']}} modules when scanning {{results['nphe']}} phenotypes, measured on {{results['nstr']}} strains.<br>
+ Additional parameters settings:
+ <ul>
+ <li>Soft thresholds checked = {{results['requestform']['SoftThresholds']}}</li>
+ <li>Power used for this analysis = {{results['Power']}}</li>
+ <li>TomType = {{results['requestform']['TOMtype']}}</li>
+ <li>Minimum module size = {{results['requestform']['MinModuleSize'] }}</li>
+ <li>mergeCutHeight = {{results['requestform']['mergeCutHeight'] }}</li>
+ </ul>
+
+ <h3>Soft threshold table</h3>
+ <table width="80%">
+ <tr><th>Power</th><th>SFT.R.sq</th><th>slope</th><th>truncated.R.sq</th><th>mean.k</th><th>median.k</th><th>max.k</th><th>Analysis</th></tr>
+ {% for r in range(powers[0][0]|length) %}
+ {% if powers[0][1][r] > 0.85 %}
+ <tr style="color: #00ff00;">
+ {% elif powers[0][1][r] > 0.75 %}
+ <tr style="color: #aaaa00;">
+ {% else %}
+ <tr style="color: #ff0000;">
+ {% endif %}
+ {% for c in range(powers[0]|length) %}
+ <td>{{powers[0][c][r]|round(3)}}</td>
+ {% endfor %}
+ <td style="color: #000000;">
+ {% if powers[0][1][r] > 0.75 %}
+ <input type="submit" value="Redo use power = {{powers[0][0][r]}}" /></td>
+ {% endif %}
+ </tr>
+ {% endfor %}
+ </table>
+ <h3>WGCNA module plot</h3>
+ <a href="/tmp/{{ results['imgurl'] }}">
+ <img alt="Embedded Image" src="data:image/png;base64,
+ {% for elem in results['imgdata'] -%}
+ {% print("%c"|format(elem)) %}
+ {%- endfor %}
+ " /></a>
+
+
+ <h3>Phenotype / Module table</h3>
+ <table width="80%">
+ <tr><th>Phenotype</th><th>Module</th></tr>
+ {% for r in range(results['nphe']) %}
+ <tr>
+ <td>{{results['phenotypes'][r][0]}}</td>
+ <td>{{results['network'][0][r]}}</td>
+ </tr>
+ {% endfor %}
+ </table>
+
+ <h3>Module eigen genes</h3>
+ <table width="80%">
+ <tr><th>Phenotype</th>
+ {% for m in range(results['nmod']) %}
+ <th><input type="submit" value="Add module {{m}} to collection" /></th>
+ {% endfor %}
+ </tr>
+ {% for r in range(results['nstr']) %}
+ <tr>
+ <td>{{results['strains'][r][0]}}</td>
+ {% for m in range(results['nmod']) %}
+ <td>{{results['network'][2][m][r]}}</td>
+ {% endfor %}
+ </tr>
+ {% endfor %}
+ </table>
+ </div>
+{% endblock %}
+
diff --git a/wqflask/wqflask/templates/wgcna_setup.html b/wqflask/wqflask/templates/wgcna_setup.html
new file mode 100644
index 00000000..49181938
--- /dev/null
+++ b/wqflask/wqflask/templates/wgcna_setup.html
@@ -0,0 +1,28 @@
+{% extends "base.html" %}
+{% block title %}WCGNA analysis{% endblock %}
+
+{% block content %} <!-- Start of body -->
+<form action="/wgcna_results" method="post">
+ <div class="container">
+
+ <h1>WGCNA analysis parameters</h1>
+ {% if request.form['trait_list'].split(",")|length <= 4 %}
+
+ <h2 style="color: #ff0000;">ERROR: Too few phenotypes as input</h2>
+ Please make sure you select enough phenotypes / genes to perform WGCNA,
+ your collection needs to contain at least 4 different phenotypes. You provided {{request.form['trait_list'].split(',')|length}} phenotypes as input
+
+ {% else %}
+ <input type="hidden" name="trait_list" id="trait_list" value= "{{request.form['trait_list']}}">
+ <table>
+ <tr><td>Soft threshold:</td><td><input type="text" class="form-inline" name="SoftThresholds" id="SoftThresholds" value="1,2,3,4,5,6,7,8,9"></td></tr>
+ <tr><td>Minimum module size:</td><td><input type="text" class="form-inline" name="MinModuleSize" id="MinModuleSize" value="30"></td></tr>
+ <tr><td>TOMtype:</td><td><input type="text" class="form-inline" name="TOMtype" id="TOMtype" value="unsigned"></td></tr>
+ <tr><td>mergeCutHeight:</td><td><input type="text" class="form-inline" name="mergeCutHeight" id="mergeCutHeight" value="0.25"></td></tr>
+ </table>
+ <input type="submit" class="btn btn-primary" value="Run WGCNA using these settings" />
+ {% endif %}
+ </div>
+</form>
+{% endblock %}
+
diff --git a/wqflask/wqflask/views.py b/wqflask/wqflask/views.py
index 39004f07..dc199ab2 100755
--- a/wqflask/wqflask/views.py
+++ b/wqflask/wqflask/views.py
@@ -5,6 +5,7 @@ import sys
print("sys.path is:", sys.path)
import csv
+import xlsxwriter
import StringIO # Todo: Use cStringIO?
import gc
@@ -32,6 +33,7 @@ from flask import (render_template, request, make_response, Response,
Flask, g, config, jsonify, redirect, url_for)
from wqflask import search_results
+from wqflask import gsearch
from wqflask import docs
from wqflask import news
from base.data_set import DataSet # Used by YAML in marker_regression
@@ -44,6 +46,9 @@ from wqflask.interval_mapping import interval_mapping
from wqflask.correlation import show_corr_results
from wqflask.correlation_matrix import show_corr_matrix
from wqflask.correlation import corr_scatter_plot
+
+from wqflask.wgcna import wgcna_analysis
+
from utility import temp_data
from base import webqtlFormData
@@ -91,7 +96,7 @@ def tmp_page(img_path):
print("img_path:", img_path)
initial_start_vars = request.form
print("initial_start_vars:", initial_start_vars)
- imgfile = open('/home/zas1024/tmp/' + img_path, 'rb')
+ imgfile = open(webqtlConfig.TMPDIR + img_path, 'rb')
imgdata = imgfile.read()
imgB64 = imgdata.encode("base64")
bytesarray = array.array('B', imgB64)
@@ -127,7 +132,7 @@ def search_page():
else:
return render_template("data_sharing.html", **template_vars.__dict__)
else:
- key = "search_results:v1:" + json.dumps(request.args, sort_keys=True)
+ key = "search_results:v2:" + json.dumps(request.args, sort_keys=True)
print("key is:", pf(key))
with Bench("Loading cache"):
result = Redis.get(key)
@@ -148,9 +153,20 @@ def search_page():
if result['quick']:
return render_template("quick_search.html", **result)
- else:
+ elif result['search_term_exists']:
return render_template("search_result_page.html", **result)
-
+ else:
+ return render_template("search_error.html")
+
+@app.route("/gsearch", methods=('GET',))
+def gsearchact():
+ result = gsearch.GSearch(request.args).__dict__
+ type = request.args['type']
+ if type == "gene":
+ return render_template("gsearch_gene.html", **result)
+ elif type == "phenotype":
+ return render_template("gsearch_pheno.html", **result)
+
@app.route("/docedit")
def docedit():
doc = docs.Docs(request.args['entry'])
@@ -161,6 +177,20 @@ def help():
doc = docs.Docs("help")
return render_template("docs.html", **doc.__dict__)
+@app.route("/wgcna_setup", methods=('POST',))
+def wcgna_setup():
+ print("In wgcna, request.form is:", request.form) # We are going to get additional user input for the analysis
+ return render_template("wgcna_setup.html", **request.form) # Display them using the template
+
+@app.route("/wgcna_results", methods=('POST',))
+def wcgna_results():
+ print("In wgcna, request.form is:", request.form)
+ wgcna = wgcna_analysis.WGCNA() # Start R, load the package and pointers and create the analysis
+ wgcnaA = wgcna.run_analysis(request.form) # Start the analysis, a wgcnaA object should be a separate long running thread
+ result = wgcna.process_results(wgcnaA) # After the analysis is finished store the result
+ return render_template("wgcna_results.html", **result) # Display them using the template
+
+
@app.route("/news")
def news_route():
newsobject = news.News()
@@ -186,7 +216,7 @@ def environments():
doc = docs.Docs("environments")
return render_template("docs.html", **doc.__dict__)
-@app.route('/export_trait_csv', methods=('POST',))
+@app.route('/export_trait_excel', methods=('POST',))
def export_trait_excel():
"""Excel file consisting of the sample data from the trait data and analysis page"""
print("In export_trait_excel")
@@ -196,15 +226,18 @@ def export_trait_excel():
print("sample_data - type: %s -- size: %s" % (type(sample_data), len(sample_data)))
buff = StringIO.StringIO()
- writer = csv.writer(buff)
- for row in sample_data:
- writer.writerow(row)
- csv_data = buff.getvalue()
+ workbook = xlsxwriter.Workbook(buff, {'in_memory': True})
+ worksheet = workbook.add_worksheet()
+ for i, row in enumerate(sample_data):
+ worksheet.write(i, 0, row[0])
+ worksheet.write(i, 1, row[1])
+ workbook.close()
+ excel_data = buff.getvalue()
buff.close()
- return Response(csv_data,
- mimetype='text/csv',
- headers={"Content-Disposition":"attachment;filename=test.csv"})
+ return Response(excel_data,
+ mimetype='application/vnd.ms-excel',
+ headers={"Content-Disposition":"attachment;filename=test.xlsx"})
@app.route('/export_trait_csv', methods=('POST',))
def export_trait_csv():
@@ -250,40 +283,49 @@ def heatmap_page():
start_vars = request.form
temp_uuid = uuid.uuid4()
- version = "v5"
- key = "heatmap:{}:".format(version) + json.dumps(start_vars, sort_keys=True)
- print("key is:", pf(key))
- with Bench("Loading cache"):
- result = Redis.get(key)
+ traits = [trait.strip() for trait in start_vars['trait_list'].split(',')]
+ if traits[0] != "":
+ version = "v5"
+ key = "heatmap:{}:".format(version) + json.dumps(start_vars, sort_keys=True)
+ print("key is:", pf(key))
+ with Bench("Loading cache"):
+ result = Redis.get(key)
- if result:
- print("Cache hit!!!")
- with Bench("Loading results"):
- result = pickle.loads(result)
+ if result:
+ print("Cache hit!!!")
+ with Bench("Loading results"):
+ result = pickle.loads(result)
- else:
- print("Cache miss!!!")
+ else:
+ print("Cache miss!!!")
- template_vars = heatmap.Heatmap(request.form, temp_uuid)
- template_vars.js_data = json.dumps(template_vars.js_data,
- default=json_default_handler,
- indent=" ")
+ template_vars = heatmap.Heatmap(request.form, temp_uuid)
+ template_vars.js_data = json.dumps(template_vars.js_data,
+ default=json_default_handler,
+ indent=" ")
- result = template_vars.__dict__
-
- for item in template_vars.__dict__.keys():
- print(" ---**--- {}: {}".format(type(template_vars.__dict__[item]), item))
-
- pickled_result = pickle.dumps(result, pickle.HIGHEST_PROTOCOL)
- print("pickled result length:", len(pickled_result))
- Redis.set(key, pickled_result)
- Redis.expire(key, 60*60)
+ result = template_vars.__dict__
+
+ for item in template_vars.__dict__.keys():
+ print(" ---**--- {}: {}".format(type(template_vars.__dict__[item]), item))
- with Bench("Rendering template"):
- rendered_template = render_template("heatmap.html", **result)
+ pickled_result = pickle.dumps(result, pickle.HIGHEST_PROTOCOL)
+ print("pickled result length:", len(pickled_result))
+ Redis.set(key, pickled_result)
+ Redis.expire(key, 60*60)
+ with Bench("Rendering template"):
+ rendered_template = render_template("heatmap.html", **result)
+
+ else:
+ rendered_template = render_template("empty_collection.html", **{'tool':'Heatmap'})
+
return rendered_template
+@app.route("/mapping_results_container")
+def mapping_results_container_page():
+ return render_template("mapping_results_container.html")
+
@app.route("/marker_regression", methods=('POST',))
def marker_regression_page():
initial_start_vars = request.form
@@ -298,17 +340,18 @@ def marker_regression_page():
'manhattan_plot',
'control_marker',
'control_marker_db',
+ 'do_control',
'pair_scan',
'mapmethod_rqtl_geno',
'mapmodel_rqtl_geno'
)
- print("Random Print too see if it is running:", initial_start_vars)
+ print("Marker regression called with initial_start_vars:", initial_start_vars)
start_vars = {}
for key, value in initial_start_vars.iteritems():
if key in wanted or key.startswith(('value:')):
start_vars[key] = value
- version = "v4"
+ version = "v3"
key = "marker_regression:{}:".format(version) + json.dumps(start_vars, sort_keys=True)
print("key is:", pf(key))
with Bench("Loading cache"):
@@ -369,7 +412,7 @@ def export():
svg_xml = request.form.get("data", "Invalid data")
filename = request.form.get("filename", "manhattan_plot_snp")
response = Response(svg_xml, mimetype="image/svg+xml")
- response.headers["Content-Disposition"] = "attchment; filename=%s"%filename
+ response.headers["Content-Disposition"] = "attachment; filename=%s"%filename
return response
@app.route("/export_pdf", methods = ('POST',))
@@ -382,7 +425,7 @@ def export_pdf():
filepath = "/home/zas1024/gene/wqflask/output/"+filename
pdf_file = cairosvg.svg2pdf(bytestring=svg_xml)
response = Response(pdf_file, mimetype="application/pdf")
- response.headers["Content-Disposition"] = "attchment; filename=%s"%filename
+ response.headers["Content-Disposition"] = "attachment; filename=%s"%filename
return response
@app.route("/interval_mapping", methods=('POST',))
@@ -435,7 +478,7 @@ def interval_mapping_page():
Redis.expire(key, 60*60)
with Bench("Rendering template"):
- rendered_template = render_template("interval_mapping.html", **result)
+ rendered_template = render_template("marker_regression.html", **result)
return rendered_template
@@ -449,12 +492,18 @@ def corr_compute_page():
@app.route("/corr_matrix", methods=('POST',))
def corr_matrix_page():
print("In corr_matrix, request.form is:", pf(request.form))
- template_vars = show_corr_matrix.CorrelationMatrix(request.form)
- template_vars.js_data = json.dumps(template_vars.js_data,
- default=json_default_handler,
- indent=" ")
+
+ start_vars = request.form
+ traits = [trait.strip() for trait in start_vars['trait_list'].split(',')]
+ if traits[0] != "":
+ template_vars = show_corr_matrix.CorrelationMatrix(start_vars)
+ template_vars.js_data = json.dumps(template_vars.js_data,
+ default=json_default_handler,
+ indent=" ")
- return render_template("correlation_matrix.html", **template_vars.__dict__)
+ return render_template("correlation_matrix.html", **template_vars.__dict__)
+ else:
+ return render_template("empty_collection.html", **{'tool':'Correlation Matrix'})
@app.route("/corr_scatter_plot")
def corr_scatter_plot_page():
diff --git a/wqflask/wqflask/wgcna/__init__.py b/wqflask/wqflask/wgcna/__init__.py
new file mode 100755
index 00000000..e69de29b
--- /dev/null
+++ b/wqflask/wqflask/wgcna/__init__.py
diff --git a/wqflask/wqflask/wgcna/wgcna_analysis.py b/wqflask/wqflask/wgcna/wgcna_analysis.py
new file mode 100644
index 00000000..f23b1417
--- /dev/null
+++ b/wqflask/wqflask/wgcna/wgcna_analysis.py
@@ -0,0 +1,156 @@
+# WGCNA analysis for GN2
+# Author / Maintainer: Danny Arends <Danny.Arends@gmail.com>
+import sys
+from numpy import *
+import scipy as sp # SciPy
+import rpy2.robjects as ro # R Objects
+import rpy2.rinterface as ri
+
+from base import webqtlConfig # For paths and stuff
+from utility import webqtlUtil # Random number for the image
+
+import base64
+import array
+
+from utility import helper_functions
+
+from rpy2.robjects.packages import importr
+utils = importr("utils")
+
+## Get pointers to some common R functions
+r_library = ro.r["library"] # Map the library function
+r_options = ro.r["options"] # Map the options function
+r_read_csv = ro.r["read.csv"] # Map the read.csv function
+r_dim = ro.r["dim"] # Map the dim function
+r_c = ro.r["c"] # Map the c function
+r_cat = ro.r["cat"] # Map the cat function
+r_paste = ro.r["paste"] # Map the paste function
+r_unlist = ro.r["unlist"] # Map the unlist function
+r_unique = ro.r["unique"] # Map the unique function
+r_length = ro.r["length"] # Map the length function
+r_unlist = ro.r["unlist"] # Map the unlist function
+r_list = ro.r.list # Map the list function
+r_matrix = ro.r.matrix # Map the matrix function
+r_seq = ro.r["seq"] # Map the seq function
+r_table = ro.r["table"] # Map the table function
+r_names = ro.r["names"] # Map the names function
+r_sink = ro.r["sink"] # Map the sink function
+r_is_NA = ro.r["is.na"] # Map the is.na function
+r_file = ro.r["file"] # Map the file function
+r_png = ro.r["png"] # Map the png function for plotting
+r_dev_off = ro.r["dev.off"] # Map the dev.off function
+
+class WGCNA(object):
+ def __init__(self):
+ print("Initialization of WGCNA")
+ #log = r_file("/tmp/genenetwork_wcgna.log", open = "wt")
+ #r_sink(log) # Uncomment the r_sink() commands to log output from stdout/stderr to a file
+ #r_sink(log, type = "message")
+ r_library("WGCNA") # Load WGCNA - Should only be done once, since it is quite expensive
+ r_options(stringsAsFactors = False)
+ print("Initialization of WGCNA done, package loaded in R session")
+ self.r_enableWGCNAThreads = ro.r["enableWGCNAThreads"] # Map the enableWGCNAThreads function
+ self.r_pickSoftThreshold = ro.r["pickSoftThreshold"] # Map the pickSoftThreshold function
+ self.r_blockwiseModules = ro.r["blockwiseModules"] # Map the blockwiseModules function
+ self.r_labels2colors = ro.r["labels2colors"] # Map the labels2colors function
+ self.r_plotDendroAndColors = ro.r["plotDendroAndColors"] # Map the plotDendroAndColors function
+ print("Obtained pointers to WGCNA functions")
+
+ def run_analysis(self, requestform):
+ print("Starting WGCNA analysis on dataset")
+ self.r_enableWGCNAThreads() # Enable multi threading
+ self.trait_db_list = [trait.strip() for trait in requestform['trait_list'].split(',')]
+ print("Retrieved phenotype data from database", requestform['trait_list'])
+ helper_functions.get_trait_db_obs(self, self.trait_db_list)
+
+ self.input = {} # self.input contains the phenotype values we need to send to R
+ strains = [] # All the strains we have data for (contains duplicates)
+ traits = [] # All the traits we have data for (should not contain duplicates)
+ for trait in self.trait_list:
+ traits.append(trait[0].name)
+ self.input[trait[0].name] = {}
+ for strain in trait[0].data:
+ strains.append(strain)
+ self.input[trait[0].name][strain] = trait[0].data[strain].value
+
+ # Transfer the load data from python to R
+ uStrainsR = r_unique(ro.Vector(strains)) # Unique strains in R vector
+ uTraitsR = r_unique(ro.Vector(traits)) # Unique traits in R vector
+
+ r_cat("The number of unique strains:", r_length(uStrainsR), "\n")
+ r_cat("The number of unique traits:", r_length(uTraitsR), "\n")
+
+ # rM is the datamatrix holding all the data in R /rows = strains columns = traits
+ rM = ro.r.matrix(ri.NA_Real, nrow=r_length(uStrainsR), ncol=r_length(uTraitsR), dimnames = r_list(uStrainsR, uTraitsR))
+ for t in uTraitsR:
+ trait = t[0] # R uses vectors every single element is a vector
+ for s in uStrainsR:
+ strain = s[0] # R uses vectors every single element is a vector
+ rM.rx[strain, trait] = self.input[trait].get(strain) # Update the matrix location
+ #DEBUG: print(trait, strain, " in python: ", self.input[trait].get(strain), "in R:", rM.rx(strain,trait)[0])
+ sys.stdout.flush()
+
+ self.results = {}
+ self.results['nphe'] = r_length(uTraitsR)[0] # Number of phenotypes/traits
+ self.results['nstr'] = r_length(uStrainsR)[0] # Number of strains
+ self.results['phenotypes'] = uTraitsR # Traits used
+ self.results['strains'] = uStrainsR # Strains used in the analysis
+ self.results['requestform'] = requestform # Store the user specified parameters for the output page
+
+ # Calculate soft threshold if the user specified the SoftThreshold variable
+ if requestform.get('SoftThresholds') is not None:
+ powers = [int(threshold.strip()) for threshold in requestform['SoftThresholds'].rstrip().split(",")]
+ rpow = r_unlist(r_c(powers))
+ print "SoftThresholds: {} == {}".format(powers, rpow)
+ self.sft = self.r_pickSoftThreshold(rM, powerVector = rpow, verbose = 5)
+
+ print "PowerEstimate: {}".format(self.sft[0])
+ self.results['PowerEstimate'] = self.sft[0]
+ if self.sft[0][0] is ri.NA_Integer:
+ print "No power is suitable for the analysis, just use 1"
+ self.results['Power'] = 1 # No power could be estimated
+ else:
+ self.results['Power'] = self.sft[0][0] # Use the estimated power
+ else:
+ # The user clicked a button, so no soft threshold selection
+ self.results['Power'] = requestform.get('Power') # Use the power value the user gives
+
+ # Create the block wise modules using WGCNA
+ network = self.r_blockwiseModules(rM, power = self.results['Power'], TOMType = requestform['TOMtype'], minModuleSize = requestform['MinModuleSize'], verbose = 3)
+
+ # Save the network for the GUI
+ self.results['network'] = network
+
+ # How many modules and how many gene per module ?
+ print "WGCNA found {} modules".format(r_table(network[1]))
+ self.results['nmod'] = r_length(r_table(network[1]))[0]
+
+ # The iconic WCGNA plot of the modules in the hanging tree
+ self.results['imgurl'] = webqtlUtil.genRandStr("WGCNAoutput_") + ".png"
+ self.results['imgloc'] = webqtlConfig.TMPDIR + self.results['imgurl']
+ r_png(self.results['imgloc'], width=1000, height=600)
+ mergedColors = self.r_labels2colors(network[1])
+ self.r_plotDendroAndColors(network[5][0], mergedColors, "Module colors", dendroLabels = False, hang = 0.03, addGuide = True, guideHang = 0.05)
+ r_dev_off()
+ sys.stdout.flush()
+
+ def render_image(self, results):
+ print("pre-loading imgage results:", self.results['imgloc'])
+ imgfile = open(self.results['imgloc'], 'rb')
+ imgdata = imgfile.read()
+ imgB64 = imgdata.encode("base64")
+ bytesarray = array.array('B', imgB64)
+ self.results['imgdata'] = bytesarray
+
+ def process_results(self, results):
+ print("Processing WGCNA output")
+ template_vars = {}
+ template_vars["input"] = self.input
+ template_vars["powers"] = self.sft[1:] # Results from the soft threshold analysis
+ template_vars["results"] = self.results
+ self.render_image(results)
+ sys.stdout.flush()
+ #r_sink(type = "message") # This restores R output to the stdout/stderr
+ #r_sink() # We should end the Rpy session more or less
+ return(dict(template_vars))
+