var fzChartColors = ['blue',    'green',   'maroon', 'purple', 'orangered', 'lime'];
var fzChartColorsHex = ['#0000FF',    '#008000',   '#800000', '#800080', '#FF4500', '#00FF00'];

function RenderFzChart(title, sets, name_sets, measurement_sets, forecast_sets, floodcfs, yint, days) 
    {

        //if(navigator.userAgent.indexOf("MSIE")==-1)
        //{
        //return RenderFzChart_nonIE(title, sets, name_sets, measurement_sets, forecast_sets, floodcfs, yint, days);
        return RenderFzChart_Highcharts(title, sets, name_sets, measurement_sets, forecast_sets, floodcfs, yint, days);
        //}
        //else
        //{
        //   return RenderFzChart_IE(title, sets, name_sets, measurement_sets, forecast_sets, floodcfs, yint, days);
        //}

    }
var highchart;
function RenderFzChart_Highcharts(title, sets, name_sets, measurement_sets, forecast_sets, floodcfs, yint, days)
{
    var tmpnow = new Date();
    var now = Date.UTC(tmpnow.getFullYear(),tmpnow.getMonth(),tmpnow.getDate(),tmpnow.getHours(),tmpnow.getMinutes());
    if (highchart)
    {
        if (days)
            highchart.xAxis[0].setExtremes(now - days*1000 * 60 * 60 * 24/(2), now+days*1000 * 60 * 60 * 24/(2));
        else
            highchart.xAxis[0].setExtremes();
        return;
    }
    var series = new Array();
    for (var i=0;i<sets;i++ )
    {
        series.push({name:  "Observed: " + name_sets[i],
            data: measurement_sets[i][2],
            color: fzChartColorsHex[i],
            lineWidth: 2,
            states: {
               hover: {
                  lineWidth: 3
               }
            },
            marker: {
                enabled: false,
                radius: 2,
                states: {
                    hover: {
                        enabled: true
                    }
                }
            }
        });
        series.push({name: "Forecast: " + name_sets[i],
            data: forecast_sets[i][2],
            color: fzChartColorsHex[i],
            marker: {
                symbol: 'circle'
            }
        });
    }
    var floodBand = [];
    var floodLine = [];
    if (title=="Snoqualmie")
    {
        //Hack for river=Snoqualmie. Should have a general solution.
        floodBand[0]={ // Flooding
						    from: 18000,
                            to:  10000000,
						    color: 'rgba(68, 170, 213, 0.1)'
	                    };
        floodLine[0]={
            color: '#999',
            width: 1,
            value: 18000,
            dashStyle: "dash",
            label: {
                    text: 'Flood Stage (Carnation & Falls)',
                    style: {
                        color:  '#606060'
                    }
                }
            };

    }
    else if (floodcfs && floodcfs>0)
    {
        floodBand[0]={ // Flooding
						    from: floodcfs,
                            to:  10000000,
						    color: 'rgba(68, 170, 213, 0.1)'
	                    };
        floodLine[0]={
            color: '#999',
            width: 1,
            value: floodcfs,
            dashStyle: "dash",
            label: {
                    text: 'Flood Stage',
                    style: {
                        color:  '#606060'
                    }
                }
            };
    }

    highchart = new Highcharts.Chart({
		            chart: {
		                renderTo: 'graphdiv',
                        type: 'spline'
		            },
		            title: {
		                text: title + " Stream Flow"
		            },
		            subtitle: {
		                text: 'in cubic feet per second (cfs)'
		            },
		            xAxis: {
		                type: 'datetime',
                        dateTimeLabelFormats: {
                            second: '%H:%M:%S',
	                        minute: '%a, %l:%M %p',
	                        hour: '%a, %l %p',
	                        day: '%a, %b %e',
	                        week: '%e. %b',
	                        month: '%b \'%y'
                        },
		                plotLines: [{
		                    color: '#999',
		                    width: 1,
		                    value: now
		                }]

		            },
		            yAxis: {
		                title: {
		                    text: 'Flow (cfs)'
		                },
		                min: 0,
                        plotBands: floodBand,
                        plotLines: floodLine

		            },
		            tooltip: {
		                formatter: function () {
		                    return '<b>' + this.series.name + '</b><br/>' +
								Highcharts.dateFormat('%a, %b %e %l:%M %p ', this.x) + ': ' + this.y + ' cfs';
		                }
		            },
		            series: series
		        });






}

