<?php

if(!isset($_SESSION['sel_market'])) $_SESSION['sel_market'] =0;
if(!isset($_SESSION['sel_target'])) $_SESSION['sel_target'] =0;
if(!isset($_SESSION['sel_target_name'])) $_SESSION['sel_target_name'] = "";

if(isset($_REQUEST['mrkt'])) {
	$_SESSION['sel_market'] = $_REQUEST['mrkt'];
}
if(isset($_REQUEST['tarid'])) {
	$_SESSION['sel_target'] = $_REQUEST['tarid'];
}
if(isset($_REQUEST['targname'])) {
	$_SESSION['sel_target_name'] = $_REQUEST['targname'];
}

if(isset($_REQUEST['save_btn'])) {
	
	$tar=0; 
	if(isset($_SESSION['targ_vars'])) {
	   foreach($_SESSION['targ_vars'] as $tar_id=>$vars_array) {
			foreach($vars_array as $var_id=>$opts_array) {   
				foreach($opts_array as $opts_id=>$sel_opts) {		
					if($tar_id>0 && $opts_id >0) {
						
						$insql = "insert ignore into mst_targets (srv_mrkt,trg_id,trg_name,trg_grp,trg_grpdesc,factorid,opt_id,user_id) values ("
								  . $_SESSION['sel_market'] . ", "
								  . $_SESSION['sel_target'] . ", '"
								  . $_SESSION['sel_target_name'] . "',1,'Group: 1',"
								  . $var_id . ", "
								  . $opts_id . ", "
								  . $_SESSION['seas_user_id'] . ")";
						
						mysql_query($insql);
						
						if($tar==0) $tar = $tar_id;
					}				
				}				
			}
	   }
	}

	$_SESSION['targ_vars']=array();
	unset($_SESSION['targ_vars']);

	echo "<script>"	;
	//echo 'opener.location.href = opener.location.href + "?tarid='. $tar .'"';
	echo 'opener.location.href = "target?trid='. $tar .'";';
	//echo 'opener.location.reload();';
	echo "window.close()";
	echo "</script>";
}



if(isset($_REQUEST['rmv_id'])) {
	$rm_code = explode(":",$_REQUEST['rmv_id']);
	$rmv_var_id=$rm_code[0];
	$rmv_opt_id=$rm_code[1];
	
	if(isset($_SESSION['targ_vars'][$_SESSION['sel_target']][$rmv_var_id][$rmv_opt_id])) {
		unset($_SESSION['targ_vars'][$_SESSION['sel_target']][$rmv_var_id][$rmv_opt_id]);
	}
}

if(isset($_REQUEST['fisrtcall'])){ 
	if($_REQUEST['fisrtcall']==1) {
		if(isset($_SESSION['targ_vars'])) {
			$_SESSION['targ_vars']=array();
			unset($_SESSION['targ_vars']);
		}
	}
}

if(isset($_REQUEST['add_btn'])) {
	$vars = trim($_REQUEST['sel_var']);	
	if(isset($_REQUEST['sel_opts'])) {
		foreach($_REQUEST['sel_opts'] as $opts) {
			$_SESSION['targ_vars'][$_SESSION['sel_target']][$vars][$opts] = $opts;
		}
	}
}



if(isset($_REQUEST['clear_all'])) {
	if(isset($_SESSION['targ_vars'])) {
		$_SESSION['targ_vars']=array();
		unset($_SESSION['targ_vars']);
	}
}



if(!isset($_SESSION['targ_vars'])) $_SESSION['targ_vars']=array();

?>