<?php
//global $Debug; $Debug=true;
class StoreView extends Slot {

	var $SectionID = 25;
	var $ModuleID = 2;
	var $rootcategory = 0;
	
	function __construct($pquery) {
		parent::__construct($pquery);
	}

	function init() {		  
		global $REGISTRY;
		if (isset($_POST["ajax"]) && $_POST["ajax"] == 'getAddedToCompare' ){
			$responce = array();
			if(isset($_SESSION['compare']))	{
				foreach($_SESSION['compare'] as $item_val) 
					$responce[] = $item_val;
			}
			print json_encode(array( "status" => "success", "link" => "", "html" => $responce ));		
			exit;
		}
		
		if (isset($_POST["ajax"]) && $_POST["ajax"] == 'ajax-form-efq' ){
			if ( $this->validateForm()) {
	   			$this->Action->processEvent($this->SectionID,'sendefq',array($_POST),$this);
				print '{"status":"success"}'; 
				exit;
			} else {
				print '{"status":"failed"}'; 
				exit;
			}
		}
		if (isset($_POST["ajax"]) && $_POST["ajax"] == 'ajax-form-rfq' ){
			if ( $this->validateForm()) {
	   			$this->Action->processEvent($this->SectionID,'sendrfq',array($_POST),$this);
				print '{"status":"success"}'; 
				exit;
			} else {
				print '{"status":"failed"}'; 
				exit;
			}
		}
		
		if (isset($_POST["ajax"]) && $_POST["ajax"] == 'compare' ){
			if ( $this->validateForm()) {
		        $beingadded=$this->Db->SelectAny("select c.ownerid from category c left join categorylineitem cl on c.id = cl.ownerid where c.ownerid <>27 and cl.item =".$_POST["id"]);
		        if(isset($_SESSION['compare'])) {
					foreach($_SESSION['compare'] as $value) {
			        	$existing=$this->Db->SelectAny("select c.ownerid from category c left join categorylineitem cl on c.id = cl.ownerid where c.ownerid <>27 and cl.item =".$value);
						if (    strcmp (   $beingadded[0]['ownerid'], $existing[0]['ownerid']) != 0 ) {
							print '{"status":"failed","link":"","reason":"You can only compare products from one category"}'; 
							exit;
						}
					}
		        }
   				if(isset($_SESSION['compare']))	$_SESSION['compare'][$_POST["id"]] = $_POST["id"];	else $_SESSION['compare'] = array ($_POST["id"] => $_POST["id"]); 
					print '{"status":"success","link":"","html":'.count($_SESSION['compare']).'}'; 
					exit;
				} else {
					print '{"status":"failed"}'; 
					exit;
				}
		}
		
		
		if(!empty($this->ID)) {
			$this->Action->processEvent($this->SectionID,'getcat_for_acc',array(),$this);
			$this->acc_category = $this->PreparedTemplates['category'];
			$this->Action->processEvent($this->SectionID,'getcart_status',array(),$this);
			if ($this->ID != 27 && strpos($_SERVER['REQUEST_URI'], 'full-accessories-chart') === false ) $this->Action->processEvent($this->SectionID,'open_chart',array('parent' => $this->ID),$this);
				else $this->Action->processEvent($this->SectionID,'open_full_chart',array('parent' => $this->ID),$this);
			if(!empty($this->PreparedTemplates['_error'])) header('Location: '.$this->Home.'/Units'.$this->SID);
		}else header('Location: '.$this->Home.'/Units'.$this->SID);
		
		if ($this->ID != 27 && strpos($_SERVER['REQUEST_URI'], 'full-accessories-chart') === false) $this->PreparedTemplates = $this->Action->getTemplate($this->SectionID, 'open_chart');
				else $this->PreparedTemplates = $this->Action->getTemplate($this->SectionID, 'open_full_chart');
		$this->generation = $this->Action->Server->getGuide('generation');
		$this->brand = $this->Action->Server->getGuide('brand');
		$this->rate = $this->Action->Server->getGuide('rate');
		$this->core = $this->Action->Server->getGuide('core');
		$this->lens = $this->Action->Server->getGuide('lens');
		$this->TempFillEls['category_part'] = array();
		$this->TempFillEls['category_part'] += $this->makeMainItems($this->PreparedTemplates);
		
    if($this->PreparedTemplates['parent']['cat_type']!=1) $this->TempFillEls['rss'] = makeLink($this->Home.implode('/',$this->Target).'.xml','RSS',array(),'','','RSS Feed','target="_blank"');
		$this->setSchemeTemplate($this->Scheme);
	}

	function fillElements() {
	}

