<?php
/**
 * @created 2007-08-08
 * @file adcentral.php
 * @author dswistowski <dswistowski@firma.gery.pl>
 * 
 * @brief Administracja eksportem danych do adcentrala, został uzyty ,,styl'' programownaia identyczny jak inne strony oscommerce
 */

  define(ADCENTRAL_START_SEPARATOR,"<?php\n#__adcentral__start\n");
  define(ADCENTRAL_STOP_SEPARATOR,"\n#__adcentral__stop\n?>");  
  define(FILENAME_ADCENTRAL,"adcentral.php");
  
  	
  /**
   * Funkcja zapewniająca zgodność między różnymi wersjami oscommerce
   */
  function hide_session_id()
  {
  	if(function_exists('tep_hide_session_id'))
  		return tep_hide_session_id();
  	else return '';
  } 
   
  /**
   * dopisuje dane adcentrala do podanego pliku
   */  
  function write_adcentral_data($file, $data)
  {
  	print "Dopisuje dane do pliku $file</br>";
  	$str = file_get_contents($file);
  	$data = ADCENTRAL_START_SEPARATOR.$data.ADCENTRAL_STOP_SEPARATOR;
  	if(strpos($str,ADCENTRAL_START_SEPARATOR))
  		return false;
  	else
		file_put_contents($file,$str.$data);
	return true;
  } 

  /**
   * usuwa dane adcentrala z podanego pliku
   */
  function remove_adcentral_data($file)
  {
  	print "<tr><td>Usuwam dane do pliku $file</td><tr>";
  	$str = file_get_contents($file);
  	$start = strpos($str,ADCENTRAL_START_SEPARATOR);
  	$stop =  strpos($str,ADCENTRAL_STOP_SEPARATOR);
  	if(!$start)
  		return false;
  	file_put_contents($file, trim(substr($str, 0, $start ).substr($str, $stop + strlen(ADCENTRAL_STOP_SEPARATOR))));
	return true;
  } 

  /**
   * Tworzy redirecta za pomocą javascripta
   */
  function js_redirect($href)
  {
	?>
	<script language="JavaScript" type="text/javascript">
	<!--
	setTimeout(function(){
			document.location = '<?php print $href ?>';
		}
	,1000);
	--></script>
	<a href="<?php print $href ?>">Kliknij jeżeli nie zostałes automatycznie przeniesiony</a> 
	<?php  	
  }
  
  
  require('includes/application_top.php');
  require(DIR_WS_CLASSES . 'currencies.php');
  //określenie akcji
  $action = (isset($HTTP_GET_VARS['action']) ? $HTTP_GET_VARS['action'] : '');
  $currencies = new currencies();

  $languages = tep_get_languages();
  $languages_array = array();
  $languages_selected = DEFAULT_LANGUAGE;
  for ($i = 0, $n = sizeof($languages); $i < $n; $i++) {
    $languages_array[] = array('id' => $languages[$i]['code'],
                               'text' => $languages[$i]['name']);
    if ($languages[$i]['directory'] == $language) {
      $languages_selected = $languages[$i]['code'];
    }
  }
  
  //zmiany w plikach, które wprowadza instalator
  $file_changes = array(
  	DIR_FS_ADMIN.'includes/column_left.php'=>"require(DIR_WS_BOXES . 'adcentral.php');",
  	DIR_FS_ADMIN.'includes/filenames.php'=>"define('FILENAME_ADCENTRAL', '".FILENAME_ADCENTRAL."');",
  	DIR_FS_ADMIN.'includes/configure.php'=>"define('ADCENTRAL_INSTALLED', true);",
  	DIR_FS_CATALOG.'includes/filenames.php'=>"define('FILENAME_ADCENTRAL', '".FILENAME_ADCENTRAL."');",
  	DIR_FS_ADMIN.'includes/database_tables.php'=>"define('TABLE_ADCENTRAL_CATEGORIES', 'adcentral_categories_groups');",  	
  	DIR_FS_CATALOG.'includes/database_tables.php'=>"define('TABLE_ADCENTRAL_CATEGORIES', 'adcentral_categories_groups');",
  );
  
  //Zmiany w plikaj językowych
  foreach($languages as $lang)
  {
  	$file_changes[DIR_FS_ADMIN.DIR_WS_LANGUAGES.$lang['directory'].'.php'] = 
		"define('BOX_HEADING_ADCENTRAL', 'Adcentral');\n".
		"define('BOX_ADCENTRAL_UNINSTALL', 'Odinstaluj');\n".
		"define('BOX_ADCENTRAL_GROUPS', 'Kategorie');\n";
	
  };
  
  //Zapytania wykonywane podczas instalacji
  $database_on_install = array(
  	'adcentral_categories_groups'=>'CREATE TABLE `'.TABLE_ADCENTRAL_CATEGORIES.'` (
		`category_id` INT NOT NULL ,
		`group_id` INT NOT NULL ,
		PRIMARY KEY ( `category_id` )
		);',
  );
  
  
  //zapytania wykonywana podczas usuwania integracji z adcentralem.
  $database_on_uninstall = array(
  	'adcentral_categories_groups'=>'DROP TABLE `'.TABLE_ADCENTRAL_CATEGORIES.'`;',
  );
  
  /*
  if(defined('FILENAME_ADMIN_FILES'))
  {
  	$database_on_install[FILENAME_ADMIN_FILES] = 'insert into `'.FILENAME_ADMIN_FILES.'` (`admin_files_name`,`admin_files_is_boxes`,`admin_files_to_boxes`,`admin_groups_id`) values (\'adcentral.php\', 1,0,1)';
  	$database_on_uninstall[FILENAME_ADMIN_FILES] = 'delete from `'.FILENAME_ADMIN_FILES.'` where admin_files_name=\'adcentral.php\'';
  }*/
  
	//Obsługa akcji niewyświetlających strone  
  switch ($action) {
	//przydzielenie kategorii grupie  	
	case 'addToGroup':
		$cID = tep_db_prepare_input($_REQUEST['pID']);
		$nID = tep_db_prepare_input($_REQUEST['nID']);
		$cPath = tep_db_prepare_input($_REQUEST['cPath']);
		tep_db_query('insert into `'.TABLE_ADCENTRAL_CATEGORIES.'` (category_id, group_id) values ('.$cID.', '.$nID.') ON DUPLICATE KEY UPDATE category_id='.$cID);
		tep_redirect(tep_href_link(FILENAME_ADCENTRAL,"cPath=$cPath&cID=$cID"));
		break;
	//usunięcie powiązania między grupą a kategorią
	case 'deleteGroup':
		$cPath = tep_db_prepare_input($_REQUEST['cPath']);
		$cID = tep_db_prepare_input($_REQUEST['cID']);
		tep_db_query('delete from `'.TABLE_ADCENTRAL_CATEGORIES.'` where category_id='.$cID);
		tep_redirect(tep_href_link(FILENAME_ADCENTRAL,"cPath=$cPath&cID=$cID"));
		break;
	default:
		break;
}
  
