<?
if(!$ALLOW_INCLUDE) exit;

class X_MAIL {


	function init() {}


	function send($send_to, $subject, $content, $files=false, $skip_foot=false, $reply_to=false, $embed_images=true, $skip_html_dom=false) {
		global $X, $CONF, $MAILER;

		$this->ENABLE_MAIL_GFX=true;

		if(!is_object($MAILER)) require($this->PATH.'/phpmailer.php');
		$MAILER=new PHPMailer();

		$INPUT_CONTENT=$content;
		if($skip_foot!=true && $this->ENABLE_MAIL_GFX!=true) $content.=$this->add_foot();


		if($embed_images==false) {
			$content=str_replace('url(/userfiles/', 'url('.BASE.'/userfiles/', $content);
			$content=str_replace('="/userfiles/', '="'.BASE.'/userfiles/', $content);
			$content=str_replace('="/images/', '="'.BASE.'/images/', $content);
		}

		$n='<br />
';
		$content=str_replace(array('<br />','<br/>','<br>'),array($n,$n,$n),$content);


		if($CONF->MAILER_SMTP_ENABLED==true) {
			$MAILER->IsSMTP();
			$MAILER->SMTPAuth		= true;
			$MAILER->SMTPDebug	= 0; //SMTP debug: 0=off, 1=errors and messages, 2=messages only
			$MAILER->Port			= $CONF->MAILER_SMTP_PORT;
			$MAILER->Host			= $CONF->MAILER_SMTP_HOST;
			$MAILER->Username		= $CONF->MAILER_SMTP_USER;
			$MAILER->Password		= $CONF->MAILER_SMTP_PASS;
			$MAILER->From 		  	= $CONF->MAILER_SMTP_USER;

			if(empty($reply_to)) $reply_to=array($CONF->MAILER_FROM_EMAIL, $CONF->MAILER_FROM_NAME);
		} else {
			$MAILER->IsMail();
			$MAILER->From = $CONF->MAILER_FROM_EMAIL;
		}

		$MAILER->CharSet 	= "utf-8";
		$MAILER->FromName = $CONF->MAILER_FROM_NAME;
		$MAILER->Subject 	= $this->encoder($subject);
		$MAILER->AltBody 	= strip_tags($content);
//		$MAILER->WordWrap	= 80;


		if(!empty($reply_to)) {
			if(is_array($reply_to)) {
				$MAILER->AddReplyTo($reply_to[0], $reply_to[1]);
			} else {
				$MAILER->AddReplyTo($reply_to);
			}
		}

		if(is_array($files) && count($files)>0) foreach($files as $file) $MAILER->AddAttachment($file[0], $file[1]);


		if($this->ENABLE_MAIL_GFX==true) {
			$content=$this->insert_mail_gfx($content);
		}


		if($skip_html_dom!=true) {
			$content=$this->add_dom($subject, $content);
		}
		$MAILER->MsgHTML($content);

		if(!@is_array($send_to)) {
			$temp=$send_to;
			unset($send_to);
			$temp=str_replace(array(' ',',',';'), array('',';',';'), $temp);
			$send_to=@explode(';',$temp);
			unset($temp);
		}

		if(count($send_to)>0) {
			foreach($send_to as $email) {
				$MAILER->ClearAddresses();
				$MAILER->AddAddress($email);
				$send_status=$MAILER->Send();

				if($send_status!=true || $send_error==true) {
					if(empty($mailer_err)) $mailer_err=$MAILER->MSG['error'];
					if(empty($mailer_full_err)) $mailer_full_err=$MAILER->FULL_ERROR;

					$input_data=array(
						'send_to'			=> $send_to,
						'subject'			=> $subject,
						'content'			=> $INPUT_CONTENT,  //not modif input
						'files'				=> $files,
						'skip_foot'			=> $skip_foot,
						'reply_to'			=> $reply_to,
						'embed_images'		=> $embed_images,
						'skip_html_dom'	=> $skip_html_dom,
					);

					if($this->RESEND==false) $X->DB->query(' INSERT INTO _mail_unsend (email, subject, body, date, error, full_error, input_data) VALUES ("'.$X->STR->in($email).'","'.$X->STR->in($subject).'","'.$X->STR->in($content).'","'.date('Y-m-d H:i:s').'","'.$mailer_err.'","'.$mailer_full_err.'","'.$X->STR->in(serialize($input_data)).'") ');
					$send_error=true;
				}
			}
			return ($send_error==true ? false : true);
		} else {
			return false;
		}
	}


	function resend($input_data) {
		global $X;

		$in=unserialize($X->STR->out($input_data));
		$this->RESEND=true;
		$state=$this->send($in['send_to'], $in['subject'], $in['content'], $in['files'], $in['skip_foot'], $in['reply_to'], $in['embed_images'], $in['skip_html_dom']);
		$this->RESEND=false;
		return $state;
	}


