<?php

function get_catid_select($title = '', $catid = 0, $moduleid = 1, $extend = '', $deep = 0, $cat_id = 1) {
	global $CATEGORY, $PL_CFG;
	$file = "catid_".$moduleid.".php";
    $CATEGORY = cache_read($file,PL_ROOT.$PL_CFG['cache']."/");
	$CATEGORY = $CATEGORY ? $CATEGORY : array();
	$parents = array();
	$cid = $catid;
	if($catid && $CATEGORY[$catid]['child']) $parents[] = $catid;
	while($catid) {
		if($CATEGORY[$cid]['parent']) {
			$parents[] = $cid = $CATEGORY[$cid]['parent'];
		} else {
			break;
		}
	}
	$parents[] = 0;
	$parents = array_reverse($parents);
	$select = '';
	foreach($parents as $k=>$v) {
		if($deep && $deep <= $k) break;
		$select .= '<select onchange="load_category(this.value, '.$cat_id.');" '.$extend.'>';
		if($title) $select .= '<option value="0">'.$title.'</option>';
		foreach($CATEGORY as $c) {
			if($c['parent'] == $v) {
				$selectid = isset($parents[$k+1]) ? $parents[$k+1] : $catid;
				$selected = $c['id'] == $selectid ? ' selected' : '';
				$select .= '<option value="'.$c['id'].'"'.$selected.'>'.$c['name'].'</option>';
			}
		}
		$select .= '</select> ';
	}
	
	return $select;
}

function ajax_catid_select($name = 'catid', $title = '', $catid = 0, $moduleid = 1, $extend = '', $deep = 0) {
	global $cat_id;
	if($cat_id) {
		$cat_id++;
	} else {
		$cat_id = 1;
	}
	$catid = intval($catid);
	$deep = intval($deep);
	$select = '';
	$select .= '<input name="'.$name.'" id="catid_'.$cat_id.'" type="hidden" value="'.$catid.'"/>';
	$select .= '<span id="load_category_'.$cat_id.'">'.get_catid_select($title, $catid, $moduleid, $extend, $deep, $cat_id).'</span>';
	$select .= '<script type="text/javascript">';
	if($cat_id == 1) $select .= 'var category_moduleid = new Array;';
	$select .= 'category_moduleid['.$cat_id.']="'.$moduleid.'";';
	if($cat_id == 1) $select .= 'var category_title = new Array;';
	$select .= 'category_title['.$cat_id.']=\''.$title.'\';';
	if($cat_id == 1) $select .= 'var category_extend = new Array;';
	$select .= 'category_extend['.$cat_id.']=\''.$extend.'\';';
	if($cat_id == 1) $select .= 'var category_catid = new Array;';
	$select .= 'category_catid['.$cat_id.']=\''.$catid.'\';';
	if($cat_id == 1) $select .= 'var category_deep = new Array;';
	$select .= 'category_deep['.$cat_id.']=\''.$deep.'\';';
	$select .= '</script>';
	if($cat_id == 1) $select .= '<script type="text/javascript" src="'.PL_URL.'js/category.js"></script>';
	return $select;
}

?>