function plotTime()
{
	return new Date();
}

function plotTimeAddS(s)
{
	return new Date(new Date().getTime() + s);
}

var plot1;
var options;
var duration;
v = [];
v1 = [];
seriescolors = [];
var subscribedPens = [];
var dataPlot = [];
var play = true;

var showYAxis;
var showDetails;
var cursorColor;
var backgroundColor;
var _name;

function playPause(divObj, isPlaying)
{
    if (isPlaying) {
        play = false;
        $("#" + divObj + "_Pause").attr("disabled", "disabled");
        $("#" + divObj + "_Play").removeAttr("disabled");
    } else {
        play = true;
        $("#" + divObj + "_Pause").removeAttr("disabled");
        $("#" + divObj + "_Play").attr("disabled", "disabled");
    }	
}

function namePlotter(divObj) {
    _name = divObj;
}

function updateTimePlot(divObj, isStartDate)
{
	if(isStartDate == null)
	{		
		duration = $('#' + divObj + '_Duration').data('datetimepicker').getDate().getTime();				
	}
	else
	{	
		if(!isStartDate) 
		{			
			options.axes.xaxis.max = new Date($('#' + divObj + '_EndDate').data('datetimepicker').getLocalDate().getTime());
		}
		var durationAux = $('#' + divObj + '_EndDate').data('datetimepicker').getLocalDate().getTime() - $('#' + divObj + '_StartDate').data('datetimepicker').getLocalDate().getTime();
		setDuration(divObj, durationAux);
	}
}

function setDuration(divObj, sec)
{
	duration = sec;
	$('#' + divObj + '_Duration').data('datetimepicker').setDate(duration);
}

var Pena = [];

function initialPens(divObj, Penas)
{	
	Penas.forEach(function(entry)
		{
			addPen(divObj, entry);			
		}
	);
}

function addPen(divObj, Pena)
{
	var row = "<tr id='line_" + Pena.tagname + "'><td>" + Pena.tagname+ "</td><td>" + Pena.description + "</td><td>";	
	row += Pena.interpolated ?
			"<svg style='position:relative;width:70px; height:15px;'>" +
			"<g><polyline points='0,15 5,5 10,10 15,0' style='stroke:#000000;stroke-width:1px;fill:#FFFFFF;'  transform='translate(0,0) rotate(0 106.5,162.5)' ></g>" +
			"</svg>"
		:
			"<svg style='position:relative;width:70px; height:15px;'>" +
			"<g><polyline points='0,15 5,15 5,5 15,5 15,15 20,15' style='stroke:#000000;stroke-width:1px;fill:#FFFFFF;' transform='translate(0,0) rotate(0 106.5,162.5)' ></g>" +
			"</svg>";
	row +=	"</td>" +
	"<td><select value=" + Pena.marker + "><option>O</option><option>X</option><option>Y</option></select></td>" +
	"<td><input type='text' value='" + Pena.lthick + "'></td>" +
	"<td><input id='penColor" + Pena.tagname + "' type='text' value='" + Pena.pencolor + "' class='pick-a-color' style='width:50px;'></td>" + 
	"<td><input type='checkbox' value=" + Pena.interpolated + "></td>" +
	"<td><select selectedIndex='" + Pena.lstyle +"'><option>___</option><option selected>- -</option><option>_.</option><option>_..</option><option>...</option></select></td>" +
	"<td><input type='checkbox' value='X'><td><input id='remove_" + Pena.tagname + "' onclick='removePen(\"" + divObj + "\", \"" + Pena.tagname + "\")' type='button' value='X'></td></tr>";
	AddExpressionToList('PenasCallBack$Tags/' + Pena.tagname + ';0');
	seriescolors.push(Pena.pencolor);
	if(options != null)
		options.seriesColors = seriescolors;
	subscribedPens.push(Pena.tagname);	
	$( "#" + divObj + "_Grid" ).append(row);
	$( "#" + divObj + "_Grid" ).ready( new function() { 
		$("#penColor" + Pena.tagname).pickAColor();
	});
}

function removePen(divObj, tag)
{	
	$("#line_" + tag).remove();	
	for(var i = subscribedPens.length - 1; i >= 0; i--) {			
		if(subscribedPens[i] == tag) {				
		   delete subscribedPens[i];
		}
	}
}

function changeBackground(divObj)
{
    options.grid.background = $("#" + divObj + "_BackgroundColor").val();
}

