/*
Cross browser Marquee script- © Dynamic Drive (www.dynamicdrive.com)
For full source code, 100's more DHTML scripts, and Terms Of Use, visit http://www.dynamicdrive.com
Credit MUST stay intact
Script modified on 9/7/09 by RWD to include background image instead of colour.
*/

//Specify the marquee's width (in pixels)
var marqueewidth="300px"
//Specify the marquee's height
var marqueeheight="38px"
//Specify the marquee's marquee speed (larger is faster 1-10)
var marqueespeed=3
//configure background color:
var marqueebgcolor="Banner/ticker-bg.jpg"
//Pause marquee onMousever (0=no. 1=yes)?
var pauseit=1


//Specify the marquee's content (don't delete <nobr> tag)
//Keep all content on ONE line, and backslash any single quotations (ie: that\'s great):

var marqueecontent='<nobr><a href="http://www.crucible-technologies.co.uk/product-categories/energy-saving-lighting"><font size=5.5 face="Verdana" color="#ffffff">--- Click here to start saving money and CO2 ---</a></font></a></nobr>'

function populate(){
	if (iedom){
		cross_marquee=document.getElementById? document.getElementById("iemarquee") : document.all.iemarquee
		cross_marquee.style.left=parseInt(marqueewidth)+8+"px"
		cross_marquee.innerHTML=marqueecontent
		actualwidth=document.all? temp.offsetWidth : document.getElementById("temp").offsetWidth
	}
	else if (document.layers){
		ns_marquee=document.ns_marquee.document.ns_marquee2
		ns_marquee.left=parseInt(marqueewidth)+8
		ns_marquee.document.write(marqueecontent)
		ns_marquee.document.close()
		actualwidth=ns_marquee.document.width
	}
	lefttime=setInterval("scrollmarquee()",20)
}

function scrollmarquee(){
	if (iedom){
		if (parseInt(cross_marquee.style.left)>(actualwidth*(-1)+8))
			cross_marquee.style.left=parseInt(cross_marquee.style.left)-copyspeed+"px"
		else
			cross_marquee.style.left=parseInt(marqueewidth)+8+"px"
		}
	else if (document.layers){
		if (ns_marquee.left>(actualwidth*(-1)+8))
			ns_marquee.left-=copyspeed
		else
			ns_marquee.left=parseInt(marqueewidth)+8
	}
}
var copyspeed;
var pausespeed;
var iedom;
var actualwidth;
var cross_marquee, ns_marquee;

