<?
namespace platyFramework;
// require_once (__DIR__."/../html/cpbPage.php");

	/*
	 * $db->clear();
	 * $db->addSelect("*");
	 * $db->addFrom("t_goods");
	 *
	 * $a = new cpbDBTableEditor();
	 *
	 * $a->setDB($db);
	 * $a->add("번호", "id");
	 * $a->add("제품명")->setOnData(function ($sender, $dataItem, $colItem, $value) {
	 * return $value.="";
	 * });
	 *
	 * // upload 처리
	 * $upload = new cpbFileUpload($db, "t_goods_files");
	 * $upload->setStoredDir($_SERVER[DOCUMENT_ROOT]."/files");
	 * $upload->setStoredUrl("/files");
	 * $upload->setFormParent("formData");
	 * $upload->setName("큰상품이미지");
	 *
	 * $upload2 = clone $upload;
	 * $upload2->setName("작은상품이미지");
	 *
	 * $a->add("판매가")->setName("판매가")->setType("number");
	 * $a->add("큰상품이미지!!")->setName("큰상품이미지")->setType("image")->setImageResource($upload);
	 * $a->add("작은상품이미지!!")->setName("작은상품이미지")->setType("image")->setImageResource($upload2);
	 *
	 * echo $a->get();
	 */


/**
 * Class listslistItem
 * @package platyFramework
 *
 */
class listslistItem
{
	/* @var string */
	var $name;
	/* @var string */
	var $label;
	/* @var string : function or null */
	var $type;

	var $thAdditional;
	var $thStyle;

	function setName($name)
	{
		$this->name = $name;
		return $this;
	}

	function setLabel($label)
	{
		$this->label = $label;
		return $this;
	}

	function __construct($label, $name = "")
	{
		$this->name = $name;
		$this->label = $label;
		return $this;
	}

	function setType($type)
	{
		$this->type = $type;
		return $this;
	}

	function setImageResource($r)
	{
		$this->imageResource = $r;
	}


	/**
	 * function ($sender, $dataItem, $colItem, $value)
	 * @param $func
	 * @return $this
	 */
	function setOnData($func)
	{
		$this->onData = $func;
		return $this;
	}

	function setTHStyle($style)
	{
		$this->thStyle = $style;
		return $this;
	}

	function setTHAdditional($str)
	{
		$this->thAdditional = $str;
		return $this;
	}
}

/**
 *
 * Class dbTableList
 */