function RenderFzChart_nonIE(title, sets, name_sets, measurement_sets, forecast_sets, floodcfs, yint, days) 
    {

        var size="680x220";
        var xLables;
        var yLabels;
        var maxX;
        var minX;
        var maxY;
        var minY;

        for (var j=0;j<sets;j++ )
        {
            var chartDatax = measurement_sets[j][0];
            var chartDatay = measurement_sets[j][1];

            for(var i=0;i<chartDatax.length;i++)
            {
                maxX = maxX ? Math.max(maxX,chartDatax[i]) : chartDatax[i];
                minX = minX ? Math.min(minX,chartDatax[i]) : chartDatax[i];
            }
            for(var i=0;i<chartDatay.length;i++)
            {
                maxY = maxY ? Math.max(maxY,chartDatay[i]) : chartDatay[i];
                minY = minY ? Math.min(minY,chartDatay[i]) : chartDatay[i];
            }
        }
        for (var j=0;j<sets;j++ )
        {
            chartDatax = forecast_sets[j][0];
            chartDatay = forecast_sets[j][1];

            for(var i=0;i<chartDatax.length;i++)
            {
                maxX = maxX ? Math.max(maxX,chartDatax[i]) : chartDatax[i];
                minX = minX ? Math.min(minX,chartDatax[i]) : chartDatax[i];
            }
            for(var i=0;i<chartDatay.length;i++)
            {
                maxY = maxY ? Math.max(maxY,chartDatay[i]) : chartDatay[i];
                minY = minY ? Math.min(minY,chartDatay[i]) : chartDatay[i];
            }
        }

        // X Lables

        minX = Math.floor(minX) - (24 + (Math.floor(minX) % 24));
        maxX = Math.ceil(maxX) + (24 - Math.ceil(maxX) % 24);
        

        if (days && days > 0)
        {
            maxX = days * 12;
            minX = -days * 12;
        }
         
        var labelX=[];
        for (var i=minX;i<=maxX ;i=i+24 )
        {
            labelX.push(i/24 + "d");
        }
        var zeroLine = Math.round(10000*Math.abs(minX)/(maxX-minX))/10000;

        // Y Labels

        minY = 0;
        maxY = Math.ceil(maxY/1000)*1000;

        //floodcfs = 5000;
        var floodLine;
        if (floodcfs && floodcfs>0)
        {   
             maxY = Math.max(maxY, Math.ceil((100+floodcfs)/1000)*1000);
             floodLine = Math.round((floodcfs/(maxY-minY))*1000)/1000;
        }

        var labelY=[];
        var tickSizeY = (maxY-minY)/5;
        for (var i=0;i<=5;i++)
        {
            labelY.push(i * tickSizeY + minY);
        }

        // Encode Data
        var encodeType = (sets > 1) ? "s" : "e";
        var chartData=[];
        var lineStyles=[];
        var pointStyles=[];
        var lineNumber = 0;
        var lineColors = [];
        var colorIndex = 0;
        for (var i=0;i<sets ;i++ )
        {
           var color;
           if (forecast_sets[i][0].length>0)
           {
               chartData.push(encodeForGoogle(encodeType,forecast_sets[i][0],forecast_sets[i][1],minX,maxX,minY,maxY));
               lineStyles.push("1,1,1");
               color = fzChartColorsHex[colorIndex++];
               lineColors.push(color);
               pointStyles.push("d,"+color+","+lineNumber+",-1,5");
               lineNumber++;
           }
           if (measurement_sets[i][0].length>0)
           {
               chartData.push(encodeForGoogle(encodeType,measurement_sets[i][0],measurement_sets[i][1],minX,maxX,minY,maxY));
               lineStyles.push("2,1,0");
               lineColors.push( color ? color : fzChartColorsHex[colorIndex++]);
               lineNumber++;
           }
        }

        // Build Chart

        return "<img src=\"http://chart.apis.google.com/chart?cht=lxy&chs="
            +size+"&chd="+encodeType+":" + chartData.join(",")
          // +"&chxt=x,y&chxl=0:|"+minX+"|"+maxX+"|1:|"+minY+"|"+maxY 
            +"&chxt=x,y&chxl=0:|"+labelX.join("|")+"|1:|"+labelY.join("|") 
          //  +"&chm=s,0000FF,0,-1,5"
            +"&chco=0000FF"
            +"&chls=" + lineStyles.join("|")
            +"&chg="+Math.round(100.0*24.0/(maxX-minX)*100)/100+",20.0"
            +"&chm=R,000000,0,"+zeroLine+","+ (zeroLine + .001)
            + (floodLine ? "|r,FF0000EE,0," + floodLine +"," + (floodLine + .004) : "")
            + (pointStyles.length > 0 ? "|" + pointStyles.join("|") : "")
            +"&chco="+lineColors.join(",")
            +"&chtt="+escape(title + " Stream Flow")
            + "\" />" ;

    }

function encodeForGoogle(type, xValues, yValues, xminValue, xmaxValue, yminValue, ymaxValue)
{
    if (type=="e")
    {
        return extendedEncode(xValues,xminValue,xmaxValue) + "," + extendedEncode(yValues,yminValue,ymaxValue);
    }
    else
    {
        return simpleEncode(xValues, yValues, xminValue, xmaxValue, yminValue, ymaxValue);
    }
}

var simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function simpleEncode(xValues, yValues, xminValue, xmaxValue, yminValue, ymaxValue) 
{
    var xData = simpleEncodeArray(xValues, xminValue, xmaxValue);
    var yData = simpleEncodeArray(yValues, yminValue, ymaxValue);
    
    var xDataCleaned =[xData[0]];
    var yDataCleaned =[yData[0]];
    for (var i=1;i<xData.length ;i++ )
    {
        if (xData[i] != xDataCleaned[xDataCleaned.length -1] || yData[i] != yDataCleaned[xDataCleaned.length -1])
        {
           xDataCleaned.push(xData[i]);
           yDataCleaned.push(yData[i]);
        }
    }

    return xDataCleaned.join("") + "," +yDataCleaned.join("");
}

