var PreviousPage = 1;
var ZoomPage = "";
var ZoomPageIndex = 0;
var ZoomContainClass = "";
var timer = null;

var ChartList = [];

// Object
function Chart(page, id)
{
	var self = this;
	self.ID = id;
	self.Page = page;
	self.Loaded = false;
	self.SelectedGraphURL = "";
	self.PreviousGraphURL = [];
	self.SelectedChartType = "column";
	self.PreviousChartType = "column";
}

function LocateChart(id)
{
	for(var i = 0; i < ChartList.length; i++)
	{
		if(ChartList[i].ID == id)
		{
			return ChartList[i];
		}
	}

	return null;
}

function ChangeGraph(widgetUserID, type)
{
	var chart = LocateChart(widgetUserID);
	if(chart != null)
	{
		chart.SelectedChartType = type;
		if(chart.PreviousChartType != "")
		{
			$("#" + chart.PreviousChartType + "Chart" + widgetUserID).attr('class', "WidgetGraphTypeItem");
			$("#" + chart.PreviousChartType + "Img" + widgetUserID).attr('src', "images/icon_chart_" + chart.PreviousChartType + ".png");
			chart.PreviousChartType = type;
		}
		$("#" + type + "Chart" + widgetUserID).attr('class', "WidgetGraphTypeItemSel");
		$("#" + type + "Img" + widgetUserID).attr('src', "images/icon_chart_" + type + "_active.png");

		var index = chart.SelectedGraphURL.indexOf("&type=");
		if(index > 0)
		{
			chart.SelectedGraphURL = chart.SelectedGraphURL.substring(0, index);
		}

		RefreshGraph(widgetUserID, chart.SelectedGraphURL + "&type=" + chart.SelectedChartType + "&e=1");
	}
}

function DrillDown(widgetUserID, url)
{
	var chart = LocateChart(widgetUserID);
	if(chart != null)
	{
		$("#SettingBtn" + widgetUserID).hide();
		$("#BackBtn" + widgetUserID).show();

		chart.PreviousGraphURL.push(chart.SelectedGraphURL);
		
		if(url.indexOf("StreamMap") > 0)
		{
			chart.SelectedGraphURL = "widget/widgetchart/" + url;
			RefreshGraph(widgetUserID, chart.SelectedGraphURL);	
		}
		else
		{
			LoadContent(widgetUserID, url);
		}
	}
}

function PreviousGraph(widgetUserID)
{
	var chart = LocateChart(widgetUserID);
	if(chart != null)
	{
		if(chart.PreviousGraphURL.length <= 1)
		{
			$("#SettingBtn" + widgetUserID).show();
			$("#BackBtn" + widgetUserID).hide();
		}
		chart.SelectedGraphURL = chart.PreviousGraphURL.pop(); 
		RefreshGraph(widgetUserID, chart.SelectedGraphURL + "&type=" + chart.SelectedChartType + "&e=1");
	}
}

function RefreshGraph(widgetUserID, url)
{
	$.ajax({
		url: url,
		type: "post",
		async: true,
		cache: false,
		success: function(data) {
			var src = data.replace("src=\"", "src=\"widget/widgetchart/");
			$("#WidgetGraphCanvas" + widgetUserID).html(src);
		},
		error: function(xhr) {
			toastr.error("Refresh graph failed.");
			console.log(xhr.responseText);
		}
	});
}

function LoadContent(widgetUserID, url)
{
	$.ajax({
		url: url,
		type: "post",
		async: true,
		cache: false,
		success: function(data) {
			$("#WidgetGraphCanvas" + widgetUserID).html(data);
		},
		error: function(xhr) {
		
		}
	});
}

