Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                		<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
		<script type="text/javascript">
		var jQuery_1_11_1 = $.noConflict(true);
		</script>

		<link href="https://www.qld.gov.au/ictdashboard/assets/styles/styles.css" media="all" rel="stylesheet" type="text/css" />
		<link href="https://www.qld.gov.au/ictdashboard/assets/styles/normalize.min.css" media="all" rel="stylesheet" type="text/css" />
		<link href="https://www.qld.gov.au/ictdashboard/assets/styles/ion.rangeSlider.css" media="all" rel="stylesheet" type="text/css" />
		<link href="https://www.qld.gov.au/ictdashboard/assets/styles/ion.rangeSlider.skinFlat.css" media="all" rel="stylesheet" type="text/css" />
		<script src="https://www.qld.gov.au/ictdashboard/assets/includes/components/ion.rangeSlider.min.js"></script>

<div id="ictdb" class="projectstable dataTable">
  <div class="toggle-sort"><a href="javascript:void(0)" id="toggleInformation">Show all</a></div>
  <table id="ictdb-datatable" class="display" cellspacing="0">
    <caption id="search-results-summary">Displaying <span id="search-type">search results</span> <strong id="result-scope"></strong> of <strong id="total-result"></strong></caption>
    <thead>
      <tr>
        <th width="5%"><a title="Agency" href="">Dept</a></th>
        <th width="40%" class="plus"><a title="Initiative name" href="">Project name</a></th>
        <th width="5%"><a title="Overall status" href="">Status</a></th>
        <th width="20%" class="desktop-view"><a title="Revised total estimated expenditure" href="">Planned<br> expenditure</a></th>
        <th width="15%" class="desktop-view"><a title="Actual start date" href="">Start date</a></th>
        <th width="15%" class="desktop-view"><a title="Planned end date" href="">Planned<br> end date</a></th>
      </tr>
    </thead>
    <tbody id="results-table">
      <tr>
        <td colspan="6">
          <p>Loading...</p>
        </td>
      </tr>
    </tbody>
  </table>
  <div id="pagination">
    <ul></ul>
  </div>
</div>

<div id="asides">
  <div class="box-sizing">
    <div class="border">
      <div class="aside search">
        
        <div class="search-widget">
          <div class="widget-header">
            <h2>Refine search</h2>
            <span class="action hide"><a href="#" id="search-toggle" class="up">Toggle</a></span>
          </div>
        </div>
        
        <form>
          <input hidden type="text" name="AdvancedSearch" id="AdvancedSearch" value="" />
            <ol class="questions form-section">
              <li>
                <label for="query"><span class="label">Keyword</span></label>
                <input type="text" maxlength="60" size="40" value="" name="query" id="query" />
              </li>
              <li>
                <fieldset id="Status">
                  <legend>
                    <span class="label">Project status</span>
                  </legend>
                  <ul class="choices" id="status-list">
                    <li>
                      <input id="status-green" name="ProjectStatusG" value="G" type="checkbox" />
                      <label for="status-green"><img src="https://www.qld.gov.au/ictdashboard/assets/images/flag-G.png" alt="" />On track</label>
                    </li>
                    <li>
                      <input id="status-amber" name="ProjectStatusA" value="A" type="checkbox" />
                      <label for="status-amber"><img src="https://www.qld.gov.au/ictdashboard/assets/images/flag-A.png" alt="" />Closely monitored</label>
                    </li>
                    <li>
                      <input id="status-red" name="ProjectStatusR" value="R" type="checkbox" />
                      <label for="status-red"><img src="https://www.qld.gov.au/ictdashboard/assets/images/flag-R.png" alt="" />Action required</label>
                    </li>
                  </ul>
                </fieldset>
              </li>

              <li>
                <label for="Agency"><span class="label">Department</span></label>
                <select size="6" name="Agency" id="Agency" multiple="multiple">
                  <option value="" selected="selected">All</option>
                  <option value="Cross-Gov">Cross Government Projects</option>
                  <option value="DATSIP">Aboriginal and Torres Strait Islander Partnerships</option>
                  <option value="DAF">Agriculture and Fisheries</option>
                  <option value="DCCSDS">Communities, Child Safety and Disability Services</option>
                  <option value="DET">Education and Training</option>
                  <option value="DEWS">Energy and Water Supply</option>
                  <option value="EHP">Environment and Heritage Protection</option>
                  <option value="QFES">Fire and Emergency Services</option>
                  <option value="QH">Health</option>
                  <option value="HPW">Housing and Public Works</option>
                  <option value="DILGP">Infrastructure, Local Government and Planning</option>
                  <option value="DJAG">Justice and Attorney-General</option>
                  <option value="NPSR">National Parks, Sport and Racing</option>
                  <option value="DNRM">Natural Resources and Mines</option>
                  <option value="QPS">Police</option>
                  <option value="DPC">Premier and Cabinet</option>
                  <option value="PSBA">Public Safety Business Agency</option>
                  <option value="DSITI">Science, Information Technology and Innovation</option>
                  <option value="DSD">State Development</option>
                  <option value="DTESB">Tourism, Major Events, Small Business and the Commonwealth Games</option>
                  <option value="TMR">Transport and Main Roads</option>
                  <option value="QT">Treasury</option>
                </select>
              </li>
              <li class="hide advsearch">
                <fieldset>
                  <legend>Planned expenditure</legend>
                  <div class="range-slider">
                    <input type="text" class="js-range-slider1" value="" />
                    <div>
                      <label for="expenditure-from" class="lbl js-from"><span class="label">From ($)</span></label>
                      <label for="expenditure-to" class="lbl js-to"><span class="label">To ($)</span></label>
                    </div>
                    <div class="extra-controls minimised">
                      <input id="expenditure-from" name="ExpenditureFrom" type="text" value="0" class="inp js-from" />
                      <input id="expenditure-to" name="ExpenditureTo" type="text" value="0" class="inp js-to" />
                    </div>
                  </div>
                </fieldset>


                <fieldset>
                  <legend>Cost to date</legend>
                  <div class="range-slider">
                    <input type="text" class="js-range-slider2" value="" />
                    <div class="lbls">
                      <label for="actualcost-from" class="lbl js-from"><span class="label">From ($)</span></label>
                      <label for="actualcost-to" class="lbl js-to"><span class="label">To ($)</span></label>
                    </div>
                    <div class="extra-controls minimised">
                      <input id="actualcost-from" name="ActualCostFrom" type="text" value="0" class="inp js-from" />
                      <input id="actualcost-to" name="ActualCostTo" type="text" value="0" class="inp js-to" />
                    </div>
                  </div>
                </fieldset>

              </li>
              <li class="atomic group hide advsearch">
                <fieldset>
                  <legend>
                    <span class="label">Planned end date</span>
                  </legend>
                  <ol class="questions compact">
                    <li>
                      <label for="end-after">
                        <span class="label">After</span>
                        <small class="hint">Example: 26/01/2013</small>
                      </label>
                      <input id="end-after" name="EndAfter" size="15" placeholder="dd/mm/year" type="text" maxlength="10" />
                    </li>
                    <li>
                      <label for="end-before">
                        <span class="label">Before</span>
                        <small class="hint">Example: 26/01/2013</small>
                      </label>
                      <input id="end-before" name="EndBefore" size="15" placeholder="dd/mm/year" type="text" maxlength="10" />
                    </li>
                  </ol>
                </fieldset>
              </li>
            <li class="footer">
              <div class="actions">
                  <strong><input type="submit" value="Search" /></strong>
                  <input type="reset" value="Reset" onclick="window.location='../projects/'" />
                <a class="advancedsearch">Show advanced search</a>
              </div>
            </li>
          </ol>   
        </form>
        
      </div>
    </div>
  </div>