class ptyDBTableList extends controller
// class cpbDBTableEditor
{
	/* @var listslistItemx[] */
	var $cols;

	/* @var String[] */
	var $footers;

	/* @var String[] */
	var $headers;

	/* @var String[] */
	var $header_title;

	/* @var String[] */
	var $header_toobars;

	var $beforeLists;

	var $enableCheckbox = false;

	/**
	 * @var string
	 * list or grid
	 */
	var $viewMode = "list";
	
	var $customViewFile = "";

	function __construct($platyFramework)
	{
		parent::__construct($platyFramework);

		$this->footers = array();
		$this->headers = array();
		$this->beforeLists = array();

		$this->setEnableAdd(true);
		$this->setEnableRemove(true);
		$this->setEnableModify(true);

//		$this->page = new cpbPage;
//		$this->page->setLimit(15);
		$this->totalCount = -1;
	}

	function isExportExcel()
	{
		if ($_REQUEST["exportExcel"] == "1")
			return true;
		else
			return false;

	}

	function setTotalCount($cnt)
	{
		$this->totalCount = $cnt;
		return $this;
	}

	function add($label, $colName = "")
	{
		if ($colName == "" && $label != "")
			$colName = $label;

		$item = new listslistItemx($label, $colName);
		$this->cols[] = $item;
		return $item;
	}

	function addHeader($html)
	{
		$this->headers[] = $html;
	}

	function addHeaderTitle($html)
	{
		$this->header_title[] = $html;
	}



	function addHeaderToolbar($html)
	{
		$this->header_toobars[] = $html;
	}

	function addBeforeList($html)
	{
		$this->beforeLists[] = $html;
	}
	function addFooter($html)
	{
		$this->footers[] = $html;
	}

	function addFormHidden($name, $value)
	{
		$this->formHiddens[] = array(
			$name => $value
		);
	}

	function addhidden($name, $value)
	{
		$this->hiddens[] = array(
			$name => $value
		);
	}

	function setDB($db)
	{
		$this->db = $db;
		return $this;
	}

	function setEnableAdd($b)
	{
		$this->enableAdd = $b;
		return $this;
	}

	function setEnableModify($b)
	{
		$this->enableModify = $b;
		return $this;
	}

	function setEnableRemove($b)
	{
		$this->enableRemove = $b;
		return $this;
	}

	function setCheckBox($b)
	{
		$this->enableCheckbox = $b;
		return $this;
	}

	function setPrefix($prefix)
	{
		$this->prefix = $prefix;
		return $this;
	}

	function getTotalList()
	{
		$this->db->setLimit(0);
		$lst = $this->db->lst();
		return $lst;
	}

	function getTotalCount()
	{
		if ($this->totalCount < 0) {
			$this->totalCount = $this->db->getCount();
		}

		return $this->totalCount;
	}

	function processExcelExport()
	{
		if (!$this->isExportExcel())
			return;

//		print_r($lst);
		// print_r($this->cols);

		ini_set('memory_limit', '-1');
		ini_set("max_execution_time", "0");
		define('EOL', (PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

		date_default_timezone_set('Asia/Seoul');

		/** 위 소스는 크게 신경 쓰지 않아도 됨 **/

		/** PHPExcel 라이브러리 포함 **/
		// require_once $_SERVER[DOCUMENT_ROOT] . "/cpbLibrary/function/phpExcel/Classes/PHPExcel.php";
		require_once PLATYFRAMEWORK_SYSTEM_DIR. "/platyLibrary/external/phpExcel/Classes/PHPExcel.php";

		/** PHPExcel 클래스 선언 **/
		$objPHPExcel = new \PHPExcel();

// Set document properties
// 이 또한 크게 신경 쓰지 않아도 되겠습니다.
		/*
		$objPHPExcel->getProperties()->setCreator('Maarten Balliauw')
								->setLastModifiedBy('Maarten Balliauw')
								->setTitle('Office 2007 XLSX Test Document')
								->setSubject('Office 2007 XLSX Test Document')
								->setDescription('Test document for Office 2007 XLSX, generated using PHP classes.');
		*/

		$objPHPExcel->setActiveSheetIndex(0);

		$excelColNames = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q");
		$tmpArray = array();

		for ($i = 0; $i < count($this->cols); $i++) {
			if ($this->cols[$i]->label == "")
				break;

			$cellName = $excelColNames[$i] . "1";
			$objPHPExcel->getActiveSheet()->setCellValue($cellName, $this->cols[$i]->label);
			$maxExcelCellIndex = $i;
			$maxExcelCellChar = $excelColNames[$i];
		}

		$sql_q = $this->db->sql_query();
		while ($row = $this->db->sql_fetch_array($sql_q)) {
			$id = $this->cols[0]->name;

			$data = array();
			foreach ($this->cols as $col) {
				$name = $col->name;

				if ($id == $name) {
					$value = $row[$name];
					$data[] = $value;
				} else {
					$value = "";
					switch ($col->type) {
						case "number":
							$value = number_format($row[$name]);
//							echo "<TD class=number>$value</TD>";
							$data[] = $value;
							break;

						case "money":
							if ($row[$name])
								$value = number_format($row[$name]) . " 원";
//							echo "<TD class=number>$value</TD>";
							$data[] = $value;
							break;

						case "image":
							if ($row[$name]) {
								if (!$col->imageResource)
									die ("ERROR. imaegResource 지정 안됨");

								$url = $col->imageResource->getUrl($row[$name]);
								$value = "<img class=image src='$url'>";
							} else
								$value = "";
							$data[] = $value;
//							echo "<TD class=image>$value</TD>";
							break;

						case "function":
							continue;

						default:
							$value = $row[$name];

							if ($col->onData) {
								$fn = $col->onData;
								$value = $fn($this, $row, $col, $row[$name]);
							}

							$tdExt = "";

							$data[] = $value;
//							echo "<TD class=text>$value</TD>";
							break;
					}
				}
			}

			$tmpArray[] = $data;
		}

		$styleArray = array(
			'borders' => array(
				'allborders' => array(
					'style' => \PHPExcel_Style_Border::BORDER_THIN
				)
			)
		);
		$objPHPExcel->getDefaultStyle()->applyFromArray($styleArray);

		/** 위 배열 $tmpArray 를 A2 부터 차례대로 쓴다는 말입니다. **/
		$objPHPExcel->getActiveSheet()->fromArray($tmpArray, NULL, 'A2');

		/** A1 에서 부터 B1 까지를 Bold 처리 함 **/
		$objPHPExcel->getActiveSheet()->getStyle('A1:F1')->getFont()->setBold(true);
		for ($col = 'A'; $col !== $maxExcelCellChar; $col++) {
			$objPHPExcel->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);
		}
		$objPHPExcel->getActiveSheet()->getStyle("A1:$maxExcelCellChar" . (count($lst) + 1))->getFont()->setSize(9);
		$objPHPExcel->getActiveSheet()->getStyle("A1:$maxExcelCellChar" . "1")->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('FFFFCC');

		/** 각각의 셀 크기를 지정함 **/
		/** 영영을 지정하여 가로 세로의 정렬을 정의함 **/
		$objPHPExcel->getActiveSheet()->getStyle("A1:$maxExcelCellChar" . (count($tmpArray) + 1))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle("A1:$maxExcelCellChar" . (count($tmpArray) + 1))->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

		/** 위에서 쓴 엑셀을 저장하고 다운로드 합니다. **/

		if (1) {
			$fileName = "excel.xls";
			ob_end_clean();
			header('Content-Type: application/vnd.ms-excel;charset=utf-8');
			header('Content-type: application/x-msexcel;charset=utf-8');
			header("Content-Disposition: attachment;filename='$fileName'");
			header('Cache-Control: max-age=0');

			$writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			$writer->save('php://output');
			exit;
		} else {
			$writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
			$writer->save('php://output');
			exit;
		}

		exit;
	}

	function renderCustomMode($lst, $pagination)
	{
		$out = "";
		// $out .= "<div style='position: relative'>";
		foreach ($lst as $item)
		{
			$item = new ptyTableItemModel(null, $item);
			$data['item'] = $item;

			if ($this->customViewFile) $out .= $this->loader->view($this->customViewFile, $data);
			else echo "customView is not setting. <br>";
		}

		// $out .= "</div></div>";
		return $out;
	}

	function renderListMode($lst, $pagination)
	{
		$out = "\r\n<div style='width: 100%; overflow-x:scroll'>";
		$out .= "\r\n<TABLE class='table table-bordered table-striped table-hover' style='width: 100%;'>\n";
		$out .= "\t<THEAD>\n\t\t<TR>\n";

		/*
		 * Header
		 */
		if ($this->enableCheckbox)
			$out .= "<TH style='width: 30px; max-width: 30px'><input type='checkbox' class='toggle-all'></TH>";

		foreach ($this->cols as $colItem) {
			$THAdditional = $colItem->thAdditional ? " " . $colItem->thAdditional : "";
			$THStyle = $colItem->thStyle ? " style='" . $colItem->thStyle . "'" : "";

			if ($colItem->name) {
				$link = $pagination->rebuildURL(array("sc" => $colItem->name, "sa" => $this->request->request["sa"] == "desc" ? "asc" : "desc"));
				$out .= "\t\t\t<TH" . $THStyle . $THAdditional . "><a href='$link'>$colItem->label</a></TH>\n";
			} else
				$out .= "\t\t\t<TH" . $THStyle . $THAdditional . ">$colItem->label</TH>\n";
		}
		$out .= "\t\t</TR>\n\t</THEAD>\n";

		$out .= "\t<TBODY>\n";
		foreach ($lst as $row) {
			$id = $this->cols[0]->name;

			if ($row[$id] == $this->request->get['focusId'])
				$out .= "\t\t<TR class='animated flash'>\n";
			else
				$out .= "\t\t<TR>\n";

			if ($this->enableCheckbox)
			{
				$out .= "<TD style='white-space: nowrap'>";
				$out .= "<INPUT TYPE=CHECKBOX NAME='cb[]' value='$row[$id]'>";
				$out .= "</TD>";
			}

			foreach ($this->cols as $c => $col) {
				$name = $col->name;

				if ($id == $name) {
					$value = $row[$name];
				} else {
					$value = $row[$name];
				}

				if ($col->onData) {
					$fn = $col->onData;
					$value = $fn($this, $row, $col, $row[$name]);
				}

				// ptyDebug($_REQUEST[pmValue]);
				// ptyDebug("row id = ".$row[id]);

				// 수정일때, 해당 라인에 위치하면 input 으로 처리
				if ($_REQUEST[$action] == "modify" && $_REQUEST[pmValue] == $row[id] && $c != 0) {
					switch ($col->type) {
						case "image":
							$value = "";
							if ($row[$name]) {
								$url = $col->imageResource->getUrl($row[$name]);
								$value = "<img class=image src='$url'><br>";
								$value .= "<input type=checkbox name=fmd[" . $col->name . "] value='삭제'>이미지 삭제";
							}
							$value .= "<input type=file name=fm[$col->name]>";
							$out .= "<TD>$value</TD>";
							break;

//							case "function":
//								continue;

						default:
							$value = "<input type=text name=fm[$col->name] value='$row[$name]'>";
							$out .= "<TD>$value</TD>";
							break;
					}
				}
				else
					$out .= "\t\t\t<TD style='white-space:nowrap;overflow:hidden;text-overflow:ellipsis;'>$value</TD>\n";
				/*
				 * else {
					$value = "";
					switch ($col->type) {
						case "number":
							$value = number_format($row[$name]);
							$out .= "<TD style='white-space: nowrap' class=number>$value</TD>";
							break;

						case "money":
							if ($row[$name])
								$value = number_format($row[$name]) . " 원";
							$out .= "<TD style='white-space: nowrap' class=number>$value</TD>";
							break;

						case "image":
							if ($row[$name]) {
								if (!$col->imageResource)
									die ("ERROR. imaegResource 지정 안됨");

								$url = $col->imageResource->getUrl($row[$name]);
								$value = "<img class=image src='$url'>";
							} else
								$value = "";
							$out .= "<TD class=image>$value</TD>";
							break;

//							case "function":
//								continue;

						default:
							$value = $row[$name];
							$tdExt = "";
							$out .= "\t\t\t<TD style='white-space:nowrap;overflow:hidden;text-overflow:ellipsis;'>$value</TD>\n";
//								$out .= "\t\t\t<TD>$value</TD>\n";
							break;
					}
				}
				*/
//				}
			}

			// 마지막 컬럼 추가
			if ($_REQUEST[$action] == "modify" && $_REQUEST[pmValue] == $row[id]) {
				$out .= "<TD style='white-space: nowrap'>
					<button class='btn btn-info btn-xs' id=modified>수정완료</button>
					<button class='btn btn-default btn-xs' id=modifyCancel>취소</button>
					</TD>";
			} else if ($this->enableModify) {
				$out .= "<TD style='white-space: nowrap'>";
				$modify = $this->enableModify ? "<button type=button class='btn btn-xs btn-primary btnModify' uid=$row[$id]>수정</button>" : "";
				$remove = $this->enableRemove ? "<button type=button class='btn btn-xs btn-warning btnRemove' uid=$row[$id]>삭제</button>" : "";
				$out .= "$modify $remove";

				foreach ($this->cols as $col) {
					if ($col->type == "function") {
						$text = $col->label;
						if ($col->onData) {
							$fn = $col->onData;
							$text = $fn($this, $row, $col, $row[$name]);
						}

						$out .= $text . " ";
					}
				}
				$out .= "</TD>";
			}

			// $out .= "$modify $remove";



			$out .= "\t\t</TR>\n";
		}

		// add 추가
		if ($this->enableAdd) {
			$out .= "<TR>";
			foreach ($this->cols as $col) {
				$id = $this->cols[0]->name;
				$name = $col->name;

				// 첫번째 primary 는 무시
				if ($id == $name) {
					$out .= "<TD></TD>";
					continue;
				}
				switch ($col->type) {
					case "image":
						$value = "";
						$value .= "<input type=file name=fa[$col->name]>";
						$out .= "<TD>$value</TD>";
						break;

					case "function":
						continue;

					default:
						$value = "<input type=text name=fa[$col->name] value=''>";
						$out .= "<TD>$value</TD>";
						break;
				}
				/*
				 * if ($id == $name)
				 * $value = "";
				 * else
				 * $value = "<input type=text name=fa[$col->name] value=''>";
				 *
				 * echo "<TD>$value</TD>";
				 */
			}
			$out .= "<TD><button class='btn btn-primary btn-xs' id=add>추가</button></TD>";
			$out .= "</tr>";
		}


		$out .= "\t</TBODY>\n";
		$out .= "</TABLE>\n\n";
		$out .= "</div>\n\n";

		return $out;
	}

	function render()
	{
		$this->processExcelExport();

		$dataHeader = array();
		$dataBottom = array();

		require_once(__DIR__ . "/./pagination.php");

		$pagination = new pagination();
		$pagination->total = $this->getTotalCount();
		$pagination->page = $_REQUEST[page];

		// 기본 페이지 길이 설정
		if ($_REQUEST[pageLength])
			$pagination->limit = (int)$_REQUEST[pageLength];
		else {
			$pagination->limit = 15;
			$this->request->request[pageLength] = 15;
		}

		// $pagination->url = $this->url->link('user/api', 'token=' . $this->session->data['token'] . $url . '&page={page}', true);

		$dataBottom[html] .= "총 " . $this->getTotalCount() . " 개";
		$dataBottom[html] .= $pagination->render();
		
		$this->totalCount = $this->getTotalCount();
		$this->db->setLimit($pagination->limit);
		$action = $this->prefix . "action";

		if ($_REQUEST[$action] == "add") {
			$tableName = $this->db->getTableName();
			$this->db->clear()
				->addFrom($tableName)
				->addSet($_POST[fa])
				->insert();
			/*
			$s = $this->db->getKeyValues($_POST[fa]);
			$this->db->insert()
			$this->db->query("INSERT INTO " . $this->db->getTableName() . " SET $s");
			*/
			$GLOBALS['tmp_newInsertedId'] = mysql_insert_id();
			$GLOBALS['tmp_pmName'] = $_REQUEST[pmName];

			// 이미지 처리
			// cpbDebug($_FILES);

			foreach ($_FILES[fa][name] as $key => $filename) {
				// cols 객체 찾기
				foreach ($this->cols as $col) {
					if ($col->name == $key && $col->type == "image") {
						$GLOBALS['tmp_imageTableName'] = $this->db->getTableName();

						$col->imageResource->setFormParent("fa");
						$col->imageResource->setFormName($key);
						$insertedId = $col->imageResource->upload($GLOBALS['tmp_newInsertedId']);
						$this->db->query("UPDATE " . $GLOBALS['tmp_imageTableName'] . " SET `$key` = '$insertedId' WHERE `" . $GLOBALS['tmp_pmName'] . "` = '" . $GLOBALS['tmp_newInsertedId'] . "'");
					}
				}
			}
			ptyGoUrl($_REQUEST[backUrl]);
		}

		if ($_REQUEST[$action] == "modified") {
			// $imageItems
			{
				$imageColNames = array();
				foreach ($this->cols as $col) {
					if ($col->type == "image") {
						$imageColNames[] = $col->name;
						$imageCols[$col->name] = $col;
					}
				}

				if (count($imageColNames))
					$imageItems = $this->db->fetch("SELECT " . implode(",", $imageColNames) . " FROM " . $this->db->getTableName());
			}

			$formData = $_POST[fm];

			// 이미지 삭제 처리
			foreach ($_POST[fmd] as $name => $value) {
				$imageId = $imageItems[$name];
				# echo "이미지 삭제중. name = $name, imageId = $imageId <br>";

				$imageCols[$name]->imageResource->delete($imageId);
				$formData[$name] = 0;
				$imageItems[$name] = 0;
			}

			// 이미지 처리
			foreach ($_FILES[fm][name] as $name => $filename) {
				$imageId = $imageItems[$name];
				# echo "이미지 수정중. name = $name, imageId = $imageId <br>";
				$imageCols[$name]->imageResource->setFormParent("fm");
				$imageCols[$name]->imageResource->setFormName($name);
				$formData[$name] = $imageCols[$name]->imageResource->modify($imageId);
				# echo "이미지 수정 완료 = $formData[$name] <br>";
			}

			$s = $this->db->getKeyValues($formData, true, true);
			$this->db->query("UPDATE " . $this->db->getTableName() . " SET $s WHERE $_POST[pmName] = '$_POST[pmValue]'");
			ptyGoUrl($_REQUEST[backUrl]);
		}

		if ($_REQUEST[$action] == "remove") {
			// 이미지 이름 검색
			$imageColNames = array();
			foreach ($this->cols as $col) {
				if ($col->type == "image") {
					$imageColNames[] = $col->name;
				}
			}

			if (count($imageColNames)) {
				$row = $this->db->fetch("SELECT " . implode(",", $imageColNames) . " FROM " . $this->db->getTableName());

				// 이미지 삭제
				foreach ($row as $k => $v) {
					# echo "delete = $v <br>";
					$col->imageResource->delete($v);
				}
			}
			$this->db->query("DELETE FROM " . $this->db->getTableName() . " WHERE $_POST[pmName] = '$_POST[pmValue]'");
			ptyGoUrl("?");
		}

		$backUrl = $_SERVER[REQUEST_URI];

		$out .= "
		<FORM class=frmDbTableList name=frmTable action='$_SERVER[REQUEST_URI]' method=post enctype='multipart/form-data'>
		<input type=hidden name=$action value=''>
		<input type=hidden name=pmName value=''>
		<input type=hidden name=pmValue value=''>
		<input type=hidden name=backUrl value='$backUrl'>
        ";

		// formHiddens 추가
		foreach ($this->formHiddens as $name => $hidden) {
			foreach ($hidden as $key => $value) {
				$out .= "<INPUT TYPE=hidden NAME='fa[$key]' value='$value'>\n";
				$out .= "<INPUT TYPE=hidden NAME='fm[$key]' value='$value'>\n";
			}
		}

		// hiddens 추가
		foreach ($this->hiddens as $name => $hidden) {
			foreach ($hidden as $key => $value) {
				$out .= "<INPUT TYPE=hidden NAME='$key' value='$value'>\n";
			}
		}

		/*
 		* Body
 		*/
		if ($this->request->request['sc']) {
			$this->db->addOrderBy(sprintf("%s %s", $this->request->request['sc'], $this->request->request['sa']));
		}

		if (true)
			$lst = $this->db->sql_list();
		else {
			// covering index 사용시
			$dd = clone $this->db;
			$this->db->clear();
			$this->db->addSelect("b.*");
			$in = $dd->getFrom() . $dd->getJoin() . $dd->GetWhere() . $dd->getHaving() . $dd->GetGroupBy() . $dd->getOrderBy() . $dd->GetLimit();
			$this->db->addFrom("(SELECT id $in) a");
			$this->db->addJoin("INNER JOIN " . $dd->getTableName() . " b ON a.id = b.id");
			$lst = $this->db->sql_list();
		}

		if ($this->viewMode == "list") {
			$out .= $this->renderListMode($lst, $pagination);
		}
		else if ($this->viewMode == "custom") {
			$out .= $this->renderCustomMode($lst, $pagination);
		}

		$this->header_toobars[] = "<a class='btn bg-olive' href='".ptyRebuildUrl(array("exportExcel" => 1))."'>엑셀 내보내기</a>";

		$dataHeader['title'] = implode("\n", $this->header_title);
		$dataHeader['toolbar'] = implode("\n", $this->header_toobars);

		$out .= "
		</div>
		";


//		$out .= $this->page->get();


		$out .= "
<script>             
$('#add').click(function (e) {
	document.frmTable.$action.value = 'add';
	document.frmTable.pmName.value = '$id';
	document.frmTable.submit();
	return false;
});

$('.btnModify').click(function (e) {
	var uid = $(this).attr('uid');
	document.frmTable.$action.value = 'modify';
	document.frmTable.pmName.value = '$id';
	document.frmTable.pmValue.value = uid;
	document.frmTable.submit();
	return false;
});

$('.frmDbTableList .toggle-all' ).click( function () {
	$( '.frmDbTableList input[type=\"checkbox\"]' ).prop('checked', this.checked)
})


$('.btnRemove').click(function (e) {
	var uid = $(this).attr('uid');
	if (confirm(uid + '번을 정말 삭제하시겠습니까?'))
	{
		if (confirm(uid + '번를 정말로 삭제하시겠습니까?'))
		{
			document.frmTable.$action.value = 'remove';
			document.frmTable.pmName.value = '$id';
			document.frmTable.pmValue.value = uid;
			document.frmTable.submit();
			return true;
		}
	}
	
});
					
$('#modified').click(function (e) {
	document.frmTable.$action.value = 'modified';
	document.frmTable.pmName.value = '$id';
	document.frmTable.pmValue.value = '$_REQUEST[pmValue]';
	document.frmTable.submit();
});

console.log('ptyDbTableListSubmit');
$( document ).ready(function() {
$('.ptyDbTableListSubmit').click(function (e) {
	var href = $(this).attr('href');
	var confirmMsg = $(this).attr('confirm');
	
	if (confirmMsg && confirmMsg.length > 0)
	{
		if (confirm(confirmMsg))
		{
			document.frmTable.action = href;
			document.frmTable.submit();
			return false;
		}
		return false;
	}
	else
	{
		document.frmTable.action = href;
		document.frmTable.submit();
		}
});

});

</script>
        ";

		$dataHeader[html2] .= implode("", $this->headers);
		$header = $this->loader->view("ptyDBTableList/list_top", $dataHeader);

		$out = implode("", $this->beforeLists).$out;

		$dataBottom[html2] .= implode("", $this->footers);
		
		$bottom = $this->loader->view("ptyDBTableList/list_bottom", $dataBottom);

		$bottom .= "</form></div>";
//		ptyDebug($bottom); exit;

		return $header . $out . $bottom;
	}

	function getPaging()
	{
		require_once(__DIR__ . "/./pagination.php");

		$pagination = new pagination();
		$pagination->total = $this->getTotalCount();
		$pagination->page = $_REQUEST[page];

		// 기본 페이지 길이 설정
		if ($_REQUEST[pageLength])
			$pagination->limit = (int)$_REQUEST[pageLength];
		else {
			$pagination->limit = 15;
			$this->request->request[pageLength] = 15;
		}

		// $dataBottom[html] .= "총 " . $this->getTotalCount() . " 개";
		return $pagination->render();
	}


	function render2()
	{
		$pagination = new pagination();
		$pagination->total = $this->getTotalCount();
		$pagination->page = $_REQUEST[page];
		
		// 기본 페이지 길이 설정
		if ($_REQUEST[pageLength])
			$pagination->limit = (int)$_REQUEST[pageLength];
		else {
			$pagination->limit = 15;
			$this->request->request[pageLength] = 15;
		}

		$this->processExcelExport();

		$dataHeader = array();
		$dataBottom = array();

		$this->totalCount = $this->getTotalCount();
		$this->db->setLimit($pagination->limit);
		$action = $this->prefix . "action";

		$backUrl = $_SERVER[REQUEST_URI];

		$out .= "
		<FORM class=frmDbTableList name=frmTable action='$_SERVER[REQUEST_URI]' method=post enctype='multipart/form-data'>
		<input type=hidden name=$action value=''>
		<input type=hidden name=pmName value=''>
		<input type=hidden name=pmValue value=''>
		<input type=hidden name=backUrl value='$backUrl'>
        ";

		// formHiddens 추가
		foreach ($this->formHiddens as $name => $hidden) {
			foreach ($hidden as $key => $value) {
				$out .= "<INPUT TYPE=hidden NAME='fa[$key]' value='$value'>\n";
				$out .= "<INPUT TYPE=hidden NAME='fm[$key]' value='$value'>\n";
			}
		}

		// hiddens 추가
		foreach ($this->hiddens as $name => $hidden) {
			foreach ($hidden as $key => $value) {
				$out .= "<INPUT TYPE=hidden NAME='$key' value='$value'>\n";
			}
		}

		/*
 		* Body
 		*/
		if ($this->request->request['sc']) {
			$this->db->addOrderBy(sprintf("%s %s", $this->request->request['sc'], $this->request->request['sa']));
		}

		if (true)
			$lst = $this->db->sql_list();
		else {
			// covering index 사용시
			$dd = clone $this->db;
			$this->db->clear();
			$this->db->addSelect("b.*");
			$in = $dd->getFrom() . $dd->getJoin() . $dd->GetWhere() . $dd->getHaving() . $dd->GetGroupBy() . $dd->getOrderBy() . $dd->GetLimit();
			$this->db->addFrom("(SELECT id $in) a");
			$this->db->addJoin("INNER JOIN " . $dd->getTableName() . " b ON a.id = b.id");
			$lst = $this->db->sql_list();
		}

		if ($this->viewMode == "list") {
			$out .= $this->renderListMode($lst, $pagination);
		}
		else if ($this->viewMode == "custom") {
			$out .= $this->renderCustomMode($lst, $pagination);
		}

		$this->header_toobars[] = "<a class='btn bg-olive' href='".ptyRebuildUrl(array("exportExcel" => 1))."'>엑셀 내보내기</a>";

		return $out;
	}


	/**
	 * @param string $viewMode
	 */
	public function setViewMode($viewMode)
	{
		$this->viewMode = $viewMode;
	}

	/**
	 * @param string $customViewFile
	 */
	public function setCustomViewFile($customViewFile)
	{
		$this->customViewFile = $customViewFile;
	}
}

?>