function InitGraph(page, widgetID, load)
{
	$.ajax({
		url: "api/JS_Dashboard_GetUserWidget.asp?id=" + widgetID,
		type: "get",
		async: true,
		cache: false,
		success: function(data) {
			var widget = JSON.parse(data);

			if(widget.Session == 1)
			{
				ChartList.push(new Chart(page, widget.WidgetUserID));

				var src = "";

				src += "<div class=\"WidgetLeftToolbar\">";
				src += "<div id=\"SettingBtn" + widget.WidgetUserID + "\">";
				src += "<a href=\"javascript:OpenSettingDialog(" + widget.WidgetUserID + ")\" title=\"Filter Setting\"><img src=\"images/icon_filter.png\" width=\"26\" height=\"26\" alt=\"Filter Setting\"/></a>";
				src += "</div>";
				src += "<div id=\"BackBtn" + widget.WidgetUserID + "\" style=\"display: none\">";
				src += "<a href=\"javascript:PreviousGraph(" + widget.WidgetUserID + ")\" title=\"Back\"><img src=\"images/btn_graph_back.png\" width=\"41\" height=\"40\" alt=\"Back\"/></a>";
				src += "</div>";
				src += "</div>";
								
				src += "<div class=\"WidgetGraph\">";
				src += "<div id=\"WidgetGraphCanvas" + widget.WidgetUserID + "\" class=\"WidgetGraphCanvas\"></div>";
				src += "<div id=\"WidgetGraphFilter" + widget.WidgetUserID + "\" class=\"WidgetGraphFilter\"></div>";
				src += "</div>";

				src += "<div class=\"WidgetGraphTypeBar\">";
				src += "<div id=\"columnChart" + widget.WidgetUserID + "\" class=\"WidgetGraphTypeItemSel\"><a href=\"javascript:ChangeGraph(" + widget.WidgetUserID + ", 'column')\" title=\"Column Graph\"><img id=\"columnImg" + widget.WidgetUserID + "\" src=\"images/icon_chart_column_active.png\" width=\"38\" height=\"38\" align=\"middle\" alt=\"Column Graph\"/></a></div>";
				src += "<div id=\"pieChart" + widget.WidgetUserID + "\" class=\"WidgetGraphTypeItem\"><a href=\"javascript:ChangeGraph(" + widget.WidgetUserID + ", 'pie')\" title=\"Pie Graph\"><img id=\"pieImg" + widget.WidgetUserID + "\" src=\"images/icon_chart_pie.png\" width=\"38\" height=\"38\" align=\"middle\" alt=\"Pie Graph\"/></a></div>";
				src += "<div id=\"stackChart" + widget.WidgetUserID + "\" class=\"WidgetGraphTypeItem\"><a href=\"javascript:ChangeGraph(" + widget.WidgetUserID + ", 'stack')\" title=\"Stack Graph\"><img id=\"stackImg" + widget.WidgetUserID + "\" src=\"images/icon_chart_stack.png\" width=\"38\" height=\"38\" align=\"middle\" alt=\"Stack Graph\"/></a></div>";
				src += "<div id=\"lineChart" + widget.WidgetUserID + "\" class=\"WidgetGraphTypeItem\"><a href=\"javascript:ChangeGraph(" + widget.WidgetUserID + ", 'line')\" title=\"Line Graph\"><img id=\"lineImg" + widget.WidgetUserID + "\" src=\"images/icon_chart_line.png\" width=\"41\" height=\"41\" align=\"middle\" alt=\"Line Graph\"/></a></div>";
				src += "</div>";
				src += "<div class=\"clear\"></div>";

				$("#WidgetPage" + page).html(src);
				$("#WidgetGraphFilter" + widget.WidgetUserID).html(widget.FilterCaption);

				if(load)
				{
					LoadGraph(widget.WidgetUserID, "column");
				}	
			}
			else
			{
				location.href = "Logon.asp";
			}
		},
		error: function(xhr) {
			toastr.error("Initialising graph failed.");
			console.log(xhr.responseText);
		}
	});
}

function InitWidget(page, url)
{
	$.ajax({
		url: url,
		type: "get",
		async: false,
		cache: false,
		success: function(data) {
				$("#WidgetPage" + page).html(data);
		},
		error: function(xhr) {
			toastr.error("Initialising widget failed.");
			console.log(xhr.responseText);
		}
	});
}

