<?php

/** KumbiaForms - PHP Rapid Development Framework *****************************
*	
* Copyright (C) 2005-2007 Andrés Felipe Gutiérrez (andresfelipe at vagoogle.net)
* 	
* This framework is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* 
* This framework is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
* 
* You should have received a copy of the GNU Lesser General Public
* License along with this framework; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
* 
* Este framework es software libre; puedes redistribuirlo y/o modificarlo
* bajo los terminos de la licencia pública general GNU tal y como fue publicada
* por la Fundación del Software Libre; desde la versión 2.1 o cualquier
* versión superior.
* 
* Este framework es distribuido con la esperanza de ser util pero SIN NINGUN 
* TIPO DE GARANTIA; sin dejar atrás su LADO MERCANTIL o PARA FAVORECER ALGUN
* FIN EN PARTICULAR. Lee la licencia publica general para más detalles.
* 
* Debes recibir una copia de la Licencia Pública General GNU junto con este
* framework, si no es asi, escribe a Fundación del Software Libre Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA 
*****************************************************************************/

class GridForm_Generator {

	static function build_form_grid($form){

		/*************************************************************************
		* Description: This function builds grid style forms
		*************************************************************************/

		if(!array_key_exists('dataRequisite', $form)) $form['dataRequisite'] = 1;
		if(!$form['dataRequisite']) {
			Generator::forms_print("<font style='font-size:11px'><center><i><b>No hay datos en consulta</b></i></center></font>");
		} else {
			if(isset($form['noExtendItems'])){
				if($form['noExtendItems']==true)
				Generator::forms_print("<input type='hidden' name='noExtendItems' id='noExtendItems' value=1>\r\n");
				else Generator::forms_print("<input type='hidden' name='noExtendItems' id='noExtendItems' value=0>\r\n");
			} else Generator::forms_print("<input type='hidden' name='noExtendItems' id='noExtendItems' value=0>\r\n");

			/***********************************************************************
			* scrmax : Grid Rows Number
			* actmin : Minimum Array Value to Show
			* actmax : Maximum Array Value to Show
			* Values : All Table Values Ordered in a MultiDimensional Array
			***********************************************************************/

			if(!isset($form['scrmax'])) formsError('0001');
			Generator::forms_print("<input type='hidden' name='scrmax' id='scrmax' value='".$form['scrmax']."'>\r\n");
			Generator::forms_print("<input type='hidden' name='actmin' id='actmin'>\r\n");
			Generator::forms_print("<input type='hidden' name='actmax' id='actmax'>\r\n");
			Generator::forms_print("<script type='text/javascript'> var Values = new Array(); \r\nvar Fields; var EmptyArr; \r\nvar Registers = new Array();\r\n");

			$db = db::raw_connect();

			$selectedFields = "";
			for($i=0;$i<=count($form['components'])-1;$i++){
				if(!isset($form['components'][key($form['components'])]['formOnly'])){
					$selectedFields.= key($form['components']).",";
				} else {
					if(!$form['components'][key($form['components'])]['formOnly']){
						$selectedFields.= key($form['components']).",";
					}
				}
				next($form['components']);
			}
			$selectedFields = substr($selectedFields, 0, strlen($selectedFields)-1);
			if(!isset($form['dataFilter'])) $form['dataFilter'] = " 1 = 1 ";
			else if(!$form['dataFilter']) $form['dataFilter'] = " 1 = 1 ";
			$valuesArrV = array();
			$valuesArr = array();
			for($i=0;$i<=count($form['components'])-1;$i++){
				$valuesArrV[] = "";
			}
			if($form['dataFilter']){
				if($x = strpos($form['dataFilter'], '@')){
					while(ereg("[\@][A-Za-z0-9_]+", $form['dataFilter'], $regs)){
						$form['dataFilter'] = str_replace($regs[0], $_REQUEST["fl_".str_replace('@', '', $regs[0])], $form['dataFilter']);
					}
				}
			}
			//print "select $selectedFields from ".$form['source']." where ".$form['dataFilter'];
			if($db->query("select $selectedFields from ".$form['source']." where ".$form['dataFilter'])){
				$n = 0;
				if($db->num_rows()){
					while($row = $db->fetch_array()){
						$valuesArr[$n] = $valuesArrV;
						for($i=0;$i<=count($row)-1;$i++){
							if(isset($row[$i])){
								if($row[$i]!==null){
									$valuesArr[$n][$i]=$row[$i];
								}
							}
						}
						$n++;
					}
					$n = 0;
					for($i=0;$i<=count($valuesArr)-1;$i++){
						$val = "";
						$emparr = "";
						reset($form['components']);
						for($j=0;$j<=count($valuesArr[$i])-1;$j++){
							$val.="'".$valuesArr[$i][$j]."'";
							$emparr.="''";
							if($j!=(count($valuesArr[$i])-1)){
								$val.=",";
								$emparr.= ",";
							}
							next($form['components']);
						}
						Generator::forms_print("Values[$n] = new Array($val);\r\n");
						$n++;
					}
				}
				reset($form['components']);
				$fields = "";
				$notNull = "";
				for($i=0;$i<=count($form['components'])-1;$i++){
					$v = current($form['components']);
					$fields.= "'".key($form['components'])."'";
					if(!isset($v['notNull'])){
						$v['notNull'] = false;
					}
					if(!isset($v['primary'])){
						$v['primary'] = false;
					}
					if($v['notNull']||$v['primary']) {
						$notNull.="1"; 
					} else {
						$notNull.="0";
					}
					if($i!=(count($form['components'])-1)) $fields.=",";
					if($i!=(count($form['components'])-1)) $notNull.=",";
					next($form['components']);
				}
				Generator::forms_print("Fields = new Array($fields);\r\n");
				Generator::forms_print("GNotNullFields = new Array($notNull);\r\n");
				Generator::forms_print("function fEmptyArr(){ return new Array($emparr); }\r\n");
			} else jerror($db->error());
			if(!$form['permissions']) {
				$form['permissions'] =  array();
			}
			Generator::forms_print("</script>\r\n<center>");

			if($form['type']=='grid'){				
				Generator::forms_print("<input type='button' id='modifica' class='controlButton' value='Modificar' onclick='if(this.value==\"Modificar\") enableForEdit(this); else saveData(); '>&nbsp;\r\n");				
				Generator::forms_print("<input type='button' class='controlButton' value='Reporte' onclick='enableForReport()'>&nbsp;\r\n");							
				Generator::forms_print("<br/><br/>\r\n");
			}
			Generator::forms_print("<table cellpadding=0 cellspacing=0><td><table cellpadding=0 align='center'><tr>");
			if(isset($form['enableFastDelete'])){
				if($form['enableFastDelete']) {
					Generator::forms_print("<td></td>");
				}
			}
			if(isset($form['componentLabels'])){
				if($form['componentLabels']){
					Generator::forms_print("<td></td>");
				}
			}
			foreach($form["components"] as $name => $component){
				if(!isset($component['caption'])) {
					$component['caption'] = "";
				}
				if($component['type']!='button'){
					Generator::forms_print("<td align='center'><b>".$component["caption"]."</b></td>\r\n");
				}
			}
			Generator::forms_print("</tr>\r\n");

			//Setting DynamicValues
			$dynamicValues = array();
			$dynamicNumber = 0;
			$dynamicImplicitValues = array();
			$referencedValues = array();
			foreach($form["components"] as $name => $component){
				if(array_key_exists('dynamicValue', $component)){
					$referencedValues = array();
					$referencedValues[] = $name;
					$numVal = 1;
					$index = getIndex($name, $form);
					$dynamicValues[$dynamicNumber] = "Values[i][$index] = ";
					//$dynamicValues[$dynamicNumber] = "alert(";
					$component['dynamicValue'].=" ";
					for($x=0;$x<=strlen($component['dynamicValue'])-1;$x++){
						$ch = substr($component['dynamicValue'], $x, 1);
						if($ch=="@"){
							$x++;
							$ch = substr($component['dynamicValue'], $x, 1);
							$dynamicValues[$dynamicNumber].="parseInt(Values[i][";
							while(ctype_alnum($ch)||$ch=='_'){
								//$dynamicValues[$dynamicNumber].=$ch;
								$referencedValues[$numVal].=$ch;
								$x++;
								if($x>(strlen($component['dynamicValue'])-1)) break 1;
								$ch = substr($component['dynamicValue'], $x, 1);
							}
							$index = getIndex($referencedValues[$numVal], $form);
							$dynamicValues[$dynamicNumber].="$index])$ch";
							$numVal++;
						} else $dynamicValues[$dynamicNumber].=$ch;
					}
					$referencedValues = array_unique($referencedValues);
					$dynamicNumber++;
				}
			}
			$dynamicImplicitValues = array_merge($dynamicImplicitValues, $referencedValues);
			$dynamicImplicitValues = array_unique($dynamicImplicitValues);
			foreach($dynamicImplicitValues as $name){
				$form['components'][$name]['implicitDynamicValue'] = true;
			}

			if(count($dynamicImplicitValues)){
				Generator::forms_print("\r\n<script>\r\n function calcDynamicValues(k){\r\n\t");
				Generator::forms_print("if(k!=undefined){\r\n\t\treturn;\r\n\t}\r\n\tfor(i=0;i<=Values.length-1;i++){\r\n\t\t");
				foreach($dynamicValues as $dynValue){
					Generator::forms_print($dynValue."\r\n\t\t");
				}
				Generator::forms_print("}\r\n\tloadValues(parseInt(document.getElementById(\"actmin\").value), parseInt(document.getElementById(\"actmax\").value))\r\n}\r\n</script>\r\n");
			}

			$autoInc = array();
			for($i=0;$i<=$form['scrmax']-1;$i++){
				Generator::forms_print("<tr id='row$i'>");
				if(isset($form['enableFastDelete']))
				if($form['enableFastDelete'])
				Generator::forms_print("<td><img src='".KUMBIA_PATH."img/delete.gif' style='cursor:pointer' onclick='deleteRow($i)'></td>");
				if(isset($form['componentLabels']))
				if($form['componentLabels'])
				Generator::forms_print("<td align='right'><b><i>".$form['componentLabels'][$i]."</i></b></td>");
				foreach($form["components"] as $name => $component){
					Generator::forms_print("<td align='center'>\n");
					switch($component["type"]){
						case "text":
						Generator::forms_print("<input type='text' name='fl_$name$i' id='flid_$name$i' disabled class='formText'");
						if($component["attributes"]){
							foreach($component["attributes"] as $nitem => $item){
								if($nitem!='onblur')
								Generator::forms_print(" $nitem='$item' ");
							}
						}

						//Validacion de Formatos
						if($component['format']){
							Generator::forms_print(" onkeypress=\"formatNumber(this, '{$component['format']}')\"");
						}

						$validation = "";
						$imp = "";
						if($component['implicitDynamicValue'])
						$imp = "calcDynamicValues(); ";
						if($component['totalize']&&$component['valueType']=='numeric'){
							$index = getIndex($name, $form);
							$imp = "totalizeColumn(\"$name\", \"$index\"); ";
						}

						if($component['vals'])
						$validation = "if(flid_$name$i.value".$component['vals'].") { this.className=\"iError\"; alert(\"ESTE VALOR NO ES VALIDO\"); document.getElementById(\"errStatus\").value = 1; this.focus(); } else { this.className=\"iNormal\"; window.status = \"\"; document.getElementById(\"errStatus\").value = 0; } ";
						if($component['valueType']=="numeric")
						Generator::forms_print("onkeydown='valNumeric(event)'");
						if($component['valueType']=="textUpper")
						Generator::forms_print("onblur='keyUpper(this)'");
						//print "<pre>";
						//print_r($component);
						//print "</pre>";
						while(ereg("[@][a-zA-Z0-9_]+", $component['attributes']['onblur'], $regs)){
							$component['attributes']['onblur'] =
							str_replace($regs[0], "document.getElementById(\"flid_".str_replace("@", "", $regs[0])."$i\")", $component['attributes']['onblur']);
						}
						$component['attributes']['onblur'] = str_replace("#?", "$i", $component['attributes']['onblur']);
						//print "<h1>-".$form['attributes']['onBlur']."</h1>";
						if(!$component['checkUnique']){
							if($component['valueType']=="date")
							Generator::forms_print("onblur='$validation; saveValue(this); checkDate(this); $imp; ".$component['attributes']['onblur']."'");
							else Generator::forms_print(" onblur='$validation; saveValue(this); $imp; ".$component['attributes']['onblur']."'");
						} else {
							if($component['valueType']=="date")
							Generator::forms_print("onblur='$validation;  saveValue(this); checkDate(this); checkUnique(this); $imp; ".$component['attributes']['onblur']."'");
							else
							Generator::forms_print(" onblur='$validation; saveValue(this); checkUnique(\"$name\", this); $imp; ".$component['attributes']['onblur']."'");
						}
						Generator::forms_print("/>\r\n");
						break;
						case "color":
						Generator::forms_print("<input type='text' name='fl_$name$i' id='flid_$name$i' disabled readonly='true' size=8 title='Color'");
						Generator::forms_print("style='color:#FFFFFF;'/>
                    <input type='button' value='...' onclick='getColor(document.getElementById(\"flid_$name$i\"))'>
                    \r\n");
						break;
						case "hidden":
						Generator::forms_print("<input type='hidden' name='fl_$name$i' id='flid_$name$i'");
						if($component["attributes"]["value"]){
							while(ereg("[@][a-zA-Z0-9_]+", $component["attributes"]["value"], $regs)){
								$component["attributes"]["value"] = str_replace($regs[0], $_REQUEST["fl_".str_replace("@", "", $regs[0])], $component["attributes"]["value"]);
							}
						}
						if($component["attributes"]){
							foreach($component["attributes"] as $nitem => $item){
								Generator::forms_print(" $nitem='$item' ");
							}
						}
						Generator::forms_print(" />\r\n");
						break;
						case "auto":
						if(isset($autoInc[$name])) $autoInc[$name]++; else $autoInc[$name] = 1;
						Generator::forms_print("<input type='hidden' name='fl_$name$i' id='flid_$name$i' value='".$autoInc[$name]."'");
						if($component["attributes"])
						foreach($component["attributes"] as $nitem => $item)
						Generator::forms_print(" $nitem='$item' ");
						Generator::forms_print(" />\r\n");
						break;
						case "combo":
						Generator::forms_print("<select name='fl_$name$i' id='flid_$name$i' disabled ");
						if($component["attributes"])
						foreach($component["attributes"] as $nitem => $item){
							if($nitem!='onchange')
							Generator::forms_print(" $nitem='$item' ");
						}
						if($component['checkUnique']) $ch = "checkUnique(\"$name\", this);";
						else $ch = "";
						$component['attributes']['onchange'] = str_replace("#?", $i, $component['attributes']['onchange']);
						$ch.=$component['attributes']['onchange'];
						Generator::forms_print(" onchange='saveValue(this);$ch;'>\r\n");
						if(!$component['noDefault']) Generator::forms_print("<option value='@'>Seleccione ...</option>\n");
						if($component['class']=='dynamic'){
							$db = db::raw_connect();
							if(!$component["orderBy"]) $ordb = $name; else $ordb = $component["orderBy"];
							if($component['whereCondition']) $where = "where ".$component['whereCondition']; else $where = "";
							if($component['column_relation']){
								$db->query("select ".$component['column_relation']." as $name, ".$component['detailField']." from ".$component['foreignTable']." $where order by $ordb");
							} else {
								$db->query("select $name, ".$component['detailField']." from ".$component['foreignTable']." $where order by $ordb");
							}
							while($row = $db->fetch_array())
							Generator::forms_print("<option value='".$row[0]."'>".$row[1]."\r\n");
						}
						if($component['class']=='static')
						foreach($component['items'] as $it)
						Generator::forms_print("<option value='".$it[0]."'>".$it[1]."\r\n");
						Generator::forms_print("</select>");
						break;
						case "button":
						Generator::forms_print("<input type='button' name='fl_$name$i' id='flid_$name$i' disabled ");
						if($component["attributes"])
						foreach($component["attributes"] as $nitem => $item)
						Generator::forms_print(" $nitem='$item' ");
						Generator::forms_print(" value='".$component['caption']."'");
						$component["onClick"].=" ";
						if($component["onClick"]){
							if(!isset($onclick)){
								$numVal = 0;
								$referencedValues = array();
								$onclick = "";
								for($x=0;$x<=strlen($component["onClick"])-1;$x++){
									$ch = substr($component["onClick"], $x, 1);
									if($ch=="@"){
										$x++;
										$ch = substr($component["onClick"], $x, 1);
										$onclick.="document.getElementById(\"flid_";
										while(ctype_alnum($ch)){
											$onclick.=$ch;
											$referencedValues[$numVal].=$ch;
											$x++;
											if($x>(strlen($component["onClick"])-1)) break 1;
											$ch = substr($component["onClick"], $x, 1);
										}
										$onclick.="[#]\").value$ch";
										$numVal++;
									} else $onclick.=$ch;
								}
								$referencedValues = array_unique($referencedValues);
								foreach($referencedValues as $rf)
								$onclick.="; saveValue(document.getElementById(\"flid_".$rf."[#]\"))";
							}
							$oonclick = str_replace("[#]", "$i", $onclick);
							$oonclick = str_replace("#?", "$i", $onclick);
							Generator::forms_print("onclick='$oonclick'");
						}
						Generator::forms_print(">");
						break;
					}
					Generator::forms_print("</td>\n");
				}
				//if(getBrowser()!="msie"){
				if(!$form['noExtendItems']) {
					if($i==0) Generator::forms_print("<td align='center'><img onselectstart='event.returnValue=false' style='cursor:pointer'
				onclick='goPrev()' 
				ondblclick='goFirst()'
				src='".KUMBIA_PATH."img/up.gif'></td>");
					else {

						if($i==($form['scrmax']-1)) Generator::forms_print("<td align='center'><img onselectstart='event.returnValue=false' style='cursor:pointer'
					onclick='goNext()' 
					ondblclick='goLast()' 
					src='".KUMBIA_PATH."img/down.gif'></td>");
					}
				}
				else {
					if(!$form['noExtendItems']) {
						if($i==($form['scrmax']-1)) Generator::forms_print("<td align='center'><img onselectstart='event.returnValue=false' style='cursor:pointer' onclick='loadValues(parseInt(document.getElementById(\"actmin\").value)+1, parseInt(document.getElementById(\"actmax\").value)+1)' src='".KUMBIA_PATH."img/down.gif'></td>");
					}
					else {
						if(!$form['noExtendItems']) {
							if($i==1) Generator::forms_print("<td align='center' style='font-family:Wingdings;cursor:pointer' align='center'></td></tr>\n");
						}
					}
				}			
				Generator::forms_print("</tr>");
			}
			Generator::forms_print("<tr>");
			Generator::forms_print("<script type='text/javascript'> loadValues(0, document.getElementById(\"scrmax\").value); </script></center>\r\n");
			
			if(count($dynamicImplicitValues)){
				Generator::forms_print("<script type='text/javascript'> calcDynamicValues(); </script>");
			}
			foreach($form['components'] as $name => $com){
				if($com['totalize']&&$com['valueType']=='numeric'){
					$index = getIndex($name, $form);
					Generator::forms_print("<td align='center'><b><span id='tot_$name'>0</span></b>
						 <script>totalizeColumn('$name', '$index')</script></td>");
				} else Generator::forms_print("<td></td>");
			}
			Generator::forms_print("</tr>");
			Generator::forms_print("</table></td><td><br>");

			Generator::forms_print("</td></table>\r\n");
			if($form['type']=='grid')
			Generator::forms_print("</form><form name='saveDataForm' action='#' method='post'></form>\r\n");


		}

	}
}
?>