<?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
require_once _LIBPATH . "library.php";
require_once _LIBPATH . "common.php";
require_once _LIBPATH . "template.php";
require_once _LIBPATH . "html.php";
require_once _LIBPATH . "config.php";
require_once _LIBPATH . "database.php";

//define ("_MSG_FORMS_UNCOMPLETE" , "Please fill in all required fields");
define ("_MSG_FORMS_UNCOMPLETE" , "Please verify if all mandatory fields are filled in correctly!");
define ("_MSG_FORMS_UNIQUE" , " already exists!");
define ("_MSG_FORMS_EXISTS" , " doesn't exists!");
define ("_MSG_FORMS_FILEEXISTS" , " doesn't exists!");
define ("_MSG_FORMS_WRONGSECURITY" , " Invalid security check!");


define ("_FORMS_SETTINGS_FIELD_IMAGE_UPLOAD" , "flash");			// html for standard html upload or flash for flash widget


define("_FORMS_ERROR_FILL" , "1");
define("_FORMS_ERROR_UNIQUE" , "2");
define("_FORMS_ERROR_CHECK" , "3");
define("_FORMS_ERROR_FILE" , "4");
define("_FORMS_ERROR_CONFIRM" , "5");
define("_FORMS_ERROR_EXISTS" , "6"); //not implemented yet, the opposite of unique=true

$form_months = array (1 => "January" , "February" , "March" , "April" , "May" , "June" , "July" , "August" , "September" , "October" , "November" , "December");
$form_months_ro = array (1 => "Ianuarie" , "Februarie" , "Martie" , "Aprilie" , "Mai" , "Iunie" , "Iulie" , "August" , "Septembrie" , "Octombrie" , "Noiembrie" , "Decembrie");

$form_days = array (0 => "Sunday" , "Monday" , "Tuesday" , "Wensday" , "Thursday" , "Friday" , "Saturday");

$form_errors = array(
						"NO_BACK_LINK" => "javascript:alert('No previous link detected');"
					 );

$form_RO_states = array(
							"AB" => "Alba",
							"AR" => "Arad",
							"AG" => "Arges",
							"BC" => "Bacau",
							"BH" => "Bihor",
							"BN" => "Bistrita-Nasaud",
							"BT" => "Botosani",
							"BR" => "Braila",
							"BV" => "Brasov",
							"B" => "Bucuresti",
							"BZ" => "Buzau",
							"CL" => "Calarasi",
							"CS" => "Caras Severin",
							"CJ" => "Cluj",
							"CT" => "Constanta",
							"CV" => "Covasna",
							"DB" => "Dambovita",
							"DJ" => "Dolj",
							"GL" => "Galati",
							"GR" => "Giurgiu",
							"GJ" => "Gorj",
							"HG" => "Harghita",
							"HD" => "Hunedoara",
							"IL" => "Ialomita",
							"IS" => "Iasi",
							"IF" => "Ilfov",
							"MM" => "Maramures",
							"MH" => "Mehedinti",
							"MR" => "Mures",
							"NT" => "Neamt",
							"OT" => "Olt",
							"PH" => "Prahova",
							"SJ" => "Salaj",
							"SM" => "Satu Mare",
							"SB" => "Sibiu",
							"SV" => "Suceava",
							"TE" => "Teleorman",
							"TM" => "Timis",
							"TL" => "Tulcea",
							"VL" => "Valcea",
							"VS" => "Vaslui",
							"VN" => "Vrancea"
						);

$form_CA_states = array(
							"Alberta" => "Alberta",
							"British" => "British",
							"Manitoba" => "Manitoba",
							"New Brunswick" => "New Brunswick",
							"Newfoundland" => "Newfoundland",
							"Northwest Territories" => "Northwest Territories",
							"Nova Scotia" => "Nova Scotia",
							"Nunavut" => "Nunavut",
							"Ontario" => "Ontario",
							"Prince Edward Island" => "Prince Edward Island",
							"Quebec" => "Quebec",
							"Saskatchewan" => "Saskatchewan",
							"Yukon" => "Yukon"
					);

$form_US_states = array (
							"AL" => "Alabama",
							"AK" => "Alaska",
							"AZ" => "Arizona",
							"AR" => "Arkansas",
							"CA" => "California",
							"CO" => "Colorado",
							"CT" => "Connecticut",
							"DE" => "Delaware",
							"DC" => "Dist. of Columbia",
							"FL" => "Florida",
							"GA" => "Georgia",
							"HI" => "Hawaii",
							"ID" => "Idaho",
							"IL" => "Illinois",
							"IN" => "Indiana",
							"IA" => "Iowa",
							"KS" => "Kansas",
							"KY" => "Kentucky",
							"LA" => "Louisiana",
							"ME" => "Maine",
							"MD" => "Maryland",
							"MA" => "Massachusetts",
							"MI" => "Michigan",
							"MN" => "Minnesota",
							"MS" => "Mississippi",
							"MO" => "Missouri",
							"MT" => "Montana",
							"NE" => "Nebraska",
							"NV" => "Nevada",
							"NH" => "New Hampshire",
							"NJ" => "New Jersey",
							"NM" => "New Mexico",
							"NY" => "New York",
							"NC" => "North Carolina",
							"ND" => "North Dakota",
							"OH" => "Ohio",
							"OK" => "Oklahoma",
							"OR" => "Oregon",
							"PA" => "Pennsylvania",
							"PR" => "Puerto Rico",
							"RI" => "Rhode Island",
							"SC" => "South Carolina",
							"SD" => "South Dakota",
							"TN" => "Tennessee",
							"TX" => "Texas",
							"UT" => "Utah",
							"VT" => "Vermont",
							"VA" => "Virginia",
							"WA" => "Washington",
							"WV" => "West Virginia",
							"WI" => "Wisconsin",
							"WY" => "Wyoming"
						);


$form_languages = array(
							"ab" => "Abkhazian", 
							"aa" => "Afar", 
							"af" => "Afrikaans", 
							"sq" => "Albanian", 
							"am" => "Amharic", 
							"ar" => "Arabic", 
							"hy" => "Armenian", 
							"as" => "Assamese", 
							"ay" => "Aymara", 
							"az" => "Azerbaijani", 
							"ba" => "Bashkir", 
							"eu" => "Basque", 
							"bn" => "Bengali, Bangla", 
							"dz" => "Bhutani", 
							"bh" => "Bihari", 
							"bi" => "Bislama", 
							"br" => "Breton", 
							"bg" => "Bulgarian", 
							"my" => "Burmese", 
							"be" => "Byelorussian", 
							"km" => "Cambodian", 
							"ca" => "Catalan", 
							"zh" => "Chinese", 
							"co" => "Corsican", 
							"hr" => "Croatian", 
							"cs" => "Czech", 
							"da" => "Danish", 
							"nl" => "Dutch", 
							"en" => "English", 
//							"en" => "English, United States", 
//							"gb" => "English, United Kingdom", 
							"eo" => "Esperanto", 
							"et" => "Estonian", 
							"fo" => "Faeroese", 
							"fj" => "Fiji", 
							"fi" => "Finnish", 
							"fr" => "French", 
							"fy" => "Frisian", 
							"gd" => "Gaelic (Scots Gaelic)", 
							"gl" => "Galician", 
							"ka" => "Georgian", 
							"de" => "German", 
							"el" => "Greek", 
							"kl" => "Greenlandic", 
							"gn" => "Guarani", 
							"gu" => "Gujarati", 
							"ha" => "Hausa", 
							"iw" => "Hebrew", 
							"hi" => "Hindi", 
							"hu" => "Hungarian", 
							"is" => "Icelandic", 
							"in" => "Indonesian", 
							"ia" => "Interlingua", 
							"ie" => "Interlingue", 
							"ik" => "Inupiak", 
							"ga" => "Irish", 
							"it" => "Italian", 
							"ja" => "Japanese", 
							"jw" => "Javanese", 
							"kn" => "Kannada", 
							"ks" => "Kashmiri", 
							"kk" => "Kazakh", 
							"rw" => "Kinyarwanda", 
							"ky" => "Kirghiz", 
							"rn" => "Kirundi", 
							"ko" => "Korean", 
							"ku" => "Kurdish", 
							"lo" => "Laothian", 
							"la" => "Latin", 
							"lv" => "Latvian, Lettish", 
							"ln" => "Lingala", 
							"lt" => "Lithuanian", 
							"mk" => "Macedonian", 
							"mg" => "Malagasy", 
							"ms" => "Malay", 
							"ml" => "Malayalam", 
							"mt" => "Maltese", 
							"mi" => "Maori", 
							"mr" => "Marathi", 
							"mo" => "Moldavian", 
							"mn" => "Mongolian", 
							"na" => "Nauru", 
							"ne" => "Nepali", 
							"no" => "Norwegian", 
							"oc" => "Occitan", 
							"or" => "Oriya", 
							"om" => "Oromo, Afan", 
							"ps" => "Pashto, Pushto", 
							"fa" => "Persian", 
							"pl" => "Polish", 
							"pt" => "Portuguese", 
							"pa" => "Punjabi", 
							"qu" => "Quechua", 
							"rm" => "Rhaeto-Romance", 
							"ro" => "Romanian", 
							"ru" => "Russian", 
							"sm" => "Samoan", 
							"sg" => "Sangro", 
							"sa" => "Sanskrit", 
							"sr" => "Serbian", 
							"sh" => "Serbo-Croatian", 
							"st" => "Sesotho", 
							"tn" => "Setswana", 
							"sn" => "Shona", 
							"sd" => "Sindhi", 
							"si" => "Singhalese", 
							"ss" => "Siswati", 
							"sk" => "Slovak", 
							"sl" => "Slovenian", 
							"so" => "Somali", 
							"es" => "Spanish", 
							"su" => "Sudanese", 
							"sw" => "Swahili", 
							"sv" => "Swedish", 
							"tl" => "Tagalog", 
							"tg" => "Tajik", 
							"ta" => "Tamil", 
							"tt" => "Tatar", 
							"te" => "Tegulu", 
							"th" => "Thai", 
							"bo" => "Tibetan", 
							"ti" => "Tigrinya", 
							"to" => "Tonga", 
							"ts" => "Tsonga", 
							"tr" => "Turkish", 
							"tk" => "Turkmen", 
							"tw" => "Twi", 
							"uk" => "Ukrainian", 
							"ur" => "Urdu", 
							"uz" => "Uzbek", 
							"vi" => "Vietnamese", 
							"vo" => "Volapuk", 
							"cy" => "Welsh", 
							"wo" => "Wolof", 
							"xh" => "Xhosa", 
							"ji" => "Yiddish", 
							"yo" => "Yoruba", 
							"zu" => "Zulu"
);

$form_countries = array(
							"af" => "Afghanistan",
							"al" => "Albania",
							"dz" => "Algeria",
							"as" => "American Samoa",
							"ad" => "Andorra",
							"ao" => "Angola",
							"ag" => "Antiqua and Barbuda",
							"am" => "Armenia",
							"ar" => "Argentina",
							"au" => "Australia",
							"at" => "Austria",
							"az" => "Azerbaijan",
							"bs" => "Bahamas, The",
							"bh" => "Bahrain",
							"bd" => "Bangladesh",
							"bb" => "Barbados",
							"by" => "Belarus",
							"be" => "Belgium",
							"bz" => "Belize",
							"bj" => "Benin",
							"bm" => "Bermuda",
							"bt" => "Bhutan",
							"bo" => "Bolivia",
							"bw" => "Botswana",
							"bv" => "Bouvet Island",
							"br" => "Brazil",
							"io" => "British Indian Ocean Territory",
							"sb" => "British Solomon Islands",
							"vg" => "British Virgin Islands",
							"bn" => "Brunei",
							"bg" => "Bulgaria",
							"mm" => "Burma",
							"bi" => "Burundi",
							"kh" => "Cambodia",
							"cm" => "Cameroon",
							"ca" => "Canada",
							"cv" => "Cape Verde Islands",
							"ky" => "Cayman Islands",
							"cf" => "Central African Republic",
							"td" => "Chad",
							"cl" => "Chile",
							"cn" => "China, People's Republic of",
							"cx" => "Christmas Island",
							"cc" => "Cocos (Keeling) Islands",
							"co" => "Colombia",
							"km" => "Comoro Islands",
							"cg" => "Congo",
							"ck" => "Cook Islands",
							"cr" => "Costa Rica",
							"hr" => "Croatia",
							"cu" => "Cuba",
							"cy" => "Cyprus",
							"cz" => "Czech Republic",
							"dk" => "Denmark",
							"dj" => "Djibouti",
							"dm" => "Dominica",
							"do" => "Dominican Republic",
							"ec" => "Ecuador",
							"eg" => "Egypt",
							"sv" => "El Salvador",
							"gq" => "Equitorial Guinea",
							"er" => "Eritrea",
							"ee" => "Estonia",
							"et" => "Ethiopia",
							"fo" => "Faeroe Islands",
							"fk" => "Falkland Islands (Malvinas)",
							"fj" => "Fiji",
							"fi" => "Finland",
							"fr" => "France",
							"pf" => "French Polynesia",
							"ai" => "French Afars and Issas",
							"ga" => "Gabon",
							"gm" => "Gambia",
							"ge" => "Georgia",
							"de" => "Germany",
							"gh" => "Ghana",
							"gi" => "Gibraltar",
							"gr" => "Greece",
							"gl" => "Greenland",
							"gd" => "Grenada",
							"gp" => "Guadeloupe",
							"gu" => "Guam",
							"gt" => "Guatemala",
							"gn" => "Guinea",
							"gw" => "Guinea Bissaw",
							"gy" => "Guyana",
							"ht" => "Haiti",
							"hn" => "Honduras",
							"hk" => "Hong Kong",
							"hu" => "Hungary",
							"is" => "Iceland",
							"in" => "India",
							"id" => "Indonesia",
							"ir" => "Iran",
							"iq" => "Iraq",
							"ie" => "Ireland",
							"ps" => "Palestine",
							"it" => "Italy",
							"ci" => "Ivory Coast",
							"jm" => "Jamaica",
							"jp" => "Japan",
							"jo" => "Jordan",
							"kz" => "Kazakhstan",
							"ke" => "Kenya",
							"kh" => "Khmer Republic",
							"kp" => "Korea, Democratic People's Republic of",
							"kr" => "Korea, Republic of",
							"kw" => "Kuwait",
							"kg" => "Kyrgystan",
							"la" => "Laos",
							"lv" => "Latvia",
							"lb" => "Lebanon",
							"ls" => "Lesotho",
							"lr" => "Liberia",
							"ly" => "Libya",
							"li" => "Liechtenstein",
							"lt" => "Lithuania",
							"lu" => "Luxembourg",
							"mo" => "Macao",
							"mg" => "Madagascar",
							"mw" => "Malawi",
							"my" => "Malaysia",
							"mv" => "Maldives",
							"ml" => "Mali",
							"mt" => "Malta",
							"mh" => "Marshall Islands",
							"mq" => "Martinique",
							"mr" => "Mauritania",
							"mu" => "Mauritius",
							"mx" => "Mexico",
							"fm" => "Micronesia",
							"md" => "Moldova",
							"mc" => "Monaco",
							"mn" => "Mongolia",
							"ms" => "Montserrat",
							"ma" => "Morocco",
							"mz" => "Mozambique",
							"mm" => "Myanmar (formerly Burma)",
							"na" => "Namibia",
							"nr" => "Nauru",
							"np" => "Nepal",
							"nl" => "Netherlands",
							"an" => "Netherlands Antilles",
							"nc" => "New Caledonia",
							"nz" => "New Zealand",
							"ni" => "Nicaragua",
							"ne" => "Niger",
							"ng" => "Nigeria",
							"nu" => "Niue Island",
							"nf" => "Norfolk Island",
							"no" => "Norway",
							"om" => "Oman",
							"pk" => "Pakistan",
							"pw" => "Palau",
							"pa" => "Panama",
							"pg" => "Papua New Guinea",
							"py" => "Paraguay",
							"pe" => "Peru",
							"ph" => "Philippines",
							"pn" => "Pitcairn Islands",
							"pl" => "Poland",
							"pt" => "Portugal",
							"pr" => "Puerto Rico",
							"qa" => "Qatar",
							"ro" => "Romania",
							"ru" => "Russia",
							"rw" => "Rwanda",
							"sh" => "St. Helena",
							"kn" => "St. Kitts-Nevis-Anguilla",
							"lc" => "St. Lucia",
							"pm" => "St. Pierre and Miquelon",
							"vc" => "St. Vincent",
							"sm" => "San Marino",
							"st" => "Sao Tome and Principe",
							"sa" => "Saudi Arabia",
							"sn" => "Senegal",
							"sc" => "Seychelles",
							"sl" => "Sierra Leone",
							"sg" => "Singapore",
							"sk" => "Slovakia",
							"si" => "Slovenia",
							"so" => "Somalia",
							"za" => "South Africa, Republic of",
							"es" => "Spain",
							"eh" => "Spanish Sahara",
							"lk" => "Sri Lanka",
							"sd" => "Sudan",
							"sr" => "Suriname",
							"sz" => "Swaziland",
							"se" => "Sweden",
							"ch" => "Switzerland",
							"sy" => "Syria",
							"tw" => "Taiwan",
							"tj" => "Tajikistan",
							"tz" => "Tanzania",
							"th" => "Thailand",
							"tg" => "Togo",
							"tk" => "Tokelau Island",
							"to" => "Tonga",
							"tt" => "Trinidad and Tobago",
							"tn" => "Tunisia",
							"tr" => "Turkey",
							"tm" => "Turkmenistan",
							"tc" => "Turks and Caicos Islands",
							"tv" => "Tuvalu",
							"ug" => "Uganda",
							"ua" => "Ukraine",
							"ae" => "United Arab Emirates",
							"gb" => "United Kingdom",
							"us" => "United States",
							"vi" => "U.S. Virgin Islands",
							"uy" => "Uruguay",
							"uz" => "Uzbekistan",
							"vu" => "Vanuatu",
							"va" => "Vatican City State (The Holy See)",
							"ve" => "Venezuela",
							"vn" => "Vietnam",
							"wf" => "Wallis and Futuna Islands",
							"ws" => "Western Samoa",
							"ye" => "Yemen",
							"zm" => "Zambia",
							"zw" => "Zimbabwe"
						);

$form_timezones = array(

	"Africa/Abidjan" => "Africa/Abidjan",
	"Africa/Accra" => "Africa/Accra",
	"Africa/Addis_Ababa" => "Africa/Addis_Ababa",
	"Africa/Algiers" => "Africa/Algiers",
	"Africa/Asmara" => "Africa/Asmara",
	"Africa/Bamako" => "Africa/Bamako",
	"Africa/Bangui" => "Africa/Bangui",
	"Africa/Banjul" => "Africa/Banjul",
	"Africa/Bissau" => "Africa/Bissau",
	"Africa/Blantyre" => "Africa/Blantyre",
	"Africa/Brazzaville" => "Africa/Brazzaville",
	"Africa/Bujumbura" => "Africa/Bujumbura",
	"Africa/Cairo" => "Africa/Cairo",
	"Africa/Casablanca" => "Africa/Casablanca",
	"Africa/Ceuta" => "Africa/Ceuta",
	"Africa/Conakry" => "Africa/Conakry",
	"Africa/Dakar" => "Africa/Dakar",
	"Africa/Dar_es_Salaam" => "Africa/Dar_es_Salaam",
	"Africa/Djibouti" => "Africa/Djibouti",
	"Africa/Douala" => "Africa/Douala",
	"Africa/El_Aaiun" => "Africa/El_Aaiun",
	"Africa/Freetown" => "Africa/Freetown",
	"Africa/Gaborone" => "Africa/Gaborone",
	"Africa/Harare" => "Africa/Harare",
	"Africa/Johannesburg" => "Africa/Johannesburg",
	"Africa/Juba" => "Africa/Juba",
	"Africa/Kampala" => "Africa/Kampala",
	"Africa/Khartoum" => "Africa/Khartoum",
	"Africa/Kigali" => "Africa/Kigali",
	"Africa/Kinshasa" => "Africa/Kinshasa",
	"Africa/Lagos" => "Africa/Lagos",
	"Africa/Libreville" => "Africa/Libreville",
	"Africa/Lome" => "Africa/Lome",
	"Africa/Luanda" => "Africa/Luanda",
	"Africa/Lubumbashi" => "Africa/Lubumbashi",
	"Africa/Lusaka" => "Africa/Lusaka",
	"Africa/Malabo" => "Africa/Malabo",
	"Africa/Maputo" => "Africa/Maputo",
	"Africa/Maseru" => "Africa/Maseru",
	"Africa/Mbabane" => "Africa/Mbabane",
	"Africa/Mogadishu" => "Africa/Mogadishu",
	"Africa/Monrovia" => "Africa/Monrovia",
	"Africa/Nairobi" => "Africa/Nairobi",
	"Africa/Ndjamena" => "Africa/Ndjamena",
	"Africa/Niamey" => "Africa/Niamey",
	"Africa/Nouakchott" => "Africa/Nouakchott",
	"Africa/Ouagadougou" => "Africa/Ouagadougou",
	"Africa/Porto-Novo" => "Africa/Porto-Novo",
	"Africa/Sao_Tome" => "Africa/Sao_Tome",
	"Africa/Tripoli" => "Africa/Tripoli",
	"Africa/Tunis" => "Africa/Tunis",
	"Africa/Windhoek" => "Africa/Windhoek",
	"America/Adak" => "America/Adak",
	"America/Anchorage" => "America/Anchorage",
	"America/Anguilla" => "America/Anguilla",
	"America/Antigua" => "America/Antigua",
	"America/Araguaina" => "America/Araguaina",
	"America/Argentina/Buenos_Aires" => "America/Argentina/Buenos_Aires",
	"America/Argentina/Catamarca" => "America/Argentina/Catamarca",
	"America/Argentina/Cordoba" => "America/Argentina/Cordoba",
	"America/Argentina/Jujuy" => "America/Argentina/Jujuy",
	"America/Argentina/La_Rioja" => "America/Argentina/La_Rioja",
	"America/Argentina/Mendoza" => "America/Argentina/Mendoza",
	"America/Argentina/Rio_Gallegos" => "America/Argentina/Rio_Gallegos",
	"America/Argentina/Salta" => "America/Argentina/Salta",
	"America/Argentina/San_Juan" => "America/Argentina/San_Juan",
	"America/Argentina/San_Luis" => "America/Argentina/San_Luis",
	"America/Argentina/Tucuman" => "America/Argentina/Tucuman",
	"America/Argentina/Ushuaia" => "America/Argentina/Ushuaia",
	"America/Aruba" => "America/Aruba",
	"America/Asuncion" => "America/Asuncion",
	"America/Atikokan" => "America/Atikokan",
	"America/Bahia" => "America/Bahia",
	"America/Bahia_Banderas" => "America/Bahia_Banderas",
	"America/Barbados" => "America/Barbados",
	"America/Belem" => "America/Belem",
	"America/Belize" => "America/Belize",
	"America/Blanc-Sablon" => "America/Blanc-Sablon",
	"America/Boa_Vista" => "America/Boa_Vista",
	"America/Bogota" => "America/Bogota",
	"America/Boise" => "America/Boise",
	"America/Cambridge_Bay" => "America/Cambridge_Bay",
	"America/Campo_Grande" => "America/Campo_Grande",
	"America/Cancun" => "America/Cancun",
	"America/Caracas" => "America/Caracas",
	"America/Cayenne" => "America/Cayenne",
	"America/Cayman" => "America/Cayman",
	"America/Chicago" => "America/Chicago",
	"America/Chihuahua" => "America/Chihuahua",
	"America/Costa_Rica" => "America/Costa_Rica",
	"America/Creston" => "America/Creston",
	"America/Cuiaba" => "America/Cuiaba",
	"America/Curacao" => "America/Curacao",
	"America/Danmarkshavn" => "America/Danmarkshavn",
	"America/Dawson" => "America/Dawson",
	"America/Dawson_Creek" => "America/Dawson_Creek",
	"America/Denver" => "America/Denver",
	"America/Detroit" => "America/Detroit",
	"America/Dominica" => "America/Dominica",
	"America/Edmonton" => "America/Edmonton",
	"America/Eirunepe" => "America/Eirunepe",
	"America/El_Salvador" => "America/El_Salvador",
	"America/Fortaleza" => "America/Fortaleza",
	"America/Glace_Bay" => "America/Glace_Bay",
	"America/Godthab" => "America/Godthab",
	"America/Goose_Bay" => "America/Goose_Bay",
	"America/Grand_Turk" => "America/Grand_Turk",
	"America/Grenada" => "America/Grenada",
	"America/Guadeloupe" => "America/Guadeloupe",
	"America/Guatemala" => "America/Guatemala",
	"America/Guayaquil" => "America/Guayaquil",
	"America/Guyana" => "America/Guyana",
	"America/Halifax" => "America/Halifax",
	"America/Havana" => "America/Havana",
	"America/Hermosillo" => "America/Hermosillo",
	"America/Indiana/Indianapolis" => "America/Indiana/Indianapolis",
	"America/Indiana/Knox" => "America/Indiana/Knox",
	"America/Indiana/Marengo" => "America/Indiana/Marengo",
	"America/Indiana/Petersburg" => "America/Indiana/Petersburg",
	"America/Indiana/Tell_City" => "America/Indiana/Tell_City",
	"America/Indiana/Vevay" => "America/Indiana/Vevay",
	"America/Indiana/Vincennes" => "America/Indiana/Vincennes",
	"America/Indiana/Winamac" => "America/Indiana/Winamac",
	"America/Inuvik" => "America/Inuvik",
	"America/Iqaluit" => "America/Iqaluit",
	"America/Jamaica" => "America/Jamaica",
	"America/Juneau" => "America/Juneau",
	"America/Kentucky/Louisville" => "America/Kentucky/Louisville",
	"America/Kentucky/Monticello" => "America/Kentucky/Monticello",
	"America/Kralendijk" => "America/Kralendijk",
	"America/La_Paz" => "America/La_Paz",
	"America/Lima" => "America/Lima",
	"America/Los_Angeles" => "America/Los_Angeles",
	"America/Lower_Princes" => "America/Lower_Princes",
	"America/Maceio" => "America/Maceio",
	"America/Managua" => "America/Managua",
	"America/Manaus" => "America/Manaus",
	"America/Marigot" => "America/Marigot",
	"America/Martinique" => "America/Martinique",
	"America/Matamoros" => "America/Matamoros",
	"America/Mazatlan" => "America/Mazatlan",
	"America/Menominee" => "America/Menominee",
	"America/Merida" => "America/Merida",
	"America/Metlakatla" => "America/Metlakatla",
	"America/Mexico_City" => "America/Mexico_City",
	"America/Miquelon" => "America/Miquelon",
	"America/Moncton" => "America/Moncton",
	"America/Monterrey" => "America/Monterrey",
	"America/Montevideo" => "America/Montevideo",
	"America/Montreal" => "America/Montreal",
	"America/Montserrat" => "America/Montserrat",
	"America/Nassau" => "America/Nassau",
	"America/New_York" => "America/New_York",
	"America/Nipigon" => "America/Nipigon",
	"America/Nome" => "America/Nome",
	"America/Noronha" => "America/Noronha",
	"America/North_Dakota/Beulah" => "America/North_Dakota/Beulah",
	"America/North_Dakota/Center" => "America/North_Dakota/Center",
	"America/North_Dakota/New_Salem" => "America/North_Dakota/New_Salem",
	"America/Ojinaga" => "America/Ojinaga",
	"America/Panama" => "America/Panama",
	"America/Pangnirtung" => "America/Pangnirtung",
	"America/Paramaribo" => "America/Paramaribo",
	"America/Phoenix" => "America/Phoenix",
	"America/Port-au-Prince" => "America/Port-au-Prince",
	"America/Port_of_Spain" => "America/Port_of_Spain",
	"America/Porto_Velho" => "America/Porto_Velho",
	"America/Puerto_Rico" => "America/Puerto_Rico",
	"America/Rainy_River" => "America/Rainy_River",
	"America/Rankin_Inlet" => "America/Rankin_Inlet",
	"America/Recife" => "America/Recife",
	"America/Regina" => "America/Regina",
	"America/Resolute" => "America/Resolute",
	"America/Rio_Branco" => "America/Rio_Branco",
	"America/Santa_Isabel" => "America/Santa_Isabel",
	"America/Santarem" => "America/Santarem",
	"America/Santiago" => "America/Santiago",
	"America/Santo_Domingo" => "America/Santo_Domingo",
	"America/Sao_Paulo" => "America/Sao_Paulo",
	"America/Scoresbysund" => "America/Scoresbysund",
	"America/Shiprock" => "America/Shiprock",
	"America/Sitka" => "America/Sitka",
	"America/St_Barthelemy" => "America/St_Barthelemy",
	"America/St_Johns" => "America/St_Johns",
	"America/St_Kitts" => "America/St_Kitts",
	"America/St_Lucia" => "America/St_Lucia",
	"America/St_Thomas" => "America/St_Thomas",
	"America/St_Vincent" => "America/St_Vincent",
	"America/Swift_Current" => "America/Swift_Current",
	"America/Tegucigalpa" => "America/Tegucigalpa",
	"America/Thule" => "America/Thule",
	"America/Thunder_Bay" => "America/Thunder_Bay",
	"America/Tijuana" => "America/Tijuana",
	"America/Toronto" => "America/Toronto",
	"America/Tortola" => "America/Tortola",
	"America/Vancouver" => "America/Vancouver",
	"America/Whitehorse" => "America/Whitehorse",
	"America/Winnipeg" => "America/Winnipeg",
	"America/Yakutat" => "America/Yakutat",
	"America/Yellowknife" => "America/Yellowknife",
	"Antarctica/Casey" => "Antarctica/Casey",
	"Antarctica/Davis" => "Antarctica/Davis",
	"Antarctica/DumontDUrville" => "Antarctica/DumontDUrville",
	"Antarctica/Macquarie" => "Antarctica/Macquarie",
	"Antarctica/Mawson" => "Antarctica/Mawson",
	"Antarctica/McMurdo" => "Antarctica/McMurdo",
	"Antarctica/Palmer" => "Antarctica/Palmer",
	"Antarctica/Rothera" => "Antarctica/Rothera",
	"Antarctica/South_Pole" => "Antarctica/South_Pole",
	"Antarctica/Syowa" => "Antarctica/Syowa",
	"Antarctica/Vostok" => "Antarctica/Vostok",
	"Arctic/Longyearbyen" => "Arctic/Longyearbyen",
	"Asia/Aden" => "Asia/Aden",
	"Asia/Almaty" => "Asia/Almaty",
	"Asia/Amman" => "Asia/Amman",
	"Asia/Anadyr" => "Asia/Anadyr",
	"Asia/Aqtau" => "Asia/Aqtau",
	"Asia/Aqtobe" => "Asia/Aqtobe",
	"Asia/Ashgabat" => "Asia/Ashgabat",
	"Asia/Baghdad" => "Asia/Baghdad",
	"Asia/Bahrain" => "Asia/Bahrain",
	"Asia/Baku" => "Asia/Baku",
	"Asia/Bangkok" => "Asia/Bangkok",
	"Asia/Beirut" => "Asia/Beirut",
	"Asia/Bishkek" => "Asia/Bishkek",
	"Asia/Brunei" => "Asia/Brunei",
	"Asia/Choibalsan" => "Asia/Choibalsan",
	"Asia/Chongqing" => "Asia/Chongqing",
	"Asia/Colombo" => "Asia/Colombo",
	"Asia/Damascus" => "Asia/Damascus",
	"Asia/Dhaka" => "Asia/Dhaka",
	"Asia/Dili" => "Asia/Dili",
	"Asia/Dubai" => "Asia/Dubai",
	"Asia/Dushanbe" => "Asia/Dushanbe",
	"Asia/Gaza" => "Asia/Gaza",
	"Asia/Harbin" => "Asia/Harbin",
	"Asia/Hebron" => "Asia/Hebron",
	"Asia/Ho_Chi_Minh" => "Asia/Ho_Chi_Minh",
	"Asia/Hong_Kong" => "Asia/Hong_Kong",
	"Asia/Hovd" => "Asia/Hovd",
	"Asia/Irkutsk" => "Asia/Irkutsk",
	"Asia/Jakarta" => "Asia/Jakarta",
	"Asia/Jayapura" => "Asia/Jayapura",
	"Asia/Jerusalem" => "Asia/Jerusalem",
	"Asia/Kabul" => "Asia/Kabul",
	"Asia/Kamchatka" => "Asia/Kamchatka",
	"Asia/Karachi" => "Asia/Karachi",
	"Asia/Kashgar" => "Asia/Kashgar",
	"Asia/Kathmandu" => "Asia/Kathmandu",
	"Asia/Khandyga" => "Asia/Khandyga",
	"Asia/Kolkata" => "Asia/Kolkata",
	"Asia/Krasnoyarsk" => "Asia/Krasnoyarsk",
	"Asia/Kuala_Lumpur" => "Asia/Kuala_Lumpur",
	"Asia/Kuching" => "Asia/Kuching",
	"Asia/Kuwait" => "Asia/Kuwait",
	"Asia/Macau" => "Asia/Macau",
	"Asia/Magadan" => "Asia/Magadan",
	"Asia/Makassar" => "Asia/Makassar",
	"Asia/Manila" => "Asia/Manila",
	"Asia/Muscat" => "Asia/Muscat",
	"Asia/Nicosia" => "Asia/Nicosia",
	"Asia/Novokuznetsk" => "Asia/Novokuznetsk",
	"Asia/Novosibirsk" => "Asia/Novosibirsk",
	"Asia/Omsk" => "Asia/Omsk",
	"Asia/Oral" => "Asia/Oral",
	"Asia/Phnom_Penh" => "Asia/Phnom_Penh",
	"Asia/Pontianak" => "Asia/Pontianak",
	"Asia/Pyongyang" => "Asia/Pyongyang",
	"Asia/Qatar" => "Asia/Qatar",
	"Asia/Qyzylorda" => "Asia/Qyzylorda",
	"Asia/Rangoon" => "Asia/Rangoon",
	"Asia/Riyadh" => "Asia/Riyadh",
	"Asia/Sakhalin" => "Asia/Sakhalin",
	"Asia/Samarkand" => "Asia/Samarkand",
	"Asia/Seoul" => "Asia/Seoul",
	"Asia/Shanghai" => "Asia/Shanghai",
	"Asia/Singapore" => "Asia/Singapore",
	"Asia/Taipei" => "Asia/Taipei",
	"Asia/Tashkent" => "Asia/Tashkent",
	"Asia/Tbilisi" => "Asia/Tbilisi",
	"Asia/Tehran" => "Asia/Tehran",
	"Asia/Thimphu" => "Asia/Thimphu",
	"Asia/Tokyo" => "Asia/Tokyo",
	"Asia/Ulaanbaatar" => "Asia/Ulaanbaatar",
	"Asia/Urumqi" => "Asia/Urumqi",
	"Asia/Ust-Nera" => "Asia/Ust-Nera",
	"Asia/Vientiane" => "Asia/Vientiane",
	"Asia/Vladivostok" => "Asia/Vladivostok",
	"Asia/Yakutsk" => "Asia/Yakutsk",
	"Asia/Yekaterinburg" => "Asia/Yekaterinburg",
	"Asia/Yerevan" => "Asia/Yerevan",
	"Atlantic/Azores" => "Atlantic/Azores",
	"Atlantic/Bermuda" => "Atlantic/Bermuda",
	"Atlantic/Canary" => "Atlantic/Canary",
	"Atlantic/Cape_Verde" => "Atlantic/Cape_Verde",
	"Atlantic/Faroe" => "Atlantic/Faroe",
	"Atlantic/Madeira" => "Atlantic/Madeira",
	"Atlantic/Reykjavik" => "Atlantic/Reykjavik",
	"Atlantic/South_Georgia" => "Atlantic/South_Georgia",
	"Atlantic/St_Helena" => "Atlantic/St_Helena",
	"Atlantic/Stanley" => "Atlantic/Stanley",
	"Australia/Adelaide" => "Australia/Adelaide",
	"Australia/Brisbane" => "Australia/Brisbane",
	"Australia/Broken_Hill" => "Australia/Broken_Hill",
	"Australia/Currie" => "Australia/Currie",
	"Australia/Darwin" => "Australia/Darwin",
	"Australia/Eucla" => "Australia/Eucla",
	"Australia/Hobart" => "Australia/Hobart",
	"Australia/Lindeman" => "Australia/Lindeman",
	"Australia/Lord_Howe" => "Australia/Lord_Howe",
	"Australia/Melbourne" => "Australia/Melbourne",
	"Australia/Perth" => "Australia/Perth",
	"Australia/Sydney" => "Australia/Sydney",
	"Europe/Amsterdam" => "Europe/Amsterdam",
	"Europe/Andorra" => "Europe/Andorra",
	"Europe/Athens" => "Europe/Athens",
	"Europe/Belgrade" => "Europe/Belgrade",
	"Europe/Berlin" => "Europe/Berlin",
	"Europe/Bratislava" => "Europe/Bratislava",
	"Europe/Brussels" => "Europe/Brussels",
	"Europe/Bucharest" => "Europe/Bucharest",
	"Europe/Budapest" => "Europe/Budapest",
	"Europe/Busingen" => "Europe/Busingen",
	"Europe/Chisinau" => "Europe/Chisinau",
	"Europe/Copenhagen" => "Europe/Copenhagen",
	"Europe/Dublin" => "Europe/Dublin",
	"Europe/Gibraltar" => "Europe/Gibraltar",
	"Europe/Guernsey" => "Europe/Guernsey",
	"Europe/Helsinki" => "Europe/Helsinki",
	"Europe/Isle_of_Man" => "Europe/Isle_of_Man",
	"Europe/Istanbul" => "Europe/Istanbul",
	"Europe/Jersey" => "Europe/Jersey",
	"Europe/Kaliningrad" => "Europe/Kaliningrad",
	"Europe/Kiev" => "Europe/Kiev",
	"Europe/Lisbon" => "Europe/Lisbon",
	"Europe/Ljubljana" => "Europe/Ljubljana",
	"Europe/London" => "Europe/London",
	"Europe/Luxembourg" => "Europe/Luxembourg",
	"Europe/Madrid" => "Europe/Madrid",
	"Europe/Malta" => "Europe/Malta",
	"Europe/Mariehamn" => "Europe/Mariehamn",
	"Europe/Minsk" => "Europe/Minsk",
	"Europe/Monaco" => "Europe/Monaco",
	"Europe/Moscow" => "Europe/Moscow",
	"Europe/Oslo" => "Europe/Oslo",
	"Europe/Paris" => "Europe/Paris",
	"Europe/Podgorica" => "Europe/Podgorica",
	"Europe/Prague" => "Europe/Prague",
	"Europe/Riga" => "Europe/Riga",
	"Europe/Rome" => "Europe/Rome",
	"Europe/Samara" => "Europe/Samara",
	"Europe/San_Marino" => "Europe/San_Marino",
	"Europe/Sarajevo" => "Europe/Sarajevo",
	"Europe/Simferopol" => "Europe/Simferopol",
	"Europe/Skopje" => "Europe/Skopje",
	"Europe/Sofia" => "Europe/Sofia",
	"Europe/Stockholm" => "Europe/Stockholm",
	"Europe/Tallinn" => "Europe/Tallinn",
	"Europe/Tirane" => "Europe/Tirane",
	"Europe/Uzhgorod" => "Europe/Uzhgorod",
	"Europe/Vaduz" => "Europe/Vaduz",
	"Europe/Vatican" => "Europe/Vatican",
	"Europe/Vienna" => "Europe/Vienna",
	"Europe/Vilnius" => "Europe/Vilnius",
	"Europe/Volgograd" => "Europe/Volgograd",
	"Europe/Warsaw" => "Europe/Warsaw",
	"Europe/Zagreb" => "Europe/Zagreb",
	"Europe/Zaporozhye" => "Europe/Zaporozhye",
	"Europe/Zurich" => "Europe/Zurich",
	"Indian/Antananarivo" => "Indian/Antananarivo",
	"Indian/Chagos" => "Indian/Chagos",
	"Indian/Christmas" => "Indian/Christmas",
	"Indian/Cocos" => "Indian/Cocos",
	"Indian/Comoro" => "Indian/Comoro",
	"Indian/Kerguelen" => "Indian/Kerguelen",
	"Indian/Mahe" => "Indian/Mahe",
	"Indian/Maldives" => "Indian/Maldives",
	"Indian/Mauritius" => "Indian/Mauritius",
	"Indian/Mayotte" => "Indian/Mayotte",
	"Indian/Reunion" => "Indian/Reunion",
	"Pacific/Apia" => "Pacific/Apia",
	"Pacific/Auckland" => "Pacific/Auckland",
	"Pacific/Chatham" => "Pacific/Chatham",
	"Pacific/Chuuk" => "Pacific/Chuuk",
	"Pacific/Easter" => "Pacific/Easter",
	"Pacific/Efate" => "Pacific/Efate",
	"Pacific/Enderbury" => "Pacific/Enderbury",
	"Pacific/Fakaofo" => "Pacific/Fakaofo",
	"Pacific/Fiji" => "Pacific/Fiji",
	"Pacific/Funafuti" => "Pacific/Funafuti",
	"Pacific/Galapagos" => "Pacific/Galapagos",
	"Pacific/Gambier" => "Pacific/Gambier",
	"Pacific/Guadalcanal" => "Pacific/Guadalcanal",
	"Pacific/Guam" => "Pacific/Guam",
	"Pacific/Honolulu" => "Pacific/Honolulu",
	"Pacific/Johnston" => "Pacific/Johnston",
	"Pacific/Kiritimati" => "Pacific/Kiritimati",
	"Pacific/Kosrae" => "Pacific/Kosrae",
	"Pacific/Kwajalein" => "Pacific/Kwajalein",
	"Pacific/Majuro" => "Pacific/Majuro",
	"Pacific/Marquesas" => "Pacific/Marquesas",
	"Pacific/Midway" => "Pacific/Midway",
	"Pacific/Nauru" => "Pacific/Nauru",
	"Pacific/Niue" => "Pacific/Niue",
	"Pacific/Norfolk" => "Pacific/Norfolk",
	"Pacific/Noumea" => "Pacific/Noumea",
	"Pacific/Pago_Pago" => "Pacific/Pago_Pago",
	"Pacific/Palau" => "Pacific/Palau",
	"Pacific/Pitcairn" => "Pacific/Pitcairn",
	"Pacific/Pohnpei" => "Pacific/Pohnpei",
	"Pacific/Port_Moresby" => "Pacific/Port_Moresby",
	"Pacific/Rarotonga" => "Pacific/Rarotonga",
	"Pacific/Saipan" => "Pacific/Saipan",
	"Pacific/Tahiti" => "Pacific/Tahiti",
	"Pacific/Tarawa" => "Pacific/Tarawa",
	"Pacific/Tongatapu" => "Pacific/Tongatapu",
	"Pacific/Wake" => "Pacific/Wake",
	"Pacific/Wallis" => "Pacific/Wallis",
	"UTC" => "UTC",
);
/**
* abstract library class
*
* @library	Forms Auto Generations and validations library
* @author	[Emanuel Giurgea <emanuel@devsaver.com>]
* @since	PHPbase 0.0.1
*/