function LoadGraph(widgetUserID, type)
{
	var chart = LocateChart(widgetUserID);
	if(chart != null)
	{
		var now = new Date();
		var pnl = document.getElementById("WidgetGraphCanvas" + widgetUserID);
		chart.SelectedGraphURL = "widget/widgetchart/BinaryStreamMap.aspx?id=" + widgetUserID + "&userid=" + USERID + "&width=" + pnl.offsetWidth + "&height=" + pnl.offsetHeight + "&time=" + now.getTime(); 
		chart.Loaded = true;	

		$.ajax({
			url: chart.SelectedGraphURL + "&type=" + type + "&e=1",
			type: "post",
			async: true,
			cache: false,
			success: function(data) {
				var src = data.replace("src=\"", "src=\"widget/widgetchart/");
				$("#WidgetGraphCanvas" + widgetUserID).html(src);
			},
			error: function(xhr) {
				toastr.error("Load graph failed.");
				console.log(xhr.responseText);
			}
		});
	}
}

/******** Widget Setting *********/
var widgetParam = new TSPDataset();
widgetParam.AJAXCallback = function()
{
	if(this.Columns.Name(0) == "ParamID")
	{
		var source = "";

		this.First();
		while(!this.eof)
		{
			source += "<div>";
			source += "<label>" + this.FieldByName("Caption").Value + "</label>";
			source += "</div>";
			source += "<div class=\"row\">";
			if(this.FieldByName("ParamType").Value == "date")
			{
				source += "<table cellpadding='0' cellspacing='0' border='0'>";
				source += "<tr>";
				source += "<td><input type='text' class='Edit' name='Control" + this.FieldByName("ParamID").Value + "' value=\"" + this.FieldByName("ParamValue").Value + "\" style='width:200px'></td>";
				source += "<td><a href=\"javascript:OpenCalendar('Control" + this.FieldByName("ParamID").Value + "');\"><img src='Images/icon_calendar.png' width='32' height='32' /></a></td>";
				source += "</tr>";
				source += "</table>";
			}
			else if(this.FieldByName("ParamType").Value == "lookup")
			{
				source += "<select name='Control" + this.FieldByName("ParamID").Value + "' class='Edit' onchange=\"WidgetLookup_OnChange(this, '" + this.FieldByName("ParamName").Value + "')\">";
				source += "<option value=''>-- Select " + this.FieldByName("Caption").Value + " --";
				source += this.FieldByName("LookupData").Value;
				source += "</select>";
			}
			else if(this.FieldByName("ParamType").Value == "boolean")
			{
				var flag = "";
				if(this.FieldByName("ParamValue").Value == "1")
				{
					flag = "checked";
				}

				source += "<input type='checkbox' class='Checkbox' name='Control" + this.FieldByName("ParamID").Value + "' value='1' " + flag + ">";		
			}
			else
			{
				source += "<input type='text' class='Edit' name='Control" + this.FieldByName("ParamID").Value + "' value=\"" + this.FieldByName("ParamValue").Value + "\">";
			}

			source += "</div>";

			this.Next();
		}

		if(this.RecordCount == 0)
		{
			source += "<div>";
			source += "<label>No filter setting available.</label>";
			source += "</div>";
		}

		$("#SettingContent").html(source);
	}
}

function WidgetLookup_OnChange(lookupCmb, paramName)
{
	var param = "WidgetUserID=" + selectedWidgetUserID + "&Parameter=" + paramName + "&ID=" + GetValue(lookupCmb);
	$.getJSON("api/JS_Dashboard_GetChildLookup.asp?" + param, function(data)
	{
		for(var i = 0; i < data.length; i++)
		{
			var controlObj = eval("document.SettingForm.Control" + data[i].paramid);
			if(controlObj != null)
			{
				ClearCombo(controlObj);
				AddComboItem(controlObj, "", "-- Select " + data[i].paramcaption + " --");
				for(var j = 0; j < data[i].lookupdata.length; j++)
				{
					AddComboItem(controlObj, data[i].lookupdata[j].id, data[i].lookupdata[j].display);
				}
			}
		}
	})
	.fail(function( jqxhr, textStatus, error ) 
	{
		toastr.error("Load lookup failed.");
		console.log(error);
	});
}

