<?php
/*
	DevSaver Web Framework
	Copyright (c) 2002-2018 DevSaver. 
	All rights reserved.
		web:  www.devsaver.com
		mail: support@devsaver.com
*/

if (!defined("STPBase")) {
	die("This file can't be accessed directly!");
}
// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/
class CLayouts extends CPlugin{
	
	var $tplvars; 

	function __construct() {
		$this->name = "layouts";
	}

	function DoEvents(){
		global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS;


		if ($_GET["mod"] == $this->name) {

			$this->tpl_module = array(
				"module_code"	=> $this->name,
				"module_name"	=> "Layouts"
			);

			parent::DoEvents();

			$sub = $_GET["sub"];
			$action = $_GET["action"];
			
			switch ($sub) {
				case "landing":
					$_GET["sub"] = $sub = "layouts";

				case "layouts":
				case "layouts.parent":

					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$data->setAclMod($this->tpl_module);

					$this->PrepareFields($data->forms["forms"]);
					$this->PrepareLayoutFields($data->forms["forms"]);

					switch ($sub) {
						case "layouts":
							$data->functions = array( 
								"ondelete"			=> array(&$this , "DeleteLayout"),
								"list_process"		=> array(&$this , "ProcessLayouts"),

							);					
						break;

						case "layouts.parent":
							$data->functions = array( 
								"onstore"			=> array(&$this , "UpdateLayoutParent"),
								"ondelete"			=> array(&$this , "UpdateLayoutParent"),
							);					
						break;
					}					
					return $data->DoEvents();
				break;


				case "duplicate":
					return $this->Duplicate();
				break;

				case "editor":
					return $this->Editor();
				break;

				case "widgets":
					return $this->EditorWidgets();
				break;

				case "editor-save":
					return $this->EditorSave();
				break;

				case "settings":

						$data = new CFormSettings($this->forms_path  . $sub . ".xml" ,$_CONF["forms"]["admintemplate"] , $this->db,$this->tables);
						$this->PrepareDashboard($data->form);

						if ($data->Done()) {

							$this->vars->SetVars(
								$this->vars->ExtractVals(
									CForm::KeyFields($data->form),
									$_POST
								)
							);
						}
						
						return $data->Show(							
							$this->vars->GetVars(
								CForm::KeyFields($data->form)
							)
						
						);
				break;


			}
		}
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareLayoutFields(&$forms) {

		if (($_GET["sub"] == "items") && ($_REQUEST["layitem_layout"])) {

			$layout = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:layouts']} WHERE layout_id={$_REQUEST[layitem_layout]}");

			$forms["search"]["fields"]["layitem_column"]["dynamic"]["to"] = $layout["layout_columns"];
		
			if ($_GET["action"] == "add") {

				global $_LANG;

				$widgets = $this->GetWidgets();				
				if (is_array($widgets)) {

					foreach ($widgets as $key => $val) {
						
						$forms["add"]["fields"]["layitem_widget"]["options"][$val["widget_id"]] = $val["widget_name"];
					}
					
				}
			}						
		}

		//show the menu box in edit 
		if (($_GET["sub"] == "layouts.parent") && $_REQUEST["layout_parent"]) {
			$layout = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:layouts']} WHERE layout_id={$_REQUEST[layout_parent]}");
			
			if ($layout["layout_fp"] && $layout["layout_fp_menu"]) {
				$forms["edit"]["lang"] = "true";
				$forms["add"]["lang"] = "true";

				$_GET["showfp"] = true;
			} else {
				$forms["edit"]["lang"] = "false";
				$forms["add"]["lang"] = "false";
			}			
		}

		if (($_GET["sub"] == "layouts") && $_REQUEST["layout_id"]) {
			$layout = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:layouts']} WHERE layout_id={$_REQUEST[layout_id]}");
			
			//show the menu column
			if ($layout["layout_fp"] && $layout["layout_fp_menu"]) {
				$_GET["showfp"] = true;
			}
		}
		
		
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetWidgets() {
				global $_LANG;

				$this->plugins["languages"]->DefaultLang();

				$widgets = $this->db->QFetchRowArray(
					"SELECT widget_note,widget_type_name , widget_module_type, widget_module , w.widget_id, widget_name FROM 
					{$this->tables['core:widgets_lang']} as l,
					{$this->tables['core:languages']} as lang,
					{$this->tables['core:widgets']} as w

					WHERE
						l.lang_id = lang.lang_id AND 
						lang.lang_default = 1 AND 
						l.widget_id = w.widget_id  AND 
						l.widget_id > 0

					ORDER BY widget_module 
				"
				);
				
				if (is_array($widgets)) {
					foreach ($widgets as $key => $val) {

						$widgets[$key]["short_name"]  = $widgets[$key]["widget_name"] ? $widgets[$key]["widget_name"] . " " : "" ;
						$widgets[$key]["module_name"] = "";

						switch ($val["widget_module_type"]) {
							case "0":
								$widgets[$key]["widget_type_name"] = "";
							break;
							//user
							case "1":
								$mod = $this->module->plugins["modules"]->GetModuleInfo($val["widget_module"] , false);
								$widgets[$key]["widget_name"] = $mod["mod_name"] . " - " . $val["widget_type_name"] . " - ( " . $val["widget_name"] . " )";									
								$widgets[$key]["module_name"] = $mod["mod_name"] ;								
								$widgets[$key]["widget_note"] = $val["widget_note"] ;								
								
							break;

							//system
							case "2":
								$mod = $this->module->plugins["modules"]->GetDefaultModuleInfoById($val["widget_module"]);
								$widgets[$key]["widget_name"] = $mod["module_name"] . " - " . $val["widget_type_name"] . " - ( " . $val["widget_name"] . " )";
								$widgets[$key]["module_name"] = $mod["module_name"] == "Widgets" ? "Static" : $mod["module_name"] ;
								$widgets[$key]["widget_note"] = $val["widget_note"] ;								
							break;

							default:

							break;

						}
						
					}
				}


				uasort(
					$widgets , 
					array($this , "sortwidgets")
				);						
				
//				debug($widgets,1);

				return $widgets;
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function sortWidgets($a , $b) {
		if ($a["short_name"] == $b["short_name"]) {
			
			if ($a["widget_note"] == $b["widget_note"]) {
				return 0;
			} else {
				return strcasecmp($a["widget_note"] , $b["widget_note"]);
			}			
		}
		
		return strcasecmp($a["short_name"] , $b["short_name"]);
	}
	
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Duplicate() {

		$layout = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:layouts']} WHERE layout_id={$_GET['layout_id']}");



		if (!is_array($layout)) {
			return "Invalid link !";
		}

		$blocks = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:layouts']} WHERE layout_parent={$layout[layout_id]} ORDER BY layout_order ASC");

		unset($layout["layout_id"]);
		unset($layout["layout_system"]);
		unset($layout["layout_generic"]);

		$layout["layout_name"] .= " (Copy)";

		$lid = $this->db->QueryInsert(
			$this->tables['core:layouts'] , 
			$layout
		);

		if (is_array($blocks)) {
			foreach ($blocks as $key => $block) {

				//read all widgets
				$widgets = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:layouts_items']} WHERE layitem_layout={$block[layout_id]} ORDER BY layitem_order ASC");

				$tmp = $block;

				unset($block["layout_id"]);
				unset($block["layout_system"]);
				unset($block["layout_generic"]);

				$block["layout_parent"] = $lid;

				$bid = $this->db->QueryInsert(
					$this->tables['core:layouts'],
					$block					
				);

				//update order
				$this->db->QueryUpdate(
					$this->tables["core:layouts"],
					array(
						"layout_order"	=> $bid
					),
					"layout_id={$bid}"
				);

				if (file_exists("../upload/layouts/{$tmp[layout_id]}.jpg")) {
					CFile::copy(
						"../upload/layouts/{$tmp[layout_id]}.jpg",
						"../upload/layouts/{$bid}.jpg"
					);
				}
				
				if (file_exists("../upload/parallax/{$tmp[layout_id]}.jpg")) {
					CFile::copy(
						"../upload/parallax/{$tmp[layout_id]}.jpg",
						"../upload/parallax/{$bid}.jpg"
					);
				}

				if (file_exists("../upload/parallax/{$tmp[layout_id]}.mp4")) {
					CFile::copy(
						"../upload/parallax/{$tmp[layout_id]}.mp4",
						"../upload/parallax/{$bid}.mp4"
					);
				}

				if (is_array($widgets)) {
					foreach ($widgets as $_key => $widget) {

						unset($widget["layitem_id"]);
						unset($widget["layitem_order"]);

						$widget["layitem_layout"] = $bid;

						$wid = $this->db->QueryInsert(
							$this->tables['core:layouts_items'] , 
							$widget,
							"layitem_order"
						);
					}
				}			
			}			
		}
		
		//redirect to details page
		urlredirect(
			"index.php?mod=layouts&sub=layouts&layout_id={$lid}&action=edit&returnurl=" . 

			urlencode("index.php?mod=layouts&sub=layouts&layout_id={$lid}&action=itemdetails&returnurl=" . 
				urlencode("index.php?mod=layouts&sub=layouts")
			)
		);
				
	}
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DeleteLayout($record) {

		$blocks = $this->db->Linear($this->db->QFetchRowArray("SELECT layout_id FROM {$this->tables['core:layouts']} WHERE layout_parent={$record[layout_id]}"));

		if (is_array($blocks)) {
			$this->db->Query("DELETE FROM {$this->tables['core:layouts_items']} WHERE layitem_layout IN (" . implode("," , $blocks) . ")");
			$this->db->Query("DELETE FROM {$this->tables['core:layouts']} WHERE layout_id IN (" . implode("," , $blocks) . ")");
		}
		
		$this->db->Query("DELETE FROM {$this->tables['core:layouts_items']} WHERE layitem_layout={$record[layout_id]}");
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function EditorWidgets() {
		global $base;

		$template = new CTemplateDynamic($this->tpl_path . "admin.editor.htm");

		$widgets = $this->getWidgets();


		return $template->blockReplace(
			"WidgetsAjax",
			array(
				"data"	=> $base->html->Table(
					$template , 
					"Widgets",
					$widgets
				),
				"widget_content"	=> $template->blockReplace("WidgetContent")
			),
			array(
				
			)
		);

	}
		

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Editor() {

		global $base , $_TSM , $_LANG_ID;


		$_TSM["PUB:MODULE_NAME"] = "Layout Widgets Editor";


		//$_TSM

		$template = new CTemplateDynamic($this->tpl_path . "admin.editor.htm");


		$main_layout = $this->db->QFetchArray("
			SELECT 
				* 
			FROM 
				{$this->tables['core:layouts']} 
			WHERE 
				layout_id=%d ",
			array(
				$_GET["layout_id"]
			)
		);

		$layouts = $this->db->QFetchRowArray("
			SELECT 
				* 
			FROM 
				{$this->tables['core:layouts']}		
			WHERE 
				layout_parent=%d AND 
				layout_device=%d
			ORDER BY 
				layout_parent ASC,layout_order ASC",
			array(
				$_GET["layout_id"],
				$_GET["section"]
			)
		);

		$widgets = $this->getWidgets();

		if (is_array($layouts)) {

			foreach ($layouts as $key => $layout) {

				$cnt ++;

				$columns_data = "";

				for ($i = 1; $i<=$layout["layout_columns"]; $i++ ) {

					$wid = $this->db->Linear($this->db->QFetchRowArray("SELECT layitem_widget FROM {$this->tables['core:layouts_items']} WHERE layitem_layout={$layout[layout_id]} AND layitem_column={$i} ORDER BY layitem_order ASC"));




					$columns_data .= $template->blockReplace(
						"Column" , 
						array(
							"widgets" => is_array($wid) ? implode("," , $wid) : "",
							"id"	=> $i,
							"size"	=> $layout["layout_c{$i}"],
							"data"	=> $base->htmlElements->Widget(
								array(
									"title"		=> "Col #{$i}",
									"icon"		=> "cogs",
									"skin"		=> "Blue",
									"height"	=> "",

									"content"	=> $template->blockReplace(
										"ColumnWidgets" , 
										array(
											
										)
									)
								)
							)
						)
					);			
				}


				//dont show paralax blocks that doesnt 
				if (!$layout["layout_parallax"] || ($layout["layout_parallax"] && $layout["layout_parallax_widgets"])) {

					$columns .= $base->htmlElements->Widget(
						array(
							"title"		=> "Block #{$cnt} " . ($layout["layout_name"] ? " (" . $layout["layout_name"] . ") " : "") , 
							"icon"		=> "cogs",
							"skin"		=> "Orange",
							"height"	=> "",

							"id"		=> "layout_block_1",

							"content"	=> $template->blockreplace(
								"Columns",
								array(
									"id"		=> $layout["layout_id"],

									"columns"	=> $columns_data
								)
							)											

						)
					);

				}				
			}
				
		} else {
			$columns .= $base->htmlElements->Widget(
				array(
					"title"		=> "Info" , 
					"icon"		=> "cogs",
					"skin"		=> "Gray",
					"height"	=> "",

					"content"	=> $template->blockreplace(
						"NoColumns",
						array(
							"link"		=> "index.php?mod=layouts&sub=landing&action=itemdetails&layout_id=" . $main_layout["layout_id"] . "&returnurl=" . urlencode(
								"index.php?mod=layouts&sub=editor&layout_id=". $main_layout["layout_id"] . "&returnurl=" . $_GET["returnurl"])
						)
					)											

				)
			);

		}
		

		/*

		*/

		if (is_array($widgets)) {

			foreach ($widgets as $key => $val) {
				
				if ($val["widget_module_type"] == "1") {
					$mids[] = $val["widget_module"];
				}				

				$modules[$val["widget_module"]] = $val["module_name"];
			}	

			$_orig_widgets = $widgets;
			//debug($widgets,1);
			
			if (is_array($mids)) {
				//read all the modules to check for parents
				$mids_data = $this->db->QFetchRowArray(
					"SELECT mod_id , mod_parent FROM {$this->tables['core:user_modules']} WHERE mod_id in (" . implode("," , $mids) . ")"
				);

				//extract all the parents
				foreach ($mids_data as $key => $val) {
					$_mids[$val["mod_id"]] = $val;
					$pids[] = $val["mod_parent"];
				}

				$mids = $_mids;

			}

			//read the parents
			if (is_array($pids)) {
				$pids_data = $this->db->QFetchRowArray(
					"SELECT p.mod_id , mod_name FROM {$this->tables['core:user_modules']} as p ,{$this->tables['core:user_modules_lang']} as l
					WHERE p.mod_id=l.mod_id and l.lang_id={$_LANG_ID} AND p.mod_id in (" . implode("," , $pids) . ")"
				);

				if (is_array($pids_data)) {
					foreach ($pids_data as $key => $val) {
						$_pids[$val["mod_id"]] = $val;
					}						
				}

				$pids = $_pids;
			}					
				//debug($mids);

			

			if (is_array($pids)) {
				//process all widgets with parents
				foreach ($widgets as $key => $val) {
					switch ($val["widget_module_type"]) {

						case "1":
							$parent = $mids[$val["widget_module"]]["mod_parent"];
							if ($parent) {

								if (!$_menu[$parent]) {
									$_menu[$parent] = array(
										"title"	=> $_pids[$parent]["mod_name"],
										"items"	=> array()
									);//$_pids[$parent];
								}

								$_menu[$parent]["items"][$val["widget_module"]] =  array(
									"id"	=> $val["widget_module"],
									"title"	=> $val["module_name"],
								);									

								unset($widgets[$key]);
							} 
						break;
					}
				}
			}

			if (is_array($widgets) && count($widgets)) {
				//process widgets without parent and system widgets
				foreach ($widgets as $key => $val) {

					switch ($val["widget_module_type"]) {
						//instance module
						case "1":
							//check if it has a parent							
							$_menu[$val["widget_module"]] =  array(
								"id"	=> $val["widget_module"],
								"title"	=> $val["module_name"],
							);									
						break;

						//global modules
						case "2":

							if ($val["module_name"] == "Widgets") {
								$val["module_name"] = "Static Widgets";
							}
							

							$system[$val["widget_module"]] =  array(
								"id"	=> $val["widget_module"],
								"title"	=> $val["module_name"],
							);																	
						break;
					}
					
				}
			}
					
			if (is_Array($system)) {
				foreach ($system as $key => $val) {
					$_menu[] = $val;
				}						
			}
					
			if (is_array($_menu)) {

				foreach ($_menu as $key => $val) {

					if (is_array($val["items"])) {
						$widgets_options.= "<optgroup label='{$val[title]}'>\n";

						foreach ($val["items"] as $k => $v) {
							$widgets_options.= "\t<option value='.widget-type-{$v[id]}'>{$v[title]}</option>\n";
						}
						
						$widgets_options.= "</optgroup>\n";
					
					} else {
						$widgets_options.= "<option value='.widget-type-{$val[id]}'>{$val[title]}</option>\n";
					}					
				}
				
			}
			
		}

		if ($main_layout["layout_has_tablet"] || $main_layout["layout_has_mobile"]) {
			$title = array(
				"options"	=> array(
					"l1"	=> array(
						"link"		=> "javascript:SwitchEditorDevice(0);" ,
						"title"		=> "Desktop / Main Layout" ,
						"icon"		=> "desktop",
						"active"	=> $_GET["section"]==0,
					),
				),
				"subtitle"	=> "Edit " . $main_layout["layout_name"] . ""
			);

			if ($main_layout["layout_has_tablet"]) {
				$title["options"]["l2"] = array(
					"link"		=> "javascript:SwitchEditorDevice(1);" ,
					"title"		=> "Tablet Layout (optional)" ,
					"icon"		=> "tablet",
					"active"	=> $_GET["section"]==1,
				);
			}
			
			if ($main_layout["layout_has_mobile"]) {
				$title["options"]["l3"] = array(
					"link"		=> "javascript:SwitchEditorDevice(2);" ,
					"title"		=> "Phone Layout (optional)" ,
					"icon"		=> "phone",
					"active"	=> $_GET["section"]==2,
				);
			}

		} else {
			$title = "Edit Layout: " . $main_layout["layout_name"] . "";
		}


		$buttons = array(
			"save2"	=> array(
				"type"		=> "button",
				"icon"		=> "save",
				"title"		=> "Save & Continue",
				"location"	=> "#",
				"onclick"	=> "SaveLayout(true)",
			),


			"back"	=> array(
				"type"		=> "button",
				"icon"		=> "back",
				"title"		=> "Back",
				"location"		=> urldecode($_GET["returnurl"]),
			),



			"save"	=> array(
				"type"		=> "button",
				"icon"		=> "save",
				"title"		=> "Save",
				"location"	=> "#",
				"onclick"	=> "SaveLayout()",
			),
		);


		if (!$_GET["returnurl"]) {
			unset($buttons["back"]);
		}
		
		return $template->blockReplace(
			"Main" , 

			array(

				"return"	=> urldecode($_GET["returnurl"]),
				"editor-url"=> "index.php?mod=layouts&sub=editor&layout_id={$_GET[layout_id]}&returnurl=" . urlencode($_GET["returnurl"]),

				"tabs"		=> CFormsTabs::newInstance(CConfig::newInstance($this->plugins["layouts"]->forms_path . "/dashboard.xml")->vars["tabs"])
									->Render(),

				"widgets"	=> $base->htmlElements->Widget(
										array(
											"title"		=> "All Widgets",
											"icon"		=> "settings",
											"skin"		=> "LightGreen",
											"height"	=> "",

											"content"	=> $template->blockReplace(
												"WidgetsMain",
												array(
													"data"	=> $base->html->Table(
														$template , 
														"Widgets",
														$_orig_widgets
													),
													"widget_content"	=> $template->blockReplace("WidgetContent")
												),
												array(
													"options"	=> $widgets_options
												)
											),

										)
									),

				"layout"	=> $base->htmlElements->Widget(
										array(
											"title"		=> $title,
											"icon"		=> "cogs",
											"skin"		=> "Orange",
											"height"	=> "",

											"content"	=> $template->blockReplace("Info"),

											"buttons"	=>	$buttons,
										)
									),
										

				"columns"	=> $columns
				
				
			)
		);

	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function EditorSave() {

		$layouts = json_decode(stripslashes($_POST["data"]),true);

		if (is_array($layouts)) {
			foreach ($layouts as $key => $layout) {
				//delete all the widgets for this layout
				$this->db->Query("DELETE FROM {$this->tables['core:layouts_items']} WHERE layitem_layout={$key}");

				if (is_array($layout)) {
					foreach ($layout as $k => $v) {
						$id = $this->db->QueryInsert(
							$this->tables['core:layouts_items'],
							array(
								"layitem_layout"		=> $v["layout"],
								"layitem_widget"		=> $v["widget"],
								"layitem_column"		=> $v["colum"],
							)
						);

						$this->db->QueryUpdate(
							$this->tables["core:layouts_items"],
							array(								
								"layitem_order"			=> $id,
							),
							"layitem_id={$id}"
						);
					}
					
				}
				

				
			}
		}
		
		



		return json_encode(array(
			"status"	=> "ok",
			"redirect"	=> "xxx",
		));
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function LoadFromFile($path) {
		$layout = new CConfig($path);
		$layout = $layout->vars["layout"];

		return $this->LoadFromString($layout);
	}
	
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function LoadFromString($layout) {

		//some default checks

		if (!is_array($layout["block"][0])) {
			//one block layout
			$layout["block"] = array(
				0	=> $layout["block"]
			);
		}

		foreach ($layout["block"] as $key => $block) {


			if (!is_array($block["col"][0])) {
				$layout["block"][$key]["col"] = array(
					0	=> $block["col"]
				);

			}			
		}
		

		foreach ($layout["block"] as $key => $block) {
			foreach ($block["col"] as $_key => $_val) {
				if (!is_array($_val["widget"])) {
					$layout["block"][$key]["col"][$_key]["widget"] = array(
						0	=> $_val["widget"]
					);
				}
				
			}
			
		}

	
		return $layout;
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function SaveLayout($layout) {

		$layout = $this->LoadFromString($layout);

		//save the main block
		$id = $this->db->QueryInsert(
			$this->tables["core:layouts"] , 
			array(
				"layout_name" => $layout["name"],
				"layout_template"	=> $layout["template"] == "footer" ? "2" : 1,
			)
		);



		foreach ($layout["block"] as $key => $val) {

			$block = array(
				"layout_parent"		=> $id,
				"layout_columns"	=> 0,
				"layout_status"		=> "1",
				"layout_extra_css"	=> $val["css"] ? "1" : "",
				"layout_css"		=> $val["css"],
			);

			//calculate the number of columns and the size for each
			foreach ($val["col"] as $_key => $_val) {
				$block["layout_columns"] ++;
				$block["layout_c" . $block["layout_columns"]] = $_val["size"];

				if ($_val["css"]) {
					$block["layout_css_" . $block["layout_columns"]] = $_val["css"];
					$block["layout_extra_css"] = "1";
				}
				
			}
			
			//save the new block
			$bid = $this->db->QueryInsert(
				$this->tables['core:layouts'],
				$block
			);

			$this->db->QueryUpdate(
				$this->tables["core:layouts"],
				array(
					"layout_order" => $bid
				),
				"layout_id={$bid}"
			);

			//save the widgets to each block
			foreach ($val["col"] as $_k => $_v) {

				foreach ($_v["widget"] as $__k => $__v) {

					switch ($__v) {
						case "__CONTENT__":
							$__v = "-1";
						break;
					}
					

					$wid = $this->db->QueryInsert(
						$this->tables["core:layouts_items"],
						array(
							"layitem_layout"	=> $bid , 
							"layitem_column"	=> $_k + 1,
							"layitem_widget"	=> $__v,
						)
					);

					$this->db->QueryUpdate(
						$this->tables["core:layouts_items"] , 
						array(
							"layitem_order"	=> $wid
						),
						"layitem_id = {$wid}"
					);

				}
				

			}
			
		}

		return $id;
		
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function UpdateLayoutParent($record) {

		if ($_GET["action"] == "delete") {

			//update the existence of the alternative versions
			$this->db->QueryUpdate(
				$this->tables['core:layouts'],
				array(
					"layout_has_tablet" => $this->db->RowCount($this->tables['core:layouts'] , " WHERE layout_parent={$record[layout_parent]} AND layout_id != {$record[layout_id]} AND layout_device=1") ? 1 : 0,
					"layout_has_mobile"	=> $this->db->RowCount($this->tables['core:layouts'] , " WHERE layout_parent={$record[layout_parent]} AND layout_id != {$record[layout_id]} AND layout_device=2") ? 1 : 0,
				),
				"layout_id = {$record[layout_parent]}"
			);

		} else {
			//update the existence of the alternative versions
			$this->db->QueryUpdate(
				$this->tables['core:layouts'],
				array(
					"layout_has_tablet" => $this->db->RowCount($this->tables['core:layouts'] , " WHERE layout_parent={$record[layout_parent]} AND layout_device=1") ? 1 : 0,
					"layout_has_mobile"	=> $this->db->RowCount($this->tables['core:layouts'] , " WHERE layout_parent={$record[layout_parent]} AND layout_device=2") ? 1 : 0,
				),
				"layout_id = {$record[layout_parent]}"
			);
		}
		

	}
		

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ProcessLayouts($items , $count) {

		if (is_array($items)) {
			foreach ($items as $key => $val) {
				$items[$key]["assigned"] = $this->ModuleLayouts($val["layout_id"]);
			}
		}

		return array(
			"items"	=> $items,
			"count"	=> $count
		);

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ModuleLayouts($id) {

		if (!$this->_loaded) {
			$mod =  $this->plugins["modules"]->GetInstanceModules();
			if (is_array($mod)) {
				foreach ($mod as $key => $val) {
					$this->mods[$val["mod_id"]] = array(
							"name"	=> $val["mod_name"],
							"link"	=> "index.php?mod=" . $val["mod_module_code"] . "&sub=landing&module_id=" . $val["mod_id"],
					);

				}				
			}
			
			$mod = $this->plugins["modules"]->GetCoreModules();
			if (is_array($mod)) {
				foreach ($mod as $key => $val) {
					$this->mods[$val["module_code"]] = array(
							"name"	=> $val["module_name"],
							"link"	=> "index.php?mod=" . $val["module_code"] . "&sub=landing",
					);
				}				
			}

			$this->_loaded = true;
		}
		

		$set = $this->db->QFetchRowArray("
			SELECT distinct(module) FROM 
				{$this->tables['core:modules_settings']}
			WHERE 
				`setting` LIKE 'set_layout%' AND
				`value` = {$id}
		");	

		if (is_array($set)) {
			$tmp = array();
			foreach ($set as $key => $val) {

				if ($this->mods[$val["module"]]) {
					$tmp[] = "<a class=\"normal\" target=\"_blank\" href=\"" . $this->mods[$val["module"]]["link"] ."\">" . $this->mods[$val["module"]]["name"] ."</a>";
				} 				
			}	
			
			sort($tmp);
			return implode(", ", $tmp);
		}

		return "<i>N/A</i>";
	}
	
}

?>