class CForm extends CLibrary{

	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $aclMod;
	

	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $skins = array(
		1	=> "default",
		2	=> "DarkBlue" , 
		3	=> "Green",
		4	=> "Orange",
		5	=> "Pink",
	);

	var $skin = 1;

	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $cache = array();
	
	

	//some default settings
	var $_textareaCols = 30;
	var $_textareaRows = 4;

	var $_textboxSize = 20;
	var $_textboxMaxLength = "";

	var $textareaButtons = array (
				"1" => "'cut' ,  'copy' , 'paste' , 'separator' , 'undo' , 'redo' , 'separator' , 'removeformat' , 'toolbar' , 'bold' , 'italic' , 'underline' , 'strike' , 'superscript' , 'subscript' , 'insertorderedlist' , 'insertunorderedlist' , 'indent' , 'outdent' , 'inserthr'",
				"2" => "'font-family' , 'font-size' , 'justifyleft' ,  'justifycenter' , 'justifyright' , 'justifyfull' , 'separator' , 'link' , 'resource'"
			);

	var $__default = array ( 
					"show" => array (
								"droplist" => array ("empty_msg" => "<span class='form-text'><i>N/A</i></span>"  , "empty_text" => "[ select ]", "empty_text_show" => "<span class='form-text'><i>N/A</i></span>"),
								"radio" => array ("empty_text" => "[ none ]" , "empty_text_show" => "<span class='form-text'><i>N/A</i></span>")
							  ),
					"list" => array(
								"fields" => array( "maxchars_text" => "[...]")
								)
					);



	var $masks = array(
		"mm/dd/yyyy"	=> "'alias': 'datetime' , 'inputformat':'mm/dd/yyyy'",
		"yyyy/mm/dd"	=> "'alias': 'datetime' , 'inputformat':'yyyy/mm/dd'",
		"email"	=> "'alias': 'email'",
		"ip"	=> "'alias': 'ip'",
		"currency"	=> "'alias': 'numeric', 'groupSeparator': ',', 'autoGroup': true, 'digits': 2, 'digitsOptional': false, 'prefix': '', 'placeholder': '0'",
	);

	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $db;

	/**
	* description array with all functions to be executed in various posittions in cform
	*
	* @var type
	*
	* @access type
	*/
	var $functions;
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __construct($template = "", &$db  = "", &$tables = "", $form = "") {
		parent::__construct("CForm");

		global $site;

		if (!is_Array($tables)) {
			$tables = $site->tables;
		}
			
		if (!is_object($template)) {	
		}

		$template = new CTemplate("templates/form.htm");

		if (!is_object($db)) {
			$db = $site->db;
		}
		
		//optionaly added $form
		if ($form != "")
			$this->form = CForm::Process($form);

		
		$this->templates = &$template;
		$this->db = &$db;
		$this->tables = &$tables;

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __render($data , $vars = array()) {

		$this->tpl_vars = array_merge($vars , (array)$this->tpl_vars);

		$this->tpl_vars['&amp;'] = "&";

		if (is_array($this->tpl_vars )) {
			//inizialize a new template
			$tmp = new CTemplate($data , "string");

			return $tmp->Replace($this->tpl_vars);
		} else 
			return $data;
	}


	/**
	* description checking if the input is an array or an xml file 
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	static function Process($input) {
		if (is_array($input)) {			
			return CForm::ProcessBox($input);
		} else {
			if (file_exists($input)) {
				$xml = new CConfig($input);				
				$xml->vars["form"]["xmlfile"] = $input ;


				if (is_array($xml->vars["form"]["skin"])) {

					switch ($xml->vars["form"]["skin"]["type"]) {
						case "eval":
							eval( "\$tmp = " . $xml->vars["form"]["skin"]["import"] );
							$xml->vars["form"]["skin"] = $tmp;
						break;
					}
					
				}
				return CForm::ProcessBox($xml->vars["form"]);
			} else
				return null;			
		}		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	static function ProcessBox($form) {

		if (is_array($form["fields"]) && is_array($form["fields"]["box"])) {

			if (is_array($form["fields"]["box"]) && !is_array($form["fields"]["box"][0])) {
				$form["fields"]["box"] = array(
					0	=> $form["fields"]["box"]
				);
			}
						
		}


		//process for restricted boxes
		if (is_array($form["fields"]["box"])) {
			foreach ($form["fields"]["box"] as $key => $val) {
				if ($val["restricted"] && CForm::__isRestricted($val["restricted"])) {
					unset($form["fields"]["box"][$key]);

					if (!count($form["fields"]["box"])) {
						unset($form["fields"]["box"]);
					}					
				} 
			}			

			foreach ($form["fields"]["box"] as $key => $val) {
				$form["fields"]["box"][$key] = CForm::processFieldTypes($val);
			}						
		}
		
				

		return $form;
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ProcessFieldTypes($box) {


		if (is_array($box["fields"])) {
			$cnt = 0;
			foreach ($box["fields"] as $key => $val) {

				switch ($val["type"]) {
					case "responsive":
						if (!$val["name"]) {
							$val["name"] = $key;
						}
						
						$fields = cForm::__field__responsive($val);

						//debug($fields,1);

						unset($box["fields"][$key]);
						array_splice ($box["fields"], $cnt, 0, $fields ); 
						$cnt += count($fields) - 1;						
					break;
				}
				
				$cnt ++;
			}


			//rekey the fields
			foreach ($box["fields"] as $key => $val) {

				if ($val["name"]) {
					$_box["fields"][$val["name"]] = $val;
				} else {
					$_box["fields"][$key] = $val;
				}
				
			}
			
			$box["fields"] = $_box["fields"];
		}				

		return $box;
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function generateResponsiveSet($field) {

		$field = array();
	}
	
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ProcessLinks($link) {
		return CryptLink($link);
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Validate($form  , $input) {

		global $_CONF , $_LANG_ID;

		$form = CForm::Process($form);


		if (is_array($form["fields"])) {


			if ($input[$form["table_uid"]]) {
				$old_record = $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$form["table"]] . "` WHERE `" . $form["table_uid"] . "`='" . $input[$form["table_uid"]] . "'" );
			}
			
			
			foreach ($form["fields"] as $key => $val) 					


				if (	
						($val["validate"] && $val["required"] && ($val["editable"] != "false")) || 
						($val["validate"] && !$val["required"] && ($val["editable"] != "false") && $input[$key]) 
				) {				

					if (
						($val["protected"] && $this->__isProtected($val["protected"] , $old_record) ) || 
						($val["restricted"] && $this->__isRestricted($val["restricted"] , $old_record)) 
					) {
						//do nothing, this is a field which doesnt need to apear
					} else {					
						//prepare the field name
						$val["name"] = $val["name"] ? $val["name"] : $key;
						switch ($val["type"]) {

							case "ccard":
							case "creditcard":
								//group all the values
								$input[$val["name"]] = trim(@implode("" , $input[$val["name"] . "_arr"] ));
								$_valid_temp[] = strtoupper($val["name"]) . ":" . "I:16:16";
							break;

							case "date":
								$input[$val["name"]] = mktime(
															$input[$val["name"] . "_hour"],
															$input[$val["name"] . "_minute"],
															$input[$val["name"] . "_second"],
															$input[$val["name"] . "_month"],
															$input[$val["name"] . "_day"],
															$input[$val["name"] . "_year"]
														);
								
								//fix if the dates werent correct
								if ($input[$val["name"]] <= 0 )
									$input[$val["name"]] = 0;
								
								$_valid_temp[] = strtoupper($val["name"]) . ":" . $val["validate"];
							break;

							case "file":
							//	$_valid_temp[] = strtoupper($val["name"]) . ":" . "FILE::";
							break;

							default:
								//check for exceptions
								if (stristr($val["validate"],"CC"))
									$val["validate"] = "CC:" . $input[$val["name"] . "_type"] . ":";
									

								$_valid_temp[] = strtoupper($val["name"]) . ":" . $val["validate"];
							break;

							case "relation":
								unset($_valid_temp);
							break;

							case "droplist":
							case "radio":
							case "radiolist":
							case "checklist":
								if (is_array($input[$val["name"]])) {								
									$input[$val["name"]] = implode("," , $input[$val["name"]]);
								}
								$_valid_temp[] = strtoupper($val["name"]) . ":" . $val["validate"];
							break;

						}								
					}
				}

			if (is_array($_valid_temp) && count($_valid_temp)) {
				$validate = implode("," , $_valid_temp);
			}
						
		}				


		//validate the input fields
		$result = ValidateVars($input ,$validate);
		$vars = array();

		if (is_array($result)) {
		
			foreach ($result as $key => $val) {

				//get the name for the element
				$fld = trim(strtolower($val));

				//check if it was refered
				if ($form["fields"][$fld]["referer"])
					$fields["errors"][$form["fields"][$fld]["referer"]] = 1;
				
				$fields["errors"][$fld] = 1;
			}

			$fields["error"] = _MSG_FORMS_UNCOMPLETE;
			$fields["values"] = $input;

			$fields["errorCode"] = "1";


		} else {

			//proceed to complex validation for unique fields 
			if (is_array($form["fields"])) {

				
				foreach ($form["fields"] as $key => $val) {					

					$name = $val["name"] ? $val["name"] : $key ;

					if (($val["type"] == "file") && ($val["required"] == "true")) {
						if (!is_array($_FILES[$name]) || (is_array($_FILES[$name]) && $_FILES[$name]["error"])) {
							$fields["error"] = _MSG_FORMS_UNCOMPLETE;
							$fields["values"] = $input;
							$fields["errorCode"] = "1";
							$fields["errors"][$name] = 1;
						}
					}


					if (($val["unique"] == "true") && (($val["required"] == "true" ) || (($val["required"]) != "true") && $input[$name]) ) {


						//check if this is an adding processor or editing one

						if ($val["unique_condition"]) {
							$cond = " AND " . $val["unique_condition"];
						} else {
							$cond = "";
						}
						

						if ($val["lang"] == "true") {
							$data = $this->db->QFetchArray("SELECT `$name` FROM `" . $this->tables[$form["table_lang"]] . "` WHERE `" . $name . "` = '" . $input[$name] . "' AND lang_id={$_LANG_ID} {$cond}");
							$old_record = $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$form["table_lang"]] . "` WHERE `" . $form["table_uid"] . "`='" . $input[$form["table_uid"]] . "' AND lang_id={$_LANG_ID}");
						} else {						
							$data = $this->db->QFetchArray("SELECT `$name` FROM `" . $this->tables[$form["table"]] . "` WHERE `" . $name . "` = '" . $input[$name] . "' {$cond}");
							$old_record = $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$form["table"]] . "` WHERE `" . $form["table_uid"] . "`='" . $input[$form["table_uid"]] . "'" );

						}
	


						if (							
							((is_array($data) && is_array($old_record)) && ($data[$name] != $old_record[$name])) || 
							(is_array($data) && !is_array($old_record))
							) {

							//preparing the message
							$fields["error"] = $val["unique_err"] ? $val["unique_err"] : $val["title"] . _MSG_FORMS_UNIQUE;
							$fields["errors"][$name] = 1;
							$fields["values"] = $input;
							$fields["errorCode"] = "2";

						}
/*
						debug($fields);
						debug($name);
						debug($data );
						debug($old_record,1);
*/
					}

