var reportParam = null;
var selectedReportID = 0;
var reportFromForm = false;

var timer = null;

// Report Class
var Report = function(title, param)
{
	this.Title = title;
	this.ParamList = param;
}

// ReportParameter Class
var ReportParameter = function ReportParameter(id, name, caption, required, type)
{
	this.ReportParamID = id;
	this.ParamName = name;
	this.ParamCaption = caption;
	this.Required = (required == 1 || required == true) ? true : false;
	this.ParamType = type;
	this.LookupProcName = "";
	this.LookupData = null;
};

ReportParameter.prototype.getComboItem = function()
{
	// lookup data
	var data = "<option value='-1'>";
	for(var i = 0; i < this.LookupData.Items().length; i++)
	{
		data += "<option value='" + this.LookupData.Items()[i].ID() + "'>" + this.LookupData.Items()[i].Caption();
	}

	return data;
};

// CheckList Class
var CheckListItem = function CheckListItem(id, caption)
{
	var self = this;
	self.ID = ko.observable(id);
	self.Checked = ko.observable(false);
	self.Caption = ko.observable(caption);
};

var CheckList = function CheckList(name)
{
	 var self = this;
	 self.Name = ko.observable(name);
	 self.Items = ko.observableArray();
};

// Helper function
function ReportParameterImport(item)
{
	var param = new ReportParameter(item.reportparamid, item.paramname, item.paramcaption, item.required, item.paramtype);
	param.LookupProcName = item.lookupprocname;
	param.LookupData = new CheckList(item.paramcaption);
	
	for(var i = 0; i < item.lookupdata.length; i++)
	{
		param.LookupData.Items.push(new CheckListItem(item.lookupdata[i].id, item.lookupdata[i].display));
	}
	return param;
}

function StartLoader()
{
	if(timer != null)
	{
		clearTimeout(timer);
	}
	timer = setTimeout(function(){ ShowLoader("Loading report") }, 300);
}

function EndLoader()
{
	if(timer != null)
	{
		clearTimeout(timer);
	}
	HideLoader();
}

// Event
function LoadReport(reportID, displayDescription, fromForm)
{
	selectedReportID = reportID;
	reportFromForm = fromForm;

	StartLoader();
	var param = "ReportID=" + selectedReportID;
	$.getJSON("api/SR_Report_GetParameter.asp?" + param, function(data)
	{
			EndLoader();
			reportParam = $.map(data.parameters, function(item) { return ReportParameterImport(item) });
			InitParameter(data.title, reportParam, fromForm);
			if(displayDescription)
			{
				WriteText("ReportDescription", data.description);
			}
	})
	.fail(function( jqxhr, textStatus, error ) 
	{
			toastr.error("Get parameter failed");
			console.log(error);
	})
}

function InitParameter(title, params, fromForm)
{
	var requireParam = true;

	if(fromForm)
	{
		var countParam = 0;
		for(var i = 0; i < params.length; i++)
		{
				if(params[i].ParamName != "@PrimaryID" && params[i].ParamName != "PrimaryID")
				{
					countParam++;
				}
		}

		if(countParam == 0)
		{
			requireParam = false;
		}
	}
	else
	{
		if(params.length == 0)
		{
			requireParam = false;
		}
	}

	if(!requireParam)
	{
		PrintReport_OnClick();
	}
	else
	{
		var source = "<table cellpadding='0' cellspacing='5' border='0' width='100%'>";
		for(var i = 0; i < params.length; i++)
		{
			if(params[i].ParamName != "@PrimaryID" && params[i].ParamName != "PrimaryID" || !fromForm)
			{
				source += "<tr>";
				source += "<td width='150'><b class='CaptionBold'>" + params[i].ParamCaption + "</b></td>";
				source += "<td>";
				switch(params[i].ParamType.toLowerCase())
				{
					case "int":
					{
						if(params[i].LookupProcName != "")
						{
							source += "<select class='Edit' name='Control" + params[i].ReportParamID + "' onchange=\"Lookup_OnChange(this, '" + params[i].ParamName + "')\">" + params[i].getComboItem() + "</select>";
						}
						else
						{
							source += "<input type='text' class='Edit' name='Control" + params[i].ReportParamID + "' onkeypress=\"return MaskNumber(this)\"/>";
						}
						break;
					}
					case "numeric":
					{
						source += "<input type='text' class='Edit' name='Control" + params[i].ReportParamID + "' onkeypress=\"return MaskNumber(this)\"/>";
						break;
					}
					case "varchar":
					{
						if(params[i].LookupProcName != "")
						{
							source += "<table cellpadding='0' cellspacing='0' border='0' width='100%'><tr><td><input type='text' class='ReadOnly' readonly name='Control" + params[i].ReportParamID + "' style='width: 100%'/></td><td width='1'><input type='button' value='...' class='LookupBtn' onclick='CheckList_OnClick(" + i + ")'/></td></tr></table>";
						}
						else
						{
							source += "<input type='text' class='Edit' name='Control" + params[i].ReportParamID + "'/>";
						}
						break;
					}
					case "datetime":
					{
						
						source += "<table cellpadding='0' cellspacing='0' border='0'>";
						source += "<tr>";
						source += "<td><input type='text' class='ReadOnly' readonly name='Control" + params[i].ReportParamID + "'/></td>";
						source += "<td><a href=\"javascript:calDate.Show('Date', document.ReportFrm.Control" + params[i].ReportParamID  + ");\" title=\"Calendar\"><img src='Images/icon_calendar.png' width='32' height='32' alt='Calendar'/></a></td>";
						source += "</tr>";
						source += "</table>";

						break;
					}
					case "bit":
					{
						source += "<input type='checkbox' class='Checkbox' name='Control" + params[i].ReportParamID + "'/>";
						break;
					}
				}
				source += "</td>";
				source += "<td>&nbsp;</td>";
				source += "</tr>";
			}
		}
		source += "</table>";

		ViewModel.ReportModel.report(new Report(title, source));
	}
}