</div>
              
            
!

CSS

              
                /* default stylesheet included in ICTDB (refer to style included within html) assumes that Qld Gov SWE template is present - the below inserts some additional CSS to allow the page to render without SWE template (it's a messy template you don't want to work with if you can avoid it!!!) - the below CSS was very quickly thrown together and could use a cleanup. */


@import url(https://fonts.googleapis.com/css?family=Open+Sans:700,400,300);

body {
  background: white;
  background-size: 100%;
  font-family: 'Open Sans', sans-serif;
  font-size: 16px;
  line-height: 1.5em;
  color: #053150;
}

#ictdb .medium .aside h2 {
  position: relative;
  left: 0;
}

caption {
color: #000000;
  text-align: left;
  margin-bottom: .2em;
}

input, select {
  width: 100%;
}

#asides {
  display: block;
  margin-left: 76%;
}

.small #asides, .medium #asides {
  margin: 0;
  padding: 0;
}

body #ictdb .aside, body #ictdb .small .aside, body #ictdb .medium .aside {
  padding: 2%;
  display: block; 
}


.aside form ol, .aside form li {
  margin: 0;
  padding: 0;
  list-style: none;
}
.aside form .actions li {
  display: inline-block;
  min-height: 4em;
}
.aside .actions input {
  padding-top: .25em;
  padding-bottom: .25em;
  margin: 0;
  width: 8em;
  border: 1px solid #666;
}
.aside .actions strong input {
  background: #78BA00;
}

tr.even {
  background: #fff;
}
tr.odd {
  background: #F3F3F3;
}


.button {
  padding: 0.5em;
  color: #fff;
  border: 1px solid rgba(0,0,0,0.2);
}

.visuallyhidden {
  border: 0;
  clip: rect(0 0 0 0);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
}

/* ----------------- */
/*  ICTDB data page  */
/* ----------------- */
div.highcharts-axis-labels.highcharts-xaxis-labels span span {
	text-decoration: underline;
	color: #007EB1; 
}
div.highcharts-axis-labels.highcharts-xaxis-labels span span:hover, div.highcharts-axis-labels.highcharts-xaxis-labels span span.active {
	text-decoration: underline;
	color: #007EB1;
	cursor: pointer;
	font-weight: 900;
}
div.highcharts-axis-labels.highcharts-xaxis-labels span span:focus {
	text-decoration: underline;
	color: #00f;
	cursor: pointer;
	font-weight: 900;
}
.highcharts-axis-labels.highcharts-xaxis-labels span {
	z-index: 1 !important;
}
.highcharts-tooltip span  {
	z-index:9999 !important;
	background: #ffffff;
	background: rgba(255,255,255,1);
	padding: 10px !important;
  -webkit-box-shadow: inset 0px 0px 4px 2px rgba(142,150,158,1);
  -moz-box-shadow: inset 0px 0px 4px 2px rgba(142,150,158,1);
  box-shadow: inset 0px 0px 4px 2px rgba(142,150,158,1);
}

/* -- table -- */
table#ictdb-datatable tr th a {
  display: inline-block;
  width: 96%;
  padding-right: 2em;
  color: #fff;
}

.thminwid { 
  width: 6em;  
}

table#ictdb-datatable td.details-control { background: url('https://www.qld.gov.au/ictdashboard/assets/images/details_open.png') no-repeat left 50%; padding-left: 35px;}
#ictdb.small table#ictdb-datatable td.details-control { padding-left: 25px; background-position: left 9px;}
table#ictdb-datatable tr.shown td.details-control{ background: url('https://www.qld.gov.au/ictdashboard/assets/images/details_close.png') no-repeat left 50%; }
table#ictdb-datatable tr.shown td.details-title { font-weight: 900;}
table#ictdb-datatable tr.shown { border-top: 1px solid;}
table#ictdb-datatable tr.detailedInfoRow.open { border-bottom: 1px solid;}
table#ictdb-datatable .even td.details-control,tr.shown.even td.details-control { background-color: white; }

table#ictdb-datatable tr.summary { cursor: pointer; cursor: hand; }

table#ictdb-datatable .detailedInfoRow td {
	padding: 0 1em 0 1em;
}
table#ictdb-datatable .detailedInfoRow td p {
	margin-top: 0 !important;
	margin-bottom: 0 !important;
}
table#ictdb-datatable p .button {
    padding-bottom: 0.5em !important;
    padding-top: 0.5em !important;
}
table#ictdb-datatable p.actions {
    text-align: right !important;
}
table#ictdb-datatable tr.even td.sorting_1 {
    background-color: #cfdde7;
}
table#ictdb-datatable tr.odd td.sorting_1 {
    background-color: #c6d3de;
}
table#ictdb-datatable tr.odd.shown td {
    background-color: #F3F3F3;
}
table#ictdb-datatable tr.even.shown td {
    background-color: #fff;
}
.toggle-sort {
  position: relative;
  width: 100%;
}
#toggleInformation{
  position: absolute;
  right: 0;
  top: 0 !important;
}


#ictdb-datatable th {
    background: url("//static.qgov.net.au/assets/v2/images/datatable/sort_both.png") no-repeat center right #13578b !important;
    padding-right: 0 !important;
	vertical-align: middle !important;
  text-align: left;
}
#ictdb-datatable th.asc {
    background: url("//static.qgov.net.au/assets/v2/images/datatable/sort_asc.png") no-repeat center right #13578b !important;
}
#ictdb-datatable th.desc {
    background: url("//static.qgov.net.au/assets/v2/images/datatable/sort_desc.png") no-repeat center right #13578b !important;
}
#ictdb-datatable ul {
  margin-left: 0;
}
#ictdb-datatable ul ul, #ictdb.small #ictdb-datatable .detailedInfoRow td ul ul {
  padding-left: 1.7em;
}
#ictdb.small #ictdb-datatable .detailedInfoRow td ul {
  padding-left: 1em;
}

#ictdb.small .desktop-view, #ictdb .small-view {
	display: none;
}
#ictdb.small .small-view {
	display: list-item;
}
#ictdb.small td, #ictdb.small th { 
  padding: 0.5em;
}
#ictdb-datatable tr td, #ictdb-datatable tr th {
  white-space: nowrap;
  padding: 0.5em 0.25em .5em .5em 
}
#ictdb-datatable td.details-title, #ictdb-datatable .detailedInfoRow td {
  white-space: normal;
}


.actions li {
  margin: 0 0.5em 0.5em 0 !important;
}
/* -- aside overides -- */ 