var selectedWidgetUserID = 0;
function OpenSettingDialog(id)
{
	selectedWidgetUserID = id;

	widgetParam.LoadAJAX("api/JS_Dashboard_GetWidgetParam.asp", "id=" + id);

	ShowBack();
	$("#SettingDialog").show();
}

function CloseSettingDialog(save)
{
	if(save)
	{
		var filter = "";
		var data = "";

		widgetParam.First();
		while(!widgetParam.eof)
		{
			if(data != "")
			{
				data = data + "::";
			}

			var obj = eval("document.SettingForm.Control" + widgetParam.FieldByName("ParamID").Value);
			data = data + selectedWidgetUserID; 
			data = data + "|" + widgetParam.FieldByName("ParamID").Value;
			
			if(widgetParam.FieldByName("ParamType").Value == "lookup")
			{
				data = data + "|" + GetValue(obj);
				if(GetValue(obj) > 0)
				{
					if(filter != "")
					{
							filter += ", ";
					}
					filter += "<b>" + widgetParam.FieldByName("Caption").Value + ":</b> " + GetText(obj);
				}
			}
			else if(widgetParam.FieldByName("ParamType").Value == "boolean")
			{
				if(filter != "")
				{
						filter += ", ";
				}

				if(obj.checked)
				{
					data = data + "|1";
					filter += "<b>" + widgetParam.FieldByName("Caption").Value + ":</b> True";
				}
				else
				{
					data = data + "|0";
					filter += "<b>" + widgetParam.FieldByName("Caption").Value + ":</b> False";
				}
			}
			else
			{
				data = data + "|" + obj.value;
				if(filter != "")
				{
						filter += ", ";
				}
				filter += "<b>" + widgetParam.FieldByName("Caption").Value + ":</b> " + obj.value;
			}

			widgetParam.Next();
		}

		$("#WidgetGraphFilter" + selectedWidgetUserID).html(filter);

		var serverAction = new TSPDataset();
		serverAction.AJAXCallback = function()
		{
			HideBack();
			$("#SettingDialog").hide();
			var chart = LocateChart(selectedWidgetUserID);
			if(chart != null)
			{
				RefreshGraph(selectedWidgetUserID, chart.SelectedGraphURL + "&type=" + chart.SelectedChartType + "&e=1");
			}
		}
		serverAction.LoadAJAX("api/JS_Dashboard_SaveWidget.asp", "WidgetUserID=" + selectedWidgetUserID + "&interval=0&filter=" + filter + "&param=" + data);
	}
	else
	{
		HideBack();
		$("#SettingDialog").hide();
	}
}

/******** Zoom  *********/
function Zoom(page, contentClass)
{
	ZoomPage = page;
	ZoomContainClass = contentClass;
	
	for(var i = 0; i < WidgetManger.Layout.length; i++)
	{
			if(WidgetManger.Layout[i].Src == page)
			{
				ZoomPageIndex = WidgetManger.Layout[i].Page;
				break;
			}
	}

	$("#WidgetPage" + ZoomPageIndex).appendTo("#ZoomContent");
	$("#" + ZoomContainClass).attr('class', ZoomContainClass + "Zoom");
	$("#ZoomToolbar" + ZoomPage).hide();

	ShowBack();
	$("#ZoomDialog").show();
}

function CloseZoomDialog()
{
	$("#WidgetPage" + ZoomPageIndex).appendTo("#WidgetPageContent");
	$("#" + ZoomContainClass).attr('class', ZoomContainClass);
	$("#ZoomToolbar" + ZoomPage).show();

	HideBack();
	$("#ZoomDialog").hide();
}