function simpleEncodeArray(valueArray,minValue,maxValue) {

var chartData = [];
  for (var i = 0; i < valueArray.length; i++) {
    var currentValue = valueArray[i];
    if (!isNaN(currentValue) && currentValue >= minValue) {
    chartData.push(simpleEncoding.charAt(Math.round((simpleEncoding.length-1) * (currentValue -minValue)/ (maxValue-minValue))));
    }
      else {
      chartData.push('_');
      }
  }
return chartData;
}


var extendedEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.';
 
function extendedEncode(valueArray,minValue,maxValue) {

var chartData = [''];
  for (var i = 0; i < valueArray.length; i++) {
    var currentValue = valueArray[i];
    if (!isNaN(currentValue) && currentValue >= minValue && currentValue <= maxValue) {
    var mappedVal = Math.round((extendedEncoding.length * extendedEncoding.length -1) * (currentValue -minValue)/ (maxValue-minValue));
    chartData.push(extendedEncoding.charAt(Math.floor(mappedVal / extendedEncoding.length)) 
                 + extendedEncoding.charAt(mappedVal % extendedEncoding.length));
    }
      else {
      chartData.push('__');
      }
  }
return chartData.join('');
}


function RenderFzChart_IE(title, sets, name_sets, measurement_sets, forecast_sets, floodcfs, yint, days) {
// sets - the number of items in the next three arrays

// Requres XYGraph.js

	var MyGraph = new XYGraph();

	var colors         = fzChartColors;
	var forecastColors = ['#C6C6FF', '#C7F9C7', '#F2CBCB', '#FFC1FF' , '#FFAC8E', ''];
	var historyLines  = new Array();
	var forecastLines = new Array();
	for (var i=0; i < sets ;i++)
	{

		historyLines[i] = new XYLine();
		historyLines[i].drawpoints=false;
		historyLines[i].VMLstroke = "weight='1pt'; color='" + colors[i] +"'; dashstyle='solid';";
		historyLines[i].label = name_sets[i] + " Gauge Readings";
		historyLines[i].x = measurement_sets[i][0];
		historyLines[i].y = measurement_sets[i][1];
		
		forecastLines[i] = new XYLine();
		forecastLines[i].drawpoints=true;
		forecastLines[i].VMLstroke = "weight='1pt'; color='" + forecastColors[i] +"'; dashstyle='solid';";
		forecastLines[i].pointsize=3;
		forecastLines[i].pointfillcolor=colors[i];
		forecastLines[i].pointstrokecolor=colors[i];
		forecastLines[i].label=name_sets[i] + " Forecast";
		forecastLines[i].x = forecast_sets[i][0];
		forecastLines[i].y = forecast_sets[i][1];
		forecastLines[i].labels = forecast_sets[i][3];
		forecastLines[i].mouseoverlabels=true;

	}

    var FloodLine = new XYLine();
	if (floodcfs && floodcfs>0)
	{
		FloodLine.drawpoints = false;
		FloodLine.VMLstroke = "weight='1pt'; color='red'; dashstyle='dash';";
		FloodLine.x[0] = historyLines[0].x[0];
		FloodLine.y[0] = floodcfs;
		FloodLine.x[1] = 0;
		FloodLine.y[1] = floodcfs;
		FloodLine.x[2] = forecastLines[0].x[forecastLines[0].x.length - 1];
		FloodLine.y[2] = floodcfs;
		FloodLine.label= "Flood Stage";
	}

	MyGraph.xint=yint;
	MyGraph.xscale=24;
	if (days && days > 0)
	{
		MyGraph.xmax = days * 12;
		MyGraph.xmin = Math.max(yint, days * -12);
		MyGraph.xint= Math.max(yint, days * -12);
	if (days >=6)
		MyGraph.xscale=12;
	else if (days >=4)
		MyGraph.xscale=6;
	else 
		MyGraph.xscale=4;

	}
	MyGraph.pad_right = 0;
	MyGraph.gheight=180; MyGraph.gwidth=515;
	MyGraph.title=title + " Stream Flow";
	MyGraph.VMLmajoraxisstroke ="weight='1pt'; color='gray';"
	MyGraph.yaxis="Stream Flow (cfs)";
	MyGraph.xticloc="auto";
//	MyGraph.userxticlabels=["10/10","10/11", "10/12"];

	var graphCommand = "MyGraph.Plot(FloodLine, ";
//	var graphCommand = "MyGraph.Plot(";
    for (var i=0;i<sets ;i++ )
    {
		if (i>0)
		{
			graphCommand += ","
		}
		graphCommand += "historyLines[" + i + "],forecastLines[" + i + "]";
    }
	graphCommand += ");"

    //MyGraph.Plot(FloodLine, forecastLines[0], historyLines[0]); // This only shows the 1st graph
	eval(graphCommand);

	return MyGraph; 
	
}