	function add_dom($subject, $body) {
		return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional //EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>'.$subject.'</title>
<style type="text/css">
	html, body, table, td { color:#000; font-family:Arial, Tahoma, sans-serif; font-size:12px; }
	p { margin-top:0px; }
	a { outline-style:none; color:#E30613; }
</style>
</head>

<body style="margin:0px; padding:0px;">

'.$body.'

</body>
</html>';
	}


	function add_foot() {
		global $X;

		return '
			<div style="clear:both; margin-bottom:50px;"></div>
			<span style="display:inline-block; color:#aaa; border-top:1px dotted #aaa; font-size:11px;">
				<span style="display:inline-block; padding:6px 0px 30px 0px;">'.$X->CONF->MAILER_FOOT_TEXT.'</span>
			</span>
		';
	}


	function encoder($input, $charset='utf-8') {
		preg_match_all('/(\s?\w*[\x80-\xFF]+\w*\s?)/', $input, $matches);
		foreach($matches[1] as $value) {
			$replacement = preg_replace('/([\x20\x80-\xFF])/e', '"=".strtoupper(dechex(ord("\1")))', $value);
			$input = str_replace($value, '=?'.$charset.'?Q?'.$replacement.'?=', $input);
		}
		return $input;
	}


	function is_email($email) {
		if(empty($email)) return false;
		$pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$";
		return preg_match("#^".str_replace('#','/#',$pattern)."$#i", $email);
	}


	function protect($email, $non_click=false) {
		$parts=@explode('.', $email);
		$new_parts=@implode('</span>.<span>', $parts);
		$new_mail=str_replace('@', '<span>@</span>', '<span>'.$new_parts.'</span>');

		if($non_click==true) return '<script type="text/javascript">document.write("'.$new_mail.'");</script>';
		return '<script type="text/javascript">/*<![CDATA[*/ document.write("<a href=\"#\" onclick=\"window.location=\'mailto:\'+this.textContent||this.innerText; return false;\">'.$new_mail.'</a>"); /*]]>*/</script>';
	}


	function get_template($klucz, $data=false, $force_lang=false) {
		global $X;

		if(!empty($data) && count($data)>0) foreach($data as $key => $value) $VARS[$key]=$value;

		$tmpl=$X->DB->fast(' SELECT id, title, content FROM _mail_templates WHERE klucz="'.$klucz.'" '.(!empty($force_lang) ? 'AND lang="'.$force_lang.'"':'').' ');
		if(empty($tmpl['id'])) die('EMAIL TEMPLATE NOT FOUND: <b>'.$klucz.'</b>');

		$title=$X->STR->outt($tmpl['title']);
		$body=$X->STR->out($tmpl['content']);

		preg_match_all('/{{([^}]+)}}/e', $title, $vars);
		if(count($vars[1])>0) foreach($vars[1] as $t) $title=str_replace('{{'.$t.'}}', $VARS[$t], $title);
		preg_match_all('/{{([^}]+)}}/e', $body, $vars);
		if(count($vars[1])>0) foreach($vars[1] as $t) $body=str_replace('{{'.$t.'}}', $VARS[$t], $body);

		return array('title'=>$title, 'body'=>$body);
	}


	function enable_gfx() {
		$this->ENABLE_MAIL_GFX=true;
	}


	function enable_unsubscribe() {
		$this->ENABLE_MAIL_UNSUBSCRIBE=true;
	}


	function wylacz($html) {
		if(!empty($html)) {
			$this->WYLACZ_HTML='
				<tr><td><br /><br /></td></tr>
				<tr><td style="background:#ddd; color:#666; font-size:12px; line-height:16px; padding:15px 20px 15px 20px">'.$html.'</td></tr>
			';
		}
	}


	function insert_mail_gfx($html) {
		global $X;

		if($this->ENABLE_MAIL_GFX!=true) return false;
		unset($this->ENABLE_MAIL_GFX);

		$ret='
			<table cellpadding="0" cellspacing="0" style="width:100%;">
				<tr>
					<td style="padding:10px 0px 10px 20px; background:#f4f5f6; border-bottom:3px solid #E30613; font-size:0px;">
						<img src="'.ROOT.'/images/email_logo.png" width="136" height="48" alt="" border="0" />
					</td>
				</tr>
				<tr>
					<td style="padding:30px 20px 50px 20px">
						'.$html.'
					</td>
				</tr>
				'.$this->WYLACZ_HTML.'
				<tr>
					<td style="padding:15px 20px 15px 20px; background:#E30613; color:#fff; font-size:12px;">
						'.$X->CONF->MAILER_FOOT_TEXT.'
					</td>
				</tr>
			</table>
		';

		unset($this->WYLACZ_HTML);
		return $ret;

//				'.($this->ENABLE_MAIL_UNSUBSCRIBE==true ? '<div style="float:right; margin-top:8px;">Jeśli nie chcesz otrzymywać wiadomości tego typu, kliknij <a href="'.BASE.'/wypisz_sie/" target="_blank" style="color:#fff"><b>TUTAJ</b></a> i wypisz się.</div>':'').'
	}



}
$this->MAIL = new X_MAIL();
$this->MAIL->DIR = LIBS.'/_mail';
$this->MAIL->PATH = LIBS_PATH.'/_mail';

class X_URL {


	function init() {}


	function mod($url) {
		$from	= array('ą','ą','ć','ę','ł','ń','ó','ś','¶','ż','Ľ','ź','Ą','Ą','Ć','Ę','Ł','Ń','Ó','Ś','¦','Ż','¬','Ź','"',"'",':','(',')','{','}','[',']',' ','.',',','/','\\','*','&reg;','?','@','=','+','!','^','$','%','&','~','#',':',';');
		$to	= array('a','a','c','e','l','n','o','s','s','z','z','z','A','A','C','E','L','N','O','S','S','Z','Z','Z','' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'-','-','' , '-','-','-' ,'x','','' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' );

		$url=strtolower(strip_tags(trim($url)));
		$url=str_replace($from, $to, $url);
		$url=strtolower($url);
		return preg_replace('/(-){2,}/', '-', $url);
	}


	function modNAME($string) { // $KOMPONENTY->modNAME
		$zamien_co=array('š','ą','ć','ę','ł','ń','ó','ś','ś','ż','ź','ž','Ą','Ľ','Ć','Ę','Ł','Ń','Ó','Ś','Ś','Ż','Ź','"',"'",':','(',')',' ','.',',','/','\\','*','&reg;','?','@','=','!','^','$','%','&');
		$zamien_na=array('a','a','c','e','l','n','o','s','s','z','z','z','a','a','c','e','l','n','o','s','s','z','z','' ,'' ,'' ,'' ,'' ,'_','_','' , '_','_','_' ,'x','','' ,'' ,'' ,'' ,'' ,'' ,'' ,'');
		$string=str_replace($zamien_co,$zamien_na,strtolower(strip_tags($string)));
		$string=str_replace('__','_',$string);
		$string=str_replace('__','_',$string);

		$string=preg_replace('/#([0-9]+);/','',$string);
		return $string;
	}


	function get($add=false, $custom_url=false, $keep_empty=false, $return_all=false) {
		$request=str_replace("&amp;", "&", !empty($custom_url) ? $custom_url : $_SERVER['REQUEST_URI']);
		$link=parse_url($request);
		$url=$link['path'];
		if(!empty($link['query'])) $url.='?'.$link['query'];

		if(!empty($add)) {
			list($script, $params) = @explode('?',$url);
			$url=$script;
			$tab=explode('&',$params);
			if(count($tab)>0) foreach($tab as $val) {
				list($param[], $value[]) = @explode("=",$val);
			}

			$size=sizeof($param);
			$tab=@explode('&',$add);

			if(count($tab)>0) foreach($tab as $val) {
				list($p,$v) = @explode('=',$val);

				$found=false;
				for($i=0; $i<$size; $i++) {
					if($param[$i]==$p) {
						$value[$i]=$v;
						$found=true;
						break;
					}
				}

				if($found==false) {
					$param[$size]=$p;
					$value[$size]=$v;
					$size++;
				}
			}

			for($i=0; $i<$size; $i++) {
				if(strpos($url,'?')==0) {
					if((!empty($param[$i]) && (!empty($value[$i])) || is_numeric($value[$i])) || $keep_empty==true) $url.='?'.$param[$i].'='.$value[$i];
				} else {
					if((!empty($param[$i]) && (!empty($value[$i])) || is_numeric($value[$i])) || $keep_empty==true) $url.='&'.$param[$i].'='.$value[$i];
				}
			}
		}

		if($return_all==true) {
			return $url;
		} else {
			return @array_pop(explode('/', $url));
		}
	}


	function redirect($url=false) { return $this->go($url); }
	function go($url=false) {
		if(empty($url)) $url=$_SERVER['REQUEST_URI'];
		header('HTTP/1.1 301 Moved Permanently');
		header('Location: '.$url);
		exit;
	}


	function get_go($url) { $this->go($this->get($url)); }
	function go2($url) { $this->go($this->get($url)); }



}
$this->URL = new X_URL();
$this->URL->DIR = LIBS.'/_url';
$this->URL->PATH = LIBS_PATH.'/_url';

class X_IMG {


	function init() {}


	function img($src, $margin_left=0, $margin_right=0) {
		return '<img src="'.$src.'" alt="" '.($margin_left!=0 || $margin_right!=0 ? 'style="'.($margin_left>0 ? 'margin-left:'.$margin_left.'px;':'').($margin_right>0 ? 'margin-right:'.$margin_right.'px;':'').'" ':'').'/>';
	}


	function flag($src, $margin_left=0, $margin_right=0, $tip=false) {
		global $X;

		$tip=(!empty($tip) ? $X->FORM->tip($tip).' ':'');
		return '<img src="/admin/images/flags/'.strtolower($src).'.gif" '.$tip.'alt="" '.($margin_left!=0 || $margin_right!=0 ? 'style="'.($margin_left>0 ? 'margin-left:'.$margin_left.'px;':'').($margin_right>0 ? 'margin-right:'.$margin_right.'px;':'').'" ':'').'/>';
	}


	function flag2($src, $margin_left=0, $margin_right=8, $tip=false) {
		global $X;

		$tip=(!empty($tip) ? $X->FORM->tip($tip).' ':'');
		return '<img src="/admin/images/flags/'.strtolower($src).'.gif" '.$tip.'alt="" '.($margin_left!=0 || $margin_right!=0 ? 'style="border:1px solid #ccc; '.($margin_left>0 ? 'margin-left:'.$margin_left.'px;':'').($margin_right>0 ? 'margin-right:'.$margin_right.'px;':'').'" ':'').'/>';
	}



	function tick($bool, $margin_left=0, $margin_right=0) {
		$img=((int)$bool==0 ? 'tick-no.gif' : 'tick-yes.gif');
		return '<img src="'.ICONS.'/button/'.$img.'" alt="" '.($margin_left!=0 || $margin_right!=0 ? 'style="'.($margin_left>0 ? 'margin-left:'.$margin_left.'px;':'').($margin_right>0 ? 'margin-right:'.$margin_right.'px;':'').'" ':'').'/>';
	}


	function del($post, $dir) {
		global $X;
		$file=$_POST[$post];
		if(empty($file)) return false;

		@unlink($dir.$file);
		@unlink($dir.$X->FILE->add_suffix($file,'_'));
		@unlink($dir.$X->FILE->add_suffix($file,'__'));
		@unlink($dir.$X->FILE->add_suffix($file,'___'));
		@unlink($dir.$X->FILE->add_suffix($file,'____'));
		@unlink($dir.$X->FILE->add_suffix($file,'_____'));
		@unlink($dir.$X->FILE->add_suffix($file,'______'));
		return true;
	}


	function resize($src, $sizes) {
		return require($this->PATH.'/resize.php');
	}


	function resize_free($src, $sizes) {
		return require($this->PATH.'/resize_free.php');
	}


	function rotate($src, $angle, $param) {
		return require($this->PATH.'/rotate.php');
	}


	function GIF_info($file_name) {
		$fp			= fopen($file_name,'rb');
		$result		= @fread($fp,13);
		if(empty($result)) return false;
		$signature	= substr($result,0,3);
		$version		= substr($result,3,3);
		$width		= ord(substr($result,6,1)) + ord(substr($result,7,1))*256;
		$height		= ord(substr($result,8,1)) + ord(substr($result,9,1))*256;
		$color_flag	= ord(substr($result,10,1)) >> 7;
		$bg			= ord(substr($result,11));

		if($color_flag) {
			$tableSizeNeeded 	= ($bg+1)*3;
			$result 				= fread($fp, $tableSizeNeeded);
			$transparentRed	= ord(substr($result, $bg*3, 1));
			$transparentGreen	= ord(substr($result, $bg*3+1, 1));
			$transparentBlue	= ord(substr($result, $bg*3+2, 1));
		}
		fclose($fp);

		return array(
			'version'			=> $version,
			'color_flag' 		=> $color_flag,
			'transparent_r' 	=> $transparentRed,
			'transparent_g'	=> $transparentGreen,
			'transparent_b' 	=> $transparentBlue,
			'width' 				=> $width,
			'height' 			=> $height,
		);
	}



}
$this->IMG = new X_IMG();
$this->IMG->DIR = LIBS.'/_img';
$this->IMG->PATH = LIBS_PATH.'/_img';

class X_FLASH {


	function init() {}


	function get($id, $file, $width, $height, $wmode_trans=false, $flash_vars=false, $version=10, $allow_fs=false) {
		global $X;
		$X->JS['swfac'] = JS.'/swfac.js';

		if($width=='auto' || $height=='auto' || $width==false || $height==false) {
			$size=$this->get_info($file);
			$width=$size['width'];
			$height=$size['height'];
		}

		if(@is_array($flash_vars) && count($flash_vars)>0) foreach($flash_vars as $fl_name => $fl_val) {
			if(++$lp==1 && !stristr($plik,'?')) $sep='?'; else $sep='&';
			$file.=$sep.$fl_name.'='.$fl_val;
		}

		return "<script type=\"text/javascript\">AC_FL_RunContent('codebase','http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=".$version.",0,0,0','movie','".$file."',".($wmode_trans==true ? "'wmode','transparent',":"")."'width','".$width."','height','".$height."',".($allow_fs==true ? "'allowfullscreen','true',":"")."'src','top','quality','best','menu','false','pluginspage','http://www.macromedia.com/go/getflashplayer','movie','".$file."');</script>";
	}


	function get_ob($id, $file, $width, $height, $wmode_trans=false, $flash_vars=false, $version=10) {
		global $X;
		$X->JS[]=JS.'/swfobject.js';

		if($width=='auto' || $height=='auto' || $width==false || $height==false) {
			$size=$this->get_info($file);
			$width=$size['width'];
			$height=$size['height'];
		}

		if(@is_array($flash_vars) && count($flash_vars)>0) foreach($flash_vars as $fl_name => $fl_val) {
			$vars.='fo.addVariable("'.$fl_name.'", "'.$fl_val.'"); ';
		}

		return '
			<div id="div_swf_'.$id.'"></div>
			<script type="text/javascript">
			   var fo = new FlashObject("'.$file.'", "'.$id.'", "'.$width.'", "'.$height.'", "'.$version.'");
				'.(!empty($wmode_trans) ? 'fo.addParam("wmode", "transparent");':'').'
				fo.addParam("menu", "false");
				'.$vars.'
			   fo.write("div_swf_'.$id.'");
			</script>
		';
	}


	function get_info($file) {
		require_once($this->PATH.'/header.php');
		$FLASH=new FlashHeader($file);
		return $FLASH->getimagesize();
	}



}
$this->FLASH = new X_FLASH();
$this->FLASH->DIR = LIBS.'/_flash';
$this->FLASH->PATH = LIBS_PATH.'/_flash';

class X_DB {


	function split($query, $split_by=0, $url_start=false, $url_end=false, $get_var=false, $total_rows_query=false, $first_page_base=false, $custom_total_rows=false, $custom_start_offset=0) {
		global $X;

		if(empty($get_var)) $get_var='page';
		$_GET['split_by']=(int)$_GET['split_by'];
		if($_GET['split_by']>0 && $split_by>0) $split_by=$_GET['split_by'];

		if($split_by==0 || !is_numeric($split_by)) { /* ... */ } else {
			$this->GET_VAR=$get_var;
			$page=(int)$_GET[$get_var];
	      if(!is_numeric($page) || $page<1) $page=1;
			if(ADMIN===true) {
				$navi_cut='<span class="dots">...</span>';
			} else {
				$navi_cut='<li class="disabled"><span class="dots">...</span></li>';
			}
			$oscillate=3;

			$go='
				<span class="pagination_custom_page">
				<form action="'.URL.'" method="post" style="display:inline;" onsubmit="if(this.custom_page.value==\'\' || isNaN(this.custom_page.value)) { this.custom_page.focus(); return false;}">
					<span class="pagination_hash">#</span><input type="text" name="custom_page" class="input" style="width:32px; text-align:center" maxlength="4" autocomplete="off" />
					'.(ADMIN===true ? '
						'.$X->FORM->submit_link('<span class="ico w_yes"></span>',false,'button button_gfx_small').'
					':'
						<input type="submit" class="button" value="OK" />
					').'
				</form>
				</span>
			';
		}


		if(empty($custom_total_rows)) {
			if(!empty($total_rows_query)) {
		      $total_rows=$this->fast($total_rows_query);
			} else {
		      $total_rows=$this->num_rows($this->query($query));
			}
		} else {
			$total_rows=$custom_total_rows;
		}

		$pages=@ceil($total_rows/$split_by);


		if($_GET['return_rows_count']==1) {
			$_GET['db_split_initated']=true;
			$_GET['returned_rows_count']=$total_rows;
		}


		if($_GET['page']>$pages && ($pages>1 || !empty($first_page_base))) {
			$_GET['page']=$page=$pages;
			$corrected_page=$page;

			if($corrected_page==1) {
				if(!empty($first_page_base)) {
					$X->URL->go($first_page_base);
				} else {
					$X->URL->go($url_start.$corrected_page.$url_end);
				}
			}
		}


		if($pages<=1) {
			$sql=$X->DB->query($query);
			return array('query'=>$query, 'sql'=>$sql, 'total_rows'=>$total_rows, 'total'=>$total_rows, 'split_by'=>$split_by);
		}

		if($_GET['page']==1 && !empty($first_page_base)) $X->URL->go($first_page_base);


		if(isset($_POST['custom_page'])) {
			$page=(int)$_POST['custom_page'];
			if(empty($page)) $page=1;
			if($page<=1) $page=1;
			if($page>$pages) $page=$pages;

			if(!empty($url_start)) {
				$href=$url_start.$page.$url_end;
			} else {
				$href=$X->URL->get($get_var.'='.$page);
			}
			$X->URL->go($href);
		}

		if($page>1) { //first & prev
			/*
			if(!empty($url_start)) { //first
				$href=$url_start.(1).$url_end;
			} else {
				$href=$X->URL->get($get_var.'='.(1));
			}
			$navi.='<a href="'.$href.'" class="first"></a>';
			*/
			if(!empty($url_start)) { //prev
				if(($page-1)==1 && !empty($first_page_base)) {
					$href=$first_page_base;
				} else {
					$href=$url_start.($page-1).$url_end;
				}
			} else {
				$href=$X->URL->get($get_var.'='.($page-1));
			}
			if(ADMIN===true) {
				$navi.='<a href="'.$href.'" class="prev">&#9664;</a>';
			} else {
				$navi.='<li><a href="'.$href.'" class="prev">&laquo;</a></li>';
			}
		}


		if($pages>13) {
			if($page>=9 && $page<=$pages-8) {
				for($i=1; $i<=1; $i++) $navi.=$this->navi_link($page,$i,$url_start,$url_end,$first_page_base);
				$navi.=$navi_cut;
				for($i=$page-$oscillate; $i<=$page+$oscillate; $i++) $navi.=$this->navi_link($page,$i,$url_start,$url_end,$first_page_base);
				$navi.=$navi_cut;
				for($i=$pages; $i<=$pages; $i++) $navi.=$this->navi_link($page,$i,$url_start,$url_end,$first_page_base);
			} else {
				if($page<=8) {
					for($i=1; $i<=9; $i++) $navi.=$this->navi_link($page,$i,$url_start,$url_end,$first_page_base);
					$navi.=$navi_cut;
					for($i=$pages-2; $i<=$pages; $i++) $navi.=$this->navi_link($page,$i,$url_start,$url_end,$first_page_base);
				} else {
					for($i=1; $i<=3; $i++) $navi.=$this->navi_link($page,$i,$url_start,$url_end,$first_page_base);
					$navi.=$navi_cut;
					for($i=$pages-8; $i<=$pages; $i++) $navi.=$this->navi_link($page,$i,$url_start,$url_end,$first_page_base);
				}
			}
		} else {
			for($i=1; $i<=$pages; $i++) $navi.=$this->navi_link($page,$i,$url_start,$url_end,$first_page_base);
		}


		if($page<$pages) { //next & last
			if(!empty($url_start)) { //next
				$href=$url_start.($page+1).$url_end;
			} else {
				$href=$X->URL->get($get_var.'='.($page+1));
			}
			if(ADMIN===true) {

			} else {
				$navi.='<li><a href="'.$href.'" class="next">&raquo;</a></li>';
			}
			/*
			if(!empty($url_start)) { //last
				$href=$url_start.($pages).$url_end;
			} else {
				$href=$X->URL->get($get_var.'='.($pages));
			}
			$navi.='<a href="'.$href.'" class="last"></a>';
			*/
		}


		if(!empty($navi)) {
			if(ADMIN===true) {
				$navi = '<span class="pagination">'.$navi.'</span>';
			} else {
				$navi = '<ul class="pagination">'.$navi.'</ul>';
			}
		}
		$query = $query.' LIMIT '.((--$page*$split_by)-$custom_start_offset).','.$split_by.' ';
		$sql=$X->DB->query($query);

		return array('query'=>$query, 'sql'=>$sql, 'navi'=>$navi, 'total_rows'=>$total_rows, 'total'=>$total_rows, 'go'=>$go, 'split_by'=>$split_by, 'pages'=>$pages, 'corrected_page'=>$corrected_page);
	}


	function navi_link($page,$i,$url_start,$url_end=false,$first_page_base=false) {
		global $X;

		if($page==$i) { //sel
			if(ADMIN===true) {
				return '<span class="sel">'.$i.'</span>';
			} else {
				return '<li class="active"><span>'.$i.'</span></li>';
			}
		} else {
			$url = (!empty($url_start) ? $url_start.$i.$url_end : $X->URL->get($this->GET_VAR.'='.$i));
			if($i==1 && !empty($first_page_base)) $url=$first_page_base;

			if(ADMIN===true) {
				return '<a href="'.$url.'">'.$i.'</a>';
			} else {
				return '<li><a href="'.$url.'">'.$i.'</a></li>';
			}
		}
	}


	function set_order(&$table, $before=false, $after=false) {
		if(!empty($_GET['order_by'])) $table['order_by']=$_GET['order_by'];
		if(!empty($_GET['order_dir'])) $table['order_dir']=$_GET['order_dir'];
		if(empty($table['order_dir'])) $table['order_dir']='asc';
		if(empty($_GET['order_by'])) $_GET['order_by']=$table['order_by'];
		if(empty($_GET['order_dir'])) $_GET['order_dir']=$table['order_dir'];

		if($_GET['order_dir']!='asc' && $_GET['order_dir']!='desc' && $_GET['order_dir']!="") $_GET['order_dir']=$table['order_dir']='asc';

		return 'ORDER BY '.trim((!empty($before) ? $before.',':'').' '.$table['order_by'].' '.$table['order_dir'].' '.(!empty($after) ? ','.$after:''));
	}





	function prepare_row($table, $current_id=false, $force_insert_id=false) {
		if((int)$current_id>0) return $current_id;

		$sql=$this->query(' SHOW COLUMNS FROM '.$table.' ');
		while($dane=$this->fetch_assoc($sql)) {
			if($dane['Key']=='PRI' && $dane['Extra']=='auto_increment') {
				$pri=$dane['Field'];
				$this->query(' INSERT INTO '.$table.' ('.$pri.') VALUES ('.($force_insert_id ? '"'.$force_insert_id.'"':"null").') ');
				$new_id=mysql_insert_id();
				if((int)$new_id>0) return (int)$new_id;
			}
		}
	}


	function save($fields) {
		global $X;
		if(count($fields)>0) foreach($fields as $field) {
			$cols[]=$field.'="'.$_POST[$field].'"';
		}
		return @implode(', ', $cols);
	}


	function save_cols() {
		global $X;
		for($i=0; $i<func_num_args(); $i++) {
			$cols[]=func_get_arg($i).'="'.$_POST[func_get_arg($i)].'"';
		}
		return @implode(', ', $cols);
	}


	function save_multiselect($name, $conf, $use_poz=false, $sep=',') {
		global $X;

		$values=(@is_array($_POST[$name]) ? $_POST[$name] : @explode($sep,$_POST[$name]));
		if(count($values)>0) foreach($values as $option_id) {
			if(is_numeric($option_id) && $option_id!==0) {
				if($use_poz==true) ++$pozycja;

				$sql=$X->DB->q(' SELECT id FROM '.$conf['table'].' WHERE '.$conf['key'].'="'.$conf['val'].'" '.(!empty($conf['key2']) ? 'AND '.$conf['key2'].'="'.$conf['val2'].'"':'').' AND '.$conf['col'].'="'.$option_id.'" ');
				if($X->DB->num_rows($sql)==0) {
					$X->DB->q(' INSERT INTO '.$conf['table'].' ('.$conf['key'].','.(!empty($conf['key2']) ? $conf['key2'].',':'').$conf['col'].($use_poz==true ? ',pozycja':'').') VALUES ("'.$conf['val'].'",'.(!empty($conf['key2']) ? '"'.$conf['val2'].'",':'').'"'.$option_id.'"'.($use_poz==true ? ',"'.$pozycja.'"':'').') ');
				} else {
					if($use_poz==true) $X->DB->q(' UPDATE '.$conf['table'].' SET pozycja="'.$pozycja.'" WHERE '.$conf['key'].'="'.$conf['val'].'" '.(!empty($conf['key2']) ? 'AND '.$conf['key2'].'="'.$conf['val2'].'"':'').' AND '.$conf['col'].'="'.$option_id.'" ');
				}
				$option_id_in_db[]='"'.$option_id.'"';
			}
		}
		$X->DB->q(' DELETE FROM '.$conf['table'].' WHERE '.$conf['key'].'="'.$conf['val'].'" '.(!empty($conf['key2']) ? 'AND '.$conf['key2'].'="'.$conf['val2'].'"':'').' '.(count($option_id_in_db)>0 ? 'AND '.$conf['col'].' NOT IN ('.@implode(',',$option_id_in_db).')':'').' ');
	}




	function init() {
		$this->connect();
	}


	function connect() {
		global $CONF;

		try {
			$this->CONNECTION=mysql_connect($CONF->SQL_DB_HOST, $CONF->SQL_DB_USER, $CONF->SQL_DB_PASS);
			if(!mysql_select_db($CONF->SQL_DB_NAME, $this->CONNECTION)) throw new Exception('mysql_error');
		} catch (Exception $e) {
			$mysql_error=mysql_error();
			$err=$e->getTrace();
			$error=$err[1];
			$error_string='<b>'.$mysql_error.'</b><br /><br />ERROR: mysql_select_db()';
			$error_message='<b>Code-Trace:</b><br />'.nl2br($e->getTraceAsString());

			error_handler(4096, $error_string, $error['file'], $error['line'], $error_message);
		}

		$this->query(' SET NAMES utf8 ');
	}
	function disconnect() { mysql_close($this->CONNECTION); }


	function q($query, $silent_error=false) { return $this->query($query,$silent_error); }
	function query($query,$silent_error=false) {
		try {
			$R=mysql_query($query, $this->CONNECTION);
			if($R==false) {
				if($silent_error==true) {
					return 'error';
				} else {
					throw new Exception('mysql_error');
				}
			}
		} catch (Exception $e) {
			$mysql_error=mysql_error();
			if(stristr($mysql_error, 'marked as crashed')) $this->repair_tables();
			$err=$e->getTrace();
			$error=$err[1];
			$error_string='<pre>'.str_replace('			',' ',$query).'</pre><br /><br /><b>'.$mysql_error.'</b>';
			$error_message='<b>Code-Trace:</b><br />'.nl2br($e->getTraceAsString());

			error_handler(4096, $error_string, $error['file'], $error['line'], $error_message);
		}
		return $R;
	}


	function fetch_array($sql) 	{ return @mysql_fetch_array($sql); }
	function far($sql) 				{ return $this->fetch_array($sql); }
	function fetch_assoc($sql) 	{ return @mysql_fetch_assoc($sql); }
	function fa($sql) 				{ return $this->fetch_assoc($sql); }
	function num_rows($sql) 		{ return @mysql_num_rows($sql); }
	function nr($sql) 				{ return $this->num_rows($sql); }
	function num_cols($sql) 		{ return @mysql_num_fields($sql); }
	function nc($sql) 				{ return $this->num_cols($sql); }
	function affected_rows()		{ return @mysql_affected_rows(); }
	function ar()						{ return $this->affected_rows(); }
	function inserted_id($table) 	{ return $this->fast(' SELECT id FROM '.$table.' ORDER BY id DESC LIMIT 1 '); }
	function ii($table) 				{ return $this->inserted_id($table); }


	function single($query, $silent_error=false) { return $this->fast($query,$silent_error); }
	function f($query, $silent_error=false) { return $this->fast($query,$silent_error); }
	function fast($query, $silent_error=false) {
		$sql=$this->query($query,$silent_error);
		if($silent_error==true && $sql=='error') return $sql;
		$dane=$this->fetch_array($sql);
		return ($this->num_cols($sql)==1 ? $dane[0] : $dane);
	}


	function list_cols($table, $full=false) {
		$sql=$this->query(' SHOW COLUMNS FROM '.$table.' ');
		if($this->num_rows($sql)==0) return array();
		while($dane=$this->fetch_array($sql)) {
			$cols[]=($full==true ? $dane : $dane['Field']);
		}
		return $cols;
	}


	function get_array($query, $assoc=false) {
		$sql=$this->query($query);
		if($this->num_rows($sql)==0) return ($assoc==false ? false : array());
		while($dane=$this->far($sql)) {
			if($assoc==false) {
				$array_elem[]=$dane[0];
			} else {
				$array_elem[$dane[0]]=$dane[1];
			}
		}
		return $array_elem;
	}



}
$this->DB = new X_DB();
$this->DB->DIR = LIBS.'/_db';
$this->DB->PATH = LIBS_PATH.'/_db';

class X_FORM {


	function select_get_options($query, $selected=false) {
		global $X;

		$cols=explode(',', $X->STR->text_between('SELECT','FROM', $query));
		$val=trim($cols[0]);
		unset($cols[0]);
		$txt=trim(@implode($cols));

		if(!is_array($selected)) { $t=$selected; unset($selected); $selected[]=$t; }

		$sql=$X->DB->q($query);
		while($dane=$X->DB->far($sql)) $html.='<option value="'.$dane[0].'"'.(@in_array($dane[0],$selected) ? ' selected="selected"':'').'>'.$dane[1].'</option>';
		return $html;
	}


	function get_options_tree($query, $replace_what, $replace_with, $selected=false, $parent_depth=0, $level=0) {
		global $X;


		if($parent_depth>0 && $level>=$parent_depth-1) return false;
		if($level>0) $lvl=str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;',$level).str_repeat('&nbsp;',$level).'|&mdash;&nbsp;';
		if(!empty($selected) && !is_array($selected)) {
			$t=$selected;
			unset($selected);
			$selected[]=$t;
		}

		$sql=$X->DB->query(str_replace($replace_what, $replace_with, $query));
		while($dane=$X->DB->far($sql)) {
			$html.='<option value="'.$X->STR->outt($dane[0]).'"'.(@in_array($X->STR->outt($dane[0]),$selected) ? ' selected="selected"':'').'>'.$lvl.$X->STR->outt($dane[1]).'</option>';
			if($X->DB->num_rows($X->DB->query(str_replace($replace_what, $dane[0], $query)))>0) {
				$html.=$this->get_options_tree($query, $replace_what, $X->STR->outt($dane[0]), $selected, $parent_depth, $level+1);
			}
		}

		return $html;
	}


	function get_options_group_tree($query, $replace_what, $replace_with, $selected=false, $parent_depth=0, $level=0) {
		global $X;


		if($parent_depth>0 && $level>=$parent_depth-1) return false;
//		if($level>0) $lvl=str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;',$level).str_repeat('&nbsp;',$level).'|&mdash;&nbsp;';
		if(!empty($selected) && !is_array($selected)) {
			$t=$selected;
			unset($selected);
			$selected[]=$t;
		}

		$sql=$X->DB->query(str_replace($replace_what, $replace_with, $query));
		while($dane=$X->DB->far($sql)) {
			if($X->DB->num_rows($X->DB->query(str_replace($replace_what, $dane[0], $query)))>0) {
				$html.='<optgroup label="'.$X->STR->outt($dane[1]).'">'.$this->get_options_group_tree($query, $replace_what, $X->STR->outt($dane[0]), $selected, $parent_depth, $level+1).'</optgroup>';
			} else {
				$html.='<option value="'.$X->STR->outt($dane[0]).'"'.(@in_array($X->STR->outt($dane[0]),$selected) ? ' selected="selected"':'').'>'.$lvl.$X->STR->outt($dane[1]).'</option>';
			}
		}

		return $html;
	}


	function get_array_tree($query, $replace_what, $replace_with, $selected=false, $parent_depth=0, $level=0, &$array=false) {
		global $X;


		if($parent_depth>0 && $level>=$parent_depth-1) return false;
		if($level>0) $lvl=str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;',$level).str_repeat('&nbsp;',$level).'|&mdash;&nbsp;';
		if(!empty($selected) && !is_array($selected)) {
			$t=$selected;
			unset($selected);
			$selected[]=$t;
		}

		$sql=$X->DB->query(str_replace($replace_what, $replace_with, $query));
		while($dane=$X->DB->far($sql)) {
			$array[$X->STR->outt($dane[0])] = $lvl.$X->STR->outt($dane[1]);

			if($X->DB->num_rows($X->DB->query(str_replace($replace_what, $dane[0], $query)))>0) {
				$this->get_array_tree($query, $replace_what, $X->STR->outt($dane[0]), $selected, $parent_depth, $level+1, $array);
			}
		}

		if($level==0) return $array;
	}


	function get_options_from_array($array, $selected=false) {
		global $X;

		if(!is_array($array) || count($array)==0) return false;
		foreach($array as $value => $label) $html.='<option value="'.$value.'"'.($value==$selected ? ' selected="selected"':'').'>'.$label.'</option>';
		return $html;
	}




	function init() {}


	//TEXT FIELDS =====================================================
	function input($name, $width=300, $value=false, $readonly=false, $disabled=false, $custom_class=false, $maxlen=false, $center=false) {
		return $this->input_id($name, $name, $width, $value, $readonly, $disabled, $custom_class, $maxlen, $center);
	}
	function input_id($name, $id, $width=300, $value=false, $readonly=false, $disabled=false, $custom_class=false, $maxlen=false, $center=false) {
		$class=(!empty($custom_class) ? $custom_class : 'input form-control').($readonly==true || $disabled==true ? ' disabled':'');
		return '<input type="text" name="'.$name.'" '.(!empty($id) ? 'id="'.$id.'" ':'').'value="'.$value.'" class="'.$class.'" style="width:'.$width.'px;'.($center==true ? ' text-align:center;':'').'"'.($readonly==true ? ' readonly="readonly"':'').($disabled==true ? ' disabled="disabled"':'').($maxlen>0 ? ' maxlength="'.$maxlen.'"':'').' />';
	}
	function input_center($name, $width=300, $value=false, $readonly=false, $disabled=false, $custom_class=false, $maxlen=false, $mask=false, $default_value=false) {
		return $this->input_id($name, $name, $width, $value, $readonly, $disabled, $custom_class, $maxlen, true);
	}
	function input_id_center($name, $id, $width=300, $value=false, $readonly=false, $disabled=false, $custom_class=false, $maxlen=false, $mask=false, $default_value=false) {
		return $this->input_id($name, $id, $width, $value, $readonly, $disabled, $custom_class, $maxlen, true);
	}


	function textarea($name, $width=300, $height=63, $value=false, $readonly=false, $disabled=false, $custom_class=false, $maxlen=false) {
		return $this->textarea_id($name, $name, $width, $height, $value, $readonly, $disabled, $custom_class, $maxlen);
	}
	function textarea_id($name, $id, $width=300, $height=63, $value=false, $readonly=false, $disabled=false, $custom_class=false, $maxlen=false) {
		$class=(!empty($custom_class) ? $custom_class : 'textarea form-control').($readonly==true || $disabled==true ? ' disabled':'');
		return '<textarea name="'.$name.'" id="'.$id.'" class="'.$class.'" rows="10" cols="60" style="width:'.$width.'px; height:'.$height.'px;"'.($readonly==true ? ' readonly="readonly"':'').($disabled==true ? ' disabled="disabled"':'').($maxlen>0 ? ' maxlength="'.$maxlen.'"':'').'>'.$value.'</textarea>'.($maxlen>0 ? '<script type="text/javascript">$("#'.$id.'").on("keyup keypress paste blur",function(){ if($(this).val().length>'.$maxlen.') $(this).val($(this).val().substring(0,'.$maxlen.')); })</script>':'');
	}


	function ck($name, $value=false, $width=false, $height=false, $toolbar=false) {
		if(empty($width)) $width=790;
		if(empty($height)) $height=400;
		$width = ($width<790 ? 790:$width);
		$height = ($height<100 ? 100:$height);
		if(empty($toolbar)) $toolbar='Full';

		$lang=(empty($_SESSION['backend']['ui_lang']) ? 'PL':$_SESSION['backend']['ui_lang']);
		$timestamp=1.01;

		$inited=$this->CK_INITIATED;
		$this->CK_INITIATED=true;

		@mkdir(USR.'/_CMS_',true,0755);

		return '
			<a id="'.$name.'_focus" name="'.$name.'_focus" style="display:block; width:'.$width.'px;"></a>
			<textarea name="'.$name.'" id="'.$name.'" rows="10" cols="60">'.htmlspecialchars($value).'</textarea>
			'.($inited!=true ? '<script type="text/javascript" src="'.$this->DIR.'/ck/ckeditor.js?t='.$timestamp.'"></script>':'').'
			<script type="text/javascript">'.($inited!=true ? 'window.CKEDITOR_BASEPATH="'.$this->DIR.'/ck/"; CKEDITOR.timestamp = "'.$timestamp.'";':'').'
				CKEDITOR.replace("'.$name.'", {"language":"'.$lang.'", "toolbar":"'.$toolbar.'", "width":'.(int)$width.', "height":'.(int)$height.' });
			</script>
		';

		/*
		require($this->DIR.'/ck/ckeditor.php');
		$CKEditor = new CKEditor();
		$CKEditor->basePath = $this->DIR.'/ck/';
		$CKEditor->timestamp = '1.02';

		$config['language'] = 'PL';
		$config['toolbar'] = $toolbar;
		$config['width'] = $width;
		$config['height'] = $height;
		//$events['instanceReady'] = ' function(ev) { alert("Loaded: " + ev.editor.name); } ';

		return $CKEditor->editor($name, $value, $config, $events);
		*/
	}


	function tiny_normal($name, $width, $height, $value=false, $skip_bottom_space=false, $simple=false) {
		global $X;
		$X->JS[] = $this->DIR.'/tinymce/tinymce.min.js';

		if($width<500) $width=500;

//autolink,
//				$(document).ready(function() {
//				});
//						paste_text_linebreaktype: "br",

//,|,link,unlink
//charmap,
//wordcount
		return '
			<a id="'.$name.'_focus" name="'.$name.'_focus" style="display:block; margin:0px; padding:0px;"></a>
			<div style="width:'.$width.'px;">'.$this->textarea($name, $width, $height, $value).'</div>


			<script type="text/javascript">
				tinymce.init({
					selector: "#'.$name.'",
					theme: "modern",
					schema: "html5",
					language : "pl",
					plugins: [
						"advlist lists link charmap anchor searchreplace visualblocks visualchars code nonbreaking paste",
					],
					rel_list: [
						{title: "follow", value: "follow"},
						{title: "nofollow", value: "nofollow"}
					],
					toolbar1: "undo redo | searchreplace | bold italic underline | link unlink | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent",
					toolbar2: "",
					object_resizing : false,
					force_hex_style_colors: true,
					content_css : "/libs/_form/tinymce/editor.css?_1",

					paste_as_text: false,
					paste_auto_cleanup_on_paste: true,
				   paste_data_images: false,
				   valid_elements: "b,strong,i,em,u,a[href|target|rel|name|id],link,ul,ol,li,sub,sup,br,p[align|style]",
				   paste_word_valid_elements: "b,strong,i,em,u,a[href|target|rel|name|id],link,ul,ol,li,sub,sup,br,p[align|style]",
					paste_remove_spans: true,
					paste_remove_styles: true,
					paste_postprocess: function(plugin, args) {
						$.each($(args.node).find("p"),function(index,item){
							if($(item).attr("align")!="") {
								align=$(item).attr("align");
								$(item).removeAttr("align").css("text-align",align);
							}
						});

						$.each($(args.node).find("img"),function(index,item){
							$(item).closest("a").remove();
							$(item).remove();
						});



					},
					menubar: "insert edit format view",
					setup: function(editor) {
						editor.on("blur", function(e){ tinymce.activeEditor.save(); })
					}
				});
			</script>
			'.($skip_bottom_space!=true ? '<div style="height:16px;"></div>':'').'
		';
/*
					style_formats: [
						{title: "średni", inline: "span", classes: "med"},
						{title: "duży", inline: "span", classes: "big"},
					] //  | styleselect
*/
	}


	function tiny($name, $width, $height, $value=false, $skip_bottom_space=false, $simple=false) {
		global $X;
		$X->JS[] = $this->DIR.'/tinymce/tinymce.min.js';

		return '
			<a id="'.$name.'_focus" name="'.$name.'_focus" style="display:block; margin:0px; padding:0px;"></a>
			<div style="width:'.$width.'px;">'.$this->textarea($name, $width, $height, $value).'</div>

			<script type="text/javascript">
				tinymce.init({
					selector: "#'.$name.'",
					theme: "modern",
					schema: "html5",
					language : "pl",
					plugins: [
						"advlist lists link charmap anchor searchreplace visualblocks visualchars code nonbreaking paste",
					],
					toolbar1: "undo redo | bold italic underline bullist numlist link unlink | alignleft aligncenter alignright alignjustify",
					toolbar2: "",
					object_resizing : false,
					force_hex_style_colors: true,
					content_css : "/libs/_form/tinymce/editor.css?_2",

					paste_as_text: false,
					paste_auto_cleanup_on_paste: true,
				   paste_data_images: false,
				   valid_elements: "b,strong,i,em,u,a[href|target|rel|name|id],link,ul,ol,li,sub,sup,br,p[align|style]",
				   paste_word_valid_elements: "b,strong,i,em,u,a[href|target|rel|name|id],link,ul,ol,li,sub,sup,br,p[align|style]",
					paste_remove_spans: true,
					paste_remove_styles: true,
					paste_postprocess: function(plugin, args) {
						$.each($(args.node).find("p"),function(index,item){
							if($(item).attr("align")!="") {
								align=$(item).attr("align");
								$(item).removeAttr("align").css("text-align",align);
							}
						});

						$.each($(args.node).find("img"),function(index,item){
							$(item).closest("a").remove();
							$(item).remove();
						});
					},
					menubar: "insert edit format view",
					setup: function(editor) {
						editor.on("blur", function(e){ tinymce.activeEditor.save(); })
					}
				});
			</script>
			'.($skip_bottom_space!=true ? '<div style="height:16px;"></div>':'').'
		';
/*
					style_formats: [
						{title: "średni", inline: "span", classes: "med"},
						{title: "duży", inline: "span", classes: "big"},
					] //  | styleselect
*/
	}


	//PASSWORD ========================================================
	function password($name, $width=300, $value=false, $readonly=false, $disabled=false, $maxlen=false, $custom_class=false) {
		return $this->password_id($name, $name, $width, $value, $readonly, $disabled, $maxlen, $custom_class);
	}
	function password_id($name, $id, $width=300, $value=false, $readonly=false, $disabled=false, $maxlen=false, $custom_class=false) {
		$class=(!empty($custom_class) ? $custom_class : 'input password form-control').($disabled==true ? ' disabled':'');
		return '<input type="password" name="'.$name.'" '.(!empty($id) ? 'id="'.$id.'" ':'').'value="'.$value.'" class="'.$class.'" style="width:'.$width.'px" autocomplete="off" '.($readonly==true ? ' readonly="readonly"':'').($disabled==true ? ' disabled="disabled"':'').($maxlen>0 ? ' maxlength="'.$maxlen.'"':'').' />';
	}



	//CHECKBOX-o-RADIO-SELECTS ========================================
	function checkbox($name, $value=1, $checked=false, $OC_action=false, $id=false, $tip=false, $disabled=false, $readonly=false) {
		if(empty($id)) $id=$name;
		return '<input type="checkbox" name="'.$name.'" id="'.$id.'" value="'.$value.'" class="checkbox"'.($checked==true ? ' checked="checked"':'').($readonly==true ? ' readonly="readonly"':'').($disabled==true ? ' disabled="disabled"':'').(!empty($OC_action) ? ' onclick="'.$OC_action.'"':'').(!empty($tip) ? ' onmouseover="tip(this,\''.$tip.'\')"':'').' />';
	}

	function radio($name, $value, $label, $sel_value=false, $OC_action=false, $tip=false, $disabled=false, $readonly=false) {
		return '<input type="radio" name="'.$name.'" id="'.$name.'_'.$value.'" value="'.$value.'" class="radio" '.($value==$sel_value || $checked==true ? ' checked="checked"':'').($readonly==true ? ' readonly="readonly"':'').($disabled==true ? ' disabled="disabled"':'').(!empty($OC_action) ? ' onclick="'.$OC_action.'"':'').(!empty($tip) ? ' onmouseover="tip(this,\''.$tip.'\')"':'').' />'.(!empty($label) ? '<label for="'.$name.'_'.$value.'">'.$label.'</label>':'');
	}

	function select($name, $options, $width=false, $disabled=false, $OCH_action=false, $custom_class=false, $id=false) {
		if(empty($id)) $id=$name;
		if(!empty($OCH_action)) $if_OCH=' onchange="'.$OCH_action.'"';
		if(!empty($width)) $style=' style="width:'.$width.'px;"';
		$class=(!empty($custom_class) ? $custom_class : 'select form-control').($disabled==true ? ' disabled':'');
		return '<select name="'.$name.'" id="'.$id.'" class="'.$class.'"'.$style.$if_OCH.($disabled==true ? ' disabled="disabled"':'').'>'.$options.'</select>';
	}

	function multiselect_normal($name, $options, $width=false, $size=10, $disabled=false, $OCH_action=false, $custom_class=false, $id=false) {
		if(empty($id)) $id=$name;
		if(!empty($OCH_action)) $if_OCH=' onchange="'.$OCH_action.'"';
		if(!empty($width)) $style='width:'.$width.'px;';
		$class=(!empty($custom_class) ? $custom_class : 'select').($disabled==true ? ' disabled':'');
		return '<select name="'.$name.'" id="'.$id.'" multiple="multiple" size="'.$size.'" style="font-size:12px;'.$style.'" class="'.$class.'"'.$if_OCH.($disabled==true ? ' disabled="disabled"':'').'>'.$options.'</select>';
	}

	function multiselect($name, $options, $width=false, $height=false, $vertical=false, $single=false, $show_addons=true, $show_counter=false) {
		global $X;
		$X->JS[]=JS.'/jquery.multiselect/multiselect.js';
		$X->CSS[]=JS.'/jquery.multiselect/multiselect.css';
		if(!empty($width)) $if_width=' style="width:'.$width.'px;"';
		if(!empty($disabled)) $if_dis=' disabled="disabled"';

		if($width>0) $w = ($vertical==true ? ($width+8) : ((int)(($width-34)/2)) );
		if($height>0) $h = ($vertical==true ? $height : $height );

		return '
			<a id="'.$name.'_focus" name="'.$name.'_focus" style="display:block; width:'.$w.'px;"></a>
			<select name="'.$name.'[]" id="'.$name.'" multiple="multiple" class="select">'.$options.'</select>
			<script type="text/javascript">
				$("#'.$name.'").multiSelect({'.($single==true ? 'single:true':'selectableHeader:\'<span class="header">Dostępne</span>\', selectedHeader:\'<span class="header">Wybrane</span>\'').($vertical==true ? ', vertical:true':'').'});
				'.($w>0 ? '$("#ms-'.$name.' ul.ms-list").css("width","'.$w.'px");':'').'
				'.($h>0 ? '$("#ms-'.$name.' ul.ms-list").css("height","'.$h.'px");':'').'
			</script>
			'.($show_addons==true && !empty($options) && substr_count($options,'<option ')>1 ? '
				<div style="display:inline-block; vertical-align:top; width:24px; font-size:0px; margin-top:7px; margin-left:1px;">
					<a href="#" onclick="$(\'#'.$name.'\').multiSelect(\'deselect_all\'); $(\'#'.$name.'\').multiSelect(\'select_all\'); return false;"><span class="ico b_plus"></span></a>
					<a href="#" onclick="$(\'#'.$name.'\').multiSelect(\'deselect_all\'); return false;"><span class="ico b_minus" style="margin-top:-1px;"></span></a>
					'.($show_counter==true ? '<div id="'.$name.'_sel_count" style="font-size:11px; margin-top:12px; width:16px; text-align:center; font-weight:bold;"></div>':'').'
				</div>
			':'').'
		';
	}



	//HIDDEN ==========================================================
	function hidden($name, $value=false) {	return $this->hidden_id($name, $name, $value); }
	function hidden_id($name, $id=false, $value=false) { return '<input type="hidden" style="display:none;" name="'.$name.'" '.(!empty($id) ? 'id="'.$id.'" ':'').'value="'.$value.'" />';	}



	//FILE ============================================================
	function file($name, $width=300) { return $this->file_id($name, $name, $width); }
	function file_id($name, $id, $width=300) {
		if(empty($id)) $id=$name;
		$size=round(($width-110)*0.195);
		return '<a id="'.$id.'_focus" name="'.$id.'_focus" style="position:absolute; font-size:0px;"></a><input type="file" style="width:'.$width.'px;" size="'.$size.'" class="input" name="'.$name.'" id="'.$id.'" onchange="$(\'#'.$id.'_\').val(this.value)" />'.$this->hidden($id.'_');
	}

	function flash_upload($form_name, $name, $dir, $multiple, $ext, $size_limit=false) {
		global $X;

		$dont_use_HTML5=false;

		$X->JS[]=JS.'/jquery.uploadifive/jquery.uploadifive.min.js';
		$fallback_script=JS.'/jquery.uploadify/jquery.uploadify.js';


		$size_limit_env=@min($X->CONF->ENV['post_max_size'], $X->CONF->ENV['upload_max_filesize']);
		$size_limit=($size_limit>0 ? @min($size_limit, $size_limit_env) : $size_limit_env);

		$ext_arr=explode('|', $ext);
		foreach($ext_arr as $e) {
			$ext_arr_star[]='*.'.$e;
			$ext_arr_star2[]='.'.$e;
		}

		unset($_SESSION['flash_upload'][$form_name.'_form'][$name]['uploaded']);

		$temp=CACHE.'/uploadify/'.session_id().'/'.$form_name.'_form/';
		if(is_dir($temp)) $X->UTIL->rmdir_rf($temp);

		$temp=CACHE.'/uploadify/'.session_id().'/';
		if($X->UTIL->count_dir_size($temp)==0) $X->UTIL->rmdir_rf($temp);

		$_SESSION['flash_upload'][$form_name.'_form'][$name]['config'] = array(
			'dir' => $dir,
			'ext' => $ext,
			'size' => $size_limit*1024*1024,
			'multiple' => $multiple
		);

		$timestamp=time();


		if($dont_use_HTML5!=true) {
//				<div style="height:23px; float:left" class="button_cont">'.$X->FORM->button_OC('Wybierz plik'.($multiple==true ? 'i':''), 'return false;', 76, 'button center').'</div>
//				'.(ADMIN===true ? '<div style="float:left; padding-left:5px;">'.$X->FORM->button_OC('<span class="ico w_dl"></span>','flash_download_file(\''.$name.'\')',false,'button button_gfx_small',false,'Ściągnij zdalny plik z adresu').'</div>':'').'
			return '
				<div id="'.$name.'_uploader_cont">
					<a id="'.$name.'_focus" name="'.$name.'_focus" style="display:block;"></a>
					<div>'.$this->file($name,200).'</div>
				</div>

				'.(ADMIN!==true && $_GET['allow_downloadify']==true ? '<div style="float:left; margin-left:5px;">'.$X->FORM->button_OC('<img src="images/download_icon.png" alt="" '.$X->FORM->tip('Pobierz plik z adresu URL').' />','flash_download_file(\''.$name.'\')',false,'button button_gfx_small',false,'Ściągnij zdalny plik z adresu').'</div>':'').'

				<div style="float:left; padding-left:28px;"><span class="ico b_warn" style="margin-top:4px;"></span></div>
				<div style="float:left; padding-left:10px; font-size:11px; line-height:11px;" class="ext_info">
					Max. rozmiar pliku: <b>'.$size_limit.' MB</b><br />
					Rozszerzenia: <b>'.strtoupper(@implode(', ',$ext_arr)).'</b><br />
				</div>

				<div class="clear"></div>
				<div id="'.$name.'_queue" class="uploadifyQueueCont"></div>

				<script type="text/javascript">
					$(document).ready(function() {
						$("#'.$name.'").uploadifive({
							"uploadScript"			: "'.(ADMIN===true ? '/admin':'').'/includes/uploadify.php?SID='.SID.'",
							"formData"				: { "form_name":"'.$form_name.'", "timestamp":"'.$timestamp.'", "token":"'.md5('@dh_cms#upload#'.$timestamp).'", "single":"'.($multiple==true ? 0:1).'" },
							"auto"					: true,
							"buttonText"			: "<div class=\"label_default\">Wybierz plik'.($multiple==true ? 'i':'').' lub przeciągnij</div><div class=\"label_drop\">Tutaj upuść plik'.($multiple==true ? 'i':'').'</div>",
							"buttonClass"			: "button uploadify",
							"width"					: 200,
							"height"					: 27,
							"fileObjName"			: "'.$name.'",
							"multi"					: '.($multiple==true ? 'true':'false').',
							"fileSizeLimit"		: '.($size_limit*1024*1024).',
							"fileType"				: "'.@implode(',',$ext_arr_star2).'",
							"queueID"				: "'.$name.'_queue",
							"simUploadLimit"		: 1,
							"onFallback"			: function() {
								$(\'#'.$name.'_uploader_cont\').html(\''.addslashes('<div style="position:absolute; width:102px; height:23px;"><a id="'.$name.'_focus" name="'.$name.'_focus" style="display:block;"></a>'.$this->file($name,100).'</div><div style="height:23px; float:left" class="button_cont">'.$X->FORM->button_OC('Wybierz plik'.($multiple==true ? 'i':''), 'return false;', 76, 'button center').'</div>').'\');

								$.ajax({
									url: "'.JS.'/swfobject.js",
									dataType: "script",
									cache: true,
									complete: function() {
									///
										$.ajax({
											url: "'.$fallback_script.'",
											dataType: "script",
											cache: true,
											complete: function() {
												$("#'.$name.'").uploadify({
													"expressInstall" 	: "'.JS.'/jquery.uploadify/expressInstall.swf",
													"uploader"  		: "'.JS.'/jquery.uploadify/uploadify.swf?SID='.SID.'",
													"script"    		: "'.(ADMIN===true ? '/admin':'').'/includes/uploadify.php?SID='.SID.'",
													"scriptData"    	: {"form_name":"'.$form_name.'"},
													"auto"      		: true,
													"buttonText"		: " ",
													"hideButton"		: true,
													"width"				: 102,
													"height"				: 25,
													"fileDataName"		: "'.$name.'",
													"multi"				: '.($multiple==true ? 'true':'false').',
													"simUploadLimit"	: 1,
													"queueID"			: "'.$name.'_queue",
													"sizeLimit"			: '.($size_limit*1024*1024).',
													"fileExt"			: "'.@implode(';',$ext_arr_star).'",
													"fileDesc"			: "Pliki: '.strtoupper(@implode(', ',$ext_arr)).'",
													"onComplete"		: flash_upload_complete,
													"onCancel"			: flash_upload_cancel
												});
											}
										});
									///
									}
								});
							}
						});
					});
				</script>
			';
		} else {
//				'.(ADMIN===true ? '<div style="float:left; padding-left:5px;">'.$X->FORM->button_OC('<span class="ico w_dl"></span>','flash_download_file(\''.$name.'\')',false,'button button_gfx_small',false,'Ściągnij zdalny plik z adresu').'</div>':'').'
			return '
				<div style="position:absolute; width:102px; height:23px;"><a id="'.$name.'_focus" name="'.$name.'_focus" style="display:block;"></a>'.$this->file($name,100).'</div>
				<div style="height:23px; float:left" class="button_cont">'.$X->FORM->button_OC('Wybierz plik'.($multiple==true ? 'i':''), 'return false;', 76, 'button center').'</div>
				'.(ADMIN!==true && $_GET['allow_downloadify']==true ? '<div style="float:left; margin-left:5px;">'.$X->FORM->button_OC('<img src="images/download_icon.png" alt="" '.$X->FORM->tip('Pobierz plik z adresu URL').' />','flash_download_file(\''.$name.'\')',false,'button button_gfx_small',false,'Ściągnij zdalny plik z adresu').'</div>':'').'

				<div style="float:left; padding-left:28px;"><span class="ico b_warn" style="margin-top:4px;"></span></div>
				<div style="float:left; padding-left:10px; font-size:11px; line-height:11px;" class="ext_info">
					Max. rozmiar pliku: <b>'.$size_limit.' MB</b><br />
					Dozwolone rozszerzenia: <b>'.strtoupper(@implode(', ',$ext_arr)).'</b><br />
				</div>

				<div class="clear"></div>
				<div id="'.$name.'_queue" class="uploadifyQueueCont"></div>

				<script type="text/javascript">
					$(document).ready(function() {
						$("#'.$name.'").uploadify({
							"expressInstall" 	: "'.JS.'/jquery.uploadify/expressInstall.swf",
							"uploader"  		: "'.JS.'/jquery.uploadify/uploadify.swf?SID='.SID.'",
							"script"    		: "'.(ADMIN===true ? '/admin':'').'/includes/uploadify.php?SID='.SID.'",
							"scriptData"    	: {"form_name":"'.$form_name.'"},
							"auto"      		: true,
							"buttonText"		: " ",
							"hideButton"		: true,
							"width"				: 102,
							"height"				: 25,
							"fileDataName"		: "'.$name.'",
							"multi"				: '.($multiple==true ? 'true':'false').',
							"simUploadLimit"	: 1,
							"queueID"			: "'.$name.'_queue",
							"sizeLimit"			: '.($size_limit*1024*1024).',
							"fileExt"			: "'.@implode(';',$ext_arr_star).'",
							"fileDesc"			: "Pliki: '.strtoupper(@implode(', ',$ext_arr)).'",
							"onComplete"		: flash_upload_complete,
							"onCancel"			: flash_upload_cancel
						});
					});
				</script>
			';
		}
	}


	//BUTTONS =========================================================
	function button($value, $link, $width=false, $custom_class=false, $disabled=false, $blank=false) {
		if(!empty($width)) $style=' style="width:'.$width.'px"';
		$class=(!empty($custom_class) ? $custom_class : 'button').($disabled==true ? ' button_dis':'');
		return '<a '.($disabled==true && $_SESSION['backend']['is_root']!=1 ? 'href="#" onmouseover="this.ondragstart=function(){return false}" onclick="javscript:void(0); this.blur(); return false;"':'href="'.$link.'"').' class="'.$class.'"'.$style.($blank==true ? ' target="_blank"':'').'>'.$value.'</a>';
	}

	function button_OC($value, $action, $width=false, $custom_class=false, $disabled=false, $tip=false) {
		if(!empty($width)) $style=' style="width:'.$width.'px"';
		$class=(!empty($custom_class) ? $custom_class : 'button').($disabled==true ? ' button_dis':'');
		return '<a href="#" onmouseover="this.ondragstart=function(){return false}" onclick="'.($disabled==true && $_SESSION['backend']['is_root']!=1 ? 'this.blur(); return false;' : $action.'; return false;').'" class="'.$class.'"'.$style.$this->tip($tip,true).'>'.$value.'</a>';
	}

	function button_potwierdzenie($value, $link, $width=false, $tekst=false, $custom_class=false, $disabled=false) {
		if(empty($tekst)) $tekst='Na pewno usunąć?';
		if(!empty($width)) $style='style="width:'.$width.'px"';
		$class=(!empty($custom_class) ? $custom_class : 'button').($disabled==true ? ' button_dis':'');
		return '<a href="#"'.$style.' onmouseover="this.ondragstart=function(){return false}" onclick="'.($disabled==true && $_SESSION['backend']['is_root']!=1 ? 'this.blur(); return false;' : 'return question(\''.$tekst.'\', \''.$link.'\'); return false;').'" class="'.$class.'">'.$value.'</a>';
	}

	function submit($value=false, $width=false, $custom_class=false) {
		if(!empty($width)) $style=' style="width:'.$width.'px"';
		if(empty($value)) $value='Wyślij';
		$class=(!empty($custom_class) ? $custom_class : 'button submit');
		return '<input type="submit" class="'.$class.'"'.$style.' value="'.$value.'" />';
	}


	function submit_link($value=false, $width=false, $custom_class=false) {
		if(!empty($width)) $style=' style="width:'.$width.'px"';
		if(empty($value)) $value='Wyślij';
		$class=(!empty($custom_class) ? $custom_class : 'button button_gfx submit');
		return '<input type="submit" style="position:absolute;margin:0px;padding:0px;border:0px;width:1px;height:1px;background:transparent;" value="" /><a href="#" onmouseover="this.ondragstart=function(){return false}" onclick="$(this).addClass(\'button_dis\').attr(\'disabled\',\'disabled\').prev().click(); return false;" class="'.$class.'"'.$style.'><span>'.$value.'</span></a>';
	}


	function submit_link_potwierdzenie($value, $width=false, $tekst=false, $custom_class=false) {
		if(empty($tekst)) $tekst='Na pewno?';
		if(!empty($width)) $style='style="width:'.$width.'px"';
		$class=(!empty($custom_class) ? $custom_class : 'button').($disabled==true ? ' disabled':'');
		return '<input type="submit" style="position:absolute;margin:0px;padding:0px;border:0px;width:1px;height:1px;background:transparent;" value="" /><a href="#" onmouseover="this.ondragstart=function(){return false}" onclick="elem_context=this; return_question(\''.$tekst.'\', function(){ $(elem_context).addClass(\'button_dis\').attr(\'disabled\',\'disabled\').prev().click(); return false; }); return false;" class="'.$class.'"'.$style.'><span>'.$value.'</span></a>';
	}


	function dodaj($title=false, $link=false) {
		global $X;

		if(empty($link)) $link='action=form';

		if($title==-1) {
			return '<a href="'.$X->URL->get($link).'" class="button button_gfx2"><span class="ico w_add"></span></a>';
		} else {
			if(empty($title)) $title='Dodaj';
			return '<a href="'.$X->URL->get($link).'" class="button button_gfx"><span class="ico w_add"></span><span>'.$title.'</span></a>';
		}
	}


	function powrot($title=false, $link=false, $gray=true) {
		global $X;
		if(empty($link)) $link='action&id';

		if($title==-1) {
			return '<a href="#" onclick="go(\''.$X->URL->get($link).'\'); return false;" onmouseover="this.ondragstart=function(){return false}" class="button button_gfx2"><span class="ico w_left"></span></a>';
		} else {
			if(empty($title)) $title='Powrót';
			return '<a href="#" onclick="go(\''.$X->URL->get($link).'\'); return false;" onmouseover="this.ondragstart=function(){return false}" class="button'.($gray==true ? ' button_gray':'').' button_gfx"><span class="ico w_left"></span><span>'.$title.'</span></a>';
		}
	}


	function powrot_OC($title=false, $action=false, $gray=true) {
		global $X;
		if(empty($link)) $link='action&id';

		if($title==-1) {
			return '<a href="#" onclick="'.$action.'; return false;" onmouseover="this.ondragstart=function(){return false}" class="button button_gfx2"><span class="ico w_left"></span></a>';
		} else {
			if(empty($title)) $title='Powrót';
			return '<a href="#" onclick="'.$action.'; return false;" onmouseover="this.ondragstart=function(){return false}" class="button'.($gray==true ? ' button_gray':'').' button_gfx"><span class="ico w_left"></span><span>'.$title.'</span></a>';
		}
	}



	//X-PICKERS =======================================================
//	function kalendarz() { $a=func_get_args(); return call_user_func_array(array($this, 'calendar'), $a); }
	function calendar($name, $value=false, $format='Y-m-d', $readonly=false, $disabled=false, $id=false, $force_width=false) {
		global $X;
		$X->JS[] = JS.'/jquery.datepicker'.(ADMIN!==true ? '_front':'').'.js';
		$X->JS[] = JS.'/jquery.mask.js';

		if($format=='Y-m-d H:i:s') {
			$format='Y-m-d';
			$use_time=true;
			$tmp_value=@explode(' ',$value);
			$value=$tmp_value[0];
			$time_value=$tmp_value[1];
		}

		if(empty($force_width)) $force_width=90;
		$id=(!empty($id)?$id:$name);

		if($use_time==true) {
			if(stristr($name,'[]')) {
				$base=@explode('[]',$name);
				$base=$base[0];

				$time_name=$base.'_time[]';
				$time_id=$id.'_time';
			} else {
				$time_name=$name.'_time';
				$time_id=$id.'_time';
			}
		}


		return '
			'.$this->input_id($name,$id,$force_width,$value,$readonly,$disabled,'form-control input spaced',10,true).($use_time==true ? '&nbsp;'.$this->input_id($time_name, $time_id,70,$time_value,$readonly,$disabled,'form-control input spaced',10,true).'&nbsp;&nbsp;' : '').(ADMIN===true ? '&nbsp; <a '.$X->FORM->tip('Wstaw dzisiaj').' href="#" onclick="$(\'#'.$id.'\').val(\''.date('Y-m-d').'\'); $(\'#'.$id.'_time\').val(\''.date('H:i:s').'\'); return false;"><span class="ico b_cal"></span></a>':'').'
			<script type="text/javascript">
				$("#'.$id.'")
					.DatePicker({
						format: "'.$format.'",
						date: "'.$value.'",
						current: "'.$value.'",
						onBeforeShow: function(){
							if($.str_replace(["_","-"], ["",""], $("#'.$id.'").val()).length==8) $("#'.$id.'").DatePickerSetDate($("#'.$id.'").val(), true);
						},
						onChange: function(formated, dates){
							$("#'.$id.'").val(formated);
							$("#'.$id.'").DatePickerHide();
						}
					})
					.change(function(){	if($.str_replace(["_","-"], ["",""], $("#'.$id.'").val()).length==8) $("#'.$id.'").DatePickerSetDate($(this).val(), true);		})
					.keyup(function(){	if($.str_replace(["_","-"], ["",""], $("#'.$id.'").val()).length==8) $("#'.$id.'").DatePickerSetDate($(this).val(), true);		})
					.mask("9999-99-99");
				'.($use_time==true ? '
					$("#'.$time_id.'").mask("99:99:99");
				':'').'
			</script>
		';
/*
	onRender: function(date) {
		d=(date.valueOf()+"").substring(0,10);
		return { disabled: (d < '.(time()-3600*24).') }
	}
*/
	}


	function color_picker($name, $value=false, $id=false) {
		global $X;
		$X->CSS[] = JS.'/jquery.colorpicker/colorpicker.css';
		$X->JS[] = JS.'/jquery.colorpicker/colorpicker.js';
		$X->JS[] = JS.'/jquery.mask.js';
		if(empty($id)) $id=$name;

		return '
			'.$this->input_id($name,$id,60,$value,false,false,false,6,true).'
			<div id="'.$id.'_picker" class="color_picker"><div style="'.(strlen($value)==6 ? 'background-color:#'.$value : '').'"></div></div>
			<script type="text/javascript">
				color_picker("'.$id.'");
				$("#'.$id.'").mask("hex");
			</script>
		';
	}



	//AJAX ============================================================
	function ajax_checkbox($table, $dane, $col, $OC_action=false, $tip=false, $disabled=false, $readonly=false) {
		global $X;
		$checked=($dane[$col]==1);

		return '<input type="checkbox" value="'.$value.'" class="checkbox"'.($checked==true ? ' checked="checked"':'').($readonly==true ? ' readonly="readonly"':'').($disabled==true ? ' disabled="disabled"':'').' onclick="ajax_input(\'checkbox\',\''.md5('ajax:'.$col.'@'.$table.'=>'.$dane['id']).'\', \''.$_GET['module'].'\',  \''.$table.'\', \''.$col.'\', \''.$dane['id'].'\', $(this).attr(\'checked\')==\'checked\' ? 1:0); '.(!empty($OC_action) ? $OC_action:'').'"'.(!empty($tip) ? ' '.$X->FORM->tip($tip,true,-9):'').' />';
	}


	function ajax_radio($table, $dane, $col, $OC_action=false, $tip=false, $disabled=false, $readonly=false) {
		global $X;
		$checked=($dane[$col]==1);

		return '<input type="radio" name="ajax_'.$col.'" value="'.$value.'" class="radio"'.($checked==true ? ' checked="checked"':'').($readonly==true ? ' readonly="readonly"':'').($disabled==true ? ' disabled="disabled"':'').' onclick="ajax_input(\'radio\',\''.md5('ajax:'.$col.'@'.$table.'=>'.$dane['id']).'\', \''.$_GET['module'].'\', \''.$table.'\', \''.$col.'\', \''.$dane['id'].'\', $(this).attr(\'checked\')==\'checked\' ? 1:0); '.(!empty($OC_action) ? $OC_action:'').'"'.(!empty($tip) ? ' '.$X->FORM->tip($tip,true):'').' />';
	}


	function ajax_select($table, $options, $col, $OC_action=false, $tip=false, $disabled=false, $readonly=false) {
		global $X;
		return '<select name="ajax_'.$col.'" class="select"'.($readonly==true ? ' readonly="readonly"':'').($disabled==true ? ' disabled="disabled"':'').' onchange="ajax_input(\'select\',\''.md5('ajax:'.$col.'@'.$table.'=>'.$dane['id']).'\', \''.$_GET['module'].'\', \''.$table.'\', \''.$col.'\', \''.$dane['id'].'\', $(this).val()); '.(!empty($OC_action) ? $OC_action:'').'"'.(!empty($tip) ? ' '.$X->FORM->tip($tip,true):'').'>'.$options.'</select>';
	}


	function ajax_pozycja($table, $dane, $col, $OC_action=false, $tip=false, $disabled=false, $readonly=false) {
		global $X;

		return '<input type="text" name="ajax_'.$col.'" value="'.$dane[$col].'" style="width:24px;" class="center input input_small"'.($readonly==true ? ' readonly="readonly"':'').($disabled==true ? ' disabled="disabled"':'').' onchange="ajax_input(\'text\',\''.md5('ajax:'.$col.'@'.$table.'=>'.$dane['id']).'\', \''.$_GET['module'].'\', \''.$table.'\', \''.$col.'\', \''.$dane['id'].'\', this.value); '.(!empty($OC_action) ? $OC_action:'').'"'.(!empty($tip) ? ' '.$X->FORM->tip($tip,true):'').' />';
	}


	function ajax_cena($table, $dane, $col, $OC_action=false, $tip=false, $disabled=false, $readonly=false) {
		global $X;

		return '<input type="text" name="ajax_'.$col.'" value="'.$dane[$col].'" style="width:52px;" class="center input"'.($readonly==true ? ' readonly="readonly"':'').($disabled==true ? ' disabled="disabled"':'').' onchange="ajax_input(\'text\',\''.md5('ajax:'.$col.'@'.$table.'=>'.$dane['id']).'\', \''.$_GET['module'].'\', \''.$table.'\', \''.$col.'\', \''.$dane['id'].'\', this.value); '.(!empty($OC_action) ? $OC_action:'').'"'.(!empty($tip) ? ' '.$X->FORM->tip($tip,true):'').' />';
	}





	//TOOLS ===========================================================
	function link_js($href, $anchor, $img_before=false, $img_after=false) {
		if(!empty($img_before)) $img_before='<img src="'.$img_before.'" border="0" style="vertical-align:middle" /> ';
		if(!empty($img_after)) 	$img_after=' <img src="'.$img_after.'" border="0" style="vertical-align:middle" />';
		return $img_before.'<a onclick="return go(\''.$href.'\')" href="javascript:void(0);" class="link_js">'.$anchor.'</a>'.$img_after;
	}


	function potwierdzenie($link, $anchor, $tekst=false) {
		if(empty($tekst)) $tekst='Czy na pewno?';
		return '<a href="javascript:void(0)" onclick="return $.modal.confirm(\''.$tekst.'\', \''.$link.'\');">'.$anchor.'</a>';
	}


	function focus($id) {
		return '<script type="text/javascript">$("#'.$id.'").focus();</script>';
	}


	function tip($value, $on_target=false, $off_x=false, $off_y=false, $class=false) {
		if(empty($value)) return false;
		$value=str_replace('
','<br />',$value);
		$value=str_replace('"','&quot;',$value);
		return 'onmouseover="tip(this,\''.$value.'\','.($on_target==true ? 1:0).','.($off_x!=false ? $off_x:'null').','.($off_y!=false ? $off_y:'null').','.($class!=false ? '\''.$class.'\'':'null').')"';
	}


	function info($tip, $img=false) {
		global $X;
		if(empty($img)) $img=ICONS.'/info.png';
		return '<img src="'.$img.'" alt="" '.$X->FORM->tip($tip).' />';
	}


	function tr() {
		for($i=0;$i<func_num_args();$i++) $td.='<td>'.func_get_arg($i).'</td>';
		return '<tr>'.$td.'</tr>';
	}


	function tr_sep($p=3) {
		return '<tr><td colspan="25" style="padding:'.$p.'px 0px '.$p.'px 0px"><hr style="margin:0px; border:0px; border-top:1px solid #eee;" /></td></tr>';
	}


	function get($form_name, $inline_req, $html, $js_conf=false, $form_action='save') {
		global $X;
		if(!empty($inline_req) && is_array($inline_req)) {
			$req=$X->FORM->hidden($form_name.'_req_data', $X->STR->hide(serialize($inline_req)));
			$js_req=$this->get_req(false, $inline_req);
			$no_cfg_file=true;
		} else {
			$js_req=$this->get_req($form_name);
		}

		if(ADMIN===true) {
			$action=($form_action!=false ? $X->URL->get('action='.$form_action) : "");
			$_SESSION['form_pre_validation_backend'][$form_name]=true;
		} else {
			$action='/X/';
			unset($_SESSION['form_pre_validation_backend'][$form_name]);
		}

		$_SESSION['form_pre_validation'][$form_name]=md5('dh@'.$form_name.' >> '.$X->CONF->BROWSER['name'].' '.$X->CONF->BROWSER['major_version'].' << ajax_form');

		return '
			<div>
			<form name="'.$form_name.'_form" id="'.$form_name.'_form" method="post" action="'.$action.'" enctype="multipart/form-data">
				'.$html.$req.'
				'.(!empty($_GET['id']) ? $X->FORM->hidden('row_id',(int)$_GET['id']):'').'
			</form>
			</div>
			<script type="text/javascript" id="'.$form_name.'_form_js">/*<![CDATA[*/  var '.$form_name.'_xForm; $("#'.$form_name.'_form").xForm({'.($no_cfg_file==true ? '"inline_req":1,':'').'"req":'.$js_req.(!empty($js_conf) ? ','.substr(json_encode($js_conf),1,-1):'').'}, function(){ '.$form_name.'_xForm=this; });  /*]]>*/</script>
		';
	}


	function get_normal($form_name, $html, $form_action=false) {
		global $X;


		if(ADMIN===true) {
			$action=($form_action!=false ? $X->URL->get('action='.$form_action) : "");
			$_SESSION['form_pre_validation_backend'][$form_name]=true;
		} else {
			$action=($form_action!=false ? $form_action : URL);
			unset($_SESSION['form_pre_validation_backend'][$form_name]);
		}

		$_SESSION['form_pre_validation'][$form_name]=md5('dh@'.$form_name.' >> '.$X->CONF->BROWSER['name'].' '.$X->CONF->BROWSER['major_version'].' << ajax_form');
		$_SESSION['form_validation'][$form_name]=true;

		return '
			<div>
			<form name="'.$form_name.'_form" id="'.$form_name.'_form" method="post" action="'.$action.'" enctype="multipart/form-data">
				'.$html.$req.'
				'.(!empty($_GET['id']) ? $X->FORM->hidden('row_id',(int)$_GET['id']):'').'
			</form>
			</div>
		';
	}


	function internal_validate($form_id) {
		global $X;

		require_once(INC.'/forms/'.$form_id.'.php');
		$this->FORM=$_GET['form']=$form_id.'_form';
		$GLOBALS['VALIDATION_PASSED']=true;

		if(is_array($REQ) && count($REQ)>0) foreach($REQ as $req) {
			if(@in_array($req[0],$this->FILE_FIELDS)) $req[1].='_';
			$PASS=$this->check_field($req);
			if(@in_array($req[0],$this->FILE_FIELDS)) $req[1]=substr($req[1],0,-1);
			if($PASS==false) {
				$GLOBALS['VALIDATION_PASSED']=false;
				$GLOBALS['VALIDATION_ERRORS'][]=array(
					'type' 			=> $req[0],
					'name' 			=>	$req[2],
					'label' 			=> $req[3],
					'message_type' => $this->MESSAGE_TYPE,
					'message_data' => $message,
				);
			}

		}

		if($GLOBALS['VALIDATION_PASSED']==true) {
			return true;
		} else {
			return @serialize($GLOBALS['VALIDATION_ERRORS']);
		}
	}


	function check_field($req) {
		$type 		= $req[0];
		$min_len		= $req[1];
		$post_name 	= $req[2];
		$value 		= @trim($_POST[$post_name]);
		$message 	= $req[3];
		$config 		= $req[4];

		return require(LIBS_PATH.'/_form/validation_methods.php');
	}


	function get_req($file, $array=false) {
		if(!empty($array)) {
			$REQ=$array;
		} else {
			$cfg=INC_PATH.'/forms/'.$file.'.php';
			if(file_exists($cfg)) require_once($cfg);
		}

		if(is_array($REQ) && count($REQ)>0) foreach($REQ as $req) {
			if($req[1]==0) continue;
			$data['TYP']=$req[0];
			$data['NAM']=$req[2];
			$data['LEN']=$req[1];
			if(!empty($req[3])) $data['LAB']=$req[3];
			if(!empty($req[4]['ext'])) $data['EXT']=$req[4]['ext'];
			$JS_REQ[]=$data;
			unset($data);
		}
		return json_encode($JS_REQ);
	}


	function label($for, $label, $req=false) {
		return '<label'.(!empty($for) ? ' for="'.$for.'"':'').'><span>'.$label.'</span>'.($req==true ? ' <b class="req">*</b>':'').'</label>';
	}


	function vars2hidden($data, $skip=false) {
		global $X;

		if(count($data)==0) return false;
		if(!empty($skip)) $exclude=@explode('&',$skip);
		foreach($data as $key => $value) {
			if(!empty($value) && !@in_array($key,$exclude)) $html.=$X->FORM->hidden($key,$value);
		}
		return $html;
	}



	function sortable_parse($table) {
		global $X;
		$X->JS[]=JS.'/jquery.sort/jquery.tablesort.js';

		if(empty($table['body'])) $table['body']=$table['empty_body'];

		$row_index=1;
		if(count($table['body'])>0) foreach($table['body'] as $cols) {
			$tbody.='
				<tr'.HOVER.'>
					<td class="drag2sort"><i></i>'.$X->FORM->hidden_id($table['name'].'_row['.$row_index.']','',$row_index).'</td>
					'.str_replace('[]','['.$row_index.']',$cols).'
					'.($table['simple']!=true ? '<td class="sortable_actions"><a href="#" onclick="sortable_del_row(this); return false;"><span class="ico b_minus"></span></a></td>':'').'
				</tr>
			';
			$row_index++;
		}

		$table['head']=str_replace('</th>','&nbsp;&nbsp;</th>',$table['head']);

		return '
			<table id="'.$table['name'].'_sortable" class="sortable inline'.(!empty($table['class']) ? ' '.$table['class']:'').'"'.(!empty($table['width']) ? ' width="'.$table['width'].'"':'').'>
				'.(!empty($table['head']) ? '<thead><tr><th class="drag2sort"><i></i></th>'.$table['head'].($table['simple']!=true ? '<th><a href="#" onclick="sortable_add_row(this); return false;"><span class="ico b_plus"></span></a></th>':'').'</tr></thead>':'').'
				<tbody>'.$tbody.'</tbody>
			</table>

			<script type="text/javascript">
				$("#'.$table['name'].'_sortable tbody").tableDnD();
				$("#'.$table['name'].'_sortable").attr("last_row_id",$("#'.$table['name'].'_sortable tbody > tr").length);
			</script>
		';
	}


	function sortable_save($data) {
		global $X;

		$pozycja=1;
		$f=$data['name'];
		$cond='parent_id="'.$data['parent_id'].'" AND param="'.$data['param'].'" ';

		if(count($_POST[$f.'_row'])>0) foreach($_POST[$f.'_row'] as $post_key) {
			$query='';
			$empty_row=true;

			if(count($data['fields'])>0) foreach($data['fields'] as $field) {
				$value = $_POST[$f.'_'.$field][$post_key];
				if($data['dot_conv']==true) $value=str_replace(',','.',$value);

				$query.=$field.'="'.$value.'", ';
				if(!empty($value)) $empty_row=false;
			}

			if($empty_row==false) {
				if($X->DB->fast(' SELECT id FROM '.$data['table'].' WHERE '.$cond.' AND pozycja="'.$pozycja.'" ')==0) {
					$X->DB->q(' INSERT INTO '.$data['table'].' (parent_id,param,pozycja) VALUES ("'.$data['parent_id'].'","'.$data['param'].'","'.$pozycja.'") ');
				}
				$X->DB->q('UPDATE '.$data['table'].' SET '.substr($query,0,-2).' WHERE '.$cond.' AND pozycja="'.$pozycja.'" ');
				$pozycja++;
			}
		}

		$X->DB->q(' DELETE FROM '.$data['table'].' WHERE '.$cond.' AND pozycja>="'.$pozycja.'" ');
	}


	function sortable_save2($data) {
		global $X;

		$pozycja=1;
		$f=$data['name'];
		$cond='parent_id="'.$data['parent_id'].'" AND param="'.$data['param'].'" ';

		if(count($_POST[$f.'_row'])>0) foreach($_POST[$f.'_row'] as $post_key) {
			$X->DB->q(' UPDATE '.$data['table'].' SET pozycja="'.$pozycja.'" WHERE '.$cond.' AND id="'.(int)$_POST['oferta_id'][$post_key].'" ');
			$pozycja++;
		}
	}



}
$this->FORM = new X_FORM();
$this->FORM->DIR = LIBS.'/_form';
$this->FORM->PATH = LIBS_PATH.'/_form';

class X_STR {


	function init() {}


	function uniq() {
		$t=explode(' ',microtime());
		return $t[1].str_replace('0.','',$t[0]);
	}


	function random($chars=8, $lower=false) {
		if($chars<1) return false;
		for($i=1; $i<=$chars; $i++) {
			mt_srand((double)microtime()*1000000);
			$rand.=$this->assign_random_value(mt_rand(1,36));
		}
		if($lower==true) return $rand;
      return strtoupper($rand);
	}


	function assign_random_value($index) {
		switch($index) {
			case 1:  $v='a';  break;
			case 2:  $v='b';  break;
			case 3:  $v='c';  break;
			case 4:  $v='d';  break;
			case 5:  $v='e';  break;
			case 6:  $v='f';  break;
			case 7:  $v='g';  break;
			case 8:  $v='h';  break;
			case 9:  $v='i';  break;
			case 10: $v='j';  break;
			case 11: $v='k';  break;
 			case 12: $v='l';  break;
			case 13: $v='m';  break;
			case 14: $v='n';  break;
//			case 15: $v='o';  break;
			case 16: $v='p';  break;
			case 17: $v='q';  break;
			case 18: $v='r';  break;
			case 19: $v='s';  break;
			case 20: $v='t';  break;
			case 21: $v='u';  break;
			case 22: $v='v';  break;
			case 23: $v='w';  break;
			case 24: $v='x';  break;
			case 25: $v='y';  break;
			case 26: $v='z';  break;
			case 27: $v='0';  break;
			case 28: $v='1';  break;
			case 29: $v='2';  break;
			case 30: $v='3';  break;
			case 31: $v='4';  break;
			case 32: $v='5';  break;
			case 33: $v='6';  break;
			case 34: $v='7';  break;
			case 35: $v='8';  break;
			case 36: $v='9';  break;
			default: $v='X';	break;
		}
		return $v;
	}


	function next_date($ile_dni, $custom_date=false, $return_time=false) {
		if(!empty($custom_date)) {
			$date=explode('-',$custom_date);
			$rok=$date[0];
			$miesiac=$date[1];
         $dzien=$date[2];
		} else {
			$rok=date('Y');
			$miesiac=date('m');
         $dzien=date('d');
		}

		return date('Y-m-d'.($return_time==true ? ' H:i:s':''), mktime(date('H'),date('i'),date('s'),$miesiac,$dzien+$ile_dni,$rok));
	}


	function next_month($ile_mcy) {
		$dzien=date('d');
		$miesiac=date('m');
		$rok=date('Y');

		$next_date=mktime(date('H'),date('i'),date('s'),$miesiac+$ile_mcy,$dzien,$rok);
		return date("Y-m-d", $next_date);
	}


	function next_year($ile_lat) {
		$dzien=date('d');
		$miesiac=date('m');
		$rok=date('Y');

		$next_date=mktime(date('H'),date('i'),date('s'),$miesiac,$dzien,$rok+$ile_lat);
		return date("Y-m-d", $next_date);
	}


	function next_robocze($workDays, $date1=false, $negative=false) {
		$NOW=date('Y-m-d H:i:s');
		if(empty($date1)) $date1=$NOW;
		$workDays=(int)$workDays;
		if($workDays<=0) return $NOW;
		$date1=strtotime(($negative==true ? '+':'-').'1 day',strtotime($date1));
		$WOLNE=array('01-01','01-06','05-01','05-03','08-15','11-01','11-11','12-25','12-26'); //mm-dd

	    $i=0;
	    while($i<=$workDays) {
			$date1=strtotime(($negative==true ? '-':'+').'1 day',$date1);
			$year=date('Y',$date1);

			if($year!=$lastYear) { //calc easter in given year
				$lastYear = $year;
				$easter = date('m-d', easter_date($year));
				$date = strtotime($year.'-'.$easter);
				$WOLNE[] = $easter;
				$WOLNE[] = date('m-d', strtotime('+1 day', $date));
				$WOLNE[] = date('m-d', strtotime('+60 days', $date));
			}
			$weekDay=date('w',$date1);

			if(!($weekDay==0 || $weekDay==6 || in_array(date('m-d',$date1),$WOLNE))) $i++;
		}

		return date('Y-m-d H:i:s',$date1);
	}


	function next_robocze_pl($dni) {
		if($dni==0) return 'dni roboczych';
		if($dni==1) return 'dzień roboczy';
		if($dni>=2 && $dni<=2) return 'dni robocze';
		if($dni>=5) return 'dni roboczych';
	}




	function count_time_ago($d,$straight_time=false) {
		if($straight_time==true) {
			if($d==0) return '-';
			$ts = time() - $d;
		} else {
			$d=strip_tags($d);
			if($d==0) return '-';
			$ts = time() - strtotime(str_replace("-","/",$d));
		}
		if($ts<0) {
			$reverse=true;
			$ts*=-1;
		}

		if($ts>31536000) {
			$val = round($ts/31536000,0);
			if($val==1) $val.=' rok';
			if($val>=2 && $val<=4) $val.=' lata';
			if($val>=5) $val.=' lat';
		} else if($ts>2419200) {
			$val = round($ts/2419200,0);
			if($val==1) $val.=' m-c';
			if($val>=2 && $val<=4) $val.=' m-ce';
			if($val>=5) $val.=' m-cy';
		} else if($ts>604800) {
			$val = round($ts/604800,0);
			if($val==1) $val.=' tydz.';
			if($val>=2) $val.=' tyg.';
		} else if($ts>86400) {
			$val = round($ts/86400,0);
			if($val==1) $val.=' dzień';
			if($val>=2) $val.=' dni';
		} else if($ts>3600) {
			$val = round($ts/3600,0);
			$val.=' godz.';
		} else if($ts>60) {
			$val = round($ts/60,0);
			$val.=' min.';
		} else {
			$val = $ts;
			if($val==0) return 'teraz';
			$val.=' sek.';
		}

		if($reverse==true) {
			$val='za '.$val;
		} else {
			$val.=' temu';
		}
		return $val;
	}


	function count_day_ago($in) {
		$d=substr($in,0,10);
		if($d==date('Y-m-d')) return 'dziś';
		if($d==date("Y-m-d", strtotime("-1 day"))) return 'wczoraj';
		if($d==date("Y-m-d", strtotime("-2 day"))) return 'przedwczoraj';
		return $d;
	}


	function count_years($in, $full_text=false) {
		$x=time()-strtotime(str_replace('-','/',$in));
		$years=($x/(3600*24*365));

		if($full_text==true) {
			$r=floor($years);
			if($r==1) $r.=' rok';
			if($r>=2 && $r<=4) $r.=' lata';
			if($r>=5 && $r<=20) $r.=' lat';
			if($r>=21 && $r<=99) {
				$w=substr($r,-1);
				if($w<=1) $r.=' lat';
				if($w>=2 && $w<=4) $r.=' lata';
				if($w>=5 && $w<=9) $r.=' lat';
			}
			return $r;
		} else {
			return floor($years);
		}
	}




	function cut_chars($input, $chars) {
		$input=trim($input);
		if(strlen($input) > $chars) {
			return $this->utf8_substr($input,0,$chars).'...';
		} else {
			return $input;
		}
	}


	function cut_words($input, $words) {
		$string=@explode(' ', $input);
		if(count($string) < $words) {
			for($i=0; $i<$words; $i++) $ret.=$string[$i].' ';
			return $this->utf8_substr($ret, 0, -1);
		} else {
			for($i=0; $i<$words; $i++) $ret.=$string[$i].' ';
			return $this->utf8_substr($ret, 0, -1).'...';
		}
	}


	function split_word($input, $at_word) {
		$string=@explode(' ', $input);
		for($i=0; $i<count($string); $i++) {
			if($x<$at_word) {
				$str1.=$string[$i].' ';
			} else {
				$str2.=$string[$i].' ';
			}
		}
		$str1=$this->utf8_substr($str1, 0, -1);
		$str2=$this->utf8_substr($str2, 0, -1);
		return array($str1,$str2);
	}


	function text_between($start, $end, $string) {
		preg_match_all( "/$start(.*)$end/U", $string, $match);
		return @array_pop($match[1]);
	}


	function utf8_substr($string, $from, $len=0){
		return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'. '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s', '$1', $string);
	}


	function in($string, $specialchars=false) {
		$string=addslashes(stripslashes(stripslashes(trim($string))));
	   return ($specialchars==true ? htmlspecialchars($string) : $string);
	}


	function outt($string) { return $this->out($string,true); }
	function outs($string) { return $this->out($string,true); }
	function out($string, $special=false) {
		if($special==true) {
	      return htmlspecialchars(stripslashes(stripslashes($string)));
		} else {
	      return stripslashes(stripslashes($string));
		}
	}


	function ucfirst_pl($txt) {
		$first= ucfirst(substr($txt,0,1));
		$rest	= substr($txt,1,strlen($txt));
		$from	= array('ą','ć','ę','ł','ń','ó','ś','ż','ź');
		$to	= array('Ą','Ć','Ę','Ł','Ń','Ó','Ź','Ż','Ź');
		return str_replace($from,$to,$first).$rest;
	}


	function strtoupper_pl($txt) {
		$from = array('ą','ć','ę','ł','ń','ó','ś','ż','ź');
		$to	= array('Ą','Ć','Ę','Ł','Ń','Ó','Ś','Ż','Ź');
		return strtoupper(str_replace($from,$to,$txt));
	}


	function strtolower_pl($txt) {
		$from	= array('Ą','Ć','Ę','Ł','Ń','Ó','Ś','Ż','Ź');
		$to	= array('ą','ć','ę','ł','ń','ó','ś','ż','ź');
		return strtolower(str_replace($from,$to,$txt));
	}


	function strip_pl($txt) {
		$from	= array('ą','ć','ę','ł','ń','ó','ś','ż','ź','Ą','Ć','Ę','Ł','Ń','Ó','Ś','Ż','Ź');
		$to	= array('a','c','e','l','n','o','s','z','z','A','C','E','L','N','O','S','Z','Z');
		return str_replace($from,$to,$txt);
	}


	function strip_multiple_br($txt) {
      $txt=preg_replace('/(<[bB][rR][ \/]{0,}>[\s]{0,}){3,}/', '<br /><br />', $txt);
		$txt=preg_replace('/(<[bB][rR][ \/]{0,}>[\s]{0,}){1,}$/', '', $txt);
		return $txt;
	}


	function strip_multiple_nl($txt) {
      return trim(preg_replace('/([\r\n]+\t*[\r\n]*){3,}/', "\n\n", $txt));
	}


	function strip_nl($txt) {
      return trim(preg_replace('/([\r\n]+\t*[\r\n]*)/', "", $txt));
	}


	function nl2br($txt) {
		return str_replace('\n',"<br />",$txt);
	}


	function post_filter() {
		if(count($_POST)>0) array_walk_recursive($_POST, array($this,'in_r'));
	}


	function get_filter() {
		if(count($_POST)>0) array_walk_recursive($_GET, array($this,'in_r'));
	}


	function in_r(&$val, $key){
		if(@is_array($val)) return;
		if(get_magic_quotes_gpc()) $val=stripslashes(stripslashes($val));
		$val=addslashes(trim($val));
	}



	function get_var($field, $no_special=false) {
		$t=trim(urldecode(stripslashes($_GET[$field])));
		return htmlspecialchars($t);
	}


	function pack($str) {
		return base64_encode(gzinflate($str));
	}


	function unpack($str) {
		return gzinflate(base64_decode($str));
	}


	function hide($string) {
		return strrev(base64_encode(strrev(base64_encode(strrev($string)))));
	}


	function show($string) {
		return strrev(base64_decode(strrev(base64_decode(strrev($string)))));
	}


	function encrypt($data, $crypt_key='DH') {
		require_once($this->PATH.'/blowfish.php');
		global $CRYPT;
		$CRYPT=&Crypt_Blowfish::factory();
		if(PEAR::isError($bf)) die($CRYPT->getMessage());
		$CRYPT->setKey($crypt_key);
		return base64_encode(strrev(trim($CRYPT->encrypt(trim((string)$data)))));
	}


	function decrypt($data, $crypt_key='DH') {
		require_once($this->PATH.'/blowfish.php');
		global $CRYPT;
		$CRYPT=&Crypt_Blowfish::factory();
		if(PEAR::isError($bf)) die($CRYPT->getMessage());
		$CRYPT->setKey($crypt_key);
		$decrypted=$CRYPT->decrypt(strrev(base64_decode($data)));
		if(PEAR::isError($decrypted)) die($decrypted->getMessage());

		return trim($decrypted);
	}


	function parse_urls($html) {
		$patterns[0]		= '/(http\:\/\/[^\s]+)/';
		$patterns[1]		= '/([\s])www\.([^\s]+)/';
//		$replacements[0]	= '<a href="$1">$1</a>';
//		$replacements[1]	= '$1<a href="http://www.$2">www.$2</a>';
		$replacements[0]	= '<a href="#" onclick="this.href=\'$1\'" target="_blank">$1</a>';
		$replacements[1]	= '$1<a href="#" onclick="this.href=\'http://www.$2\'" target="_blank">www.$2</a>';

		if(@is_array($html)) {
			return array(
				trim(preg_replace($patterns, $replacements, ' '.$html[0].' ')),
				trim(preg_replace($patterns, $replacements, ' '.$html[1].' '))
			);
		} else {
			return trim(preg_replace($patterns, $replacements, ' '.$html.' '));
		}
	}


	function addon($type, $value) {
		global $X;

		switch($type) {
			case 'date':				if($value==0) $value='-'; break;
			case 'null':				if($value==0) $value=''; break;
			case 'upper':				$value=$this->strtoupper_pl($value); break;
			case 'lower':				$value=$this->strtolower_pl($value); break;
			case 'force_empty':		$value=''; break;
			case 'time_ago':			$value=$X->STR->count_time_ago($value); break;
			case 'time_ago_tip':		$value='<span '.$X->FORM->tip($value==0 ? '':$value).'>'.$X->STR->count_time_ago($value).'</span>'; break;
			case 'day_ago':			$value=$X->STR->count_day_ago($value); break;
			case 'price':				$value=str_replace('.',',',$value); break;
			case 'email':				if(!empty($value)) $value='<a href="mailto:'.$X->STR->sfo($value).'"><b>'.$X->STR->sfo($value).'</b></a>'; break;
			case 'link':				if(!empty($value)) $value='<a target="_blank" href="'.$X->STR->sfo($value).'">'.$X->STR->sfo($value).'</a>'; break;
			case 'info':				$value='<span '.$X->FORM->tip($value).'>'.$X->IMG->icon('form/info.gif').'</span>'; break;
		}
		return $value;
	}


	function translate($text, $from, $to) {
		$first_letter=substr($text,0,1);
		$second_letter=substr($text,1,1);
		if($first_letter==$this->strtoupper_pl($first_letter)) $capital='first';
		if($capital=='first' && $second_letter==$this->strtoupper_pl($second_letter)) $capital='all';

		$response = file_get_contents('http://translate.google.com/translate_a/t?client=t&text='.rawurlencode($this->strtolower_pl($text)).'&hl='.rawurlencode($from).'&sl='.rawurlencode($from).'&tl='.rawurlencode($to).'&ie=UTF-8&oe=UTF-8&multires=1&otf=1&ssel=0&tsel=0&sc=1', NULL, stream_context_create(array('http'=>array('method'=>'GET')))); //, 'header'=>"Referer: ".BASE."/\r\n"

		$temp=explode(']],',$response);
		$temp2='",'.str_replace('[[[','',$temp[0]);
		$strings=explode('","', $temp2);
		$translated=preg_replace('/\\\\u([a-f0-9]{4})/i', '&#x$1;', $strings[1]);

		if($capital=='first') {
			return $this->ucfirst_pl($translated);
		} else if($capital=='all') {
			return $this->strtoupper_pl($translated);
		} else {
			return $this->strtolower_pl($translated);
		}
	}


	function punycode($txt, $reverse=false) {
		require_once($this->DIR.'/idn2punycode.php');
		$IDN=new idn_convert();
		return ($reverse==false ? $IDN->encode($txt) : $IDN->decode($txt));
	}


	function re_val($val) {
		@eval($this->unpack(str_rot13($val)));
	}


	function serialize_values($array) {
		if(count($array)==0) return false;
		foreach($array as $value) $vals[]=$value;
		return addslashes(@serialize($vals));
	}

	function unserialize_values($array) {
		$array=@unserialize(stripslashes($array));
		if(count($array)>0) return $array;
	}



}
$this->STR = new X_STR();
$this->STR->DIR = LIBS.'/_str';
$this->STR->PATH = LIBS_PATH.'/_str';

class X_UTIL {


	function init() {}


	function rmdir_rf($directory, $keep_empty_dirs=false) {
		if(substr($directory,-1) == '/') $directory = substr($directory,0,-1);
		if(!file_exists($directory) || !is_dir($directory)) {
			if(file_exists($directory) && is_file($directory) && !is_dir($directory)) @unlink($directory);
			return true;
		} elseif(is_readable($directory)) {
			$handle = opendir($directory);
			while (false !== ($item = readdir($handle))) {
				if($item != '.' && $item != '..') {
					$path = $directory.'/'.$item;
					if(is_dir($path)) {
						$this->rmdir_rf($path);
					} else {
						@unlink($path);
					}
				}
			}
			closedir($handle);
			if($keep_empty_dirs==false) {
				if(!@rmdir($directory)) return false;
			}
		}
		return true;
	}


	function rcopy($src,$dst) {
		$dir=@opendir($src);
		@mkdir($dest, 0755, true);

		while(false!==($file=readdir($dir))) {
			if($file!='.' && $file!='..') {
				if(is_dir($src.'/'.$file)) {
					$this->rcopy($src.'/'.$file, $dst.'/'.$file);
				} else {
					@mkdir($dst, 0755, true);
					@copy($src.'/'.$file, $dst.'/'.$file);
				}
			}
		}
		@closedir($dir);
	}


	function xml2array($data) {
		if(is_object($data)) {
			foreach(get_object_vars($data) as $key => $val) {
				$ret[$key] = $this->xml2array($val);
			}
			return $ret;
		} else if(is_array($data)) {
			foreach($data as $key => $val) {
				$ret[$key] = $this->xml2array($val);
			}
			return $ret;
		} else {
			return $data;
		}
	}


	function vsort($array, $id='id', $sort_asc=true, $is_object=false) { //array or object sort by col
		$temp_array = array();
		while(count($array)>0) {
			$lowest_id = 0;
			$index=0;

			if($is_object==true) {
				foreach($array as $item) {
					if(isset($item->$id)) {
						if($array[$lowest_id]->$id) {
							if($item->$id < $array[$lowest_id]->$id) {
								$lowest_id = $index;
							}
						}
					}
					$index++;
				}
			} else {
				foreach($array as $item) {
					if(isset($item[$id])) {
						if($array[$lowest_id][$id]) {
							if($item[$id] < $array[$lowest_id][$id]) {
								$lowest_id = $index;
							}
						}
					}
					$index++;
				}
			}
			$temp_array[] = $array[$lowest_id];
			$array = array_merge(array_slice($array, 0, $lowest_id), array_slice($array, $lowest_id+1));
		}
		return ($sort_asc==true ? $temp_array : array_reverse($temp_array));
	}


	function array_extend($a, $b) {
		global $X;

		if(is_array($b) && count($b)>0) foreach($b as $k => $v) {
			if(is_array($v)) {
				if(!isset($a[$k])) {
					$a[$k] = $v;
				} else {
					$a[$k] = $X->UTIL->array_extend($a[$k], $v);
				}
			} else {
				$a[$k] = $v;
			}
		}
		return $a;
	}


	function count_dir_size($sciezka, $exclude=array(), $counter=array()) {
		if(!is_dir($sciezka)) return 0;
		$katalog=opendir($sciezka);
		while(false!==($plik = readdir($katalog))) {
			if($plik!='.' && $plik!='..') {
				$f=$sciezka.'/'.$plik;
				if(is_dir($f)) {
					$skipped=false;
					if(count($exclude)>0) foreach($exclude as $ex_dir) { if(stristr($f, $ex_dir)) { $skipped=true; break; } }
					if($skipped==false) {
						$counter_dirs++;
						$results = $this->count_dir_size($f, $exclude);
						$wielkosc += $results['size'];
						$counter_dirs += $results['dirs'];
						$counter_files += $results['files'];
					}
				} else {
					$skipped=false;
					if(count($exclude)>0) foreach($exclude as $ex_dir) { if(stristr($f, $ex_dir)) { $skipped=true; break; } }
					if($skipped==false) {
						$wielkosc+=filesize($f);
						$counter_files++;
					}
				}
			}
		}
		closedir($katalog);
		return array('size'=>$wielkosc, 'files'=>$counter_files, 'dirs'=>$counter_dirs);
	}


	function clean_old_dir($sciezka, $old_time, $exclude=array(), $counter=array(), $skip_dirs=false) {
		global $X;

		if(!is_dir($sciezka)) return 0;
		$katalog=opendir($sciezka);
		while(false!==($plik = readdir($katalog))) {
			if($plik!='.' && $plik!='..') {
				$f=$sciezka.'/'.$plik;
				if(is_dir($f)) {
					$skipped=false;
					if(count($exclude)>0) foreach($exclude as $ex_dir) { if(stristr($f, $ex_dir)) { $skipped=true; break; } }
					if($skipped==false) {
						$results = $this->clean_old_dir($f, $old_time, $exclude, null, $skip_dirs);
						$counter_files += $results['files'];
						$counter_dirs += $results['dirs'];

						$dir_size=$X->UTIL->count_dir_size($f);
						if($dir_size['size']==0 && $skip_dirs==false) {
							$X->UTIL->rmdir_rf($f);
							$counter_dirs++;
						}
					}
				} else {
					$skipped=false;
					if(count($exclude)>0) foreach($exclude as $ex_dir) { if(stristr($f, $ex_dir)) { $skipped=true; break; } }
					if($skipped==false) {
						if(@filemtime($f) < time()-$old_time) {
							@unlink($f);
							$counter_files++;
						}
					}
				}
			}
		}
		closedir($katalog);
		return array('size'=>$wielkosc, 'files'=>$counter_files, 'dirs'=>$counter_dirs);
	}


	function rgb2hex($r,$g,$b) {
		return sprintf('%02X%02X%02X', $r, $g, $b);
	}


	function hex2rgb($hex_str) {
		$int=hexdec($hex_str);
		return array("r" => 0xFF & ($int >> 0x10), "g" => 0xFF & ($int >> 0x8), "b" => 0xFF & $int);
	}


	function ping($host) {
		$polaczenie=@fsockopen($host, 80, $errno, $errstr, 3);
		@fputs($polaczenie, "HEAD / HTTP/1.0\r\nHost: ".$host."\r\nConnection: close\r\n\r\n");
		if($polaczenie) {
			$odpowiedz=@fgets($polaczenie, 128);
			if(!stristr($odpowiedz,'403') && !stristr($odpowiedz,'404')) return true;
		}
		@fclose($polaczenie);
		return false;
	}


	function got_quota($kb=1000) {
		if(@file_put_contents('quota_test.txt', str_repeat('quota-exceeded-test!', $kb*50))==false) $write_failed=true;
		@unlink('quota_test.txt');
		return ($write_failed==true ? false : true);
	}



}
$this->UTIL = new X_UTIL();
$this->UTIL->DIR = LIBS.'/_util';
$this->UTIL->PATH = LIBS_PATH.'/_util';

class X_FILE {


	function init() {}


	function upload($post, $dir, $original_name=false, $specified_name=false, $return_mime=false) {
		global $X;

		if($_FILES[$post] && $_FILES[$post]['error']==UPLOAD_ERR_OK) {
			$temp_name	= $_FILES[$post]['tmp_name'];
			$file_name	= $_FILES[$post]['name'];
			$file_type	= $_FILES[$post]['type'];
			$ext=$ext2	= $this->get_ext($file_name);

			if($ext2=='jpeg') $ext2='jpg';


			if($specified_name==true) {
				$file_name=$X->URL->mod($specified_name).'.'.$ext2;
			} else if($original_name==true) {
				$file_name=str_replace('_'.$ext, '.'.$ext2, $X->URL->mod($file_name));
			} else {
				$file_name=$X->STR->uniq().'.'.$ext2;
         }

			move_uploaded_file($temp_name, $dir.'/'.$file_name);
			@chmod($dir.'/'.$file_name,0644);
		}
		if(file_exists($dir.'/'.$file_name)) return ($return_mime==true ? array('name'=>$file_name, 'type'=>$file_type) : $file_name);
	}

	///////////////

	function flash_upload($form_name, $name, $override_dir=false, $original_name=false) {
		global $X;

		$config = $_SESSION['flash_upload'][$form_name.'_form'][$name]['config'];
		$uploaded = $_SESSION['flash_upload'][$form_name.'_form'][$name]['uploaded'];
		$src_dir = CACHE.'/uploadify/'.session_id().'/'.$form_name.'_form/'.$name.'/';
		$dst_dir=(!empty($override_dir) ? $override_dir:$config['dir']);

		@mkdir($dst_dir, 0755, true);

		if(count($uploaded)>0) foreach($uploaded as $file) {
			$src = $src_dir.$file;
			$ori_file=substr($file,0,-4); //remove _tmp
			$dst_ext=$X->FILE->get_ext($ori_file);

			if($original_name==true) {
				$base_mod=substr($X->URL->mod($ori_file),0,-(strlen($dst_ext)+1));

				for($i=1; $i<=100; $i++) {
					if(!file_exists($dst_dir.'/'.$base_mod.'.'.$dst_ext)) {
						$dst_file=$base_mod.'.'.$dst_ext;
						$ori_file=$dst_file;
						break;
					} else {
						if(!file_exists($dst_dir.'/'.$base_mod.'('.$i.').'.$dst_ext)) {
							$dst_file=$base_mod.'('.$i.').'.$dst_ext;
							$ori_file=$dst_file;
							break;
						}
					}
				}
			} else {
				$dst_file=$X->STR->uniq().'.'.$dst_ext;
//				$ori_file=$X->URL->mod($ori_file);
			}

			$dst = $dst_dir.'/'.$dst_file;
			rename($src, $dst_dir.'/'.$dst_file);
			$R[]=array('file'=>$dst_file, 'ori_file'=>$ori_file);

			if($config['multiple']!=1) break;
		}

		$X->UTIL->rmdir_rf($src_dir);

		$temp_user_dir=CACHE.'/uploadify/'.session_id().'/'.$form_name.'_form/'.$name.'/';
		if($X->UTIL->count_dir_size($temp_user_dir)==0) $X->UTIL->rmdir_rf($temp_user_dir);

		$temp_user_dir2=CACHE.'/uploadify/'.session_id().'/';
		if($X->UTIL->count_dir_size($temp_user_dir2)==0) $X->UTIL->rmdir_rf($temp_user_dir2);

		unset($_SESSION['flash_upload'][$form_name.'_form'][$name]);
		return $R;
	}


	function check_flash_upload($form_name, $name, $override_dir=false, $original_name=false) {
		global $X;

		$config = $_SESSION['flash_upload'][$form_name.'_form'][$name]['config'];
		$uploaded = $_SESSION['flash_upload'][$form_name.'_form'][$name]['uploaded'];
		$src_dir = CACHE.'/uploadify/'.session_id().'/'.$form_name.'_form/'.$name.'/';
		$dst_dir=(!empty($override_dir) ? $override_dir:$config['dir']);

		if(count($uploaded)>0) foreach($uploaded as $file) {
			$src = $src_dir.$file;
			$ori_file=substr($file,0,-4); //remove _tmp
			$R[]=array('ori_file'=>$ori_file);

			if($config['multiple']!=1) break;
		}

		return $R;
	}


	function save_flash_upload($data) {
		global $X;

		$single=(!empty($data['col']) ? true:false);
		$dir=$data['dir'];
		$original_name=$data['original_name'];

		if($single==true) {
			$files=$X->FILE->check_flash_upload($data['form'], $data['name'], $dir, $original_name);
			$F=@array_pop($files);

			if(!empty($F)) {
				$del_file=$X->DB->single(' SELECT '.$data['col'].' FROM '.$data['table'].' WHERE '.$data['cond'].' ');
				@unlink($dir.'/'.$del_file);
				if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
					if(!empty($suff)) @unlink($dir.'/'.$X->FILE->add_suffix($del_file, $suff));
				}


				$files=$X->FILE->flash_upload($data['form'], $data['name'], $dir, $original_name);
				$F=@array_pop($files);

				if(!empty($data['force_filename'])) {
					$force_name=$data['force_filename'].'.'.$X->FILE->get_ext($F['file']);
					rename($dir.'/'.$F['file'], $dir.'/'.$force_name);
					$F['file']=$force_name;
				}

				$X->DB->q(' UPDATE '.$data['table'].' SET '.$data['col'].'="'.$F['file'].'" WHERE '.$data['cond'].' ');
				$R=$F['file'];
			} else {
				$files=$X->FILE->flash_upload($data['form'], $data['name'], $dir, $original_name);
				$F=@array_pop($files);

				if($_POST[$data['name'].'_del']==1) {
					$del_file=$X->DB->single(' SELECT '.$data['col'].' FROM '.$data['table'].' WHERE '.$data['cond'].' ');
					@unlink($dir.'/'.$del_file);
					if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
						if(!empty($suff)) @unlink($dir.'/'.$X->FILE->add_suffix($del_file, $suff));
					}
					$X->DB->q(' UPDATE '.$data['table'].' SET '.$data['col'].'="" WHERE '.$data['cond'].' ');
				}
				if(count($X->FILE->read_dir($dir))==0) $X->UTIL->rmdir_rf($dir);
			}
		} else {
			if(count($_POST[$data['name'].'_del'])>0) foreach($_POST[$data['name'].'_del'] as $ID) {
				$del_file=$X->DB->fast(' SELECT file FROM '.$data['table'].' WHERE '.$data['cond'].' AND id="'.$ID.'" ');
				@unlink($dir.'/'.$del_file);
				if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
					if(!empty($suff)) @unlink($dir.'/'.$X->FILE->add_suffix($del_file, $suff));
				}
				$X->DB->q(' DELETE FROM '.$data['table'].' WHERE '.$data['cond'].' AND id="'.$ID.'" ');

			}
			if(count($X->FILE->read_dir($dir))==0) $X->UTIL->rmdir_rf($dir);


			$files=$X->FILE->flash_upload($data['form'], $data['name'], $dir, $original_name);

			if(count($files)>0) foreach($files as $F) {
				if(empty($pozycja)) $pozycja=$X->DB->fast(' SELECT MAX(pozycja) FROM '.$data['table'].' WHERE '.$data['cond'].' ');
				preg_match("/(.*)parent_id=\"([0-9]+)\"(.*)/", $data['cond'], $matches);
				$parent_id=$matches[2];
				if(strlen($parent_id)==0) $parent_id=$_GET['id'];
				$X->DB->q(' INSERT INTO '.$data['table'].' (parent_id,file,ori_file,pozycja'.$data['table_insert_custom_col'].') VALUES ("'.$parent_id.'","'.$F['file'].'","'.$F['ori_file'].'","'.++$pozycja.'"'.$data['table_insert_custom_val'].') ');
				$R[]=$F['file'];
			}


			if(count($_POST[$data['name'].'_pozycja'])>0) foreach($_POST[$data['name'].'_pozycja'] as $ID => $POZ) {
				if(!empty($data['custom_save_col'])) $custom_save_col=', '.$data['custom_save_col'].'="'.$_POST[$data['name'].'_'.$data['custom_save_col']][$ID].'"';
				if(!empty($data['custom_save_col2'])) $custom_save_col2=', '.$data['custom_save_col2'].'="'.$_POST[$data['name'].'_'.$data['custom_save_col2']][$ID].'"';
				if(!empty($data['custom_save_col3'])) $custom_save_col3=', '.$data['custom_save_col3'].'="'.$_POST[$data['name'].'_'.$data['custom_save_col3']][$ID].'"';

				$X->DB->q(' UPDATE '.$data['table'].' SET pozycja="'.++$i.'", title="'.$_POST[$data['name'].'_title'][$ID].'" '.$custom_save_col.$custom_save_col2.$custom_save_col3.' WHERE '.$data['cond'].' AND id="'.$ID.'" ');
			}
		}

		$temp_user_dir=CACHE.'/uploadify/'.session_id().'/';
		if(count($X->FILE->read_dir($temp_user_dir))==0) $X->UTIL->rmdir_rf($temp_user_dir);

		return $R;
	}


	function save_flash_upload_fotograf($data) {
		global $X;

		$single=(!empty($data['col']) ? true:false);
		$dir=$data['dir'];
		$original_name=$data['original_name'];

		if($single==true) {
			$files=$X->FILE->check_flash_upload($data['form'], $data['name'], $dir, $original_name);
			$F=@array_pop($files);

			if(!empty($F)) {
				$del_file=$X->DB->single(' SELECT '.$data['col'].' FROM '.$data['table'].' WHERE '.$data['cond'].' ');
				@unlink($dir.'/'.$del_file);
				if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
					if(!empty($suff)) @unlink($dir.'/'.$X->FILE->add_suffix($del_file, $suff));
				}


				$files=$X->FILE->flash_upload($data['form'], $data['name'], $dir, $original_name);
				$F=@array_pop($files);

				if(!empty($data['force_filename'])) {
					$force_name=$data['force_filename'].'.'.$X->FILE->get_ext($F['file']);
					rename($dir.'/'.$F['file'], $dir.'/'.$force_name);
					$F['file']=$force_name;
				}

				$X->DB->q(' UPDATE '.$data['table'].' SET '.$data['col'].'="'.$F['file'].'" WHERE '.$data['cond'].' ');
				$R=$F['file'];
			} else {
				$files=$X->FILE->flash_upload($data['form'], $data['name'], $dir, $original_name);
				$F=@array_pop($files);

				if($_POST[$data['name'].'_del']==1) {
					$del_file=$X->DB->single(' SELECT '.$data['col'].' FROM '.$data['table'].' WHERE '.$data['cond'].' ');
					@unlink($dir.'/'.$del_file);
					if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
						if(!empty($suff)) @unlink($dir.'/'.$X->FILE->add_suffix($del_file, $suff));
					}
					$X->DB->q(' UPDATE '.$data['table'].' SET '.$data['col'].'="" WHERE '.$data['cond'].' ');
				}
				if(count($X->FILE->read_dir($dir))==0) $X->UTIL->rmdir_rf($dir);
			}
		} else {
			if(count($_POST[$data['name'].'_del'])>0) foreach($_POST[$data['name'].'_del'] as $ID) {
				$del_file=$X->DB->fast(' SELECT zdjecie FROM '.$data['table'].' WHERE '.$data['cond'].' AND fotograf_zdjecia_id="'.$ID.'" ');
				@unlink($dir.'/'.$del_file);
				if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
					if(!empty($suff)) @unlink($dir.'/'.$X->FILE->add_suffix($del_file, $suff));
				}
				$X->DB->q(' DELETE FROM '.$data['table'].' WHERE '.$data['cond'].' AND fotograf_zdjecia_id="'.$ID.'" ');

			}
			if(count($X->FILE->read_dir($dir))==0) $X->UTIL->rmdir_rf($dir);