#asides li.hide {
    display: none !important;
}
#asides .advancedsearch {
    text-decoration: underline;
    color: #13578b;
    cursor: pointer;
}

#ictdb .aside {
  padding: 1px;
  margin: 0;
}

#ictdb .actions {
  padding: 0;
  margin: 0;
}

#ictdb .aside h2 {
  position: absolute;
  left: -9999em;
}
#ictdb.small .aside h2 {
  position: relative;
  left: 0;
}
#ictdb .aside .actions a {
  color: #fff;
}

#ictdb .aside .actions a:hover {
  color: #000;
}

#asides .status.warn h2 {
  position: absolute;
  left: -9999em;
}
#asides .status.warn ol {
  margin: 0;
  padding: 0;
}
#asides .status.warn li {
  margin: 0;
  display: block;
  min-height: 3em;
}

#asides form fieldset {
	border: none;
	padding: .35em 0;
}
.aside.search {
	background: #f2f7f9;
}
#asides form.hide {
	display: none;
}
#asides form .choices label {
    position: absolute;
    top: -4px;
}

#status-list label{
    display: inline-block;
}

#status-list label img{
    pointer-events: none;
}

#asides form .choices img {
    position: absolute;
    top: 5px;
    padding-right: 0.5em;
}

/* -- sliders -- */ 
.extra-controls.unminimised {
    position: relative;
    border-top: 1px solid #eee;
    border-bottom: 3px solid #ccc;
    padding: 1em 0 0;
    height: 4em;
    margin: 1em 0 2.5em 0;
}
.extra-controls {
    position: relative;
    border-top: 1px solid #eee;
    border-bottom: 3px solid #eee;
    padding:0;
    height: 0px;
    overflow: hidden;
    margin: 1em 0 0 0;
    clear: both;
}
body #asides form .questions input.inp {
    width: 45%;
    text-align: center;
    padding: 5px;
}
.lbls {
  width: 100%;

}
.lbl {
  float: left;
}
.inp + .inp, .lbl + .lbl {
    float: right;
}
.lbl {
    font-size: 80%;
    padding: .5em 5px;
}
.irs-slider.to:before {
position: absolute;
display: block;
content: "";
top: -120%;
left: -20%;
width: 150%;
height: 256%;
background: rgba(0,0,0,0.0);
}
.range-slider {
  margin: 0 1em 0 0 !important;
}
.lbl.js-from, .lbl.js-to {
  text-decoration: underline;
  color: #13578B;
}

#asides select {
  overflow: auto;
}

#ictdb.dataTable {
  width: 75%;
  float: left;
}

#ictdb.dataTable.small, #ictdb.dataTable.medium {
  width: 100%;
}

#asides.medium {
  width: 100%
}
#content-container .article .box-sizing #asides.small div.border, #content-container .article .box-sizing #asides.medium div.border {
  margin: 0;
}
.search-widget .widget-header .action a.up:before, .search-widget .widget-header .action a:before {
  position: absolute;
  top: 0;
  left: 0;
}
.search-widget .widget-header .action a:hover:before, .search-widget .widget-header .action a.up:hover:before {
  color: #0066cc;
}

#content-container .article .box-sizing .border {
  margin-left: 2.9em;
}

#ictdb.dataTable.small .desktop-view, #ictdb.dataTable .mobile-view {
  display: none;
}

#ictdb.dataTable.small .mobile-view {
  display: list-item;
}
#ictdb.dataTable .projectStatusCol {
  text-align: center;
}
#ictdb.dataTable .projectStatusCol span {
  position: absolute;
  left: -9999em;
}

/* temp pagination */ 
#pagination ul {
  padding: 0;
  text-align: center;
}
#pagination li {
  display: inline-block;
  list-style: none;
  margin: 1em;
}





#asides form .choices label {
    position: relative;
    top: -4px;
}
.questions ul {
  margin: .5em;
  padding: 0;
  position: relative;
  width: 100%;
}
.questions .choices li {
    padding: 0 0 0 20px;
    margin: .3em 0;
    background: transparent;
    list-style: none;
    border: none;
    position: relative;
    text-align: left;
}
.choices li input[type="checkbox"] {
    position: absolute;
    left: 0;
    padding: 0;
    margin: 0;
    top: .3em;
    width: 1em;
}

.questions .footer {
  display: inline-block
}
.advancedsearch {
  white-space: nowrap;
}


/* Print overrides -webkit-print-color-adjust: exact; */

@media print {
  #overview-status .print-link-url, #overview-expenditure .print-link-url, #ui-controls, #nav-site, #tools, #feature-search-db, .aside.search, .toggle-sort {
    display: none !important;
  }

  .franchise-index-with-asides h1, #results-table th, #results-table td, #content-container .article .box-sizing .box-sizing, #content-container .article .box-sizing .border {
    left-padding: 0 !important;
    margin-left: 0 !important;
  }
  #ictdb.dataTable {
    width: 100%;
  }

  #overview-expenditure .graph li span, #overview-status .graph li span {
    color: #000 !important;
  }
  #overview-expenditure .graph li span, #overview-status .graph li span {
    text-shadow: 1px 1px 3px rgba(255, 255, 255, 1);
  }

  body #ictdb-datatable thead tr th a {
    color: #000000 !important;
  }
  table#ictdb-datatable td.details-control{
    padding-left: 0;
  }
  #ictdb.dataTable .projectStatusCol span {
    position: relative;
    left: 0;
    top: -0.2em;
    margin: 0 0 0 .6em;
  }

  #asides {
    clear: left;
  }
}

              
            
!

JS

              
                function getDataFromCKAN( domain, sql, options ) {
		var errorCallback;

		if ( $.isFunction( options )) {
			options = {
				successCallback: options,
				cache: false
			};
		} else {
			options = $.extend({ cache: false }, options );
		}

		errorCallback = function() {
			/* Need non-SWE lightbox/other alert errror message here
      
      $( document ).status( 'show', {
				status: 'fail',
				lightbox: true,
				title: 'Error loading data',
				body: '<p>We were unable to retrieve data.</p><p>Please try again later.</p>'
			}); */
		};
  
  	jQuery.getJSON({
			url: 'https://' + domain + '/api/action/datastore_search_sql',
			data: { sql: sql },
			callbackParameter: 'callback',
			success: options.successCallback,
			error: errorCallback,
			pageCache: options.cache
		});
 
         $.ajax({
                   type: 'GET',
                    url: 'https://' + domain + '/api/action/datastore_search_sql',
          			    data: { sql: sql },
			              callbackParameter: 'callback',
                    success: options.successCallback,
                    error: errorCallback,
                    pageCache: options.cache,
                    dataType: 'jsonp'

       }).done(function(json){
           //console.log(json);
                    //callback(json);
       }).fail(function(f){
           console.log("f");
                    //console.log(f.status);
       }).always(function(){
                   // console.log('complete');
      }); 

	}; 