function Lookup_OnChange(lookupCmb, paramName)
{
	var param = "ReportID=" + selectedReportID + "&Parameter=" + paramName + "&ID=" + GetValue(lookupCmb);
	$.getJSON("api/SR_Report_GetChildLookup.asp?" + param, function(data)
	{
		for(var i = 0; i < data.length; i++)
		{
			var controlObj = eval("document.ReportFrm.Control" + data[i].reportparamid);
			if(controlObj != null)
			{
				ClearCombo(controlObj);
				AddComboItem(controlObj, "-1", "");
				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("Get child lookup failed.");
		console.log(error);
	});
}

function CheckList_OnClick(index)
{
	ViewModel.ReportModel.showCheckList(reportParam[index].ReportParamID, reportParam[index].LookupData);
}

function GetReportParameter(callback)
{
	if(reportParam != null)
	{
		var paramStr = "";
		var errorStr = "";
		for(var i = 0; i < reportParam.length; i++)
		{
			if(reportParam[i].ParamName != "@PrimaryID" && reportParam[i].ParamName != "PrimaryID" || !reportFromForm)
			{
				var control = eval("document.ReportFrm.Control" + reportParam[i].ReportParamID);
				if(control != null)
				{
					var value = "";
					switch(reportParam[i].ParamType.toLowerCase())
					{
						case "int":
						{
							if(reportParam[i].LookupProcName != "")
							{
								// Combo box
								if(GetValue(control) != -1)
								{
									value = GetValue(control);
								}
							}
							else
							{
								value = control.value;
							}
							break;
						}
						case "numeric":
						{
							value = control.value;
							break;
						}
						case "varchar":
						{
							if(reportParam[i].LookupProcName != "")
							{
								// Check List
								var idStr = "";
								for(var j = 0; j < reportParam[i].LookupData.Items().length; j++)
								{
									if(reportParam[i].LookupData.Items()[j].Checked())
									{
										if(idStr != "")
										{
											idStr += ", ";
										}
										idStr += reportParam[i].LookupData.Items()[j].ID();
									}
								}

								if(idStr != "")
								{
									value = "\"" + idStr + "\"";
								}
							}
							else
							{
								if(control.value != "")
								{
									value = "\"" + control.value + "\"";
								}
							}
							break;
						}
						case "datetime":
						{
							// format yyyy-mm-dd
							if(control.value != "")
							{
								var dataPart = control.value.split("/");
								if(dataPart.length >= 3)
								{
									var dd = dataPart[0];
									var mm = dataPart[1];
									if(dd.length < 2)
									{
										dd = "0" + dd;
									}
									if(mm.length < 2)
									{
										mm = "0" + mm;
									}
									value = dataPart[2] + "-" + mm + "-" + dd;
								}
							}
							break;
						}
						case "bit":
						{
							if(control.checked)
							{
								value = "1";
							}
							else
							{
								value = "0";
							}
							break;
						}
					}

					if(value != "")
					{
						if(paramStr != "")
						{
							paramStr += ",";
						}
						paramStr += reportParam[i].ParamName + "=" + value;
					}
					else
					{
						if(reportParam[i].Required)
						{
							errorStr += "- " + reportParam[i].ParamCaption + " is required<br>";
						}
					}
				}
			}
		}
	}
	else
	{
		errorStr = "No report selected. Please select a report and try again.";
	}

	if(callback)
	{
		callback(paramStr, errorStr);
	}
}

// Viewmodel
function ReportViewModel()
{
	var self = this;

	self.id = 0;
	self.checkList = ko.observable();
	self.report = ko.observable();

	self.showCheckList = function(id, list)
	{
		self.id = id;
		self.checkList(list);
	}

	self.closeCheckList = function()
	{
		var str = "";
		for(var i = 0; i < self.checkList().Items().length; i++)
		{
			if(self.checkList().Items()[i].Checked())
			{
				if(str != "")
				{
					str += ", ";
				}
				str += self.checkList().Items()[i].Caption();
			}
		}

		var control = eval("document.ReportFrm.Control" + self.id);
		if(control != null)
		{
			control.value = str;
		}

		self.checkList(null);
	}

	self.closeReport = function()
	{
			self.report(null);
	}
}