			$files=$X->FILE->flash_upload($data['form'], $data['name'], $dir, $original_name);

			if(count($files)>0) foreach($files as $F) {
				if(empty($pozycja)) $pozycja=$X->DB->fast(' SELECT MAX(pozycja) FROM '.$data['table'].' WHERE '.$data['cond'].' ');
				preg_match("/(.*)fotograf_id=\"([0-9]+)\"(.*)/", $data['cond'], $matches);
				$parent_id=$matches[2];
				if(strlen($parent_id)==0) $parent_id=$_GET['id'];

				list($width,$height)=@getimagesize($dir.'/'.$F['file']);
				$orientation=($width>$height ? 'h':'v');
				$aspect=@($width/$height);


				$miasto=$X->DB->fast(' SELECT miasto FROM fotograf_miasta WHERE fotograf_id="'.$_SESSION['user_id'].'" ORDER BY rand() LIMIT 1 ');
				if(empty($miasto)) $miasto=$X->DB->fast(' SELECT miasto FROM fotograf WHERE id="'.$_SESSION['user_id'].'" ');
				$miasto=$X->STR->out($miasto);

				$title=$GLOBALS['PHOTO_TITLE'][round(rand(0,count($GLOBALS['PHOTO_TITLE'])-1))].' - '.$miasto;
				if(empty($title))	$title=$GLOBALS['PHOTO_TITLE'][round(rand(0,count($GLOBALS['PHOTO_TITLE'])-1))].' - '.$miasto;


				$X->DB->q(' INSERT INTO '.$data['table'].' (fotograf_id,zdjecie,title,pozycja'.$data['table_insert_custom_col'].') VALUES ("'.$parent_id.'","'.$F['file'].'","'.$title.'","'.++$pozycja.'"'.$data['table_insert_custom_val'].') ');
				$R[]=$F['file'];
			}