	function validateForm() { 			
		switch($_POST["ajax"]) {
			case 'ajax-form-efq': {
				if( !validate($_POST['efq-name']) ||
					!is_Email($_POST['efq-email']) ||
					!is_Email($_POST['efq-confeamail']) ) return FALSE;
			break;
			}
			case 'ajax-form-rfq': {
				if( !validate($_POST['rfq-name']) ||
					!is_Email($_POST['rfq-email']) ||
					!is_Email($_POST['rfq-confemail']) ) return FALSE;
			break;
			}
			case 'compare': {
				if( !isset($_POST['id']) ||	!validate(intval($_POST['id'])) ) return FALSE;
			break;
			}
			default: {
			break;
			}
		}
		if(sizeof($this->errors) > 0) return FALSE;
		return TRUE;
	}
	
	function getCategoryPath($id) {
		global $Paths;
		if(empty($Paths)) {
			$query = 'SELECT id, sys_name, ownerid FROM category';
			$selected = $this->Db->SelectAny($query);
			foreach($selected as $value)
				$Paths[$value['id']] = array(
					'path' => $value['sys_name'],
					'parent' => $value['ownerid'],
				);
		}
		$p = '';
		while(1){
			if(empty($Paths[$id])) return null;
			if(empty($Paths[$id]['parent']) || $Paths[$id]['parent'] == 1 ) return '/'.$Paths[$id]['path'].$p;
			$p = '/'.$Paths[$id]['path'].$p;
			$id = $Paths[$id]['parent'];
		}
	}