					if ($val["exists"] == "true") {

						//check if this is an adding processor or editing one
						if ($input[$form["table_uid"]]) {
							$old_record = $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$form["table"]] . "` WHERE `" . $form["table_uid"] . "`='" . $input[$form["table_uid"]] . "'" );
						}

						$data = $this->db->QFetchArray("SELECT `$name` FROM `" . $this->tables[$form["table"]] . "` WHERE `" . $name . "` = '" . $input[$name] . "'");

						if (!is_array($data)) {
							//preparing the message
							$fields["error"] = $val["unique_err"] ? $val["unique_err"] : $val["title"] . _MSG_FORMS_EXISTS;
							$fields["errors"][$name] = 1;
							$fields["values"] = $input;
							$fields["errorCode"] = "6";

						}
					}

					if ($val["type"] == "checkIMG") {

						if ($_SESSION[$_CONF["site"]]["XML_verify_key"] != $_POST[$name]) {

							$fields["error"] = $fields["error"]  ? $fields["error"]  : _MSG_FORMS_WRONGSECURITY;
							$fields["errors"][$name] = 1;
							$fields["values"] = $input;
							$fields["errorCode"] = "3";

						}						
					}

								
					// search to see if is a vvalid file path
					if ($val["fileexists"] == "true") {
						$name = $val["name"] ? $val["name"] : $key ;

						if (!is_file($input[$name])) {
							//preparing the message
							$fields["error"] = $val["fileexists_err"] ? $val["fileexists_err"] : $val["title"] . ": \"$input[$name]\"" . _MSG_FORMS_FILEEXISTS;
							$fields["errors"][$name] = 1;
							$fields["values"] = $input;
							$fields["errorCode"] = "4";
						}
						
					}

					//echo $input[$name . "_confirm"];

					

					// search to see if is a vvalid file path
					if (($input[$name] != $input[$name . "_confirm"]) && is_array($form["fields"][$name . "_confirm"])) {
						
						if ($input[$name] != $input[$name . "_confirm"]) {
							//preparing the message
							$fields["error"] = "Password and confirmation doesnt match.";
							$fields["errors"][$name] = 1;
							$fields["errors"][$name . "_confirm"] = 1;
							$fields["values"] = $input;
							$fields["errorCode"] = "5";
						}
						
					}

				}
					
			}
			
		}

		return is_array($fields) ? $fields : true;

	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __simple_list_load_Records($form , $page = null) {
		global $_SESS;

		if (!is_array($items) && is_object($this->db) && count($this->tables)) {
	
			//if no items and no sql then build an sql query right here
			if (!is_array($form["sql"])) {	


				$form["sql"] = array(
					"vars" => array(
							"table_lang"	=> array("type"	=> "table_lang"),
							"table"			=> array("type" => "table"),
							"page"			=> array("type" => "page"),
							"items"			=> array("type" => "form" , "var" => "items"),
							"lang"			=> array("type"	=> "var"	, "import" => $_GET["lang_id"]) , 
							"order"			=> array("type" => "var" , "import" => $_GET["order"]),
							"order_mode"	=> array("type" => "var" , "import" => $_GET["order_mode"] && array_exists($_GET["order_mode"] , array("ASC" , "DESC" )) ? $_GET["order_mode"] : "ASC")
						)
				);

				//detect if its  language select or simple
				if ($form["table_lang"]) {

					$form["sql"]["query"] = "
						SELECT * FROM 
							{TABLE} as p , 
							{TABLE_LANG} as l 
						WHERE  
							p.{$form[table_uid]} = l.{$form[table_uid]} AND 
							l.lang_id = {LANG}

							" . ($_GET["order"] ? "ORDER BY {ORDER} {ORDER_MODE}" : "") . " LIMIT {PAGE} , {ITEMS} ";

					$form["sql"]["count"] = array("table" => "{TABLE} as p , {TABLE_LANG} as l " , "condition" => "WHERE  p.{$form[table_uid]} = l.{$form[table_uid]} AND l.lang_id = {LANG}");

				} else {				
					$form["sql"]["query"] = "SELECT * FROM {TABLE} " . ($_GET["order"] ? "ORDER BY {ORDER} {ORDER_MODE}" : "") . " LIMIT {PAGE} , {ITEMS} ";
					$form["sql"]["count"] = array("table" => "{TABLE}" , "condition" => "");
				}



			} else {



				//force the $order and order mode to be after the data from the $_GET
				if ($form["sql"]["vars"]["order"] && $_GET["order"] && ($form["header"]["nolinks"] != "true"))
					$form["sql"]["vars"]["order"]["import"] = $_GET["order"];

				if ($form["sql"]["vars"]["order_mode"] && $_GET["order_mode"] && ($form["header"]["nolinks"] != "true"))
					$form["sql"]["vars"]["order_mode"]["import"] = $_GET["order_mode"];
				
			}


			if (is_array($form["sql"])) {

				if (is_array($form["sql"]["vars"])) {

					foreach ($form["sql"]["vars"] as $key => $val) {
						//echeking if the default must be evaluated
						if ($val["action"] == "eval") {
							eval("\$val[\"import\"] = " . $val["default"] .";");
						}

						switch ($val["type"]) {
							case "eval":
								eval("\$sql_vars[\"$key\"] = " . $val["import"] . ";");
							break;

							case "var":
								$sql_vars[$key] = $val["import"];
							break;

							case "table":
								$sql_vars[$key] = $val["import"] ? $this->tables[$val["import"]] : $this->tables[$form["table"]];
								$__tables[] = $key;
							break;

							case "table_lang":
								$sql_vars[$key] = $this->tables[$form["table_lang"]];
								$__tables[] = $key;
							break;

							case "page":
								if ($page != null) {
									$sql_vars[$key] = $page;
								} else {								
									$sql_vars[$key] = ($_GET[($val["code"] ? $val["code"] : 'page')] -1 )* $form['items'];
								}
							break;

							case "form":
								$sql_vars[$key] = $form[$val["var"]];
							break;
						}										
					}
		
					foreach ($sql_vars as $key => $val) {							

						$sql_vars[$key] = CTemplateStatic::Replace($sql_vars[$key] , $sql_vars);
						$sql_vars[$key] = str_replace("]" , ">" , str_replace("[" , "<" , $sql_vars[$key]));
					}	
					
					//doing a double replace, in case there are unreplaced variable sfom "vars" type
					$sql = CTemplateStatic::Replace($form["sql"]["query"] , $sql_vars);

					//do a precheck for [] elements to be replaced with <>
					$sql = str_replace("]" , ">" , str_replace("[" , "<" , $sql));

					$items = $this->db->QFetchRowArray($sql);
					//$items = $this->Query						

					//processing the counting query
					if (is_array($form["sql"]["count"])) {

						//if no table is set then i use the default table'
						$form["sql"]["count"]["table"] = $form["sql"]["count"]["table"] ? $form["sql"]["count"]["table"] : $form["table"];

						foreach ($form["sql"]["count"] as $key => $val) {
							$form["sql"]["count"][$key] = CtemplateStatic::Replace($val , $sql_vars);
						}						

						
						$count = $this->db->RowCount(
							$form["sql"]["count"]["table"] , 
							$form["sql"]["count"]["condition"] , 
							//$form["sql"]["count"]["select"] , 
							$form["sql"]["count"]["fields"] 
						);
					}					
				}				
			}
		}

		$_GET["page"] = $_GET["page"] ? $_GET["page"] : 1;

		$pages = ceil($count / $form["items"]);

		//if i try to access a bigger page the maximum then 
		if (($pages > 0) && ($_GET["page"] > $pages) && !$_GET["ajax"]) {
			$_GET["page"] = $pages;

			return $this->__simple_list_load_Records($form);
		}

		//auto index the element
		$start = $form["items"] * ($_GET["page"] ? $_GET["page"] - 1 : 0);

		

		$_old_count = $start + 1;

		if (is_array($items)) {
			if (is_array($items[key($items)])) {
				foreach ($items[key($items)] as $key => $val) {
					$sortable[$key] = 1;
				}				
			}

			foreach ($items as $key => $val) {
				$items[$key]["_count"] = ++$start;
				$items[$key]["original_count"] = $items[$key]["_count"] ;
			}	
			
		}		

		if (is_Array($items)) {
			return array(
				"items"			=> $items,
				"count"			=> $count,
				"tables"		=> $__tables,
				"table_fields"	=> $sortable,
			);
		}
		

	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AjaxList($form , $items = "", $count = "", $extra = null , $search = false , $returnArray  = false) {
		global 
			$_CONF , 			
			$form_errors , 
			$_USER , 
			$form_countries, 
			$form_months,
			$form_US_states,
			$form_RO_states,
			$form_CA_states;


		
		if (is_array($form["order"]) && ($form["order"]["drag"] == "true")) {
			
			if (!$this->__isRestricted($form["order"]["restricted"])) {
				$form["fields"]["button_reorder"] = array(
					"type"		=> "button",
					"width"		=> "20",
					"align"		=> "center",
					"button"	=> $form["order"]["button"] ? $form["order"]["button"]  : "reorder",
					"location"	=> "javascript:void(0);"
				);

			}

		}		


		//add the extra button if order exists

		if (is_array($form["vars"])) {
			foreach ($form["vars"] as $key => $val) {
				//echeking if the default must be evaluated
				if ($val["action"] == "eval") {
					eval("\$val[\"import\"] = " . $val["default"] .";");
				}

				switch ($val["type"]) {
					case "eval":
						eval("\$tpl_vars[\"$key\"] = " . $val["import"] . ";");
					break;
					case "complex_eval":
						eval($val["import"]);
					break;

					case "var":
						$tpl_vars[$key] = $val["import"];
					break;
				}													
			}
		}
		//$tpl_vars = array_merge($tpl_vars);
		$global_vars = $this->GlobalVars($form);

		$records = $this->__simple_list_load_records($form);

		$items = $records["items"];
		$count = $records["count"];
		$__tables = $records["tables"];
		$sql_vars = $records["sqlvars"];

		if ($returnArray == true) {
			return array(
						"items" => $items,
						"count" => $count
						);
		}

		if (!count($items)) {
			return "empty";
		}		


		//check if ordering field is acctivated disable the reordering
		if (is_array($form["order"])) {
			//$form["header"]["nolinks"] = "true";
		}
				
		$_new_count = $start;

		$html = new CHtml();

		$form = $this->Process($form);

		$template = &$this->templates;

		//this sux, building the template
		if (is_array($form["fields"])) {

			//prepare the fields list
			if ($form["sql"]["vars"]["fields"] != "")
				$__fields = explode("," , $form["sql"]["vars"]["fields"]);
			else {
				//read the fields from the table
				if (is_array($__tables)  && is_object($this->db)) {
					$__fields = array();
					foreach ($__tables as $_k => $_v) {
						$__fields = array_merge((array)$__fields , (array)$this->db->GetTableFields($sql_vars[$_v]));
					}					
				}
			}

			$tmp_count = 0;
			foreach ($form["fields"] as $key => $val) {
				if (!($val["restricted"] && $this->__isRestricted($val["restricted"]))) {

					$tmp_count ++;

					$cell = array (
									"width" => $val["width"],
									"align" => $val["align"],
									"value" => "{" . strtoupper($key) . "}",
									"valign" => $val["valign"] ? $val["valign"] : "middle",
									"final" => !is_array($form["buttons"]) && ($tmp_count == count($form["fields"])) ? "Final" : "",
									"first" => $tmp_count == 1 ? "First" : "",
								);

					$data .= $template->blocks["ListCell"]->Replace (
								$cell
							  );

					if ($val["type"] == "multiple")
						$val["header"] = $template->blocks["SimpleListMultipleHeader"]->Replace(array(
											"name" => $val["field"],
											"start" => $_old_count,
											"end" => $_new_count
										));
					
					//prepare the title
					$__title = ($val["header"] ?  $val["header"]  : "<img width=0 height=1 border=0/>");

					if ($sql_vars["order"] == $key)
						$__sorting_mode = $_GET["order_mode"] == "ASC" ? "DESC" : "ASC";				
					else
						$__sorting_mode = "ASC";								


					//check if this forms allows the title to be sortable
					if ($form["header"]["nolinks"] == "true") {
						//unclickable link
						$__template = "ListTitle";
					} else {
						//if this field appears in the list of table firles show title with link
						if (is_array($__fields) && in_array($key , $__fields))
							$__template = "ListTitleLink";
						else
							//no link title
							$__template = "ListTitle";
					}

					
					$__tmp_title = array(
								"title" => $__title,
								"width" => $val["width"] ? " width=\"{$val[width]}\" " : "",
								"final" => !is_array($form["buttons"]) && ($tmp_count == count($form["fields"])) ? "Final" : "",
								"first" => $tmp_count == 1 ? "First" : "",
								"link" => CSYS::_GetVar(
												array( 
													"order" => $key , 
													"order_mode"=> $__sorting_mode
													)
											),
								"order" => $sql_vars["order"] == $key ? 
												$template->blocks["ListTitleLinkOrder"]->Replace(
													array(
														"order" => strtolower($__sorting_mode)
													)
												) : ""
							);

					if ($form["valternance"] == "true") {
						$__tmp_title["_valternance"] = $this->_tmpVAlternanceHeader ? "2" : "";
						$this->_tmpVAlternanceHeader = $this->_tmpVAlternanceHeader ? 0 : 1;
					} else
						$__tmp_title["_valternance"]  = "";

					
					//buildint the title header
					$titles .= $template->blocks[$__template]->Replace ( $__tmp_title );

				}
				
			}



			//adding one more title col in titles ( the one for buttons )
			if (is_array($form["buttons"])) {

# DEPRECATED
				$titles .= $template->blocks["ListTitle"]->Replace ( array(
									"title" => "&nbsp" , 
									"final" => "Final" , 
									"width" => $val["width"] ? " width=\"{$val[width]}\" " : ""
							));
				$row = $data . $template->blocks["ButtonsCell"]->output;
			} else
				$row = $data;
			
			//debug($form);

			$template->blocks["ListElement"]->input = $template->blocks["ListRow"]->Replace(array(
					"ROW"			=> $row,
					"class"			=> "FormSimpleListRow",
					"order_id"		=> is_array($order),
					"order_value"	=> "table_order_{" . strtoupper($form["table_uid"]) . "}"

			));			


			$titles = $template->blocks["ListRow"]->Replace(array(
					"ROW"			=> $titles ,
					"CLASS"			=> "FormSimpleListTitle",
					"order_value"	=> "",
				));

			//fuck i know this is stupid, but now i dont have other idees
			//if i see a variable <no heade> then i clear the template
			if ($form["header"]["titles"] == "false") {
				$titles = "";
			}			
		}
		
		
		
		$template->blocks["ListGroup"]->input = $template->blocks["ListGroupAjax"]->input;

		//prereplace the vars main template
		$template->blocks["ListGroup"]->input = $template->blocks["ListGroup"]->Replace($form);

//! TEST
		if (is_array($global_vars)) {
			$template->blocks["ListElement"]->input = $template->blocks["ListElement"]->Replace($global_vars);
			$template->blocks["Button"]->input = $template->blocks["Button"]->Replace($global_vars);
		}		

//! E:TEST
		//prereplace the pagination template

		if (is_array($_GET)) {
			foreach ($_GET as $key => $val) {
				if ($key != "page") {

					//check if the data from get isnt a complex array too.
					if (is_array($val)) {
						foreach ($val as $k => $v)
							$url[] = $key . "[$k]" . "=" . $v;
					} else {					
						if ($key == "returnurl") {
							$url[] = $key . "=" . urlencode($val);
						} else {					
							$url[] = $key . "=" . $val;
						}
					}
				}
			}
			
			$url = $_SERVER["SCRIPT_NAME"] . "?" . @implode("&" , $url) . "&";
		}

		$template->blocks["Page"]->input = $template->blocks["Page"]->Replace(array("BASE" => $url));
		
		$_GET["page"] = ($_GET["page"] ? $_GET["page"] : "1");

		$items = $this->__simple_list_process_items($form , $items);
		
		if ($form["items"]) {

			$return = CTemplateStatic::Replace(
				$html->Table( $template , "List" , $items),
				array(
					"paging" => CHTML::CustomPaging(
						$template , 
						"Paging",
						10 , 
						ceil($count / $form["items"]) , 
						$_GET["page"] , 
						$url . "&page={PAGE}"
					),
				)
			);

		} else {
			$return = $html->Table( $template , "List" , $items );			
		}

		if (is_array($this->functions["list"]["after"]))
			call_user_func($this->functions["list"]["after"],$append);
		
		
		$this->templates->blocks["Temp"]->input = $return;

		return $this->__render($this->templates->blocks["Temp"]->input , array_merge((array)$global_vars,(array)$tpl_vars));
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __simple_list_process_items($form , $items) {
		global $_CONF , $form_countries , $form_languages , $form_RO_states, $form_US_states, $form_CA_states;

		$global_vars = $this->GlobalVars($form);

		$template = &$this->templates;
		

		if (is_array($items) && array_key_exists ("items" , $items)) {
			$tmp = $items;
			$items = $items["items"];
		}
		

//preprocessing the items
		if (is_array($items)) {

			if ($form["table_lang"] && !$form["languages"]) {
				$tmp = CXMLFormLanguage::LanguageButtons();
				foreach ($tmp as $key => $val) {
					$form["languages"][$val["id"]] = $val;
				}
			}

			if ($this->functions["pre_process_record"]) {
				foreach ($items as $key => $val) {
					$items[$key] = call_user_func($this->functions["pre_process_record"] , $val);
				}
				
			}

			//preprocess for restricted. I need to remove them before i go in processing because i might have fields linked to modules that doesnt exists
			if (is_array($form["fields"])) {
				foreach ($form["fields"] as $k => $v) {
					if (isset($v["restricted"]) && $this->__isRestricted($v["restricted"])) {
						unset($form["fields"][$k]);
					}					
				}
			}
						

			foreach ($items as $key => $val) {
				if (is_array($form["fields"])) {

					foreach ($form["fields"] as $k => $v) {

						if (!isset($v["name"]))
							$v["name"] = $k;

						if ($v["protected"] && $this->__isProtected($v["protected"] , $items[$key]) ) {
							$items[$key][$k] = "___is_protected___";
						} else {
						
							//this is for utf8 support, EXPERIMENTAL
							if ($items[$key][$k]) {
								$items[$key][$k] = html_entity_decode($items[$key][$k] , ENT_QUOTES);
							}
							

							switch ($v["type"]) {

								case "eval":

									eval("\$__tmp = " . $v["import"]);

									$items[$key][$k] = $__tmp;
								break;


								case "iptrace":
									
									$items[$key][$k] = "<a href='http://www.iplocationfinder.com/{$items[$key][$k]}' target='_blank'>{$items[$key][$k]}</a>";
									$v["nolink"] = "true";
								break;



								case "rostates":
									$items[$key]["original_" . $k] = $items[$key][$k];
									$items[$key][$k] = $form_RO_states[$items[$key][$k]];
								break;

								case "languages":
									$items[$key]["original_" . $k] = $items[$key][$k];
									$items[$key][$k] = $form_languages[$items[$key][$k]];
								break;


								case "states":
								case "usstates":
									$items[$key]["original_" . $k] = $items[$key][$k];
									$items[$key][$k] = $form_US_states[$items[$key][$k]];
								break;

								case "castates":
									$items[$key]["original_" . $k] = $items[$key][$k];
									$items[$key][$k] = $form_CA_states[$items[$key][$k]];
								break;

								case "countries":
									$items[$key]["original_" . $k] = $items[$key][$k];
									$items[$key][$k] = $form_countries[$items[$key][$k]];
								break;

								case "date":

									//save the value
									$items[$key]["original_" . $k] = $items[$key][$k];

	#### STILL WORKING ON THIS
									if (isset($v["fields"])) {
										$supp_fields = array("month" , "year" , "month_str", "day");

										$_tmp_v = "";


										foreach ($supp_fields  as $__k => $__v) {
											switch ($__v) {
												case "month_str":
													$_tmp_v[$__v] = $form_months[$val[$k . "_month" ]];
												break;

												case "day":
													$_tmp_v[$__v] = sprintf("%02d" ,$val[$k . "_day" ]);
												break;
											}										
										}

										$items[$key][$k] = $v["fields"];
										foreach ($_tmp_v as $__k => $__v) {
											$items[$key][$k] = str_replace($__k , $__v , $items[$key][$k]);									
										}									
										
									} else {
									
										if (isset($val[$k . "_day" ]) && isset($val[$k . "_month" ]) && isset($val[$k . "_year" ]))  {

											$items[$key][$k] = 
																( $val[$k . "_month" ] ? sprintf("%02d" ,$val[$k . "_month" ])  : "--" ). "/" . 
																( $val[$k . "_day" ] ? sprintf("%02d" ,$val[$k . "_day" ]) : "--" ) . "/" .  
																( $val[$k . "_year" ] ? $val[$k . "_year" ] : "----" ) ;
										} else						
											//$field["value"] = $field["value"] > 0 ? @date($field["params"] , $field["value"]) : "not available";
											$items[$key][$k] = $items[$key][$k] > 0 ? @date($v["params"] , ($v["now"] == "true" ? time() : $items[$key][$k])) : "N/A";
									}

	//								$items[$key][$k] = $items[$key][$k] > 0 ? @date($v["params"] , ($v["now"] == "true" ? time() : $items[$key][$k])) : "N/A";
								break;

								case "price":
									$items[$key]["original_" . $k] = $items[$key][$k];

									if ($items[$key][$k]) {
										$items[$key][$k] = number_format($items[$key][$k],isset($v["digits"]) ? $v["digits"] : 2);
									}
								
								break;

								case "int":
									$items[$key][$k] = (int)$items[$key][$k];
								break;

								case "image":
									if (isset($items[$key][$k]) && $items[$key][$k]) {

										$path = $v["link"] ? $v["link"] : (($v["absolute"] == "true" ? "" : $_CONF["upload"]) . $v["path"] . CTemplateStatic::Replace($v["file"]["default"] , $items[$key]) . ($v["file"]["field"] ? $items[$key][$v["file"]["field"]] : "") . $v["file"]["ext"]);
										$url = $v["link"] ? $v["link"] : (($v["absolute"] == "true" ? "" : $_CONF["url"] . "upload/") . $v["path"] . CTemplateStatic::Replace($v["file"]["default"] , $items[$key]) . ($v["file"]["field"] ? $items[$key][$v["file"]["field"]] : "") . $v["file"]["ext"]);

										if (file_exists($path)) {
											$url .= "?" . filemtime ($path);
										}
										

										// if is the image then show it
										$items[$key][$k] = $template->blocks[$v["nolink"] == "true"  ? "imageshownolink" : "imageshowtable"]->Replace(
																array(
																	"width" => $v["width"],
																	"border" => $v["border"] ? $v["border"] : 0,
																	"height" => $v["height"] ? "height='{$v[height]}' " : "",
																	"src" => $url,
																	"title" => $v["title"]
																)
															);

										
										
									} else {
										//else check if the default image exists
										
										if ($v["default"]) {
											$items[$key][$k] = $template->blocks["imageshownolink"]->Replace(
																	array(
																		"width" => $v["width"],
																		"border" => $v["border"] ? $v["border"] : 0,
																		"height" => $v["height"] ? "height='{$v[height]}' " : "",
																		"src" => $_CONF["url"] . "upload/" . $v["path"] . $v["default"] . "?" . filemtime($_CONF["path"] . "upload/" . $v["path"] . $v["default"]) ,
																		"title" => $v["title"]
																	)
																);
										} else 
											//if not simply return a space
											$items[$key][$k] = "&nbsp;";
									}
								break;



								case "relation":
									//cheking if there are static relations or dinamic relations
									$items[$key]["original_" . $k] = $items[$key][$k];
									
									if (is_array($v["options"])) {

										if (($v["multi"] == "true" )) {
											$_tmp = explode("," , $items[$key][$k]);
											$items[$key][$k] = array();
											foreach ($_tmp as $__k => $__v)
												$items[$key][$k][] = $v["options"][$__v];
											

											if (count($items[$key][$k]))
												//implode by ,
												$items[$key][$k] = implode($v["sep"] ? $v["sep"] : ", " , $items[$key][$k]);
											else
												$items[$key][$k] = "";
											
										} else	{
										
											$tmp_val = $v["options"][$items[$key][$k]];
											//ok, i have the static ones

											if ($tmp_val&& is_array($tmp_val)) {

												if ($tmp_val["color"]) {
													$items[$key][$k] =  "<span style='color:{$tmp_val[color]}'>{$tmp_val[value]}</span>";
												} else {
													$items[$key][$k] =  $tmp_val["value"] ? $tmp_val["value"] : "&nbsp;";	
												}
												
											} else {										
												$items[$key][$k] =  $tmp_val ? $tmp_val : "&nbsp;";	
											}
										}
									}
						
									if (is_array($v["relation"])) {
										//reading from database
										//MULTI ELEMENTS

										$tmp_table= explode("," , $v["relation"]["table"]);
										$rel_table = array();

										if (count($tmp_table)) {
											foreach ($tmp_table as $__k => $__table) {
												$rel_table[] = $this->tables[$__table];
											}

											$rel_table = implode(" , " , $rel_table);							
										} else 
											$rel_table = $this->tables[$v["relation"]["table"]];


										if ($v["multi"] == "true") {
											$record = null;
											$_tmp = explode("," , $items[$key][$k]);
											if (is_array($_tmp)) {
												//read the elements which arent already in the cache
												foreach ($_tmp as $__key => $__val) {
													if (!is_array($this->cache["list"][$v["name"]][$__val])) {

														if ($v["relation"]["table_lang"]) {
															if (!is_array($this->cache["list"][$v["name"]])) {
																$this->cache["list"][$v["name"]] = array();
															}
															
															$record[] = $this->cache["list"][$v["name"]][$__val] = $this->db->QFetchArray(
																	"SELECT * FROM 
																		{$rel_table} as p ,  
																		" . $this->tables[$v["relation"]["table_lang"]] . " as l 																	
																	WHERE 
																		p.{$v[relation][id]} = l.{$v[relation][id]} AND 
																		p.{$v[relation][id]}='{$__val}' AND 
																		l.lang_id={$_GET[lang_id]}"
																);

														} else {													
															$record[] = $this->cache["list"][$v["name"]][$__val] = $this->db->QFetchArray(
																	"SELECT * FROM " . $rel_table . " WHERE `" . $v["relation"]["id"] . "`='" . $__val . "'"
																);
														}

														
													} else 
														$record[] = $this->cache["list"][$v["name"]][$__val];
												}											

												//add all the elements to the existing
											}
										} else {
											//NON MULTI ELEMENTS
											//check if this isnt already inthe cache
											if (!is_array($record = $this->cache["list"][$v["name"]][$items[$key][$k]])) {

												if ($v["relation"]["table_lang"]) {

													$lang_table = $this->tables[$v["relation"]["table_lang"]];

													$sql =	"SELECT * FROM 
																{$rel_table} as record, 
																{$lang_table} as record_data ,
																{$this->tables['core:languages']} as lang
															WHERE
																record.{$v['relation']['id']}=record_data.{$v['relation']['id']} AND 
																record_data.lang_id = lang.lang_id AND 
																lang.lang_default=1 AND " . 
																"record." . $v["relation"]["id"] . "='" . $items[$key][$k] . "'";
												} else{
													$sql =	"SELECT * FROM " . $rel_table . " WHERE `" . $v["relation"]["id"] . "`='" . $items[$key][$k] . "'";
												}

												$record =$this->db->QFetchArray( $sql );

												//save the record in some sort of cache
												if (!is_array($record)) {
													$this->cache["list"][$v["name"]][$items[$key][$k]] = array();
												} else
													$this->cache["list"][$v["name"]][$items[$key][$k]] = $record;											
											}
										}
										
										//build the label for multiple fields 

										if (is_array($v["relation"]["text"])) {
											$_tmp_text = array();

											foreach ($v["relation"]["text"] as $kkey => $vval)
												if (is_array($vval))
													$_tmp_text[] = $vval["preffix"] . $record[$vval["field"]] . $vval["suffix"];
												else
													$_tmp_text[] = $record[$vval];
											
											$items[$key][$k] = implode($v["relation"]["separator"] ? $v["relation"]["separator"] . " " : " " , $_tmp_text);
										} else
											if (($v["multi"] == "true" ) && is_array($record)) {
												foreach ($record as $__k => $__v)
													$record[$__k] = $record[$__k][$v["relation"]["text"]];
												
												//implode by ,
												$items[$key][$k] = implode($v["sep"] ? $v["sep"] : ", " , $record);
												
											} else										
												//else return the single field
												$items[$key][$k] = $record[$v["relation"]["text"]];

									}	
									
									if ($items[$key][$k] == "")
										$items[$key][$k] = $v["empty_text"] ? $v["empty_text"] : "N/A";
									
								break;

								case  "sql":
									$items[$key]["original_" . $k] = $items[$key][$k];
							
									if (is_array($v["sql"])) {
										$form_sql_vars = array();

										if (is_array($v["sql"]["vars"])) {
											foreach ($v["sql"]["vars"] as $_key => $_val) {
												//echeking if the default must be evaluated
												if ($_val["action"] == "eval") {
													eval("\$_val[\"import\"] = " . $_val["default"] .";");
												}

												switch ($_val["type"]) {
													case "eval":												
														eval("\$form_sql_vars[\"$_key\"] = " . $_val["import"] . ";");
													break;

													case "var":
														$form_sql_vars[$_key] = $_val["import"];
													break;

													case "page":
														$form_sql_vars[$_key] = ($_GET[($_val["code"] ? $_val["code"] : 'page')] -1 )* $form['items'];
													break;

													case "form":
														eval("\$form_sql_vars[\"$_key\"] = " . $form[$_val["var"]] . ";");
													break;

													case "table":
														$form_sql_vars[$_key] = $_val["import"] ? $this->tables[$_val["import"]] : $this->tables[$form["table"]];
													break;

													case "field":
														$form_sql_vars[$_key] = $items[$key][$_val["import"]];
													break;
												}													
											}

											foreach ($form_sql_vars as $_key => $_val) {							
												$this->templates->blocks["Temp"]->input = $_val;							
												$form_sql_vars[$_key] = $this->templates->blocks["Temp"]->Replace($form_sql_vars);
											}	

											//doing a double replace, in case there are unreplaced variable sfom "vars" type
											$this->templates->blocks["Temp"]->input = $v["sql"]["query"];
											$sql = $this->templates->blocks["Temp"]->Replace($form_sql_vars);

											//do a precheck for [] elements to be replaced with <>
											$sql = str_replace("]" , ">" , str_replace("[" , "<" , $sql));

											$record = $this->db->QFetchArray($sql);								

											$items[$key][$k] = $record[$v["sql"]["field"]] ? $record[$v["sql"]["field"]] : "N/A";
											$items[$key][$k] = $record[$v["sql"]["field"]] ? $record[$v["sql"]["field"]] : (isset($v["empty_msg"]) ? $v["empty_msg"] : "N/A");
										}							
									} else
										$items[$key][$k] = isset($v["empty_msg"]) ? $v["empty_msg"] : "N/A";
								break;

								case "button":
									//check to see if this button isnt a protected one

									//fix the url transformations from the buttons
									$v["nolink"] = "true";
	/*
									if ($v["protected"] && $this->__isProtected($v["protected"] , $items[$key])) {
										$items[$key][$k] = "&nbsp;";
									} else {
	*/									
										//replace the location and the button in the template
										$tmp = $v;
										//chec for variables which might not be defined
										$tmp["onmouseout"] = $tmp["onmouseout"] ? $tmp["onmouseout"] : "";
										$tmp["onmouseover"] = $tmp["onmouseover"] ? $tmp["onmouseover"] : "";
										$tmp["onclick"] = $tmp["onclick"] ? $tmp["onclick"] : "";
										$tmp["title"] = $tmp["title"] ? $tmp["title"] : "";
										$tmp["target"] = $tmp["target"] ? $tmp["target"] : "";
										$button = new CTemplate($template->blocks["Button"]->Replace($tmp),"string");
										$button->input = $button->Replace($global_vars);
										
										//$items[$key][$k] = CTemplateStatic::Replace($tmp , $button->Replace($items[$key]);
	/*
									}*/
								break;

								case "multiple":
									$items[$key]["original_" . $k] = $items[$key][$k];
									// a control variable to know to add the data to end
									$found_multiple = true;	
									
									$_tmp_data = array();

									if ($v["checked"]) {

										if ($v["checked"] == "exact") {
											$_tmp_data["value"] = $v["value"];

											if ($items[$key][$v["field"]] == $v["value"])
												$_tmp_data["checked"] = "checked";
											else
												$_tmp_data["checked"] = "";

										} else {									
											$_tmp_data["value"] = $items[$key][$v["value"]];

											if ($items[$key][$v["field"]])
												$_tmp_data["checked"] = "checked";
											else
												$_tmp_data["checked"] = "";																			
										}
									} else {
										$_tmp_data["value"] = $items[$key][$v["value"]];
									}

									$items[$key][$k] = $template->blocks["SimpleListMultiple"]->Replace(array(
															"value" => $_tmp_data["value"],
															"checked" => $_tmp_data["checked"],
															"field" => $v["field"] , 
															"subfield" => $items[$key][$v["subfield"]],
															"name" => $v["field"],
															"_count" => $items[$key]["original_count"]
														));
								break;

								case "color":

									$items[$key]["original_" . $k] = $items[$key][$k];

									$items[$key][$k] = $template->BlockReplace(
										"colorpickerdisabled",
										array(
											"value" => $items[$key][$k]
										)
									);
								break;


								case "field":
									$items[$key]["original_" . $k] = $items[$key][$k];

									$items[$key][$k] = $template->blocks["SimpleListFieldInput"]->Replace(array(
															"value" => $items[$key][$v["field-value"]] , 
															"field" => $v["field-id"] , 
															"_count" => $items[$key]["original_count"],
															"size" => $v["field-size"],
															"align" => $v["field-align"], //? "align=\"{$v['field-align']}\"" : "",
															"id" => $items[$key][$v["field-id"]],
															"field-type" => $v["field-type"],	
															"field-sub" => $v["field-sub"] ? "[" . $v["field-sub"] . "]" : "",
															"width"	=> $v["field-width"],
														));
									
								break;

								case "eval":
									eval("\$items[\"\$key\"][\"\$k\"] = " . $v["value"]);							
								break;

								case "langs":
									if ($form["table_lang"]) {
										$tmp = $this->db->Linear($this->db->QFetchRowArray("SELECT lang_id FROM " . $this->tables[$form["table_lang"]] . " WHERE {$form[table_uid]}=" . $items[$key][$form["table_uid"]]));

										foreach ($tmp as $_k => $_v) {

											if ($form["languages"][$_v]["code"]) {
												$tmp[$_k] = $template->blockREplace(
													"LangsTitle",
													array(
														"code"	=> $form["languages"][$_v]["code"]
													)
												);
											} else {
												unset($tmp[$_k]);
											}
											
										}
										
										$items[$key][$k] = implode("" , $tmp);
									}
									
								break;

								case "columns":

									if (defined("STP_LAYOUT_GRID") && (STP_LAYOUT_GRID == "BS3")) {
										$items[$key][$k] = $template->BlockReplace(
											"bootstrapcolumnsshowBS3",
											array(
												"main"		=> $items[$key][$k] ? $items[$key][$k] : "--",
												"desktop"	=> $items[$key][$k . "_desktop"] ? $items[$key][$k . "_desktop"] : "--",
												"tablet"	=> $items[$key][$k . "_tablet"] ? $items[$key][$k . "_tablet"] : "--",
												"phone"		=> $items[$key][$k . "_phone"] ? $items[$key][$k . "_phone"] : "--",
											)
										);
									} else {
										$items[$key][$k] = $template->BlockReplace(
											"bootstrapcolumnsshow",
											array(
												"main"		=> $items[$key][$k] ? $items[$key][$k] : "--",
												"lg"		=> $items[$key][$k . "_lg"] ? $items[$key][$k . "_lg"] : "--",
												"md"		=> $items[$key][$k . "_md"] ? $items[$key][$k . "_md"] : "--",
												"sm"		=> $items[$key][$k . "_sm"] ? $items[$key][$k . "_sm"] : "--",
												"xs"		=> $items[$key][$k . "_xs"] ? $items[$key][$k . "_xs"] : "--",
											)
										);
									}

								break;

								default:

									//if ($v["html"] != "true") 
										//$items[$key][$k] = htmlentities($items[$key][$k]);
									
									$items[$key][$k] = $items[$key][$k] ? $items[$key][$k] : ($v["default"] ? $v["default"] : "&nbsp;");
									
								break;
							}							
							

	//!!!!!!!!!!!!!!!!!!!!!!						//
	// might be a gix but as well may fuck everithing
							switch ($v["type"]) {

								case "image":
								break;

								default:
									$items[$key][$k] = str_replace("&amp;","&",$items[$key][$k]);

									if ($v["maxchars"]) {
										$items[$key][$k] = substr($items[$key][$k],0,$v["maxchars"]) . (strlen($items[$key][$k]) > $v["maxchars"] ? ($v["maxchars_text"] ? $v["maxchars_text"] : $this->__default["list"]["fields"]["maxchars_text"]) : "");
									}
							
									if (($v["html"] != "true") && !$v["link"]) {

			//added the bbcode		
										if ($v["bbcode"] == "true") {
											$items[$key][$k] = CBBCode::Convert($items[$key][$k],"");							
										} else {
											if ($v["nolink"] != "true") {

												/*** make sure there is an http:// on all URLs ***/
												$items[$key][$k] = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2",$items[$key][$k]);
												/*** make all URLs links ***/
												$items[$key][$k] = preg_replace("/([\w]+:\/\/[\w-?&;#+~=\.\/\@]+[\w\/])/i","<a target=\"_blank\" href=\"$1\">$1</A>",$items[$key][$k]);
												/*** make all emails hot links ***/
												$items[$key][$k] = preg_replace("/([\w-?&;#~=\.\/]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))/i","<A HREF=\"mailto:$1\">$1</A>",$items[$key][$k]);

											}
										}
									}
								break;
							}

		
							//if ($v["protected"])
							//debug($this->__isProtected($v["protected"] , $items[$key]));
						

							//check for protection
							if ($v["protected"] && $this->__isProtected($v["protected"] , $items[$key]) ) {
								//remove preffix and suffix
								$v["preffix"] = $v["suffix"] = "";
								$items[$key][$k] = "&nbsp;";
							} else {

								if (($v["preffix"] || $v["suffix"]) && !$items[$key]["original_" . $k]) {
									$items[$key]["original_" . $k] = $items[$key][$k];

								}
								

								$items[$key][$k] = $v["preffix"] . ( strtoupper($v["allownl"]) == "TRUE" ? nl2br($items[$key][$k]) : $items[$key][$k] ). $v["suffix"];

								//check to see if there is a tag set called link
								if ($v["link"]) {
									//okay, this field must be a link

									$tmp = $this->templates->BlockReplace(
										"ListLink",
										array(
											"link" => $v["link"],
											"title" => $items[$key][$k]
										)
									);

									$tmp = CTemplateStatic::Replace($tmp , $items[$key]);
									$tmp = CTemplateStatic::Replace($tmp , $global_vars);

									//backup the original 
									if (!$items[$key]["original_" . $k])
										$items[$key]["original_" . $k] = $items[$key][$k];
									
									$items[$key][$k] = CTemplateStatic::REplace($tmp , $items[$key]);
								
								
								}
								
								if ($v["nobr"] == "true") {
									$items[$key][$k] = "<nobr>" . $items[$key][$k] . "</nobr>";
								}					

								//format the font style apearing in the column
								// can be b,u,i meaning <b></b> , etc
								
								if ($v["font"]) {
									//bread the font selements
									$__fonts = @explode("," , $v["font"]);
									if (is_array($__fonts)) {
										$font__pre = "";
										$font__after = "";

										foreach ($__fonts as $__font) {
											$font__pre = $font__pre . "<$__font>";
											$font__after = "</$__font>" . $font__pre;
										}
										
										$items[$key][$k] = $font__pre . $items[$key][$k] . $font__after;
									}							
								}

								//format the color of the font for the text from the column, 
								//allows font color and background speared w/ :, can be only one too.
								if ($v["color"]) {
									$colors = @explode(":" , $v["color"]);
									if (count($colors) == 1)
										$style = "color: {$colors[0]}";
									else
										$style = "color: {$colors[0]};backgrond: {$colors[1]}";

									//add a span w/ color info
									$items[$key][$k] = "<span style=\"{$style}\">" . $items[$key][$k] . "</span>";							
								}												
							}
						}						
					}

				}				

				//adding the fucking buttons
				if (is_array($form["buttons"])) {
					foreach ($form["buttons"] as $key2 => $val2) {

						if ($key2 != "set") {

							if ($val2["protected"] && $this->__isProtected($val2["protected"] , $items[$key2])) {
							} else {

								//do a replace with the values from the item
								$this->templates->blocks["Temp"]->input = $val2["location"];						
								$this->templates->blocks["Temp"]->input = $this->templates->blocks["Temp"]->Replace($global_vars);
								$val2["location"] = $this->ProcessLinks($this->templates->blocks["Temp"]->Replace(array_merge($items[$key],$global_vars)));

								//do an extra replacement for space with %20
								$val2["location"] = str_replace(" ","%20" , $val2["location"]);
								$val2["title"] = $val2["title"];
								$val2["onmouseout"] = $val2["onmouseout"];
								$val2["onmouseover"] = $val2["onmouseover"];
								$val2["onclick"] = $val2["onclick"];
								$val2["target"] = $val2["target"];

								$items[$key]["buttons"] .=
										($form["buttons"]["set"]["buttonsvert"] == "true" ? "<tr><td height=3></td></tr><tr>" : "" ). 
										$template->blocks["Button"]->Replace($val2) . 
										($form["buttons"]["set"]["buttonsvert"] == "true" ? "</tr>" : "" );
							}
						}
					}
					
					//do a check for the cases when all buttons were protected
					if ( $items[$key]["buttons"] == "") {
						$items[$key]["buttons"] = "&nbsp;";
					}
					
				} else {
					$items[$key]["buttons"] = "";
				}

			//add the alternance field here
			if ($form["alternance"] == "true") {
				$items[$key]["_alternance"] = $this->_tmpAlternance ? "Alt" : "";
				$this->_tmpAlternance = $this->_tmpAlternance ? 0 : 1;
			} else
				$items[$key]["_alternance"] = "";

			}	
			

			if ($this->functions["process_record"]) {
				foreach ($items as $key => $val) {
					$items[$key] = call_user_func($this->functions["process_record"] , $val);
				}
				
			}

		}

		
		return $items;
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function SimpleList($form , $items = "", $count = "", $extra = null , $search = false , $returnArray  = false) {

		global 
			$_CONF , 			
			$form_errors , 
			$_USER , 
			$base,
			$form_countries, 
			$form_months,
			$form_US_states,
			$form_RO_states,
			$form_CA_states;

		if (is_array($form["order"]) && ($form["order"]["drag"] == "true")) {


			if (!$this->__isRestricted($form["order"]["restricted"])) {	


				if (!$form["order"]["acl"] || ($this->aclMod && $form["order"]["acl"] && $base->acl->checkModRule($this->aclMod , $form["order"]["acl"]))) {

					$form["fields"]["button_reorder"] = array(
						"type"		=> "button",
						"width"		=> "20",
						"align"		=> "center",
						"button"	=> $form["order"]["button"] ? $form["order"]["button"]  : "reorder",
						"location"	=> "javascript:void(0);"
					);

					$form["header"]["nolinks"] = "true";

				} else {
					unset($form["order"]);
				}


			} else {
				if (isset($form["header"]["nolinks"])) {
					unset($form["header"]["nolinks"]);
				}				
				if (isset($form["header"])) {
					unset($form["order"]);
				}
			}

		} else {
			if (is_array($form["order"])) {
				unset($form["order"]);
			}			
		}


		if ($form["table_lang"] && !($form["lang"] == "false")) {

			if ($form["table_lang"] && !$form["languages"]) {
				$tmp = CXMLFormLanguage::LanguageButtons();
				foreach ($tmp as $key => $val) {
					$form["languages"][$val["id"]] = $val;
				}
			}

			$cnt = count($form["languages"]);
			if ( $cnt > 1) {
				
				$size = "1%";
				if ($cnt > 10 ) {
					$size = 160;
				} elseif ($cnt > 4 ) {
					$size = 120;
				} elseif ($cnt > 2) {
					$size = 80;
				} 
				
				array_unshift(
					$form["fields"],
					array(
						"type"		=> "langs",
						"width"		=> $size,
						"align"		=> "center",
						"header"	=> "Lang."
					)
				);

			}
			

		}
		//add the extra button if order exists

		if (is_array($form["vars"])) {
			foreach ($form["vars"] as $key => $val) {
				//echeking if the default must be evaluated
				if ($val["action"] == "eval") {
					eval("\$val[\"import\"] = " . $val["default"] .";");
				}

				switch ($val["type"]) {
					case "eval":
						eval("\$tpl_vars[\"$key\"] = " . $val["import"] . ";");
					break;
					case "complex_eval":
						eval($val["import"]);
					break;

					case "var":
						$tpl_vars[$key] = $val["import"];
					break;
				}													
			}
		}
		//$tpl_vars = array_merge($tpl_vars);
		$global_vars = $this->GlobalVars($form);

		if (!is_array($items) || !is_array($items["items"])) {
			if ($form["table"]) {
				$records = $this->__simple_list_load_records($form);
			}
			
			$items		= $records["items"];
			$sortable	= $records["table_fields"];
			$count		= $records["count"];

		} else {

			if (array_key_exists("items" , $items)) {
				$count = $items["count"];

				if ($items["norecords"])
					$form["norecords"] = $items["norecords"];
				
				$sortable = $items["table_fields"];
				$items = $items["items"];

			} else {
			
				$items	= $items;
				$count = $count ? $count : count($items) ;
			}
		}


		$__tables = $records["tables"];
		$sql_vars = $records["sqlvars"];

		$has_paging = $records["count"] > count($records["items"]);
		


		if ($returnArray == true) {
			return array(
						"items" => $items,
						"count" => $count,
						"table_fields"	=> $sortable,
					);
		}


		//check if ordering field is acctivated disable the reordering
		if (is_array($form["order"])) {
			//$form["header"]["nolinks"] = "true";
		}
		

		$_new_count = $start;

		$html = new CHtml();

		$form = $this->Process($form);

		$template = &$this->templates;


		if ($this->functions["process_records"]) {
			$data = call_user_func_array($this->functions["process_records"], array( $items , $count));

			$items = $data["items"];
			$count = $data["count"];
		}


		$items = $this->__simple_list_process_items($form , $items);
				
		$_html = new CXMLSimpleList($form , array( "items"	=> $items , "count" => $count , "table_fields" => $sortable), $this->tables );
		$_html->setAclMod($this->aclMod);
		return $_html->Process();




		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function InsertField( $params ) {
		//for the momment it dont support complex fields like referers, and multiple

		//preparing the input vars
		$form["fields"]["temp"] = $params;
		$values["values"][$params["name"]] = $params["value"] ;

		//draw the element
		return $this->DrawElement ( $form , "temp" , $values ); 
	}
		
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DrawElement( $form , $_field , &$values , $draw_referer = 0 ) {

		global $_SESS , 
				$_CONF,
				$form_RO_states,
				$form_US_states,
				$form_CA_states,
				$form_countries , 
				$form_timezones , 
			
				$_VARS , 
				$_USER , 
				$base , 
				$_TSM , 
				$_SESS , 
				$form_months;


		

		$field = $form["fields"][$_field];

		if ($field["restricted"] && $this->__isRestricted($field["restricted"] , $values["values"])) {
			return "";
		}
		
		$field["_end_char"] = $field["title"] ? ":" : "";



		//add a special type
		if ($field["type"] == "after_save") {
			$form["fields"][$_field] = $field = array(	
						"type" => "droplist",
						"name" => "after_save",
						"default" => "\$_GET[after_save];",
						"action" => "eval",
						"title" =>  "After Save",
						"options" => array(
											"0" => "return to previous page",
											"1" => "add a new record"
										)													
					);
		}
		



		//doing a precheck in case there are referers or multiples to elements which arent in xml
		if (!is_array($field))
			return "";		

		if (!$field["type"]) {
			return "";
		}

		if (is_string($field["default"])) {			
			if ((substr($field["default"],0,5) == "eval:")) {
				$field["action"] = "eval";
				$field["default"] = substr($field["default"],5);
			}
		}
		
		
		
		
		//a temporary solution for name loosing
		$field["name"] = $_field;

		if (!isset($values["values"][$field["name"]])) {		
			switch ($field["action"]) {
				case "eval":
					if (isset($field["default"]) && $field["default"])
						eval("\$field[\"value\"] = " . $field["default"] . ";");
				break;

				case "complex_eval":
					if (isset($field["default"]) && $field["default"])
						eval($field["default"]);
				break;

				case "value":
					$field["value"] = $values["values"][$field["default"]];
				break;

				default:
					$field["value"]	= $field["default"];
				break;
			}
		} else {
			
			$field["value"] = $values["values"][$field["name"]];
		}

		//somtimes i may want to force a specific value nomatter of what is already set
		if (isset($field["forcevalue"])) {
			switch ($field["action"]) {
				case "eval":
//					echo $field["forcevalue"];
					eval("\$field[\"value\"] = " . $field["forcevalue"] . ";");
				break;

				default:

					if (stristr($field["forcevalue"] , "eval:" )) {
						eval("\$field[\"value\"] = " . str_replace("eval:" , "" , $field["forcevalue"]) . ";");
					} else {					
						$field["value"] = $field["forcevalue"];
					}
				break;
			}

		}
		

//!!!!!!!!!!!!!!!!!!!!!!						//
// might be a gix but as well may fuck everithing
//			$field["value"] = "test";str_replace("&amp;","&",$field["value"]);


		//load data from external files
		if ((($field["type"] != "image")&&($field["type"] != "upload")) && is_array($field["file"]) && !($values["values"][$field["name"]]) && file_exists($_CONF["path"] . $_CONF["upload"] . $field["file"]["path"] . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"])) {
			$field["value"] = GetFileContents($_CONF["path"] . $_CONF["upload"] . $field["file"]["path"] . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"]);
		}		

		//prepare the description for fields
		if (is_array($field["description"])) {
			switch ($field["description"]["type"]) {
				case "file":
					$_description = GetFileContents(dirname($form["xmlfile"]) . "/" . $field["description"]["file"]);
					if ($field["description"]["html"] != "true") {
						$_description = htmlspecialchars($_description);
					}
					
				break;
			}

			$field["description"] = $_description;			
		} else {
			//if (isset($field["description"]) && ($field["html"] !="true"))		
				//$field["description"] = nl2br((str_replace("]" , ">" , str_replace("[" , "<" , $field["description"]))));
		}
		

		//strip the slashes from the value
//		$field["value"] = stripslashes($field["value"]);
			
		//checking if this file is a referer, and if i have to show the referers at this point
		if (! $draw_referer && (($field["referer"]) || ($field["multiple"] == "true")))
			return "";

		//parse the field for special events, onkeyup, down etc...
		$this->__private__handlers($field);

		//parse the fields form editable=false
		if ($field["editable"] == "false") {
			switch ($field["type"]) {
				case "textbox":
				case "textarea":					
					$field["type"] = "text";
					$field["required"] = $field["unique"] = $field["validate"];
					unset($field["description"]);
				break;
			}
		}
		

		//drawing the form elements
		switch ($field["type"]) {

			case "checkIMG"	:
				$field["required"] = "true";
				$field["validate"] = "A:8:8";
				$current_field = $this->templates->blocks["imgCheck"]->Replace($field);				
			break;

			case "textarea":
				$current_field = $this->__field__textarea($field , $values );				
			break;

			case "html":
				$current_field = $this->__field__html($field , $values );				
			break;

			case "file":				
				$current_field = $this->__field__file($field , $values);				
			break;

			case "colorpicker":
			case "password":
			case "textbox":
				$current_field = $this->__field__textbox($field , $values);				
			break;

			case "iframe":
				$current_field = $this->__field__iframe($field , $values);
			break;

			case "autocomplete":
				$current_field = $this->__field__autocomplete($field , $values);
			break;

			case "sql":
				$this->__field__sql($field , $values );
			case "text":

//				$field["value"] = $field["html"] == "true" ? $field["value"] : nl2br(htmlentities($field["value"]));
				$current_field = $this->__field__text($field , $values);
			break;

			case "hidden":
				$current_field = $this->__field__hidden($field , $values );

				$current_field_extra = "";
			break;

			case "button":			
			case "submit":			
				$current_field = $this->__field__button($field , $values);
			break;

			case "checkbox":			
				$current_field = $this->__field__checkbox($field , $values);
			break;

			case "vardump":			
				$current_field = $this->__field__vardump($field , $values);
			break;

//			case "minititle":			
//				$current_field = $this->__field__minititle($field);
//			break;

			case "radiolist":
			case "radio":
				$field["radio"] = "true";		
				$field["type"] = "radio";

				if (!isset($field["empty_text"]))
					$field["empty_text"] = $this->__default["show"]["radio"]["empty_text" . ($field["editable"] == "false" ? "_show" : "")];							

			
			case "checklist":
				if ($field["type"] == "checklist") {
					$field["checkbox"] = "true";
					$field["radio"] = "";
					$field["empty"] = "";
					$field["multi"] = "true";
				}
				
			case "relation":
				if ($field["type"] == "relation")
					$field["editable"] = "false";

			case "double":			
			case "doubleselect":			

			case "USstates":								
			case "fileslist":								
			case "folderlist":								
			case "usstates":								
			case "droplist":				
			case "countries":
			case "CAstates":
			case "castates":
			case "ROstates":			
			case "timezone":			
			case "timezones":			
			case "rostates":						
			case "languages":						
				$current_field = $this->__field__droplist($field , $values );
			break;

//			case "responsive":						
//				$current_field = $this->__field__responsive($field , $values );
//			break;

			case "upload":
			case "image":
				$current_field = $this->__field__image($field , $values  , $form);
			break;

			case "comment":
				$current_field = $this->__field__comment($field , $values , $form);
			break;

			case "date":
				$current_field = $this->__field__date($field , $values );
			break;

			case "multiple":
				//cheking for multiple ellements
				
				if (is_array($field["multiple"])) {
					foreach ($field["multiple"] as $key => $val) {
						$current_field .= $this->DrawElement($form , $key , $values , 1);
					}					
				}
			break;


			case "ccard":				
			case "creditcard":
				$current_field = $this->__field__creditcard($field , $values);							
			break;

			case "namesort":
				$current_field = $this->__field__namesort($field , $values );							
			break;

			case "time":
			case "calendar":
				$current_field = $this->__field__calendar($field , $values);
			break;

			case "columns":
				$current_field = $this->__field__bootstrap_columns($field, $values);
			break;

			case "widths":
				$current_field = $this->__field__bootstrap_widths($field, $values);
			break;

		}

		//if the field hs description then i add the valign code
		$current_field_extra = ""; 


		//add the link if exists
		if ($field["link"]) {

			$tmp_tpl = new Ctemplate( '<a href="' . $field["link"] . '">'  . $current_field . '</a>'  , "string");
			$current_field = $tmp_tpl->Replace($values["values"]);
		}
				

		$element["type"] = $field["editable"] == "false" ? "text" : $field["type"];
		$element["width"] = $field["width"];

		if ($field["hidden"] != "true") {

			if (is_array($field["help"])) {

				$element["_helptopic"] = $this->templates->blocks["ElementHelpTopic"]->Replace(array(
						"location" => ($field["help"]["location"] == "module" ? dirname($form["xmlfile"]) . "/" : "") . $field["help"]["file"]
					));
			} else 
				$element["_helptopic"] = "";

				
			if (is_array($field["preffix"])) {
				foreach ($field["preffix"] as $key => $val) {
					if ((substr($val,0,5) == "eval:")) {
						eval("\$val = " . str_replace("eval:" , "" , $val));;
					}
					$field["preffix"][$key] = $val;
				}

				$field["preffix"] = implode("" , $field["preffix"]);				
			}

			if (is_array($field["suffix"])) {
				foreach ($field["suffix"] as $key => $val) {
					if ((substr($val,0,5) == "eval:")) {
						eval("\$val = " . str_replace("eval:" , "" , $val));;
					}
					$field["suffix"][$key] = $val;
				}

				$field["suffix"] = implode("" , $field["suffix"]);				
			}

			if ((substr($field["suffix"],0,5) == "eval:")) {
				eval("\$field[\"suffix\"] = " . str_replace("eval:" , "" , $field["suffix"]));;
			}

			if ((substr($field["preffix"],0,5) == "eval:")) {
				eval("\$field[\"preffix\"] = " . str_replace("eval:" , "" , $field["preffix"]));;
			}
			

			$element["_suffix"] = trim($field["suffix"]) != "" ? $this->templates->blocks["ElementSuffix"]->Replace($field) : "";
			$element["_prefix"] = trim($field["preffix"]) != "" ? $this->templates->blocks["ElementPrefix"]->Replace($field) : "";

			//checking if this element isnt a referer
			if (!isset($field["referer"])) {

				//building the element structure ( title, description, etc )				
				$element["title"] = $field["title"];

				$element["lang_data"] = $field["lang"] == "true" ? $field["lang_data"] : "";
				//$element["lang_data"] = $field["lang_data"];
				//add the id used for javascript thingx
				$element["name"] = str_replace("[]" , "" , $field["name"]);

				$element["_end_char"] = $field["title"] ? ":" : "";
				$element["align"] = $field["align"] ? $field["align"] : "left";
				
				//replacing ]n with <br> in descriptions
				$field["description"] = $field["description"];
				$element["_description"] = $field["description"] ? $this->templates->blocks["Description"]->Replace($field) : "";

				$element["_element"] = $current_field;

				$element["_element"] = $this->templates->blocks["ElementInner"]->Replace(
					$element
				);

				//cheking if this element has referers

				if (!is_array($field["referers"]) && isset($field["referers"])) {
					$tmp = explode("," , $field["referers"]);
					if (is_array($tmp)) {
						$field["referers"] = array();
						foreach ($tmp as $_tmp => $referer) {
							$field["referers"][$referer] = "true";
							//alter the form too
							if (is_array($form["fields"][$field["name"]]) ) {

								if (!is_array($form["fields"][$field["name"]]["referers"])) {
									$form["fields"][$field["name"]]["referers"] = array();
								}
								

								$form["fields"][$field["name"]]["referers"][$referer] = "true";							
							}
							
						}						
					}					
				}
				
				
				if (is_array($field["referers"])) {
					$_cnt = 0;
					foreach ($field["referers"] as $key => $val) {

						//also alter the fields which are used as referers
						if (is_array($form["fields"][$key])) {
							$form["fields"][$key]["referer"] = $field["name"];
						}

						$element["_element"] .= $this->DrawElement($form , $key , $values , 1) ;
						$_cnt ++;
					}

					$element["_element"] = $element["_element"];
				}

				//adding the preffix and suffix
								
				$element["_extra"] = $current_field_extra;
				$element["_extra_code"] = $field["_extra_code"];
		

				$element["_required"] = $field["required"] == "true" ? trim($this->templates->blocks["RequiredMark"]->output) : "";
				$element["_required_error"] = $values["errors"][str_replace("[]" , "" , $field["name"])] ? trim($this->templates->blocks["Required"]->output) : "";



		

				if (($field["multiple"] == "true") && $draw_referer ){
						return $this->templates->blocks["ElementMultipleBody"]->Replace($element);
				}

				if ($field["type"] == "multiple") {
					if ($form["alternance"] == "true") {
						$this->_tmpAlternance = $this->_tmpAlternance ? 0 : 1;
						$vars["_alternance"] = $this->templates->blocks["Alternance" . $this->_tmpAlternance]->output;

						$this->templates->blocks["Temp"]->input = $this->templates->blocks["ElementMultiple"]->Replace($element);
						return $this->templates->blocks["Temp"]->Replace($vars);
					} else					
						return $this->templates->blocks["ElementMultiple"]->Replace($element);
				}

							

				if ($field["extend"] != "true") {


						switch ($field["type"]) {
							case "subtitle":
/*
								$skin = ++$this->skin;

								if ($skin > count($this->skins)) {
									$skin = 1;
								}								

								$element["skin"] = $this->skins[$skin];
*/
								$element["skin"] = $field["skin"] ?$field["skin"] : $form["skin"];
								$element["collapsed"] = $field["nocollapse"] ? "no-collapse" : ($field["collapsed"] ? "collapsed" : "collapsed open");

								return $this->templates->blocks["Subtitle"]->Replace($element);
							break;

							case "minititle":
								$element["collapsed"] = "";
								$element["skin"] = $field["skin"] ?$field["skin"] : $form["skin"];
								return $this->templates->blocks["Minititle"]->Replace($element);
							break;
							

							case "comment":
								return $current_field;
							break;

							default:
								return $this->templates->blocks["Element" /*. ($field["dir"] == "rtl" ? "RTL" : "")*/]->Replace($element);
							break;
						}
				} else {
					//change since version 0.7,
					//added the title block separed then the main one

					if (is_object($this->templates->blocks["ExtendElementTitle"])) {
						if ($element["title"])
							$element["element_title"] = $this->templates->blocks["ExtendElementTitle"]->Replace($element);
						else
							$element["element_title"] = "";
					} else {
						$element["element_title"] = "";
					}
					

					return $this->templates->blocks["ExtendElement"]->Replace($element);
				}
			} else {
				//adding the preffix and suffix
//				$element["_suffix"] = $field["suffix"];
//				$element["_preffix"] = $field["preffix"];
				$element["_element"] = $current_field;

//				$element["_element"] = $this->templates->blocks["ElementInner"]->Replace(
//					$element
//				);
	
				//if the element is only a referer return only the form
				return $draw_referer ? $this->templates->blocks["ElementInner"]->Replace($element): "";
			}

		} else {
			return $current_field;
		}

	}

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


		$tabs = new CFormsTabs($tabs);
		return $tabs->Render();

	}
	
		
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Show($form = array(), $values = array()  , $extra = array()) {
		global $_CONF , $_USER, $_SESS, $form_errors , $_LANG_ID , $base;

		if (is_array($form))
			$form = $this->Process($form);
		else 
			$form = $this->form;

		if ($form["editable"] == "false") {
			$this->__private__showonly($form);
		}
	
		
		//values structure
		/*
			<values>
				<error>Field already exists</error>

				<fields>
					<name>jon doe</name>
					<address>eartch </earth>
					...

				</fields>
			</values>
		*/

		if (is_array($form["vars"])) {
			foreach ($form["vars"] as $key => $val) {
				//echeking if the default must be evaluated
				if ($val["action"] == "eval") {
					eval("\$val[\"import\"] = " . $val["default"] .";");
				}
				
				switch ($val["type"]) {
					case "eval":
						eval("\$tpl_vars[\"$key\"] = " . $val["import"] . ";");
					break;

					case "value":
						$tpl_vars[$key] = $values["values"][$val["import"]];
					break;

					case "complex_eval":
						eval($val["import"]);
					break;

					case "var":
						$tpl_vars[$key] = $val["import"];
					break;
				}													
			}
		}

		// force the alternance to be allsways on
//		$form["alternance"] = "true";

		$tpl_vars = array_merge((array)$tpl_vars , $globalvars = $this->GlobalVars($form));

		//debug($tpl_vars,1);


		$form["_language_data"] = $this->LanguageButtons($form);

		//i have a form with multiple boxes
		if (!is_array($form["fields"]["returnurl"]) && ($tpl_vars["self.previous"] != "")) {
			$form["fields"]["returnurl"] = array(
													"type" => "hidden",
													"default" => $globalvars["self.previous_enc"]
												);
		}


		if (!is_array($form["fields"]["request_uri"])) {
			$form["fields"]["request_uri"] = array(
				"type"	=> "hidden",
				"default"	=> $_SERVER["REQUEST_URI"],
			);
		}
		

		$form["fields"]["lang_id"] = array(
			"type"	=> "hidden",
			"default"	=> $_GET["lang_id"],
		);


		if (is_array($form["fields"])) {

			$field_count = 0;

			$lang_buttons = false;
		
			foreach ($form["fields"] as $key => $field) {
				

				if (($key == "box") && is_array($form["fields"]["box"])) {


					$content = $this->templates->blockReplace("BoxEndWidget" , array());


					$size = 0;					
					
					foreach ($form["fields"]["box"] as $key_box => $box) {						

						//preinit some default values for the boxes
						$box["xmlfile"] = $form["xmlfile"];
						$box["skin"] = $box["skin"] ? $box["skin"]: $form["skin"];
						$box["collapsed"] = $box["nocollapse"] ? "no-collapse" : ($box["collapsed"] ? "collapsed" : "collapsed open");
						$box_content = "";
						$box["uridata"] = $form["uridata"];
						$box["uridata"] = $form["urilinks"];

						if (is_array($box["fields"])) {
							foreach ($box["fields"] as $_key => $_field) {

								if ($_field["lang"] == "true") {
									$lang_buttons = true;
								}
								


								if (is_array($box["fields"])) {

									//checking for <code> field
									if (!$_field["name"])
										$box["fields"][$_key]["name"] = $_key;

									if ($_field["protected"] && $this->__isProtected($_field["protected"] , $values["values"]) && ($_field["showprotected"] == "true")) {
										
										//do some forms replacement
										$box["fields"][$_key]["type"] = "text";
										$box["fields"][$_key]["validate"] = "";
										$box["fields"][$_key]["required"] = "";
										$box["fields"][$_key]["unique"] = "";
										$box["fields"][$_key]["description"] = "";

										unset($_field["protected"]);
									}
									

									//check to see if it isnt a protected field, usefull for admin
									if (($_field["protected"] && $this->__isProtected($_field["protected"] , $values["values"])) || ($_field["restricted"] && $this->__isRestricted($_field["restricted"] , $values["values"]))) {
									} else {				
								
										//empty some variable for each field
										$element = array();
										$current_field_extra = "";
										$current_field = "";

										//do a precheck for values, to load it from _POST, _GET _SESSION _FILE _COOKIE
										if (!@isset($values["values"][$_field["name"]]) && @isset($GLOBALS[$_field["get"]][$_field["name"]]))  {
											$values["values"][$_field["name"]] = $GLOBALS[$_field["get"]][$_field["name"]];
										}

										if (isset($extra["fields"][$_key]))
											$box["fields"][$_key]["_extra_code"] = $extra["fields"][$_key];
										else					
											$box["fields"][$_key]["_extra_code"] = "";

									
										$box_content .= $this->DrawElement($box , $_key, $values);
									}
								}
							}
						}


						if ($size == 0) {
							$content .= $this->templates->blockReplace("BoxRowStart" , array());
						}

						$size += $box["width"];				

						if ($size > 12) {

							$content .= $this->templates->blockReplace("BoxRowEnd" , array());					
							$content .= $this->templates->blockReplace("BoxRowStart" , array());
							$size = 0;

						}


						$content .= $this->templates->blockReplace(
							"Box",
							array(
								"skin"		=> $box["skin"],
								"id"		=> $box["id"] ? $box["id"] : ++$bid,
								"title"		=> $box["title"],
								"content"	=> $box_content,
								"size"		=> $box["width"],
								"collapsed"	=> $box["collapsed"],


							)
						);

						
					}
					
					if ($size == 12) {
						$content .= $this->templates->blockReplace("BoxRowEnd" , array());					
						$size = 0;
					}




					$form["_template_data"] .= $content;

				} else {			
					//checking for <code> field
					if (!$field["name"])
						$form["fields"][$key]["name"] = $key;

					if ($field["lang"] == "true") {
						$lang_buttons = true;
					}


					if ($field["protected"] && $this->__isProtected($field["protected"] , $values["values"]) && ($field["showprotected"] == "true")) {
						
						//do some forms replacement
						$form["fields"][$key]["type"] = "text";
						$form["fields"][$key]["validate"] = "";
						$form["fields"][$key]["required"] = "";
						$form["fields"][$key]["unique"] = "";
						$form["fields"][$key]["description"] = "";

						unset($field["protected"]);
					}
					

					//check to see if it isnt a protected field, usefull for admin
					if (($field["protected"] && $this->__isProtected($field["protected"] , $values["values"])) || ($field["restricted"] && $this->__isRestricted($field["restricted"] , $values["values"]))) {
					} else {				
				
						//empty some variable for each field
						$element = array();
						$current_field_extra = "";
						$current_field = "";

						//do a precheck for values, to load it from _POST, _GET _SESSION _FILE _COOKIE
						if (!@isset($values["values"][$field["name"]]) && @isset($GLOBALS[$field["get"]][$field["name"]]))  {
							$values["values"][$field["name"]] = $GLOBALS[$field["get"]][$field["name"]];
						}

						if (isset($extra["fields"][$key]))
							$form["fields"][$key]["_extra_code"] = $extra["fields"][$key];
						else					
							$form["fields"][$key]["_extra_code"] = "";
						$form["_template_data"] .= $this->DrawElement($form , $key, $values);
					}
				}

			}
			
		}

		//fix the language buttons
		if (!$lang_buttons) {
			$form["_language_data"]  = "";
		}
		
		
			
		//adding the buttons
		if (is_array($form["buttons"])) {

			foreach ($form["buttons"] as $key => $val)
				//checking not to be a setting group

				

				if (($key != "set") && (!($val["protected"] && $this->__isProtected($val["protected"] , $values["values"]))) && (!($val["restricted"] && $this->__isRestricted($val["restricted"] , $values["values"]) ) )) {

					if (!$val["acl"] || ($this->aclMod && $val["acl"] && $base->acl->checkModRule($this->aclMod , $val["acl"]))) {
					

						$val = CXMLSimpleList::__oldButton($val);

						$val["icon"] = $val["icon"] ? $this->templates->BlockReplace("ButtonIcon" , $val) : "";

			//making a small trick to replace some vars in links, i hate this
						$this->templates->blocks["Temp"]->input = $val["location"];
						//replacing the values
						//also replaging the global variables defined for templates
						$this->templates->blocks["Temp"]->input = $this->templates->blocks["Temp"]->Replace($tpl_vars);

						$val["location"] = CryptLink(CTemplateStatic::Replace($val["location"] , $tpl_vars , $values["values"]));

						$val["onmouseout"] = $val["onmouseout"];
						$val["onmouseover"] = $val["onmouseover"];
						$val["onclick"] = $val["onclick"];
						$val["title"] = $val["title"];
						$val["target"] = $val["target"];

						$buttons .= $this->templates->blocks[$val["type"] == "submit" ? "ButtonSubmit" : "Button"]->Replace($val);
					}
				}

			if (	
					(($form["buttons"]["set"]["header"] == "true") && (count($form["buttons"])>1) ) 
					|| $form["subtitle"]) {

				$form["_header_buttons"] = $this->templates->blocks["HeaderButtons"]->Replace(array(
						"SUBTITLE" => ($form["subtitle"] ? $form["subtitle"] : "&nbsp;") , 
						"BUTTONS" => $form["buttons"]["set"]["header"] == "true" ? $buttons : "&nbsp" 
					)
				); 
			} else $form["_header_buttons"] = "";

			$form["_footer_buttons"] = $form["buttons"]["set"]["footer"] == "true" ? $this->templates->blocks["FooterButtons"]->Replace(array("BUTTONS" => $buttons)) : "";
		} else {
			$form["_header_buttons"] = $form["_footer_buttons"] = "";
			if (strlen($form["subtitle"])) {
				$form["_header_buttons"] =  $this->templates->blocks["HeaderButtons"]->Replace(array(
						"SUBTITLE" => ($form["subtitle"] ? $form["subtitle"] : "&nbsp;") , 
						"BUTTONS" => "&nbsp" ));
			}
			//return empty variable
				
		}

		//check and add the error message
		if ($values["error"])
			$form["_error"] = $this->templates->blocks["Error"]->Replace(array("error" => $values["error"] ));		
		else
			$form["_error"] = "";


		//adduing the javascript to form
		$form["_pre_javascript"] = $form["javascript"]["pre"] ? "<script language=\"Javascript\">" . $form["javascript"]["pre"] . "</script>" : "";
		$form["_after_javascript"] = $form["javascript"]["after"] ? "<script language=\"Javascript\">" . $form["javascript"]["after"] . "</script>" : "";
		
		//adding the extra html
		$form["_pre_tabs"] = $this->DrawTabs($form["tabs"]);
		$form["_pre_html"] = (is_array($form["html"]["pre"]) && ($form["html"]["pre"]["type"] == "extern")) ? GetFileContents(dirname($form["xmlfile"]) . "/" . $form["html"]["pre"]["file"]) : html_entity_decode($form["html"]["pre"]);
		$form["_middle_html"] = (is_array($form["html"]["middle"]) && ($form["html"]["middle"]["type"] == "extern")) ? GetFileContents(dirname($form["xmlfile"]) . "/" . $form["html"]["middle"]["file"]) : html_entity_decode($form["html"]["middle"]);
		$form["_after_html"] = (is_array($form["html"]["after"]) && ($form["html"]["after"]["type"] == "extern")) ? GetFileContents(dirname($form["xmlfile"]) . "/" . $form["html"]["after"]["file"]) : html_entity_decode($form["html"]["after"]);

		//adding the pre extra and after extra
		$form["_pre_form"] = $extra["pre"];

		if ($form["fields"]["box"]) {
			$form["_after_form1"] = $extra["after"];
			$form["_after_form2"] = "";
		} else {
			$form["_after_form1"] = "";
			$form["_after_form2"] = $extra["after"];
		}

		

		//preprocess the post form
		//replace the form vars in the form action
		$this->templates->blocks["Temp"]->input = $form["action"];
		$form["action"] = CryptLink($this->templates->blocks["Temp"]->Replace($tpl_vars));

		//process target and on submit
		$form["target"]	= $form["target"] ? " target=\"{$form['target']}\" " : "";
		$form["onsubmit"]	= $form["onsubmit"] ? " onsubmit=\"{$form['onsubmit']}\" " : "";


		//drawing the form
		$form["_template_data"] = $form["_template_data"] == "" ? "" : $form["_template_data"];

		if ($form["titlebar"] == "hide") {
			$form["_template_data"] = $this->templates->blocks["FormNoTitle"]->Replace($form);
		} else {		

			if (is_array($form["title"])) {
				$form["title"] = $form["title"]["default"];
			} 


			if (is_array($form["title"])) {

				foreach ($form["title"]["options"] as $key => $val) {


					if (!$val["acl"] || ($this->aclMod && $val["acl"] && $base->acl->checkModRule($this->aclMod , $val["acl"]))) {

						if ($val["restricted"] && CForm::__isRestricted($val["restricted"] , $values)) {
							unset($form["title"]["options"][$key]);
						} else {
						

							$act = $this->__evalValue($val["active"]);

							$val["icon"] = $val["icon"] ? $this->templates->blockReplace("TitleMenuIcon" , $val) : "";

							if ($act) {
								$title = $val;
								$form["title"]["options"][$key]["active"] = $this->templates->blockReplace("TitleMenuActive");

								//unset($forms["title"]["options"][$key]);
							} else {
								$form["title"]["options"][$key]["active"] = "";
							}

							$form["title"]["options"][$key]["icon"] = $val["icon"];
						}
					} else {
						unset($form["title"]["options"][$key]);
					}
				}
				

				$form["_title"] = $this->templates->blockReplace(
					"TitleMenu" ,
					array(
						"items"	=> $base->html->table(
							$this->templates , 
							"TitleMenu",
							$form["title"]["options"]
						),				
						
						"subtitle"	=> $title["title"],

						"icon"		=> $title["icon"],

						"details"	=> $form["title"]["subtitle"] ? $this->templates->blockreplace("TitleMenuSubtitle" , array("subtitle" => $form["title"]["subtitle"])) : "",

					)
				);

			} else {
				$form["_title"] = $this->templates->blockReplace("TitleText" , $form);
			}
			

			$form["_template_data"] = $this->templates->blocks["Form"]->Replace($form);
		}

		//adding the border
		if ($form["border"] == "true") {
			$form["_template_data"] = $this->templates->blocks["Border"]->Replace( $form );
		}

// no need to check this, i'll have the tpl vars all the time
//		if (is_array($form["vars"])) {
			//doing a double replace, in case there are unreplaced variable sfom "vars" type
			$this->templates->blocks["Temp"]->input = $form["_template_data"];
			$form["_template_data"] = $this->templates->blocks["Temp"]->Replace($tpl_vars);
//		}
		
		//adding the <form tag
		if ($form["formtag"] == "true") {
			$form["id"] = $form["id"] ? " id=\"" . $form["id"] . "\" " : "";
			$form["encoding"] = $form["encoding"] ? $form["encoding"] : "";
			$form["method"] = $form["method"] ? $form["method"] : "post";
			$form["_template_data"] = $this->templates->blocks["Action"]->Replace( $form );		
		}

		//$form["title"] = "x";

		//debug($form,1);

		return $this->__render($form["_template_data"] , $tpl_vars);
		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function LanguageButtons(&$form) {		

		if ($form["lang"] != "true") {
			return "";
		}
		

		if (!$form["table_lang"]) {
			return "";
		}
		
		
		if (!$form["languages"]) {
			$form["languages"] = CXMLFormLanguage::LanguageButtons();
		}

		global $base;

		if (is_array($form["languages"])) {

			if ($_REQUEST["lang_id"]) {
				$default = $_REQUEST["lang_id"];

				foreach ($form["languages"] as $key => $val) {
					if ($val["default"] && ( $default == $val["id"])){
						$is_default = true;
					}
				}
			} else {
				foreach ($form["languages"] as $key => $val) {
					if ($val["default"]) {
						$is_default = true;
						$default = $val["id"];
						$_GET["lang_id"] = $_POST["lang_id"] = $default;
					}					
				}
			}
			
			
			

			if (count($form["languages"] )> 1 ) {

				foreach ($form["languages"] as $key => $val) {							

					if ($val["id"] == $default) {
						$form["languages"][$key]["selected"] = $this->templates->blockReplace("LangsSelected" , array());
						$default_lang = $val;
					} else {						
						$form["languages"][$key]["selected"] = "";
					}
				}				


				//parepare the buttons
				if (is_array($form["fields"]["box"])) {
					foreach ($form["fields"]["box"] as $key => $val) {
						if (is_array($val["fields"])) {
							foreach ($val["fields"] as $k => $v) {
								$form["fields"]["box"][$key]["fields"][$k]["lang_data"] = $this->templates->blockReplace("LangsTitle" , $default_lang);
								$form["fields"]["box"][$key]["fields"][$k]["dir"] = $default_lang["dir"];

								

								if (!$is_default) {
									$form["fields"]["box"][$key]["fields"][$k]["required"] = "";
								}
								
							}							
						}
						
						
					}
					
				} else {
					if (is_array($form["fields"])) {
						foreach ($form["fields"] as $key => $val) {
							$form["fields"][$key]["lang_data"] = $this->templates->blockReplace("LangsTitle" , $default_lang);
							$form["fields"][$key]["dir"] = $default_lang["dir"];
							

							if (!$is_default) {
									$form["fields"][$key]["required"] = "";
							}
							
						}							
					}
				}

				
				if (is_array($form["languages"])) {
					$data = $_GET;
					foreach ($form["languages"] as $key => $val) {
						$data["lang_id"] = $val["id"];

						$val["details_link"] = "index.php?". http_build_query($data);

						$form["languages"][$key]["button"] = $this->templates->blockReplace($form["editable"] == "false" ? "LangsDetails" : "LangsEdit" , $val );
					}					
				}

				return $base->html->table(
					$this->templates , 
					"Langs" , 
					$form["languages"]
				);
			}
			
		}
		

		

	}
	

	/**
	* description defines the list of the global vars
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	static function GlobalVars($form = array(), $_FROM = array()) {
		global $_CONF , $_TSM , $_MODULES;

		// if no from was passed then get all the vars from get
		if (!count($_FROM))
			$_FROM = &$_GET;
		
		if ($_GET["returnurl"])
			$private_return = $_GET["returnurl"];

		if ($_GET["returnURL"])
			$private_return = $_GET["returnURL"];

		if ($_POST["returnurl"])
			$private_return = $_POST["returnurl"];

		$return_enc = urlencode($private_return);
		$return_dec = ($private_return);

		//do a check to be sure the decoded its valid
		
		
		$repl_count = 1;

		if ( substr($return_dec , 0 , 1) == "%" ){

			while ( substr($return_dec , 0 , 1) == "%" ) {
				$return_dec = urldecode($return_dec);
				$repl_count ++;
			}

		}

		//do another check
		if (strstr($return_enc  , '/'))
			$return_enc = urlencode($return_enc);


		$return = array (
			"self.conf.url" => $_CONF["url"],
			//script file name
			"self.file" => $_SERVER["PHP_SELF"],
			//the mod prepared for url
			"self.mod" => $_FROM['mod'] ? 'mod=' . $_FROM['mod'] . '&' : '',
			//the sub prepared for url
			"self.sub" => $_FROM['sub'] ? 'sub=' . $_FROM['sub'] . '' : '',
			//the action prepared for url
			"self.action" => $_FROM['action'] ? 'action=' . $_FROM['action'] . '' : '',

			//mod value, got from get
			"self.var.mod" => $_FROM['mod'],
			//sub value, got from get
			"self.var.sub" => $_FROM['sub'],
			//action value, got from get
			"self.var.action" => $_FROM['action'],

			//record id from database
			"self.uid" => $form["table_uid"],
			//record id from database encoded with {} to b replaced
			"self.uidvar" => '{' . strtoupper($form["table_uid"]) . '}',
			"self.request.uid.value"	=> $_REQUEST[$form["table_uid"]],
			
			//link with module and sub defined
			"self.link" => $_SERVER["PHP_SELF"] . "?" . ($_FROM['mod'] ? 'mod=' . $_FROM['mod'] . '&' : '') . ($_FROM['sub'] ? 'sub=' . $_FROM['sub'] . '&' : ''),
			//link with the record id
			//address of the current page
			"self.location" => urlencode(urlencode($_SERVER["REQUEST_URI"])),
			"self.location.link" => $_SERVER["REQUEST_URI"],

			//the title to apear in the box, depends of the action, edit or delete
			"self.title" => !$_FROM[$form["table_uid"]] || $_POST[$form["table_uid"]] ? "Add New " : "Edit ",

			//previus detected page ( link )
			"self.previous" => $private_return ? $return_dec : $form_errors["NO_BACK_LINK"],
			//previous detected page encoded link
			"self.previous_enc" => $private_return ? $return_enc : $form_errors["NO_BACK_LINK"],
				
			//ALIAS TO THE SELF ONES, DEPRECATED
			"private.get_mod" => $_FROM["mod"],
			"private.get_sub" => $_FROM["sub"],
			"private.get_action" => $_FROM["action"],
			"private.table_uid" => $form["table_uid"],
			"private.value_uid" => '{' . strtoupper($form["table_uid"]) . "}",

			//the title to apear in the editable boxes
			"private.form_action_title" => !$_FROM[$form["table_uid"]] || $_POST[$form["table_uid"]] ? "Add New " : "Edit ",

			//previus detected page ( link )
			"private.form_previous_page" => $private_return ? $return_dec : $form_errors["NO_BACK_LINK"],
			//previous detected page encoded link
			"private.form_previous_page_enc" => $private_return ? urlencode($return_enc) : $form_errors["NO_BACK_LINK"],
			//"private.form_previous_page_enc" => $private_return ? urlencode($return_enc) : $form_errors["NO_BACK_LINK"],

			//DEPRECATED, will be removed in future versions
			"current_page" => urlencode(urlencode($_SERVER["REQUEST_URI"])),


			"self.address.site"		=> str_replace("/admin" , "" , $_TSM["PRIV.BASE.HREF"]),
			"self.address.admin"	=> $_TSM["PRIV.BASE.HREF"],


			"module.pub.link"		=> $_MODULES["modules"]->getCurrentModuleLink(),
		);


		//build link uid. The main issues is when i have more fields in the table_uid

		$tmp = explode("," , $form["table_uid"]);

		$tmp_link = $_SERVER["PHP_SELF"] . "?" . ($_FROM['mod'] ? 'mod=' . $_FROM['mod'] . '&' : '') . ($_FROM['sub'] ? 'sub=' . $_FROM['sub'] . '&' : '');

		foreach ($tmp as $k => $v) {
			$_tmp[] = $v . "=" . '{' . strtoupper($v) . '}';
		}
		$return["self.linkuid"] = $tmp_link . implode("&" , $_tmp);


		if (is_array($_GET)) { 
			foreach ($_GET as $key => $val) { 
				$return["global.get." . strtolower($key)] = $val; 
			} 
		} 


		//autogenerate the reorder link if not exists

		if (!$form["urilinks"]["ajax.reorder-records"]) {
			//try to generate it from the storing link
			$form["urilinks"]["ajax.reorder-records"] = "{SELF.LINK}&action=ajax.reorder-records";
		}

		if (!$form["urilinks"]["ajax.download-file"]) {
			//try to generate it from the storing link
			$form["urilinks"]["ajax.download-file"] = "{SELF.LINK}&{SELF.UID}=" . 
				($_REQUEST[$form["table_uid"]] ? "{SELF.REQUEST.UID.VALUE}" : "{SELF.UIDVAR}") .
				"&action=ajax.download-file" . 
				($_REQUEST["module_id"] ? "&module_id={$_REQUEST[module_id]}" : "");

			$form["uridata"]["ajax.download-file"] = "ajax.download-file";
		}
		

		//ajax.reorder-records

		//add the url links
		if (is_array($form["urilinks"])) {
			foreach ($form["urilinks"] as $key => $val) {
				$return["self.uri.$key"] = $val;
			}			
		}

		//add the url links
		if (is_array($form["uridata"])) {
			foreach ($form["uridata"] as $key => $val) {
				$return["self.action.$key"] = $form["uridata"]["action"] . "=" . $val;
				$return["self.linkuid.$key"] = $return["self.linkuid"] . "&" . $return["self.action.$key"];
				$return["self.link.$key"] = $return["self.link"] . "&" . $return["self.action.$key"];
			}			
		}		


		//do a replace for the variables which are inside this variable
		//this is usefull whtn the generated variable looks like index.php?{SELF.MOD}...
		

//		debug($return,1);
		//use a temporary template, i hope this wont go to slow
		foreach ($return as $key => $val) {
			$return[$key] = CTemplateStatic::Replace($val , $return);
		}

		//double replacement for cetain files
		foreach ($return as $key => $val) {
			$return[$key] = CTemplateStatic::Replace($val , $return);
		}
		
		return $return;
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __private__handlers(&$field) {
		$events = array( 
					"tabindex" , 
					"accesskey" , 
					"onfocus" , 
					"onblur" , 
					"onselect" , 
					"onchange" , 
					"onclick" , 
					"ondblclick" , 
					"onmousedown" , 
					"onmouseup" , 
					"onmouseover" , 
					"onmousemove" , 
					"onmouseout" , 
					"onkeypress" , 
					"onkeydown" , 
					"onkeyup"
		);

		//check to see if find any existence of events in the field

		foreach ($events as $key => $val) {
			if (array_key_exists($val , $field))
				$final[] = " {$val}=\"" . $field[$val] ."\" ";
		}

		if (is_array($final))
			$field["handlers"] = implode("" , $final);		
		else
			$field["handlers"] = "";
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	static function __private__showonly(
						&$form = array(),
						$set = array ( 
										"description" => TRUE,
										"comments" => TRUE
									)
						) {
		
		//if (!count($form)) 
		//	$form = $this->form;

		$form = CForm::Process($form);

		if (is_array($form["title"]) && is_array($form["title"]["details"])) {
			$form["title"]["default"] = $form["title"]["details"];
		} 
		

		
		if (is_array($form["fields"])) {
			foreach ($form["fields"] as $key => $val) {


				if ($key == "box") {

					foreach ($val as $k => $box) {
						if (is_array($box["fields"])) {

							foreach ($box["fields"] as $_k => $_v) {

								//remove some of the fields
								unset($form["fields"]["box"][$k]["fields"][$_k]["required"]);
								unset($form["fields"]["box"][$k]["fields"][$_k]["validate"]);				

								if (($set["description"] == TRUE) && ($form["fields"]["box"][$k]["fields"][$_k]["type"] != "comment" ))
									unset($form["fields"]["box"][$k]["fields"][$_k]["description"]);

								//set the field editable
								$form["fields"]["box"][$k]["fields"][$_k]["editable"] = "false";

								switch ($_v["type"]) {
									case "textbox":
									case "textarea":
										$form["fields"]["box"][$k]["fields"][$_k]["type"] = "text";
									break;
									
									case "password":
										$form["fields"]["box"][$k]["fields"][$_k]["type"] = "text";
										$form["fields"]["box"][$k]["fields"][$_k]["forcevalue"] = "**********";
									break;

									case "comment":
										if (($set["comments"] == TRUE) && ($_v["ondetails"] != "true")) {
											unset($form["fields"]["box"][$k]["fields"][$_k]);
										}
									break;

									case "after_save":
										unset($form["fields"]["box"][$k]["fields"][$_k]);
									break;
								}
								

							}
						}
						
					}
					
					
				} else {			
					//remove some of the fields
					unset($form["fields"][$key]["required"]);
					unset($form["fields"][$key]["validate"]);				

					if (($set["description"] == TRUE) && ($val["type"] != "comment" ))
						unset($form["fields"][$key]["description"]);

					//set the field editable
					$form["fields"][$key]["editable"] = "false";

					switch ($val["type"]) {
						case "textbox":
						case "textarea":
							$form["fields"][$key]["type"] = "text";
						break;
						
						case "password":
							$form["fields"][$key]["type"] = "text";
							$form["fields"][$key]["forcevalue"] = "**********";
						break;

						case "comment":
							if (($set["comments"] == TRUE) && ($val["ondetails"] != "true")) 
								unset($form["fields"][$key]);
						break;

						case "after_save":
							unset($form["fields"][$key]);
						break;
					}
				}
			}	
		}

		$form["editable"] = "false";

		return $form;
	}		


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __private_generate_field($val) {
			return array(
						"type" => $val["item_type"],
						"title" => $val["item_set_title"] ? "" : $val["item_title"],
						"description" => $val["item_description"],

						"size" => $val["item_type"] == "textbox" ? $val["item_size_cols"] : ($val["item_type"] == "textarea" ? $val["item_size_cols"] . ":" . $val["item_size_rows"] : ""),

						"options" => $val["options"],
						"padding" => $val["item_type"] == "comment"  ? "20" : "",

						"empty" => $val["item_type"] == in_array($val["item_type"] , array("droplist" , "radiolist" , "checklist" , "usstates" , "rostates" , "castates")) ? "true" : "",
						"required" => $val["item_required"] ? "true" : "",
						"validate" => strtoupper($val["item_required_type"]) . ":" . $val["item_required_size_min"] . ":" . $val["item_required_size_max"],

						"preffix" => $val["item_set_preffix"],
						"suffix" => $val["item_set_suffix"],		

						"checked" => $val["item_type"] == "checkbox" ? "1" : "",

						//show the value only if is a details view
//															"value" => $__answer ? $__values[$val["item_id"]] : "",

						"label" => $val["item_set_label"],
						"empty" => $val["item_set_radio_empty"] ? "true" : "",
						"newline" => $val["item_set_radio_line"] ? "true" : "false"

					);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __private_tree($records , $parent , $record_id , $parent_field , $separator , $level = 0 , $full = array() , $location = array()) {

		if ($level && ($full["full"]!="true")) {
			for ($i = 1; $i<= $level; $i++) {
				$sep .= $separator;				
			}			
		}
		
		if (is_array($records)) {
			foreach ($records as $key => $val) {
				if ($val[$parent_field] == $parent) {
					$val["separator"] = $sep;
					if ($full["full"] == "true") {
						//$location[]  = $val[$full["field"]];
						
						$tmp = $location;
						$tmp[] = $val[$full["field"]];

						$val[$full["field"]] = implode($separator , $tmp);

						
					}

					$_records[] = $val;					
					$_records = array_merge((array)$_records , (array)CForm::__private_tree($records , $val[$record_id] ,$record_id , $parent_field , $separator , $level+1 , $full , $tmp));
				}				
			}			
		}

		
		if ($level == 0) {
//			debug($_records,1);
		}
		
				
		return $_records;
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	static function ProcessVariables($form , &$input) {
		$form = CForm::Process($form);


		if (is_array($form["fields"])) {

			$fields = Cform::AllFields($form);

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



				switch ($val["type"]) {

					case "textbox":
						if ($val["mask"] && $val["maskconvert"] != "false") {
							$input[$key]  = CForm::convertFromMask($val["mask"] , $input[$key]);
						}
					break;						

					case "ccard":
					case "creditcard":
						
						if (is_array($input[$key . "_arr"])) {
							$input[$key] = trim(implode("" , $input[$key . "_arr"] ));
						}						
					break;							

					case "calendar":

						if ($val["range"] == "true") {

								if (!is_numeric($input[$key . "_start"])) {
									$input[$key . "_start"] = strtotime($input[$key . "_start"]);
								}
								

								if (is_array($val["calendar"]) && $val["calendar"]["time"]) {


									if ($input[$key . "_end"] && !is_numeric($input[$key . "_end"])) {
										$input[$key . "_end"] = strtotime($input[$key . "_end"]) + 1;
									}
									
								} else {

									if ($input[$key . "_end"] && !is_numeric($input[$key . "_end"])) {
										$input[$key . "_end"] = strtotime($input[$key . "_end"]) + 3600 * 24 - 1;
									}

								}
								
						} else {					
							if ($input[$key]) {
								$input[$key] = strtotime($input[$key]);
							}
						}

						//process aditional fields

						if ($input[$key]) {
							$input[$key . "_year"] = date("Y" , $input[$key]);
							$input[$key . "_month"] = date("n" , $input[$key]);
							$input[$key . "_day"] = date("d" , $input[$key]);
							$input[$key . "_hour"] = date("H" , $input[$key]);
							$input[$key . "_minute"] = date("i" , $input[$key]);
							$input[$key . "_seconds"] = date("s" , $input[$key]);
						}
						
						
					break;

					case "checkbox":
						$input[$key] = $input[$key] ? $input[$key]  : "0";
					break;

					case "date":
						$__date = mktime($input[$key . "_hour"] , $input[$key . "_min"] , $input[$key . "_sec"] , $input[$key . "_month"] , $input[$key . "_day"] , $input[$key . "_year"]);
						if ($__date > 1000) {
							$input[$key] = $__date;
						} else 
							$input[$key] = 0;
					break;

					case "autocomplete":
						if (is_array($input[$key]))						
							$input[$key] = implode("," , $input[$key]);
						else
							$input[$key] = "";
					break;

					case "double":
					case "doubleselect":
					case "checklist":
						$val["multi"] = "true";

						if (is_array($input[$key]))						
							$input[$key] = implode("," , $input[$key]);
						else
							$input[$key] = "";
					break;

					case "droplist":
					case "radiolist":
					case "countries":
					case "usstates":
					case "states":
					case "rostates":
					case "castates":
					case "autocomplete":

						if ($val["multi"] == "true") {
							if (!isset($input[$key])) {
								$input[$key] = "";
							}							
						}
						

						if (is_array($input[$key]))						
							$input[$key] = implode("," , $input[$key]);

						/* DEPRECATED
							if ($val["subtype"] == "multiple") {

								//detect the fields which should be available for this field
								if (is_array($_POST)) {
									
									foreach ($_POST as $k => $v) {
										if (strstr($k , $key . "_option_")) {
											$option[] = $v;
										}										
									}						
									//ok, now build the result
									if (is_array($option)) {
										$_POST[$key] = implode($val["tree"]["db_separator"],$option);
									} else {
										$_POST[$key] = "";
									}
								} else {
									
								}
							}
						*/
					break;

					case "calendar":

						if ($input[$key]) {
							$input[$key] = strtotime($input[$key]);
							
							if ($input[$key]) {

								$input[$key . "_hour"]  = date("H" , $input[$key]); 
								$input[$key . "_min"]	= date("i" , $input[$key]);
								$input[$key . "_sec"]	= date("s" , $input[$key]);
								$input[$key . "_month"] = date("m" , $input[$key]);
								$input[$key . "_day"]	= date("d" , $input[$key]);
								$input[$key . "_year"]  = date("Y" , $input[$key]);
							}
						}											
					break;
				}

				if (isset($input[$key])) {
					//just changed
					//$input[$key] = stripslashes($input[$key]);
				}
				
			}
		}
		return $input;
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	static function __isRestricted($data , $field = array()) {
		global $_MODULES , $site , $_USER , $_SESS , $base;

		if (strpos($data , "eval:") === 0) {
			eval("\$result = " . substr($data , 5) );			
			return $result;
		}		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __evalValue($data) {
		global $_MODULES , $site , $_USER , $_SESS;

		if (strpos($data , "eval:") === 0) {
			eval("\$result = " . substr($data , 5) );			
			return $result;
		} 

		if ($data == "true") {
			return true;
		} else {
			return false;
		}
		
		

		return $result;
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	static function __isProtected($data , $field = array()) {
		global $_MODULES , $site , $_USER, $base;


		if (strpos($data , "eval:") === 0) {

			//$data = "eval:time();";


			eval("\$result = " . substr($data , 5) );
			
			return $result ? true : false;
		}

		//debug($data);
		//debug($field);
		
		return $field[$data] ? true  : false;
	}
		

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ProcessItems($items , $relations) {
		if (is_array($items)) {
			foreach ($items as $key => $val) {
				$items[$key] = CForm::ProcessItem($val , $relations);
			}
			
		}

		return $items;
		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ProcessItem($item , $relations) {
		if (is_array($item)) {
			foreach ($item as $k => $v) {
			
				if ($relations[$k]) {
					$relation = $relations[$k];

					//detect the type of the relation
					switch ($relation["type"]) {
						case "date":
							if ($v) 
								$item[$k] = date($relation["params"] , $v);
							else
								$item[$k] = $relation["default"] ?  $relation["default"] : "N/A";
						break;

						case "price":
							$item[$k] = number_format($item[$k],2);
						break;

						case "options":
							$item[$k] = $relation["options"][$v];
						break;

						case "bbcode":
							$bbc = new CBBCode();
							if ($relation["tpl"]) {
								$bbc->language_tpl = $relation["tpl"];
							}		
							$item[$k] = $bbc->Convert($v , $relation["lang"]["default"]);
						break;
					}

					if ($relation["maxchars"]) {
						if (strlen($item[$k]) > $relation["maxchars"]) {
							$item[$k] = substr($item[$k] , 0 , $relation["maxchars"] ) . "...";
						}
					}
					
				}
			}
		}

		return $item;
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field_filelist_options($field) {

		$files = CDir::GetFiles($field["path"] , $field["extension"]);

		if (is_array($files) && count($files)) {
			foreach ($files as $key => $val) {
				$tmp = basename($val);
				$_files[$tmp] = $tmp;
			}
			
			
			sort($_files);
			foreach ($_files as $key => $val) {

				if ($field["hideextension"] == "true") {
					$val = basename($val , $field["extension"]);
				}
				

				$__files[$val] = $val;
			}
			
			$_files = $__files;
		}		

		//
		return $_files ;

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field_folderlist_options($field) {

		$files = CDir::GetFolders($field["path"]);
		//
		return $files ;

	}
	


	/* FIELDS DEFINITIONS */

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__responsive($field ) {

		$_field = $field;

		//main field
		$_field["type"] = "droplist";
		$_field["empty_text"] = "[large dev.]";
		$_field["referers"] = $field["name"] . "_desktop," . $field["name"] . "_tablet," .  $field["name"] . "_phone";
		$fields[$field["name"]] = $_field;

		//desktop
		unset($_field["referers"]);
		unset($_field["default"]);
		unset($_field["value"]);
		$_field["referer"] = "true";
		$_field["empty_text"] = "[desktop]";
		$_field["name"] = $field["name"] . "_desktop";

		$fields[$field["name"] . "_desktop"] = $_field;


		//tablet
		$_field["empty_text"] = "[tablet]";
		$_field["name"] = $field["name"] . "_tablet";
		$fields[$field["name"] . "_tablet"] = $_field;

		//phone
		$_field["empty_text"] = "[phone]";
		$_field["name"] = $field["name"] . "_phone";
		$fields[$field["name"] . "_phone"] = $_field;

		return $fields;
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__droplist(&$field , &$values) {
		global 
			$form_US_states,
			$form_RO_states,
			$form_CA_states,
			$form_countries,
			$form_languages,
			$form_timezones;

		if ($field["height"]) {
			$field["style"] .= "height: {$field[height]}" . (stristr($field["height"] , "%") ? "" : "px" ) . ";";
		}

		if ($field["width"]) {
			//$field["style"] .= "width: {$field[width]}" . (stristr($field["width"] , "%") ? "" : "px" ) . ";";
			$field["data-width"] = $field["width"] . (stristr($field["width"] , "%") ? "" : "px" );
		}  else {
			$field["data-width"] ="100%";
		}

		$field["style"] = $field["style"];
		

		if ($field["newline"] == "false") {
			$field["inline-class"] = $this->templates->blocks["RC-Inline"]->output;
//			$field["line_bottom"] = "";
//			$field["line_top"] = "";
		} else {
			$field["inline-class"] = "";			
//			$field["line_bottom"] = $this->templates->blocks["CheckBoxOption_line_bottom"]->output;
//			$field["line_top"] = $this->templates->blocks["CheckBoxOption_line_top"]->output;
		}


		if ($field["sortable"] == "true") {
			$field["sortable"] = "sortable" ;
		} else {
			$field["sortable"] = "" ;
		}
		
		if (($field["sortable"] && $field["multi"]) || $field["large"]) {
			$field["class"] = "doubleselect";
		} else {
			$field["class"] = "select";
		}
		
		

		if (!isset($field["emptymsg"]))
			$field["emptymsg"] = $this->__default["show"]["droplist"]["empty_text" . ($field["editable"] == "false" ? "_show" : "")];

		if (!isset($field["empty_text"]))
			$field["empty_text"] = $this->__default["show"]["droplist"]["empty_text" . ($field["editable"] == "false" ? "_show" : "") ];

		//select multiple values for the complex selects
		if (($field["multi"]||$field["double"]) && !is_array($field["value"]) && $field["value"])
			$field["value"] = explode("," , $field["value"]);

		$values["values"]["original_" . $field["name"]] = $field["value"];			

		switch ($field["type"]) {
			case "USstates":
			case "states":
			case "usstates":
				$field["options"] = $form_US_states;
			break;

			case "languages":
				$field["options"] = $form_languages;
			break;
			
			case "ROstates":
			case "rostates":
				$field["options"] = $form_RO_states;
			break;

			case "CAstates":
			case "castates":
				$field["options"] = $form_CA_states;
			break;

			case "countries":
				$field["options"] = $form_countries;
			break;

			case "relation":
				$field["editable"] = "false";
			break;

			case "timezones":
			case "timezone":				
				$field["options"] = $form_timezones;
			break;


			case "fileslist":
				$field["options"] = $this->__field_filelist_options($field);
			break;

			case "folderlist":
				$field["options"] = $this->__field_folderlist_options($field);
			break;

		}
		

		//if is set use text then dont use the small names INSTED of CA use CANADA
		if (($field["usetext"] == "true") && (is_array($field["options"]))) {
			foreach ($field["options"] as $key => $val){
				unset($field["options"][$key]);
				$field["options"][$val] = $val;						
			}
				//$_field["options"][$val] = $val; 
			
			//$field["options"] = $_field["options"];
		}

		//if editable false change the type in relation ( non editable )
		if ($field["editable"] == "false")
			$field["type"] = "relation";				
		
		//clearign vals
		$temp_options = "";

		//check if the options are generated dinamic
		if (is_array($field["dynamic"])) {
			
			if ($field["dynamic"]["from_type"] == "eval") {
				eval( "\$field[\"dynamic\"][\"from\"] = " . $field["dynamic"]["from"] . ";");
			}

			if ($field["dynamic"]["from"] > $field["dynamic"]["to"])
				for ($i = $field["dynamic"]["from"]; $i>= $field["dynamic"]["to"]; $i-- ) {
					$field["options"][$i] = $field["dynamic"]["width"] ? sprintf("%0" . $field["dynamic"]["width"] . "d", $i) : $i;						
				}					
			else 					
				for ($i = $field["dynamic"]["from"]; $i<=$field["dynamic"]["to"]; $i++ ) {
					$field["options"][$i] = $field["dynamic"]["width"] ? sprintf("%0" . $field["dynamic"]["width"] . "d", $i) : $i;						
				}					
		}

###
		if (is_array($field["relation"])) {
			if (is_array($field["relation"]["sql"])) {
		

				if (is_array($field["relation"]["sql"]["vars"])) {
					
					$form_sql_vars = array();

					foreach ($field["relation"]["sql"]["vars"] as $key => $val) {
						//echeking if the default must be evaluated
						if ($val["action"] == "eval") {
							eval("\$val[\"import\"] = " . $val["default"] .";");
						}

						switch ($val["type"]) {
							case "eval":
								eval("\$form_sql_vars[\"$key\"] = " . $val["import"] . ";");
							break;

							case "var":
								$form_sql_vars[$key] = $val["import"];
							break;

							case "table":
								$form_sql_vars[$key] = $val["import"] ? $this->tables[$val["import"]] : $this->tables[$form["table"]];
							break;

							case "table_lang":
								$form_sql_vars[$key] = $val["import"] ? $this->tables[$val["import"]] : $this->tables[$form["table_lang"]];
							break;

							case "page":
								$form_sql_vars[$key] = ($_GET[($val["code"] ? $val["code"] : 'page')] -1 )* $form['items'];
							break;

							case "form":
								eval("\$form_sql_vars[\"$key\"] = " . $form[$val["var"]] . ";");
							break;
						}													
					}

					foreach ($form_sql_vars as $key => $val) {							
						$this->templates->blocks["Temp"]->input = $val;							
						$form_sql_vars[$key] = $this->templates->blocks["Temp"]->Replace($form_sql_vars);
					}	

					//doing a double replace, in case there are unreplaced variable sfom "vars" type
					$this->templates->blocks["Temp"]->input = $field["relation"]["sql"]["query"];
					$sql = $this->templates->blocks["Temp"]->Replace($form_sql_vars);

					//do a precheck for [] elements to be replaced with <>
					$sql = str_replace("]" , ">" , str_replace("[" , "<" , $sql));

					$records = $this->db->QFetchRowArray($sql);								
				} else {
					$records = $this->db->QFetchRowArray($field["relation"]["sql"]["query"]);								
				}

			} else {


				//check to eval the condition if requred
				if (is_array($field["relation"]["condition"]) && ($field["relation"]["condition"]["eval"] == "true")) {
					eval("\$field[\"relation\"][\"condition\"] = " . $field["relation"]["condition"]["import"]);
				}

				$tmp_table= explode("," , $field["relation"]["table"]);

				if (count($tmp_table)) {
					foreach ($tmp_table as $__k => $__table) {
						$rel_table[] = $this->tables[$__table];
					}

					$rel_table = implode(" , " , $rel_table);							
				} else 
					$rel_table = $this->tables[$field["relation"]["table"]];

				if ($field["relation"]["table_lang"]) {
					$lang_table = $this->tables[$field["relation"]["table_lang"]];
					$lang_table = $this->tables[$field["relation"]["table_lang"]];
					$id = $field["relation"]["id"];



					$sql =	"SELECT * FROM 
								{$rel_table} as record, 
								{$lang_table} as record_data ,
								{$this->tables['core:languages']} as lang
							WHERE
								record.{$id}=record_data.{$id} AND 
								record_data.lang_id = lang.lang_id AND 
								lang.lang_default=1 								
								" . 
								($field["relation"]["condition"] ? " AND (" . $field["relation"]["condition"] . ") " : "" ) . 
								($field["relation"]["order"] ? " ORDER BY " . $field["relation"]["order"] . " " . 
								($field["relation"]["ordermode"] ? $field["relation"]["ordermode"] : "") : "" );

/*

							($field["relation"]["condition"] ? " WHERE (" . $field["relation"]["condition"] . ") " : "" ) . 
							($field["relation"]["order"] ? " ORDER BY " . $field["relation"]["order"] . " " . 
							($field["relation"]["ordermode"] ? $field["relation"]["ordermode"] : "") : "" );
*/

				} else {				

					$sql =	"SELECT * FROM " . $rel_table . " " . 
							($field["relation"]["condition"] ? " WHERE (" . $field["relation"]["condition"] . ") " : "" ) . 
							($field["relation"]["order"] ? " ORDER BY " . $field["relation"]["order"] . " " . 
							($field["relation"]["ordermode"] ? $field["relation"]["ordermode"] : "") : "" );


				}

				$records =$this->db->QFetchRowArray( $sql );

			}

			if (is_array($records)) {

			// prepare the tree type
				if (($field["editable"] != "false") && is_array($records) && is_array($field["tree"])) {
					$records = CForm::__private_tree(
							$records , 
							$field["tree"]["first"] ? $field["tree"]["first"] : 0 , 
							$field["relation"]["id"] , 
							$field["tree"]["parent"] , 
							$field["tree"]["separator"] , 
							0, 
							array ( 
								"full" => $field["tree"]["full"]  , 
								"field" => $field["tree"]["field"] 
							)
							
					);							
				}


				if (is_array($records)) {

					foreach ($records as $key => $val) {
						if (is_array($field["relation"]["text"])) {
							$_tmp_text = array();

							foreach ($field["relation"]["text"] as $kkey => $vval)
								if (is_array($vval))
									$_tmp_text[] = $vval["preffix"] . $val[$vval["field"]] . $vval["suffix"];
								else
									$_tmp_text[] = $val[$vval];

							$field["options"][$val[$field["relation"]["id"]]] = $val["separator"] . implode($field["relation"]["separator"] ? $field["relation"]["separator"] . " " : " " , $_tmp_text);

						} else							
							$field["options"][$val[$field["relation"]["id"]]] = $val["separator"] . " " . $val[$field["relation"]["text"]];
					}						

				}
				
			}					
		}

		//debug($field,1);

		//prepare the templates list
		if ($field["radio"] == "true") {
			$template = "Radio";
			$checked = " checked=\"checked\" ";
		} else {
			if ($field["checkbox"] == "true") {				
				$template = "CheckBox";
				$checked = " checked=\"checked\" ";
			} else {
				$template = "Select";
				$checked = " selected=\"selected\" ";
			}
		}

		
		
		
		if ($field["sortable"] && is_array($field["value"]) && is_array($field["options"])) {

			$options = $field["options"];
			foreach ($field["value"] as $key => $val) {
				$_options[$val] = $options[$val];
				unset($options[$val]);
			}

			if (count($options)) {
				foreach ($options as $key => $val) {
					$_options[$key] = $val;
				}
			}

			$field["options"] = $_options;
			
		}
		
###
		//add the enpty option
		if ($field["empty"] == "true") {
			if ($field["editable"] == "false")
				$__empty = $field["empty_text"] ? $field["empty_text"] : "<i>N/A</i>";
			else {
				$__empty = $field["empty_text"] ? $field["empty_text"] : " [ select ] ";
				//$field["placeholder"] = $field["empty_text"] ? $field["empty_text"] : " [ select ] ";
			}
			
			$field["options"] = array("" => $__empty) + (is_array($field["options"]) ? $field["options"] : array() );
		}

####

		if (is_array($field["options"])) {

			//if the field admists multiple values then add the array simbol
			if ($field["multi"] && ($field["editable"] != "false"))  {
				$field["name_original"] = $field["name"];
				$field["name"] .= "[]";
			}


			if (($field["editable"] == "false" ) && !$field["multi"]) {


				
				//check if i have a value and it exists
				if ($field["options"][$field["value"]]) {

					$field["value_original"] = $field["value"];
					$field["value"] = $field["options"][$field["value"]];
				} else {
					$field["value"] = $field["empty_text"] ? $field["empty_text"] : $field["emptymsg"];
				}

				if (is_array($field["value"]) && isset($field["value"]["value"])) {
					$field["value"] = $field["value"]["value"];
				}
					
				if ($field["radio"]) {
					$this->templates->blocks["RadioDisabled"]->Replace($field , false);
					$current_field = $this->templates->blocks["RadioDisabled"]->EmptyVars();	
				} else {				
					$this->templates->blocks["SelectDisabled"]->Replace($field , false);
					$current_field = $this->templates->blocks["SelectDisabled"]->EmptyVars();	
				}

			} else {
			
				//building the select from options
				foreach ($field["options"] as $key => $val) {

					//hm ... support for noeditable fields, will apear as text
					if ($field["editable"] == "false") {					
							if ($field["multi"]) {									
								//change the structure of current fields make it array, and use it for later recognition
								
								if (is_array($values["values"]["original_" . $field["name"]]) && in_array($key , $values["values"]["original_" . $field["name"]] )) {
									$current_field[] = $val;
								}

							} else {			
								

									/*
									if (isset($field["default"]) && $field["default"] !== "") {

										$field["value_original"] = $field["default"];
										$field["value"] = $field["options"][$field["default"]];
									} elseif (!$values["values"][$field["name"]]) {
											$field["value"] = $field["empty_text"];
										} else {							
											$field["value_original"] = $values["values"][$field["name"]];
											$field["value"] = $field["options"][$values["values"][$field["name"]]];
										}
	*/


								/*
								if (($key == $values["values"][$field["name"]]) && (strlen($key) == strlen($values["values"][$field["name"]])) ) {
									$found = 1;

									$field["value"] = $val;

									$this->templates->blocks["text"]->Replace($field , false);
									$current_field = $this->templates->blocks["text"]->EmptyVars();	
								}

								*/
							}

					} else {					

						//checking if is a complex option or a simple one
						if (is_array($val)) {

							$label = $val["value"];
							$disabled = $val["disabled"] == "true" ? " disabled " : "";
						} else {
							$label = $val;
							$disabled = "";
						}

						if (is_array($field["value"]) && $field["value"] != "") {
							$selected = in_array($key , $field["value"])  ? $checked : "" ? $checked : "";
						} else {																 

							$selected = (($key == $field["value"]) && (strlen($key) == strlen($field["value"])) ? $checked : "");						
						}

						
												
						
						if (!is_array($val) || (is_array($val) && !$val["restricted"]) || (is_array($val) && ($val["restricted"] != "") && !CForm::__isRestricted($val["restricted"]))) {

						$temp_options .= $this->templates->blocks["{$template}Option" . (is_array($val) && $val["type"] == "group" ? "Group" : "")]->Replace(
							array(	
								"value" => $key,
								"label" => $label,
								"checked" => $selected,
								"disabled" => $disabled,
								"name" => $field["name"],
								"line_top" => $field["line_top"],
								"line_bottom" => $field["line_bottom"],
								"inline-class" => $field["inline-class"]
							)
						  );
						}
						
													
					}
				}														
			}


			//if is array then it is an no editable and multi true
			if (is_array($current_field)) {
				$current_field = implode(", " , $current_field );
				//mark as found
				$found = 1;
			}
			
		}

		if ($field["editable"] != "false") {

			//prepare the fields

			if (!isset($field["emptymsg"]))
				$field["emptymsg"] = $this->__default["show"]["droplist"]["emptytext"];

			$field["options"] = $temp_options;

			
			$field["size"] = $field["size"] ? $field["size"] : "1";
			$field["multiple"] = $field["multi"] ? " multiple=\"multiple\" " : "";

			$field["disabled"] = $field["disabled"] == "true" ? " disabled " : "";					

			if ($temp_options != "")
				$current_field = $this->templates->blocks[$template]->Replace($field);
			else 
				//else return a message, customizable from xml
				$current_field = $field["emptymsg"];
		} else {


			if ($current_field == "") {

				//else return a message, customizable from xml
				$current_field = $field["emptymsg"];
			}


			$current_field = $this->templates->blocks["text"]->replace(
				array(
					"value"	=> $current_field
				)
			);
			//$current_field .="<input type=\"hidden\" name=\"{$field[name]}\" id=\"{$field[name]}\" value="
		}


		return CTemplateStatic::Replace(
			$current_field , 
			array(
				"handlers"	=> $field["handlers"]
			)
		);
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__minititle(&$field) {
		return $this->templates->blockReplace("Minititle" , $field);
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__image(&$field , &$values , &$form) {


		global $_CONF , $base;

		if ($field["type"] == "upload") {
			$file = true;
		}
		

		if ($field["force_values"]) {
			$values["values"][$field["name"] . "_file"] = $field["force_values"]["file"];
			$values["values"][$field["file"]["field"]] = $field["force_values"]["field"];
			$values["values"][$field["name"]] = $field["force_values"]["value"];
		}

		$field["allowed"] = $field["allowed"];

		//generate download link
		if ($values["values"][$field["name"]]) {
			
			//debug($form,1);
			if ($field["download-file"]) {
				$field["file_download"] = CTemplateStatic::Replace($field["download-file"] , $values["values"]);
			} else {			
				$field["file_download"] = $form["uridata"]["ajax.download-file"] . "&field=" . $field["name"];
			}
		} else {
			$field["file_download"] = "";
		}
		
		if ($field["editable"] != "false") {
			
			$field["file_name"] = $values["values"][$field["name"] . "_file"];
/*???*/				$field["target"] = $field["target"] == "self" ? "" : "target=\"_new\"" ;

			//add the cropping details
			$field["crop_width"] = $field["crop_height"] = "0";
			if (is_array($field["thumbnails"]["resize"])) {
				$field["crop_width"] = (int)$field["thumbnails"]["resize"]["width"];
				$field["crop_height"] = (int)$field["thumbnails"]["resize"]["height"];
			} else {
				if ($field["process"]) {
					$field["crop_width"] = (int)$field["process"]["width"];
					$field["crop_height"] = (int)$field["process"]["height"];
				} 
			}

			//it is an image
			$tmp_file_path = $_CONF["path"] . $_CONF["upload"] . ($field["path"] ? $field["path"] : $field["file"]["path"]) . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"];
			$tmp_file_url = $_CONF["url"] . "upload/" . ($field["path"] ? $field["path"] : $field["file"]["path"]) . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"];

			$tmp_file_path = str_replace("/./" , "/" , $tmp_file_path);
			$tmp_file_url = str_replace("/./" , "/" , $tmp_file_url);

			if (file_exists($tmp_file_path) && is_file($tmp_file_path)) {
				$field["src"] = $tmp_file_url . ($file ? "" : "?" . time());
			} else
				$field["src"] = "";
		
			//check if the savinf gor returned and error and keep the file
			$field["previous_file"] = "";
			$field["previous_file_name"] = "";

			if ($values["values"][$field["name"] . "_temp"]) {
				$tmp_file_previous_path = $_CONF["path"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"];
				$tmp_file_previous_url = $_CONF["url"] . "upload/" . "tmp/" . $values["values"][$field["name"] . "_temp"];

				if (is_file($_CONF["path"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"])) {

					$tmp_file_previous_path = str_replace("/./" , "/" , $tmp_file_previous_path);
					$tmp_file_previous_url = str_replace("/./" , "/" , $tmp_file_previous_url);

					$field["previous_file"] = $tmp_file_previous_path;
					$field["previous_file_name"] = $values["values"][$field["name"] . "_temp_file"];
				}
			}

			if ($values["values"][$field["name"] . "_crop_oxbc"]) {
				$tmp_img = explode(":" , $values["values"][$field["name"] . "_crop_oxbc"]);
				$field["prev_x"] = $tmp_img[2];
				$field["prev_y"] = $tmp_img[3];
				$field["prev_w"] = $tmp_img[4];
				$field["prev_h"] = $tmp_img[5];
			} else 
				$field["prev_x"] = $field["prev_y"] = $field["prev_w"] =  $field["prev_h"] = '';


			//add the filename
			$field["file_name"] = $values["values"][$field["name"] . "_file"];
			$field["crop_oxbc"] = $values["values"][$field["name"] . "_crop_oxbc"];

			//add the max size supported by php
			$field["max_size"] = return_bytes(ini_get('post_max_size'));

			$field["alt_value"] = $values["values"][$field["name"] . "_alt"];
			$field["alt_hidden"] = $field["hidealt"] == "true" ? "hidden" : "";

			$image["editable"] = $this->templates->blocks[$file ? "uploadedit" : "imageedit"]->Replace($field);
		}	
//				DEBUG($values["values"]);

		
		if ($file) {
			if (is_file($_CONF["path"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"])) {
				

				//show the image
				$image["preview"] = $this->templates->blocks["fileshow"]->Replace(
										array(
											"name" => $_CONF["url"] . "upload/" . "tmp/" . $values["values"][$field["name"] . "_file"],
											"src" => $_CONF["url"] . "upload/" . "tmp/" . $values["values"][$field["name"] . "_temp"] ,
											"target" => $field["target"] == "self" ? "" : "target=\"_new\"" 
										)
									);
	
		
			} else {
				$file_name = $_CONF["path"] . $_CONF["upload"] . ($field["path"] ? $field["path"] : $field["file"]["path"]) . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"];
				//$file_url = $_CONF["url"] . "upload/" . ($field["path"] ? $field["path"] : $field["file"]["path"]) . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"];

				if (/*$values["values"][$field["name"]] && */file_exists($file_name)) {				
					$image["preview"] = $this->templates->BlockReplace(
											"fileshow",
											array(
												"name"	=> $field["name"],
												"file_download"	=> $field["file_download"],
												"file_name" => $values["values"][$field["name"] . "_file"] ? $values["values"][$field["name"] . "_file"]  : $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"],
												//"src" => $file_url,
												//"target" => $field["target"] == "self" ? "" : "target=\"_new\"" 
											)
										);
				} else 
					$image["preview"] = $field["error"] ? $field["error"] : "No file uploaded.";
			}

		} else {
		
			if (is_file($_CONF["path"] . $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"])) {

				//show the fucking image
				$image["preview"] = $this->templates->blocks["imageshow"]->Replace(
										array(
											"width" => $field["adminwidth"],
											"height" => $field["adminheight"] ? ' height="' . $field["adminheight"] . '"' : "",
											"border" => $field["border"] ? $field["border"] : 0,
											"src" => $_CONF["upload"] . "tmp/" . $values["values"][$field["name"] . "_temp"] 
										)
									);

			} else {
				//hm ... making a small trick to keep the image even if that was an failed adding,
				//this sux becouse if the add process is not completed then i get crap in the temp folder.					
				if ($values["values"][$field["name"]] && file_exists($filepath = $_CONF["path"] . $_CONF["upload"] . $field["path"] . $field["file"]["default"] . $values["values"][$field["file"]["field"]] . $field["file"]["ext"])) {
					$image["preview"] = $this->templates->blocks["imageshow"]->Replace(
											array(
												"width" => $field["adminwidth"],
												"height" => $field["adminheight"] ? ' height="' . $field["adminheight"] . '"' : "",
												"border" => $field["border"] ? $field["border"] : 0,
												"src" => $filepath . "?" . filemtime($filepath)
											)
										);

				} else {

					//checking if there exists a default image
					if ($field["default"]) {
						$image["preview"] = $this->templates->blocks["imageshownolink"]->Replace(
												array(
													"width" => $field["adminwidth"],
													"height" => $field["adminheight"] ? ' height="' . $field["adminheight"] . '"' : "",
													"border" => $field["border"] ? $field["border"] : 0,
													"src" => $_CONF["upload"] . $field["path"] . $field["default"]
												)
											);
					} else
						//return an error from xml
						$image["preview"] = $field["error"] ? $field["error"] : "No image curently available.";
				}
			}
		}


		if ($field["editable"] != "false"){
			$image["preview"] = "";
		}

		$image["temp"] = $values["values"][$field["name"] . "_temp"];
		$image["error"] = $field["error"];
		$image["name"] = $field["name"];


		//use the original obkect
		$this->templates->blocks["image"]->Replace($image , false);
		$current_field = $this->templates->blocks["image"]->EmptyVars();							

		return $current_field;
	}
	


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__textarea( &$field , &$values) {
		global $_TSM;

		if (is_array($temp = @explode(":" , $field["size"]))) {
			//size from xml
			$field["_cols"] = $temp["0"];
			$field["_rows"] = $temp["1"];
		} else {
			//preset size
			$field["_cols"] = $this->_textareaCols;
			$field["_rows"] = $this->_textareaRows;
		}

		if ($field["readonly"] == "true")
			$field["readonly"] = " readonly ";
		else
			$field["readonly"] = "";


		//uhm ... this is a crappy part becouse i have to integrate the html editor here so ...
		if ($field["html"] == "true") {
			//checking if the editor.js was loaded until now
			if ($_GLOBALS["cform_editor_loaded"] != true) {
				$current_field = $this->templates->blocks["htmlareainit"]->output;
				$_GLOBALS["cform_editor_loaded"] = true;
			}

			if ($field["fullPage"] == "true") {
				$field["fullPage"] = "true";
			} else 
				$field["fullPage"] = "false";
			
			if ($field["fullPage"] == "true") {
				$field["emptynbsp"] = "true";
			} else 
				$field["emptynbsp"] = "false";


			//just changed
			//$field["value"] = stripslashes($field["value"]);
			$_TSM["FORMS.PRIVATE.ONLOAD"] .= "";
			$current_field .= $this->templates->blocks["htmlarea"]->Replace($field);
		} else {				
			//$field["value"] = $field["denyhtml"] ? $field["value"] : htmlentities($field["value"]);
			//prepare some optional width value

			if ($field["width"]) {
				//$field["style"][] = "width:{$field[width]};";
			}

			if ($field["height"]) {
				$field["style"][] = "height:{$field[height]}px;";
			}
			

			if (is_array($field["style"])) {
				$field["style"] = "style=\"" . implode("" , $field["style"]) . "\"";
			}
			
			$current_field = $this->templates->blocks["textarea"]->Replace($field);
			//$current_field = $this->templates->blocks["textarea"]->EmptyVars();
		}

		return $current_field;
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__textbox( &$field , &$values) {

		$field["_mask"] = "";

		$locale = localeconv();


		//check if the size for textbox is defined
		if ($field["size"]) {

			//autodetect if the size value contaigns the maxlength too
			if (is_array($temp = @explode(":" , $field["size"]))) {								

				$field["_size"] = $temp["0"];
				$field["_maxlength"] = $temp["1"];

			} else {

				//else the size field is the size of textbox
				$field["_size"] = $field["size"];
				$field["_maxlength"] = $this->_textboxMaxLength;
			}

		} else {

			//check if there is defined any withd value
			if ($field["width"]) {

				//$field["style"] = " style=\"width:{$field[width]}\" ";

				$field["_size"] = "";
				$field["_maxlength"] = "";

			} else {
				//get the default values
				$field["style"] = "";

				$field["_size"] = $this->_textboxSize;
				$field["_maxlength"] = $this->_textboxMaxLength;
			}

							
		}

		//prepare the html entities for the nonhtml forms.
		//if ($field["html"] != "true")
			//$field["value"] = htmlentities($field["value"]);
		

		if (!isset($values["values"][$field["name"] . "_confirm"]))				
			$values["values"][$field["name"] . "_confirm"] = $field["value"];

		if ($field["align"]) {

			if (!is_array($field["style"])) {
				$field["style"] = array();
			}
			
			$field["style"][] = "text-align:{$field[align]}";
		}

		if ($field["readonly"] == "true")
			$field["readonly"] = " readonly ";
		else
			$field["readonly"] = "";

		//add the show element
		if ($field["type"] == "password") {
			if ($field["show"] == "true")
				$field["show"] = is_object($this->templates->blocks["password_show"]) ? $this->templates->blocks["password_show"]->Replace($field) : "";
			else
				$field["show"] = "";
		}

		if (is_array($field["style"]))
			$field["style"] = ' style="' . implode(";" , $field["style"]) . '" ';
		else
			$field["style"] = $field["style"];

		//replace the " with the html code for that else it will wont appear
		$field["value"] = str_replace("\"" , "&quot;" , $field["value"]);


		if ($field["mask"]) {

			if ($this->masks[$field["mask"]]) {
				$field["_mask"] = "data-inputmask=\"" . $this->masks[$field["mask"]] . "\"";
			} else {
				$field["_mask"] = "data-inputmask=\"" . $field["mask"] . "\"";
			}

			if ($field["maskconvert"] != "false") {
				$field["value"] = $this->convertToMask($field["mask"] , $field["value"]);
			}
					
			
		}
		


		if (($field["type"] == "colorpicker") && ($field["editable"] == "false")) {
			$current_field = $this->templates->blocks["colorpickerdisabled"]->Replace($field);
		} else {
		
			$current_field = $this->templates->blocks[$field["type"]]->Replace($field);
		}
		//$current_field = $this->templates->blocks[$field["type"]]->EmptyVars();	

		return $current_field;
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__file(&$field , &$values) {
		$field["file"] = $values["values"][$field["name"]];
		$this->templates->blocks["file"]->Replace($field , false);
		$current_field = $this->templates->blocks["file"]->EmptyVars();	

		return $current_field;
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__html(&$field , &$values) {
		return $this->templates->blockReplace("htmlfield" , $field);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__sql(&$field , &$values) {

		if (is_array($field["sql"])) {
			$form_sql_vars = array();

			if (is_array($field["sql"]["vars"])) {
				foreach ($field["sql"]["vars"] as $_key => $_val) {
					//echeking if the default must be evaluated
					if ($_val["action"] == "eval") {
						eval("\$_val[\"import\"] = " . $_val["default"] .";");
					}

					switch ($_val["type"]) {
						case "eval":
							eval("\$form_sql_vars[\"$_key\"] = " . $_val["import"] . ";");
						break;

						case "var":
							$form_sql_vars[$_key] = $_val["import"];
						break;

						case "page":
							$form_sql_vars[$_key] = ($_GET[($_val["code"] ? $_val["code"] : 'page')] -1 )* $form['items'];
						break;

						case "form":
							eval("\$form_sql_vars[\"$_key\"] = " . $form[$_val["var"]] . ";");
						break;

						case "field":
							$form_sql_vars[$_key] = $items[$key][$_val["import"]];
						break;
					}													
				}

				foreach ($form_sql_vars as $_key => $_val) {							
					$form_sql_vars[$_key] = CTemplateStatic::Replace($_val , $form_sql_vars);
				}	

				//doing a double replace, in case there are unreplaced variable sfom "vars" type
				$sql = CTemplateStatic::Replace($field["sql"]["query"] , $form_sql_vars);

				//do a precheck for [] elements to be replaced with <>
				$sql = str_replace("]" , ">" , str_replace("[" , "<" , $sql));

				$record = $this->db->QFetchArray($sql);								

				$field["value"] = $record[$field["sql"]["field"]];
			}							
		}
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__text(&$field , &$values) {

		if ($field["mask"]) {

			if ($this->masks[$field["mask"]]) {
				$field["_mask"] = "data-inputmask=\"" . $this->masks[$field["mask"]] . "\"";
			} else {
				$field["_mask"] = "data-inputmask=\"" . $field["mask"] . "\"";
			}

			if ($field["maskconvert"] != "false") {
				$field["value"] = $this->convertToMask($field["mask"] , $field["value"]);
			}
					
			
		}


		if (($field["html"] == "true") && (($field["fullpage"] == "true") || ($field["iframe"] == "true"))) {
			return $this->templates->blocks["text_iframe"]->Replace($field , false);	
		}

		if ($field["script"] == "true") {
			$field["value"] = "<div style='width: 100%; overflow: auto'><pre>" . htmlspecialchars($field["value"]) . "</pre></div>";
		} else {
				
			if ($field["html"] != "true") {
				//$field["value"] = htmlentities($field["value"]);

				//deprecated
				//$field["value"] = eregi_replace("([_a-z0-9\-\.]+)@([a-z0-9\-\.]+)\." . "(net|com|gov|mil|org|edu|int|biz|info|name|pro|[A-Z]{2})". "($|[^a-z]{1})", "<a title=\"Click to open the mail client.\" href=\"mailto:\\1@\\2.\\3\">\\1@\\2.\\3</a>\\4", $field["value"]);
				//$field["value"] = eregi_replace("(http|https|ftp)://([[:alnum:]/\n+-=%&:_.~?]+[#[:alnum:]+]*)","<a href=\"\\1://\\2\" title=\"Click to open in new window.\" target=\"_blank\">\\2</a>", $field["value"]);

				$field["value"] = autolink($field["value"]);

				$field["value"] = nl2br($field["value"]);
			}
		}
		
		if ($field["html"] != "true") {
		}

		if ($field["html_entities_decode"] == "true")
			$field["value"] = html_entity_decode($field["value"]);

		if ($field["maxchars"]) {
			$field["o_value"] = $field["value"];
			$field["value"] = substr($field["value"],0,$field["maxchars"]) . (strlen($field["value"]) > $field["maxchars"] ? ($field["maxchars_text"] ? $field["maxchars_text"] : $this->__default["list"]["fields"]["maxchars_text"]) : "");
		}


		$field["action"] = $field["subtype"] ? $field["subtype"] : $field["action"];

		switch ($field["action"]) {
			case "date":
				if (isset($values["values"][$field["name"] . "_day" ]) && isset($values["values"][$field["name"] . "_month" ]) && isset($values["values"][$field["name"] . "_year" ])) 
					$field["value"] = 
										( $values["values"][$field["name"] . "_month" ] ? sprintf("%02d" ,$values["values"][$field["name"] . "_month" ])  : "--" ). "." . 
										( $values["values"][$field["name"] . "_day" ] ? sprintf("%02d" ,$values["values"][$field["name"] . "_day" ]) : "--" ) . "." .  
										( $values["values"][$field["name"] . "_year" ] ? $values["values"][$field["name"] . "_year" ] : "----" ) ;
				else						
					$field["value"] = $field["value"] > 0 ? @date($field["params"] , $field["value"]) : "not available";
			break;

			case "price":
				$field["value"] = number_format($field["value"] , 2);
			break;

			case "link":
				$link = $field["o_value"] ? $field["o_value"] : $field["value"];
				$field["value"] = "<a href='{$link}' target='_blank'>{$field[value]}</a>";
			break;
		}

//WARNING THIS IS IN TESTING MODE SO IF ANYTHING WILL GO WRONG IT WILL DISPEAR				
		//do some special tricks, to transform the links and the email addresses in urls
//				if ($field["linkstransform"] == "true") {
		//check if there is any html content around

//				}



		//format the text
		switch ($field["font"]) {

			case "normal":
			break;

			default:
				$field["value"] = "" . $field["value"] . "";
			break;
		}


		if ($field["nobr"] == "true") 
			$field["value"] = "<nobr>{$field[value]}</nobr>";

		$current_field = $this->templates->blocks[$field["html"] == "true" ? "html" :  "text"]->Replace($field , false);
		//$current_field = $this->templates->blocks["text"]->EmptyVars();	

		return $current_field;
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__hidden(&$field , &$values) {
		//fix a small bug, if the hidden!= true then the elemet is drow like normal element.
		$field["hidden"] = "true";

		$current_field = $this->templates->blocks["hidden"]->Replace($field , false);

		return $current_field;
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__button(&$field , &$values) {
		$field["target"] = $field["target"];
		$field["title"] = $field["title"];

		$field["onmouseover"] = $field["onmouseover"];
		$field["onmouseout"] = $field["onmouseout"];
		$field["onclick"] = $field["onclick"];

		$field["id"] = $field["id"];
		$current_field = $this->templates->blocks[$field["type"]]->Replace($field , false);
		//$this->templates->blocks["button"]->EmptyVars();							

		return $current_field;
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__checkbox(&$field , &$values) {
		$_value = $field["checked"];
		$field["checked"] = $field["value"] == $field["checked"] ? " checked=\"checked\" " : "";
		$field["value"] = $_value;

		$field["check"] = $field["checked"] ? "on" : "off";

		//prepare the label 
		if (strstr($field["label"] , "|")) {
			$tmp = explode("|" , $field["label"]);
			$field["label"] = $tmp[0];					

			if ($field["editable"] == "false")
				$new = true;
		}
		

		

		if ($new == true) {
			if ($field["editable"] == "false") {
				$field["value"] = $field["check"] == "on" ? $tmp[0] : $tmp[1];
				$current_field = $this->templates->blocks["checkbox_details"]->Replace($field , false);
			}
		} else {
		
				$this->templates->blocks["checkbox" . ($field["editable"] == "false" ? "_show" : "")]->Replace($field , false);
				$current_field = $this->templates->blocks["checkbox" . ($field["editable"] == "false" ? "_show" : "")]->EmptyVars();							
		}

		return $current_field;

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__bootstrap_widths(&$field , &$values) {


		if ($field["options"]) {
			foreach ($field["options"] as $key => $val) {
				$_options[$key] = array("title"	=> $val , "value" => $key);
			}			
		} else {
	
			$_options = array(
				"12"	=> array("title" => "1" , "value"	=> "12"),
				"6"		=> array("title" => "2" , "value"	=> "6"),
				"4"		=> array("title" => "3" , "value"	=> "4"),
				"3"		=> array("title" => "4" , "value"	=> "3"),
				"1-5"	=> array("title" => "5" , "value"	=> "1-5"),
				"2"		=> array("title" => "6" , "value"	=> "2"),
				"1-7"	=> array("title" => "7" , "value"	=> "1-7"),
				"1-8"	=> array("title" => "8" , "value"	=> "1-8"),
				"1"		=> array("title" => "12" , "value"	=> "1"),
			);
		}

		foreach ($_options as $key => $val) {
			$options .= $this->templates->blockReplace(
				"bootstrapcolumnsoption",
				$val
			);
		}


		$default = explode("," , $field["default"]);

		$default[0] = $default[0] != "" ? $default[0] : "--";
		$default[1] = $default[1] != "" ? $default[1] : "--";
		$default[2] = $default[2] != "" ? $default[2] : "--";
		$default[3] = $default[3] != "" ? $default[3] : "--";
		$default[4] = $default[4] != "" ? $default[4] : "--";

		
		if (defined("STP_LAYOUT_GRID") && (STP_LAYOUT_GRID == "BS3")) {
			$val = 	array(
				"phone"		=> $values["values"][$field["name"] . "_phone"],
				"tablet"	=> $values["values"][$field["name"] . "_tablet"],
				"desktop"	=> $values["values"][$field["name"] . "_desktop"],
				"main"		=> $values["values"][$field["name"]],
			);

			if ($field["editable"] == "false") {
				$val["main"]	= $_options[$val["main"]]["title"];
				$val["desktop"]	= $_options[$val["desktop"]]["title"];
				$val["tablet"]	= $_options[$val["tablet"]]["title"];
				$val["phone"]	= $_options[$val["phone"]]["title"];
			}

			$current_field = CTemplateStatic::Replace(
				$this->templates->BlockReplace(
					$field["editable"] != "false" ? "bootstrapcolumnsBS3" : "bootstrapcolumnsshowBS3", 
					array(				
						"options"	=> $options,
						"main"		=> $val["main"] != "" ? $val["main"] : $default[0],
						"desktop"	=> $val["desktop"] != "" ? $val["desktop"] : $default[1],
						"tablet"	=> $val["tablet"] != "" ? $val["tablet"] : $default[2],
						"phone"		=> $val["phone"] != "" ? $val["phone"] : $default[3]
					)
				),
				$field 
			);

		} else {
			$val = 	array(
				"xs"		=> $values["values"][$field["name"] . "_xs"],
				"sm"		=> $values["values"][$field["name"] . "_sm"],
				"md"		=> $values["values"][$field["name"] . "_md"],
				"lg"		=> $values["values"][$field["name"] . "_lg"],
				"main"		=> $values["values"][$field["name"]],
			);

			if ($field["editable"] == "false") {
				$val["main"]	= $_options[$val["main"]]["title"];
				$val["lg"]	= $_options[$val["lg"]]["title"];
				$val["md"]	= $_options[$val["md"]]["title"];
				$val["sm"]	= $_options[$val["sm"]]["title"];
				$val["xs"]	= $_options[$val["xs"]]["title"];
			}

			$current_field = CTemplateStatic::Replace(
				$this->templates->BlockReplace(
					$field["editable"] != "false" ? "bootstrapcolumns" : "bootstrapcolumnsshow", 
					array(				
						"options"	=> $options,
						"main"		=> $val["main"] != "" ? $val["main"] : $default[0],
						"lg"		=> $val["lg"] != "" ? $val["lg"] : $default[1],
						"md"		=> $val["md"] != "" ? $val["md"] : $default[2],
						"sm"		=> $val["sm"] != "" ? $val["sm"] : $default[3],
						"xs"		=> $val["xs"] != "" ? $val["xs"] : $default[4]
					)
				),
				$field 
			);

		}
		
			


		return $current_field;

	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__bootstrap_columns(&$field , &$values) {

		for ($i = 1; $i <= 12 ; $i ++) {
			$options .= $this->templates->blockReplace(
				"bootstrapcolumnsoption",
				array(
					"title"	=> $i,
					"value"	=> $i,
				)
			);			
		}

		$default = explode("," , $field["default"]);

		$default[0] = $default[0] ? $default[0] : "--";
		$default[1] = $default[1] ? $default[1] : "--";
		$default[2] = $default[2] ? $default[2] : "--";
		$default[3] = $default[3] ? $default[3] : "--";
		$default[4] = $default[4] ? $default[4] : "--";

		if (defined("STP_LAYOUT_GRID") && (STP_LAYOUT_GRID == "BS3")) {
			$val = 	array(
				"phone"		=> $values["values"][$field["name"] . "_phone"],
				"tablet"	=> $values["values"][$field["name"] . "_tablet"],
				"desktop"	=> $values["values"][$field["name"] . "_desktop"],
				"main"		=> $values["values"][$field["name"]],
			);

			$current_field = CTemplateStatic::Replace(
				$this->templates->BlockReplace(
					$field["editable"] != "false" ? "bootstrapcolumnsBS3" : "bootstrapcolumnsshowBS3", 
					array(				
						"options"	=> $options,
						"main"		=> $val["main"] ? $val["main"] : $default[0],
						"desktop"	=> $val["desktop"] ? $val["desktop"] : $default[1],
						"tablet"	=> $val["tablet"] ? $val["tablet"] : $default[2],
						"phone"		=> $val["phone"] ? $val["phone"] : $default[3],
					)
				),
				$field 
			);
		} else {
			$val = 	array(
				"xs"	=> $values["values"][$field["name"] . "_xs"],
				"sm"	=> $values["values"][$field["name"] . "_sm"],
				"md"	=> $values["values"][$field["name"] . "_md"],
				"lg"	=> $values["values"][$field["name"] . "_lg"],
				"main"	=> $values["values"][$field["name"]],
			);

			$current_field = CTemplateStatic::Replace(
				$this->templates->BlockReplace(
					$field["editable"] != "false" ? "bootstrapcolumns" : "bootstrapcolumnsshow", 
					array(				
						"options"	=> $options,
						"main"		=> $val["main"] ? $val["main"] : $default[0],
						"lg"		=> $val["lg"] ? $val["lg"] : $default[1],
						"md"		=> $val["md"] ? $val["md"] : $default[2],
						"sm"		=> $val["sm"] ? $val["sm"] : $default[3],
						"xs"		=> $val["xs"] ? $val["xs"] : $default[4],
					)
				),
				$field 
			);


		}

		return $current_field;

	}
	

	function __field__vardump(&$field , &$values) {



		if ($field["serialize"]) {

			if ($field["base64"]) {
				$field["value"] = base64_decode($field["value"]);
			}
			
			$field["value"] = print_r(unserialize($field["value"]) , true) ;

			$field["value"] = preg_replace("/\[(\w*)\]/i", '[<font color="red">$1</font>]', $field["value"]);
			$field["value"] = preg_replace("/(\s+)\)$/", '$1)</span>', $field["value"]);
			/* turn array indexes to red */ 
			/* turn the word Array blue */ 
			$field["value"] = str_replace('Array','<font color="blue">Array</font>',$field["value"]); 
			/* turn arrows graygreen */ 
			$field["value"] = str_replace('=>','<font color="#556F55">=></font>',$field["value"]);

			$field["height"] = $field["height"] ? $field["height"] : "200";

		}


		$current_field = $this->templates->blocks["vardump"]->Replace($field , false);
		return $current_field;

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__comment(&$field , &$values , $form) {
		global $_CONF;

		//changed the way it handles the comments
		if ($field["value"] && ($field["html"] != "true")) {
			$field["description"] = nl2br($field["value"]);
		}	
		
		//debug($field,1);

		if ($field["subtype"] == "extern") {
			$field["description"] = GetFileContents(dirname($form["xmlfile"]) . "/" . $field["file"]);
		} else {
		
			$field["description"] = preg_replace( 
							array( '(\[)' , '(\])' ),
							array( "<" , ">" ),
							$field["description"]
						);
		}
		//save the input 
		$old = $this->templates->blocks["Comment"]->input ;

		//do the replaces
		
		$this->templates->blocks["Comment"]->input = $this->templates->blocks["Comment"]->Replace(array(
																									"COMMENT" => $field["description"],
																									"PADDING" => $field["padding"] ? $field["padding"] : "0",
																									"ALIGN" => $field["align"],
																									"NAME"	=> $field["name"],
																									));								
		$this->templates->blocks["Comment"]->input = $this->templates->blocks["Comment"]->Replace($values["values"]);
		$this->templates->blocks["Comment"]->input = $this->templates->blocks["Comment"]->Replace($_GET);
		$current_field = $this->templates->blocks["Comment"]->Replace($_POST);

		//restore the template 
		$this->templates->blocks["Comment"]->input = $old;
			
		return $current_field;
	}

	
	function __field__iframe(&$field , &$values) {
		global $_CONF;

		$current_field = $this->templates->BlockReplacE(
			"iframe" , 
			array(
				"loading"	=> $field["showloading"] == "true" ? $this->templates->BlockReplace("iframe_loading" ) : "",
				"src"		=> $field["source"] ? $field["source"] : "about:blank",
				"height"	=> $field["height"] ? $field["height"] : 100,
				"name"		=> $field["name"] ,				
			)
		);
			
		return $current_field;
	}


	function __field__autocomplete(&$field , &$values) {
		global $_CONF;

		$current_field = $this->templates->BlockReplacE(
			"autocomplete" , 
			array(
				"value"		=> $field["value"],
				"name"		=> $field["name"] ,				
				"script"	=> $field["script"],
				"max"		=> max($field["items"] , 1),
			)
		);
			
		return $current_field;
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__date(&$field , &$values) {


		if (($field["now"] == "true") && !$field["value"]) {
			$field["value"] = time();
		}
#### FIX ME IF NO SEPARATE DATES IT WONR WORK, NEED TO CREATE THEM FROM THE MAIN DATE IF DOESNT EXIST				
		if ($field["editable"] == "false") {

			$val = &$values["values"];					
			$k = $field["name"];

## not sure if this is okay
			if (!isset($val[$k])) {
				$val[$k] = $field["value"];
			}
			

			if (is_string($field["fields"])) {
				$supp_fields = array("month" , "year" , "month_str", "day");

				$_tmp_v = "";


				foreach ($supp_fields  as $__k => $__v) {
					switch ($__v) {
						case "month_str":
							$_tmp_v[$__v] = $form_months[$val[$k . "_month" ]];
						break;

						case "day":
							$_tmp_v[$__v] = sprintf("%02d" ,$val[$k . "_day" ]);
						break;

						case "year":
							$_tmp_v[$__v] = sprintf("%02d" ,$val[$k . "_year" ]);
						break;
					}										
				}

				$current_field = $field["fields"];
				foreach ($_tmp_v as $__k => $__v) {
					$current_field = str_replace($__k , $__v , $current_field);									
				}									

			} else {

				if (isset($val[$k . "_month" ]) && isset($val[$k . "_day" ]) && isset($val[$k . "_year" ])) {
					$current_field = 
										( $val[$k . "_month" ] ? sprintf("%02d" ,$val[$k . "_month" ])  : "--" ). "/" . 
										( $val[$k . "_day" ] ? sprintf("%02d" ,$val[$k . "_day" ]) : "--" ) . "/" .  
										( $val[$k . "_year" ] ? $val[$k . "_year" ] : "----" )  . "&nbsp;&nbsp;" . 
					
										($val[$k . "_hour"] && $val[$k . "_minute"]  ? $val[$k . "_hour"] . ":" . $val[$k . "_minute"] : "");
				} else {
					$current_field = $val[$k] > 1000 ? date(($field["params"] ? $field["params"] : "m/d/Y") , $val[$k]) : "not available";
				}				
			}
		} else {			
			if (is_array($field["fields"])) {

				$html = new CHtml;

				//do some variables cleaning
				if (is_array($years))
					unset($years);
				if (is_array($days))
					unset($days);
				if (is_array($months))
					unset($months);
			
				$date_vals = &$values["values"][$field["name"]];
				//try to do a small trick with default values
				if (($date_vals < 1000) && isset($field["value"])) {
					$date_vals = $field["value"];
				}
				
				if (($date_vals > 1000) || (isset($values["values"][$field["name"] ."_year"]) || isset($values["values"][$field["name"] ."_month"]) || isset($values["values"][$field["name"] ."_day"]))) {

					//setting the previous values
					$year_selected = isset($values["values"][$field["name"] ."_year"]) ? $values["values"][$field["name"] ."_year"] : @date("Y" , $date_vals );
					$month_selected = isset($values["values"][$field["name"] ."_month"]) ? $values["values"][$field["name"] ."_month"] : @date("n" , $date_vals );
					$day_selected = isset($values["values"][$field["name"] ."_day"]) ? $values["values"][$field["name"] ."_day"] : @date("j" , $date_vals );

					//crap, adding the time values too
					$hour_selected = isset($values["values"][$field["name"] ."_hour"]) ? $values["values"][$field["name"] ."_hour"] : @date("G" , $date_vals );
					$minute_selected = isset($values["values"][$field["name"] ."_minute"]) ? $values["values"][$field["name"] ."_minute"] : @date("i" , $date_vals );
					$second_selected = isset($values["values"][$field["name"] ."_second"]) ? $values["values"][$field["name"] ."_second"] : @date("s" , $date_vals );

				} else {

					$fld = $field["fields"];

					//setting the default value 						
					$year_selected = $fld["year"]["default"] == "now" ? date("Y") : $fld["year"]["default"];
					$month_selected = $fld["month"]["default"] == "now" ? date("n") : $fld["month"]["default"];
					$day_selected = $fld["day"]["default"] == "now" ? date("j") : $fld["day"]["default"];

					//crap, adding the time values too
					$hour_selected = $fld["hour"]["default"] == "now" ? date("G") : $fld["hour"]["default"];
					$minute_selected = $fld["minute"]["default"] == "now" ? date("i") : $fld["minute"]["default"];
					$second_selected = $fld["second"]["default"] == "now" ? date("s") : $fld["second"]["default"];						
				}						

				if ($field["calendar"] == true) {
					$current_field = $this->templates->blocks["Calendar"]->Replace(array(
						"name" => $field["name"],
						"value" => mktime(1,1,1,$month_selected, $day_selected , $year_selected),//$field["value"],
						"value_day" => $day_selected,
						"value_month" => $month_selected,
						"value_year" => $year_selected,
						"form" => $form["name"]
					));
				} else {
				
					foreach ($field["fields"] as $key => $val) {
						switch ($key) {
							case "year":
								if ($field["fields"]["year"]["empty"] == "true") {
									$years[0] = "--" ;
								}
								
								for ($i = $field["fields"]["year"]["from"] ; $i <= $field["fields"]["year"]["to"] ; $i++ )
									$years[$i] = $i;									

								$current_field .= $html->FormSelect(
																		$field["name"]."_year" , 
																		$years , 
																		$this->templates , 
																		"DateSelect", 
																		$year_selected , 
																		array() , 
																		array("DISABLED" => ($field["fields"]["year"]["editable"] == "false") ? "DISABLED" : "")									
																	);

								$current_field .= $val["separator"];
							break;

							case "day":
								if ($field["fields"]["day"]["empty"] == "true") {
									$days[0] = "--" ;
								}

								for ($i = 1 ; $i <= 31 ; $i++ )
									$days[$i] = sprintf("%02d",$i);

								$current_field .= $html->FormSelect(
																		$field["name"]."_day" , 
																		$days , 
																		$this->templates , 
																		"DateSelect", 
																		$day_selected,
																		array() , 
																		array("DISABLED" => ($field["fields"]["day"]["editable"] == "false") ? "DISABLED" : "")
																	);
								$current_field .= $val["separator"];
							break;

							case "month":
								if (($field["fields"]["month"]["empty"] == "true"))  {
									$months[0] = "--" ;
								}

								//importing the months from global
								global $form_months;

								if (is_array($months))
									$formmonths = array_merge($months, $form_months);
								else
									$formmonths = $form_months;

								//ehcking if the dates must apear like strings or numbers
								$current_field .= $html->FormSelect(
																		$field["name"]."_month" , 
																		$formmonths, 
																		$this->templates , 
																		"DateSelect", 
																		$month_selected,
																		array() , 
																		array("DISABLED" => ($field["fields"]["month"]["editable"] == "false") ? "DISABLED" : "")
																	);

								$current_field .= $val["separator"];
							break;

							case "hour":
								for ($i = 0; $i <= 23; $i++ )
									$hours[$i] = sprintf("%02d",$i);;									

								$current_field .= $html->FormSelect(
																		$field["name"]."_hour" , 
																		$hours , 
																		$this->templates , 
																		"DateSelect", 
																		$hour_selected , 
																		array() , 
																		array("DISABLED" => ($field["fields"]["hour"]["editable"] == "false") ? "DISABLED" : "")									
																	);

								$current_field .= $val["separator"];
							break;

							case "minute":
								for ($i = 0; $i <= 59; $i++ )
									$minutes[$i] = sprintf("%02d",$i);;									

								$current_field .= $html->FormSelect(
																		$field["name"]."_minute" , 
																		$minutes , 
																		$this->templates , 
																		"DateSelect", 
																		$minute_selected , 
																		array() , 
																		array("DISABLED" => ($field["fields"]["minute"]["editable"] == "false") ? "DISABLED" : "")									
																	);

								$current_field .= $val["separator"];
							break;

							case "second":
								for ($i = 0; $i <= 59; $i++ )
									$seconds[$i] = sprintf("%02d",$i);;									

								$current_field .= $html->FormSelect(
																		$field["name"]."_second" , 
																		$seconds , 
																		$this->templates , 
																		"DateSelect", 
																		$second_selected , 
																		array() , 
																		array("DISABLED" => ($field["fields"]["minute"]["editable"] == "false") ? "DISABLED" : "")									
																	);

								$current_field .= $val["separator"];
							break;

						}						
					}					
				}
			}				
		}

		return $current_field;
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__creditcard(&$field , &$values) {
		//crap prepare the values
		if (is_array($values["values"][$field["name"] . "_arr"])) {
			//okay, here are the data
			$field["value_group_1"] = $values["values"][$field["name"] . "_arr"]["1"];
			$field["value_group_2"] = $values["values"][$field["name"] . "_arr"]["2"];
			$field["value_group_3"] = $values["values"][$field["name"] . "_arr"]["3"];
			$field["value_group_4"] = $values["values"][$field["name"] . "_arr"]["4"];
		} else {

			switch ($field["show"]) {

				case "blank":
					$field["value_group_1"] = ""; 
					$field["value_group_2"] = "";
					$field["value_group_3"] = "";
					$field["value_group_4"] = "";
				break;

				case "none":
					$field["value_group_1"] = $field["editable"] == "false" ? "xxxx" : "";
					$field["value_group_2"] = $field["editable"] == "false" ? "xxxx" : "";
					$field["value_group_3"] = $field["editable"] == "false" ? "xxxx" : "";
					$field["value_group_4"] = $field["editable"] == "false" ? "xxxx" : "";
				break;

				case "last":
					$field["value_group_1"] = $field["editable"] == "false" ? "xxxx" : "";
					$field["value_group_2"] = $field["editable"] == "false" ? "xxxx" : "";
					$field["value_group_3"] = $field["editable"] == "false" ? "xxxx" : "";
					$field["value_group_4"] = substr($field["value"],12,4);
				break;

				default:
					$field["value_group_1"] = substr($field["value"],0,4) ;
					$field["value_group_2"] = substr($field["value"],4,4);
					$field["value_group_3"] = substr($field["value"],8,4);
					$field["value_group_4"] = substr($field["value"],12,4);
				break;
			}
			
		}
		
		$this->templates->blocks[$field["editable"] == "false" ? "cc_show" : "cc"]->Replace($field , false);
		$current_field = $this->templates->blocks[$field["editable"] == "false" ? "cc_show" : "cc"]->EmptyVars();
		return $current_field;
	}
	
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__namesort(&$field , &$values) {
		global $base;

		switch ($field["content"]) {
			case "alphanumeric":
			case "digits":
				for ($i = 0; $i<= 9; $i++) {
					$content[] = array("name" => $i , "link" => "javascript:document.forms[" . ($form["name"] ? "'" .$form["name"] . "'": '0') . "].{$field[name]}.value='" . $i. "'");							
				}

				if ($field["content"] == "digits")						
					break;
				
			case "letters":
				//65
				for ($i = 65; $i<= 90; $i++) {
					$content[] = array("name" => chr($i) , "link" => "javascript:document.forms[" . ($form["name"] ? "'" .$form["name"] . "'": '0') . "].{$field[name]}.value='" . chr($i). "'");							
				}
			break;
		}

		if (is_array($content)) {
			$current_field = $base->html->table(
					$this->templates,
					"namesort",
					$content
				);
		}
		return $current_field;
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __field__calendar(&$field , &$values) {

		switch ($field["type"]) {
			case "time":
					$field["params"] = "HH:mm:ss";
			break;

			case "calendar":


				//check for variables from client
				if (is_array($field["calendar"]) && ($field["calendar"]["time"] == "true")) {
					$field["params"] = "DD MMMM YYYY, HH:mm";

					if ($field["value"]) {
						$field["value"] = date("d F Y, H:i", $field["value"]);
					} else {
						$field["value"] = "";
					}
									
				} else {
					$field["params"] = "DD MMMM YYYY";

					if ($field["value"] && is_numeric($field["value"])) {
						$field["value"] = date("d F Y" , $field["value"]);
					} else {
						$field["value"] = "";
					}
				}

				if (is_array($field["calendar"]) && $field["calendar"]["range"]) {
					$tmp = explode(":" ,  $field["calendar"]["range"]);

					$field["_start"] = $this->templates->blockReplace("calendar_start"  ,array("start" => $tmp[0]));
					$field["_end"] = $this->templates->blockReplace("calendar_end"  ,array("end" => $tmp[1]));
				} else {
					$field["_start"] = $field["_end"] = "";
				}

				$field["time"] = is_array($field["calendar"]) && ($field["calendar"]["time"] == "true") ? "true" : "false";


				if ($field["range"] == "true") {

					if (($values["values"][$field["name"] . "_start"] != "" )&& is_numeric($values["values"][$field["name"] . "_start"]) && ($values["values"][$field["name"] . "_start"] > 10000)) {						
						$field["value_start"] = date("d F Y" , $values["values"][$field["name"] . "_start"]);
					} else {

						if (is_numeric($values["values"][$field["name"] . "_start"])) {
							$field["value_start"] = $values["values"][$field["name"] . "_start"] = "";
						} else {						
							$field["value_start"] = $values["values"][$field["name"] . "_start"];
						}
					}

					if ($values["values"][$field["name"] . "_end"] && is_numeric($values["values"][$field["name"] . "_end"]) && ($values["values"][$field["name"] . "_end"] > 10000)) {
						$field["value_end"] = date("d F Y" , $values["values"][$field["name"] . "_end"]);
					} else {
						if (is_numeric($values["values"][$field["name"] . "_end"])) {
							$field["value_end"] = $values["values"][$field["name"] . "_end"] = "";
						} else {
							$field["value_end"] = $values["values"][$field["name"] . "_end"];
						}
					}
				}
				
			break;
		}

		


		if ($field["editable"] == "false") {
			$current_field = $this->templates->blocks["text"]->Replace($field);
		} else {				
							
			$current_field = $this->templates->blockReplace(
				$field["type"] . ($field["range"] == "true"? "_range" : ""),
				$field ,
				array(
					"params" => $params,
				)
			);
		}
		return $current_field;
	}

	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __private_uploads_pre($field , &$_fields = array()) {

		global $_CONF , $base;

		$key = $field["name"];
		$val = $field;

		//checking how choosed the client to set the image
		switch ($_POST[$key . "_radio_type"]) {
			case 0:
				//checking if the client specified any image type
				if (is_array($_FILES[$key . "_upload_client"]) && is_uploaded_file($_FILES[$key . "_upload_client"]["tmp_name"])) {									
					$img = &$_FILES[$key . "_upload_client"];

					//generate the extension
					$_POST[$key . "_ext"] = FileExt($_POST[$key . "_temp_file"]);

					//temporary upload the file in images/upload/tmp/
					$name = $_POST[$key . "_temp"] != "" ? $_POST[$key . "_temp"] : $key . $val["file"]["default"] . time() . $val["file"]["ext"];	

					// generate the tn image


					if ($val["process"]) {						

						Image::newInstance()
							->read($img["tmp_name"])
							->resize(
								$val["process"]["width"],
								$val["process"]["height"]
							)
							->WaterMark(
								$val["process"]["watermark"]["file"] , 
								$val["process"]["watermark"]["pos_x"],
								$val["process"]["watermark"]["pos_y"]
							)
							->save(
								$_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , 
								$val["process"]["quality"],
								0644
							)
							->destroy();

					} else 
						//dont use move uploaded file becouse will erase it and wont be available fro processing											
						@copy($img["tmp_name"] , $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name );

					$_file_name = $img["tmp_name"];
					
//										die;
					//setting the temp variable
					$_fields["values"][$key . "_temp"] = $name;
					$_POST[$key . "_temp"] = $name;
					//$_POST[$key . "_file"] = $_FILES[$key . "_upload_client"]["name"];
					$_POST[$key] = "1";										

					if (file_exists($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name)) {
						$size = getimagesize($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name);

						if (is_array($size)) {
							$_POST[$key . "_width"] = $size[0];
							$_POST[$key . "_height"] = $size[1];
						}

					}
					

				}								
			break;
/*
			case "1":
				//fuck, the guy wants to download a fucking image

				if ($_POST[$key . "_upload_web"] != "http://") {										
					//i have to be very carefully here, if the image is not a valid link, then 
					//everithing get messed.
					$image = @GetFileContents($_POST[$key . "_upload_web"]);
					
					$name = $_POST[$key . "_temp"] != "" ? $_POST[$key . "_temp"] : $key . $val["file"]["default"] . time() . $val["file"]["ext"];

					SaveFileContents( $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , $image);
					chmod ($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , 0777);

					if ($val["process"]) {
						$base->image->Resize(
												$_CONF["path"] . $_CONF["upload"] . "tmp/" . $name ,
												$_CONF["path"] . $_CONF["upload"] . "tmp/" . $name . "resize" ,
												$val["process"]["width"],
												strtoupper($val["process"]["force"])
											);
						unlink($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name);
						rename($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name . "resize" , $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name);

					}


					
					$_file_name = $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name ;


					// generate the tn image
					if ($val["tn"]["generate"] == "true") {
						@$base->image->Resize(
												$_CONF["path"] . $_CONF["upload"] . "tmp/" . $name ,
												$_CONF["path"] . $_CONF["upload"] . "tmp/" . $val["tn"]["preffix"] . $name ,
												$val["tn"]["width"]
											);

						$_POST["tn_" . $key] = "1";
					}



					//setting the temp variable
					$_fields["values"][$key . "_temp"] = $name;
					$_POST[$key . "_temp"] = $name;
					//$_POST[$key . "_file"] = basename($_POST[$key . "_upload_web"]);
					$_POST[$key] = "1";

					@$size = getimagesize($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name);

					if (is_array($size)) {
						$_POST[$key . "_width"] = $size[0];
						$_POST[$key . "_height"] = $size[1];
					}

				}

			break;
*/
			case "-1":
//									echo "<pre style=\"background-color:white\">";
//									print_r($_POST);
//									die;
				//trying to remove the tmp image is exists
				if (file_exists($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]) && is_file($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]))
					@unlink($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]);										
				//removing the original image too if exists
				else
					@unlink($_CONF["path"] . $_CONF["upload"] . $val["path"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"]);

				$_fields["values"][$key . "_radio_type"] = 0;

				$_POST[$key] = 0;
				$_fields["values"][$key . "_temp"] = "";
				$_POST[$key . "_temp"] = "";
				//$_POST[$key . "_file"] = "";
			break;

		}

		if ($field["type"] == "image") {
		
			//hm ... checking if that IS A REAL IMAGE
			if ($_POST[$key . "_temp"] && !$file) {

				if (file_exists($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"])) {
					$img = GetImageSize($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]);
				}
				
				

				if (!is_array($img)) {

					//removing the image, maybe in future return the fucker a proper answer
					//echo "MOHHHHH";
					@unlink($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]);
					$_POST[$key . "_temp"] = "";
					$_POST[$key] = 0;
				}		
			}
		}
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __private_uploads_after($field) {
		global $base, $_CONF;


		$val = $field;
		$key = $field["name"];

		//process for cropping			
		$crop = $_POST[$key . "_crop_oxbc"];


		if ($crop) {		

			$tmp_img = explode(":" , $crop);

			$width = $tmp_img[0];
			$height = $tmp_img[1];

			$x = $tmp_img[2];
			$y = $tmp_img[3];

			$c_width = $tmp_img[4];
			$c_height = $tmp_img[5];

			$source = $tmp_img[6];



			if (!file_exists($source)) {
				$source = urldecode($source);

				if (!file_exists($source)) {

					return "";
				}
				
			}
			


			$image_data = getImageSize($source);

			//check if the image isnt set to be proportional
			if (!$width && !$height) {
				$width = $c_width;
				$height = $c_height;
			}
				
			//if the image its at the correct size, dont touch it
			if (($image_data[0] == $c_width) && ($image_data[1] == $c_height) && ($width == $c_width ) && ($height == $c_height)) {

			} else {
				//check if i need to resize just based on one dimension
				if ($width || $height) {

					if (!$width && $height) {
						$width = $c_width * ($height / $c_height );
					} else {

						//check if no height
						if ($width && !$height) {
							$height = $c_height * ($width / $c_width );
						}
					}

				} else {

					// i have no width or crop so i need to generate them
					$width = $c_width;
					$height = $c_height;
				}

				Image::newInstance()
					//->enableDebug()
					->read($source)
					->Crop(
						$width ,
						$height , 
						$x , 
						$y , 
						$c_width , 
						$c_height						
					)
					->save(
						$source, 
						90 , 
						0644
					)
					->destroy();
			}

		}

		$source = $_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"];
		$destination = $_CONF["path"] . $_CONF["upload"] . $field["path"] . $field["file"]["default"] . $_POST[$field["file"]["field"]] . $field["file"]["ext"];




		if (!is_file($source))
			return false;


		if ($_POST[$key . "_temp"]) {
			$_POST[$key . "_file"] = $_POST[$key . "_temp_file"];
		}


		

		
		//moving the image stored in temp variable
		//check if the file already exists

		CFile::Remove($destination);

		copy(
			$source ,
			$destination
		);	

		
		if (is_array($val["thumbnails"])) {

			foreach ($val["thumbnails"] as $__k => $__thumbnail) {											

				$tn_path = $_CONF["path"] . $_CONF["upload"] . $val["path"] . $__thumbnail["preffix"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"];

				if (file_exists($tn_path)) {
					unlink($tn_path);
				}

					

				// i have at least one thumb dimension
				if (($__thumbnail["width"] || $__thumbnail["height"]) && !($__thumbnail["width"] && $__thumbnail["height"])) {


					if ($__thumbnail["width"]) {
						Image::newInstance()						
							->enableDebug()
							->read($source)
							->ResizeByWidth(
								$__thumbnail["width"] 
							)
							->WaterMark(
								$val["process"]["watermark"]["file"] , 
								$val["process"]["watermark"]["pos_x"],
								$val["process"]["watermark"]["pos_y"]
							)
							->save(
								$tn_path, 
								$val["process"]["quality"]
							)
							->destroy();
					} else {
						Image::newInstance()						
							->enableDebug()
							->read($source)
							->ResizeByHeight(
								$__thumbnail["height"] 
							)
							->WaterMark(
								$val["process"]["watermark"]["file"] , 
								$val["process"]["watermark"]["pos_x"],
								$val["process"]["watermark"]["pos_y"]
							)
							->save(
								$tn_path, 
								$val["process"]["quality"]
							)
							->destroy();
					}
					

				} elseif ( $__thumbnail["width"] && $__thumbnail["height"] ) {
					//i have both dimensions

					Image::newInstance()
//						->enableDebug()
						->read($source)
						->ScaleCrop(
							$__thumbnail["width"] ,
							$__thumbnail["height"]
						)
						->WaterMark(
							$val["process"]["watermark"]["file"] , 
							$val["process"]["watermark"]["pos_x"],
							$val["process"]["watermark"]["pos_y"]
						)
						->save(
							$tn_path, 
							$val["process"]["quality"]
						)
						->destroy();


				} else {
					//i have no dimennsions
					Image::newInstance()
						->read($source)
						->ResizeFit(
							ImageConst::MAX_WIDTH ,
							ImageConst::MAX_HEIGHT
						)
						->WaterMark(
							$val["process"]["watermark"]["file"] , 
							$val["process"]["watermark"]["pos_x"],
							$val["process"]["watermark"]["pos_y"]
						)
						->save(
							$tn_path,
							$val["process"]["quality"]
						)
						->destroy();

				}				
			}
		}
		//setting the image as true			
		//remove the tmp image

		$_POST[$key] = 1;

	
		return true;
	}
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __private_uploads_clean($field) {
		global $base, $_CONF;

		$key = $field["name"];

		if ($_POST[$key . "_temp"]) {
			$source = $_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"];

			if (file_exists($source) ) {
				unlink($source);
			}
		
			return true;
		}
		 
	
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function KeyFields($form) {
		if (is_array($form["fields"])) {
			foreach ($form["fields"] as $key => $val) {

				switch ($val["type"]) {
					case "subtitle":
					case "text":
					break;

					case "widths":
					case "columns":

						$data[] = $key;

						if (defined("STP_LAYOUT_GRID") && (STP_LAYOUT_GRID == "BS3")) {
							$data[] = $key . "_desktop";
							$data[] = $key . "_tablet";
							$data[] = $key . "_phone";
						} else {
							$data[] = $key . "_lg";
							$data[] = $key . "_md";
							$data[] = $key . "_sm";
							$data[] = $key . "_xs";
						}
					break;

					default:

						if ($key == "box") {
							foreach ($val as $k => $v) {
								if (is_array($v["fields"])) {
									foreach ($v["fields"] as $_k => $_v) {

										switch ($_v["type"]) {

											case "columns":
											case "widths":
												$data[] = $_k;

												if (defined("STP_LAYOUT_GRID") && (STP_LAYOUT_GRID == "BS3")) {
													$data[] = $_k . "_desktop";
													$data[] = $_k . "_tablet";
													$data[] = $_k . "_phone";
												} else {
													$data[] = $_k . "_lg";
													$data[] = $_k . "_md";
													$data[] = $_k . "_sm";
													$data[] = $_k . "_xs";
												}
											break;

											case "upload":
												$data[] = $_k;
												$data[] = $_k . "_file";
											break;

											case "image":
												$data[] = $_k;
												$data[] = $_k . "_alt";
												$data[] = $_k . "_file";
											break;

											default:
												$data[] = $_k;
											break;

										}
																				
									}								
								}							
							}
							
						} else {		
							
							switch ($val["type"]) {
								case "upload":
									$data[] = $key;
									$data[] = $key . "_file";
								break;

								case "image":
									$data[] = $key;
									$data[] = $key . "_alt";
								break;

								default:
									$data[] = $key;
								break;

							}

							$data[] = $key;
						}
					break;
				}
				
			}
			
			return $data;
		}	
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetField($form , $field) {

		if (is_array($form["fields"])) {
			foreach ($form["fields"] as $key => $val) {

				if ($key == $field) {
					return $val;
				}

				if ($key == "box") {
					foreach ($val as $k => $v) {
						if (is_array($v["fields"])) {
							foreach ($v["fields"] as $_k => $_v) {

								if ($_k == $field) {
									return $_v;
								}								
																		
							}								
						}							
					}
					
				}
				
			}

		}

	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	static function AllFields($form) {

		if (is_array($form["fields"])) {

			foreach ($form["fields"] as $key => $val) {

				if ($key == "box") {
					foreach ($val as $k => $box) {
						if (is_array($box["fields"])) {
							foreach ($box["fields"] as $_k => $_v) {

								if ($_v["restricted"] && CForm::__isRestricted($_v["restricted"])) {
								} else {																	
									switch ($_v["type"]) {
										case "subtitle":
										case "text":
										break;

										case "columns":
										case "widths":
											if (defined("STP_LAYOUT_GRID") && (STP_LAYOUT_GRID == "BS3")) {
												$data[$_k . "_phone"] = $_v;
												$data[$_k .	"_tablet"] = $_v;
												$data[$_k .	"_desktop"] = $_v;
											} else {
												$data[$_k . "_xs"] = $_v;
												$data[$_k .	"_sm"] = $_v;
												$data[$_k .	"_md"] = $_v;
												$data[$_k .	"_lg"] = $_v;
											}

											$data[$_k] = $_v;
										break;

										default:
											$data[$_k] = $_v;
										break;
									}
								}
							}						
						}
						
					}
					
				} else {		

					if ($val["restricted"] && CForm::__isRestricted($val["restricted"])) {
					} else {										
						switch ($val["type"]) {
							case "subtitle":
							case "text":
							break;

							case "columns":
							case "widths":
								if (defined("STP_LAYOUT_GRID") && (STP_LAYOUT_GRID == "BS3")) {
									$data[$key . "_phone"] = $val;
									$data[$key . "_tablet"] = $val;
									$data[$key . "_desktop"] = $val;
								} else {
									$data[$key . "_xs"] = $val;
									$data[$key . "_sm"] = $val;
									$data[$key . "_md"] = $val;
									$data[$key . "_lg"] = $val;
								}
								$data[$key] = $val;
							break;

							default:
								$data[$key] = $val;
							break;
						}
					}
				}
				
			}
			
			return $data;
		}
		
	}
	

	static function DeleteFields(&$form , $fields) {

		if (is_array($form["fields"])) {
			foreach ($form["fields"] as $key => $val) {

				if ($key == "box") {
					foreach ($val as $k => $v) {
						
						if (is_array($v["fields"])) {
							foreach ($v["fields"] as $_key => $_val) {
								if (in_array($_key , $fields)) {
									unset($form["fields"]["box"][$k]["fields"][$_key]);
								}
							}
						}
						
						
					}
					
				} else {

					if (in_array($key , $fields)) {
						unset($form["fields"][$key]);
					}
					
				}
				
			}
			
		}
		
	}


	static function PreProcessImage($crop , $destination){
		if ($crop) {		

			$tmp_img = explode(":" , $crop);

			$width = $tmp_img[0];
			$height = $tmp_img[1];

			$x = $tmp_img[2];
			$y = $tmp_img[3];

			$c_width = $tmp_img[4];
			$c_height = $tmp_img[5];

			$source = $tmp_img[6];



			if (!file_exists($source)) {
				$source = urldecode($source);

				if (!file_exists($source)) {

					return "";
				}
				
			}
			


			$image_data = getImageSize($source);

			//check if the image isnt set to be proportional
			if (!$width && !$height) {
				$width = $c_width;
				$height = $c_height;
			}
				
			//if the image its at the correct size, dont touch it
			if (($image_data[0] == $c_width) && ($image_data[1] == $c_height) && ($width == $c_width ) && ($height == $c_height)) {

				CFile::Remove($destination);

				CFile::Copy(
					$source,
					$destination
				);

			} else {
				//check if i need to resize just based on one dimension
				if ($width || $height) {

					if (!$width && $height) {
						$width = $c_width * ($height / $c_height );
					} else {

						//check if no height
						if ($width && !$height) {
							$height = $c_height * ($width / $c_width );
						}
					}

				} else {

					// i have no width or crop so i need to generate them
					$width = $c_width;
					$height = $c_height;
				}

				CFile::Remove($destination);
				

				Image::newInstance()
					//->enableDebug()
					->read($source)
					->Crop(
						$width ,
						$height , 
						$x , 
						$y , 
						$c_width , 
						$c_height						
					)
					->save(
						$destination, 
						90
					)
					->destroy();
			}

		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function setAclMod($mod) {
		$this->aclMod = $mod;
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function convertFromMask($mask , $val) {
//		debug($mask);
//		debug($val,1);


		switch ($mask) {

			case "mm/dd/yyyy":
				if ($val) {
					return strtotime($val);
				}				
			break;

			case "yyyy/mm/dd":
				if ($val) {
					return strtotime($val);
				}
				
			break;

			case "currency":
				return str_replace("," , "" , $val);
			break;
		
		}

		return $val;
						
	}

	function convertToMask($mask , $val) {

		switch ($mask) {

			case "mm/dd/yyyy":
				if ($val) {
					return CDate::ToStr("%m/%d/%Y" , $val);
				} else {
					return "";
				}
				
			break;

			case "yyyy/mm/dd":
				if ($val) {
					return CDate::ToStr("%Y/%m/%d" , $val);
				} else {
					return "";
				}				
			break;

			case "currency":

			break;
		
		}

		return $val;
						
	}
	
	
}

/*

History


v1.1 December 2014
	Unreleased
		Removed	Double select and double = true, 
		Removed Phone
		Removed Alternance tags from lists 

		Removed image flash uploader
		Removed image old html uploader

		Removed upload flash uploader
		Removed upload old html uploader

		Added to file uploader allowed="pdf|gif|etc"
		Added getField();

		Added hidealt=true for image field
		Added html5 image uploader support based on jquery-file-upload

v1.0 July 2014
	Released
		Upgraded to support 5.4
		Added multiple new controls and options
		Using bootstrap for frontend generation
		Fixed tons of bugs
		Optimised existing code.

v0.1
		Added support for flash cropper
		Added support for flash uploader
		Moved all elements in its own function
		Removed the decodeentities from description for form->editelement
v0.0.13
	Unreleased
		Added multiple tables for relation type from simple list and drawelement		
		Changed DrawElement its now split in functions for each element type		
	

v0.0.12
	Monday 02 June 2008
		Added doubleselect or double=true to droplist element
		Added exists=true to validate forms, opposite of the unique=true
		Added errors code to the validate errorCode = 1..5 and the defined constants
		Added type="calendar" to SimpleForm(); 
				<cal default="eval:time();" type="calendar" title="Publish Date">
					<calendar
						time="true"
						align="Bl"
						range="from:to"
						style="us|eu"
						
						[..] all params supported by the calendar
					/>
				</cal>
		Added eval:php function to the default="eval:time()"
		Added ProcessItems function
		Added crop=true to thumbnails, requieres the last library of images.
		Added support for simplelist->relation->multi=true when values are from <options>
		Added support for usstates / states / castates and rostates 
		Added support for multiple records in categories / (ro|ca|us states)
		Changed store record to use CForm:ProcessVariables
		Full php 5 compatible

#EXPERIMENTAL
		Changed the htmlentties in text elements and simple list in order to show the special chars romanian , french etc. so now if you have
		<p> inside the field it will be parsed as html it wont appear the code anymore.
#

		Fixed recognition of empty=true and value=0 for droplists and related
		Fixed droplists with multilevel for php5
		Fixed Calendar default date if not valid
		Fixed automatic url genration for text fields in details mode
		Fixed variables transmision over the search pages
		Fixed sql cacheing for simple list
		Deprecated alternance=true for editable forms, its my default now

v0.0.11
	Wensday 1 August 2007

### BUG PHONE VALID ISNT WORKING RIGHT I:X:X now is A:X:X
		Added restricted="eval:.." to form edit, tabs, simplelist for dinamicaly limitations.
		Added referers="field1,field2" as an alias to <referers>.... to Form. also the refereed fields are automaticaly be marked as been refered.
		Added timezones field for show.
		Added multi=true for relation fields to SimpleList
		Added nolinks=true to SimpleList <header> 
		Added nobr=true for text fields in show form
		Added "self.conf.url" to CForm::GlobalVars()
		Added IN ( similar for WHERE x in () for seach/sql_fields )
		Added storeredirect=STOREDETAILS it will redirec to details page for add and edit.
		Added simplelist-type="image" tooltip text title=""
		Added alternance and valternance to simplelist
		Added $this->_set_nochecks to sql admin for the cases when i update a few fields and i dont want he checkboxes to be reseted ( must be set from the php only )
		Added height to <image / <process, if height isnt then will be ignored

		Changed simplelist <header> if no se the gray part wont appear
		Changed simplelist <image to acced othe links then enlarge image ones
		
		Fixed image height and adminheight, if exists the image will be force to the certain height if not the proportion will be kept
		Fixed checkbox when in displaymode added both values label="<true_val>|<false_val>"
		Fixed type="usstates" , empty droplist
		Fixed IN_SET if no value specified it wont appears
		Fixed template problem for php5 for the search sections
		Fixed various array_merge warnings for php5
		Fixed simplelist->relation cache to avoid douplicate queries.
		Fixed various imcompatibilities with php5.1
		Fixed alternance="true" for DrawElement()
		Fixed droplist default text in noneditable mode.
		Fixed Search Header, acceptsn emtpy headers now to be transmited simplelist		
		Fixed validatevars for imgCHECK element.
		Fixed showing error for validate routing for mutiple droplist.
		Fixed an older date fix for mktime
		Fixed $extra[<D|a|e>]["fields"]...
		Fixed appearing of the default image in simple list.
		Fixed SHOW::<section> to remove the after_save field

		NOTE changed the header to match to OX and current year

v0.0.10
	Wensday 8 November 2006 
		Added IN_SET ( for seach/sql_fields alias to FIND_IN_SET - sql function )
		Added maxchars_text to SimpleList fields
		Added color="fg:bg" to SimpleList fields
		Added font="b,u,i" BOLD, UNDERLINE, ITALIC
		Added ordering to all columns in simple list
		Added radio w/ alias radiolist for droplist
		Added checklist for droplists w/ multi = true
		Added ID to button
		Added editable = false to all types
		Added phone field (xxx-xxx-xxxx) to show form, sql, admin, validate, size="box1size,box2size,box3size"
		Added html_entities_decode attribute to text tag
		Added onclick='' to checkbox
		Added editable=false to checkbox
		Added nolink=true to simpllist/image to remove the link from the image. Also added border=x
**		Added multi='true', default='select1,select2' size='xrows' for multiple selects
		Added all javascript events to all elements

**		Fixed multi=true for checlist in sqladmin
		Fixed ProcessVars _arr when nonarray vars passed then dont process it
		Fixed empty options
		Fixed password confirmation in CFORM::Validate()
		Fixed loose of original value in simplelist when link= is used
		Fixed phone showing when phone_arr isnt array
		Fixed sqladmin returnurl when the variable contaigns no / char.
	
		Changed refered elements, referer="true" became referer="refering_field", needed for validation
		Changed simple list query type. When empty build an <sql> group and execute as requested.
		Changed validate="" if the field is filled and validate exists it will be validated even if required=false

		Rewrited the droplist and related subroutine
		Removed subtypes from droplist

v0.0.9
	Tuesday 3 January 2006 
		Removed the showpassword button from password type and added show="true" for showing it
		Changed droplists <dynamic> to support descendendt numbers 2005-1900
		Changed the description for the fields from editable pages to support content from external files, html or not.
		Added checkIMG tag ( enter the text from image in the box to can submit the form ) it works w/ local/after.forms.private.php
		Added nobr=true attribute to the simple list fields
		Added romanian states as ROstates, editable=false and usetext to use the text instead of the shornames for droplists
		Added new class CFormSettings, usefull for the settings elements.
		Added more usefulll variables to globalvars self.linkuid.add/delete...edc delete in section.xml for each $_GET[sub],
			self.action, and doing variables replaces in the global vars too
		Added after_save tag usefull when you need to add many records, avoids click every time on "add"
		Added default tag for simplelist fields (LATER MAKE IT COMPLEX ( eval etc )) 
		Added support for comment elements to get the text from the $values is is set.
		Added urilink in the main sqladmin xml file.
		Added <help file="help/cvv2.html" location="module" type="popup"/> ( popup w/ help for form fields )
		Remove the buttons from the html editor no need of it as far, will be redone in future
		Fixed the mysql error when no tables and db are passed to the object
		Fixed the returnurl when the variable wasnt in lower case for Editable forms.
		Fixed the variable name from vars when the name was the same with the ones from the fields
		Fixed align atribute for the comment elements
		Fixed sqladmin move_uploaded_files to copy.
		TO ADD ident to collapse

v0.0.7
	Saturday 3 September 2005
		Added link feature to simplelist fields.
		Added new preexisted variables, organized them in one function instead of all over the code:
			self.file, self.mod, self.sub, self.action, self.var.mod, self.var.sub, self.var.action, self.uid, 
			self.uidvar, self.link, self.linkuid, self.location, self.title, self.previous, self.previous_enc
		Changed the extended element not to show the title when it is missind, template altration too
		Added SIMPLE LIST: sql->vars->table type supports the import param, to get other tables from $this->tables
		Added date / editable = false, it already knows about the params m/d/Y if not set the user ones.	
		Fixed date apearing when the main field was empty and the _month _day _year exists
		Fixed the checkbox autofill
		Fixed the subtitle apearance when no buttons are defined in Edit Form
		Various bug fixes

v0.0.6
	Sunday 3 May 2005 ( one of the most important days :) )
		Added collapse option for simple list
		Added Canada states CAstates type.
		Added denyhtml to textarea, not to htmlentities the text from it.
		Added storeredirect=ADDDETAILS, when a new field is added to db, then the browser is redirected to the record details instead of HTTP_REFERER, this is usefull for the cases when
			you add a record, then you have to add some subrecord to that, and insted of ADD->STORE->LIST->DETAILS will be ADD->STORE->DETAILS. Smmother navigation.
		Added protected="table_field" for list buttons and for FormFields, if 1 then the fields will not apear, if showprotected=true then the fields will apear as text, not editable.
		Added complex_eval type, the return isnt put in the $tpl_var, so now we can have complex phpcode there :) >:)
		Added easy navigation variables, autogeneration of returnurl input field, PRIVATE.prev page and PRIVATE. action title varibales.
		Added align option for text fields
		Added allownl=true in simple list header
		Added [html][pre] to form generator
		Added comment tag in forms
		Added fileexists=true to Validate
		Added option to load/save the values from/to text files
		Added editable=flase to date field
		Added default value to text field
		Added <vars> to Simple list
		Added time to date field
		Added eval in all default values
		Added state field
		Added countries field
		Added pre and after for Simple List
		Added upload fild, extended the image field
		Added price action to text field in edit forms
		Added page type for sql vars in simple list
		Added form type for sql vars in simple list
		Added support for tree droplist in relation field ( not editable one )
		Added CURRENT_PAGE variable in simple list pages
		Added confirmation page for deleting items when rconfirm=true title and description are the variables

		Changed [html] to support extern files
		Fixed paging return url, when jumping from page to page the url encode was lost
		Fixed the slash problem in the database, now handling the slashed directly from the database
		Fixed global vars replacing in links
		Fixed the uniq=true in edit mode
		Fixed the path in CSQLAdmin path
		Fixed buttons values ( now checking if value="true" instead of is_set($value) )
				Fixed pagging count
		Fixed Comment field templates lossing
		Fixed vars replacing in form acction
		Fixed saving/reading external files content
		Fixed the template global vars in simple list
		Fixed tree droplists / saving and showing
		Fixed date incompatibility with Windows OS
		Fixed server_referer when the browser is redirected using javascript ( in delete operations )
		

		Various bug fixes

v0.0.5
	Saturday 1 May 2004
		Added alternance to drawelement function
		Added <subtitle> to Simple List, it apears on the bar wiht the buttons and search box
		Added extra content after each element $extra["fields"]["field_name"] in CForm and $extra["edit|add|details"]["fields"]["field_name"] in CSQLAdmin
		Added extra content to pre and after form content $extra["pre|after"] in CForm and $extra["edit|add|details"]["pre|after"] in CSQLAdmin
		Added <html tag to textarea and a first alhpa of html editor.
		Added support to configure the buttons to apear in html editor
		Added suffix and preffix to SimpleList elements.
		Added subtitle element.
		Added html|pre|and after form in Show
		Added html|pre|and after form in SimpleList
		Added javascript|pre|after in Show
		Added "disabled" option to droplist's options
		Added relation type and editable=false to droplists
		Fixed the buttons variables if no <buttons tag exists
		Fixed the SimpleList is the <items is missing
		Fixed the problem when is a referer or multiple to an element which doesnt exist
		Fixed the preffix and suffix order in DrawElement		
		Fixed the images field, for uploading
		Fixed tn generation.

v0.0.4
	Monday 29 March 2004
		Added referer option to elements, now you can have more then one "input" on the same element
		Added multiple option to elements
		Added the <condition ,<order and <ordermode tags to droplist/relations, to select only a custom number of records from db
		Added the preffix and suffix to fields $ [___] (USD)
		Added PRE and AFTER form javascript code
		Added ONCHANGE to droplist
		Added elements count _COUNT to list form
		Added options to list form, future will be added the relations
		Description gets a html_entity_decode before showing
		Changed the saving part to detect if the <table_uid> is set = edit else = add
				
v0.0.3
	Wensday 24 March 2004
		Moved SimpleList from sqladmin in forms class
		Added image element to SimpleList
		Added date element to SimpleList	
		Instead of $form array the data can be a path to a xml file
		The template is passed to sql admin, no longer loading from generic_form

v0.0.2
	Tuesday 16 March 2004
		Fixed, add/edit SQL query.

	Sunday 14 March 2004
		Added search support for list section.
		Added header titles to list section.
		Fixed the buttons apearance in list. ( they dont apear broken anymore )
		Added upload/resize/efects image form to forms library, FUCK loosing the image if the forms isnt complety
		validated from first time.
		Added html editor to forms library.		
		Fixed the image loosing when the form wasnt validated.
		Added the download from web image.

v0.0.1
	Wensday 3 March 2004 
		First version with basic options, edit, list, add.

*/

/*


FIELD STRUCTURE // edit/add/details


//forms, crappy, but this is the only file to remember how this crap works.

<form> //all files must start and end with this tag	

	//		<msg field="link_id" field-type="textbox" field-sub="link_order" field-id="link_id" field-value="link_order" align="center" field-size="35" field-align="right" header="Order" width="40" type="field"/>


		<check type="checkIMG" src="register.php?security" required="true" validate="A:8:8">
			<title>Security Code</title>
			<description>Enter the text from the image in the box bellow. The text is CASE SENSITIVE.</description>
		</check>



	//for simple list
	<collapse enable="true" id="project_milestones" default="false" cookie="true"/>

	<title></title> //the title of the form, it ususaly apear in the top of the html table.
	<action></action> // the link where the data will be posted
			  //specials type = add , new data is ready to be added, edit = its a simple edit operation

	<name></name>	  // the name of the html form <form name="..."
	<widht><width>	  // the width of the form ( the html block )

	<formtag><formtag> // if true then the <form action ... will be added
	<border></border>  // if true then the border , which contaign the title and the <form tag

	
	<buttons> //define what buttons to apear in form, and where
		<set>
			<footer></footer> //if true then all buttons will apear in footer
			<header></header> //if true then all buttons will apear in header
					  // if both are set then the buttons apears in both places	
		</set>
		
		<button>
			<onclick></onclick> // javascript content which to be execudet at onclick event
			<button></button>   // the name of the button, i dont acctualu see the point to havbe the same as tag
					    // the image with the name button_{button}.gif will be showed for it, this depending
					    // of the javascript code which draws the button.
			<location></location> // where to go when the button is pressed, like <a href="location" ...
		</button>
		[...]
		// the rest of the buttons
	</buttons>

	<fields> // the list of the fields which will apear on page

		<field_name>	//the name of the fields exactly how it is in the database
			<name></name>  // in case you want to use the same tag for all fields <field ... you have to specify the 
				       // name of the field ( drom the database table))
			<type></type>  // what type the field is, avaible types listed bellow
					  hidden, - the field will not apear visual, will be just a hidden input
					  textbox
					  droplist
					  image
					  droplist
					  checkbox
					  html
					  textarea
					  radio
					  text
					  button

			<alternance>true</alternance> //alternate 2 colors for table rows

			<size></size> // the size of the field, it can have diferent semnifications depending of the field type
					X:Y and the type is textarea means the cols="x" and rows="y"
					S:M and type type is textbos means the size="s" and maxlength="m"

			<unique></unique> // if is true then the the database will be searched for duplicate names
			<unique_err></unique_err> // what error to be displayed to user in case there are duplicates

			<referer></referer> //if true then the field will apear in combination with other field, the title and 
					      the description will be ignored then, still having problems at validation
					      ex: Name: [________] [_______]
			
			<required></required> // if is true, then the field will be required
			<validate>A:3:20</validate> // the validation formula which will be used
						       A = the type, can be A, Z, I, ... see the common,php for all 
						       3 = the min allower chars
						       20 = the maximum number of chars allowed

						       NOTE: even if required is false, if any text is presend the it twill be validated

			<title></title> // the title of the field which will apearin the left part: Your Name: [_______]
			<description></description> // optional description/hint for this field
			<help 
					file="help/cvv2.html"  // the location of the file 
					location="module|site"  // location relative to module location or not
					type="popup|over"	// what to happen when you click on the ? button , popup or overlib
			/>

			<default></default> // default value
			<forcevalue></forcevalue> // will set this value no matter if other exists
			<action>
				eval,	// executes the default as phpcode and output is put in field value
				price,	// formats the value as a price XX.xx
				int		// formats the value as a integer number
			</action>

			// textarea ONLY
			<html>true</html> // shows a html editor instead oof a textarea, works on Mozilla and Internet Explorere too

			<buttons>		//defines the list of the buttons to apear in html editor. Please take care at ''
				<toolbarX>'button1','button2'..  
			</buttons>
			
			// DROPLIST ONLY

			subtype="tree" parentfield="cat_parent"

			<options>   // block avaible for droplists only, this is for building a droplist using static values from xml
				<option name="1"></option> // in html will apear like <option value="1"></option>
			</options>

			<dinamyc from="100" to="200" width="2" />

			<relation>
				<sql>
					<vars>
						<var import="..." type="eval|var|page|form" />
					</vars>
					<query>SELECT * FROM {TABLE} ....</query>
				</sql>

				<table></table> // the table from database which will be queried
				<id></id> // the field values which will be used for <option value="...."
				<text>code,name</text> // the fields which will be used for the option text, they are fields from table, 
							  thre can be more then one separed with comma, in the text will apeare separed with the
							  charachtest specified in <separator></separator> tags
				<text>
					<field>field_name</field>
					<field field="table_field" preffix="{" suffix="}" />
				</text>

				<separator></separator>
				<condition>`field`='1'</condition> // the were clause which will be used in sql query
				<order>field</order>	//the result will be ordered after 'field' ...
				<ordermode>ASC|DESC</ordermode> //ascending or descending
			</relation>

			<empty></empty> // a set if the droplist to have fullfiled or to have a [slect] option on the first row
			<emptyMSG></emptyMSG> // an optional text which will apear if no options or no relations were found, instead of droplist element

			// <-- END


					
	</fields>				
*/



/**
* description
*
* @param
*
* @return
*
* @access
*/
function restrictedConst($val) {
	return defined($val) && constant($val);
}


?>