function draw_banner(){ 
	marqueespeed=(document.all)? marqueespeed : Math.max(1, marqueespeed-1) //slow speed down by 1 for NS
	copyspeed=marqueespeed
	pausespeed=(pauseit==0)? copyspeed: 0
	iedom=document.all||document.getElementById
	if (iedom)
		document.write('<span id="temp" style="visibility:hidden;position:absolute;top:-100px;left:-9000px">'+marqueecontent+'</span>')
	actualwidth=''
	
	
	window.onload=populate
	
	if (iedom||document.layers){
		with (document){
			document.write('<table border="0" cellspacing="0" cellpadding="0" background='+marqueebgcolor+'><td>')
				if (iedom){
					write('<div style="position:relative;width:'+marqueewidth+';height:'+marqueeheight+';overflow:hidden">')
					write('<div style="position:absolute;width:'+marqueewidth+';height:'+marqueeheight+';" onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed">')
					write('<div id="iemarquee" style="position:absolute;left:0px;top:0px"></div>')
					write('</div></div>')
				}
				else if (document.layers){
					write('<ilayer width='+marqueewidth+' height='+marqueeheight+' name="ns_marquee" >')
					write('<layer name="ns_marquee2" left=0 top=0 onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed"></layer>')
					write('</ilayer>')
				}
				document.write('</td></table>')
		}
	}
}

	var myOdometer;
	var n;
	var persec;
	function run () {
		var arry = CSVToArray(clientSideInclude("CO2/co2.csv"), ",");
		n = returnCO2start(arry);
		persec = returnCO2(arry) /365 /60 /60 /24;
		var div = document.getElementById("odometerDiv");
		myOdometer = new Odometer(div, {value: n, digits: 6, tenths: true});
		setInterval("updaten()",10);
	}
	
	function updaten()
	{
		n=n+(persec/100);
		myOdometer.set(n);
	}
		// This will parse a delimited string into an array of
    // arrays. The default delimiter is the comma, but this
    // can be overriden in the second argument.
    function CSVToArray( strData, strDelimiter ){
        // Check to see if the delimiter is defined. If not,
        // then default to comma.
        strDelimiter = (strDelimiter || ",");

        // Create a regular expression to parse the CSV values.
        var objPattern = new RegExp(
                (
                        // Delimiters.
                        "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

                        // Quoted fields.
                        "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

                        // Standard fields.
                        "([^\"\\" + strDelimiter + "\\r\\n]*))"
                ),
                "gi"
                );


        // Create an array to hold our data. Give the array
        // a default empty first row.
        var arrData = [[]];

        // Create an array to hold our individual pattern
        // matching groups.
        var arrMatches = null;


        // Keep looping over the regular expression matches
        // until we can no longer find a match.
        while (arrMatches = objPattern.exec( strData )){

                // Get the delimiter that was found.
                var strMatchedDelimiter = arrMatches[ 1 ];

                // Check to see if the given delimiter has a length
                // (is not the start of string) and if it matches
                // field delimiter. If id does not, then we know
                // that this delimiter is a row delimiter.
                if (
                        strMatchedDelimiter.length &&
                        (strMatchedDelimiter != strDelimiter)
                        ){

                        // Since we have reached a new row of data,
                        // add an empty row to our data array.
                        arrData.push( [] );

                }


                // Now that we have our delimiter out of the way,
                // let's check to see which kind of value we
                // captured (quoted or unquoted).
                if (arrMatches[ 2 ]){

                        // We found a quoted value. When we capture
                        // this value, unescape any double quotes.
                        var strMatchedValue = arrMatches[ 2 ].replace(
                                new RegExp( "\"\"", "g" ),
                                "\""
                                );

                } else {

                        // We found a non-quoted value.
                        var strMatchedValue = arrMatches[ 3 ];

                }


                // Now that we have our value string, let's add
                // it to the data array.
                arrData[ arrData.length - 1 ].push( strMatchedValue );
        }

        // Return the parsed data.
        return( arrData );
    }
    
    function clientSideInclude(url) {
      var req = false;
      // For Safari, Firefox, and other non-MS browsers
      if (window.XMLHttpRequest) {
        try {
          req = new XMLHttpRequest();
        } catch (e) {
          req = false;
        }
      } else if (window.ActiveXObject) {
        // For Internet Explorer on Windows
        try {
          req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
          try {
            req = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (e) {
            req = false;
          }
        }
      }
      if (req) {
        // Synchronous request, wait till we have it all
        req.open('GET', url, false);
        req.send(null);
        return req.responseText;
      } else {
        return
       "Sorry, your browser does not support " +
          "XMLHTTPRequest objects. This page requires " +
          "Internet Explorer 5 or better for Windows, " +
          "or Firefox for any system, or Safari. Other " +
          "compatible browsers may also exist.";
      }
    }

function returnCO2 (arr)
{
 	var co2 = 0;
 	var i = 1;
 	for (; i!= arr.length; i++)
 	{
 		var t = parseInt(arr[i][9]);
 		if (typeof t == 'number' && t > 0)
 		{
 			co2+=parseInt(arr[i][9]);
 		}
 	}
 	return co2;	
 }

function returnCO2start (arr)
{
 	var co2 = 0;
 	var today = new Date();
 	var i = 1;
 	for (; i!= arr.length; i++)
 	{
		if (arr[i][0] != null && arr[i][9] != null && arr[i][9] != "" && arr[i][0] != "")
		{
			var t = arr[i][0];
			var datestring = t.substr(3,2) + "/" + t.substr(0,2) + "/" + t.substr(6,4);
			var startdate = new Date(datestring);
			var daysdiff = (today.getTime() - startdate.getTime()) /1000 /60 /60 /24;
			var t = parseInt(arr[i][9]);
			co2+=parseInt(arr[i][9])/365*daysdiff;
		}
 	}
 	return co2;	
 }
 
 
function Odometer (parentDiv,opts) {
     if (!parentDiv) throw "ERROR: Odometer object must be past a document element.";
 
     this.digits       = 6;
     this.tenths       = 0;
     this.digitHeight  = 20;
     this.digitPadding = 0;
     this.digitWidth   = 15;
     this.bustedness   = 2;
     this.fontStyle    = "font-family: Courier New, Courier, monospace; font-weight: 900;";
     this.value        = -1;
 
     for (var key in opts) { this[key] = opts[key]; }
 
     var style = {
         digits:        "position:absolute; height:"+this.digitHeight+"px; width:"+(this.digitWidth-(2*this.digitPadding))+"px; "+
                        "padding:"+this.digitPadding+"px; font-size:"+(this.digitHeight-(2*this.digitPadding))+"px; "+
                        "background:black; color:white; text-align:center; "+this.fontStyle,
         columns:       "position:relative; float:left; overflow:hidden;"+
                        "height:"+this.digitHeight+"px; width:"+this.digitWidth+"px;",
         highlight:     "position:absolute; background:white; opacity:0.25; filter:alpha(opacity=25); width:100%; left:0px;",
         lowlight:      "position:absolute; background:black; opacity:0.25; filter:alpha(opacity=25); width:100%; left:0px;",
         sidehighlight: "position:absolute; background:white; opacity:0.50; filter:alpha(opacity=50); height:100%; top:0px;",
         sidelowlight:  "position:absolute; background:black; opacity:0.50; filter:alpha(opacity=50); height:100%; top:0px;"
     };
 
     var highlights = [
         "top:20%;   height:32%;" + style.highlight,
         "top:27.5%; height:16%;" + style.highlight,
         "top:32.5%; height:6%;"  + style.highlight,
         "right:0%;  width:6%;"   + style.sidelowlight,
         "left:0%;   width:4%;"   + style.sidehighlight,
         "top:0%;    height:14%;" + style.lowlight,
         "bottom:0%; height:25%;" + style.lowlight,
         "bottom:0%; height:8%;"  + style.lowlight
     ];
 
     this.setDigitValue = function (digit, val, frac) {
 	var di = digitInfo[digit];
        	var px = Math.floor(this.digitHeight * frac);
 	px = px + di.offset;
 	if (val != di.last_val) {
 		var tmp = di.digitA;
 		di.digitA = di.digitB;
 		di.digitB = tmp;
         	di.digitA.innerHTML = val;
         	di.digitB.innerHTML = (1+Number(val)) % 10;
 		di.last_val = val;
 	}
 	if (px != di.last_px) {
         	di.digitA.style.top = (0-px)+"px";
         	di.digitB.style.top = (0-px+this.digitHeight)+"px";
 		di.last_px = px;
 	}
     };
 
 
     this.set = function (inVal) {
         if (inVal < 0) throw "ERROR: Odometer value cannot be negative.";
 	this.value = inVal;
 	if (this.tenths) inVal = inVal * 10;
         var numb = Math.floor(inVal);
         var frac = inVal - numb;
 	numb = String(numb);
         for (var i=0; i < this.digits; i++) {
             var num = numb.substring(numb.length-i-1, numb.length-i) || 0;
             this.setDigitValue(this.digits-i-1, num, frac);
             if (num != 9) frac = 0;
         }
     };
 
     this.get = function () {
         return(this.value);
     };
 
 
     var odometerDiv = document.createElement("div")
     odometerDiv.setAttribute("id","odometer");
     odometerDiv.style.cssText="text-align: left";
     parentDiv.appendChild(odometerDiv);
 
     var digitInfo = new Array();
     for (var i=0; i < this.digits; i++) {
         var digitDivA = document.createElement("div");
         digitDivA.setAttribute("id","odometer_digit_"+i+"a");
         digitDivA.style.cssText=style.digits;
 
         var digitDivB = document.createElement("div");
         digitDivB.setAttribute("id","odometer_digit_"+i+"b");
         digitDivB.style.cssText = style.digits;
 
         var digitColDiv = document.createElement("div");
         digitColDiv.style.cssText = style.columns;
 
         digitColDiv.appendChild(digitDivB);
         digitColDiv.appendChild(digitDivA);
 
         for (var j in highlights) {
             var hdiv = document.createElement("div");
             hdiv.innerHTML="<p></p>"; // For Dumb IE
             hdiv.style.cssText = highlights[j];
             digitColDiv.appendChild(hdiv);
         }
         odometerDiv.appendChild(digitColDiv);
 	var offset = Math.floor(Math.random()*this.bustedness);
 	digitInfo.push({digitA:digitDivA, digitB:digitDivB, last_val:-1, last_px: -1, offset:offset});
     };
 
 
     if (this.tenths) {
 	digitInfo[this.digits - 1].digitA.style.background = "#cccccc";
 	digitInfo[this.digits - 1].digitB.style.background = "#cccccc";
 	digitInfo[this.digits - 1].digitA.style.color = "#000000";
 	digitInfo[this.digits - 1].digitB.style.color = "#000000";
     }
 
     if (this.value >= 0) this.set(this.value);
 }

 
