/*
Start date: 12/6/04
EST: 1102309200 (midnight)
GMT: 1102327200 (5am)

Saves 1 ton of CO2 every 13 seconds

Saves 1 ton of Energy every 40 seconds

Saves 10 tons of water every 3 seconds

Good localization reference.  Not exactly what we need, but a good idea:
http://www.jspwiki.org/wiki/JavascriptLocalization
*/


// -----------------------------------------------------------------------------
// Class Declarations ----------------------------------------------------------
// -----------------------------------------------------------------------------

/**
 */
function ArmstrongGlobalSavings() {
    this.savings = new Array();
    this.savings[0] = new ArmstrongCO2Savings();
    this.savings[1] = new ArmstrongEnergySavings();
    this.savings[2] = new ArmstrongWaterSavings();
}

ArmstrongGlobalSavings.prototype.activate = function() {
    var buffer = "\n<div>\n";
    
    var size = this.savings.length;
    for(var i = 0; i < size; i++) {
        //buffer += "<div id='" + this.savings[i].idPrefix + "_value'></div>";
        buffer += this.savings[i].display();
        // I would prefer to use setInterval here, but there is a bug with multiple setInterval in Firefox...
        //setInterval("armSavings.update(" + i + ")", 1000);
        setTimeout("armSavings.update(" + i + ")", 1000);
    }
    
    buffer += "</div>\n"
    
    document.write(buffer);
}

ArmstrongGlobalSavings.prototype.update = function(index) {
    setTimeout("armSavings.update(" + index + ")", 1000);// Call this first behavior is closer to setInterval
    this.savings[index].update();
}

/**
 * Basic savings calculator.  Should be extended.
 */
function ArmstrongBaseSavings() {
    this.init();
}

/**
 * Configure variables.  Must be done in init() function so they can be inherited.
 */
ArmstrongBaseSavings.prototype.init = function() {
    //this.imgPath = "/drupal_stage/files/images/digits/";
    this.imgPath = "/files/images/digits/";
    this.imgExt = "gif";
    this.width = 11;
    this.idPrefix = "default";
    this.currentValue = 0;
    this.labels = new Array();
    this.label = "Default Label:";
}

ArmstrongBaseSavings.prototype.createImg = function(id, digitName) {
    return "<img id='" + id + "' src='" + this.imgPath + digitName + "." + this.imgExt + "' style='margin: 0; padding: 0;' hspace='0' vspace='0' border='0' />";
}

/**
 * Returns HTML to display.  Does not actually print to screen.
 */
ArmstrongBaseSavings.prototype.display = function() {
    var buffer = "<div>\n";
    
    //TODO: Add label
    //buffer += "<div style='font-size: 1em; font-face: bold;'>" + this.label + "</div>\n";
    buffer += "<p style='margin: 0; padding: 0;'><strong>" + this.label + "</strong></p>\n";

    for(var i = 0; i < this.width; i++) {
        buffer += this.createImg(this.idPrefix + "_" + i, "off");
    }
    
    //TODO: Add units
    
    buffer += "</div>\n";
    
    return buffer;
}

/**
 * Updates current value and graphic display
 */
ArmstrongBaseSavings.prototype.update = function() {
    this.currentValue = this.calculateNewValue(this.currentValue);
    
    // Update the images based on currentValue
    var formattedValue = this.formatValue(this.currentValue, this.width)
    
    //var div = document.getElementById(this.idPrefix + "_value");
    //div.innerHTML = formattedValue;
    //div.innerHTML = this.currentValue;
    
    for(var i = 0; i < this.width; i++) {
        var img = document.getElementById(this.idPrefix + "_" + i);
        var newSrc = this.imgPath + this.toFileName(formattedValue.charAt(i)) + "." + this.imgExt;
        if(newSrc != img.src) {
            img.src = newSrc;
        }
    }
}

/**
 * Converts given digit to the corresponding filename
 */
ArmstrongBaseSavings.prototype.toFileName = function(digit) {
    if("," == digit) {
        return "comma";
    } else if("_" == digit) {
        return "off";
    } else if(" " == digit) {
        return "space";
    } else {
        return digit;
    }
}