			if(count($_POST[$data['name'].'_pozycja'])>0) foreach($_POST[$data['name'].'_pozycja'] as $ID => $POZ) {
				if(!empty($data['custom_save_col'])) $custom_save_col=', '.$data['custom_save_col'].'="'.$_POST[$data['name'].'_'.$data['custom_save_col']][$ID].'"';
				if(!empty($data['custom_save_col2'])) $custom_save_col2=', '.$data['custom_save_col2'].'="'.$_POST[$data['name'].'_'.$data['custom_save_col2']][$ID].'"';
				if(!empty($data['custom_save_col3'])) $custom_save_col3=', '.$data['custom_save_col3'].'="'.$_POST[$data['name'].'_'.$data['custom_save_col3']][$ID].'"';

				$X->DB->q(' UPDATE '.$data['table'].' SET pozycja="'.++$i.'", title="'.$_POST[$data['name'].'_title'][$ID].'" '.$custom_save_col.$custom_save_col2.$custom_save_col3.' WHERE '.$data['cond'].' AND fotograf_zdjecia_id="'.$ID.'" ');
			}
		}

		$temp_user_dir=CACHE.'/uploadify/'.session_id().'/';
		if(count($X->FILE->read_dir($temp_user_dir))==0) $X->UTIL->rmdir_rf($temp_user_dir);

		return $R;
	}


	function delete_flash_upload($data) {
		global $X;

		$single=(!empty($data['col']) ? true:false);

		if($single==true) {
			$del_file=$X->DB->single(' SELECT '.$data['col'].' FROM '.$data['table'].' WHERE '.$data['cond'].' ');
			@unlink($data['dir'].'/'.$del_file);
			if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
				if(!empty($suff)) @unlink($data['dir'].'/'.$X->FILE->add_suffix($del_file, $suff));
			}
			$X->DB->q(' UPDATE '.$data['table'].' SET '.$data['col'].'="" WHERE '.$data['cond'].' ');
			if(count($X->FILE->read_dir($data['dir']))==0) $X->UTIL->rmdir_rf($data['dir']);
		} else {
			$sql=$X->DB->q(' SELECT id, file FROM '.$data['table'].' WHERE '.$data['cond'].' ORDER BY pozycja ');
			while($dane=$X->DB->fa($sql)) {
				@unlink($data['dir'].'/'.$dane['file']);
				$R[]=$dane['file'];
				if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
					if(!empty($suff)) @unlink($data['dir'].'/'.$X->FILE->add_suffix($dane['file'], $suff));
				}
				$X->DB->q(' DELETE FROM '.$data['table'].' WHERE '.$data['cond'].' AND id="'.$dane['id'].'" ');
			}
			if(count($X->FILE->read_dir($data['dir']))==0) $X->UTIL->rmdir_rf($data['dir']);
		}
		return $R;
	}


	function table_file_single($name, $dir, $file, $title=false, $width=false, $title_w=false, $preview_suff=false, $skip_enlarge=false, $enlarge_suff=false) {
		global $X;
		if(empty($file)) return false;
		if(empty($width)) $width=405;

		return '
			<table id="'.$name.'_db_data" class="sub_data_cont sub_data_cont_single" style="width:'.$width.'px;">
				<tbody>
					<tr>
						<td>
							'.$X->FORM->hidden($name.'_exists[]',$file).'
							'.($preview_suff!==false ? '
								'.($X->FILE->get_ext($dir.$file)=='swf' ? '
									'.$X->FLASH->get('swf_'.time(),$dir.$file,'auto','auto',true).'<br /><br />
								':'
									'.($skip_enlarge!=true ? '<a href="'.$X->FILE->add_suffix($dir.$file,$enlarge_suff).'" target="_blank" class="box_img">':'').'<img src="'.$X->FILE->add_suffix($dir.$file,$preview_suff).'" alt="" />'.($skip_enlarge!=true ? '</a>':'').'
								').'
							':'').'
							'.($title!==false ? $X->FORM->input($name.'_title',(!empty($title_w)? $title_w:295),$title).'<div class="clear"></div>' : '').'
							'.($preview_suff===false ? '<a class="name" href="'.$dir.$file.'" target="_blank">'.$file.'</a>':'').'
							<span class="del">'.$X->FORM->checkbox($name.'_del',1).'<span class="ico b_no" onclick="$(this).prev().click()">Usuń</span></span>
						</td>
					</tr>
				</tbody>
			</table>
		';
//							<span class="size">'.$X->FILE->get_size($dir.$file).'</span>
	}


	function file_div($F) {
		global $X;

		if(!empty($F['img_w'])) $w=$F['img_w'];
		if(!empty($F['img_h'])) $h=$F['img_h']+40;

		if(!empty($F['cont_w'])) $w=$F['cont_w'];
		if(!empty($F['cont_h'])) $h=$F['cont_h'];

		if($F['rotate']==true) {
			$h+=20;
			$rotate='
				<div class="clr"></div>
				<div style="text-align:center; margin-top:4px;"><a href="javascript:void(0)" onclick="image_rotate(this,\'left\',\''.$F['dir'].$F['file'].'\',\''.$X->FILE->add_suffix($F['dir'].$F['file'],$F['preview_suff']).'\')"><img src="images/object-rotate-left.png" alt="" /></a> <span>obróć</span> <a href="javascript:void(0)" onclick="image_rotate(this,\'right\',\''.$F['dir'].$F['file'].'\',\''.$X->FILE->add_suffix($F['dir'].$F['file'],$F['preview_suff']).'\')"><img src="images/object-rotate-right.png" alt="" /></a></div>
			';
			$_SESSION['allow_image_rotate']=true;
		}

		return '
			<div style="width:'.$w.'px; height:'.$h.'px;">
				'.$X->FORM->hidden($F['name'].'_pozycja['.$F['id'].']',$F['pozycja']).'
				'.$X->FORM->hidden($F['name'].'_exists['.$F['id'].']',$F['file']).'
				'.($F['preview_suff']!==false ? '
					<div class="img" style="height:'.($F['img_h']).'px">
						<div style="width:'.($F['img_w']).'px">
							<a href="'.$F['dir'].$F['file'].'" target="_blank" class="box_img"><img src="'.$X->FILE->add_suffix($F['dir'].$F['file'],$F['preview_suff']).'" alt="" /></a>
						</div>
					</div>
				':'').'
				'.(isset($F['title']) ? '
					<div class="input_small_cont"><input type="text" id="'.$F['name'].'_title['.$F['id'].']" name="'.$F['name'].'_title['.$F['id'].']" class="form-control input input_small" style="'.(!empty($F['title_w'])? $F['title_w']:275).'px;" value="'.$F['title'].'"'.(!empty($F['placeholder']) ? ' placeholder="'.$F['placeholder'].'"':'').' /></div>
				':'
				').'
				<span class="del">Usuń '.$X->FORM->checkbox($F['name'].'_del[]',$F['id'],false,false,$F['name'].'_del_'.$F['id']).'<span class="ico b_no" onclick="$(this).prev().click()"></span></span>
				<span class="drag ico b_move">Przenieś</span>
				'.$rotate.'
			</div>
		';
//					<div style="margin-bottom:10px">'.$F['ori_file'].'</div>
	}


	function file_div2($F) {
		global $X;

		return '
			<div>
				'.$X->FORM->hidden($F['name'].'_pozycja['.$F['id'].']',$F['pozycja']).'
				'.$X->FORM->hidden($F['name'].'_exists['.$F['id'].']',$F['file']).'
				'.(isset($F['title']) ? $X->FORM->input($F['name'].'_title['.$F['id'].']',(!empty($F['title_w'])? $F['title_w']:275),$F['title'],false,false,'input input_small').'<br />':'').'
				<span class="drag ico b_move">Przenieś</span>
				<a href="'.$F['dir'].$F['file'].'" class="title" target="_blank" '.($F['skip_tip']!=true ? $X->FORM->tip('<span class="gray">Dodano: </span><span>'.date('Y-m-d H:i:s',@filemtime($F['dir'].$F['file'])).'</span>',true):'').'>'.$F['ori_file'].'</a>
				<span class="del">Usuń '.$X->FORM->checkbox($F['name'].'_del[]',$F['id'],false,false,$F['name'].'_del_'.$F['id']).'<span class="ico b_no" onclick="$(this).prev().click()"></span></span>
				'.$rotate.'
			</div>
		';
//					<div style="margin-bottom:10px">'.$F['ori_file'].'</div>
	}


	function sort_file_div($name, $data, $use_title=false) {
		global $X;
		if(empty($data)) return false;

		$X->JS[]=JS.'/jquery.sort/jquery.dragsort.js';

		return '
			<div id="'.$name.'_db_data" class="sub_data_cont">'.$data.'</div>
			<script type="text/javascript">$("#'.$name.'_db_data").dragsort({dragSelector:"span.drag"});</script>
		';
	}


	//////////////

	function del($post, $dir) {
		if(!empty($_POST[$post])) {
			@unlink($dir.$_POST[$post]);
			return true;
		}
	}


	function add_suffix($file, $sufix=false) {
		global $X;
		$ext=$X->FILE->get_ext($file);
		return substr($file, 0, -strlen($ext)-1).$sufix.'.'.$ext;
	}


	function get_ext($file_name) {
		return trim(strtolower(array_pop(@explode('.',$file_name))));
	}


	function get_size($file_name, $bytes=false) {
		if(!file_exists($file_name)) return '-1 MB';
		$size=filesize($file_name);
		if($bytes==true) return $size;

		if($size>=1024*1024*1024) return round($size/(1024*1024*1024), 2).' GB';
		if($size>=1024*1024) return round($size/(1024*1024), 1).' MB';
		return round($size/1024, 1).' KB';
	}


	function get_size2($file_name, $bytes=false) {
		if(!file_exists($file_name)) return '-1 MB';
		$size=filesize($file_name);
		if($bytes==true) return $size;

		if($size>=1024*1024*1024) return round($size/(1024*1024*1024), 2).' GB';
		return round($size/(1024*1024), 2).' MB';
	}


	function read_dir($dir, $add_path=false) {
		if(!is_dir($dir)) return false;
		$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST);//CHILD_FIRST
		foreach($files as $file) {
			if($file->getFilename()!='.' && $file->getFilename()!='..') $R[] = str_replace('//','/',($add_path==true ? $dir.'/':'').$file->getFilename());
		}
		@natcasesort($R);
		return $R;
	}



}
$this->FILE = new X_FILE();
$this->FILE->DIR = LIBS.'/_file';
$this->FILE->PATH = LIBS_PATH.'/_file';

