/////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created: 11/15/2018	ELL
// 
//

var param_array = {'popup_msg_type' : 1, 'status_msg' : '', 'popup_timeout' : -1};
var popup_msg = new PopupMsg(param_array);

window.parent.document.title = document.title;

var browser = BrowserDetect.browser;
var browser_version = BrowserDetect.version;
var popupW = 600;
var popupH = 600;

var total_rec = 0;
var total_pages = 0;
var page = 0;
var max_rec = 50;
var sort_field = "";
var sort_direction = "ASC";
var printing = false;

////////////////////////////////////////////////////////////////////////////////////////////
function OpenHelpWindow()
{
	window.open(http + "breezewebsitebuilder.com/docs/cms/help.html#plugins#view_form_tables", "Help", "scrollbars=1,resizable=1,status=0,toolbar=0,menubar=0,location=0,height=700,width=800");
}

////////////////////////////////////////////////////////////////////////////////////////////
function titleCase(str) {
   var splitStr = str.toLowerCase().split(' ');
   for (var i = 0; i < splitStr.length; i++) {
       // You do not need to check if i is larger than splitStr length, as your for does that for you
       // Assign it back to the array
       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
   }
   // Directly return the joined string
   return splitStr.join(' '); 
}

function purifyStringToText(html){
   var doc = new DOMParser().parseFromString(html, 'text/html');
   return doc.body.textContent || "";
}

////////////////////////////////////////////////////////////////////////////////////
function RetrieveTable(table)
{
	if ((table == "") || (table == "-not selected-"))	{
		document.getElementById("user_nav_row_top").style.display = "none";
		document.getElementById("user_nav_row_bot").style.display = "none";
		document.getElementById("FormTable").innerHTML = "&nbsp;";
		document.getElementById("filter_read_msg_div").style.display = "none";
		document.getElementById("print_btn").style.display = "none";
		document.getElementById("records_per_page").style.display = "none";
	}
	else	{
		if (printing == false)	{
			document.getElementById("filter_read_msg_div").style.display = "block";
			document.getElementById("print_btn").style.display = "block";
			document.getElementById("records_per_page").style.display = "inline-block";
		}
		var order_by = "";
		if (sort_field != "")
			order_by = sort_field + " " + sort_direction;
			var where = "";
			if (document.getElementById("filter_read_msg").checked)
				where = "marked_read = 0";
			var filter_read_msg = 
		$.post( "../get_rows.php", { table: table, no_prefix: 1, max_rec: max_rec, page: page, where: where, order_by: order_by } ).done(PopulateTable) ;
	}
}