/******** Page Management *********/
function ChangePage(page)
{
	// Restore previous menu
	$("#WidgetPageMenu" + PreviousPage).attr('class', "WidgetPageItem");
	$("#WidgetPage" + PreviousPage).hide();
	PreviousPage = page;

	// Set selected menu
	$("#WidgetPageMenu" + page).attr('class', "WidgetPageItemSel");
	$("#WidgetPage" + page).show();

	if(WidgetManger.Layout[page - 1].Type == "CHART")
	{
		for(var i = 0; i < ChartList.length; i++)
		{
			if(!ChartList[i].Loaded && ChartList[i].Page == page)
			{
				LoadGraph(ChartList[i].ID, "column");
			}
		}
	}
	else
	{
		eval(WidgetManger.Layout[page - 1].Src + "_onload()");
	}
}

/******** helper function to load external scripts *********/
function LoadScript(src, onLoad)
{
	var script_tag = document.createElement('script');
	script_tag.setAttribute("type", "text/javascript");
	script_tag.setAttribute("src", src);

	if (script_tag.readyState)
	{
		script_tag.onreadystatechange = function ()
		{
			if (this.readyState == 'complete' || this.readyState == 'loaded')
			{
					onLoad();
			}
		};
	}
	else
	{
		script_tag.onload = onLoad;
	}
	(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}

/******** helper function to load external css  *********/
function LoadCss(href)
{
	var link_tag = document.createElement('link');
	link_tag.setAttribute("type", "text/css");
	link_tag.setAttribute("rel", "stylesheet");
	link_tag.setAttribute("href", href);
	(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(link_tag);
}

function BannerRefresh()
{
	var now = new Date();

	var imgDefer = document.getElementsByTagName('img');
	for (var i = 0; i < imgDefer.length; i++)
	{
		if(imgDefer[i].getAttribute('data-src'))
		{
			imgDefer[i].setAttribute('src', imgDefer[i].getAttribute('data-src') + "&time=" + now.getTime());
		}
	}
}

$(document).ready(function(){
	$('.BannerWidgetSlider').slick({
		arrows: false,
		dots: true,
		infinite: true,
		speed: 300,
		slidesToShow: 1,
		centerMode: true,
		variableWidth: true,
		initialSlide: 0,
		autoplay: true,
		autoplaySpeed: 2500
	});

	BannerRefresh();

	timer = setInterval("BannerRefresh()", 60000);

	// Render Widget
	var menuSrc = "";
	var menuSel = "";

	var pageSrc = "";
	var pageHidden = "";
	for(var i = 0; i < WidgetManger.Layout.length; i++)
	{
		menuSel = "";
		if(i == 0)
		{
			menuSel = "Sel"
		}

		menuSrc += "<div id=\"WidgetPageMenu" + WidgetManger.Layout[i].Page + "\" class=\"WidgetPageItem" + menuSel + "\"><a href=\"javascript:ChangePage(" + WidgetManger.Layout[i].Page + ")\" title=\"" + WidgetManger.Layout[i].Caption + "\">" + WidgetManger.Layout[i].Caption + "</a></div>";
		
		pageHidden = "";
		if(i != 0)
		{
			pageHidden = "style=\"display: none\"";
		}
		pageSrc += "<div id=\"WidgetPage" + WidgetManger.Layout[i].Page + "\" class=\"WidgetPage\" " + pageHidden + "></div>";
	}

	$("#WidgetPageBar").html(menuSrc);
	$("#WidgetPageContent").html(pageSrc);

	// Init Widget
	for(var i = 0; i < WidgetManger.Layout.length; i++)
	{
		if(WidgetManger.Layout[i].Type == "CHART")
		{
			InitGraph(WidgetManger.Layout[i].Page, WidgetManger.Layout[i].Src, i == 0);
		}
		else
		{
			var callback = function() {};
			if(i == 0)
			{
				callback = function() {
					eval(WidgetManger.Layout[0].Src + "_onload()");
				};
			}
			InitWidget(WidgetManger.Layout[i].Page, "widget/" + WidgetManger.Layout[i].Src + "/layout.asp");
			LoadScript("widget/" + WidgetManger.Layout[i].Src + "/script.js", callback);
			LoadCss("widget/" + WidgetManger.Layout[i].Src + "/style.css");
		}
	}
});