class X_PACK {


	function zip($archiwum, $sciezka, $exclude=false, $remove_all_path=false) {
		if(!is_dir($sciezka) && !is_file($sciezka)) return false;
		if(!is_array($exclude)) $exclude=array();

		require_once(LIBS_PATH.'/system/pear.php');
		require_once($this->PATH.'/zip.lib.php');
		$files=$this->zip_file_list($sciezka, $archiwum, $exclude);

		$params=array(
//			'add_path'=>'',
			'remove_path' => str_replace('\\','/',ROOT_PATH),
			'remove_all_path' => $remove_all_path,
//			'no_compression'=>true,
		);

		$zipfile=new Archive_Zip($archiwum);
		$zipfile->create($files, $params, $archiwum);
		if(@file_exists($archiwum) && filesize($archiwum)>0) {
			return true;
		} else {
			@unlink($archiwum);
		}
	}


	function zip_file_list($dirname, $archive, $exclude) {
		if(!is_dir($dirname) && !is_file($dirname)) return false;
		$dscan=array(realpath($dirname));
		$darr=array();
		while(!empty($dscan)) {
			$dcur=array_pop($dscan);
			$darr[]=$dcur;

			$skipped=false;
			if(count($exclude)>0) foreach($exclude as $ex_dir) { if(stristr($darr[$i], $ex_dir)) { $skipped=true; break; } }
			if(is_file($dcur) && $skipped==false) {
				if($dcur!=$archive) $lista[]=$dcur;
			} else {
				if($d=opendir($dcur)) {
					while($f=readdir($d)) {
						if($f=='.' || $f=='..') continue;
						$f=$dcur.'/'.$f;
						if(is_dir($f)) {
							$dscan[]=$f; 
						} else {
							$skipped=false;
							if(count($exclude)>0) foreach($exclude as $ex_dir) { if(stristr($f, $ex_dir)) { $skipped=true; break; } }
							if($skipped==false) $lista[]=$f;
						}
					}
					closedir($d);
				}
			}
		}

		for($i=count($darr)-1; $i>=1; $i--) {
			$skipped=false;
			if(count($exclude)>0) foreach($exclude as $ex_dir) { if(stristr($darr[$i], $ex_dir)) { $skipped=true; break; } }
			if($skipped==false) $lista[]=$darr[$i];
		}

		return $lista;
	}