?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<meta name="robots" content="noindex,nofollow">
<title><?php echo TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<script language="javascript" src="includes/general.js"></script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF" onload="SetFocus();">
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->

<!-- body //-->
<table border="0" width="100%" cellspacing="2" cellpadding="2">
  <tr>
    <td width="<?php echo BOX_WIDTH; ?>" valign="top"><table border="0" width="<?php echo BOX_WIDTH; ?>" cellspacing="1" cellpadding="1" class="columnLeft">
<!-- left_navigation //-->
<?php require(DIR_WS_INCLUDES . 'column_left.php'); ?>
<!-- left_navigation_eof //-->
    </table></td>
<!-- body_text //-->
    <td width="100%" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2">
      <tr>
        <td><table border="0" width="100%" cellspacing="0" cellpadding="2" height="40">
          <tr>
            <td class="pageHeading"><?php echo STORE_NAME; ?></td>
            <td class="pageHeading" align="right"><?php echo tep_draw_form('adminlanguage', FILENAME_DEFAULT, '', 'get') . tep_draw_pull_down_menu('language', $languages_array, $languages_selected, 'onChange="this.form.submit();"') . hide_session_id() . '</form>'; ?></td>
          </tr>
        </table></td>
      </tr>
      <tr>
        <td>
        <table border="0" width="100%" cellspacing="0" cellpadding="2">