/*Date.prototype.format = function(format) //author: meizz
{
  var o = {
    "M+" : this.getMonth()+1, //month
    "d+" : this.getDate(),    //day
    "h+" : this.getHours(),   //hour
    "m+" : this.getMinutes(), //minute
    "s+" : this.getSeconds(), //second
    "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
    "S" : this.getMilliseconds() //millisecond
  }

  if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
    (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)if(new RegExp("("+ k +")").test(format))
    format = format.replace(RegExp.$1,
      RegExp.$1.length==1 ? o[k] :
        ("00"+ o[k]).substr((""+ o[k]).length));
  return format;
}*/

function setPlotData()
{
	$.each(subscribedPens, function(index, value)	
	{ 
		//.format("yy-MM-dd hh:mm:ss") <~~ IE PRECISA DISSO, MAS MESMO COM ISSO NÃO PLOTA		
		var array = [plotTime(), ScriptTagValues[GetKey("Tags/" + value + ";0")]];		
		if(dataPlot.length == index)
		{
			v = [] ;
			v.push(array);
			dataPlot.push(v);
		}
		else
		{
			dataPlot[index].push(array);
		}
	});
}

function updPlot(divObj){
	setPlotData();	
	if(plot1 != null)
	{					
		if(plotTime().getTime() > options.axes.xaxis.max && play)
		{		
			options.axes.xaxis.max = new Date(options.axes.xaxis.max.getTime() + 1000);
			options.axes.xaxis.min = new Date(options.axes.xaxis.max.getTime() - (duration > 0 ? duration : 1000));
		}
		
		plot1.data = dataPlot;
		plot1.replot(options);
	}
	else
	{
		options = {
			seriesColors:  seriescolors,
			grid: {background: '#ffffff'},
			cursor: {
				show: true,
				tooltipLocation:'sw', 
				zoom:true
			}, 
			axes:
			{			
				xaxis:{
					renderer:$.jqplot.DateAxisRenderer,
					min: plotTime(),
					max: plotTimeAddS(duration),
					tickOptions:{formatString:'%H:%M:%S'}
				}				
			}
		};
		plot1 = $.jqplot(divObj + '_Chart', [dataPlot], options);		
	}
	//atualizando o Start e o End Date
	if(options != null)
	{
		$('#' + divObj + '_StartDate').data('datetimepicker').setLocalDate(new Date(options.axes.xaxis.min));
		$('#' + divObj + '_EndDate').data('datetimepicker').setLocalDate(new Date(options.axes.xaxis.max));
	}	
}









//Validação e Funções do Dialog
		$(function() {		
		var tagname = $( "#tagname" ),
		description = $( "#description" ),
		pencolor = $( "#pencolor" ),
		marker = $( "#marker" ),
		lthick = $( "#lthick" ),
		interpolated = $( "#interpolated" ),
		lstyle = $( "#lstyle" ),
		allFields = $( [] ).add( tagname ).add( description ).add( pencolor ).add( marker ).add( lthick ).add( interpolated ).add( lstyle ),
		tips = $( ".validateTips" );
 
			function updateTips( t ) {
			  tips
				.text( t )
				.addClass( "ui-state-highlight" );
			  setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			  }, 500 );
			}
		 
			function checkLength( o, n, min, max ) {
			  if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Length of " + n + " must be between " +
				  min + " and " + max + "." );
				return false;
			  } else {
				return true;
			  }
			}
		 
			function checkRegexp( o, regexp, n ) {
			  if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			  } else {
				return true;
			  }
			}
		 
			$( "#dialog-form" ).dialog({
			  autoOpen: false,      
			  modal: true,
			  buttons: {
				"Add Pen": function() {
				  var bValid = true;
				  allFields.removeClass( "ui-state-error" );
		 
				  bValid = bValid && checkLength( tagname, "tagname", 3, 16 );
				  /*bValid = bValid && checkLength( email, "email", 6, 80 );
				  bValid = bValid && checkLength( password, "password", 5, 16 );
		 
				  bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
				  // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
				  bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
				  bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );
				*/
				  if ( bValid ) {            
					Pena.tagname = tagname.val();
					Pena.description = description.val();
					Pena.pencolor = pencolor.val();
					Pena.marker = marker.val();
					Pena.lthick = lthick.val();
					Pena.interpolated = interpolated.val();
					Pena.lstyle = lstyle.val();
					addPen(_name, Pena);
					$( this ).dialog( "close" );
				  }
				},
				Cancel: function() {
				  $( this ).dialog( "close" );
				}
			  },
			  close: function() {
				allFields.val( "" ).removeClass( "ui-state-error" );
			  }
			});
		 
			$( "#addPen" )
			  .button()
			  .click(function() {
				$( "#dialog-form" ).dialog( "open" );
			  });
		  });