/*
 * 
 * TableSorter 2.0 - Client-side table sorting with ease!
 * Version 2.0.3
 * @requires jQuery v1.2.3
 * 
 * Copyright (c) 2007 Christian Bach
 * Examples and docs at: http://tablesorter.com
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 */
//(function($){$.extend({tablesorter:new function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'.',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}var rows=table.tBodies[0].rows;if(table.tBodies[0].rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,cells[i]);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,node){var l=parsers.length;for(var i=1;i<l;i++){if(parsers[i].is($.trim(getElementText(table.config,node)),table,node)){return parsers[i];}}return parsers[0];}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=table.tBodies[0].rows[i],cols=[];cache.row.push($(c));for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c.cells[j]),table,c.cells[j]));}cols.push(i);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){if(!node)return"";var t="";if(config.textExtraction=="simple"){if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){t=node.childNodes[0].innerHTML;}else{t=node.innerHTML;}}else{if(typeof(config.textExtraction)=="function"){t=config.textExtraction(node);}else{t=$(node).text();}}return t;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){rows.push(r[n[i][checkCell]]);if(!table.config.appender){var o=r[n[i][checkCell]];var l=o.length;for(var j=0;j<l;j++){tableBody[0].appendChild(o[j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false,tableHeadersRows=[];for(var i=0;i<table.tHead.rows.length;i++){tableHeadersRows[i]=0;};$tableHeaders=$("thead th",table);$tableHeaders.each(function(index){this.count=0;this.column=index;this.order=formatSortingOrder(table.config.sortInitialOrder);if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(!this.sortDisabled){$(this).addClass(table.config.cssHeader);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){i=(v.toLowerCase()=="desc")?1:0;}else{i=(v==(0||1))?v:0;}return i;}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(getCachedSortType(table.config.parsers,c)=="text")?((order==0)?"sortText":"sortTextDesc"):((order==0)?"sortNumeric":"sortNumericDesc");var e="e"+i;dynamicExp+="var "+e+" = "+s+"(a["+c+"],b["+c+"]); ";dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function sortText(a,b){return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){$this.trigger("sortStart");var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){var $cell=$(this);var i=this.column;this.order=this.count++%2;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){var DECIMAL='\\'+config.decimal;var exp='/(^[+]?0('+DECIMAL+'0+)?$)|(^([-+]?[1-9][0-9]*)$)|(^([-+]?((0?|[1-9][0-9]*)'+DECIMAL+'(0*[1-9][0-9]*)))$)|(^[-+]?[1-9]+[0-9]*'+DECIMAL+'0+$)/';return RegExp(exp).test($.trim(s));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[Â£$â‚¬?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9.]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}$("tr:visible",table.tBodies[0]).filter(':even').removeClass(table.config.widgetZebra.css[1]).addClass(table.config.widgetZebra.css[0]).end().filter(':odd').removeClass(table.config.widgetZebra.css[0]).addClass(table.config.widgetZebra.css[1]);if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);
(function($){$.extend({tablesorter:new function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'.',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}var rows=table.tBodies[0].rows;if(table.tBodies[0].rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,cells[i]);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,node){var l=parsers.length;for(var i=1;i<l;i++){if(parsers[i].is($.trim(getElementText(table.config,node)),table,node)){return parsers[i];}}return parsers[0];}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=table.tBodies[0].rows[i],cols=[];cache.row.push($(c));for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c.cells[j]),table,c.cells[j]));}cols.push(i);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){if(!node)return"";var t="";if(config.textExtraction=="simple"){if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){t=node.childNodes[0].innerHTML;}else{t=node.innerHTML;}}else{if(typeof(config.textExtraction)=="function"){t=config.textExtraction(node);}else{t=$(node).text();}}return t;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){rows.push(r[n[i][checkCell]]);if(!table.config.appender){var o=r[n[i][checkCell]];var l=o.length;for(var j=0;j<l;j++){tableBody[0].appendChild(o[j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false,tableHeadersRows=[];for(var i=0;i<table.tHead.rows.length;i++){tableHeadersRows[i]=0;};$tableHeaders=$("thead th",table);$tableHeaders.each(function(index){this.count=0;this.column=index;this.order=formatSortingOrder(table.config.sortInitialOrder);if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(!this.sortDisabled){$(this).addClass(table.config.cssHeader);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){i=(v.toLowerCase()=="desc")?1:0;}else{i=(v==(0||1))?v:0;}return i;}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(getCachedSortType(table.config.parsers,c)=="text")?((order==0)?"sortText":"sortTextDesc"):((order==0)?"sortNumeric":"sortNumericDesc");var e="e"+i;dynamicExp+="var "+e+" = "+s+"(a["+c+"],b["+c+"]); ";dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function sortText(a,b){return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){$this.trigger("sortStart");var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){var $cell=$(this);var i=this.column;this.order=this.count++%2;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){var DECIMAL='\\'+config.decimal;var exp='/(^[+]?0('+DECIMAL+'0+)?$)|(^([-+]?[1-9][0-9]*)$)|(^([-+]?((0?|[1-9][0-9]*)'+DECIMAL+'(0*[1-9][0-9]*)))$)|(^[-+]?[1-9]+[0-9]*'+DECIMAL+'0+$)/';return RegExp(exp).test($.trim(s));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[Â£$â‚¬?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9.]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}$("tr:visible",table.tBodies[0]).filter(':even').removeClass(table.config.widgetZebra.css[1]).addClass(table.config.widgetZebra.css[0]).end().filter(':odd').removeClass(table.config.widgetZebra.css[0]).addClass(table.config.widgetZebra.css[1]);if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);

var IS_FIXED_MAP = false;
var IS_MAP_MODE_SWITCH_DISPLAYED = true;

var LAT_LONG_PAIRS =
{
	MAP_DEFAULT:new VELatLong(39.16414104768743, -95.97656250000001, 0, VEAltitudeMode.RelativeToGround),
	SEPA_HQ:new VELatLong(38.906631, -77.043878, 0, VEAltitudeMode.Default)
}

var MAP_ZOOM_LEVELS =
{
	DEFAULT:4,
	MARKER_ZOOM_IN:10
}

var COORDINATES_INDEX_FOR_LONG = 0;
var COORDINATES_INDEX_FOR_LAT = 1;
var COORDINATES_INDEX_FOR_ALT = 2;

var PATH_TO_CUSTOM_MAP_MARKER = "/common/images/icons/red_map_marker.png";

var DEFAULT_DISPLAY_FILTER_INDEX = 3;
var DEFAULT_CELL_TEXT = "&nbsp;";

var ELEMENT_NAME_FOR_ROW = "row";
var ELEMENT_NAME_FOR_CELL = "cell";

var JIDs =
{
	FeedbackDisplay:"#feedback",
	DisplayMode:"#menuDisplay input[name='displayOption']",
	SelectedDisplayMode:"#menuDisplay input[name='displayOption']:checked",
	MapContainerDOMID:"mapUS",
	MapContainer:"#mapUS",
	MapResetControl:"#mapReset",
	AllSectionContainers:"#cellDataDisplay div.sectionContainer",
	AllFilterContainers:"#dataFilters div.filterContainer",
	FilterOptions:("#dataFilters input.df"),
	SelectedFilterOptions:("#dataFilters div.filterContainer:visible input.df:checked"),
	FilterResults:"#filterResults",
	RemoveFiltersControl:"#removeFiltersControl"
}

var NO_DATA_FILTERS_MESSAGE = "Currently, no display filters are selected.";

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Visual Animation and Effects:
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
var ANIMATION_OPTIONS = {FADE_IN:{opacity:1}, FADE_OUT:{opacity:0}};
var UI_EFFECT_DURATION = 1000;

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Geocoding Functions:
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Creates a pusphin from a set of coordinates.
// Last Revision Date:  12/10/2008
// Parameters:
//		coordinates:  	The [longitude, lattitude, altitude]
//		name:  			The map marker title
//		utility:  		The utility name
//		moreInfo:		The more information link
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function CreatePushPin(coordinates, name, utility, moreInfo)
{
	try
	{
		if ((coordinates != null) && (coordinates.length == 3)) 
		{
			var pushpin = SetPushPin(new VELatLong(coordinates[COORDINATES_INDEX_FOR_LAT], 
			coordinates[COORDINATES_INDEX_FOR_LONG], 
			coordinates[COORDINATES_INDEX_FOR_ALT], 
			VEAltitudeMode.Default), 
			// Map Marker description:
			'<p>' + ((utility != null) ? 'Utility:  ' + utility.text() : "Unknown") + '</p><p>' + ((moreInfo != null) ? 'More Info:  ' + moreInfo.html() : "") + '</p>',
			// Map Marker title:
			$(name).text());
			
			var aID = "a_" + pushpin.GetID();
			
			$(name).html('<a id="' + aID + '" class="mapRef" rel="' + pushpin.GetID() + '" title="Zoom and center the map on the \'' + $(name).text() + '\' installation.">' + $(name).text() + '</a>');
		
			$("#" + aID).click(function()
			{
				var shape = CenterAndZoomOnMapShape($(this).attr("rel"));									
				
				if (shape != null)
				{
					mapVE.ShowInfoBox(shape, null, null);
				}
			});									
		}
		else
		{
			$(name).html('<span class="mapRef">' + $(name).text() + '</span>');
		}
	}
	catch (e)
	{
		//alert("An error occurred in the 'CreatePushPin' function:\n\n" + e);
	}
}


var GEOCODING_FUNCTIONS =
{
	GENERIC: function(JID,colIndices)
	{
		rows = $(JID + " > tbody > tr");
		
		jQuery.each(rows, function(i)
		{
			if ($(this).css("display") != "none") 
			{			
				var name = $(this).find("td:eq(" + colIndices.name + ")");
				var utility = $(this).find("td:eq(" + colIndices.utility + ")");
				var moreInfo = $(this).find("td:eq(" + colIndices.moreInfo + ")");
				var zipCode = $(this).find("td:eq(" + colIndices.zipcode + ")");
				var latitude = $(this).find("td:eq(" + colIndices.latitude + ")");
				var latText = (latitude.length == 1) ? jQuery.trim(latitude.text()): "";		
				var longitude = $(this).find("td:eq(" + colIndices.longitude + ")");
				var longText = (longitude.length == 1) ? jQuery.trim(longitude.text()): "";
				
				// Do the latitude and longitude values exist for the row?
				//if ((latitude.length == 1) && (longitude.length == 1) && (latitude.text().length > 0) && (longitude.text().length > 0)) 
				if ((latText.length > 0) && (longText.length > 0))
				{
					// Create the pushpin using the stored coordinates.
					CreatePushPin(([longText, latText, 0]), name, utility, moreInfo);
				}
				// Geocode using the centroid for the ZIP code.			
				else 
					if (zipCode != null) 
					{
						// Replace any special characters, and trim the results.
						var zipCodeText = jQuery.trim(zipCode.text().replace("TBD", "").replace("'", ""));
								
						if (zipCodeText.length > 0) 
						{
							$.ajax({
								type: "get",
								url: RSS_PROXY + "?furl=" + escape("http://maps.google.com/maps/geo?q=" + zipCodeText + "&output=xml&oe=utf8&sensor=false&key=ABQIAAAAMbymHzvs9XuP64m1Z8URBhQ-pbl8IO4gIBWIjw6hWqww0rioNhT-eKoPCUTyybYIGxUxL3rfrv_HLg"),
								dataType: "xml",
								success: function(data, textStatus){
									CreatePushPin(($(data).find("coordinates:first").text().split(",")), name, utility, moreInfo);
								}
							})
						}
						else
						{
							CreatePushPin(([]), name, utility, moreInfo);
						}
					}
			}
		});
		
		//SetPushPin(LAT_LONG_PAIRS.SEPA_HQ, "http://www.solarelectricpower.org", "SEPA Headquarters");
	}
}

var ITERATION_FUNCTIONS =
{
	GENERIC:function(i, JID, row)
	{
		var cells = "";
		
		$(row).find(ELEMENT_NAME_FOR_CELL).each(function(j, cell)
		{
			var cellText = $(cell).text();
			
			cellText = ((cellText == null) || (cellText.length == 0)) ? DEFAULT_CELL_TEXT : cellText;
			
			// Does the cell text begin with "http://"?
			if (cellText.toLowerCase().indexOf("http://") == 0)
			{
				// If so, create a link element.
				cellText = '<a href="' + cellText + '" title="View more information." target="_blank">Click Here</a>';
			}
			
			cells += '<td class="' + ("cell" + j) + '">' + cellText + '</td>';
		});
		
		$(JID + " tbody").append(('<tr class="row">' + cells + '</tr>'));		
	}
}

var DISPLAY_MODE_DEFS =
[
	{
		index:0,
		sectionSelector:"#pvLayout",
		sectionTableSelector:"#pvIndex",
		sectionFilterSelector:("#pvLayoutFilters"),		
		isSectionTableSortable:true,
		tableSorterOptions:{headers:{1:{sorter:"MW"}}},
		queryURL:"/solar-tools/google-data-spreadsheet-query.aspx?sn=SEPADataMap&wsn=Top25PV&page=1&rows=100&sidx=maxmw&sord=desc&_search=true&searchField=pv&searchString=x&searchOper=" + escape("="),			
		iterationFunction:ITERATION_FUNCTIONS.GENERIC,
		populationFunction:QueryForSectionData,
		geocodingFunction:GEOCODING_FUNCTIONS.GENERIC,
		colIndices:{name:0,utility:2,moreInfo:7,zipcode:8,latitude:9,longitude:10}
	},		
	{
		index:1,
		sectionSelector:"#cspLayout",
		sectionTableSelector:"#cspIndex",
		sectionFilterSelector:("#cspLayoutFilters"),		
		isSectionTableSortable:true,
		tableSorterOptions:{headers:{4:{sorter:"MW"}}},
		queryURL:"/solar-tools/google-data-spreadsheet-query.aspx?sn=SEPADataMap&wsn=Top20CSP&page=1&rows=100&sidx=maxmw&sord=desc&_search=true&searchField=csp&searchString=x&searchOper=" + escape("="),			
		iterationFunction:ITERATION_FUNCTIONS.GENERIC,
		populationFunction:QueryForSectionData,
		geocodingFunction:GEOCODING_FUNCTIONS.GENERIC,
		colIndices:{name:0,utility:1,moreInfo:7,zipcode:8,latitude:9,longitude:10}
	},
	{
		index:2,
		sectionSelector:"#usaLayout",
		sectionTableSelector:"#usaIndex",
		sectionFilterSelector:("#usaLayoutFilters"),
		isSectionTableSortable:true,
		tableSorterOptions:{headers:{1:{sorter:"MW"},2:{sorter:"MW"}}},
		queryURL:"/solar-tools/google-data-spreadsheet-query.aspx?sn=SEPADataMap&wsn=Announcements&page=1&rows=100&sidx=maxmw&sord=desc&_search=true&searchField=utility&searchString=x&searchOper=" + escape("="),		
		iterationFunction:ITERATION_FUNCTIONS.GENERIC,
		populationFunction:QueryForSectionData,
		geocodingFunction:GEOCODING_FUNCTIONS.GENERIC,
		colIndices:{name:0,utility:3,moreInfo:8,zipcode:9,latitude:10,longitude:11}
	},	
	{
		index:3,
		sectionSelector:"#iuLayout",
		sectionTableSelector:"#iuIndex",
		sectionFilterSelector:("#iuLayoutFilters"),		
		isSectionTableSortable:true,
		tableSorterOptions:{headers:{5:{sorter:"MW"}}},
		queryURL:"/solar-tools/google-data-spreadsheet-query.aspx?sn=SEPADataMap&wsn=InnovativeUtility&page=1&rows=100&sidx=maxmw&sord=desc&_search=true&searchField=csp&searchString=x&searchOper=" + escape("="),			
		iterationFunction:ITERATION_FUNCTIONS.GENERIC,
		populationFunction:QueryForSectionData,
		geocodingFunction:GEOCODING_FUNCTIONS.GENERIC,
		colIndices:{name:0,utility:1,moreInfo:10,zipcode:11,latitude:12,longitude:13}				
	},	
	{
		index:4,
		sectionSelector:"#caseStudyLayout",
		sectionTableSelector:"#caseStudiesIndex",
		sectionFilterSelector:("#caseStudyLayoutFilters"),		
		isSectionTableSortable:true,
		tableSorterOptions:{headers:{5: {sorter: false}, 6: {sorter: false}, 11: {sorter: false}}},
		queryURL:null,
		rowTemplate:null,
		iterationFunction:null,
		populationFunction:null,
		geocodingFunction:GEOCODING_FUNCTIONS.GENERIC,
		colIndices:{name:0,utility:1,moreInfo:0,zipcode:8,latitude:9,longitude:10}		
	}
]

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Sets a pushpin on the map.
// Last Revision Date:  12/10/2008
// Parameters:
//		veLatLong:  The lat/long instance
//		description:  A description for the icon
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function SetPushPin(veLatLong, description, titleText)
{
	try
	{
		// VEShape contains the information about a map shape. 
		var pushpin = new VEShape(VEShapeType.Pushpin, veLatLong);
		
		// Sets the VEShape object's custom icon.
		pushpin.SetCustomIcon (PATH_TO_CUSTOM_MAP_MARKER);
		
		// If specified, set the title; otherwise, use a default.
		pushpin.SetTitle('<div class="mapMarkerTitle">' + (((titleText == null) || (titleText.length <= 0)) ? "Map Marker" : titleText) + '</div>');
		
		// If specified, set the description; otherwise, use a default.
	    pushpin.SetDescription('<div class="mapMarkerDesc">' + (((description == null) || (description.length <= 0)) ? "" : description) + '</div>');
		
	    mapVE.AddShape(pushpin);
		
		return pushpin;
	}
	catch (e)
	{
		alert("There was an error in the 'SetPushPin' function:\n\n" + e);	
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Queries against an external data source and executes
// a population function for the specified display mode.
// Last Revision Date:  12/10/2008
// Parameters:
//		displayMode:  The current display mode
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function QueryForSectionData(displayMode)
{
	try
	{
		$.ajax(
		{
			type:"GET",
			url:displayMode.queryURL,
			dataType:"xml",
			complete:function (xhr, textStatus) 
			{
				 //alert(xhr.responseText);
			},
			success: function(responseXML)
			{
				if ($(displayMode.sectionTableSelector).length == 1) 
				{		
					var JID = displayMode.sectionTableSelector;
				
					// Empty the table body container.
					$(JID + " tbody").empty();
					
					if (displayMode.iterationFunction != null)
					{					
						// Retrieve the <row> nodes from the response XML.
						jQuery.each($(responseXML).find(ELEMENT_NAME_FOR_ROW), function(i)
						{	
							// Call the iteration function to create the rows from templates.
							displayMode.iterationFunction(i, JID, $(this));
						});
					}
					
					onSectionDisplayReady(displayMode);
					
					// Alert the table sorter that rows have been added.
					$(JID).trigger("update");  
					
					$(JID + " > thead th.queryMaxMW").click();
					$(JID + " > thead th.queryMaxMW").click();				
				}
			},
			error: function(data)
			{
				//alert(data);
			}
		});
	}
	catch (e)
	{
		alert("There was an error in the 'QueryForSectionData' function:\n\n" + e);	
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Filters table rows based on whether 
// table cells within the row contain an appropriate text
// value.
// Last Revision Date:  12/10/2008
// Parameters:
//		displayMode:  The current display mode.
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function ApplyDataFiltering(displayMode)
{
	try
	{
		var tableRows = $(displayMode.sectionTableSelector + " > tbody > tr");
		var masterCount = tableRows.length;
		var selectedFilters = $(displayMode.sectionFilterSelector + " > div.filters input.df:checked");
		
		// Start by hiding all rows.
		tableRows.hide();		
		
		// Show only those rows that meet all of the currently selected filtering criteria.
		// Note that each filters section must be iterated over to allow for multiple filters to be specified.
		$(displayMode.sectionFilterSelector + " div.filters").each(function(index, domElement)
		{
			// Start with a blank selector.
			var selector = "";
			
			// Find the collection of checked filter elements.
			var checkedFilters = $("#" + $(domElement).attr("id") + " div.filter input.df:checked");
			
			// Calculate the max index of the checked filters for the section to use in the suffix text.
			var maxIndex = (checkedFilters.length - 1);
			
			checkedFilters.each(function(index, checkBoxElement)
			{
				// Add a suffix to chain filters.
				var suffix = ((index < maxIndex) ? ", " : "");
				
				// Append to the selector.
				selector += ("tr:has(td." + $(checkBoxElement).attr("name") + ":contains('" + $(checkBoxElement).val() + "'))" + (suffix));
			});
			
			// Apply the filter for the section.
			if ((selector != null) && (selector.length > 0))
			{	
				tableRows = tableRows.filter(selector);
			}
		});
		
		// Show any rows remaining from the filtering.
		tableRows.show();
		
		var filteredCount = 0;
		
		$(displayMode.sectionTableSelector + " > tbody > tr").each(function(i)
		{
			if ($(this).css("display") != "none")
			{
				++filteredCount;
			}
		});
	
		$(JIDs.FilterResults).show().text("Displaying " + filteredCount + " result" + ((filteredCount != 1) ? "s" : "") + " that match" + ((filteredCount == 1) ? "es" : "") + " the current filter criteria.");
	}
	catch (e)
	{
		alert("There was an error in the 'ApplyDataFiltering' function:\n\n" + e);	
	}	
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Prepares the data display section when the
// data and map are ready.
// Last Revision Date:  12/10/2008
// Parameters:
//		displayMode:  The current display mode.
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function onSectionDisplayReady(displayMode)
{
	try
	{
		// Hide the feedback control.					
		$(JIDs.FeedbackDisplay).animate(ANIMATION_OPTIONS.FADE_OUT, UI_EFFECT_DURATION);					
	
		if (displayMode != null)
		{
			if (displayMode.sectionSelector != null)
			{
				// Show the container section.
				$(displayMode.sectionSelector).show();
			}
			
			if (displayMode.sectionFilterSelector != null)
			{
				// Show the filter container for the section.
				$(displayMode.sectionFilterSelector).fadeIn(UI_EFFECT_DURATION);
			}		
			
			// Reset the results display.
			//$(JIDs.FilterResults).show().text(NO_DATA_FILTERS_MESSAGE);	
			
			// Geocode the table rows.
			if (displayMode.geocodingFunction != null)
			{
				displayMode.geocodingFunction(displayMode.sectionTableSelector, displayMode.colIndices);					
			}				
		}
	}
	catch (e)
	{
		alert("There was an error in the 'onSectionDisplayReady' function:\n\n" + e);	
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Changes the display in response to a new section selection.
// Last Revision Date:  12/10/2008
// Parameters:
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function ChangeSectionDisplay()
{
	try
	{
		// Clear the map.
		mapVE.DeleteAllShapes();
		
		// Reset the map.
		$("#mapReset").click();
		
		// Hide all section containers.
		$(JIDs.AllSectionContainers).hide();
		
		// Hide all filter containers.
		$(JIDs.AllFilterContainers).hide();
		
		// Reset the results display.
		$(JIDs.FilterResults).hide().text(NO_DATA_FILTERS_MESSAGE);
		
		$(JIDs.FeedbackDisplay).fadeIn().animate(ANIMATION_OPTIONS.FADE_IN, UI_EFFECT_DURATION, null,		
			function()
			{
				var index = 0;
				
				try
				{
					index = parseInt($(JIDs.SelectedDisplayMode).val());
				}
				catch (e)
				{
					index = 0;
				}
				
				if ((index >= 0) && (index < DISPLAY_MODE_DEFS.length))
				{
					var _mode = DISPLAY_MODE_DEFS[index];
						
					// If defined, call the population function.
					if (_mode.populationFunction != null)
					{
						_mode.populationFunction(_mode);
					}
					else
					{
						onSectionDisplayReady(_mode);
					}
					
					if (index == 0)
					{
						//$(_mode.sectionTableSelector).trigger("sorton",[[1,1]]); 
					}				
				}
				
				$(this).fadeOut();	
			}
		);
	}
	catch (e)
	{
		// Hide the feedback control.					
		$(JIDS.FeedbackDisplay).animate(ANIMATION_OPTIONS.FADE_OUT, UI_EFFECT_DURATION, function(){$(this).hide();});		

		alert("There was an error in the 'ChangeSectionDisplay' function:\n\n" + e);	
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Center the map, and zoom in on the map shape.
// Last Revision Date:  12/10/2008
// Parameters:
//		elementID:  DOM ID for the map shape
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function CenterAndZoomOnMapShape(elementID)
{
	try 
	{
		if (elementID != null) 
		{
			// Retrieve the clicked shape.
			var shape = mapVE.GetShapeByID(elementID);
			
			if ((shape) && (shape.GetPoints()[0])) 
			{
				// Center the map on the icon and zoom in.
				mapVE.SetCenterAndZoom(shape.GetPoints()[0], MAP_ZOOM_LEVELS.MARKER_ZOOM_IN);
			}
			
			return shape;
		}
		
		return null;
	} 
	catch (ex) 
	{
		alert("There was an error in the 'CenterAndZoomOnMapShape' event handler for the map:\n\n" + ex);
	}
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Initialize the map to the default orientation, zoom level, and map style.
// Last Revision Date:  12/10/2008
// Parameters:
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function InitializeMapControl()
{
	try
	{
	   	// Initialize the mapping options.
	   	mapVEOptions = new VEMapOptions();
	   	mapVEOptions.EnableBirdseye = false;
		// Use the "mapUS" div as the map container.
		mapVE = new VEMap(JIDs.MapContainerDOMID);
		// Set the initial viewport.
	   	mapVE.LoadMap(LAT_LONG_PAIRS.MAP_DEFAULT, MAP_ZOOM_LEVELS.DEFAULT, VEMapStyle.Road, IS_FIXED_MAP, VEMapMode.Mode2D, IS_MAP_MODE_SWITCH_DISPLAYED, mapVEOptions);
		// When a shape is clicked, execute the following function:
		mapVE.AttachEvent("onclick", 
		//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
		// Purpose:  Displays information for the selected shape icon.
		// Last Revision Date:  12/10/2008
		// Parameters:
		//		e:  The current event
		//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\		
		function(e)
		{	
			try 
			{
				CenterAndZoomOnMapShape(e.elementID);				
			} 
			catch (ex) 
			{
				alert("There was an error in the 'onclick' event handler for the map:\n\n" + ex);
			}
		});
	}
	catch (e)
	{
		alert("There was an error in the 'InitializeMapControl' function:\n\n" + e);	
	}
}

$(document).ready(function()
{
	$.tablesorter.addParser(
	{ 
        // set a unique id 
        id: "MW", 
        is: function(s) 
		{ 
            // return false so this parser is not auto detected 
            return false; 
        }, 
        format: function(s) 
		{ 
            // format your data for normalization 
            return s.replace("", 0);
        }, 
        // set type, either numeric or text 
        type: 'numeric' 
    });   
	
    $(JIDs.FilterOptions).click(function()
    {
		// Retrieve the display filter index.
		var index = GetValueAsInt($(this).attr("alt").replace("DFI:", ""), DEFAULT_DISPLAY_FILTER_INDEX);
		
		ChangeSectionDisplay();
		
        ApplyDataFiltering(DISPLAY_MODE_DEFS[index]);
    });

    $(JIDs.RemoveFiltersControl).click(function()
    {
		// Retrieve the display filter index.
		var index = DEFAULT_DISPLAY_FILTER_INDEX;
	
        // Deselect each selected option.
        $(JIDs.SelectedFilterOptions).each(function(index, element)
        {
            $(element).attr("checked", false);	
			
			index = GetValueAsInt($(element).attr("alt").replace("DFI:", ""), DEFAULT_DISPLAY_FILTER_INDEX);			
        });

        ApplyDataFiltering(DISPLAY_MODE_DEFS[index]);

        //$(JIDs.FilterResults).text(NO_DATA_FILTERS_MESSAGE);
    });
		
	$(JIDs.FeedbackDisplay).css("opacity", 0);
   
	$(JIDs.DisplayMode + "[alt='" + $.query.get("view") + "']:first").attr("checked", "checked");
      
	// Add sorting to all of the sortable tables.
	$.each(DISPLAY_MODE_DEFS, function(i)
	{
		var _mode = DISPLAY_MODE_DEFS[i];
	
		/**/
		if (_mode.isSectionTableSortable === true)
		{
	   		$(_mode.sectionTableSelector).tablesorter(_mode.tableSorterOptions);
		}
		
	});  

	// Create the initial map view.
	InitializeMapControl();

	$(JIDs.DisplayMode).click(function()
	{
		ChangeSectionDisplay();
	});
	
	$(JIDs.MapResetControl).click(function()
	{
		mapVE.SetCenterAndZoom(LAT_LONG_PAIRS.MAP_DEFAULT, MAP_ZOOM_LEVELS.DEFAULT);
	});
	
	ChangeSectionDisplay();
})