	function makeMainItems($prepared,$flag = true) {
		global $REGISTRY;
		$ret_items = array();
		$make_sys_name = true;
//printArray($prepared ); exit();
		foreach($prepared as $key => $val) {
			if ($val['ownerid'] == 27 ) $val['cat_type'] = 1;
			if (strpos($_SERVER['REQUEST_URI'], 'full-accessories-chart') !== false ) $val['cat_type'] = 3;			
			switch($key) {
				case 'parent': {
					// set description, name, color
					$this->TempFillEls['name'] = $val['name'];
					$this->TempFillEls['Description'] = validate(trim($val['description']))? array(array('description' => $val['description'])) : array();
					$this->TempFillEls['color'] = $val['color']['name'];
					$this->TempFillEls['return_url'] = $this->Home.$REGISTRY['Request']['RawTarget'];
					// set links
					if(array_key_exists('links', $val) && is_array($val['links']) && count($val['links'])) {
						$links = array();
						$link_type = array ('1' => 'Scope Applications', '2' => 'Featured Retailers');
						foreach($val['links'] as $k => $v) {
							$links[$v['linktype']]['linkitems'][$v['id']] = array(
								'link' => $v['link'],
								'url' => $v['js']? 'javascript:;' : $v['url'],
								'onclick' => $v['js']? 'onclick="window.open(\''.$v['url'].'\',\'Link\')"' : '',
								'text1' => $v['linktype']==2? 'Buy ' : '',
								'text2' => $v['linktype']==2? ' from '.(!empty($v['description'])? $v['description'] : 'Liburdi') : '',
							);
						}
						if(sizeof($links)) {
							ksort($links);
							foreach($links as $lk => $lv) {
								$links[$lk]['type_name'] = $val['color']['label'].' '.$link_type[$lk];
								ksort($links[$lk]);
							}
						}
						$this->TempFillEls['Links'] = !empty($links)? array(array('links' => $links)) : array();
					}
					if(empty($this->TempFillEls['Links'])) $this->TempFillEls['Links'] = array(array());
					if(!in_array($val['ownerid'],array(0,1))) $this->TempFillEls['backs'][0]['back'] = $this->getCategoryPath($val['ownerid']);
					// check on category, where categorylineitems in parent
					if(count($prepared) != 1) break;
					$make_sys_name = false;
					// ------------
				}
				default: {
					if($val['cat_type']==3 && count($prepared) > 2 && $flag) {
						$this->TempFillEls['subcategories'][0]['subcategory'][$key]['subcat_name'] = makeLink($this->Home.$this->getCategoryPath($val['id']),$val['name']);
						$this->TempFillEls['subcategories'][0]['subcategory'][$key]['color'] = $val['color']['value'];
					}
					if(array_key_exists('subcat', $val)) {
						if(!empty($ret_items) && $val['cat_type']==3) continue;
						else {
							$ret_items_temp = $this->makeMainItems($val['subcat'],false);
							foreach($ret_items_temp as $k_temp => $v_temp)
								$ret_items[sizeof($ret_items)+1] = $ret_items_temp[$k_temp];
							continue;
						}
					}
			          // Get parent category
			          $cat=explode('/',$_SERVER['REQUEST_URI']);
			          $this->TempFillEls['parent'][0]['path_to_parent']=$this->Home.'/'.$cat[1];
			          $selected=$this->Db->SelectAny("select name from category where sys_name like '".$cat[1]."' and ownerid='1';");
		        	  $this->TempFillEls['parent'][0]['name']=$selected[0]['name'];
					switch($val['cat_type']) {		//Category
						case 0: {
							if(empty($this->colors)) {
								$this->colors = $this->Db->SelectAny('select *, lower(replace(label,\' \',\'-\')) as label from color');
								foreach($this->colors as $value)
									$this->TempFillEls['js_types'][] = array(
										'id' => $value['id'],
										'name' => $value['label'],
									);
							}
							$items = array();
							foreach($val['categorylineitems'] as $item_val) {
								//---------Set Sort Order
								if (isset($_GET["sort"])){
									//printArray($item_val['item']);exit;
									switch($_GET["sort"]) {
										case 'price': {
												$price_range = '';							
												foreach($val['price_range'] as $key_pr => $val_pr )
													if ($item_val['item']['prices'][0]['value'] >= $val_pr['min'] && $item_val['item']['prices'][0]['value'] <= $val_pr['max'] ) {
														$item_val['item']['generation']['sort_order'] =  $val_pr['sort_order'];
														$price_range = $val_pr['name'];
														break;
													}
												$items[  $item_val['item']['generation']['sort_order']  ]['generation'] = array(array('name' => '$'.$price_range    ));
										break;
										}
										case 'generation': {
												$items[  $item_val['item']['generation']['sort_order']  ]['generation'] = $item_val['item']['generation']['id']==10? array() : array(array('name' => 'GENERATION '.@$this->generation[$item_val['item']['generation']['id']].($item_val['item']['generation']['gen_type']==2? ' International' : '')));						
										break;
										}
										case 'rate': {
												$item_val['item']['generation']['sort_order'] =  $item_val['item']['rate'];
												$items[  $item_val['item']['generation']['sort_order']  ]['generation'] = array(array('name' =>  'IMAGE FRAME RATE '.@$this->rate[$item_val['item']['rate']['id']] ));						
										break;
										}
										case 'core': {
												$item_val['item']['generation']['sort_order'] =  $item_val['item']['core'];
												$items[  $item_val['item']['generation']['sort_order']  ]['generation'] = array(array('name' =>  'CORE TECHNOLOGY '.@$this->core[$item_val['item']['core']['id']] ));						
										break;
										}
										case 'lens': {
												$item_val['item']['generation']['sort_order'] =  $item_val['item']['lens'];
												$items[  $item_val['item']['generation']['sort_order']  ]['generation'] = array(array('name' =>  'LENS '.@$this->lens[$item_val['item']['lens']['id']] ));						
										break;
										}
										case 'brand': {
												$item_val['item']['generation']['sort_order'] =  $item_val['item']['brand'];
												$items[  $item_val['item']['generation']['sort_order']  ]['generation'] = array(array('name' => @$this->brand[$item_val['item']['brand']]));						
										break;
										}
									}
									if ($this->PreparedTemplates['parent']['ownerid'] == 56) { // thermal imaging
											$this->TempFillEls['Thermal_Vision'][0]['Thermal_Vision_sort_'.$_GET["sort"]] = array(array());
										} 
										elseif ($item_val['ownerid'] == 52 )		//international  thermal
													$this->TempFillEls['International_Thermal_Vision'][0]['International_Thermal_Vision_sort_'.$_GET["sort"]] = array(array());
										
										
										elseif ($this->PreparedTemplates['parent']['ownerid'] == 33 )		//international and NOT thermal
													$this->TempFillEls['International_Vision'][0]['International_Vision_sort_'.$_GET["sort"]] = array(array());
												else		 //Night_Vision
													$this->TempFillEls['Night_Vision'][0]['Night_Vision_sort_'.$_GET["sort"]] = array(array());
								} else {  
										if (($this->PreparedTemplates['parent']['ownerid'] == 56)) { // thermal imaging
												$item_val['item']['generation']['sort_order'] =  $item_val['item']['core'];
												$items[  $item_val['item']['generation']['sort_order']  ]['generation'] = array(array('name' => 'CORE TECHNOLOGY  '.@$this->core[$item_val['item']['core']['id']]  ));
												$this->TempFillEls['Thermal_Vision'][0]['Thermal_Vision_sort_core'] = array(array());
										} elseif ( $item_val['ownerid'] == 52 ){		//international thermal
													$item_val['item']['generation']['sort_order'] =  $item_val['item']['core'];
													$items[  $item_val['item']['generation']['sort_order']  ]['generation'] = array(array('name' => 'CORE TECHNOLOGY  '.@$this->core[$item_val['item']['core']['id']]));
													$this->TempFillEls['International_Thermal_Vision'][0]['International_Thermal_Vision_sort_core'] = array(array());
										  } elseif ( $this->PreparedTemplates['parent']['ownerid'] == 33 ){		//international and NOT thermal
													$item_val['item']['generation']['sort_order'] =  $item_val['item']['brand'];
													$items[  $item_val['item']['generation']['sort_order']  ]['generation'] = array(array('name' => @$this->brand[$item_val['item']['brand']]));
													$this->TempFillEls['International_Vision'][0]['International_Vision_sort_brand'] = array(array());
										  }
												else {		 //Night_Vision
													$items[  $item_val['item']['generation']['sort_order']  ]['generation'] = array(array('name' => 'Generation '.@$this->generation[$item_val['item']['generation']['id']]));
													$this->TempFillEls['Night_Vision'][0]['Night_Vision_sort_generation'] = array(array());
												}
								}
								//---------		
								$id_path = $item_val['item']['id'];
								$id_path2 = $item_val['item']['id'];
								foreach($item_val['item']['files'] as $file_val) {
									if($file_val['filetype']==1) {
										$id_path = !empty($file_val['image_link'])? $file_val['image_link'] : $item_val['item']['id'];
									}
									if($file_val['filetype']==2) {
										$id_path2 = !empty($file_val['image_link'])? $file_val['image_link'] : $item_val['item']['id'];
									}
								}
								$i_path = file_exists($this->ImagePath.'/products/'.$id_path.'/middle.jpg')? '/products/'.$id_path.'/middle.jpg' : '/products/NA/prew.gif';
								$i_path2 = file_exists($this->ImagePath.'/products/'.$id_path2.'/middle.jpg')? '/products/'.$id_path2.'/middle.jpg' : '/products/NA/middle.jpg';
								$image = makeImage($this->ImagePath.$i_path,$this->ImageWPath.$i_path,(!empty($item_val['item']['nav_name'])? $item_val['item']['nav_name'] : $item_val['item']['name']));
								$items[  $item_val['item']['generation']['sort_order']  ]['lineitems'] [ $item_val['item']['id'] ] = array(
									'name' => makeLink($item_val['item']['url'],$item_val['item']['name'],array(),'','class="name"',(!empty($item_val['item']['nav_name'])? $item_val['item']['nav_name'] : $item_val['item']['name'])),
									'nav_name' => !empty($item_val['item']['nav_name'])? $item_val['item']['nav_name'] : $item_val['item']['name'],
									'id' => $item_val['item']['id'],
									'image' => makeLink($item_val['item']['url'],$image,array(),'','',(!empty($item_val['item']['nav_name'])? $item_val['item']['nav_name'] : $item_val['item']['name'])),
									'price' => '0.00',
									'image_link' => $this->ImageWPath.$i_path2,
									'path' => $item_val['item']['path'],
									'type' => $item_val['item']['color'],
									//'display_compare' => !isset($_SESSION['compare'][$item_val['item']['id']])?'block':'none',
									//'display_compare_added' => isset($_SESSION['compare'][$item_val['item']['id']])?'inline':'none',
									'callforquote' => $item_val['item']['callforquote'],
									'pid' => $item_val['item']['pid'],
									'name_text' => $item_val['item']['name'],
								    'sort_order' => $item_val['sort_order'],
								);
								
								foreach($item_val['item']['prices'] as $price_val) {
									if($price_val['current']) {
										$items[$item_val['item']['generation']['sort_order']]['lineitems'][$item_val['item']['id']]['price'] = (double)$price_val['value'];
										break;
									}
								}
							}
							if(!empty($items)) {
								ksort($items);
								foreach($items as $item_key => $item_val) {
									uasort($items[$item_key]['lineitems'],'by_price2');
									foreach($item_val['lineitems'] as $item_key1 => $item_val1) {
										if ($items[$item_key]['lineitems'][$item_key1]['callforquote'] == 1)	{	
											$items[$item_key]['lineitems'][$item_key1]['price_efq'] = array(array('name' => $items[$item_key]['lineitems'][$item_key1]['name_text'],'pid' => $items[$item_key]['lineitems'][$item_key1]['pid'],	));
											$items[$item_key]['lineitems'][$item_key1]['price'] = '';
										} else {
												if (!empty($items[$item_key]['lineitems'][$item_key1]['price'])	&& is_numeric($items[$item_key]['lineitems'][$item_key1]['price']) && (double)$items[$item_key]['lineitems'][$item_key1]['price'] > 0) {
															$items[$item_key]['lineitems'][$item_key1]['price'] = "$".number_format($items[$item_key]['lineitems'][$item_key1]['price'], 2, '.',',');
															$items[$item_key]['lineitems'][$item_key1]['price_addtocart'] = array(array( 'id' => $items[$item_key]['lineitems'][$item_key1]['id'] ));
												}	else $items[$item_key]['lineitems'][$item_key1]['price'] = ''; 																											
										  }
									}
								}
							}
							if(!empty($items)) {
								$ret_items[$val['id']]['Header_name'] = ($make_sys_name)? array(array('header_name' => $val['name'])) : array();
								$ret_items[$val['id']]['color'] = $val['color']['name'];
								$ret_items[$val['id']]['items'] = $items;
							}
							$this->Scheme = 'default';
							break;
						}
						case 1: {	// ----------------------------------------ACCESSORIES-------------------------------
							$items = array();
							foreach($val['categorylineitems'] as $item_key => $item_val) {
								$id_path = $item_val['item']['id'];
								foreach($item_val['item']['files'] as $file_val) {
									if($file_val['filetype']==8) {
										$id_path = !empty($file_val['image_link'])? $file_val['image_link'] : $item_val['item']['id'];
									}
								}
								$i_path = file_exists($this->ImagePath.'/products/'.$id_path.'/prew.jpg')? '/products/'.$id_path.'/prew.jpg' : '/products/NA/middle.png';
								$i_path_big = file_exists($this->ImagePath.'/products/'.$id_path.'/middle.jpg')? '/products/'.$id_path.'/middle.jpg' : '';
								
								$items[$item_key] = array(
									'name' => $item_val['item']['name'],
									'image' =>  ($i_path_big =='')? makeImage($this->ImagePath.$i_path,  $this->ImageWPath.$i_path,  $item_val['item']['name'],'',array(),  0, array(115,82) ):
																	makeLink($this->ImageWPath.$i_path_big, 
																	makeImage($this->ImagePath.$i_path,  $this->ImageWPath.$i_path,  $item_val['item']['name'],'',array(),  0, array(115,82)),
																	array(),
																	'',
																	' class = "fancy" '),
									'id' => $item_val['item']['id'],
									'color' => $val['color']['value'],
									'desc' => $item_val['item']['full_desc'],
									'pid' => $item_val['item']['pid'],
									'return_url' => $this->Home.$REGISTRY['Request']['RawTarget']
								);
								// get price
								$items[$item_key]['price'] = ''; // default
								foreach($item_val['item']['prices'] as $price_val)
									if(!empty($price_val['value']) && (double)$price_val['value'] > 0.01) {
										$items[$item_key]['price'] = '$'.number_format($price_val['value'],2,'.',',');
										$items[$item_key]['google_price'] = number_format($price_val['value'],2,'.','');
										$items[$item_key]['sort_price'] = floatval($price_val['value']);
									}
								if(empty($items[$item_key]['price'])) {
									unset($items[$item_key]);
									continue;
								}
								if ($item_val['item']['callforquote'] == 1 || $item_val["ownerid"] == 21 )	{	
											$items[$item_key]['price_efq'] = array(array('name' => $item_val['item']['name'],'pid' => $item_val['item']['pid'],	));
											$items[$item_key]['price'] = '';
										} else {
												if (!empty( $items[$item_key]['google_price'])&& is_numeric($items[$item_key]['google_price']) && (double)$items[$item_key]['google_price'] > 0) {
															$items[$item_key]['price_addtocart'] = array(array( 'id' => $item_val['item']['id'] ));
												}	else $items[$item_key]['price'] = ''; 																											
										  }
								// get applicable_items
								if(!empty($item_val['item']['applicableitems'])) { 	
									foreach($item_val['item']['applicableitems'] as $ap_val) {
										$items[$item_key]['applic'][0]['applicable'][] = array(
											'ap_name' => $ap_val['name'],
											'ap_link' => $ap_val['url'],
										);
									}
								}
								if(count($item_val['item']['applicableitems']) > 3 ) 
										$items[$item_key]['applic'][0]['applic_minimize']= array(array());
							}
							if(!empty($items)) {
								$ret_items[$val['id']]['Header_name'] = ($make_sys_name)? array(array('header_name' => $val['name'])) : array();
								$ret_items[$val['id']]['color'] = $val['color']['name'];
								$ret_items[$val['id']]['items'] = $items;
							}
							// END ACCESSORIES
							$this->Scheme = 'accessories';
							break;
						}
						case 2: {
							$items = array();
							foreach($val['categorylineitems'] as $item_val) {
								
								$id_path = $item_val['item']['id'];
								foreach($item_val['item']['files'] as $file_val) {
									if($file_val['filetype']==8) {
										$id_path = !empty($file_val['image_link'])? $file_val['image_link'] : $item_val['item']['id'];
									}
								}
								$i_path = file_exists($this->ImagePath.'/products/'.$id_path.'/middle.png')? '/products/'.$id_path.'/middle.png' : '/products/NA/middle.png';
								$image = makeImage($this->ImagePath.$i_path,$this->ImageWPath.$i_path,(!empty($item_val['item']['nav_name'])? $item_val['item']['nav_name'] : $item_val['item']['name']));
								$items[$item_val['item']['id']] = array(
									'name' => makeLink($item_val['item']['url'],$item_val['item']['name'],array(),'','',(!empty($item_val['item']['nav_name'])? $item_val['item']['nav_name'] : $item_val['item']['name'])),
									'id' => $item_val['item']['id'],
									'image' => makeLink($item_val['item']['url'],$image,array(),'','',(!empty($item_val['item']['nav_name'])? $item_val['item']['nav_name'] : $item_val['item']['name'])),
									'calc_price' => '0.00',
									'price' => '0.00',
									'price2' => '0.00',
									'price3' => '0.00',
									'generation' => $item_val['item']['generation']['id']==10? '' : @$this->generation[$item_val['item']['generation']['id']].($item_val['item']['generation']['gen_type']==2? ' International' : ''),
									'product_class' => $item_val['item']['product_class'],
									'pid' => $item_val['item']['pid'],
									'url' => $item_val['item']['url'],
									'desc' => substr(strip_tags($item_val['item']['full_desc']),0,115).'...',
								);
								
								if (!empty($item_val['item']['productlineitems']))
								{
							
									foreach($item_val['item']['productlineitems'] as $acc_key => $acc_val) 
										$items[$item_val['item']['id']]['optional'][0]['optionalacc'][$acc_key] = array(
											'uid' => $acc_val['lineitem']['pid'],
											'name' => makeLink($this->Home.$this->getCategoryPath($this->acc_category),$acc_val['lineitem']['name'],array(),$acc_val['lineitem']['id'],'',$acc_val['lineitem']['name']),
											'acc_price' => ((!empty($acc_val['lineitem']['prices'][0]['value']) && $acc_val['lineitem']['prices'][0]['value'] != 'n/a'))? '$'.number_format($acc_val['lineitem']['prices'][0]['value'], 2, '.','') : 'n/a',
										);
									
									$items[$item_val['item']['id']]['optional_slot']= array(array( ));
								}
								
								if($item_val['item']['grade_tube'] == 1 ) $items[$item_val['item']['id']]['grade_tube']= array(array( ));
								
								if(!empty($item_val['item']['shipcosts'])) {
									foreach($item_val['item']['shipcosts'] as $sh_val) {
										$this->TempFillEls['google_ship'][$item_val['item']['id']]['ship_items'][] = array(
											'id' => $item_val['item']['id'],
											'number' => $sh_val['type']['id'],
											'shipping_price' => number_format($sh_val['value'],2,'.','')
										);
									}
								}
								$this->TempFillEls['calculator'][$item_val['item']['id']]['name'] = $item_val['item']['name'];
								$this->TempFillEls['calculator'][$item_val['item']['id']]['id'] = $item_val['item']['id'];
								$this->TempFillEls['js_calc'][$item_val['item']['id']]['id'] = $item_val['item']['id'];
								$this->TempFillEls['google_acs'][$item_val['item']['id']] = 
									$this->TempFillEls['paypal_acs'][$item_val['item']['id']] = 
										array(
											'id' => $item_val['item']['id'],
											'name' => $item_val['item']['name']
										);
								foreach($item_val['item']['prices'] as $price_val) {
									if($price_val['current']) {
										$items[$item_val['item']['id']]['price'] = (double)$price_val['value'];
										$this->TempFillEls['calculator'][$item_val['item']['id']]['price'] = (double)$price_val['value'];
									}
									else $items[$item_val['item']['id']]['price2'] = (double)$price_val['value'];
								}
							}
							if(!empty($items)) {
								uasort($items,'by_price2');
								uasort($this->TempFillEls['calculator'],'by_price2');
								foreach($items as $item_key => $item_val) {
									$items[$item_key]['Prices'][0]['price'] = !empty($item_val['price']) && is_numeric($item_val['price']) && (double)$item_val['price'] > 0? array(array('value' => "$".number_format($item_val['price'], 2, '.',' '))) : array(array('value' => "Call for quote"));
									$items[$item_key]['Prices'][0]['price2'] = !empty($item_val['price2']) && is_numeric($item_val['price2']) && (double)$item_val['price2'] > 0? array(array('value' => "$".number_format($item_val['price2'], 2, '.',' '))) : array();
									$items[$item_key]['Prices'][0]['price3'] = !empty($item_val['price']) && is_numeric($item_val['price']) && (double)$item_val['price'] > 0 && !empty($item_val['price2']) && is_numeric($item_val['price2']) && (double)$item_val['price2'] > 0? array(array('value' => "$".number_format($item_val['price2'] - $item_val['price'], 2, '.',' '))) : array();
									$this->TempFillEls['calculator'][$item_key]['calc_price'] = !empty($item_val['price']) && is_numeric($item_val['price']) && (double)$item_val['price'] > 0? "$".number_format($item_val['price'], 2, '.','') : '0.00';
									$items[$item_key]['button'] = !empty($item_val['price']) && is_numeric($item_val['price']) && (double)$item_val['price'] > 0? array(array('calc_price' => "$".number_format($item_val['price'], 2, '.',''),'id' => $item_key)) : array();
									if(!empty($item_val['price']) && is_numeric($item_val['price']) && (double)$item_val['price'] > 0) {
										$this->TempFillEls['google_acs'][$item_key]['google_price'] = 
											$this->TempFillEls['paypal_acs'][$item_key]['google_price'] = 
												number_format($item_val['price'], 2, '.','');
									}
									else {
										unset($this->TempFillEls['google_acs'][$item_key]);
										unset($this->TempFillEls['paypal_acs'][$item_key]);
										unset($this->TempFillEls['google_ship'][$item_key]);
									}
								}
							}
							if(!empty($items)) {
								$ret_items[$val['id']]['Header_name'] = ($make_sys_name)? array(array('header_name' => $val['name'],'color' => $val['color']['name'])) : array();
								$ret_items[$val['id']]['color'] = $val['color']['name'];
								$ret_items[$val['id']]['items'] = $items;
							}
							$this->Scheme = 'sale';
							break;
						}
						case 3: {
							if(empty($ret_items)) {
								$items = array();
								foreach($val['categorylineitems'] as $item_val) {
									$id_path = $item_val['item']['id'];
									foreach($item_val['item']['files'] as $file_val) {
										if($file_val['filetype']==1)
											$id_path = !empty($file_val['image_link'])? $file_val['image_link'] : $item_val['item']['id'];
									}
									$i_path = file_exists($this->ImagePath.'/products/'.$id_path.'/middle.jpg')? '/products/'.$id_path.'/middle.jpg' : '/products/NA/prew.gif';
									$image = makeImage($this->ImagePath.$i_path,$this->ImageWPath.$i_path, (!empty($item_val['item']['nav_name'])? $item_val['item']['nav_name'] : $item_val['item']['name']), '',array(),  0, array(115)    );
									$items[$item_val['item']['id']] = array(
										'name' => $item_val['item']['name'],
										'id' => $item_val['item']['id'],
										'pid' => !empty($item_val['item']['pid'])? "PN: ".$item_val['item']['pid']:'',   //$item_val['item']['pid'],
										'image' => $image,
										'link' => $item_val['item']['url'],
										'price' => '0.00',
									);
									foreach( $item_val['item']['productlineitems'] as $acc_val) {
										$grid[$item_val['item']['id']][$acc_val['lineitem']['id']] = 1;
										$id_path = $acc_val['lineitem']['id'];
										foreach($acc_val['lineitem']['files'] as $file_val) {
											if($file_val['filetype']==1)
												$id_path = !empty($file_val['image_link'])? $file_val['image_link'] : $acc_val['lineitem']['id'];
										}
										$i_path = file_exists($this->ImagePath.'/products/'.$id_path.'/prew.jpg')? '/products/'.$id_path.'/prew.jpg' : '/products/NA/prew.gif';
										$image = makeImage($this->ImagePath.$i_path,  $this->ImageWPath.$i_path,  $acc_val['lineitem']['name'], '',array(),  0, array(115,82)     );
										$accessories[$acc_val['lineitem']['id']] = array(
											'acc_name' => $acc_val['lineitem']['name'],
											'acc_id' => $acc_val['lineitem']['id'],
											'acc_pid' => !empty($acc_val['lineitem']['pid'])? "PN: ".$acc_val['lineitem']['pid']:'',
											'acc_link' => $this->Home.$this->getCategoryPath($this->acc_category).'/'.$this->Target[count($this->Target)-1].'#acc-'.$acc_val['lineitem']['id'],
											'acc_image' => $image,
											'price' => !empty($acc_val['lineitem']['prices'][0]['value'])? (double)$acc_val['lineitem']['prices'][0]['value'] : '0.00',
										);
									}
									foreach($item_val['item']['prices'] as $price_val) {
										if($price_val['current']) {
											$items[$item_val['item']['id']]['price'] = (double)$price_val['value'];
											break;
										}
									}
								}
								$i = 0;
								if(!empty($items)) uasort($items,'by_price2');
								if(!empty($accessories)) uasort($accessories,'by_acc_name');
								foreach(array_keys($items) as $i_id) {
									$crosses[$i_id]['class_id'] = ($i%2)?'':' class="odd" '; // ($i%2)+1;
									foreach(array_keys($accessories) as $as_id) {
										$crosses[$i_id]['line'][$as_id]['dot_image'] =  in_array($as_id,array_keys($grid[$i_id]))? '<img alt="" src="/img/icons_galka.png">': '&ndash;';
									}
									$i++;
								}
								if(!empty($items)) {
									$ret_items[0]['items'] = $items;
									$ret_items[0]['accessories'] = $accessories;
									$ret_items[0]['grid'] = $crosses;
									$ret_items[0]['total_acc'] = count($accessories)*150;
									$selected = $this->Db->SelectAny('select name from category where id = '.$this->ID);									
									$ret_items[0]['selected_acc'] = str_replace('Accessories','',$selected[0]['name']);
									$ret_items[0][$this->ID] = array(array());
								}
							}
							$this->Scheme = 'grid';
							break;
						}
						case 4: {
							// ACCESSORIES ARCHIVE
							$items = array();
							foreach($val['categorylineitems'] as $item_key => $item_val) {
								$id_path = $item_val['item']['id'];
								foreach($item_val['item']['files'] as $file_val) {
									if($file_val['filetype']==8) {
										$id_path = !empty($file_val['image_link'])? $file_val['image_link'] : $item_val['item']['id'];
									}
								}
								$i_path = file_exists($this->ImagePath.'/products/'.$id_path.'/middle.png')? '/products/'.$id_path.'/middle.png' : '/products/NA/middle.png';
								$items[$item_key] = array(
									'name' => $item_val['item']['name'],
									'image' => makeImage($this->ImagePath.$i_path,$this->ImageWPath.$i_path,$item_val['item']['name']),
									'id' => $item_val['item']['id'],
									'color' => $val['color']['value'],
									'desc' => $item_val['item']['full_desc'],
									'pid' => $item_val['item']['pid'],
									'return_url' => $this->Home.$REGISTRY['Request']['RawTarget'],
								);
								// get price
								$items[$item_key]['price'] = ''; // default
								$items[$item_key]['sort_price'] = ''; // default
								foreach($item_val['item']['prices'] as $price_val)
									if(!empty($price_val['value']) && is_numeric($price_val['value']) && (double)$price_val['value'] > 0) {
										$items[$item_key]['price'] = 'Price $<strong>'.number_format($price_val['value'],2,'.',' ').'</strong>';
										$items[$item_key]['sort_price'] = floatval($price_val['value']);
									}
								// -----------
								// get applicable_items
								foreach($item_val['item']['applicableitems'] as $ap_val) {
									$items[$item_key]['Applicable'][0]['applicable'][] = array(
										'ap_name' => $ap_val['product']['name'],
										'ap_link' => $ap_val['product']['url'],
									);
								}
							}
							// sort by price
							if(sizeof($items) > 1) usort($items,'sortCompare');
							if(!empty($items)) {
								$ret_items[$val['id']]['Header_name'] = ($make_sys_name)? array(array('header_name' => $val['name'])) : array();
								$ret_items[$val['id']]['color'] = $val['color']['name'];
								$ret_items[$val['id']]['items'] = $items;
							}
							// ACCESSORIES ARCHIVE
							$this->Scheme = 'accessories_archive';
							break;
						}
						case 5: {
							$items = array();
							foreach($val['categorylineitems'] as $item_val) {
								if(count($item_val['item']['files']) < 2) continue;
								$id_path = $item_val['item']['id'];
								$id_path_ss = $item_val['item']['id'];
								$id_path_ug = $item_val['item']['id'];
								foreach($item_val['item']['files'] as $file_val) {
									switch($file_val['filetype']) {
										case 1: {
											$id_path = !empty($file_val['image_link'])? $file_val['image_link'] : $item_val['item']['id'];
											break;
										}
										case 6: {
											$id_path_ss = $item_val['item']['id'];
											break;
										}
										case 7: {
											$id_path_ug = $item_val['item']['id'];
											break;
										}
									}
								}
								$i_path = file_exists($this->ImagePath.'/products/'.$id_path.'/middle.jpg')? '/products/'.$id_path.'/middle.jpg' : '/products/NA/prew.gif';
								$i_path_ss = file_exists($this->ImagePath.'/products/'.$id_path_ss.'/ss.pdf')? '/ATNNightVisionPDF/'.$item_val['item']['path'].'/'.$item_val['item']['path'].'_UserGuide.pdf' : '';
								$i_path_ug = file_exists($this->ImagePath.'/products/'.$id_path_ug.'/ug.pdf')? '/ATNNightVisionPDF/'.$item_val['item']['path'].'/'.$item_val['item']['path'].'_SpecSheet.pdf' : '';
								$image = makeImage($this->ImagePath.$i_path,$this->ImageWPath.$i_path,(!empty($item_val['item']['nav_name'])? $item_val['item']['nav_name'] : $item_val['item']['name']));
								$items[$item_val['item']['generation']['sort_order']]['generation'] = $item_val['item']['generation']['id']==10? array() : array(array('name' => @$this->generation[$item_val['item']['generation']['id']].($item_val['item']['generation']['gen_type']==2? ' International' : '')));
								$items[$item_val['item']['generation']['sort_order']]['lineitems'][$item_val['item']['id']] = array(
									'name' => makeLink($item_val['item']['url'],$item_val['item']['name'],array(),'','',(!empty($item_val['item']['nav_name'])? $item_val['item']['nav_name'] : $item_val['item']['name'])),
									'nav_name' => !empty($item_val['item']['nav_name'])? $item_val['item']['nav_name'] : $item_val['item']['name'],
									'id' => $item_val['item']['id'],
									'image' => makeLink($item_val['item']['url'],$image,array(),'','',(!empty($item_val['item']['nav_name'])? $item_val['item']['nav_name'] : $item_val['item']['name'])),
									'ss' => !empty($i_path_ss)? array(array('value' => makeLink($i_path_ss,'Spec Sheet'))) : array(),
									'ug' => !empty($i_path_ug)? array(array('value' => makeLink($i_path_ug,'User Guide'))) : array(),
									'no_pdf' => empty($i_path_ug) || empty($i_path_ss)? array(array('padding' => empty($i_path_ug)? 6: 0)) : array(),
								);
							}
							ksort($items);
							if(!empty($items)) {
								$ret_items[$val['id']]['Header_name'] = ($make_sys_name)? array(array('header_name' => $val['name'])) : array();
								$ret_items[$val['id']]['color'] = $val['color']['name'];
								$ret_items[$val['id']]['items'] = $items;
							}
							$this->Scheme = 'download';
							break;
						}
					}
				}
			}
		}
		return $ret_items;
	}
}
?>