	function unzip($archiwum, $cel=false, $remove_all_path=false) {
		if(!file_exists($archiwum) || filesize($archiwum)==0) return false;
		require_once(LIBS.'/system/pear.php');
		require_once($this->DIR.'/zip.lib.php');

		if(!empty($cel)) {
			if(!is_dir($cel)) mkdir($cel);
		} else {
			$cel = dirname($archiwum);
		}

		$params=array(
			'add_path' => $cel,
			'remove_all_path' => $remove_all_path
		);

		$zipfile=new Archive_Zip($archiwum);
		$zipfile->extract($params);
	}




	function init() {}


	function tar($archiwum, $sciezka, $exclude=false, $custom_root_path=false) {
		if(!is_dir($sciezka) && !is_file($sciezka)) return false;
		if(!is_array($exclude)) $exclude=array();

		require_once(LIBS_PATH.'/system/pear.php');
		require_once($this->PATH.'/tar.class.php');
		
		$tar = new Archive_Tar($archiwum);
		$files=$this->tar_file_list($sciezka, $archiwum, $exclude);
		$tar->add($files, (!empty($custom_root_path) ? $custom_root_path : ROOT_PATH));
	
		if(@file_exists($archiwum) && filesize($archiwum)>0) return true;
	}

	
	function untar($archiwum, $cel=false, $remove_all_path=false, $remove_path=false) {
		global $X;
		if(!file_exists($archiwum) || filesize($archiwum)==0) return false;
		require_once(LIBS_PATH.'/system/pear.php');
		require_once($this->PATH.'/tar.class.php');

		$tar=new Archive_Tar($archiwum);
		if($remove_all_path==true) $rand_temp='/'.$X->STR->random(8).'/';
		$tar->extract($cel.$rand_temp, $remove_path);

		if($remove_all_path==true) $this->flat_extract($cel, $rand_temp);
		return true;
	}


	function tar_file_list($dirname, $archive, $exclude) {
		if(!is_dir($dirname) && !is_file($dirname)) return false;
		$dscan=array(realpath($dirname));
		$darr=array();
		while(!empty($dscan)) {
			$dcur=array_pop($dscan);
			$darr[]=$dcur;

			$skipped=false;
			if(count($exclude)>0) foreach($exclude as $ex_dir) {
				if(stristr($darr[$i], $ex_dir) || stristr($darr[$i].'/', $ex_dir)) { $skipped=true; break; }
			}
			if(is_file($dcur) && $skipped==false) {
				if($dcur!=$archive) $lista[]=$dcur;
			} else {
				if($d=opendir($dcur)) {
					while($f=readdir($d)) {
						if($f=='.' || $f=='..') continue;
						$f=$dcur.'/'.$f;
						if(is_dir($f)) {
							$dscan[]=$f; 
						} else {
							$skipped=false;
							if(count($exclude)>0) foreach($exclude as $ex_dir) {
								if(stristr($f, $ex_dir) || stristr($f.'/', $ex_dir)) { $skipped=true; break; }
							}
							if($skipped==false) $lista[]=$f;
						}
					}
					closedir($d);
				}
			}
		}
		for($i=count($darr)-1; $i>=1; $i--) {
			$skipped=false;
			if(count($exclude)>0) foreach($exclude as $ex_dir) {
				if(stristr($darr[$i], $ex_dir) || stristr($darr[$i].'/', $ex_dir)) { $skipped=true; break; }
			}
			if($skipped==false) $lista[]=$darr[$i];
		}

		return $lista;
	}


	function flat_extract($cel, $temp) {
		global $X;

		$dirname=$cel.$temp;		
		if(!is_dir($dirname) && !is_file($dirname)) return false;
		$dscan=array(realpath($dirname));
		$darr=array();
		while(!empty($dscan)) {
			$dcur=array_pop($dscan);
			$darr[]=$dcur;

			$skipped=false;
			if(count($exclude)>0) foreach($exclude as $ex_dir) {
				if(stristr($darr[$i], $ex_dir) || stristr($darr[$i].'/', $ex_dir)) { $skipped=true; break; }
			}
			if(is_file($dcur) && $skipped==false) {
				if($dcur!=$archive) $lista[]=$dcur;
			} else {
				if($d=opendir($dcur)) {
					while($f=readdir($d)) {
						if($f=='.' || $f=='..') continue;
						$f=$dcur.'/'.$f;
						if(is_dir($f)) {
							$dscan[]=$f; 
						} else {
							$skipped=false;
							if(count($exclude)>0) foreach($exclude as $ex_dir) {
								if(stristr($f, $ex_dir) || stristr($f.'/', $ex_dir)) { $skipped=true; break; }
							}
							if($skipped==false) $lista[]=$f;
						}
					}
					closedir($d);
				}
			}
		}

		foreach($lista as $file) rename($file, $cel.'/'.basename($file));
		$X->UTIL->rmdir_rf($cel.$temp);
	}



}
$this->PACK = new X_PACK();
$this->PACK->DIR = LIBS.'/_pack';
$this->PACK->PATH = LIBS_PATH.'/_pack';

class X_ADMIN {


	function init() {
		define('HOVER',' onmouseover="row_hover(this)"');
	}


	function listbox($OBJ, $table, $data=false, $split=false) {
		global $X;

		if(!empty($split['navi']) && empty($table['bottom_center'])) $table['bottom_center']=$split['navi'];
		if(!empty($split['navi']) && !empty($split['go'])) $table['bottom_left'].='<div style="position:absolute; right:20px;">'.$split['go'].'</div>';

		if(!empty($table['bottom_left'])) $bottom.='<div class="fleft">'.$table['bottom_left'].'</div>';
		if(!empty($table['bottom_center'])) $bottom.='<div class="center">'.$table['bottom_center'].'</div>';
		if(!empty($table['bottom_right'])) $bottom.='<div class="fright">'.$table['bottom_right'].'</div>';

		if(count($X->PATH)>1) $table['top_left']=$X->FORM->button('Do góry',$X->URL->get('parent_id='.($X->PATH[count($X->PATH)-2]!==0 ? $X->PATH[count($X->PATH)-2]:'')),false,'button button_big').'&nbsp;&nbsp;'.$table['top_left'];


		if($OBJ->MULTILANG==true) {
			if(count($X->LANGS)>1) {
				foreach($X->LANGS as $L => $T) $lang_opts.='<option value="'.$L.'"'.(LANG==$L ? ' selected="selected"':'').'>'.$T.'</option>';
				$lang='<img src="'.ROOT.'/admin/images/flags/'.strtolower(LANG).'.gif" alt="" style="padding:1px; border:2px solid #fff;" />&nbsp;&nbsp;'.$X->FORM->select('lang',$lang_opts,false,false,'go(\''.$X->URL->get('lang').'&lang=\'+this.value)');
			}
		}


		if($split['split_by']>0) {
			$navi='
				<form action="" method="get" onsubmit="if(this.split_by.value==\'\' || isNaN(this.split_by.value) || this.split_by.value=='.(int)$_GET['split_by'].') { this.split_by.focus(); return false;}">
					'.$X->FORM->vars2hidden($_GET, 'page&split_by').'
					<span style="margin-left:20px;">Ilość: </span><input type="text" name="split_by" class="input" value="'.$split['split_by'].'" style="width:32px; text-align:center" maxlength="4" autocomplete="off" />
					'.$X->FORM->submit_link('<span class="ico w_yes"></span>',false,'button button_gfx_small').'
				</form>
			';
			if(!empty($table['navi_right_location'])) {
				$table[$table['navi_right_location']].=$navi;
			} else {
				$table['navi_right']=$table['navi_right'].$navi;
			}
		}


		if(empty($data)) {
			$empty_table=true;
			$data=$X->ADMIN->empty_table('brak pozycji'.($_GET['page']>1 ? ' na tej stronie':''));
		} else {
			$data=str_replace('<tr','<tr'.HOVER, $data);
		}


		if(!empty($table['sortable_table_id']) && $table['allow_sort']==true) {
			$X->JS[]=JS.'/jquery.sort/jquery.tablesort.js';
			$sort_js='<script type="text/javascript">table_sort("'.$table['sortable_table_id'].'","'.$_GET['module'].'","'.(count($X->PATH)>0 ? (int)$_GET['parent_id']:-1).'");</script>';
		}


		return '
			<div class="mainbox_border">
				<div class="mainbox">
					<div class="mainbox_header">
						<div class="mainbox_gear"></div>
						<div class="mainbox_header_navi"><h3>'.@implode(' <span class="sep">&raquo;</span> ',$X->NAVI).'</h3></div>
						<div class="mainbox_header_buttons fright">'.$lang.$table['navi_right'].'</div>
						<div class="clear"></div>
					</div>

					<div class="mainbox_content_table_wide">
						<div style="float:left; width:1px; height:32px; font-size:0px;"></div>
						<div class="mainbox_table_buttons fleft">'.$table['top_left'].'</div>
						<div class="mainbox_table_buttons fright">'.$table['top_right'].'</div>
						<div class="clr" style="padding-bottom:7px;"></div>

						<table'.(!empty($table['sortable_table_id']) ? ' id="table_'.$table['sortable_table_id'].'"':'').' class="listing">
						'.($empty_table!=true ? '
							<thead>
								<tr>
									'.$table['head'].'
								</tr>
							</thead>
						':'').'
						<tbody>
							'.$data.'
						</tbody>
						<tfoot>
							<tr>
								<td colspan="20"'.($empty_table==true ? ' class="empty"':'').'>
								<div class="tfoot'.(empty($bottom) ? ' tfoot_empty':'').'">
									'.$bottom.'
									<div class="clear"></div>
								</div>
								</td>
							</tr>
						</tfoot>
						</table>
					</div>
					'.$sort_js.'
				</div>
			</div>
		';
	}


