// Configuration of the web GUI
var confMode = true;	// true = with config button
						// false = without config button
var docReady = false;                        
var langList = 'DEDE,ENUS,ITIT,ESES,FRFR,PTPT,NLNL,CSCZ,TRTR,HUHU,PLPL,RORO,SLSI';
var monthNameList  = [ '', '', '', '', '', '', '', '', '', '', '', '' ];
var dayNameMinList = [ '', '', '', '', '', '', '' ]; 
var nennleistung = '';
var unbekannt = '';
var heute = '';
var dieserMonat = '';
var diesesJahr = '';
var uhrzeit = '';
var tag = '';
var monat = '';
var jahr = '';
var keineDaten = '';
var pvsp1 = '';
var pvsp2 = '';
var pvsp3 = '';
var pvst1 = '';
var pvst2 = '';
var pvst3 = '';
var nsp1 = '';
var nsp2 = '';
var nsp3 = '';
var nst1 = '';
var nst2 = '';
var nst3 = '';
var pvl1 = '';
var pvl2 = '';
var pvl3 = '';
var temperatur = '';
var nl = '';
var gesamtUebersicht = '';
var gesamtAnsicht = '';
var jahresAnsicht = '';
var monatsAnsicht = '';
var tagesAnsicht = '';
var toolAnsicht = '';
var einPhasig = '';
var dreiPhasig = '';
var datumsFormat = 'd.m.y, h:i:s'; // d = day, m = month, y = year, h = hours (24h), H = hours (12h), i = minutes, s = seconds, n = AM/PM
var containerOn = false; // Is webpage shown?
var startCount = 1;
var secCnt = 29;
var pauseRealtime = false;
var loadingTxt = 'Loading...';
var realTimeReq = false;
var realTimeReqCnt = 0;
var totalYieldFromCsvHeader = 0;
var firstLoadData = true;
if (!String.pad) 
{
    String.prototype.pad = function(l, s, t) 
    {
        return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length) + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2)) + this + s.substr(0, l - t) : this;
    };
}
if (!String.trim) 
{
    String.prototype.trim = function() 
    {
        return this.replace(/^\s*/, "").replace(/\s*$/, "");
    }
}
// ----------- change fav icon ---------------
document.head = document.head || document.getElementsByTagName('head')[0];
function changeFavicon(src) 
{
    var link = document.createElement('link'), oldLink = document.getElementById('favicon');
    link.id = 'favicon';
    link.rel = 'shortcut icon';
    link.href = src;
    if (oldLink) 
    {
        document.head.removeChild(oldLink);
    }
    document.head.appendChild(link);
}
// ------------------------------------------
// ----------- disable href ---------------
function disableAnchor(objId, disable) 
{ 
	var obj = document.getElementById(objId); 
	if(obj != null) 
	{ 
        if(disable) 
        { 
            var href = obj.getAttribute("href"); 
            var onclick = obj.getAttribute("onclick"); 
            //First we store previous value in a new attribute 
            if(href && href != "" && href != null) 
            { 
                obj.setAttribute('href_bak', href); 
            } 
            if(onclick != null) 
            { 
                obj.setAttribute('onclick_back', onclick); 
                obj.setAttribute('onclick', "void(0);"); 
            } 
            obj.removeAttribute('href'); 
            obj.style.color="gray";
            //obj.style.addClass('naviItemDisabled');
            //obj.style.textDecoration="none";
        } 
        else 
        { 
            var hrefBack = obj.getAttribute("href_bak"); 
            var onclickBack = obj.getAttribute("onclick_back"); 
            if(onclickBack !=null ) 
            { 
                obj.setAttribute('onclick', onclickBack); 
                obj.removeAttribute('onclick_back'); 
            } 
            if(hrefBack !=null ) 
            { 
                obj.setAttribute('href', hrefBack); 
                obj.removeAttribute('href_bak'); 
                obj.style.color="#ffffff";
                //obj.style.removeClass('naviItemDisabled');
                //obj.style.textDecoration="underline";
            } 
        } 
	} 
}
// ------------------------------------------
function getRect (o)
{ 
    var r = { top:0, left:0, width:0, height:0 }; 
    
	if(!o) 
		return r; 
    else 
		if(typeof o == 'string' ) o = document.getElementById(o);
		
    if( typeof o != 'object' ) 
		return r; 
		
    if(typeof o.offsetTop != 'undefined')    
	{ 
		r.height = o.offsetHeight; 
        r.width = o.offsetWidth; 
        r.left = r.top = 0; 
        while (o && o.tagName != 'BODY')         
		{ 
            r.top  += parseInt( o.offsetTop ); 
            r.left += parseInt( o.offsetLeft ); 
            o = o.offsetParent; 
        } 
    } 
    return r; 
} 
function moveDivTo(o, x, y) 
{
	if( !o ) 
		return -1;
	
	if( o.style ) 
	{ 
		o = o.style; 
	}
	var noPx = document.childNodes ? 'px' : 0;
	o.left = x + noPx;
	o.top = y + noPx;
	return 0;
}
function str_replace(find, replace, src) 
{
    return src.split(find).join(replace);
}
function getFloatVal(str) 
{
    return str_replace(",", ".", str);
}
function createVersionNumber(number) 
{
    var n = number.toString();
    n = "V" + n.substring(0,n.length-2) + "." + n.substring(n.length-2,n.length);
    return n;
}
function roundCommaSeparated(x, n) 
{
    var k = (Math.round(x * 100) / 100).toString();
    var p = 0;
    if (n == 2)
    {
        k += (k.indexOf('.') == -1)? '.00' : '00';
        var p = k.indexOf('.');
        return k.substring(0, p) + ',' + k.substring(p+1, p+3);
    }
    else if (n = 1)
    {
        k += (k.indexOf('.') == -1)? '.0' : '0';
        var p = k.indexOf('.');
        return k.substring(0, p) + ',' + k.substring(p+1, p+2);
    }   
}
function num_format(num, prec) 
{
	var n = num.toString();
	var nums = n.split('.');
	var newNum = "";
	if (nums.length > 1) 
	{
		var dec = nums[1].substring(0, prec);
		newNum = nums[0] + "," + dec + (nums[1].length < prec ? "0" : "");
	} 
	else 
	{
		newNum = num;
	}
	return newNum;
}
function inList(psString, psList) 
{
    var laList = psList.split(',');
    var i = laList.length;
    while (i--) {
        if (laList[i] === psString) return true;
    }
    return false;
}
$( document ).ready(function() {
    docReady = true;
})
var kaco = {
    csv : '',
    initCount : 0,
    mode : '',
    view : null,
    tstamp : null,
    dcCount : 0,
    acCount : 0,
    acVoltPhaseMon : 0,
    acCurrPhaseMon : 0,
    showAcPhaseMonMode : 0,
    
    initDate : new Date(2011, 0, 1, 0, 0, 0),
    langId : '',
    pktVer : '',
    armVersion : '',
    armChecksum : '',
    cfgVersion : '',
    cfgChecksum : '',
    dspVersion : '',
    dspChecksum : '',
    picVersion : '',
    picChecksum : '',
    vendorName : '',
    override : false,
    dataIndex : null,
    data : {},
    state : {},
    langText : {},
    noDataMode : false,
    
    switchConfMode : function(confMd)
    {   
        if (confMd == true)
		{   // Navigation bar with "Config" button
			$("ul#navi").css({
				"left" : 30 + "px"
			});
			$("ul#navi li.naviSpacer").css({
				"line-height" : 10 + "px",
				"margin" : 0 + " " + 35 + "px"
			});			
			$("#viewConfig").show();
			$("#viewConfigSpacer").show();
			$("#navi").trigger("create");
			$("#navi").show();
		}
		else
		{   // Navigation bar without "Config" button
			$("ul#navi").css({
				"left" : 50 + "px"
			});
			$("ul#navi li.naviSpacer").css({
				"line-height" : 15 + "px",
				"margin" : 0 + " " + 50 + "px"
			});
			$("#viewConfig").hide();
			$("#viewConfigSpacer").hide();
			$("#navi").trigger("create");
			$("#navi").show();
		}
    },
    start : function() 
    {	
		// Disbable cache for all jQuery AJAX requests
		//$.ajaxSetup({ cache: false });
		
		/* Errorhandler
		$(document).ajaxError(function(e, xhr, opts, err){
			var status = (xhr || {}).status;
			xhr = null;
			setTimeout(function(){
				throw(e.type +' | '+ status +' | '+ opts.url);
			}, 0);
		});
		*/
        $('#updateButton').hide();
        
        $('#toggleAdvanced').live('click',function(){
            if ($('#extendTable').css('display')=='none') 
            {
                $('#extendTable').css({'display':'block'});
            } 
            else 
            {
                $('#extendTable').css({'display':'none'});
            }
        });
        $('#showPreset1').live('click',function(){
            if ($(this).attr('checked')) 
            {
                $('input').removeAttr('checked');
                $('#pac').attr('checked','checked');
                $(this).attr('checked','checked');
            } 
            else 
            {
                $('input').removeAttr('checked');
            }
            kaco.updateVisibleDayGraphs();
        });
        
        $('#showPreset2').live('click',function() 
        {
            if ($(this).attr('checked')) 
            {
                $('input').removeAttr('checked');
                $('#pvl1').attr('checked','checked');
                if (kaco.dcCount == 2) 
                {
                    $('#pvl2').attr('checked','checked');
                }
                if (kaco.dcCount == 3) 
                {
                    $('#pvl2, #pvl3').attr('checked','checked');
                }
                $(this).attr('checked','checked');
            } 
            else 
            {
                $('input').removeAttr('checked');
            }
            kaco.updateVisibleDayGraphs();
        });
        
        $('#showPreset3').live('click',function(){
            if ($(this).attr('checked')) 
            {
                $('input').removeAttr('checked');
                $('#pvsp1').attr('checked','checked');
                if(kaco.dcCount == 2) 
                {
                    $('#pvsp2').attr('checked','checked');
                }
                if(kaco.dcCount == 3) 
                {
                    $('#pvsp2, #pvsp3').attr('checked','checked');
                }
                $(this).attr('checked','checked');
            } 
            else 
            {
                $('input').removeAttr('checked');
            }
            kaco.updateVisibleDayGraphs();
        });
        
        $('.detail').live('click',function(){
            $('.preset').removeAttr('checked');
            kaco.updateVisibleDayGraphs();
        });
        
        $.ajax({
            cache: false,
            url : this.csv + '/initlog.txt',
            //async : false,
            context : this,
            success : kaco.parseInitlog
        });
        
        $.ajax({
            cache: false,
            url : this.csv + '/meta.csv',
            //async : false,
            context : this,
            success : kaco.parseMeta
        });
        this.tstamp = new Date();
        $("#chartContainer").bind("plotclick", function(event, pos, item){
            if (item) 
            {
                var val = item.datapoint[0];
                switch (kaco.mode) 
                {
                    case 'ETERNAL': 
                    {
                        kaco.tstamp.setYear(val);
                        kaco.switchToYearView();
                        break;
                    }
                    case 'YEAR': 
                    {
                        kaco.tstamp.setMonth(val - 1);
                        kaco.switchToMonthView();
                        break;
                    }
                    case 'MONTH': 
                    {
                        kaco.tstamp.setDate(val);
                        kaco.switchToDayView(true);
                        break;
                    }
                }
            }
        });
        $("#chartContainer").bind("plothover", function(event, pos, item){
            if (item) 
            {
                kaco.showHover(item);
            } 
            else 
            {
                $("#tooltip").remove();
                kaco.dataIndex = null;
            }
        });
		             
        // Start updater thread
        //setInterval(function() { kaco.triggerRealtimeUpdate(); }, 30000);
        setInterval(function() { kaco.triggerRealtimeUpdate(); }, 1000);
        
        // Timer for web config 500ms
        setInterval(function() { kaco.triggerWebConfig(); }, 500);
        // Timer for web config 1 Min
        setInterval(function() { kaco.trigger1MinTimerWebConfig(); }, 60000);
        
        // Init graph without loading of data
        this.switchToDayView(false);
			  	
        //this.switchConfMode(confMode);
        
        paraData[paraIndexWebgui][PARA_OFFS] = DEBUG;
        switchDebug(paraData[paraIndexWebgui][PARA_OFFS]);
    },
    
    showHover : function(item) 
    {
        var x = item.pageX + 10;
        var y = item.pageY + 10;
        var contents = item.datapoint[1].toFixed(2);
        if (this.dataIndex != item.dataIndex) 
        {
            this.dataIndex = item.dataIndex;
            $("#tooltip").remove();
            $('<div id="tooltip">' + contents + '</div>').css({
                position : 'absolute',
                display : 'none',
                top : y,
                left : x,
                border : '1px solid #fdd',
                padding : '2px',
                'background-color' : '#ccc',
                opacity : 0.9
            }).appendTo("body").fadeIn(200);
        }
    },
    parseInitlog: function(data) 
    {
        var fields = data.split(';');
        kaco.initCount++;
    },
    parseStatus : function(data) 
    {
        var lines = data.split('\r');
        for (var x = 0; x < lines.length; x++) 
        {
            var entry = lines[x].split('  ');
            this.state[entry[0].trim()] = entry[1].trim();
        }
        if (kaco.initCount < 4)
            kaco.initCount++;
    },
    parseLangText : function(data) 
    {
        var lines = data.split('\r');
        for (var x = 0; x < lines.length; x++) 
        {
            var entry = lines[x].split('  ');
            this.langText[entry[0].trim()] = entry[1].trim();
        }
        for (var i=0; i<12; i++)
        {
            monthNameList[i] = this.langText[i];
        }
        unbekannt = this.langText[13];
        heute = this.langText[14];
        dieserMonat = this.langText[15];
        diesesJahr = this.langText[16];
        uhrzeit = this.langText[17];
        $('#axisLabel').html(uhrzeit);
        tag = this.langText[18];
        monat = this.langText[19];
        jahr = this.langText[20];
        keineDaten = this.langText[21];
        pvsp1 = this.langText[22];
        pvsp2 = this.langText[23];
        pvsp3 = this.langText[24];
        pvst1 = this.langText[25];
        pvst2 = this.langText[26];
        pvst3 = this.langText[27];
        nsp1 = this.langText[28];
        nsp2 = this.langText[29];
        nsp3 = this.langText[30];
        nst1 = this.langText[31];
        nst2 = this.langText[32];
        nst3 = this.langText[33];
        pvl1 = this.langText[34];
        pvl2 = this.langText[35];
        pvl3 = this.langText[36];
        temperatur = this.langText[37];
        nl = this.langText[38];
		parameter = this.langText[39];
        gesamtAnsicht = this.langText[41];
        jahresAnsicht = this.langText[42];
        monatsAnsicht = this.langText[43];
        tagesAnsicht = this.langText[44];
        toolAnsicht = this.langText[39];
        $('#viewDay').attr('title',this.langText[44]);
        $('a#viewDay').text(this.langText[44]);
        $('#viewMonth').attr('title',this.langText[43]);
        $('a#viewMonth').text(this.langText[43]);
        $('#viewYear').attr('title',this.langText[42]);
        $('a#viewYear').text(this.langText[42]);
        $('#viewEternal').attr('title',this.langText[41]);
        $('a#viewEternal').text(this.langText[41]);
        $('#viewConfig').attr('title',this.langText[39]);
        $('a#viewConfig').text(this.langText[39]);
        $('#currentScreenTitle').html(this.view.getTitle(this.tstamp));
        
        nennleistung = this.langText[12];
        dreiPhasig = this.langText[46];
        einPhasig = this.langText[45];
        var type = roundCommaSeparated((this.acPower / 1000), 2) + ' kW ' + nennleistung + ', ';
        if (this.acCount == 3) 
        {
            type += dreiPhasig;
            $("input.a3").css( {
                display : 'block'
            });
        } 
        else 
        {
            type += einPhasig;		 
        }
        $('#type').html(type);
            
        $('th#devName').text(this.langText[48]);
        $('th#devAddr').text(this.langText[49]);
        $('th#devTyp').text(this.langText[50]);
        $('th#devNetAddr').text(this.langText[51]);
        $('th#devSerNo').text(this.langText[52]);
        $('th#devMacAddr').text(this.langText[53]);
        $('th#dataRev').text(this.langText[54]);
        $('#lblHrefGoToFirst').attr('title',this.langText[63]);
        $('#lblAltGoToFirst').attr('alt',this.langText[64]);
        $('#lblHrefGoOneBack').attr('title',this.langText[65]);
        $('#lblAltGoOneBack').attr('alt',this.langText[66]);
        $('#lblHrefGoOneFwd').attr('title',this.langText[67]);
        $('#lblAltGoOneFwd').attr('alt',this.langText[68]);
        $('#lblHrefGoToLast').attr('title',this.langText[69]);
        $('#lblAltGoToLast').attr('alt',this.langText[70]);
        $('#toTodayLink').attr('title',this.langText[71]);
        $('#lblAltGoToday').attr('alt',this.langText[72]);
        $('h3#lblValueState').text(this.langText[73]);
        $('h3#lblLiveValues').text(this.langText[74]);
        $('th#lblValueGen').text(this.langText[75]);
        $('th#lblValueIn').text(this.langText[76]);
        $('h3#lblYields').text(this.langText[77]);
        $('h3#lblChooseView').text(this.langText[78]);
        $('td#lblGridPower').text(this.langText[79]);
        $('td#lblGenPower').text(this.langText[80]);
        $('td#lblGenVolt').text(this.langText[81]);
        $('a#toggleAdvanced').text(this.langText[82]);
        $('label#lblSelGenVolt').text(this.langText[83]);
        $('label#lblSelGenCurr').text(this.langText[84]);
        $('label#lblSelGenPow').text(this.langText[85]);
        $('label#lblSelGridVolt').text(this.langText[86]);
        $('label#lblSelGridCurr').text(this.langText[87]);
        $('label#lblSelGridPow').text(this.langText[88]);
        $('label#lblSelDevTemp').text(this.langText[89]);
        document.getElementById("dlLinkSpan").innerHTML=this.langText[90];
        var mon;
        if (this.acVoltPhaseMon == 3) 
        {
            mon = dreiPhasig;
        } 
        else 
        {
            mon = einPhasig;		 
        }
        $('#mon').html(mon);
        
        $('th#devMon').text(this.langText[91]);
        $('th#cntryGrid').text(this.langText[92]);
        $('th#pktVersion').text(this.langText[93]);
        loadingTxt = this.langText[94];
        
        for (var i=0; i<7; i++)
        {
            dayNameMinList[i] = this.langText[95+i];
        }       
        
        if ((this.mode != 'TOOL') && (this.mode != 'PARAINPUT'))
        {
            /*
            // Refresh date and time
            $.ajax({
                url : this.csv + '/realtime.csv',
                context : this,
                success : kaco.refreshStatus
            });
            
            logAddMsg('<-:  # URL: /realtime.csv');
            */
            // Show webpage
            if (containerOn == false)
            {
                containerOn = true;
                $("#container").show();
            }            
            
            // refresh the chart with loading of the data
            this.switchToDayView(true);
        }
        else
            kaco.updateCurrentLabel('DAY');
           
        $("#calendar").datepicker({
            buttonImage : 'btn_cal.gif',
            buttonImageOnly : true,
            gotoCurrent : true,
            showOn : 'button',
            changeYear : true,
            maxDate : new Date(),
            minDate : this.initDate,
            monthNames: monthNameList,
            dayNamesMin: dayNameMinList,
            
            beforeShow : function(input, inst) 
            {
                $("#calendar").datepicker("setDate", kaco.tstamp);
            },
            
            onSelect : function() 
            {
                var tmpDate = new Date();
                var pickedDate = $('#calendar').attr('value');
                tmpDate.setFullYear(pickedDate.substring(6,10));
                tmpDate.setDate(pickedDate.substring(3,5));
                tmpDate.setMonth((pickedDate.substring(0,2)-1));
                kaco.tstamp = tmpDate;
                kaco.switchToDayView(true);
            }
        });
        
        if (kaco.initCount < 4)
            kaco.initCount++;
    },
	
    loadLang : function(langName)
    {
        $.ajax({
            url : kaco.csv + 'psta' + langName + '.txt',
            context : kaco,
            success : kaco.parseStatus
        });
        
        $.ajax({
            url : kaco.csv + 'lang' + langName + '.txt',
            context : kaco,
            success : kaco.parseLangText
        });
    },
    
    changeLangTo : function(langName)
    {
        var tmpLangName = langName.toUpperCase();
        if (inList(tmpLangName,langList) == false)
            langName = "enUS";
        
        if (langName != lang.gui1)
        {
            lang.gui1 = langName;
            kaco.langId = langName;
             
            this.loadLang(langName);
        }
    },
    
    parseMeta : function(data) 
    {
        /*
        0.)     Serial
        1.)     Device type
        2.)     MAC address
        3.)     IP address                      (IPv4)
        4.)     Inverter RS485 address          (Range 1-31)
        5.)     Anzahl AC-Phasen                (Range 1-3)
        6.)     DC entries                      (Range 1-3)
        7.)     AC nominal power                [W]
        8.)     AC voltage phases monitoring    (1: Show 1 phase voltage; 3: Show 3 phase voltages)
        9.)     AC current phases monitoring    (1: Show 1 phase current; 3: Show 3 phase currents)
        10.)    Show AC phases monitoring mode  (0: Hide; 1: Show)        
        11.)    Language ID                     (ISO 639)
        12.)    SW packet version               (for example 101 for 1.01)
        13.)    ARM SW-Version                  (for example 101 for 1.01)
        14.)    ARM SW-Version checksum
        15.)    CFG SW-Version                  (for example 10001 for 1.0001)
        16.)    CFG SW-Version checksum       
        17.)    DSP SW-Version                  (for example 123 for 1.23)
        18.)    DSP SW-Version checksum
        19.)    PIC SW-Version                  (for example 123 for 1.23)
        20.)    PIC SW-Version checksum
        21.)    Vendor name                     (for example 'KACO', 'SCHUECO', ...)
        22.)    WebConfig active/inactive
        */
        var fields = data.split(';');
        $('#serial').html(fields[0]);
        $('#name').html(fields[1]);
        $('#mac').html(fields[2]);
        $('#network').html(fields[3]);
        $('#rsid').html(fields[4]);
        this.acCount = parseInt(fields[5]);       
        this.dcCount = parseInt(fields[6]);
        this.acPower = parseInt(fields[7]);           
        this.acVoltPhaseMon = parseInt(fields[8]);
        this.acCurrPhaseMon = parseInt(fields[9]);
        this.showAcPhaseMonMode = parseInt(fields[10]);
        if (this.showAcPhaseMonMode == 1)
        {
            $("#devMon").show();
            $("#mon").show();
        }
        else
        {
            $("#devMon").hide();
            $("#mon").hide();
        }
        this.langId = fields[11];
        lang.inverterOrg = this.langId;
        
        $('#pktVer').html(createVersionNumber(fields[12]));
        this.armVersion = parseInt(fields[13]);
        this.armChecksum = parseInt(fields[14]);
        this.cfgVersion = parseInt(fields[15]);
        this.cfgChecksum = parseInt(fields[16]);
        this.dspVersion = parseInt(fields[17]);
        this.dspChecksum = parseInt(fields[18]);
        this.picVersion = parseInt(fields[19]);
        this.picChecksum = parseInt(fields[20]);      
        this.vendorName = fields[21].toUpperCase();
        confMode = (Number(fields[22]) == 0) ? false : true;
        this.switchConfMode(confMode);
        
        this.changeLangTo(kaco.langId);
        
        var type = roundCommaSeparated((this.acPower / 1000), 2) + ' kW ' + nennleistung + ', ';
          
        if (this.acVoltPhaseMon == 3)
        {
            $("input.aVolt2, input.aVolt3").css({
                display : 'inline'
            });
        }
        if (this.acCurrPhaseMon == 3) 
        {
            $("input.aCurr2, input.aCurr3").css({
                display : 'inline'
            });
        }
        $('#type').html(type);
        if (this.dcCount == 2) 
        {
            $("input.d2").css({
                display : 'inline'
            });
        }
        if (this.dcCount == 3) 
        {
            $("input.d2, input.d3").css({
                display : 'inline'
            });
        }
                
        // Set Vendor specific display
        if ((this.vendorName == 'KACO') || (this.vendorName == 'SUNPOWER') || (this.vendorName == 'BLUEPLANET'))
        {
            document.getElementById("logo").src = 'kacologo.gif';
            document.getElementById("logo").alt = 'KACO new energy Logo';
            document.title = 'KACO new energy';
            document.getElementById("hr1").style.background = '#D0D6D8';
            document.getElementById("hr1").style.color = '#D0D6D8';
            document.getElementById("hr2").style.background = '#D0D6D8';
            document.getElementById("hr2").style.color = '#D0D6D8';
            document.getElementById("headerBox").style.background = "#e9eaec url(kacobggr.gif) bottom left repeat-x";
            document.getElementById("logoBox").style.background = '#ffffff';
            document.getElementsByClassName("greyBox")[0].style.background = "#e9eaec url(kacobggr.gif) bottom left repeat-x";
            document.getElementsByClassName("greyBox")[1].style.background = "#e9eaec url(kacobggr.gif) bottom left repeat-x";
            document.getElementById("chartContainer").style.background = '#f9f9f9 url(kacobgch.jpg) no-repeat center center';
            changeFavicon('kacofavi.ico');
        }
        else if (this.vendorName == 'SCHUECO')
        {
            document.getElementById("logo").src = 'schulogo.gif';
            document.getElementById("logo").alt = 'Schüco International Logo';
            document.title = 'Schüco International';
            document.getElementById('hr1').style.background = '#40464b';
            document.getElementById('hr1').style.color = '#40464b';
            document.getElementById('hr2').style.background = '#40464b';
            document.getElementById('hr2').style.color = '#40464b';
            document.getElementById("headerBox").style.background = '#cccccc';
            document.getElementById("logoBox").style.background = '#40464b';
            document.getElementsByClassName("greyBox")[0].style.background = "#cccccc";
            document.getElementsByClassName("greyBox")[1].style.background = "#cccccc";
            document.getElementById("chartContainer").style.background = '#f9f9f9 url(schubgch.jpg) no-repeat center center';
            changeFavicon('kacofavi.ico');
        }
        else if (this.vendorName == 'INVENTUX')
        {
            document.getElementById("logo").src = 'invelogo.gif';
            document.getElementById("logo").alt = 'Inventux Technologies AG Logo';
            document.title = 'Inventux Technologies AG';
            document.getElementById("hr1").style.background = '#D0D6D8';
            document.getElementById("hr1").style.color = '#D0D6D8';
            document.getElementById("hr2").style.background = '#D0D6D8';
            document.getElementById("hr2").style.color = '#D0D6D8';
            document.getElementById("headerBox").style.background = "#e9eaec url(kacobggr.gif) bottom left repeat-x";
            document.getElementById("logoBox").style.background = '#ffffff';
            document.getElementsByClassName("greyBox")[0].style.background = "#e9eaec url(invebggr.gif) bottom left repeat-x";
            document.getElementsByClassName("greyBox")[1].style.background = "#e9eaec url(invebggr.gif) bottom left repeat-x";
            document.getElementById("chartContainer").style.background = '#f9f9f9 url(invebgch.jpg) no-repeat center center';
            changeFavicon('invefavi.ico');
        }
        else if (this.vendorName == 'WUERTH')
        {
            document.getElementById("logo").src = 'wuerlogo.gif';
            document.getElementById("logo").alt = 'Würth Solar Logo';
            document.title = 'Würth Solar';	
            document.getElementById("hr1").style.background = '#b9b9a0';
            document.getElementById("hr1").style.color = '#b9b9a0';
            document.getElementById("hr2").style.background = '#b9b9a0';
            document.getElementById("hr2").style.color = '#b9b9a0';
            document.getElementById("headerBox").style.background = "#d8d7cc";
            document.getElementById("logoBox").style.background = '#ffffff';
            document.getElementsByClassName("greyBox")[0].style.background = "#d8d7cc";
            document.getElementsByClassName("greyBox")[1].style.background = "#d8d7cc";
            document.getElementById("chartContainer").style.background = '#f9f9f9 url(wuerbgch.jpg) no-repeat center center';
            changeFavicon('kacofavi.ico');
        }
        if ((this.dcCount > 2) || (this.acVoltPhaseMon > 2))
		{
            $("#textLabel1").show();
            $("#textLabel2").show();
            $("#textLabel3").show();
        }
        else if (this.dcCount > 1 || this.acVoltPhaseMon > 1) 
		{
            $("#textLabel1").show();
            $("#textLabel2").show();
            $("#textLabel3").hide();
        }
        else 
		{
            $("#textLabel1").show();
            $("#textLabel2").hide();
            $("#textLabel3").hide();
        }
        
        // Initialization of the language for webConfig here already necessary 
        // for correct display of the time-out dialog box
        initCfgLang();
        
        if (confMode)
            sendSetPara(99);
            
        $('#logo').load(function()
        {
            kaco.initCount++;
        });
        
        if (firstLoadData == true)
        {
            setTimeout(function(){
                $.ajax({
                    cache: false,
                    url : kaco.csv + '/realtime.csv',
                    //async : false,
                    context : kaco,
                    success:function(data){
                        kaco.refreshStatus(data);
                    },
                });
            }, 500);
            firstLoadData = false;
        }
    },
    
    parseMetaLang : function(data) 
    {
        /*
        11.)    Language ID                     (ISO 639)
        */
        var fields = data.split(';');
        this.langId = fields[11];
        this.changeLangTo(kaco.langId);
        changeCfgLangTo(kaco.langId);
    },
    
    triggerRealtimeUpdate : function() 
    {
        if ((this.initCount < 4) || (docReady == false))
            return;
        
        if (pauseRealtime == false)
        {
            if (secCnt > 0)
            {
                if ((autoRefresh == true) && ((secCnt == 4) || (secCnt == 14) || (secCnt == 24)) && (quitCfg == false))
                    maskRefresh(true);
                secCnt--;
            }
            else
            {
                secCnt = 29;
                if (startCount > 0)
                {
                    startCount--;
                }
                else
                {
                    $.ajax({
                        cache: false,
                        url : this.csv + '/realtime.csv',
                        context : this,
                        success : kaco.refreshStatus
                    });
                    if ($('#rtDbgMsg').attr('checked'))
                        logAddMsg('<-:  # URL: /realtime.csv');
                    
                    triggerTimeout(0,answerTimeout);
                    realTimeReq = true;
                }
            }
        }
        /* Debug
        else
        {
            if ($('#rtDbgMsg').attr('checked'))
                logAddMsg('+++ Realtime Pause');
        }
        */
    },
    
    triggerWebConfig : function() 
    {
        if ((this.initCount < 4) || (docReady == false))
            return;
            
        zyclicTimerWebConfig();
    },
    
    trigger1MinTimerWebConfig : function() 
    {
        if ((this.initCount < 4) || (docReady == false))
            return;
            
        zyclic1MinTimerWebConfig();
    },
    refreshStatus : function(data) 
    {
        var fields = data.split(';');
        var tDate = new Date(fields[0]*1000);
        var tmpMonth = (tDate.getUTCMonth() + 1);
        var tmpAMPM = 'AM';
        var tmpHours24 = (tDate.getUTCHours());
        var tmpHours12 = tmpHours24;
        
        if ($('#rtDbgMsg').attr('checked'))
            logAddMsg("->: " + data);
        
        if (tmpHours12>12) 
        {
            tmpHours12 = tmpHours12-12;
            tmpAMPM = 'PM';
        }
        var dateString = datumsFormat.replace('d', String(tDate.getUTCDate()).pad(2,'0'))
                                     .replace('m', String(tmpMonth).pad(2,'0'))
                                     .replace('y', tDate.getUTCFullYear())
                                     .replace('h', String(tmpHours24).pad(2,'0'))
                                     .replace('H', String(tmpHours12).pad(2,'0'))
                                     .replace('i', String(tDate.getUTCMinutes()).pad(2,'0'))
                                     .replace('s', String(tDate.getUTCSeconds()).pad(2,'0'))
                                     .replace('n', tmpAMPM);
        $('#today').html(dateString);
        var gen = [];
        for (var t = 1; t <= this.dcCount; t++) 
        {
            gen.push(roundCommaSeparated(((fields[t] / (65535.0 / 1600.0)) * ((fields[t + this.dcCount + this.acCount]) / (65535.0 / 200.0)) / 1000.0), 2));
        }
        $('#nowValueGen').html(gen.join(' kW<br/>') + ' kW');
        $('#nowValueIn').html(roundCommaSeparated((fields[fields.length - 3] / (65535.0 / 100000.0) / 1000.0), 2) + ' kW');
        var st = fields[fields.length - 1].trim();
        if (this.state[st]) 
        {
            $('#nowValueState').html(this.state[st]);
        } 
        else 
        {
            $('#nowValueState').html(unbekannt);
        }
                
        // Show webpage
        if (containerOn == false)
        {
            containerOn = true;
            $("#container").show();
        }  
        
        stopTimeout(0);
        
        if (realTimeReq == true)
        {
            realTimeReq = false;
            if (realTimeReqCnt > 0)
                realTimeReqCnt--;
        }
        
        if ((timeoutDlgActive) && (activeMaskIndex != 0))
        {
            closeDlgBox();
        }
    },
    goToToday : function() 
    {
        this.loadData(this.view.getToday(this.tstamp));
        this.updateCurrentLabel(this.mode);
    },
    goBack : function() 
    {
        this.loadData(this.view.getPrevious(this.tstamp));
        this.updateCurrentLabel(this.mode);
    },
    goForward : function() 
    {
        this.loadData(this.view.getNext(this.tstamp));
        this.updateCurrentLabel(this.mode);
    },
    goFastForward : function() 
    {
        this.loadData(this.view.getNextFast(this.tstamp));
        this.updateCurrentLabel(this.mode);
    },
    goFastBack : function() 
    {
        this.loadData(this.view.getPreviousFast(this.tstamp));
        this.updateCurrentLabel(this.mode);
    },
    updateCurrentLabel : function(dataViewMode) 
    {
        var label;
        switch (dataViewMode) 
        {
            case 'DAY': 
            {
                label = heute;
                if ((new Date).getMonth() != this.tstamp.getMonth() || (new Date).getFullYear() != this.tstamp.getFullYear() || (new Date).getDate() != this.tstamp.getDate()) 
                {
                    label = this.tstamp.getDate() + '. ' + monthNameList[this.tstamp.getMonth()] + ' ' + this.tstamp.getFullYear();
                }
                break;
            }
            case 'MONTH': 
            {
                label = dieserMonat;
                if ((new Date).getMonth() != this.tstamp.getMonth() || (new Date).getFullYear() != this.tstamp.getFullYear()) 
                {
                    label = monthNameList[this.tstamp.getMonth()] + ' ' + this.tstamp.getFullYear();
                }
                break;
            }
            case 'YEAR': 
            {
                label = diesesJahr;
                if ((new Date).getFullYear() != this.tstamp.getFullYear()) 
                {
                    label = this.tstamp.getFullYear();
                }
                break;
            }
        }
        $('#dayLabel').html(label);
    },
    switchToDayView : function(with_load) 
    {
        pauseRealtime = false;
        if (this.mode == 'TOOL')
            sendSetPara(99);
        this.mode = 'DAY';
        this.view = dayView;
        this.view.range.min = (this.initDate);
        $("#chart").show();
        $('#axisLabel').html(uhrzeit);
        $('#chartBarNavi').show();
        $('#graphselector').show();
        $('#calenderLink').show();
        $('.fastfwd').show();
        if (with_load == true)
            this.loadData(this.view.getCurrent(this.tstamp));
        else
            $('#currentScreenTitle').html(this.view.getTitle(this.tstamp));
        this.updateCurrentLabel(this.mode);
        $('#toTodayLink').css('visibility','visible');
		$("#tool").hide();
		$("#paraInput").hide();
        disableAnchor('viewConfig', false);
    },
    switchToMonthView : function() 
    {
        pauseRealtime = false;
        if (this.mode == 'TOOL')
            sendSetPara(99);
        this.mode = 'MONTH';
        this.view = monthView;
        this.view.range.min = (this.initDate);
        $("#chart").show();
        $('#axisLabel').html(tag);
        $('#chartBarNavi').show();
        $('.fastfwd').show();
        $('#graphselector').hide();
        $('#calenderLink').hide();
        this.loadData(this.view.getCurrent(this.tstamp));
        this.updateCurrentLabel(this.mode);
        $('#toTodayLink').css('visibility','hidden');
		$("#tool").hide();
		$("#paraInput").hide();
        disableAnchor('viewConfig', false);
    },
    switchToYearView : function() 
    {
        pauseRealtime = false;
        if (this.mode == 'TOOL')
            sendSetPara(99);
        this.mode = 'YEAR';
        this.view = yearView;
        this.view.range.min = (this.initDate);
        $("#chart").show();
        $('#axisLabel').html(monat);
        $('#chartBarNavi').show();
        $('#calenderLink').hide();
        $('#graphselector').hide();
        $('.fastfwd').hide();
        this.loadData(this.view.getCurrent(this.tstamp));
        this.updateCurrentLabel(this.mode);
        $('#toTodayLink').css('visibility','hidden');
		$("#tool").hide();
		$("#paraInput").hide();
        disableAnchor('viewConfig', false);
    },
    switchToEternalView : function() 
    {
        pauseRealtime = false;
        if (this.mode == 'TOOL')
            sendSetPara(99);
        this.mode = 'ETERNAL';
        this.view = eternalView;
        this.view.range.min = (this.initDate);
        $("#chart").show();
        $('#axisLabel').html(jahr);
        $('#dayLabel').html(gesamtUebersicht);
        $('#graphselector').hide();
        $('#chartBarNavi').hide();
        this.loadData('eternal');
        $('#toTodayLink').css('visibility','hidden');
		$("#tool").hide();
		$("#paraInput").hide();
        disableAnchor('viewConfig', false);
    },
	
    switchToToolView : function() 
	{
		if (this.mode != 'TOOL')
		{
			this.mode = 'TOOL';
			$("#chart").show();
			rect = getRect (document.getElementById('chart'));
			$("#chart").hide();
			retval = moveDivTo (document.getElementById('tool'), rect.left + 20, rect.top + 10);
			this.view = toolView;
            
			$('#graphselector').hide();
			$('#chartBarNavi').hide();
			$('#calenderLink').hide();
			$('#toTodayLink').css('visibility','hidden');
            if (dataViewDisabled == false)
            {
                disableAnchor('viewDay', true);
                disableAnchor('viewMonth', true);
                disableAnchor('viewYear', true);
                disableAnchor('viewEternal', true);
                disableAnchor('viewConfig', true);
                dataViewDisabled = true;
            }
            
            waitMsgStat = 0;
            testCnt = 0;
            treeActive = false;
            
			$("#tool").show();
            
            $("#tree").hide();
            initMask();
            $("#paraInput").show();
            $("#result-text").html('');
            $("#result-text").css({'background-color' : 'white'});     
            $("#result-text").show();
            
            if (paraData[paraIndexWebgui][PARA_OFFS] == true)
            {
                $("#dbg-text").show(); 
            }
		}
	},
	
    updateVisibleDayGraphs : function() 
    {
        if ((this.mode != 'TOOL') && (this.mode != 'PARAINPUT'))
            this.drawGraph(this.data);
    },
    loadData : function(src) 
    {
        pauseRealtime = true;
        this.showLoading();
        openThrobberBox(); // load data in standard data view
        try 
        {
            var path = this.csv + '/' + src + '.CSV';
            $('#currentScreenTitle').html(this.view.getTitle(this.tstamp));
            $.ajax( {
                cache: false,
                url : path,
                context : this,
                /*success : kaco.parseData,
                error : kaco.noData*/
                success:function(data){
                    kaco.parseData(data);
                    closeThrobberBox();
                },
                timeout: 120000,    /* 120 s = 2 Min */
                error: function(jqXHR, textStatus, errorThrown)
                {
                    closeThrobberBox();
                    if(textStatus==="timeout") 
                    {
                        //do something on timeout
                        this.dataTimeOut();
                        return false;
                    }
                    else
                    {   
                        this.noData();
                        return false;
                    }
                }
            });         
            $('#downloadLink').attr('href', this.csv + '/' + src + '.CSV');
            return true;
        } 
        catch (e) 
        {
            closeThrobberBox();
            this.noData();
            return false;
        }
    },
    noData : function() 
    {
        kaco.noDataMode = true;
        $("#tooltip").remove();
        $('#downloadLink').attr('href', 'javascript:alert("'+keineDaten+'");');
        $('#graphselector').hide();
        $('#axisLabel').hide();
        $('#chartContainer').html('<p class="nodata">'+keineDaten+'</p>');
        $('#dayValue').html('');
        $('#dayLabel').html('');
        pauseRealtime = false;
    },
    
    dataTimeOut : function() 
    {
        kaco.noDataMode = true;
        $("#tooltip").remove();
        $('#downloadLink').attr('href', 'javascript:alert("load data timeout");');
        $('#graphselector').hide();
        $('#axisLabel').hide();
        $('#chartContainer').html('<p class="nodata">load data timeout</p>');
        $('#dayValue').html('');
        $('#dayLabel').html('');
        pauseRealtime = false;
    },
    
    showLoading : function() 
    {
        $("#tooltip").remove();
        $('#downloadLink').attr('href', 'javascript:alert(" '+loadingTxt+' ");');
        $('#graphselector').hide();
        $('#axisLabel').hide();
        $('#chartContainer').html('<p class="loading">'+loadingTxt+' </p>');
        $('#dayValue').html('');
        $('#dayLabel').html('');
    },
    parseData : function(res) 
    {
        var lines = res.split('\r');
        var values = [];
        // Read the total yield value from the CSV header
        totalYieldFromCsvHeader = getFloatVal(lines[1].split(';')[4]);
        
        // Skip the first 3 lines (contain meta data and column headers)
        for (var t = 3; t < lines.length; t++) 
        {
            values[t - 3] = lines[t].split(';');
        }
        
        if ((values.length == 0) ||
            ((values.length == 1) && (values[0] == "")))
        {
            this.noData();
        }
        else
        {
            switch (this.mode) 
            {
                case 'ETERNAL':
                case 'MONTH':
                case 'YEAR': 
                {
                    this.data = this.parseGrouped(values);
                    break;
                }
                case 'DAY': 
                {
                    this.data = this.parseDay(values);
                    $('#graphselector').show();
                    break;
                }
            }
            this.drawGraph(this.data);
            if (this.noDataMode) 
            {
                this.noDataMode = false;
                switch (this.mode) 
                {
                    case 'ETERNAL': 
                        this.switchToEternalView();
                        break;
                    case 'YEAR': 
                        this.switchToMonthView();
                        break;
                    case 'MONTH': 
                        this.switchToMonthView();
                        break;
                    case 'DAY':
                        this.switchToDayView(true);
                        break;
                }
            }
        }
            
        pauseRealtime = false;
    },
    parseGrouped : function(values) 
    {
        var curValue = 0;
        var flag = false;
        var tmp = [];
        for (var x = 0; x < values.length - 1; x++) 
        {
            var data = values[x];
            var time = data[0].split("/");
            var day = 1, month = 0, year = 0;
            if (time.length == 3) 
            {
                day = time[0];
                month = time[1] - 1;
                year = time[2];
            } 
            else if (time.length == 2) 
            {
                month = time[0] - 1;
                year = time[1];
            } 
            else 
            {
                year = data[0];
            }
            var d = new Date(year, month, day, 0, 0, 0);
            curValue += parseInt(data[1]);
            var tick;
            switch (this.mode) 
            {
                case 'YEAR': 
                {
                    tick = d.getMonth() + 1;
                    break;
                }
                case 'MONTH': 
                {
                    tick = d.getDate();
                    break;
                }
                case 'ETERNAL': 
                {
                    tick = d.getFullYear();
                    break;
                }
                default: 
                {
                    tick = d;
                }
            }
            tmp.push([tick, (data[1]/1000)]);
            if (flag)
                break;
        }
        var curValueCalculated = 0
        if (parseInt(curValue) > 0) 
        {
            curValueCalculated = curValue / 1000;
        }
        //$('#dayValue').html(roundCommaSeparated(curValueCalculated, 1) + ' kWh');
        
        // use the total yield value from the CSV header not the calculated value fron this JS-Script
        $('#dayValue').html(roundCommaSeparated(totalYieldFromCsvHeader, 1) + ' kWh');
        return tmp;
    },
    parseDay : function(values) 
    {
        var tmp = {
            'pvsp1' : {
                label : pvsp1,
                data : [],
                yaxis : 1,
                color : 'rgb(255,0,0)'
            },
            'pvsp2' : {
                label : pvsp2,
                data : [],
                yaxis : 1,
                color : 'rgb(255,128,128)'
            },
            'pvsp3' : {
                label : pvsp3,
                data : [],
                yaxis : 1,
                color : 'rgb(255,192,192)'
            },
            'pvst1' : {
                label: pvst1,
                data : [],
                yaxis : 2,
                color : 'rgb(0,255,0)'
            },
            'pvst2' : {
                label: pvst2,
                data : [],
                yaxis : 2,
                color : 'rgb(128,255,128)'
            },
            'pvst3' : {
                label: pvst3,
                data : [],
                yaxis : 2,
                color : 'rgb(192,255,192)'
            },
            'nsp1' : {
                label : nsp1,
                data : [],
                yaxis : 3,
                color : 'rgb(0,0,255)'
            },
            'nsp2' : {
                label : nsp2,
                data : [],
                yaxis : 3,
                color : 'rgb(128,128,255)'
            },
            'nsp3' : {
                label : nsp3,
                data : [],
                yaxis : 3,
                color : 'rgb(192,192,255)'
            },
            'nst1' : {
                label : nst1,
                data : [],
                yaxis : 9,
                color: 'rgb(255,255,0)'
            },
            'nst2' : {
                label : nst2,
                data : [],
                yaxis : 9,
                color: 'rgb(255,255,128)'
            },
            'nst3' : {
                label : nst3,
                data : [],
                yaxis : 9,
                color: 'rgb(255,255,192)'
            },
            'pvl1' : {
                label : pvl1,
                data : [],
                yaxis : 5,
                color : 'rgb(255,128,0)'
            },
            'pvl2' : {
                label : pvl2,
                data : [],
                yaxis : 5,
                color : 'rgb(255,192,64)'
            },
            'pvl3' : {
                label : pvl3,
                data : [],
                yaxis : 5,
                color : 'rgb(255,255,0)'
            },
            'temp' : {
                label : temperatur,
                data : [],
                yaxis : 6,
                color : 'rgb(0,0,0)'
            },
            'nl' : {
                label : nl,
                data : [],
                yaxis : 7,
                color : 'rgb(0,255,255)'
            }
        };
        for (var x = 0; x < values.length - 1; x++) 
        {
            var data = values[x];
            if (data[0] == 0)
                continue;
            // Zeitstempel
            var time = data[0].split(":"); // data[0]     Time (07:31:13)
            var tstamp = new Date(this.tstamp.getFullYear(),this.tstamp.getMonth(),this.tstamp.getDate(),time[0],time[1],time[2]);
            tstamp.setHours(tstamp.getHours() - (tstamp.getTimezoneOffset() / 60));
            if ((this.dcCount == 1) && (this.acVoltPhaseMon == 3))
            {
                /*
                data[1]     UDC1 (12345.6) - DC-Voltage 1, MPPT1 [V]
                data[2]     IDC1 (123.45) - DC-Current 1, MPPT1 [A]
                data[3]     PDC1 (123456) - DC-Power 1, MPPT1 [W]
                data[4]     UAC1 (12345.6) - AC-Voltage 1, Phase 1 [V]
                data[5]     IAC1 (123.45) - AC-Current 1, Phase 1 [A]
                data[6]     UAC2 (12345.6) - AC-Voltage 2, Phase 2 [V]
                data[7]     IAC2 (123.45) - AC-Current 2, Phase 2 [A]
                data[8]     UAC3 (12345.6) - AC-Voltage 3, Phase 3 [V]
                data[9]     IAC3 (123.45) - AC-Current 3, Phase 3 [A]
                data[10]    PDC (12345) - DC-Power total [W]
                data[11]    PAC (12345) - AC-Power total [W]
                data[12]    T (123.45) - Circuit board temperatur
                */
                // DC Spannung
                tmp.pvsp1.data.push([tstamp, getFloatVal(data[1])]);
                // DC Strom
                tmp.pvst1.data.push([tstamp, getFloatVal(data[2])]);
                // AC Spannung
                tmp.nsp1.data.push([tstamp, getFloatVal(data[4])]);
                tmp.nsp2.data.push([tstamp, getFloatVal(data[6])]);
                tmp.nsp3.data.push([tstamp, getFloatVal(data[8])]);
                // AC Strom
                tmp.nst1.data.push([tstamp, getFloatVal(data[5])]);
                if (this.acCount != 1)
                {
                    tmp.nst2.data.push([ tstamp, getFloatVal(data[7])]);
                    tmp.nst3.data.push([ tstamp, getFloatVal(data[9])]);
                }
                // DC Leistung
                tmp.pvl1.data.push([tstamp, getFloatVal(data[3]) / 1000]);
                // AC Leistung
                tmp.nl.data.push([tstamp, getFloatVal(data[11]) / 1000]);
                // Gerätetemperatur
                tmp.temp.data.push([tstamp, getFloatVal(data[12])]);
            }
            else if ((this.dcCount == 2) && (this.acVoltPhaseMon == 3))
            {
                /*
                data[1]     UDC1 (12345.6) - DC-Voltage 1, MPPT1 [V]
                data[2]     IDC1 (123.45) - DC-Current 1, MPPT1 [A]
                data[3]     PDC1 (123456) - DC-Power 1, MPPT1 [W]
                data[4]     UDC2 (12345.6) - DC-Voltage 2, MPPT2 [V]
                data[5]     IDC2 (123.45) - DC-Current 2, MPPT2 [A]
                data[6]     PDC2 (123456) - DC-Power 2, MPPT2 [W]
                data[7]     UAC1 (12345.6) - AC-Voltage 1, Phase 1 [V]
                data[8]     IAC1 (123.45) - AC-Current 1, Phase 1 [A]
                data[9]     UAC2 (12345.6) - AC-Voltage 2, Phase 2 [V]
                data[10]    IAC2 (123.45) - AC-Current 2, Phase 2 [A]
                data[11]    UAC3 (12345.6) - AC-Voltage 3, Phase 3 [V]
                data[12]    IAC3 (123.45) - AC-Current 3, Phase 3 [A]
                data[13]    PDC (12345) - DC-Power total [W]
                data[14]    PAC (12345) - AC-Power total [W]
                data[15]    T (123.45) - Circuit board temperatur
                */
                // DC Spannung
                tmp.pvsp1.data.push([tstamp, getFloatVal(data[1])]);
                tmp.pvsp2.data.push([tstamp, getFloatVal(data[4])]);
                // DC Strom
                tmp.pvst1.data.push([tstamp, getFloatVal(data[2])] );
                tmp.pvst2.data.push([tstamp, getFloatVal(data[5])] );
                // AC Spannung
                tmp.nsp1.data.push([tstamp, getFloatVal(data[7])]);
                tmp.nsp2.data.push([tstamp, getFloatVal(data[9])]);
                tmp.nsp3.data.push([tstamp, getFloatVal(data[11])]);
                // AC Strom
                tmp.nst1.data.push([tstamp, getFloatVal(data[8])]);
                if (this.acCount != 1)
                {
                    tmp.nst2.data.push( [ tstamp, getFloatVal(data[10]) ]);
                    tmp.nst3.data.push( [ tstamp, getFloatVal(data[12]) ]);
                }
                // DC Leistung
                tmp.pvl1.data.push([tstamp, getFloatVal(data[3]) / 1000]);
                tmp.pvl2.data.push([tstamp, getFloatVal(data[6]) / 1000]);
                // AC Leistung
                tmp.nl.data.push([tstamp, getFloatVal(data[14]) / 1000]);
                // Gerätetemperatur
                tmp.temp.data.push([tstamp, getFloatVal(data[15])]);
            }
            else if ((this.dcCount == 3) && (this.acVoltPhaseMon == 3)) 
            {
                /*
                data[0]     Time (07:31:13)
                data[1]     UDC1 (12345.6) - DC-Voltage 1, MPPT1 [V]
                data[2]     IDC1 (123.45) - DC-Current 1, MPPT1 [A]
                data[3]     PDC1 (123456) - DC-Power 1, MPPT1 [W]
                data[4]     UDC2 (12345.6) - DC-Voltage 2, MPPT2 [V]
                data[5]     IDC2 (123.45) - DC-Current 2, MPPT2 [A]
                data[6]     PDC2 (123456) - DC-Power 2, MPPT2 [W]
                data[7]     UDC3 (12345.6) - DC-Voltage 3, MPPT3 [V]
                data[8]     IDC3 (123.45) - DC-Current 3, MPPT3 [A]
                data[9]     PDC3 (123456) - DC-Power 3, MPPT3 [W]
                data[10]    UAC1 (12345.6) - AC-Voltage 1, Phase 1 [V]
                data[11]    IAC1 (123.45) - AC-Current 1, Phase 1 [A]
                data[12]    UAC2 (12345.6) - AC-Voltage 2, Phase 2 [V]
                data[13]    IAC2 (123.45) - AC-Current 2, Phase 2 [A]
                data[14]    UAC3 (12345.6) - AC-Voltage 3, Phase 3 [V]
                data[15]    IAC3 (123.45) - AC-Current 3, Phase 3 [A]
                data[16]    PDC (12345) - DC-Power total [W]
                data[17]    PAC (12345) - AC-Power total [W]
                data[18]    T (123.45) - Circuit board temperatur
                */
                // DC Spannung
                tmp.pvsp1.data.push([tstamp, getFloatVal(data[1])]);
                tmp.pvsp2.data.push([tstamp, getFloatVal(data[4])]);
                tmp.pvsp3.data.push([tstamp, getFloatVal(data[7])]);
                // DC Strom
                tmp.pvst1.data.push([tstamp, getFloatVal(data[2])]);
                tmp.pvst2.data.push([tstamp, getFloatVal(data[5])]);
                tmp.pvst3.data.push([tstamp, getFloatVal(data[8])]);
                // AC Spannung
                tmp.nsp1.data.push([tstamp, getFloatVal(data[10])]);
                tmp.nsp2.data.push([tstamp, getFloatVal(data[12])]);
                tmp.nsp3.data.push([tstamp, getFloatVal(data[14])]);
                // AC Strom
                tmp.nst1.data.push([tstamp, getFloatVal(data[11])]);
                tmp.nst2.data.push([tstamp, getFloatVal(data[13])]);
                tmp.nst3.data.push([tstamp, getFloatVal(data[15])]);
                // DC Leistung
                tmp.pvl1.data.push([tstamp, getFloatVal(data[3]) / 1000]);
                tmp.pvl2.data.push([tstamp, getFloatVal(data[6]) / 1000]);
                tmp.pvl3.data.push([tstamp, getFloatVal(data[9]) / 1000]);
                // AC Leistung
                tmp.nl.data.push([tstamp, getFloatVal(data[17]) / 1000]);
                // Gerätetemperatur
                tmp.temp.data.push([tstamp, getFloatVal(data[18])]);
            }
            else if ((this.dcCount == 1) && (this.acVoltPhaseMon == 1)) 
            {
                /*
                data[0]     Time (07:31:13)
                data[1]     UDC1 (12345.6) - DC-Voltage 1, MPPT1 [V]
                data[2]     IDC1 (123.45) - DC-Current 1, MPPT1 [A]
                data[3]     PDC1 (123456) - DC-Power 1, MPPT1 [W]
                data[4]     UAC1 (12345.6) - AC-Voltage 1, Phase 1 [V]
                data[5]     IAC1 (123.45) - AC-Current 1, Phase 1 [A]
                data[6]     PDC (12345) - DC-Power total [W]
                data[7]     PAC (12345) - AC-Power total [W]
                data[8]     T (123.45) - Circuit board temperatur
                */
                // DC Spannung
                tmp.pvsp1.data.push([tstamp, getFloatVal(data[1])]);
                // DC Strom
                tmp.pvst1.data.push([tstamp, getFloatVal(data[2])]);
                // AC Spannung
                tmp.nsp1.data.push([tstamp, getFloatVal(data[4])]);
                // AC Strom
                tmp.nst1.data.push([tstamp, getFloatVal(data[5])]);
                // DC Leistung
                tmp.pvl1.data.push([tstamp, getFloatVal(data[3]) / 1000]);
                // AC Leistung
                tmp.nl.data.push([tstamp, getFloatVal(data[7]) / 1000]);
                // Gerätetemperatur
                tmp.temp.data.push([tstamp, getFloatVal(data[8])]);
            }
            else if ((this.dcCount == 2) && (this.acVoltPhaseMon == 1)) 
            {
                /*
                data[0]     Time (07:31:13)
                data[1]     UDC1 (12345.6) - DC-Voltage 1, MPPT1 [V]
                data[2]     IDC1 (123.45) - DC-Current 1, MPPT1 [A]
                data[3]     PDC1 (123456) - DC-Power 1, MPPT1 [W]
                data[4]     UDC2 (12345.6) - DC-Voltage 2, MPPT2 [V]
                data[5]     IDC2 (123.45) - DC-Current 2, MPPT2 [A]
                data[6]     PDC2 (123456) - DC-Power 2, MPPT2 [W]
                data[7]     UAC1 (12345.6) - AC-Voltage 1, Phase 1 [V]
                data[8]     IAC1 (123.45) - AC-Current 1, Phase 1 [A]
                data[9]     PDC (12345) - DC-Power total [W]
                data[10]    PAC (12345) - AC-Power total [W]
                data[11]    T (123.45) - Circuit board temperatur
                */
                // DC Spannung
                tmp.pvsp1.data.push([tstamp, getFloatVal(data[1])]);
                tmp.pvsp2.data.push([tstamp, getFloatVal(data[4])]);
                // DC Strom
                tmp.pvst1.data.push([tstamp, getFloatVal(data[2])]);
                tmp.pvst2.data.push([tstamp, getFloatVal(data[5])]);
                // AC Spannung
                tmp.nsp1.data.push([tstamp, getFloatVal(data[7])]);
                // AC Strom
                tmp.nst1.data.push([tstamp, getFloatVal(data[8])]);
                // DC Leistung
                tmp.pvl1.data.push([tstamp, getFloatVal(data[3]) / 1000]);
                tmp.pvl2.data.push([tstamp, getFloatVal(data[6]) / 1000]);
                // AC Leistung
                tmp.nl.data.push([tstamp, getFloatVal(data[10]) / 1000]);
                // Gerätetemperatur
                tmp.temp.data.push([tstamp, getFloatVal(data[11])]);
            }
            else if ((this.dcCount == 3) && (this.acVoltPhaseMon == 1)) 
            {
                /*
                data[0]     Time (07:31:13)
                data[1]     UDC1 (12345.6) - DC-Voltage 1, MPPT1 [V]
                data[2]     IDC1 (123.45) - DC-Current 1, MPPT1 [A]
                data[3]     PDC1 (123456) - DC-Power 1, MPPT1 [W]
                data[4]     UDC2 (12345.6) - DC-Voltage 2, MPPT2 [V]
                data[5]     IDC2 (123.45) - DC-Current 2, MPPT2 [A]
                data[6]     PDC2 (123456) - DC-Power 2, MPPT2 [W]
                data[7]     UDC3 (12345.6) - DC-Voltage 3, MPPT3 [V]
                data[8]     IDC3 (123.45) - DC-Current 3, MPPT3 [A]
                data[9]     PDC3 (123456) - DC-Power 3, MPPT3 [W]
                data[10]    UAC1 (12345.6) - AC-Voltage 1, Phase 1 [V]
                data[11]    IAC1 (123.45) - AC-Current 1, Phase 1 [A]
                data[12]    PDC (12345) - DC-Power total [W]
                data[13]    PAC (12345) - AC-Power total [W]
                data[14]    T (123.45) - Circuit board temperatur
                */
                // DC Spannung
                tmp.pvsp1.data.push([tstamp, getFloatVal(data[1])]);
                tmp.pvsp2.data.push([tstamp, getFloatVal(data[4])]);
                tmp.pvsp3.data.push([tstamp, getFloatVal(data[7])]);
                // DC Strom
                tmp.pvst1.data.push([tstamp, getFloatVal(data[2])]);
                tmp.pvst2.data.push([tstamp, getFloatVal(data[5])]);
                tmp.pvst3.data.push([tstamp, getFloatVal(data[8])]);
                // AC Spannung
                tmp.nsp1.data.push([tstamp, getFloatVal(data[10])]);
                // AC Strom
                tmp.nst1.data.push([tstamp, getFloatVal(data[11])]);
                // DC Leistung
                tmp.pvl1.data.push([tstamp, getFloatVal(data[3]) / 1000]);
                tmp.pvl2.data.push([tstamp, getFloatVal(data[6]) / 1000]);
                tmp.pvl3.data.push([tstamp, getFloatVal(data[9]) / 1000]);
                // AC Leistung
                tmp.nl.data.push([tstamp, getFloatVal(data[13]) / 1000]);
                // Gerätetemperatur
                tmp.temp.data.push([tstamp, getFloatVal(data[14])]);
            }
        }
        
        var curValue = 0;
        var diff = 5;
      
        for (var xx = 0; xx < tmp.nl.data.length; xx++) 
        {
            if (xx > 0) 
            {
                diff = ((tmp.nl.data[xx][0].getTime() - tmp.nl.data[xx-1][0].getTime())/60000);
            }
            curValue += tmp.nl.data[xx][1] * diff;
        }
        var curValueCalculated = 0;
        if (parseInt(curValue) > 0)
        {
            curValueCalculated = curValue / 60.0;
        }
        //$('#dayValue').html(roundCommaSeparated(curValueCalculated, 1) + ' kWh');
        
        // use the total yield value from the CSV header not the calculated value fron this JS-Script
        $('#dayValue').html(roundCommaSeparated(totalYieldFromCsvHeader, 1) + ' kWh');
        return tmp;
    },
    drawGraph : function(data) 
    {
        if (this.override) 
        {
            $("outOfBoundInfo").show();
        } 
        else 
        {
            $("outOfBoundInfo").hide();
        }
        this.override = false;
        var config = this.view.getChartConfig(data);
        if (config != undefined)
        {
            $.plot($("#chartContainer"), config.chart, config.options);
            $('#axisLabel').show();
        }
    }
}
var toolView = 
{
	getTitle : function(tstamp) 
	{
		return toolAnsicht;
	}
}
var eternalView = {
    range : {
        min : (new Date(2006, 0, 1, 0, 0, 0)).getTime(),
        max : (new Date()).getTime()
    },
    getTitle : function(tstamp) 
    {
        return gesamtAnsicht;
    },
    getChartConfig : function(data) 
    {
        var ticks = [];
        var min = 0;
        var max = 25000;
        if (data.length > 0)
        {
            for(var xyz = 0; xyz < data.length; ++xyz) 
            {
                ticks.push(data[xyz][0]);
            }
            return {
                chart : [ {
                    label : 'E [kWh]',
                    data : data,
                    bars : {
                        show : true,
                        barWidth : 0.5,
                        align : 'center'
                    }
                } ],
                options : {
                    grid : {
                        clickable : true,
                        hoverable : true,
                        autoHighlight : true
                    },
                    legend : {
                        position : 'nw'
                    },
                    xaxis : {
                        ticks : ticks,
                        tickDecimals : 0,
                        max : data[data.length-1][0] + 1,
                        min : data[0][0] - 1
                    },
                    colors : [ "#003871" ]
                }
            };
        }
    },
    getCurrent : function(tstamp) 
    {
        if (tstamp.getTime() < this.range.min) 
        {
            kaco.override = true;
            tstamp.setTime(this.range.min);
        }
        if (tstamp.getTime() > this.range.max) 
        {
            kaco.override = true;
            tstamp.setTime(this.range.max);
        }
        return tstamp.getFullYear();
    },
    getPrevious : function(tstamp) 
    {
        tstamp.setFullYear(tstamp.getFullYear() - 1);
        return this.getCurrent(tstamp);
    },
    getNext : function(tstamp) 
    {
        tstamp.setFullYear(tstamp.getFullYear() + 1);
        return this.getCurrent(tstamp);
    }
}
var yearView = {
    range : {
        min : (new Date(2008, 0, 1, 0, 0, 0)).getTime(),
        max : (new Date()).getTime()
    },
    getTitle : function(tstamp) 
    {
        return jahresAnsicht + ' ' + tstamp.getFullYear();
    },
    getChartConfig : function(data) 
    {
        return {
            chart : [ {
                label : 'E [kWh]',
                data : data,
                bars : {
                    show : true,
                    barWidth : 0.5,
                    align : 'center'
                }
            } ],
            options : {
                grid : {
                    clickable : true,
                    hoverable : true,
                    autoHighlight : true
                },
                legend : {
                    position : 'nw',
                    opacity : 0.4,
                    style : 'bar'
                },
                xaxis : {
                    ticks : [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ],
                    tickDecimals : 0,
                    max : 13,
                    min : 0
                },
                colors : [ "#003871" ]
            }
        };
    },
    getCurrent : function(tstamp) 
    {
        if (tstamp.getTime() < this.range.min) 
        {
            kaco.override = true;
            tstamp.setTime(this.range.min);
        }
        if (tstamp.getTime() > this.range.max) 
        {
            kaco.override = true;
            tstamp.setTime(this.range.max);
        }
        return tstamp.getFullYear();
    },
    getPrevious : function(tstamp) 
    {
        tstamp.setFullYear(tstamp.getFullYear() - 1);
        return this.getCurrent(tstamp);
    },
    getNext : function(tstamp) 
    {
        tstamp.setFullYear(tstamp.getFullYear() + 1);
        return this.getCurrent(tstamp);
    }
}
var monthView = {
    range : {
        min : (new Date(2009, 0, 1, 0, 0, 0)).getTime(),
        max : (new Date()).getTime()
    },
    getTitle : function(tstamp) 
    {
        return monatsAnsicht + ' ' + monthNameList[tstamp.getMonth()] + ' ' + tstamp.getFullYear();
    },
    getChartConfig : function(data) 
    {
        var tmp = yearView.getChartConfig(data);
        tmp.options.xaxis = {
            ticks : [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ],
            tickDecimals : 0,
            max : 32,
            min : 0
        }
        return tmp;
    },
    getCurrent : function(tstamp) 
    {
        if (tstamp.getTime() < this.range.min) 
        {
            kaco.override = true;
            tstamp.setTime(this.range.min);
        }
        if (tstamp.getTime() > this.range.max) 
        {
            kaco.override = true;
            tstamp.setTime(this.range.max);
        }
        var m = (tstamp.getMonth() + 1) + '';
        return tstamp.getFullYear() + '' + m.pad(2, '0');
    },
    getPrevious : function(tstamp) 
    {
        tstamp.setMonth(tstamp.getMonth() - 1);
        return this.getCurrent(tstamp);
    },
    getNext : function(tstamp) 
    {
        tstamp.setMonth(tstamp.getMonth() + 1);
        return this.getCurrent(tstamp);
    },
    getPreviousFast : function(tstamp) 
    {
        tstamp.setYear(tstamp.getFullYear() - 1);
        return this.getCurrent(tstamp);
    },
    getNextFast : function(tstamp) 
    {
        tstamp.setYear(tstamp.getFullYear() + 1);
        return this.getCurrent(tstamp);
    }
};
var dayView = {
    range : {
        min : (new Date(2012, 1, 1, 0, 0, 0)).getTime(),
        max : (new Date()).getTime()
    },
    getTitle : function(tstamp) 
    {
        return tagesAnsicht + ' ' + tstamp.getDate() + '. ' + monthNameList[tstamp.getMonth()] + ' ' + tstamp.getFullYear();
    },
    getChartConfig : function(data) 
    {
        /*
        * var label; switch (kaco.dayGraph) { case 'pvsp1': case 'pvsp2': case
        * 'pvsp3': { label = 'U [V]'; break; }
        * 
        * case 'pvst1': case 'pvst2': case 'pvst3': { label = 'I [A]'; break; }
        * 
        * case 'nsp1': case 'nsp2': case 'nsp3': { label = 'U [V]'; break; }
        * 
        * case 'nst1': case 'nst2': case 'nst3': { label = 'I [A]'; break; }
        * 
        * case 'nfr': { label = 'F [Hz]'; break; } case 'temp': { label = 'T
        * [°C]'; break; } case 'nl': { label = "P [kW]"; break; } }
        */
        var showData = [];
        $('#graphselector').find("input:checked").each(function() {
            var key = $(this).attr("value");
            if (key && data[key])
                showData.push(data[key]);
        });
        return {
            chart : showData,
            /*
            * { label: label, data: data, lines: { show: true } },
            */
            options : {
                grid : {
                    clickable : true,
                    hoverable : true,
                    autoHighlight : true
                },
                legend : {
                    position : 'nw'
                },
                xaxis : {
                    mode : 'time',
                    timeformat : '%h:%M'
                },
                yaxis : {
                    position : "left",
                    min : 0,
                    max : null                   
                },
            }
        };
    },
    getCurrent : function(tstamp) 
    {
        if (tstamp.getTime() < this.range.min) 
        {
            kaco.override = true;
            tstamp.setTime(this.range.min);
        }
        if (tstamp.getTime() > this.range.max) 
        {
            kaco.override = true;
            tstamp.setTime(this.range.max);
        }
        var m = (tstamp.getMonth() + 1) + '';
        var d = tstamp.getDate() + '';
        return tstamp.getFullYear() + '' + m.pad(2, '0') + d.pad(2, '0');
    },
    getPrevious : function(tstamp) 
    {
        tstamp.setDate(tstamp.getDate() - 1);
        return this.getCurrent(tstamp);
    },
    getNext : function(tstamp) 
    {
        tstamp.setDate(tstamp.getDate() + 1);
        return this.getCurrent(tstamp);
    },
    getPreviousFast : function(tstamp) 
    {
        tstamp.setMonth(tstamp.getMonth() - 1);
        return this.getCurrent(tstamp);
    },
    
    getToday : function(tstamp) 
    {
        tstamp = new Date();
        kaco.tstamp = tstamp;
        return this.getCurrent(tstamp);
    },
    getNextFast : function(tstamp) 
    {
        tstamp.setMonth(tstamp.getMonth() + 1);
        return this.getCurrent(tstamp);
    }
};