/////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created: 11/15/2018	ELL
// Modified: 2/6/2021	ELL
// Added creation of link for uploaded files and also image for uploaded images.
// 
//

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 = -1;
var popupH = -1;
const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);

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;

var form_page;

////////////////////////////////////////////////////////////////////////////////////////////
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 resizeIFrameToFitContent(iFrame_id)
{
	var iFrame = document.getElementById(iFrame_id);
		
    if (popupW == -1)	{
		iFrame.width = Math.max(iFrame.contentWindow.document.body.scrollWidth || 0, iFrame.contentWindow.document.body.clientWidth || 0, iFrame.contentWindow.innerWidth || 0) + 250;
		iFrame.style.width = (Math.max(iFrame.contentWindow.document.body.scrollWidth || 0, iFrame.contentWindow.document.body.clientWidth || 0, iFrame.contentWindow.innerWidth || 0) + parseInt(250)).toString() + 'px';
	}
    else
      iFrame.width = popupW;
  
  	if (popupH == -1)	{
		iFrame.height = Math.max(iFrame.contentWindow.document.body.scrollHeight || 0, iFrame.contentWindow.document.body.clientHeight || 0, iFrame.contentWindow.innerHeight || 0) + 20;
		iFrame.style.height = (Math.max(iFrame.contentWindow.document.body.scrollHeight || 0, iFrame.contentWindow.document.body.clientHeight || 0, iFrame.contentWindow.innerHeight || 0) + parseInt(20)).toString() + 'px';
	}
  	else
      iFrame.height = popupH;
  
  if (iFrame.width <= 250)
    iFrame.width = 550;
  else if (popupW == -1)
    popupW = iFrame.width;
    
  if (iFrame.height <= 200)
    iFrame.height = 650;
  else if (popupH == -1)
    popupH = iFrame.height;
}

////////////////////////////////////////////////////////////////////////////////////
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("add_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";
			document.getElementById("add_btn").style.display = "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]);
//console.log(JSON.stringify(rows[0]));
			for (var key in JSON_row_4_keys) {
//console.log(key);
			   fields[j] = key;
			   if ((key != "uploads_dir") && (key != "store_uploads_instead") && (key != "form_page"))	{	// We need store_uploads_instead and uploads_dir, but we don'n want to display them.
				   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";
			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, marked_read, file_ext;
		var store_uploads_instead = 0;
		var uploads_dir = "uploads";
		var img_exts = new Array("jpg", "jpeg", "gif", "png");
		var got_img;
		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] == "store_uploads_instead") || (fields[j] == "uploads_dir") || (fields[j] == "form_page"))	{
					field_value = purifyStringToText(JSON_row[fields[j]]);
					if ((field_value == null) || (field_value == "") || (field_value == "null"))
						field_value = "&nbsp;";
					if ((fields[j] == "store_uploads_instead") && (field_value != "&nbsp;"))
						store_uploads_instead = parseInt(field_value);
					if ((fields[j] == "uploads_dir") && (field_value != "&nbsp;"))
						uploads_dir = field_value;
					if ((fields[j] == "form_page") && (field_value != "&nbsp;"))
						form_page = field_value;
				}
			}

			for (j = 0; j < field_cnt; j++)	{
				if (fields[j] != "marked_read")	{
					field_value = purifyStringToText(JSON_row[fields[j]]);
					if ((field_value == null) || (field_value == "") || (field_value == "null"))
						field_value = "&nbsp;";
					if ((fields[j] != "uploads_dir") && (fields[j] != "store_uploads_instead") && (fields[j] != "form_page"))	{
						if ((fields[j].indexOf("upload_file") > -1) && (store_uploads_instead == 1))	{
							var file_name_parts = field_value.split(".");
							file_ext = file_name_parts[file_name_parts.length - 1].toLowerCase();
							got_img = false;
							for (var k in img_exts)	{
								if (img_exts[k] == file_ext)	{
									got_img = true;
									break;
								}
							}
							
							if (got_img)
								output_str = output_str + "<td valign='top'><a href='../../" + uploads_dir + "/" + field_value + "' target='_blank'><img src='../../" +  uploads_dir + "/" + field_value + "' class='table_view_img' /></a></td>\n";
							else
								output_str = output_str + "<td valign='top'><a href='../../" + uploads_dir + "/" + field_value + "' target='_blank'>" + field_value + "</a></td>\n";
						}
						else
							output_str = output_str + "<td valign='top'>" + field_value + "</td>\n";
					}
				}
			}
			
			output_str = output_str + "<td valign='top' style='padding-left:10px; padding-right:10px;'>\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' style='padding-left:10px; padding-right:10px;'>\n<img src='../theme/" + theme + "/images/edit.png' border=0 alt='Edit'  onClick=\"EditRecord(" + JSON_row.id + ");\" style='cursor:pointer;' />\n<\/td>\n";
			
			output_str = output_str + "<td valign='top' style='padding-left:10px;'>\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 EditRecord(id)
{
	var url = http + server_name + "/manage/plugins/edit_form_record.php?table=" + document.getElementById("form_name").value + "&id=" + id + "&form_page=" + form_page;
	document.getElementById("edit_record_form").style.right = (vw - tempX + 10).toString() + "px";
	document.getElementById("edit_record_form").style.top = (tempY - 150).toString() + "px";
	document.getElementById("edit_record_form").style.bottom = "inherit";
	document.getElementById("edit_record_form").style.display = "block";
	document.getElementById("edit_record_form").style.width = "";
	document.getElementById("edit_record_form").src = url;
	setTimeout("resizeIFrameToFitContent('edit_record_form');", 500);
}

function AddRecord()
{
	var url = http + server_name + "/manage/plugins/edit_form_record.php?table=" + document.getElementById("form_name").value + "&form_page=" + form_page;
	document.getElementById("edit_record_form").style.right = (vw - tempX + 10).toString() + "px";
	document.getElementById("edit_record_form").style.top = "inherit";
	document.getElementById("edit_record_form").style.bottom = "0px";
	document.getElementById("edit_record_form").style.display = "block";
	document.getElementById("edit_record_form").style.width = "";
	document.getElementById("edit_record_form").src = url;
	setTimeout("resizeIFrameToFitContent('edit_record_form');", 500);
}

//////////////////////////////////////////////////////////////////////////////////
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("add_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 CloseEditForm()
{
	document.getElementById("edit_record_form").style.display = "none";
}

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