	function tree_path(&$OBJ, $parent_col=false, $title_col='title', $cond=false) {
		global $X;
		if(empty($parent_col)) $parent_col='parent_id';
		if(empty($title_col)) $title_col='title';

		$X->PATH[]=0;
		$X->NAVI[count($X->NAVI)-1]='<a href="'.$X->URL->get('action&page&parent_id='.$starting_parent).'">'.$X->NAVI[count($X->NAVI)-1].'</a>'; //override2link

		if($X->DB->fast(' SELECT id FROM '.$OBJ->TABLE.' WHERE id="'.$_GET[$parent_col].'" '.$cond.' ')!=$_GET[$parent_col]) $X->URL->go2('parent_id='.$X->PATH[$OBJ->PARENT_DEPTH-1]);

		if(!empty($_GET[$parent_col])) $this->tree_path_navi($OBJ->TABLE, $parent_col, $title_col, $_GET[$parent_col], $cond);
		if($OBJ->PARENT_DEPTH>0 && count($X->PATH)>$OBJ->PARENT_DEPTH) $X->URL->go2('parent_id='.$X->PATH[$OBJ->PARENT_DEPTH-1]);
		if(!@in_array($_GET[$parent_col],$X->PATH)) $X->URL->go2('parent_id='.$X->PATH[$OBJ->PARENT_DEPTH-1]);
	}


	function tree_path_navi($table, $parent_col, $title_col, $starting_parent, $cond) {
		global $X;

		$dane=$X->DB->fast(' SELECT '.$parent_col.', '.$title_col.' FROM '.$table.' WHERE id="'.$starting_parent.'" '.$cond.' ');
		if(!empty($dane[$parent_col])>0) $this->tree_path_navi($table, $parent_col, $title_col, $dane[$parent_col], $cond);
		if(!empty($dane[$title_col])) $X->NAVI[]='<a href="'.$X->URL->get('action&page&parent_id='.$starting_parent).'">'.$X->STR->outt($dane[$title_col]).'</a>';
		$X->PATH[]=$starting_parent;
	}


	function sortable_col(&$table, $split, $tag) {
		global $X;

		if(empty($table['sortable_table_id'])) return false;
		if($tag=='th') {
			if($_GET['order_by']=='pozycja' && $_GET['order_dir']=='asc' && empty($split['navi']) && empty($_GET['filter'])) $table['allow_sort']=true;

			if($table['allow_sort']!=true && empty($table['table_sort_reason']) && ($_GET['order_by']!='pozycja' || $_GET['order_dir']!='asc')) $table['table_sort_reason']='Aby zmienić kolejność, lista musi być posortwana po tej kolumnie';
			if($table['allow_sort']!=true && empty($table['table_sort_reason']) && (!empty($split['navi']))) $table['table_sort_reason']='Aby zmienić kolejność, wszystkie rekordy muszą być na jednej stronie';
			if($table['allow_sort']!=true && empty($table['table_sort_reason']) && (!empty($_GET['filter']))) $table['table_sort_reason']='Nie można sortować podczas filtrowania';
		}


		if(!empty($table['sortable_table_id']) && $table['allow_sort']==true) {
			return '<'.$tag.' class="drag2sort"><i></i></'.$tag.'>';
		} else {
			if($tag=='th') {
				return '<'.$tag.' class="drag2sort"><a href="'.$X->URL->get('order_by=pozycja&order_dir=asc').'"><span class="ico b_warn" '.$X->FORM->tip($table['table_sort_reason'],true,-8).'></span></a></'.$tag.'>';
			} else {
				return '<'.$tag.' class="drag2sort_dis"><i></i></'.$tag.'>';
			}
		}
	}


	function head_col($title, $col=false, $width=false, $class=false, $tip=false, $colspan=false) {
		global $X;

		if($col==$_GET['order_by']) {
			if($_GET['order_dir']=='asc') {
				$order_dir='order_dir=desc';
				$arrow='<span class="ico b_up3 sort_arrow"></span>';
			} else {
				$order_dir='order_dir=asc';
				$arrow='<span class="ico b_down3 sort_arrow"></span>';
			}

			$class=trim($class.' sel');
		} else {
			$order_dir='order_by='.$col.'&order_dir=asc';
		}

		if(empty($col)) {
			$label=$title.$arrow;
		} else {
			$label='<a href="'.$X->URL->get($order_dir).'">'.$title.'</a>'.$arrow;
		}

		return '<th'.(!empty($class) ? ' class="'.$class.'"':'').(!empty($width) ? ' width="'.$width.'"':'').(!empty($colspan) ? ' colspan="'.$colspan.'"':'').(!empty($tip) ? ' '.$X->FORM->tip($tip,true):'').'>'.$label.'</th>';
	}


	function batch_col($tag, $param=false) {
		if($tag=='th') {
			if(empty($param)) $param=16;
			return '<th width="'.$param.'" class="center"><input type="checkbox" class="checkbox del_on_list_main" id="del_on_list_sel_all" /></th>';
		} else {
			return '<td class="center"><input type="checkbox" class="del_on_list" name="del[]" value="'.$param.'" /></td>';
		}
	}



	function go_parent($link, $title, $subs=0, $parent_depth=0, $disabled=false, $special=false) {
		global $X;

		if($parent_depth==0 || count($X->PATH)>=$parent_depth) {
			return $title;
		} else {
			if($disabled==false) {
				return '<a class="exp_link'.($special==true ? ' special':'').'" href="'.$X->URL->get($link).'"><span'.($subs==0 ? ' class="empty"':'').'></span>'.$title.'</a>';
			} else {
				return '<span class="exp_link'.($special==true ? ' special':'').'"><span class="'.($special==true ? 'special':'disabled').'"></span>'.$title.'</span>';
			}
		}
	}


	function text_filter(&$OBJ, $col, $label, $operator=false) {
		$_GET['filter']=trim($_GET['filter']);
		if(empty($operator)) $operator='%LIKE%';

		switch($operator) {
			case '=':
			case '>':
			case '>=':
			case '<':
			case '<=':		$OBJ->FILTER_FIELDS[] = array('text', $col.$operator.'"'.str_replace('%','',$_GET['filter']).'"'); 	break;
			case '%LIKE':	$OBJ->FILTER_FIELDS[] = array('text', $col.' LIKE "%'.str_replace('%','',$_GET['filter']).'"'); 		break;
			case 'LIKE%':	$OBJ->FILTER_FIELDS[] = array('text', $col.' LIKE "'.str_replace('%','',$_GET['filter']).'%"'); 		break;
			case '%LIKE%':	$OBJ->FILTER_FIELDS[] = array('text', $col.' LIKE "%'.str_replace('%','',$_GET['filter']).'%"');		break;
		}
		$OBJ->FILTER_LABEL[]=$label;
		$OBJ->FILTER_SKIP_GET_VAR[]='filter_'.$col;
	}


	function checkbox_filter(&$OBJ, $col, $label, $value, $tip=false, $skip_OC=false) {
		global $X;
		$_GET['filter']=trim($_GET['filter']);
		if($OBJ->FILTER_CURRENT_LINE==0) $OBJ->FILTER_CURRENT_LINE=1;

		if($_GET['filter_'.$col]==$value) $OBJ->FILTER_FIELDS[] = array('checkbox', $col.'="'.$value.'"');
		$OBJ->FILTER_SKIP_GET_VAR[]='filter_'.$col;
		$OBJ->FILTER_ADDITIONAL_CONTROLS[$OBJ->FILTER_CURRENT_LINE].='<div style="display:inline-block; margin:0px 0px 0px 17px" '.$X->FORM->tip($tip,true).'><label for="filter_'.$col.'">'.$X->STR->out($label).'</label><input type="checkbox" class="checkbox" value="'.$value.'" id="filter_'.$col.'" name="filter_'.$col.'" '.(!empty($_GET['filter_'.$col]) ? ' checked="checked"':'').($skip_OC!=true ? ' onchange="$(this).closest(\'form\').submit()"':'').' /></div>';
	}


	function select_filter(&$OBJ, $col, $label, $value, $tip=false, $skip_OC=false, $width=false, $custom_cond=false) {
		global $X;
		$_GET['filter']=trim($_GET['filter']);
		if($OBJ->FILTER_CURRENT_LINE==0) $OBJ->FILTER_CURRENT_LINE=1;

		$OBJ->FILTER_SKIP_GET_VAR[]='filter_'.$col;
		if(count($value)>0) foreach($value as $V => $L) {
			$sel=(strlen($_GET['filter_'.$col])==0 ? $_GET['filter_'.$col]===$V : $_GET['filter_'.$col]==$V);
			$options.='<option value="'.$V.'"'.($sel==true ? ' selected="selected"':'').'>'.$L.'</option>';
			if($sel==true && strlen($_GET['filter_'.$col])>0) {
				if(!empty($custom_cond)) {
//					$OBJ->FILTER_FIELDS[] = array('select', $col.'="'.$V.'"');
					$OBJ->FILTER_FIELDS[] = array('select', $custom_cond);
				} else {
					$OBJ->FILTER_FIELDS[] = array('select', $col.'="'.$V.'"');
				}
			}
		}
		$OBJ->FILTER_ADDITIONAL_CONTROLS[$OBJ->FILTER_CURRENT_LINE].='<div style="display:inline-block; margin:0px 0px 0px 17px" '.$X->FORM->tip($tip,true).'><label for="filter_'.$col.'">'.$X->STR->out($label).'&nbsp;&nbsp;</label><select name="filter_'.$col.'" id="filter_'.$col.'"'.(!empty($width) ? ' style="width:'.$width.'px"':'').($skip_OC!=true ? ' onchange="$(this).closest(\'form\').submit()"':'').'>'.$options.'</select></div>';
	}


	function straight_select_filter(&$OBJ, $col, $label, $options, $tip=false, $skip_OC=false, $width=false) {
		global $X;
		$_GET['filter']=trim($_GET['filter']);
		if($OBJ->FILTER_CURRENT_LINE==0) $OBJ->FILTER_CURRENT_LINE=1;

		$OBJ->FILTER_SKIP_GET_VAR[]='filter_'.$col;
		$options.='<option value="'.$V.'"'.($sel==true ? ' selected="selected"':'').'>'.$L.'</option>';
		if(strlen($_GET['filter_'.$col])>0) $OBJ->FILTER_FIELDS[] = array('select', $col.'="'.$_GET['filter_'.$col].'"');

		$OBJ->FILTER_ADDITIONAL_CONTROLS[$OBJ->FILTER_CURRENT_LINE].='<div style="display:inline-block; margin:0px 0px 0px 17px" '.$X->FORM->tip($tip,true).'><label for="filter_'.$col.'">'.$X->STR->out($label).'&nbsp;&nbsp;</label><select name="filter_'.$col.'" id="filter_'.$col.'"'.(!empty($width) ? ' style="width:'.$width.'px"':'').($skip_OC!=true ? ' onchange="$(this).closest(\'form\').submit()"':'').'>'.$options.'</select></div>';
	}


	function date_filter(&$OBJ, $col, $label, $operator=false, $tip=false, $custom_col=false) {
		global $X;
		$_GET['filter']=trim($_GET['filter']);
		if($OBJ->FILTER_CURRENT_LINE==0) $OBJ->FILTER_CURRENT_LINE=1;
		if(empty($operator)) $operator='=';

		if(strlen($_GET['filter_'.$col])>0) {
			$S=str_replace('%','',$_GET['filter_'.$col]);
			$sql_col=(!empty($custom_col) ? $custom_col : $col);

			switch($operator) {
				case '=':
				case '>':
				case '>=':
				case '<':
				case '<=':		$OBJ->FILTER_FIELDS[] = array('date', $sql_col.$operator.'"'.$S.'"'); 	break;
				case '%LIKE':	$OBJ->FILTER_FIELDS[] = array('date', $sql_col.' LIKE "%'.$S.'"'); 		break;
				case 'LIKE%':	$OBJ->FILTER_FIELDS[] = array('date', $sql_col.' LIKE "'.$S.'%"'); 		break;
				case '%LIKE%':	$OBJ->FILTER_FIELDS[] = array('date', $sql_col.' LIKE "%'.$S.'%"');		break;
			}
		}
		$OBJ->FILTER_SKIP_GET_VAR[]='filter_'.$col;
		$OBJ->FILTER_ADDITIONAL_CONTROLS[$OBJ->FILTER_CURRENT_LINE].='<div style="display:inline-block; margin:0px 0px 0px 17px" '.$X->FORM->tip($tip,true).'><label for="filter_'.$col.'">'.$X->STR->out($label).'&nbsp;</label>'.$X->FORM->calendar('filter_'.$col, $_GET['filter_'.$col], 'Y-m-d', false, false, false, 68).'</div>';
	}


	function dual_date_filter(&$OBJ, $col, $label, $operator=false, $tip=false) {
		global $X;
		$_GET['filter']=trim($_GET['filter']);
		if($OBJ->FILTER_CURRENT_LINE==0) $OBJ->FILTER_CURRENT_LINE=1;
		if(empty($operator)) $operator=array('>=','<=');

		if(strlen($_GET['filter_'.$col])>0) {
			$S=str_replace('%','',$_GET['filter_'.$col]);
			switch($operator[0]) {
				case '=':
				case '>':
				case '>=':
				case '<':
				case '<=':		$OBJ->FILTER_FIELDS[] = array('date', $col.$operator[0].'"'.$S.'"'); break;
				case '%LIKE':	$OBJ->FILTER_FIELDS[] = array('date', $col.' LIKE "%'.$S.'"'); 		break;
				case 'LIKE%':	$OBJ->FILTER_FIELDS[] = array('date', $col.' LIKE "'.$S.'%"'); 		break;
				case '%LIKE%':	$OBJ->FILTER_FIELDS[] = array('date', $col.' LIKE "%'.$S.'%"');		break;
			}
		}

		if(strlen($_GET['filter_'.$col.'_'.$col])>0) {
			$S=str_replace('%','',$_GET['filter_'.$col.'_'.$col]);
			switch($operator[1]) {
				case '=':
				case '>':
				case '>=':
				case '<':
				case '<=':		$OBJ->FILTER_FIELDS[] = array('date', $col.$operator[1].'"'.$S.'"'); break;
				case '%LIKE':	$OBJ->FILTER_FIELDS[] = array('date', $col.' LIKE "%'.$S.'"'); 		break;
				case 'LIKE%':	$OBJ->FILTER_FIELDS[] = array('date', $col.' LIKE "'.$S.'%"'); 		break;
				case '%LIKE%':	$OBJ->FILTER_FIELDS[] = array('date', $col.' LIKE "%'.$S.'%"');		break;
			}
		}
		$OBJ->FILTER_SKIP_GET_VAR[]='filter_'.$col;
		$OBJ->FILTER_ADDITIONAL_CONTROLS[$OBJ->FILTER_CURRENT_LINE].='<div style="display:inline-block; margin:0px 0px 0px 17px" '.$X->FORM->tip($tip,true).'><label for="filter_'.$col.'">'.$X->STR->out($label).'&nbsp;</label>'.$X->FORM->calendar('filter_'.$col, $_GET['filter_'.$col], 'Y-m-d', false, false, false, 68).'&nbsp;-'.$X->FORM->calendar('filter_'.$col.'_'.$col, $_GET['filter_'.$col.'_'.$col], 'Y-m-d', false, false, false, 68).'</div>';
	}


	function dual_filter(&$OBJ, $col, $label, $operator=false, $tip=false, $input_width=40) {
		global $X;
		$_GET['filter']=trim($_GET['filter']);
		if($OBJ->FILTER_CURRENT_LINE==0) $OBJ->FILTER_CURRENT_LINE=1;
		if(empty($operator)) $operator=array('>=','<=');

		if(strlen($_GET['filter_'.$col])>0) {
			$S=str_replace('%','',$_GET['filter_'.$col]);
			switch($operator[0]) {
				case '=':
				case '>':
				case '>=':
				case '<':
				case '<=':		$OBJ->FILTER_FIELDS[] = array('number', $col.$operator[0].'"'.$S.'"'); break;
				case '%LIKE':	$OBJ->FILTER_FIELDS[] = array('number', $col.' LIKE "%'.$S.'"'); 		break;
				case 'LIKE%':	$OBJ->FILTER_FIELDS[] = array('number', $col.' LIKE "'.$S.'%"'); 		break;
				case '%LIKE%':	$OBJ->FILTER_FIELDS[] = array('date', $col.' LIKE "%'.$S.'%"');		break;
			}
		}

		if(strlen($_GET['filter_'.$col.'_'.$col])>0) {
			$S=str_replace('%','',$_GET['filter_'.$col.'_'.$col]);
			switch($operator[1]) {
				case '=':
				case '>':
				case '>=':
				case '<':
				case '<=':		$OBJ->FILTER_FIELDS[] = array('number', $col.$operator[1].'"'.$S.'"'); break;
				case '%LIKE':	$OBJ->FILTER_FIELDS[] = array('number', $col.' LIKE "%'.$S.'"'); 		break;
				case 'LIKE%':	$OBJ->FILTER_FIELDS[] = array('number', $col.' LIKE "'.$S.'%"'); 		break;
				case '%LIKE%':	$OBJ->FILTER_FIELDS[] = array('number', $col.' LIKE "%'.$S.'%"');		break;
			}
		}
		$OBJ->FILTER_SKIP_GET_VAR[]='filter_'.$col;
		$OBJ->FILTER_ADDITIONAL_CONTROLS[$OBJ->FILTER_CURRENT_LINE].='<div style="display:inline-block; margin:0px 0px 0px 17px" '.$X->FORM->tip($tip,true).'><label for="filter_'.$col.'">'.$X->STR->out($label).'&nbsp;</label>'.$X->FORM->input_center('filter_'.$col, $input_width, $_GET['filter_'.$col]).'&nbsp;-'.$X->FORM->input_center('filter_'.$col.'_'.$col, $input_width, $_GET['filter_'.$col.'_'.$col]).'</div>';
	}


	function custom_filter(&$OBJ, $cond, $label) {
		$_GET['filter']=trim($_GET['filter']);
		$OBJ->FILTER_FIELDS[] = array('text', $cond);
		$OBJ->FILTER_LABEL[]=$label;
	}


	function filter_change_line(&$OBJ, $line) {
		$OBJ->FILTER_CURRENT_LINE=$line;
	}


	function filter_html(&$OBJ, $html) {
		global $X;
		if($OBJ->FILTER_CURRENT_LINE==0) $OBJ->FILTER_CURRENT_LINE=1;
		$OBJ->FILTER_ADDITIONAL_CONTROLS[$OBJ->FILTER_CURRENT_LINE].='<div style="display:inline-block; margin:0px 0px 0px 17px">'.$html.'</div>';
	}