function templateFormat(text, format, options) {

		options = $.extend( {}, options );
		var value, actual;

		if ( text === null ) {
			return '';
		}

		switch ( format ) {
		case '%':
			return Math.round( parseFloat( text )) + '%';

		case '$':
			value = parseFloat( text );
			if ( value >= 10000 ) {
				actual = text.replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1,' );
				if ( value < 1000000 ) {
					// thousands
					return '$' + actual;

				} else {
					// millions
					actual = text.replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1,' );
					text = String( Math.round( text / 100000 ) / 10 ) + '\xA0million';

					switch ( options.abbr ) {
					case true:
						return '<abbr title="$' + actual + '">$' + text + '</abbr>';
					case 'both':
						return '$' + text + ' ($' + actual + ')';
					}
				}
			}
			return '$' + text;

		case 'shortnum':
			value = parseFloat( text );
			if ( value >= 10000 ) {
				actual = text.replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1,' );
				if ( value < 1000000 ) {
					// thousands
					return actual;

				} else {
					// millions
					actual = text.replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1,' );
					text = String( Math.round( text / 100000 ) / 10 ) + '\xA0million';

					switch ( options.abbr ) {
					case true:
						return '<abbr title="' + actual + '">' + text + '</abbr>';
					case 'both':
						return text + ' (' + actual + ')';
					}
				}
			}
			return text;

		case 'md':
			return markdown.toHTML( text );

		case 'date':
		case 'datetime':
			if ( typeof text === 'string' ) {
				value = new Date( text );
				if ( isNaN( value.getTime() )) {
					// assume ISO format: YYYY-MM-DD
					actual = text.split( /[-:T ]/ );
					value = new Date( actual[ 0 ], parseInt( actual[ 1 ], 10 ) - 1, actual[ 2 ] );
					if ( isNaN( value.getTime() )) {
						return text;
					}
					// optional time component
					if ( actual.length > 3 ) {
						value.setHours( actual[ 3 ] );
						if ( actual.length > 4 ) {
							value.setMinutes( actual[ 4 ] );
							if ( actual.length > 5 ) {
								value.setSeconds( actual[ 5 ] );
							}
						}
					}
				}
			} else {
				// assume date object
				value = text;
			}

			text = value.getDate() + ' ' + 'January,February,March,April,May,June,July,August,September,October,November,December'.split( ',' )[ value.getMonth() ] + ' ' + value.getFullYear();

			if ( format === 'datetime' ) {
				// format time component
				text += ', ' + qgovTimeFormat( value );
			}

			return text;

		case 'time':
			if ( typeof text === 'string' ) {
				if ( /^\d+[:.]\d+$/.test( text )) {
					text = text.split( /[:.]/ );
					value = new Date();
					value.setHours( text[ 0 ] );
					value.setMinutes( text[ 1 ] );
				} else {
					return text;
				}
			} else {
				// assume date object
				value = text;
			}
			return qgovTimeFormat( value );

		case 'abn':
			return String( text ).replace( /\s+/g, '' ).replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1\xA0' );
		}
		// default
		return cleanText( text );
  
};

	function cleanText (text ) {
		return $( '<div/>' ).text( text ).html().replace( /"/g, '&quot;' );
	};

		// set up container relative to device size
	    var win = $(window); 
	    if (win.width() < 640) {
			$('#ictdb').addClass('small');
			$('#asides').addClass('small');
			$('#asides .widget-header span').removeClass('hide');
			$('#asides form').addClass('hide');
			$('#asides').insertBefore('#pagination');	
			$('#appnav').insertAfter('#ictdb');
		} else if (win.width() >= 640 && win.width() <= 980) {
			$('#ictdb').addClass('medium');
			$('#asides').addClass('medium');
			$('#asides .widget-header span').removeClass('hide');
			$('#asides form').addClass('hide');
			$('#asides').insertBefore('#ictdb .toggle-sort');
			$('#appnav').insertAfter('#ictdb');
		} else if (win.width() > 980) {
			$('#asides form').removeClass('hide');
      $('#content').removeClass('small');
		}

		$(document).on('click','.advancedsearch',function(){
			$( "#asides form li.advsearch" ).toggleClass( 'hide' );
			if ( $( '#AdvancedSearch' ).val() === '' ) {
				$( '#AdvancedSearch' ).val('true');
				$( ".advancedsearch" ).text('Hide advanced search');
			} else {
				$( '#AdvancedSearch' ).val('');
				$( ".advancedsearch" ).text('Show advanced search');		
			}
		});

// watch page for width changed - to clean up graph errors and to reload if crossing device specific dimensions
		$(window).on('resize', function(){

			setTimeout(function (){
					jQuery_1_11_1(".js-range-slider1, .js-range-slider2").ionRangeSlider("update", {});
				}, 100);

			

		    var win = $(this); //this = window

			if ( win.width() > 980 && $( '#asides form' ).hasClass( 'hide' ) ) {
				$( '#asides form' ).removeClass( 'hide' );
			}

		    if (win.width() < 620 && !$('#ictdb').hasClass('small')) {
				$('#ictdb').addClass('small');
				$('#ictdb').removeClass('medium');
				$('#asides').addClass('small');
				$('#asides').removeClass('medium'); 
				$('#asides .widget-header span').removeClass('hide');

				$('#asides').insertBefore('#ictdb .toggle-sort');	
				$('#appnav').insertAfter('#ictdb');
			} else if (win.width() >= 620 && win.width() <= 980 && $('#ictdb').hasClass('small')) {
				$('#ictdb').removeClass('small');
				$('#ictdb').addClass('medium');
				$('#asides').removeClass('small');
				$('#asides').addClass('medium');
				$('#asides .widget-header span').removeClass('hide');

				$('#asides').insertBefore('#ictdb .toggle-sort');	
				$('#appnav').insertAfter('#ictdb');

			} else if (win.width() >= 620 && win.width() <= 980 && !$('#ictdb').hasClass('medium') && !$('#ictdb').hasClass('small') ) {
				$('#ictdb').addClass('medium');
				$('#asides').addClass('medium');
				$('#asides .widget-header span').removeClass('hide');

				$('#asides').insertBefore('#ictdb .toggle-sort');	
				$('#appnav').insertAfter('#ictdb');
			} else if (win.width() > 980 && $('#ictdb').hasClass('small')) {
				$('#ictdb').removeClass('small');
				$('#ictdb').removeClass('medium');
				$('#asides').removeClass('small');
				$('#asides').removeClass('medium');
				$('#asides .widget-header span').addClass('hide');
	
				$('#asides').insertAfter('#ictdb');       		
				$('#asides .border').append($('#appnav'));				
			} else if (win.width() > 980 && $('#ictdb').hasClass('medium')) {
				$('#ictdb').removeClass('medium');
				$('#asides').removeClass('medium');
				$('#asides .widget-header span').addClass('hide');

				$('#asides').insertAfter('#ictdb');       	
				$('#asides .border').append($('#appnav'));				
			}
			 else {
				 // run cleanup?
			}
		});

		$(document).on('click','#search-toggle',function(){
			$( "#asides form" ).toggleClass( 'hide' );
		    $(this).toggleClass ( 'up' );
			jQuery_1_11_1(".js-range-slider1, .js-range-slider2").ionRangeSlider("update", {
			});
		});

		// SLIDER FUN TIMES
		$( ".extra-controls" ).delegate( "input", "focus blur", function() {
			var elem = $( this );
			setTimeout(function() {
			elem.parent().toggleClass( "unminimised", elem.is( ":focus" ) );
			}, 0 );
		});

		var QueryString = function () {
			// This function is anonymous, is executed immediately and 
			// the return value is assigned to QueryString!
			var query_string = {};
			var query = window.location.search.substring(1);
			var vars = query.split("&");
			for (var i=0;i<vars.length;i++) {
				var pair = vars[i].split("=");
				// If first entry with this name
				if (typeof query_string[pair[0]] === "undefined") {
					query_string[pair[0]] = pair[1];
					// If second entry with this name
				} else if (typeof query_string[pair[0]] === "string") {
					var arr = [ query_string[pair[0]], pair[1].replace(/</g, "&lt;").replace(/>/g, "&gt;") ];
					query_string[pair[0]] = arr;
					// If third or later entry with this name
				} else {
					query_string[pair[0]].push(pair[1].replace(/</g, "&lt;").replace(/>/g, "&gt;"));
				}
			} 
			return query_string;
		} ();

		var domain = (window.location.href.indexOf("qld-uat.ssq.qld.gov.au") > -1 ? 'staging.data.qld.gov.au' : 'data.qld.gov.au'  );
		$( 'body' ).addClass( domain == 'data.qld.gov.au' ? 'prod' : 'test env-uat' );		
		var table = 'ictdashboards_tables()',
			overviewTitle = '',
			getFilters,
			displayStatusOverview,
			displayExpendituresOverview,
			displayProjectOverview,
			getProjectOverview,
			searchResultsCount,
			displaySearchResultsCount,
			searchResults,
			displaySearchResult,
			populateAsideSearchForm,
			displayPagination,
			paginationWhenReady,
			sortableTableWhenReady,
			getExpenditureActualCost,
			setExpenditureActualCost
		;

		getFilters = function( ) {
			var query = '';

			query += ( QueryString.query && (typeof QueryString.query !== 'undefined' || typeof QueryString.query !== '' ) ? ', plainto_tsquery(\'english\', \'' + QueryString.query.replace(/\%2F/g, '/') + '\') query' : '' );
			query += ' WHERE 1=1 AND (\"Overall status\" != \'\')';
			query += ( QueryString.query && (typeof QueryString.query !== 'undefined' || typeof QueryString.query !== '' ) ? ' AND (_full_text @@ query OR \"Agency\"=\''+ QueryString.query.toUpperCase() +'\')' : '' );

			if ( ( QueryString.ProjectStatusR && typeof QueryString.ProjectStatusR !== 'undefined' ) || ( QueryString.ProjectStatusA && typeof QueryString.ProjectStatusA !== 'undefined' )  || ( QueryString.ProjectStatusG && typeof QueryString.ProjectStatusG !== 'undefined' ) ) {

				query += ' AND (';
				if (  QueryString.ProjectStatusR && typeof QueryString.ProjectStatusR !== 'undefined' ) {
					query += ' \"Overall status\" = \'R\'';
				}

				if ( ( QueryString.ProjectStatusR && typeof QueryString.ProjectStatusR !== 'undefined' )  && ( QueryString.ProjectStatusA && typeof QueryString.ProjectStatusA !== 'undefined' ) ) {
					query += ' OR ';
				}

				if (  QueryString.ProjectStatusA && typeof QueryString.ProjectStatusA !== 'undefined' ) {
					query += ' \"Overall status\" = \'A\'';
				}

				if ( (( QueryString.ProjectStatusR && typeof QueryString.ProjectStatusR !== 'undefined' )  || ( QueryString.ProjectStatusA && typeof QueryString.ProjectStatusA !== 'undefined' )) &&  ( QueryString.ProjectStatusG && typeof QueryString.ProjectStatusG !== 'undefined' ) ) {
					query += ' OR ';
				}

				if ( QueryString.ProjectStatusG && typeof QueryString.ProjectStatusG !== 'undefined' ) {
					query += ' \"Overall status\" = \'G\'';
				}
				query += ') ';

			} else {
				$( $( 'form', '#asides' )[ 0 ][ 'ProjectStatusR' ] ).prop('checked', true);
				$( $( 'form', '#asides' )[ 0 ][ 'ProjectStatusA' ] ).prop('checked', true);
				$( $( 'form', '#asides' )[ 0 ][ 'ProjectStatusG' ] ).prop('checked', true);
			}

			if ( QueryString.ExpenditureFrom && typeof QueryString.ExpenditureFrom !== 'undefined' ) {
				query += ' AND \"Revised total estimated expenditure\" >= \'' + unescape(QueryString.ExpenditureFrom).replace(/\D/g,'') +'\'';
			}

			if ( QueryString.ExpenditureTo && typeof QueryString.ExpenditureTo !== 'undefined' ) {
				query += ' AND \"Revised total estimated expenditure\" <= \'' + unescape(QueryString.ExpenditureTo).replace(/\D/g,'') +'\'';
			}

			if ( QueryString.ActualCostFrom && typeof QueryString.ActualCostFrom !== 'undefined' ) {
				query += ' AND \"Actual cost to date\" >= \'' + unescape(QueryString.ActualCostFrom).replace(/\D/g,'') +'\'';
			}

			if ( QueryString.ActualCostTo && typeof QueryString.ActualCostTo !== 'undefined' ) {
				query += ' AND \"Actual cost to date\" <= \'' + unescape(QueryString.ActualCostTo).replace(/\D/g,'') +'\'';
			}

			if ( QueryString.Agency && (typeof QueryString.Agency !== 'undefined' || typeof QueryString.Agency !== '' )) {

				if ( typeof  QueryString.Agency !== 'object') {
					query += ' AND (\"Agency\"=\'' + QueryString.Agency.replace(/\+/g, ' ') + '\')';
				} else {
					var AgencyArray = [];
					
					$.each(QueryString.Agency, function ( item, value ) {   
						AgencyArray.push (' \"Agency\"=\'' + value.replace(/\+/g, ' ') + '\'');
					});
					query += ' AND (' + AgencyArray.join( ' OR ') +')';
				}
			}


			if (  QueryString.EndBefore && typeof QueryString.EndBefore !== 'undefined' ) {
				var before = QueryString.EndBefore.replace(/\%2F/g, '/').replace(/\-/g, '/');
				var dateParts = before.split('/');
				var date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0]);
				var text = date.getFullYear() + '-' + ('0' + (date.getMonth()+1)).slice(-2) + '-' + date.getDate();
				query += ' AND (\"Planned end date\"::DATE <= \'' + text + '\'::DATE)';
			
			}

			if (  QueryString.EndAfter && typeof QueryString.EndAfter !== 'undefined' ) {
				var after = QueryString.EndAfter.replace(/\%2F/g, '/').replace(/\-/g, '/');
				var  dateParts = after.split('/');
				var date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0]);
				var text = date.getFullYear() + '-' + ('0' + (date.getMonth()+1)).slice(-2) + '-' + date.getDate();
				query += ' AND (\"Planned end date\"::DATE >= \'' + text + '\'::DATE)';
			}

			return query;
		};

		function SortByExpenditure(x,y) {
     		return y.totalprojects -  x.totalprojects; 
    	}

		searchResultsCount = function( ) {
			// load json data
			var rules = getFilters();
			var sql = 'SELECT COUNT(*), (SELECT COUNT(*) from ' + table + ' WHERE 1=1 AND (\"Overall status\" != \'\')) AS TOTAL from ' + table + rules;
			getDataFromCKAN( domain, sql, displaySearchResultsCount );
		};

		displaySearchResultsCount = function( jsonData   ) {
			$( '#total-result' ).text( jsonData.result.records[0].count );
			$( '#search-type' ).text( jsonData.result.records[0].count === jsonData.result.records[0].total ? 'all projects' : 'search results' );
		};

		searchResults = function() {
			// load json data
			var rules = getFilters(); 
			var resultLimit = 20;
			var orderBy = '';
			var direction = !QueryString.direction && typeof QueryString.direction === 'undefined' ? '' : QueryString.direction;
			var sort = typeof QueryString.sort !== 'undefined' && QueryString.sort ? QueryString.sort.replace(/\+/g, ' ') :  'Overall status';

			if  (typeof QueryString.sort !== 'undefined' && QueryString.sort.replace(/\+/g, ' ') !== 'Overall status') {
				orderBy = '\"' + QueryString.sort.replace(/\+/g, ' ') + '\" ' + direction + ', \"Initiative name\"';	
			} else {
				if ( direction === 'desc' ) {
					orderBy += '(CASE \"Overall status\" WHEN \'R\' THEN 1 WHEN \'A\' THEN 2 WHEN \'G\' THEN 3 END)';
				} else {
					orderBy += '(CASE \"Overall status\" WHEN \'G\' THEN 1 WHEN \'A\' THEN 2 WHEN \'R\' THEN 3 END)';
				}
				orderBy += ', \"Agency\", \"Initiative name\" '
			}
			$( "th a[title*='"+ sort +"']" ).parent().addClass( direction );

			var sql = 'SELECT * FROM  ' + table + rules +  ' ORDER BY ' + orderBy +  
					'  LIMIT ' + resultLimit +' OFFSET ' + (QueryString.offset && typeof QueryString.offset !== 'undefined' ? QueryString.offset * resultLimit : 0 );

			getDataFromCKAN( domain, sql, displaySearchResult );
		};

		function convertDate( text ) {
			if ( typeof text === 'string' ) {
				var value = new Date( text );
				if ( isNaN( value.getTime() )) {
					// assume ISO format: YYYY-MM-DD
					var actual = text.split( /[-:T ]/ );
					value = new Date( actual[ 0 ], parseInt( actual[ 1 ], 10 ) - 1, actual[ 2 ] );
					if ( isNaN( value.getTime() )) {
						return text;
					}
					// optional time component
					if ( actual.length > 3 ) {
						value.setHours( actual[ 3 ] );
						if ( actual.length > 4 ) {
							value.setMinutes( actual[ 4 ] );
							if ( actual.length > 5 ) {
								value.setSeconds( actual[ 5 ] );
							}
						}
					}
				}
			} else {
				value = text;
			}

			text = ('0' + value.getDate()).slice(-2) + '-' + ('0' + (value.getMonth()+1)).slice(-2) + '-' + value.getFullYear();
			return text;
		}

		displaySearchResult = function( jsonData   ) {
			var resultsHTML = '',
			    results = $( '#results-table' )
			;
			results.empty();

			if ( jsonData.result.records.length > 0 ) {
        console.log('why sdfsdf');
				// loop through items // (question)?(result if true):(result is false)
				// item['Overall status'] === 'G' ? 'Green' : (item['Overall status'] === 'A' ? 'Amber' : (item['Overall status'] === 'R' ? 'Red' : '')
				$.each( jsonData.result.records, function( index, item ) {
					// append to search results
					resultsHTML += '<tr class="' + (index%2==1?'even':'odd')+' summary">';
					// Adding dept name - note removal of hyphen from name of Cross Gov if it exists
					resultsHTML += '<td><abbr title="' + item['Agency name'] +'">' + (item['Agency'] == 'Cross-Gov'? 'Cross Gov' : item['Agency']) +'</abbr></td>';	          
					resultsHTML += '<td class="details-title details-control"><a href="javascript:void(0)">' + item['Initiative name'] +'</a></td>';
					resultsHTML += '<td class="projectStatusCol"><img src="https://www.qld.gov.au/ictdashboard/assets/images/flag-' + item['Overall status'] +'.png" alt="" title="' + (item['Overall status'] === 'G' ? 'On track' : (item['Overall status'] === 'A') ? 'Closely monitored' : (item['Overall status'] === 'R') ? 'Action required' : '') +'" /><span>' + (item['Overall status'] === 'G' ? 'On track' : (item['Overall status'] === 'A') ? 'Closely monitored' : (item['Overall status'] === 'R') ? 'Action required' : '') + '</span></td>';
					resultsHTML += '<td class="desktop-view">' + (item['Revised total estimated expenditure'] !== '0' ? templateFormat( item['Revised total estimated expenditure'], '$' ) : 'TBC') + '</td>';
					resultsHTML += '<td class="desktop-view">' + convertDate( item['Actual start date'], 'date' ) +'</td>';
					resultsHTML += '<td class="desktop-view">' + convertDate( item['Planned end date'], 'date' ) +'</td>';
					resultsHTML += '</tr>';
          
          
					resultsHTML += '<tr class="detailedInfoRow ' + (index%2==1?'even':'odd')+'"><td colspan="6">';
					resultsHTML += '<ul><li><strong>Objectives</strong>:' + markdown.toHTML( item['Investment objectives'] ) + '</li>';
					resultsHTML += '<li><strong>Expenditure:</strong><ul>';
					resultsHTML += '<li><strong>Cost to date</strong>: ' +  (item['Actual cost to date'] !== '0' ? templateFormat( item['Actual cost to date'], '$' ) : 'TBC') + '</li>';
					resultsHTML += '<li><strong>Planned expenditure</strong>: ' +  (item['Revised total estimated expenditure'] !== '0' ? templateFormat( item['Revised total estimated expenditure'], '$' ) : 'TBC') + '</li>';
					resultsHTML += '<li><strong>Original planned expenditure</strong>: ' + (item['Original total estimated expenditure'] !== '0' ? templateFormat( item['Original total estimated expenditure'], '$' ) : 'TBC') + '</li>';
					resultsHTML += '</ul></li>';	
					resultsHTML += '<li><strong>Timeframe:</strong><ul>';
					resultsHTML += '<li><strong>Start date</strong>: ' + convertDate(item['Actual start date']) + '</li>';
					resultsHTML += '<li><strong>Planned end date</strong>: ' + convertDate(item['Planned end date']) + '</li>';
					resultsHTML += '<li><strong>Original planned end date</strong>: ' + (item['Original planned end date'] && typeof item['Original planned end date'] !== 'undefined' && item['Original planned end date'] !== '' ? convertDate( item['Original planned end date'], 'date' ) : 'Not available') + '</li>';
					resultsHTML += '</ul></li>';
					resultsHTML += '<li><strong>Explanatory notes</strong>:' +  markdown.toHTML( item['Explanation of variance'] ) + '</li>';
					resultsHTML += '<li><strong>Priority</strong>: ' + item['Priority'] + '</li>';
					resultsHTML += '<li><strong>Stage</strong>: ' + item['Initiative stage'] + '</li>';
					resultsHTML += '<li><strong>Date data current</strong>: ' + convertDate(item['Date data current at']) + '</li></ul>';
					resultsHTML += '</td></tr>';
				});
				$( results ).append( resultsHTML );
			} else {
				results.append( resultsHTML + '<tr><td colspan="6">No projects were found for this search</td></tr>' );
			}

			// Add event listener for opening and closing details
		    $('#ictdb-datatable tbody').on('click', 'tr.summary', function () {
		        var tr = $(this).next();
		        if ( tr.hasClass( 'open' ) ) {
		            tr.hide();
		            $(this).removeClass( 'shown' );
		            tr.addClass( 'closed' );
		            tr.removeClass( 'open' );
		        } else {
		            tr.show();
		            $(this).addClass( 'shown' );
		            tr.addClass( 'open' );
		            tr.removeClass( 'closed' );
		            results.trigger( 'x-height-change' );
		        }
		    } );


		    // Add event listener for opening and closing details
		    $('#ictdb').on('click', '#toggleInformation', function () {

		        if ( $(this).hasClass( 'shownall' ) ) {
		            $( '.detailedInfoRow' ).hide();
		            $(this).removeClass( 'shownall' );
		            $( '.detailedInfoRow' ).addClass( 'closed' );
		            $( '.detailedInfoRow' ).removeClass( 'open' );
		            $( '.summary' ).removeClass( 'shown' );
		            $(this).text( 'Show all');
		        } else {
		            $( '.detailedInfoRow' ).show();
		            $(this).addClass( 'shownall' );
		            $( '.detailedInfoRow' ).addClass( 'open' );
		            $( '.detailedInfoRow' ).removeClass( 'closed' );
		            $( '.summary' ).addClass( 'shown' );
		            $(this).text( 'Hide all');
		            results.trigger( 'x-height-change' );
		        }
		    } );

		    $( '.detailedInfoRow' ).hide();
		    results.trigger( 'x-height-change' );

			var direction = !QueryString.direction && typeof QueryString.direction === 'undefined' ? '' : QueryString.direction;
			function getColumnIndexesByClass(direction) {
					return $("." + direction).map(function() {
					         	return $(this).index() + 1; // add one because nth-child is not zero based
					}).get();		
			}
			if (direction != '') {
			 	var indexes = getColumnIndexesByClass(direction),
			 	    table = $('#ictdb-datatable');
			 	for ( var i=0; i<indexes.length; i++ ) {
			 	  table.find('tr.summary td:nth-child(' + indexes[i] + '), th:nth-child(' + indexes[i] + ')').addClass('sorting_1');
			 	}
			}	
		};

		function dollarSlider($range, $from, $to, min, max, from, to) {
		  
			$from = jQuery_1_11_1('.' + $range).parent().find('.' + $from);
			$to = jQuery_1_11_1('.' + $range).parent().find('.' + $to);
			$range = jQuery_1_11_1('.' + $range);
		  
		    $range.ionRangeSlider({
		      type: "double",
		      min: min,
		      max: max,
		      from: from,
		      to: to,
		      prefix: "$",
		      onChange: function (data) {
		        from = data.from;
		        to = data.to;
		        updateValues();
		      }
		    });

		    var slider = $range.data("ionRangeSlider");

		    $from.on("change", function () {
		      from = jQuery_1_11_1(this).prop("value");
		      if (from < min) {
		        from = min;
		      }
		      if (from > to) {
		        from = to;
		      }
		      updateValues();    
		      updateRange();
		    });

		    $to.on("change", function () {
		      to = jQuery_1_11_1(this).prop("value");
		      if (to > max) {
		        to = max;
		      }
		      if (to < from) {
		        to = from;
		      }
		      updateValues();    
		      updateRange();
		    });

		    var updateRange = function () {
		      slider.update({
		        from: from,
		        to: to
		      });
		    };

		    var updateValues = function () {
		      $from.prop("value", from);
		      $to.prop("value", to);
		    };
		}

		getExpenditureActualCost = function( ) {
			// load json data
			var sql = 'SELECT MAX(\"Actual cost to date\") AS acmax, MIN(\"Actual cost to date\") AS acmin, MAX(\"Revised total estimated expenditure\") as eemax, MIN(\"Revised total estimated expenditure\") AS eemin from ' + table;
			getDataFromCKAN( domain, sql, setExpenditureActualCost );
		};

		setExpenditureActualCost = function( jsonData   ) {
			
			var acmin = jsonData.result.records[0].acmin,
				acmax = jsonData.result.records[0].acmax,
				acfrom = ( QueryString.ActualCostFrom && typeof QueryString.ActualCostFrom !== 'undefined' ) ? unescape(QueryString.ActualCostFrom).replace(/\D/g,'') : acmin,
				acto = ( QueryString.ActualCostTo && typeof QueryString.ActualCostTo !== 'undefined' ) ? unescape(QueryString.ActualCostTo).replace(/\D/g,'') : acmax,
				eemin = jsonData.result.records[0].eemin,
				eemax = jsonData.result.records[0].eemax,
				eefrom = ( QueryString.ExpenditureFrom && typeof QueryString.ExpenditureFrom !== 'undefined' ) ? unescape(QueryString.ExpenditureFrom).replace(/\D/g,'') : eemin,
				eeto = ( QueryString.ExpenditureTo && typeof QueryString.ExpenditureTo !== 'undefined' ) ? unescape(QueryString.ExpenditureTo).replace(/\D/g,'') : eemax,
				test = ''
			;

			$( '#actualcost-from' ).val(acfrom);
			$( '#actualcost-to' ).val(acto);
			$( '#expenditure-from' ).val(eefrom);
			$( '#expenditure-to' ).val(eeto);

			dollarSlider('js-range-slider1', 'js-from', 'js-to', parseInt(eemin), parseInt(eemax), parseInt(eefrom), parseInt(eeto));
			dollarSlider('js-range-slider2', 'js-from', 'js-to', parseInt(acmin), parseInt(acmax), parseInt(acfrom), parseInt(acto));
			
		};

		populateAsideSearchForm = function( ){
			if ( QueryString.query && (typeof QueryString.query !== 'undefined' || typeof QueryString.query !== '' )) {
				$( $( 'form', '#asides' )[ 0 ][ 'query' ] ).val( QueryString.query.replace(/\+/g, ' ').replace(/\%2C/g, ',').replace(/\%2F/g, '/') );
			}

			if ( QueryString.EndBefore && (typeof QueryString.EndBefore !== 'undefined' || typeof QueryString.EndBefore !== '' )) {
				$( $( 'form', '#asides' )[ 0 ][ 'EndBefore' ] ).val( unescape( QueryString.EndBefore.replace(/\+/g, ' ') ) );
			}

			if ( QueryString.EndAfter && (typeof QueryString.EndAfter !== 'undefined' || typeof QueryString.EndAfter !== '' )) {
				$( $( 'form', '#asides' )[ 0 ][ 'EndAfter' ] ).val( unescape( QueryString.EndAfter.replace(/\+/g, ' ') ) );
			}

			
			if ( QueryString.ProjectStatusR && typeof QueryString.ProjectStatusR !== 'undefined' ) {
				$( $( 'form', '#asides' )[ 0 ][ 'ProjectStatusR' ] ).prop('checked', true);
			}

			if ( QueryString.ProjectStatusA && typeof QueryString.ProjectStatusA !== 'undefined' ) {
				$( $( 'form', '#asides' )[ 0 ][ 'ProjectStatusA' ] ).prop('checked', true);
			}

			if ( QueryString.ProjectStatusG && typeof QueryString.ProjectStatusG !== 'undefined' ) {
				$( $( 'form', '#asides' )[ 0 ][ 'ProjectStatusG' ] ).prop('checked', true);
			}

			if ( QueryString.Agency && (typeof QueryString.Agency !== 'undefined' || typeof QueryString.Agency !== '' )) {

				if ( typeof  QueryString.Agency !== 'object') {
					$( $( 'form', '#asides' )[ 0 ][ 'Agency' ] ).val( unescape( QueryString.Agency.replace(/\+/g, ' ') ) );
				} else {
					var AgencyArray = [];
					
					$.each(QueryString.Agency, function ( item, value ) {   
						//AgencyArray.push (' \"Agency\"=\'' + value.replace(/\+/g, ' ') + '\'');
						$("#Agency option[value='" + value + "']").prop("selected", true);
					});
					$("#Agency option[value='']").prop("selected", false);
				}
			}

			if ( QueryString.AdvancedSearch && (typeof QueryString.AdvancedSearch !== 'undefined' || typeof QueryString.AdvancedSearch !== '' )) {
				$( $( 'form', '#asides' )[ 0 ][ 'AdvancedSearch' ] ).val( QueryString.AdvancedSearch.replace(/\+/g, ' ').replace(/\%2C/g, ',').replace(/\%2F/g, '/') );
				$( "#asides form li.advsearch" ).toggleClass( 'hide' );
				$( ".advancedsearch" ).text('Hide advanced search');
			}


		};
		
		searchResultsCount(); 
		searchResults();
		getExpenditureActualCost();
		populateAsideSearchForm();

		// Pagination for results

		displayPagination = function( total ) {
			// current page and total results
      
			var url = $.url();
			var offset = parseInt( url.param( 'offset' ), 10 ) || 0;
			var start = (offset * 20) + 1;

			// how many results on each page
			var resultspp = 20; // per page

			// display at most 10 pages, preferably up to 5 previous pages
			var min = Math.max( 1, start - 5 * resultspp );
			var max = Math.min( total, start + 10 * resultspp );

			if (total > 20) {
				url = url.attr( 'source' ).replace( /#.*?/, '' );
				if ( ! /offset/.test( url )) {
					url += ( window.location.search.substring(1) ) ? '&offset=0' : '?offset=0';
				}

				// 'Previous' link
				if ( offset > 0 ) {
				  $( 'ul', '#pagination' ).append( '<li><a href="' + url.replace( /offset=\d+/, 'offset=' + ( offset - 1 )) + '">Previous</a></li>' );
				}

				// numbered links

				for ( var i = min; i <= max; i += resultspp ) {
					var pageNumber = Math.ceil( i / resultspp );
					var page = '<li>' + ( start === i ? '<strong>' + pageNumber + '</strong>' : '<a href="' + url.replace( /offset=\d+/, 'offset=' + ( pageNumber - 1 )) + '">' + pageNumber + '</a>' ) + '</li>';
					$( 'ul', '#pagination' ).append( page );
				}

				// 'Next' link
				if ( start + resultspp <= total ) {
				  $( 'ul', '#pagination' ).append( '<li><a href="' + url.replace( /offset=\d+/, 'offset=' + ( offset + 1 )) + '">Next</a></li>' );
				}
			}

			$( '#result-scope' ).html( total > 0 ? (((offset+1)*resultspp) > total ? (start + ' - ' + total) : (start + ' - ' + ((offset+1)*resultspp)) ) : '0' );
		};

		paginationWhenReady = function( ) {
			if ( /^\d+$/.test( $( '#total-result' ).text() )) {
				$( '.total-search-count' ).hide();
				displayPagination( parseInt( $( '#total-result' ).text(), 10 ));
			} else {
				// try again in a minute
				setTimeout( paginationWhenReady, 1000 );
			}
		};

		paginationWhenReady();

		sortableTableWhenReady = function( ) {
			// clicking on a search result should show that result
		    $( 'th', '#ictdb-datatable' ).on( 'click', 'a', function( event ) {
		    	var queryParameters = {}, 
					queryString = location.search.substring(1), 
					re = /([^&=]+)=([^&]*)/g, 
					m
				; 

				while (m = re.exec(queryString)) {
	    			queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
				}

		        var sortField = $( this ).attr( 'title' );
		        var sortFieldParam = QueryString.sort && typeof QueryString.sort !== 'undefined' ? queryParameters['sort'].replace(/\+/g, ' ') : '';
		        var direction = '';

		        if ( sortField !== sortFieldParam) {
		        	queryParameters['offset'] = '0';
		        	queryParameters['direction'] = 'asc';
		        	queryParameters['sort'] = sortField;
		        } else {
		        	queryParameters['sort'] = sortField.replace(/\+/g, ' ');
		        	if (queryParameters['direction'] === 'desc') {
				    	queryParameters['direction'] = 'asc';
				    } else {
				    	queryParameters['direction'] = 'desc';
				    }
		        }
				window.location.search = $.param(queryParameters);
		        return false;
		    });
	    };

	    sortableTableWhenReady();

	    $( '#end-after, #end-before' ).bind( 'change', function() {
 
		    var datePattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/,
		        dateField = $( this ),
		        value = dateField.val()
		    ;
		 
		    // if there is no value
		    if ( value === '' ) {
		        // clear the custom error
		        dateField[ 0 ].setCustomValidity( '' );
		        // required field validation will kick in
		 
		    // test if value matches pattern
		    } else if ( datePattern.test( value )) {
		        // valid
		        dateField[ 0 ].setCustomValidity( '' );
		    } else {
		        // invalid
		        dateField[ 0 ].setCustomValidity( 'Must be in dd/mm/yyyy format' );
		    }
		});

		$( '#expenditure-from, #expenditure-to, #actualcost-from, #actualcost-to' ).bind( 'change', function() {
 
		    var numberField = $( this );

		    if ( $.isNumeric( $( this ).val().replace(/\,/g,'') ) ) {
		        // valid
		        numberField[ 0 ].setCustomValidity( '' );
		    } else {
		        // invalid
		        numberField[ 0 ].setCustomValidity( 'Must be a number' );
		    }
		});

	    $( '#end-after, #end-before' ).datepicker({ dateFormat: 'dd/mm/yy' });
              
            
!
999px

Console