/**
 * Formats the supplied value as a string.
 * Will zero-pad or truncate to width
 * Only handles integer for now.
 *
 * TODO: Could add commas or decimal points.
 *
 * @param int value the values as an integer
 * @param int width width to pad/truncate to
 * @return int the value as a formatted string
 */
ArmstrongBaseSavings.prototype.formatValue = function(value, width) {
    var strVal = value + "";
    
    // Partial source: http://www.mredkj.com/javascript/nfbasic.html
	x = strVal.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	strVal = x1 + x2;
    
    if(strVal.length > width) {
        return strVal.substring(strVal.length - width);
    }
    
    while(strVal.length < width) {
        strVal = "_" + strVal;
    }
    
    return strVal;
}

/**
 * Calculates new display value.
 * Subclasses should override this function.
 *
 * @param int oldValue the previous value
 * @return int the new value
 */
ArmstrongBaseSavings.prototype.calculateNewValue = function(oldValue) {
    return oldValue + 1;
}

/**
 *
 */
function ArmstrongCO2Savings() {
    this.init();
    this.idPrefix = "co2";
    
    // Translated labels go here
    // Remove '//' when adding a translation
    this.labels["en"]      = "1 ton of CO<sub>2</sub> every 13 seconds<br /><img src='' width='1px' height='3px'/>";
    this.labels["de"]      = "1 Tonne CO2 alle 13 Sekunden";
    //this.labels["en-IN"]   = "1 ton of CO<sub>2</sub> every 13 seconds<br /><img src='' width='1px' height='3px'/>";
    //this.labels["es"]      = "1 tonelada de CO2 cada 13 segundos";
    //this.labels["fr"]      = "1 tonne de CO2 toutes les 13 secondes";
    //this.labels["it"]      = "1 Tonnellata di CO2 ogni 13 secondi";
    //this.labels["ru"]      = "1 ????? CO2 ?????? 13 ??????";
    //this.labels["zh-hans"] = "?13??,??1?????(CO2)???40??,??1????40??,??1???";
    //this.labels["ko"]      = "? 13? ?? CO2 1?";
    
    var label = this.labels[drupalLanguage];
    this.label = label ? label : this.labels["en"];
}
copyPrototype(ArmstrongCO2Savings, ArmstrongBaseSavings);

ArmstrongCO2Savings.prototype.calculateNewValue = function(oldValue) {
    //Saves 1 ton of CO2 every 13 seconds
    
    var date = new Date();
    var nowSeconds = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()) / 1000;
    var seconds = nowSeconds - 1102327200;
    
    return parseInt(seconds / 13);//tons
}

/**
 *
 */
function ArmstrongEnergySavings() {
    this.init();
    this.idPrefix = "energy";
    
    // Translated labels go here
    // Remove '//' when adding a translation
    this.labels["en"]      = "1 ton of FUEL every 40 seconds";
    this.labels["de"]      = "1 Tonne Kraftstoff alle 40 Sekunden";
    //this.labels["en-IN"]   = "1 ton of FUEL every 40 seconds";
    //this.labels["es"]      = "1 tonelada de combustible cada 40 segundos";
    //this.labels["fr"]      = "1 tonne de COMBUSTIBLE toutes les 40 secondes";
    //this.labels["it"]      = "1 Tonnellata di combustibile ogni 40 secondi";
    //this.labels["ru"]      = "1 ????? ??????? ?????? 40 ??????";
    //this.labels["zh-hans"] = "?40??,??1???";
    //this.labels["ko"]      = "? 40? ?? FUEL 1? ";
    
    var label = this.labels[drupalLanguage];
    this.label = label ? label : this.labels["en"];
}
copyPrototype(ArmstrongEnergySavings, ArmstrongBaseSavings);

ArmstrongEnergySavings.prototype.calculateNewValue = function(oldValue) {
    //Saves 1 ton of Energy every 40 seconds
       
    var date = new Date();
    var nowSeconds = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()) / 1000;
    var seconds = nowSeconds - 1102327200;
    
    return parseInt(seconds / 40);//tons
}