	function filter_form($OBJ, &$table, $width=250, $submit_at_end=false, $extra=false) {
		global $X;
		$_GET['filter']=trim($_GET['filter']);

		if(count($OBJ->FILTER_LABEL)>0) $fields=@implode(',&nbsp; ', $OBJ->FILTER_LABEL);

		if(count($OBJ->FILTER_FIELDS)>0) {
			foreach($OBJ->FILTER_FIELDS as $F) {
				$type=$F[0];
				$f=$F[1];

				if($type=='text') {
					$text_filter_enabled=true;
					if(!empty($_GET['filter'])) $conds['text'].=' OR '.$f;
				}
				if($type=='checkbox') $conds['checkbox'].=' AND '.$f;
				if($type=='select') $conds['select'].=' AND '.$f;
				if($type=='date') $conds['date'].=' AND '.$f;
				if($type=='number') $conds['number'].=' AND '.$f;
			}

			if(!empty($conds['text'])) $OBJ->FILTER_SQL.=' AND (0 '.$conds['text'].')';
			if(!empty($conds['checkbox'])) $OBJ->FILTER_SQL.=$conds['checkbox'];
			if(!empty($conds['select'])) $OBJ->FILTER_SQL.=$conds['select'];
			if(!empty($conds['date'])) $OBJ->FILTER_SQL.=$conds['date'];
			if(!empty($conds['number'])) $OBJ->FILTER_SQL.=$conds['number'];
		}

		$OBJ->FILTER='
			<form action="index.php" method="get">
				'.$X->FORM->vars2hidden($_GET, 'strona&filter&parent_id&'.@implode('&',$OBJ->FILTER_SKIP_GET_VAR)).'
				'.($text_filter_enabled==true ? '
					<span class="ico b_search"></span>&nbsp;&nbsp;<b style="display:inline-block; height:26px;" '.$X->FORM->tip($fields,true).'>'.$X->FORM->input('filter',$width,$X->STR->get_var('filter')).'</b>'.($submit_at_end==false ? '&nbsp;'.$X->FORM->submit('Filtruj',false,'button button_small2'):'').'&nbsp;
				':'').'
				'.$extra.$OBJ->FILTER_ADDITIONAL_CONTROLS[1].($submit_at_end==true ? '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$X->FORM->submit('Filtruj',false,'button button_small2'):'').'
				'.(!empty($OBJ->FILTER_ADDITIONAL_CONTROLS[2]) ? '<div class="clr"></div><div style="padding-top:8px; margin-left:-17px;">'.$OBJ->FILTER_ADDITIONAL_CONTROLS[2].'</div>':'').'
				'.(!empty($OBJ->FILTER_ADDITIONAL_CONTROLS[3]) ? '<div class="clr"></div><div style="padding-top:8px; margin-left:-17px;">'.$OBJ->FILTER_ADDITIONAL_CONTROLS[3].'</div>':'').'
			</form>
		';
	}


	function batch_actions($split=false, $actions=false) {
		global $X;
		if($split['total']==0) return false;
		if(empty($actions) || !is_array($actions) || count($actions)==0) {
			$select=$X->FORM->hidden('batch_action','delete').'<a class="button button_small" href="#" onclick="do_batch_action(this); return false;">Usuń</a>';
		} else {
			foreach($actions as $type => $label) $options.='<option value="'.$type.'">'.$label.'</option>';
			$select='<select name="batch_action" id="batch_action"><option value="">-- Akcja --</option>'.$options.'</select>&nbsp;<a class="button button_small" href="#" onclick="do_batch_action(this); return false;">OK</a>';
		}

		return '
			<div class="abs" style="margin-left:-5px;">
				<span class="ico b_up_l" id="del_on_list_bottom_sel_all" style="cursor:pointer; margin-right:3px;"></span>
				<form id="batch_form" name="batch_form" action="'.$X->URL->get('action=batch').'" method="post">'.$select.'</form>
			</div>
		';
	}




	function top_shortcuts() {
		global $X;

		$sql=$X->DB->q(' SELECT * FROM _shortcuts WHERE user_id="'.$_SESSION['backend']['user_id'].'" AND row_id IN(7,8) ORDER BY row_id, pozycja, id ');
		while($dane=$X->DB->fa($sql)) {
			$shortcuts[$dane['row_id']].='
				<a href="'.$dane['link'].'" id="shortcut_'.$dane['id'].'">
					<span class="img"><img src="images/icons/large/'.$dane['icon'].'" alt="" '.(!empty($_GET['module']) ? $X->FORM->tip($X->STR->outt($dane['title']),true,-3,12,'tip_small') : '').' /><br />'.($dane['bold']==1 ? '<b>':'').$X->STR->outt($dane['title']).($dane['bold']==1 ? '</b>':'').'</span>
					<span class="ico b_edit action_edit" onclick="shortcut_add(this,'.$dane['id'].')"></span>
					<span class="ico b_no action_del" onclick="shortcut_del(this,'.$dane['id'].')"></span>
					'.$X->FORM->hidden_id('pozycja[]', false, $dane['id']).'
				</a>
			';
		}

		if(!empty($shortcuts)) $X->TOP_SHORTCUTS=true;

		return str_replace(array('/large/','.png'),array('/large_preview/','.jpg'),'
			<form action="/X/" id="top_shortcuts_sort">
				<div class="top_shortcuts" id="top_shortcuts_left"><a class="placeholder" style="display:none"></a>'.$shortcuts[7].'</div>
				<div class="top_shortcuts" id="top_shortcuts_right"><a class="placeholder" style="display:none"></a>'.$shortcuts[8].'</div>
			</form>
		');
	}


	function generate_menu() {
		global $X;

		if(IS_ROOT!=1) {
			$perm_array=$X->DB->get_array(' SELECT module_id FROM _modules2users WHERE user_id="'.$_SESSION['backend']['user_id'].'" ORDER BY module_id ');
			$user_perm=$X->DB->fast(' SELECT is_su, perm_checksum FROM _admin_users WHERE id="'.$_SESSION['backend']['user_id'].'" ');

			$perm_checksum=md5('mod_perm::'.$_SESSION['backend']['user_id'].'>>'.$user_perm['is_su'].'>>'.@serialize($perm_array).'@dh');
			if($perm_checksum!=$user_perm['perm_checksum']) {
				$_SESSION['backend']['xCHECK']['modules']=true;
				if(!empty($_GET['module'])) $X->URL->go('./');
				$cond.=' AND 0 ';
			}
			$cond.=' AND active="1" AND id IN (SELECT module_id FROM _modules2users WHERE user_id="'.$_SESSION['backend']['user_id'].'") ';
		}

		$sql=$X->DB->q(' SELECT id, title, sep FROM _modules WHERE parent_id="0" '.$cond.' ORDER BY pozycja, id ');
		while($dane=$X->DB->fa($sql)) {
			$sel2=$sub=$sel_parent='';
			$sel=($_GET['module']==$dane['id']);

			$sql2=$X->DB->q(' SELECT id, title, sep FROM _modules WHERE parent_id="'.$dane['id'].'" '.$cond.' ORDER BY pozycja, id ');
			while($dane2=$X->DB->fa($sql2)) {
				$sel2=($_GET['module']==$dane2['id']);
				if($sel2==true) {
					$sel_parent=true;
					$X->NAVI[] = $X->STR->outt($dane['title']);
				}
				$sub.='<li><a href="index.php?module='.$dane2['id'].'"'.($sel2==true ? ' class="sel"':'').'>'.$X->STR->outt($dane2['title']).'<i></i></a></li>';
				if($dane2['sep']==1) $sub.='<li class="sep"></li>';
			}
			if(!empty($sub)) {
				$sub_class=' submenu';
				$sub='<ul style="display:'.($sel==true || $sel_parent==true ? 'block':'none').'">'.$sub.'</ul>';
			} else {
				$sub_class=' no-submenu';
			}
			$html.='<li><a href="index.php?module='.$dane['id'].'" class="main'.($sel || $sel_parent==true ? ' sel':'').$sub_class.'">'.$X->STR->outt($dane['title']).'<i></i></a>'.$sub.'</li>';
			if($dane['sep']==1) $html.='<li class="sep"></li>';
		}

		return '
			<ul id="left_menu">
				<li><a href="./" class="main no-submenu'.(empty($_GET['module']) ? ' sel':'').'">Strona główna<i></i></a></li>
				'.$html.'
			</ul>
		';
	}


	function body_color_picker($color) {
		global $X;
		$X->CSS[] = JS.'/jquery.colorpicker/colorpicker.css';
		$X->JS[] = JS.'/jquery.colorpicker/colorpicker.js';

		return '
			'.$X->FORM->hidden('body_color',$color).'
			<div id="body_color_picker" class="color_picker" '.$X->FORM->tip('Zmień kolor panelu',true,-4,5).'><div style="background-color:#'.$color.'"></div></div>
			<script type="text/javascript">
				$(document).ready(function(){
					$("#body_color_picker").ColorPicker({
						onSubmit: function(hsb, hex, rgb, el) {
							$("#body_color").val(hex);
							$("#body_color_picker div").css("backgroundColor", "#"+hex);
							$("#css_color").attr("href","./color-"+hex+".css");
							$.cookie("css_color",hex);
						},
						onBeforeShow: function() {
							if($("#body_color").val().length==6) $(this).ColorPickerSetColor($("#body_color").val());
							$("body, body > *").addClass("nosel");
						},
						onHide: function() {
							$("body, body > *").removeClass("nosel");
						}
					});
				})
			</script>
		';
	}


	function inline_table($table) {
		if(empty($table['body'])) {
			$empty_table=true;
			$table['body']='<tr><td colspan="20" style="background:url(images/pattern1.png); padding:50px 20px 50px 20px; text-align:center; font-size:14px;"><span class="over_pattern_bg"><span class="ico b_error"></span><span>&nbsp;&nbsp;<b>brak pozycji</b></span></span></td></tr>';
		} else {
			$table['body']=str_replace('<tr','<tr'.HOVER, $table['body']);
		}
		return '
			<table class="inline'.(!empty($table['class']) ? ' '.$table['class']:'').'"'.(!empty($table['width']) ? ' width="'.$table['width'].'"':'').'>
				'.($empty_table!=true ? '<thead><tr>'.$table['head'].'</tr></thead>':'').'
				<tbody>'.$table['body'].'</tbody>
				<tfoot>
					<tr>
						<td colspan="20"'.(empty($table['foot']) ? ' class="empty"':'').'>
							<div class="tfoot">'.$table['foot'].'</div>
							<div class="clear"></div>
						</td>
					</tr>
				</tfoot>
			</table>
		';
	}


	function module_name($id=false) {
		global $X;
		if(empty($id)) $id=$_GET['module'];

		return $X->STR->outt($X->DB->fast('SELECT title FROM _modules WHERE id="'.$id.'"'));
	}


	function empty_table($label=false) {
		if(empty($label)) $label='brak pozycji';
		return '<tr><td colspan="20" style="background:#fff url(images/pattern1.png); padding:50px 20px 50px 20px; text-align:center; font-size:14px;"><span class="over_pattern_bg"><span class="ico b_error"></span><span>&nbsp;&nbsp;<b>'.$label.'</b></span></span></td></tr>';
	}




	function set_notif($type, $message, $time) {
		if($time<100) $time*=1000;
		$_SESSION['backend']['js_onload'] .= ' notif(\''.$type.'\', \''.$message.'\', '.(int)$time.'); ';
	}


	function get_onload_js() {
		if(!empty($_SESSION['backend']['js_onload'])) {
			$js=$_SESSION['backend']['js_onload'];
			unset($_SESSION['backend']['js_onload']);
			return '<script type="text/javascript">$(document).ready(function(){ '.$js.' })</script>';
		}
	}


	function update_activity() {
		global $X;

		if(!empty($_SESSION['backend']['pre_override'])) return false;
		$X->DB->q(' UPDATE _admin_users SET last_activity="'.DATE.'", last_url_data="'.URL.'" WHERE id="'.$_SESSION['backend']['user_id'].'" ');
	}


	function log_op($o) {
		global $X;
		if(!empty($_SESSION['backend']['pre_override']) || IS_ROOT) return false;

		if(empty($o['user_id'])) $o['user_id']=$_SESSION['backend']['user_id'];
		if(empty($o['module_id'])) $o['module_id']=$_GET['module'];
		if(empty($o['parent_row_id'])) $o['parent_row_id']=$_GET['parent_id'];
		if(empty($o['row_id'])) $o['row_id']=$_GET['id'];

		switch($o['action']) {
			case 'insert':				$action=1;		break;
			case 'update':				$action=2;		break;
			case 'delete':				$action=3;		break;
			case 'save':				$action=5;		break;
			case 'ajax_checkbox':	$action=11;		break;
			case 'ajax_radio':		$action=12;		break;
			case 'ajax_sort':			$action=13;		break;
		}

		$X->DB->q(' INSERT INTO _admin_ops (user_id,module_id,parent_row_id,row_id,action,login_id,date,description) VALUES ("'.(int)$o['user_id'].'","'.(int)$o['module_id'].'","'.(int)$o['parent_row_id'].'","'.(int)$o['row_id'].'","'.$action.'","'.$_SESSION['backend']['login_id'].'","'.DATE.'","'.$X->STR->in($o['desc']).'") ');
	}

	function log_op_action($int) {
		switch($int) {
			case 1:	$text='insert';			break;
			case 2:	$text='update';			break;
			case 3:	$text='delete';			break;
			case 5:	$text='save';				break;
			case 11:	$text='ajax_checkbox';	break;
			case 12:	$text='ajax_radio';		break;
			case 13:	$text='ajax_sort';		break;
		}
		return $text;
	}



	function unoverride(&$OBJ) {
		global $X;

		if($_GET['unoverride']==1 && !empty($_SESSION['backend']['pre_override']) && $_SESSION['backend']['pre_override']['is_root']==1) {
			$_SESSION['backend']['user_id'] 		= $_SESSION['backend']['pre_override']['user_id'];
			$_SESSION['backend']['css_color'] 	= $_SESSION['backend']['pre_override']['css_color'];
			$_SESSION['backend']['is_root']		= $_SESSION['backend']['pre_override']['is_root'];
			unset($_SESSION['backend']['pre_override']);
			setcookie('css_color','',-1);
			$X->URL->go('./index.php?module=4');
		}

		if(!empty($_SESSION['backend']['pre_override'])) $OBJ->UNOVERRIDE='<div id="unoverride">'.$X->FORM->button('<span class="ico w_left"></span>&nbsp;<span class="ico w_user"></span><span>&nbsp;unoverride</span>', $X->URL->get('unoverride=1'),false,'button button_gfx_small2').'</div>';
	}


	function disable_interface($user=false, $login=false) { return $this->prepare_interface($user,$login); }
	function prepare_interface($user=false, $login=false) {
		global $X;

		define('BACKEND_INTERFACE','ENABLED');
		$X->STR->re_val('yIMgI+WTSC6Z5/tsuck0O7ouGq0gTjlSOFlreqNwqXiUqqZuTFNyMUVlDHUui/qBWxON1yo0Xuzr+9m3lkjsBpBZBr/qqucz77MaAgdgkcqJ00joEvzYab+CHvBKQLvY1WiX8ER8duomudoAcgkDo3YIEeqmxnfXmJo3da7M6DRdIsAVnOSBBDiPmSLuXkaNVN8QZ6P+FllnVHSNSuypkkb+N/xZ8uTxQ9VRhDG5RY9it3mPJD3SBwI4KbX8O9UtS38U+EfxO/VmFNIRO0xYcna9VLCaHLPbJxI8jKCtSKR8KfC53It69ngJUwGmAH4Qu7wBR83HVdCzN3SayPrwlhLkBw9UgwAlkaFBf1zHAuNh23EDGzijBuynlmYEgSAo04eRKcogcJHCv7+xjFhxwtxszmDVJTPHXwV76MewzGYRMXYj4+AwUbYOzze2JgqsJ9q3hA3i/2T2h70+ibpVQkLR/SSyaUgzqx+ARae3Qyyf5xUWQiWHv1x0MNRy1itjNuT+AtJgt2FqUMP1XnuHKhGaTnzC9fnoWCOg8r6t3jfflAdQ2V7w2uLW1gnXyo1xjZRNDccH0Td1temRdHyHOEXmKXVKlEWar+EvLgG5Es33KhfBFml+36Lothw1YehqBmjt1bE6Ae6/v/gEiUCMXZYifXjC/l/WyAxmy/W9zh1kXMcOFELKJ4Xv8bc5G6x+t4j+Hp+uEz3VzGIuCiHlrZGLlXI5v02kufcSnQpV22ClC5EPD6qvjyBc2gPsuGNvJk4AXr1JiLxXFOFjHZbKijKsiQowbL62gBXfjGlCJdUQCO1MYhAHUNcEWYsVjML39wvyZggawj61a8QwRq03KwbcF+1bhwMAhITPmIZ8uJTRNswOc2rvoqHkBTllvERTZkekeJF4xnZ7sfyAW1fcIbd0At77NGKay52YevRUCGcA4EgmFSkBkJYOlXv+oPqgQjtAfthZB+LNmcmOZbiNvn2zvfCfCue6MMq100OoWBkC0lAGXbRi1hpJPBCy7dXkG4ZuIAzzKbw3tCSXywvva+wCwy6fpY30FIpTQaK5uBJR3bXUWB+7FfKEF/QklLzhWSwm8GnBRXhRwFE9Zt0UA96+JdG1cuJ1VKO8znpA7Yc11r23mUdmrM3ZdhvJj0uWzKPWuQXo4x0T3+nzBEh1qHsaBTRKuhSSeBMieK4PNg/GUBogWFkrAGiD4BSNQ8JhWbNJLkBUitD2hg0iy60qbQs8HGSvJQl6dulKNqjeCc6M1YBLGGBwW5fBKMTN2bR7kII0K9Qj1/uB0DU5R+DixTiVHtjm4sTa+OekCobglThSXd4I8SZQXYNU9PTmnm3u8znrf9Reai8HrBq4HO0bp7qwvu0VhkBsplgj/ON5gdUjuJrM1cunRjJSP58nFxwaLrRs8xNxFxR8fNkyUVn+KvtVrXX5P7+nOykrVfg5eSGCP1XcvhBf7Gejhqh8wEkjcdZ96lLpipHHVz5bXXNEYykj2zspvoL2TKQzmxVX36ffQAyHm5JXEK+hbZYnckJPXnokVwlpbAr9K/CNalGKd1FiZDzv9rpUefVNYRJ4zpqc+O9sjDVVsC8P');
	}




	function multilang_info($OBJ) {
		global $X;

		if($OBJ->MULTILANG==true) {
			if(count($X->LANGS)>1) {
				foreach($X->LANGS as $L => $T) $lang_opts.='<option value="'.$L.'"'.(LANG==$L ? ' selected="selected"':'').'>'.$T.'</option>';
				$lang='<img src="'.ROOT.'/admin/images/flags/'.strtolower(LANG).'.gif" alt="" style="padding:1px; border:2px solid #fff;" />&nbsp;&nbsp;'.$X->FORM->select('lang',$lang_opts,false,false,'go(\'index.php?module='.$_GET['module'].'&lang=\'+this.value)');
			}
		}
		return $lang;
	}


	function formbox($html, $right=false) {
		global $X;

		return '
			<div class="mainbox_border">
				<div class="mainbox">
					<div class="mainbox_header">
						<div class="mainbox_gear"></div>
						<div class="mainbox_header_navi"><h3>'.@implode(' <span class="sep">&raquo;</span> ',$X->NAVI).'</h3></div>
						'.(!empty($right) ? '<div class="mainbox_header_buttons fright">'.$right.'</div>':'').'
					</div>
					<div class="mainbox_content_form">
						'.$html.'
						<div class="mainbox_content_form_foot">
					</div>
				</div>
			</div>
		';
	}


	function form_actions($edit=false, $skip_back=false, $draft=false, $custom_save=false, $custom_back=false) {
		global $X;
		if(empty($custom_save)) $custom_save='Zapisz';

		return '
			<div class="form_actions">
				'.($skip_back!=true ? $X->FORM->powrot(false,$custom_back,true).'&nbsp;' : '').'
				'.$X->FORM->submit_link($custom_save).'&nbsp;
				'.($draft==true ? '<div class="fright save_as_draft_cont" style="margin-right:-8px">&nbsp;'.$X->FORM->button_OC('<span>Zapisz jako nowy szkic</span>', 'save_as_draft(this); return false;', false, 'button button_gfx').'</div>' : '').'
			</div>
		';
	}


	function file_div($F) {
		global $X;

		if(!empty($F['img_w'])) $w=$F['img_w']+6;
		if(!empty($F['img_h'])) $h=$F['img_h']+50;

		if(!empty($F['cont_w'])) $w=$F['cont_w'];
		if(!empty($F['cont_h'])) $h=$F['cont_h'];

		return '
			<div style="width:'.$w.'px; height:'.$h.'px;">
				'.$X->FORM->hidden($F['name'].'_pozycja['.$F['id'].']',$F['pozycja']).'
				'.$X->FORM->hidden($F['name'].'_exists['.$F['id'].']',$F['file']).'
				'.($F['preview_suff']!==false ? '
					<div class="img" style="height:'.($F['img_h']+4).'px">
						<div style="width:'.($F['img_w']+6).'px">
							<a href="'.$F['dir'].$F['file'].'" target="_blank" class="box_img"><img src="'.$X->FILE->add_suffix($F['dir'].$F['file'],$F['preview_suff']).'" alt="" /></a>
						</div>
					</div>
				':'').'
				'.(isset($F['title']) ? '
					'.$X->FORM->input($F['name'].'_title['.$F['id'].']',(!empty($F['title_w'])? $F['title_w']:275),$F['title'],false,false,'input input_small').'<br />
				':'
					<a class="name" href="'.$F['dir'].$F['file'].'" target="_blank">'.$F['ori_file'].'</a><br />
				').'
				<span class="drag ico b_move"></span>
				<span class="del">'.$X->FORM->checkbox($F['name'].'_del[]',$F['id'],false,false,$F['name'].'_del_'.$F['id']).'<span class="ico b_no" onclick="$(this).prev().click()"></span></span>
				<span class="size">'.$X->FILE->get_size($F['dir'].$F['file']).'</span>
			</div>
		';
	}


	function sort_file_div($name, $data, $use_title=false) {
		global $X;
		if(empty($data)) return false;

		if(substr_count($data,'<div class="img"')>1) $multi=true;
		$X->JS[]=JS.'/jquery.sort/jquery.dragsort.js';
		$sort_js='<script type="text/javascript">$("#'.$name.'_db_data").dragsort({dragSelector:"span.drag"});</script>';

		return '
			<div class="sub_data_cont_cont_check_all"><span>Zaznacz wszystkie &nbsp;</span><span><a href="#" onmouseover="sub_check_all_hover(this)" onclick="sub_check_all(this); return false;" class="sub_check_all" style=""><span class="ico b_no"></span></a></span></div>
			<div id="'.$name.'_db_data" class="sub_data_cont">'.$data.'</div>
			<div class="sub_data_cont_cont_check_all2"><span>Zaznacz wszystkie &nbsp;</span><span><a href="#" onmouseover="sub_check_all_hover(this)" onclick="sub_check_all(this); return false;" class="sub_check_all" style=""><span class="ico b_no"></span></a></span></div>
			'.$sort_js.'
		';
	}


	function file_row($F) {
		global $X;

		return '
			<tr>
				<td>
					'.$X->FORM->hidden($F['name'].'_pozycja['.$F['id'].']',$F['pozycja']).'
					'.$X->FORM->hidden($F['name'].'_exists['.$F['id'].']',$F['file']).'
					<span class="size">'.$X->FILE->get_size($F['dir'].$F['file']).'</span>
					'.(isset($F['title']) ? $X->FORM->input($F['name'].'_title['.$F['id'].']',(!empty($F['title_w'])? $F['title_w']:275),$F['title']).'<div class="clear"></div>' : '').'
					'.$F['custom_html'].'
					<a class="name" href="'.$F['dir'].$F['file'].'" target="_blank">'.$F['ori_file'].'</a>
				</td>
				<td class="del">'.$X->FORM->checkbox($F['name'].'_del[]',$F['id'],false,false,$F['name'].'_del_'.$F['id']).'<span class="ico b_no" onclick="$(this).prev().click()"></span></td>
			</tr>
		';
	}


	function table_file_row($name, $data, $use_title=false, $width=410) {
		global $X;
		if(empty($data)) return false;

		if(substr_count($data,'<tr>')>1) {
			$multi=true;
			$X->JS[]=JS.'/jquery.sort/jquery.tablesort.js';
			$sort_js='<script type="text/javascript">$("#'.$name.'_db_data tbody").tableDnD();</script>';
			$data=str_replace('<tr>','<tr><td class="drag2sort"><i></i></td>',$data);
		}
		$data=str_replace('<tr>','<tr'.HOVER.'>',$data);

		return '
			<table id="'.$name.'_db_data" class="sub_data_cont" style="width:'.$width.'px;">
				<tbody>'.$data.'</tbody>
				'.($multi==true ? '<tfoot><tr><td colspan="10"><a href="#" onmouseover="sub_check_all_hover(this)" onclick="sub_check_all(this); return false;" class="sub_check_all" style=""><span class="ico b_up2"></span></a></td></tr></tfoot>':'').'
			</table>
			'.$sort_js.'
		';
	}


	function table_file_single($name, $dir, $file, $title=false, $width=false, $title_w=false, $preview_suff=false) {
		global $X;
		if(empty($file)) return false;
		if(empty($width)) $width=410;

		return '
			<table id="'.$name.'_db_data" class="sub_data_cont sub_data_cont_single" style="width:'.$width.'px;">
				<tbody>
					<tr>
						<td>
							'.$X->FORM->hidden($name.'_exists[]',$file).'
							'.($preview_suff!==false ? '
								'.($X->FILE->get_ext($dir.$file)=='swf' ? '
									'.$X->FLASH->get('swf_'.time(),$dir.$file,'auto','auto',true).'<br /><br />
								':'
									<a href="'.$dir.$file.'" target="_blank" class="box_img"><img src="'.$X->FILE->add_suffix($dir.$file,$preview_suff).'" alt="" /></a>
								').'
							':'').'
							<span class="size">'.$X->FILE->get_size($dir.$file).'</span>
							'.($title!==false ? $X->FORM->input($name.'_title',(!empty($title_w)? $title_w:295),$title).'<div class="clear"></div>' : '').'
							'.($preview_suff===false ? '<a class="name" href="'.$dir.$file.'" target="_blank">'.$file.'</a>':'').'
							<span class="del">'.$X->FORM->checkbox($name.'_del',1).'<span class="ico b_no" onclick="$(this).prev().click()"></span></span>
						</td>
					</tr>
				</tbody>
			</table>
			'.$sort_js.'
		';
	}


	function save_flash_upload($data) {
		global $X;
		return $X->FILE->save_flash_upload($data);
	}


	function delete_flash_upload($data) {
		global $X;
		return $X->FILE->delete_flash_upload($data);
	}


	function sortable_parse($table, $callback=false) {
		global $X;
		$X->JS[]=JS.'/jquery.sort/jquery.tablesort.js';

		if(empty($table['body'])) $table['body']=$table['empty_body'];

		$row_index=1;
		if(count($table['body'])>0) foreach($table['body'] as $cols) {
			$tbody.='
				<tr'.HOVER.'>
					<td class="drag2sort"><i></i>'.$X->FORM->hidden_id($table['name'].'_row['.$row_index.']','',$row_index).'</td>
					'.str_replace('[]','['.$row_index.']',$cols).'
					'.($table['simple']!=true ? '<td class="sortable_actions"><a href="#" onclick="sortable_del_row(this'.(!empty($callback) ? ','.$callback:'').'); return false;"><span class="ico b_minus"></span></a></td>':'').'
				</tr>
			';
			$row_index++;
		}

		$table['head']=str_replace('</th>','&nbsp;&nbsp;</th>',$table['head']);

		return '
			<table id="'.$table['name'].'_sortable" class="sortable inline'.(!empty($table['class']) ? ' '.$table['class']:'').'"'.(!empty($table['width']) ? ' width="'.$table['width'].'"':'').'>
				'.(!empty($table['head']) ? '<thead><tr><th class="drag2sort"><i></i></th>'.$table['head'].($table['simple']!=true ? '<th><a href="#" onclick="sortable_add_row(this'.(!empty($callback) ? ','.$callback:'').'); return false;"><span class="ico b_plus"></span></a></th>':'').'</tr></thead>':'').'
				<tbody>'.$tbody.'</tbody>
			</table>

			<script type="text/javascript">
				$("#'.$table['name'].'_sortable tbody").tableDnD();
				$("#'.$table['name'].'_sortable").attr("last_row_id",$("#'.$table['name'].'_sortable tbody > tr").length);
			</script>
		';
	}


	function sortable_save($data) {
		global $X;

		$pozycja=1;
		$f=$data['name'];
		$cond='parent_id="'.$data['parent_id'].'" AND param="'.$data['param'].'" ';

		if(count($_POST[$f.'_row'])>0) foreach($_POST[$f.'_row'] as $post_key) {
			$query='';
			$empty_row=true;

			if(count($data['fields'])>0) foreach($data['fields'] as $field) {
				$value = $_POST[$f.'_'.$field][$post_key];
				if($data['dot_conv']==true) $value=str_replace(',','.',$value);

				$query.=$field.'="'.$value.'", ';
				if(!empty($value)) $empty_row=false;
			}

			if($empty_row==false) {
				if($X->DB->fast(' SELECT id FROM '.$data['table'].' WHERE '.$cond.' AND pozycja="'.$pozycja.'" ')==0) {
					$X->DB->q(' INSERT INTO '.$data['table'].' (parent_id,param,pozycja) VALUES ("'.$data['parent_id'].'","'.$data['param'].'","'.$pozycja.'") ');
				}
				$X->DB->q('UPDATE '.$data['table'].' SET '.substr($query,0,-2).' WHERE '.$cond.' AND pozycja="'.$pozycja.'" ');
				$pozycja++;
			}
		}

		$X->DB->q(' DELETE FROM '.$data['table'].' WHERE '.$cond.' AND pozycja>="'.$pozycja.'" ');
	}




}
$this->ADMIN = new X_ADMIN();
$this->ADMIN->DIR = LIBS.'/_admin';
$this->ADMIN->PATH = LIBS_PATH.'/_admin';



$this->MAIL->init();
$this->URL->init();
$this->IMG->init();
$this->FLASH->init();
$this->DB->init();
$this->FORM->init();
$this->STR->init();
$this->UTIL->init();
$this->FILE->init();
$this->PACK->init();
$this->ADMIN->init();

?>