<?php
       
	if(isset($_GET['pg']))
		$page =  $_GET['pg'];
	else
		$page = 'groups';
	//Opsługa wyświetlania róznych stron
	switch ($page) {
		//pierwsza faza odinstalowywania
		case 'uninstall1':
			?>		
			<tr><td>TEXT_ADCENTRAL_UNINSTALL</td></tr>	 
			<tr><td><a href="<?php print tep_href_link(FILENAME_ADCENTRAL, 'pg=uninstall2') ?>"><?php print tep_image('../'.DIR_WS_LANGUAGES . $language . '/images/buttons/'.'button_continue.gif', 'dalej');?></a></td></tr>
			<?php 
			break;		
		//druga faca odinstlowywania (zapytania sql)
		case 'uninstall2':
			$ok = true;
			foreach($database_on_uninstall as $name=>$query)
			{
				tep_db_query($query);
				print "Usuwam tabele: ".$name;					
			}
			if($ok): 
				print js_redirect(tep_href_link(FILENAME_ADCENTRAL, 'pg=uninstall3'));
				
			endif;
			break;
		//trzecia faza odinstlowywania (usuwanie danych z plików)
		case 'uninstall3':
			foreach($file_changes as $file=>$change)
				if(!remove_adcentral_data($file, $change))
					print ("$file nieposiada wpisów adcentrala.<br/>");
			print js_redirect(tep_href_link(FILENAME_DEFAULT));
			break;
		//pierwsza faza instalacji (sprawdzenie praw dostępu do plików)
		case 'stage1':
			$ok = true;
	  		foreach($file_changes as $file=>$change)
	  		{
				$writable = is_writable($file);
				if(!$writable)
					print "$file jest niezapisywalny.<br/>"; 
	  			$ok = ($ok and $writable);
	  		};
	  		if($ok): ?>
				<tr><td><?php print TEXT_ADCENTRAL_GOOD_FILE_RIGTHS?></td></tr>
				<tr><td><?php print js_redirect(tep_href_link(FILENAME_ADCENTRAL, 'pg=stage2')); ?></tr></td>
			<?php 
				
			else: 
				print TEXT_ADCENTRAL_BAD_FILE_RIGTHS;
			endif; 
			break;
		//druga faza instalacji (zmiany w plikach)
		case 'stage2':
			$ok = true;
			foreach($file_changes as $file=>$change)
				if(!write_adcentral_data($file, $change))
				{
					$ok = false;
					print ( "$file posiada już wpisy adcentrala.<br/>");
				}
			if($ok): 
				print js_redirect(tep_href_link(FILENAME_ADCENTRAL, 'pg=stage3'));
			endif;
			break;	
		//trzecia faza instalacji (zapytania sql)
		case 'stage3':
			$ok = true;
			foreach($database_on_install as $name=>$query)
			{
				tep_db_query($query);				
				print "Dodaje tabele: ".$name;
			}
			if($ok): 
				print js_redirect(tep_href_link(FILENAME_ADCENTRAL, 'pg=stage4'));
			endif;
			break;
		//koniec instalacji, komunikat o powodzeniu
		case 'stage4':
			?>
			<tr><td>TEXT_INSTALATION_SUCCESFULL</tr><td>
			<tr><td><a href="<?php print tep_href_link(FILENAME_ADCENTRAL) ?>"><?php print tep_image('../'.DIR_WS_LANGUAGES . $language . '/images/buttons/'.'button_continue.gif', 'dalej');?></a></td></tr>
			<?php
			break;
		default:
			if(ADCENTRAL_INSTALLED===true):?>
				 
<!-- BODY START -->
	
	  <table border="0" width="100%" cellspacing="0" cellpadding="2">
      <tr>
        <td><table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <td class="pageHeading"><?php echo HEADING_TITLE; ?></td>
            <td class="pageHeading" align="right"><?php echo tep_draw_separator('pixel_trans.gif', 1, HEADING_IMAGE_HEIGHT); ?></td>
            <td align="right"><table border="0" width="100%" cellspacing="0" cellpadding="0">
              <tr>
                <td class="smallText" align="right">
<?php
    echo tep_draw_form('search', FILENAME_ADCENTRAL, '', 'get');
    echo HEADING_TITLE_SEARCH . ' ' . tep_draw_input_field('search');
    echo hide_session_id() . '</form>';
?>
                </td>
              </tr>
              <tr>
                <td class="smallText" align="right">
<?php
    echo tep_draw_form('goto', FILENAME_ADCENTRAL, '', 'get');
    echo HEADING_TITLE_GOTO . ' ' . tep_draw_pull_down_menu('cPath', tep_get_category_tree(), $current_category_id, 'onChange="this.form.submit();"');
    echo hide_session_id() . '</form>';
?>
                </td>
              </tr>
              
               <tr>
                <td class="smallText" align="right">
				<a href="<?php print tep_href_link(FILENAME_ADCENTRAL, 'show_uncategorized')?>"><?php print SHOW_UNLINKED;?></a>
                </td>
              </tr>
              
            </table></td>
          </tr>
        </table></td>
      </tr>
      <tr>
        <td><table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <td valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2">
              <tr class="dataTableHeadingRow">
                <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_CATEGORIES_PRODUCTS; ?></td>
                <td class="dataTableHeadingContent" align="center"><?php echo TABLE_HEADING_EXPORTED; ?></td>
                <td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_ACTION; ?>&nbsp;</td>
              </tr>
<?php
	
	$categories_count = 0;
    $rows = 0;
    //zapytania to stworzenia listingu kategorii
    if (isset($HTTP_GET_VARS['search'])) {
      $search = tep_db_prepare_input($HTTP_GET_VARS['search']);
      $categories_query = tep_db_query("select c.categories_id, cd.categories_name, c.categories_image, c.parent_id, c.sort_order, c.date_added, c.last_modified, (agc.group_id is null) as exported  from " . TABLE_CATEGORIES . " c left join ". TABLE_ADCENTRAL_CATEGORIES ." agc on ( c.categories_id = agc.category_id), " . TABLE_CATEGORIES_DESCRIPTION . " cd where c.categories_id = cd.categories_id and cd.language_id = '" . (int)$languages_id . "' and cd.categories_name like '%" . tep_db_input($search) . "%' order by c.sort_order, cd.categories_name");
    }elseif(isset($HTTP_GET_VARS['show_uncategorized'])) {
    	$categories_query = tep_db_query("select c.categories_id, cd.categories_name, c.categories_image, c.parent_id, c.sort_order, c.date_added, c.last_modified, agc.category_id as adcentral_category_id, (agc.group_id is null) as exported from " . TABLE_CATEGORIES . " c left join ". TABLE_ADCENTRAL_CATEGORIES ." agc on ( c.categories_id = agc.category_id), " . TABLE_CATEGORIES_DESCRIPTION . " cd where  agc.group_id is null and c.categories_id = cd.categories_id and cd.language_id = '" . (int)$languages_id . "' order by c.sort_order, cd.categories_name");
    } else {
      $categories_query = tep_db_query("select c.categories_id, cd.categories_name, c.categories_image, c.parent_id, c.sort_order, c.date_added, c.last_modified, agc.category_id as adcentral_category_id, (agc.group_id is null) as exported from " . TABLE_CATEGORIES . " c left join ". TABLE_ADCENTRAL_CATEGORIES ." agc on ( c.categories_id = agc.category_id), " . TABLE_CATEGORIES_DESCRIPTION . " cd where c.parent_id = '" . (int)$current_category_id . "' and c.categories_id = cd.categories_id and cd.language_id = '" . (int)$languages_id . "' order by c.sort_order, cd.categories_name");
    }
    while ($categories = tep_db_fetch_array($categories_query)) {
      $categories_count++;
      $rows++;

      if (isset($HTTP_GET_VARS['search']) || isset($HTTP_GET_VARS['show_uncategorized'])) $cPath= $categories['parent_id'];

      if ((!isset($HTTP_GET_VARS['cID']) && !isset($HTTP_GET_VARS['pID']) || (isset($HTTP_GET_VARS['cID']) && ($HTTP_GET_VARS['cID'] == $categories['categories_id']))) && !isset($cInfo) && (substr($action, 0, 3) != 'new')) {
        $category_childs = array('childs_count' => tep_childs_in_category_count($categories['categories_id']));
        $category_products = array('products_count' => tep_products_in_category_count($categories['categories_id']));

        $cInfo_array = array_merge($categories, $category_childs, $category_products);
        $cInfo = new objectInfo($cInfo_array);
      }

      if (isset($cInfo) && is_object($cInfo) && ($categories['categories_id'] == $cInfo->categories_id) ) {
        echo '              <tr id="defaultSelected" class="dataTableRowSelected" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" onclick="document.location.href=\'' . tep_href_link(FILENAME_ADCENTRAL, tep_get_path($categories['categories_id'])) . '\'">' . "\n";
      } else {
        echo '              <tr class="dataTableRow" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" onclick="document.location.href=\'' . tep_href_link(FILENAME_ADCENTRAL, 'cPath=' . $cPath . '&cID=' . $categories['categories_id']) . '\'">' . "\n";
      }
?>
                <td class="dataTableContent"><?php echo '<a href="' . tep_href_link(FILENAME_ADCENTRAL, tep_get_path($categories['categories_id'])) . '">' . tep_image(DIR_WS_ICONS . 'folder.gif', ICON_FOLDER) . '</a>&nbsp;<b>' . $categories['categories_name'] . '</b>'; ?></td>
                <td class="dataTableContent" align="center">
     <?php          
                if ($categories['exported'] != '1') {
        echo tep_image(DIR_WS_IMAGES . 'icon_status_green.gif', IMAGE_ICON_STATUS_GREEN, 10, 10) . '&nbsp;&nbsp;<a href="' . tep_href_link(FILENAME_ADCENTRAL, 'action=deleteGroup&cID=' . $categories['categories_id'] . '&cPath=' . $cPath) . '">' . tep_image(DIR_WS_IMAGES . 'icon_status_red_light.gif', IMAGE_ICON_STATUS_RED_LIGHT, 10, 10) . '</a>';
      } else {
        echo '<a href="' . tep_href_link(FILENAME_ADCENTRAL, 'action=edit_category&cID=' . $categories['categories_id'] . '&cPath=' . $cPath) . '">' . tep_image(DIR_WS_IMAGES . 'icon_status_green_light.gif', IMAGE_ICON_STATUS_GREEN_LIGHT, 10, 10) . '</a>&nbsp;&nbsp;' . tep_image(DIR_WS_IMAGES . 'icon_status_red.gif', IMAGE_ICON_STATUS_RED, 10, 10);
      };
      ?>
                </td>
                <td class="dataTableContent" align="right"><?php if (isset($cInfo) && is_object($cInfo) && ($categories['categories_id'] == $cInfo->categories_id) ) { echo tep_image(DIR_WS_IMAGES . 'icon_arrow_right.gif', ''); } else { echo '<a href="' . tep_href_link(FILENAME_ADCENTRAL, 'cPath=' . $cPath . '&cID=' . $categories['categories_id']) . '">' . tep_image(DIR_WS_IMAGES . 'icon_info.gif', IMAGE_ICON_INFO) . '</a>'; } ?>&nbsp;</td>
              </tr>
<?php
    }
    $cPath_back = '';
    if (sizeof($cPath_array) > 0) {
      for ($i=0, $n=sizeof($cPath_array)-1; $i<$n; $i++) {
        if (empty($cPath_back)) {
          $cPath_back .= $cPath_array[$i];
        } else {
          $cPath_back .= '_' . $cPath_array[$i];
        }
      }
    }

    $cPath_back = (tep_not_null($cPath_back)) ? 'cPath=' . $cPath_back . '&' : '';
?>
              <tr>
                <td colspan="3"><table border="0" width="100%" cellspacing="0" cellpadding="2">
                  <tr>
                    <td class="smallText"><?php echo TEXT_CATEGORIES . '&nbsp;' . $categories_count; ?></td>
                    <td align="right" class="smallText"><?php if (sizeof($cPath_array) > 0) echo '<a href="' . tep_href_link(FILENAME_ADCENTRAL, $cPath_back . 'cID=' . $current_category_id) . '">' . tep_image_button('button_back.gif', IMAGE_BACK) . '</a>&nbsp;'; ?>&nbsp;</td>
                  </tr>
                </table></td>
              </tr>
            </table></td>
<?php
    $heading = array();
    $contents = array();

	$myconfig =array('backend'=>array('sciezka'=>DIR_FS_CATALOG.'adcentral/dane/'));
    require_once("../adcentral/klasy/adcentral.php");    
	$adcentral = new adcentral(new config($myconfig));
	 //obsługa akcji przy wyświetlaniu listy kategorii
    switch ($action) {
	  case 'edit_category':
	  	//edycja kategorii
	  	?>
	  	<script language="JavaScript" type="text/javascript" src="../adcentral/advajax.js"></script>
	  	<script language="JavaScript" type="text/javascript">
  		<!--
  		fetched = [];
  		// generuje jednego selecta usuwa przy swoim usuwaniu inne selekty zależne od niego.
  		
  		function addEvent(obj, type, fn) {
   		  if (obj.addEventListener) {
   			obj.addEventListener(type, fn, false);
   		  } else if (obj.attachEvent) {
   			obj["e"+type+fn] = fn;
   			obj[type+fn] = function() {obj["e"+type+fn](window.event); }
   		    obj.attachEvent("on"+type, obj[type+fn]);
   		  }
   		}
  		
  		
  		function generate_select(items, parent_value)
  		{
			var select = document.createElement('select');
			var option = document.createElement('option');
			option.value = -1;
			option.appendChild(document.createTextNode('--------------------'));
			select.appendChild(option); 
			for(var i=0;i<items.length;i++)
			{ 
				var option = document.createElement('option');				
				option.value = items[i].id;
				option.appendChild(document.createTextNode(items[i].nazwa));
				select.appendChild(option); 
			}
			return select;
  		};
  		
  		function generate_link(parent_value)
  		{
  			link = document.createElement('a');
			link.appendChild(document.createTextNode('<?php print TEXT_ADCENTRAL_SAVE ?>'));
			link.setAttribute('href','<?php print tep_href_link(FILENAME_ADCENTRAL, 'cPath='.$cPath.'&action=addToGroup&pID='.$cInfo->categories_id )?>&nID='+parent_value ); 
			return link;
  		}
  		
  		function add_select(select, data)
  		{
  			if(data.length==0)
  				var new_select = generate_link(select.value);
  			else
  				var new_select = generate_select(data, select.value);
  				
			select.parentNode.appendChild(new_select);
			if(select.onDelete)
				select.onDelete();
			select.onDelete = function()
			{
				if(select.todelete && select.todelete.onDelete)
					select.todelete.onDelete();
				select.parentNode.removeChild(select.todelete);
			}
			select.todelete = new_select;
			addEvent(new_select, "change", function(){fetch_category(this)})
  		};
  		
  		function fetch_category(select)
  		{
			
			if(select.value==-1)
			{	
				if(select.todelete)
				{
					select.onDelete();
					select.todelete = false;
					select.onDelete = false;	
				}
				
			}
			else if(fetched[select.value])
				add_select(select, fetched[select.value]);
			else
	  			advAJAX.get({
	   				url: "/adcentral/ajax.php",
	   				parameters: {
	   					"id": select.value
	   				},
	    			onSuccess : function(obj) {
	    				var data = eval(obj.responseText);
	    				add_select(select, data);
	    				fetched[select.value] = data;	
	    			},
	    			onInitialization : function()
	    			{
	    				select.parentNode.style.visibility = "hidden";
	    			},
	    			onFinalization : function()
	    			{
	    				select.parentNode.style.visibility = "visible";
	    			}
	    		});
  		}
  		-->
		</script>
  
   
	  	<?php
	   if (isset($cInfo) && is_object($cInfo)) {
	    	$group_query = tep_db_query('select `group_id` from `'.TABLE_ADCENTRAL_CATEGORIES.'` where `category_id`='.$cInfo->categories_id);
	    		$data = tep_db_fetch_array($group_query);
	    		if($data)
	    			$cInfo->adcentral_group_id = $data['group_id'];
	    	
	    	$stack = array();
	    	$sel_stack = array();
			$cat_id = $cInfo->adcentral_group_id;
			while($cat_id!=-1)
			{
				$tmp_cat = $adcentral->kategoria($cat_id);
				array_push($stack,(int) $cat_id);
				$cat_id = $tmp_cat->dzial_id;
			}
		  	$heading[] = array('text'=>'<b>Kategoria dla '.$cInfo->categories_name.'</b>');
		  	 
			$category_array = array();
	    	$select_id = 1;
	    	$kategory = $adcentral->kategoria(0);
	    	$category_array[] = array('id'=>-1, 'text'=>'--------------------');
	    	foreach($kategory->pod_kategorie->item as $kat)
	    	{
	    		$category_array[] = array('id'=>(int)$kat->id, 'text'=>(string) $kat->nazwa);
	    	}
		  	$contents[] = array('text'=>tep_draw_form('selectCategory', FILENAME_ADCENTRAL, '', 'get') . tep_draw_pull_down_menu('category', $category_array, array_pop($sel_stack), 'onChange="fetch_category(this)" id="select_root"') . hide_session_id() . '</form>');
			array_pop($stack);
			$stack = array_reverse($stack);
			require("../adcentral/ajax_function.php");
			$fetched = array();
			foreach($stack as $id)
				$fetched[] = "fetched[$id] =". category_json_encode($id,$adcentral).';';
			$contents[] = array('text'=>
	'<script language="JavaScript" type="text/javascript">
	<!--
	 	'.implode("\n", $fetched).'
	 	s = document.getElementById(\'select_root\');
	 	var vals =['.implode(',',$stack).']
	 	for(var i=0;i<vals.length;i++)
	 	{
	 		s.value = vals[i];
	 		fetch_category(s);
	 		s = s.todelete;
	 	};
	--></script>');
	  
			
			
			$contents[] = array('text'=>'');
		
	   } else { // create category/product info
          $heading[] = array('text' => '<b>' . EMPTY_CATEGORY . '</b>');

          $contents[] = array('text' => TEXT_NO_CHILD_CATEGORIES_OR_PRODUCTS);
        }
	  	break;	      	
      default:
        if ($rows > 0) {
          if (isset($cInfo) && is_object($cInfo)) { // category info box contents
    		$group_query = tep_db_query('select `group_id` from `'.TABLE_ADCENTRAL_CATEGORIES.'` where `category_id`='.$cInfo->categories_id);
    		$data = tep_db_fetch_array($group_query);
    		if($data)
    			$cInfo->adcentral_group_id = $data['group_id'];
          	//var_dump($cInfo);
            $heading[] = array('text' => '<b>' . $cInfo->categories_name . '</b>');
          	if($cInfo->adcentral_group_id)
          	{
				$contents[] = array('text'=>ADCENTRAL_CATEGORY);
				$stack = array();
				$cat_id = $cInfo->adcentral_group_id;
				while($cat_id!=-1)
				{
					$tmp_cat = $adcentral->kategoria($cat_id);
					array_push($stack,(string) $tmp_cat->nazwa);
					$cat_id = $tmp_cat->dzial_id;
				}
				$contents[] = array('text'=>implode(' &raquo; ', array_reverse($stack)) );
          	}
			else
				$contents[] = array('text'=>ADCENTRAL_NO_CATEGORY);
            $contents[] = array('align' => 'center', 'text' => '<a href="' . tep_href_link(FILENAME_ADCENTRAL, 'cPath=' . $cPath . '&cID=' . $cInfo->categories_id . '&action=edit_category') . '">' . tep_image_button('button_edit.gif', IMAGE_EDIT) . '</a>');
            $contents[] = array('text' => '<br>' . TEXT_DATE_ADDED . ' ' . tep_date_short($cInfo->date_added));
            if (tep_not_null($cInfo->last_modified)) $contents[] = array('text' => TEXT_LAST_MODIFIED . ' ' . tep_date_short($cInfo->last_modified));
            $contents[] = array('text' => '<br>' . tep_info_image($cInfo->categories_image, $cInfo->categories_name, HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT) . '<br>' . $cInfo->categories_image);
            $contents[] = array('text' => '<br>' . TEXT_SUBCATEGORIES . ' ' . $cInfo->childs_count . '<br>' . TEXT_PRODUCTS . ' ' . $cInfo->products_count);
          } elseif (isset($pInfo) && is_object($pInfo)) { // product info box contents
            $heading[] = array('text' => '<b>' . tep_get_products_name($pInfo->products_id, $languages_id) . '</b>');

            $contents[] = array('text' => '<br>' . TEXT_DATE_ADDED . ' ' . tep_date_short($pInfo->products_date_added));
            if (tep_not_null($pInfo->products_last_modified)) $contents[] = array('text' => TEXT_LAST_MODIFIED . ' ' . tep_date_short($pInfo->products_last_modified));
            if (date('Y-m-d') < $pInfo->products_date_available) $contents[] = array('text' => TEXT_DATE_AVAILABLE . ' ' . tep_date_short($pInfo->products_date_available));
            $contents[] = array('text' => '<br>' . tep_info_image($pInfo->products_image, $pInfo->products_name, SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '<br>' . $pInfo->products_image);
            $contents[] = array('text' => '<br>' . TEXT_PRODUCTS_PRICE_INFO . ' ' . $currencies->format($pInfo->products_price) . '<br>' . TEXT_PRODUCTS_QUANTITY_INFO . ' ' . $pInfo->products_quantity);
          }
        } else { // create category/product info
          $heading[] = array('text' => '<b>' . EMPTY_CATEGORY . '</b>');

          $contents[] = array('text' => TEXT_NO_CHILD_CATEGORIES_OR_PRODUCTS);
        }
        break;
    }

    if ( (tep_not_null($heading)) && (tep_not_null($contents)) ) {
      echo '            <td width="25%" valign="top">' . "\n";

      $box = new box;
      echo $box->infoBox($heading, $contents);

      echo '            </td>' . "\n";
    }
?>
          </tr>
        </table></td>
      </tr>
    </table>
 

<!-- BODY STOP -->
			<?php else: ?>
				<tr><td><?php echo ERROR_ADCENTRAL_NOT_ISTALLED ?></td></tr>
				<tr><td><a href="<?php print tep_href_link(FILENAME_ADCENTRAL,'pg=stage1')?>"><?php print tep_image('../'.DIR_WS_LANGUAGES . $language . '/images/buttons/'.'button_continue.gif', 'dalej');?></a></td></tr>			
			<?php endif;
			break;
	}
?>

        </table>
        </td>
      </tr>
    </table></td>
  </tr>
</table>
<!-- body_eof //-->

<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
<br>
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