//////////////////////////////////////////////////////////////////////////////////////
function PopulateTable(rows_str)
{
//alert(rows_str);
	var rows = new Array();
	var fields = new Array();
	var bgclr;
	
	var output_str = "<table width='90%' align='center'>\n";
	output_str = output_str + "<tr bgcolor='#CCCCCC' class='header_row'>\n";
	
	row_data = rows_str.split("&&&&&");
	if (typeof row_data[1] != "undefined")	{	// If undefined, most likely table not created yet.
		total_rec = row_data[1];
		total_pages = Math.ceil(total_rec/max_rec) - 1;
		if (total_pages > 0)	{
			if (printing == false)	{
				document.getElementById("user_nav_row_top").style.display = "table-row";
				document.getElementById("user_nav_row_bot").style.display = "table-row";
			}
		
			document.getElementById("rcrd_start_top").innerHTML = (page * max_rec) + 1;
			document.getElementById("rcrd_start_bot").innerHTML = (page * max_rec) + 1;
			document.getElementById("rcrd_end_top").innerHTML = (page * max_rec) + max_rec;
			document.getElementById("rcrd_end_bot").innerHTML = (page * max_rec) + max_rec;
			document.getElementById("total_rcrds_top").innerHTML = total_rec;
			document.getElementById("total_rcrds_bot").innerHTML = total_rec;
			document.getElementById("page_num_top").innerHTML = page + 1;
			document.getElementById("page_num_bot").innerHTML = page + 1;
			document.getElementById("total_pages_top").innerHTML = total_pages + 1;
			document.getElementById("total_pages_bot").innerHTML = total_pages + 1;
			
			if (page < 1)
			{
				document.getElementById("first_top").src = "../theme/" + theme + "/images/First_disabled.gif";
				document.getElementById("prev_top").src = "../theme/" + theme + "/images/Previous_disabled.gif";
				document.getElementById("first_bot").src = "../theme/" + theme + "/images/First_disabled.gif";
				document.getElementById("prev_bot").src = "../theme/" + theme + "/images/Previous_disabled.gif";
				document.getElementById("first_top").style.cursor = "default";
				document.getElementById("prev_top").style.cursor = "default";
				document.getElementById("first_bot").style.cursor = "default";
				document.getElementById("prev_bot").style.cursor = "default";
			}
			else
			{
				document.getElementById("first_top").src = "../theme/" + theme + "/images/First.gif";
				document.getElementById("prev_top").src = "../theme/" + theme + "/images/Previous.gif";
				document.getElementById("first_bot").src = "../theme/" + theme + "/images/First.gif";
				document.getElementById("prev_bot").src = "../theme/" + theme + "/images/Previous.gif";
				document.getElementById("first_top").style.cursor = "pointer";
				document.getElementById("prev_top").style.cursor = "pointer";
				document.getElementById("first_bot").style.cursor = "pointer";
				document.getElementById("prev_bot").style.cursor = "pointer";
			}
			
			if (page == total_pages)
			{
				document.getElementById("next_top").src = "../theme/" + theme + "/images/Next_disabled.gif";
				document.getElementById("last_top").src = "../theme/" + theme + "/images/Last_disabled.gif";
				document.getElementById("next_bot").src = "../theme/" + theme + "/images/Next_disabled.gif";
				document.getElementById("last_bot").src = "../theme/" + theme + "/images/Last_disabled.gif";
				document.getElementById("next_top").style.cursor = "default";
				document.getElementById("last_top").style.cursor = "default";
				document.getElementById("next_bot").style.cursor = "default";
				document.getElementById("last_bot").style.cursor = "default";
			}
			else
			{
				document.getElementById("next_top").src = "../theme/" + theme + "/images/Next.gif";
				document.getElementById("last_top").src = "../theme/" + theme + "/images/Last.gif";
				document.getElementById("next_bot").src = "../theme/" + theme + "/images/Next.gif";
				document.getElementById("last_bot").src = "../theme/" + theme + "/images/Last.gif";
				document.getElementById("next_top").style.cursor = "pointer";
				document.getElementById("last_top").style.cursor = "pointer";
				document.getElementById("next_bot").style.cursor = "pointer";
				document.getElementById("last_bot").style.cursor = "pointer";
			}
		}
		else	{
			document.getElementById("user_nav_row_top").style.display = "none";
			document.getElementById("user_nav_row_bot").style.display = "none";
		}
	
		rows = row_data[0].split("@@@@@");
		var j = 0;
		if (rows[0] != "-no data-")	{
			var JSON_row_4_keys = JSON.parse(rows[0]);
			for (var key in JSON_row_4_keys) {
			   fields[j] = key;
			   if (key != "marked_read")	{
				   field_str = fields[j].replace(/_/g, " ");
				   if (field_str.length > 2)
					   field_str = titleCase(field_str);
				   output_str = output_str + "<td class='header_row' onclick=\"sortTable('" + key + "');\"><b><div class='column_heading_w_sort' id='" + key + "_column_heading'>" + field_str + "<\/div><\/b><\/td>\n";
			   }
			   j++;
			}
			output_str = output_str + "<td>&nbsp;<\/td>\n";
			output_str = output_str + "<td>&nbsp;<\/td>\n";
		}
		else
			output_str = output_str + "<td>&nbsp;<\/td>\n";
	}
	else
		output_str = output_str + "<td>&nbsp;<\/td>\n";

	var field_cnt = j;

	output_str = output_str + "<\/tr>\n";

	if (rows[0] == "-no data-")	// If no menu items yet (first time).
		var i = 0;
	else	// Create rows for menu items.
	{
		var field_value;
		var marked_read;
		for (var i in rows)
		{
			try	{
				var JSON_row = JSON.parse(rows[i]);
			}
			catch(err) {
				err = 0;
				continue;
			}
			
			if (bgclr == "#dddddd")
				bgclr = "#eeeeee";
			else
				bgclr = "#dddddd";
				
			marked_read = "";
			if (typeof JSON_row.marked_read != 'undefined')	{
				if (JSON_row.marked_read == 1)
					marked_read = " class=\"marked_read\"";
			}
				
			output_str = output_str + "<tr id=\"row" + i + "\" bgcolor=\"" + bgclr + "\"" + marked_read + ">\n";
			
			for (j = 0; j < field_cnt; j++)	{
				if (fields[j] != "marked_read")	{
					if (field_value == null)
						field_value = "&nbsp;";
					field_value = purifyStringToText(JSON_row[fields[j]]);
					if ((field_value == null) || (field_value == "") || (field_value == "null"))
						field_value = "&nbsp;";
					output_str = output_str + "<td valign='top'>" + field_value + "</td>\n";
				}
			}
			
			output_str = output_str + "<td valign='top' style='padding-right:20px;'>\n<img src='../theme/" + theme + "/images/check.png' border=0 alt='Mark as Read' onClick=\"MarkAsRead(" + JSON_row.id + ");\" style='cursor:pointer;' />\n<\/td>\n";
			output_str = output_str + "<td valign='top'>\n<img src='../theme/" + theme + "/images/delete.png' border=0 alt='Delete'  onClick=\"DeleteConfirm(" + JSON_row.id + ");\" style='cursor:pointer;' />\n<\/td>\n";
					
			output_str = output_str + "<\/tr>\n";
		}
		i++;
	}

	output_str = output_str + "<\/table>\n";
	
	document.getElementById("FormTable").innerHTML = output_str;
	
	setTimeout("setSortIcons();", 1000);
}