/**
 *
 */
function ArmstrongWaterSavings() {
    this.init();
    this.idPrefix = "water";
    
    // Translated labels go here
    // Remove '//' when adding a translation
    this.labels["en"]      = "10 tons of WATER every 3 seconds";
    this.labels["de"]      = "10 Tonnen Wasser alle 3 Sekunden";
    //this.labels["en-IN"]   = "10 tons of WATER every 3 seconds";
    //this.labels["es"]      = "10 toneladas de agua cada 3 segundos";
    //this.labels["fr"]      = "10 tonnes d'EAU toutes les 3 secondes";
    //this.labels["it"]      = "10 Tonnellata di acqua ogni 3 secondi";
    //this.labels["ru"]      = "10 ???? ???? ?????? 3 ???????";
    //this.labels["zh-hans"] = "?3??,??10??";
    //this.labels["ko"]      = "? 3? ?? WATER 10?";
    
    var label = this.labels[drupalLanguage];
    this.label = label ? label : this.labels["en"];
}
copyPrototype(ArmstrongWaterSavings, ArmstrongBaseSavings); 

ArmstrongWaterSavings.prototype.calculateNewValue = function(oldValue) {
    //Saves 10 tons of water every 3 seconds
    
    var date = new Date();
    var nowSeconds = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()) / 1000;
    var seconds = nowSeconds - 1102327200;
    
    return parseInt(10 * (seconds / 3));//tons
}

// -----------------------------------------------------------------------------
// Main Scope ------------------------------------------------------------------
// -----------------------------------------------------------------------------

var drupalLanguage = getDrupalLanguage();

var armSavings = new ArmstrongGlobalSavings();
armSavings.activate();

//var time = new Date()
//var gmtMS = time.getTime() + (time.getTimezoneOffset() * 60000)
//var gmtTime = new Date(gmtMS)

//alert(gmtMS);
//alert(gmtTime.toUTCString());
//alert(time.toUTCString());
//document.write(time.getTime());

// -----------------------------------------------------------------------------
// Global Functions ------------------------------------------------------------
// -----------------------------------------------------------------------------

/**
 * Provides basic inheritance.
 *
 * Source: http://www.sitepoint.com/blogs/2006/01/17/javascript-inheritance/
 */
function copyPrototype(descendant, parent) { 
    var sConstructor = parent.toString(); 
    var aMatch = sConstructor.match( /\s*function (.*)\(/ ); 
    if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; } 
    for (var m in parent.prototype) { 
        descendant.prototype[m] = parent.prototype[m]; 
    } 
}

/**
 * Reads drupal_locale meta tag to get current language.
 * This is a custom Armstrong tag.
 */
function getDrupalLanguage() {
    var metaElements = document.all ?
        document.all.tags('META') :
        document.getElementsByTagName ?
        document.getElementsByTagName('META') : new Array();
    var drupalLanguage = "en";
    var i = 0;
    for (var i = 0; i < metaElements.length; i++) {
        var element = metaElements[i];
        if (element.name == 'drupal_locale') {
            var content = element.content;
            if(content && content.length > 0) {
                return content;
            }
        }
    }
    
    return drupalLanguage;
}

/**
 * Constructs a multi-digit number
 *
 * TODO: Add commas (maybe include commas in string and this function figures out the image name) Could even do: "0012,345 KWH", maybe leading zeros are "off" LEDs
 * TODO: Add leading zeros??
 */
 /*
function createNumber(number) {
    var html = "";
    var length = number.length;
    for(var i = 0; i < length; i++) {
        html += createImg("", number.charAt(i));
    }
    return html;
}
*/

/*
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function addSeparatorsNF(nStr, inD, outD, sep)
{
	nStr += '';
	var dpos = nStr.indexOf(inD);
	var nStrEnd = '';
	if (dpos != -1) {
		nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
		nStr = nStr.substring(0, dpos);
	}
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(nStr)) {
		nStr = nStr.replace(rgx, '$1' + sep + '$2');
	}
	return nStr + nStrEnd;
}
*/