////////////////////////////////////////////////////////////////////////////////////////////
function MarkAsRead(id)
{
	if ((id != -1) && (id != ""))	{
		var table = document.getElementById("form_name").value;
		$.post( "mark_form_record_read.php", { table: table, id: id } ).done(CompleteMarkAsRead) ;
	}
}
function CompleteMarkAsRead(data)
{
	RetrieveTable(document.getElementById("form_name").value);
}

function DeleteConfirm(id)
{
	popup_msg.top_offset = 0;
	popup_msg.right_offset = 300;
	popup_msg.popup_msg_type = 3;
	popup_msg.popup_btn_cnt = 2;
	popup_msg.popup_msg_cell = DELETE_RECORD_1_MSG + " <b>" + id + "</b> " + DELETE_RECORD_2_MSG;
	popup_msg.popup_button_2_span = YES_WORD;
	popup_msg.popup_button_1_span = NO_WORD;
	popup_msg.popup_timeout = -1;
	popup_msg.ShowPopupMsg();
	document.getElementById("popup_button_2_span").onclick = function () { DeleteRecord(id); };
	document.getElementById("popup_button_1_span").onclick = function () { popup_msg.HidePopupMsg(); };
}

function DeleteRecord(id)
{
	popup_msg.HidePopupMsg();
	if ((id != -1) && (id != ""))	{
		var table = document.getElementById("form_name").value;
		var where = "id = " + id;
		$.post( "../delete_rows.php", { table: table, where: where, no_prefix: 1 } ).done(CompleteDeleteRecord) ;
	}
}
function CompleteDeleteRecord(data)
{
	RetrieveTable(document.getElementById("form_name").value);
}


//////////////////////////////////////////////////////////////////////////////////
function moveFirst()
{
	page = 0;
	RetrieveTable(document.getElementById("form_name").value);
}

function movePrev()
{
	page = Math.max(0, (page - 1));
	RetrieveTable(document.getElementById("form_name").value);
}

function moveNext()
{
	page = Math.min(total_pages, (page + 1));
	RetrieveTable(document.getElementById("form_name").value);
}

function moveLast()
{
	page = total_pages;
	RetrieveTable(document.getElementById("form_name").value);
}

function sortTable(key)
{
	if (key != sort_field)	{
		sort_direction = "ASC";
		sort_field = key;
	}
	else if (sort_field != "")	{
		if (sort_direction == "ASC")
			sort_direction = "DESC";
		else
			sort_direction = "ASC";
	}			
	
	RetrieveTable(document.getElementById("form_name").value);
}

function setSortIcons()
{
	if (sort_field != "")
	{
		if (sort_direction == "ASC")
			document.getElementById(sort_field + "_column_heading").style.backgroundImage = "url('../theme/" + theme + "/images/icon_sort_asc.png')";
		else
			document.getElementById(sort_field + "_column_heading").style.backgroundImage = "url('../theme/" + theme + "/images/icon_sort_desc.png')";
	}	
}

function PrintTable()
{
	max_rec = 1000000;
	printing = true;
	document.getElementById("user_nav_row_top").style.display = "none";
	document.getElementById("user_nav_row_bot").style.display = "none";
	document.getElementById("filter_read_msg_div").style.display = "none";
	document.getElementById("print_btn").style.display = "none";
	document.getElementById("records_per_page").style.display = "inline-block";
	RetrieveTable(document.getElementById("form_name").value);
	setTimeout("window.print();", 2);
	setTimeout("max_rec = 50; printing = false;", 10);
	var code = "RetrieveTable('" + document.getElementById("form_name").value + "');";
	setTimeout(code, 60);
}

function ChangeRecordsPerPage(new_max_rec)
{
	max_rec = parseInt(new_max_rec);
	RetrieveTable(document.getElementById("form_name").value);
}

function initializeConsole()
{
	document.getElementById("user_nav_row_top").style.display = "none";
	document.getElementById("user_nav_row_bot").style.display = "none";
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////
function ResizeWorkspace(mainWidth, mainHeight, menuWidth, headerHeight) {
}