<?php
/*

  osCommRes, Services Online
  http://www.oscommres.com

  Copyright (c) 2005 osCommRes

  Released under the GNU General Public License
  
  Freeway eCommerce from ZacWare
http://www.zac-ware.com/freeway

Copyright 2007 ZacWare Pty. Ltd 
*/
// Set flag that this is a parent file
	define( '_FEXEC', 1 );

  require('includes/application_top.php');
  require(DIR_WS_LANGUAGES.$language.'/'.FILENAME_SUBSCRIPTION_COPY_MESSAGES);
  $message_command=isset($HTTP_GET_VARS['message_command'])?$HTTP_GET_VARS['message_command']:'';
  if($message_command!=''){
  	switch($message_command){
		case 'copy_message':
			echo 'message^^^^copy_message^^^^';
			echo tep_subscription_copy_message();
			break;
		case 'save_message':
			echo 'message^^^^save_message^^^^';
			echo tep_message_update();
			break;
	}
  exit;
  }
  
  require('includes/functions/subscription_tree.php');
  require(DIR_WS_CLASSES . 'currencies.php');
  $currencies=new currencies;  
	$action = (isset($HTTP_GET_VARS['action']) ? $HTTP_GET_VARS['action'] : '');
	$subscription_id = (isset($HTTP_GET_VARS['subscriptionID']) ?(int)$HTTP_GET_VARS['subscriptionID'] : 0);
	$select_id=(isset($HTTP_POST_VARS['select_id']) ?(int)$HTTP_POST_VARS['select_id'] : 0);
	$command=(isset($HTTP_GET_VARS['command']) ? $HTTP_GET_VARS['command'] : '');	
	$msg_id = (isset($HTTP_GET_VARS['msg_id']) ?$HTTP_GET_VARS['msg_id'] : 'RCF');
	
	$message_subscription=array();
	$message_subscription=array(
				array('id'=>'RCF','text'=>TEXT_TYPE_SUB_RCF,'mode'=>1),
				array('id'=>'MOD','text'=>TEXT_TYPE_SUB_MOD,'mode'=>1),
				//array('id'=>'INV','text'=>TEXT_TYPE_SUB_INV,'mode'=>2),
				array('id'=>'RN1','text'=>TEXT_TYPE_SUB_RN1,'mode'=>5),
				array('id'=>'RN2','text'=>TEXT_TYPE_SUB_RN2,'mode'=>5),
				array('id'=>'RN3','text'=>TEXT_TYPE_SUB_RN3,'mode'=>5),
				array('id'=>'RN4','text'=>TEXT_TYPE_SUB_RN4,'mode'=>5),
				array('id'=>'RN5','text'=>TEXT_TYPE_SUB_RN5,'mode'=>5),
				array('id'=>'MEV','text'=>TEXT_TYPE_SUB_MEV,'mode'=>2));
				//array('id'=>'PMEV','text'=>TEXT_TYPE_SUB_PMEV,'mode'=>4));			
							
		$message_type_array=array();
		$message_type_array['RCF']=array(array('id'=>'AFR','text'=>TEXT_AFR),array('id'=>'DFR','text'=>TEXT_DFR));

		$fields_type['RCF']='P_O_S';
		$fields_type['MOD']='P_S';
		$fields_type['INV']='P_O_S';
		$fields_type['RN1']='P_S';
		$fields_type['RN2']='P_S';
		$fields_type['RN3']='P_S';
		$fields_type['RN4']='P_S';
		$fields_type['RN5']='P_S';
		$fields_type['WTR']='P_S_R';
		$fields_type['MEV']='P_S';
		$fields_type['PMEV']='P_S';
		$fields_type['CCMEV']='P_S';
    $mes_array=array('message_id'=>'','message_type'=>'','message_send'=>'','message_subject'=>'','message_text'=>'');
  // susbscription registeration
    $fields_details['P']=array(array('id'=>'TITLE_P','text'=>TEXT_TITLE_P),
                    array('id'=>'FN','text'=>'&nbsp;&nbsp;' . TEXT_FN),
                    array('id'=>'LN','text'=>'&nbsp;&nbsp;' . TEXT_LN),
    			    array('id'=>'DF','text'=>'&nbsp;&nbsp;' . TEXT_DF),
			        array('id'=>'SU','text'=>'&nbsp;&nbsp;' . TEXT_SU),
			        array('id'=>'EM','text'=>'&nbsp;&nbsp;' . TEXT_EM),
			        array('id'=>'TN','text'=>'&nbsp;&nbsp;' . TEXT_TN),
			        array('id'=>'FX','text'=>'&nbsp;&nbsp;' . TEXT_FX),
			        array('id'=>'SA','text'=>'&nbsp;&nbsp;' . TEXT_SA),
			        array('id'=>'CT','text'=>'&nbsp;&nbsp;' . TEXT_CT),
			        array('id'=>'ST','text'=>'&nbsp;&nbsp;' . TEXT_ST),
			        array('id'=>'PC','text'=>'&nbsp;&nbsp;' . TEXT_PC),
			        array('id'=>'CY','text'=>'&nbsp;&nbsp;' . TEXT_CY),
			        array('id'=>'IV','text'=>'&nbsp;&nbsp;' . TEXT_IV),
			        array('id'=>'RE','text'=>'&nbsp;&nbsp;' . TEXT_RE),
			        array('id'=>'UN','text'=>'&nbsp;&nbsp;' . TEXT_UN));
					

    $fields_details['O']=array(array('id'=>'TITLE_P','text'=>TEXT_TITLE_O),
					array('id'=>'ON','text'=>'&nbsp;&nbsp;' . TEXT_ON),
					array('id'=>'OC','text'=>'&nbsp;&nbsp;' . TEXT_OC),
					array('id'=>'OD','text'=>'&nbsp;&nbsp;' . TEXT_OD),
					array('id'=>'BT','text'=>'&nbsp;&nbsp;' . TEXT_BT),
					array('id'=>'BA','text'=>'&nbsp;&nbsp;' . TEXT_BA),
					array('id'=>'PY','text'=>'&nbsp;&nbsp;' . TEXT_PY),
					array('id'=>'DD','text'=>'&nbsp;&nbsp;' . TEXT_DD),
					array('id'=>'SB','text'=>'&nbsp;&nbsp;' . TEXT_SB),
					array('id'=>'TX','text'=>'&nbsp;&nbsp;' . TEXT_TX),
					array('id'=>'TL','text'=>'&nbsp;&nbsp;' . TEXT_TL),
					array('id'=>'IL','text'=>'&nbsp;&nbsp;' . TEXT_IL));
    $fields_details['S']=array(array('id'=>'TITLE_S','text'=>TEXT_TITLE_S),
					array('id'=>'NA','text'=>'&nbsp;&nbsp;' . TEXT_SUB_NA),
					array('id'=>'CO','text'=>'&nbsp;&nbsp;' . TEXT_SUB_CO),
					array('id'=>'PE','text'=>'&nbsp;&nbsp;' . TEXT_SUB_PE),
					
					array('id'=>'DT','text'=>'&nbsp;&nbsp;'. TEXT_SUB_DT),
					array('id'=>'SD','text'=>'&nbsp;&nbsp;'.TEXT_SUB_SD),
					array('id'=>'ED','text'=>'&nbsp;&nbsp;'.TEXT_SUB_ED));

    $fields_details['V']=array(array('id'=>'TITLE_V','text'=>TEXT_TITLE_V),
                   array('id'=>'CF','text'=>'&nbsp;&nbsp;' . TEXT_CF),
			       array('id'=>'CL','text'=>'&nbsp;&nbsp;' . TEXT_CL),
			       array('id'=>'FE','text'=>'&nbsp;&nbsp;' . TEXT_FE),
			       array('id'=>'IC','text'=>'&nbsp;&nbsp;' . TEXT_IC),
			       array('id'=>'IF','text'=>'&nbsp;&nbsp;' . TEXT_IF));

	if ($action=='insert_message' || $action=='update_message'){
			$sql_array=array(	'message_type'=>tep_db_prepare_input($HTTP_POST_VARS['message_type']),
								'message_subject'=>tep_db_prepare_input($HTTP_POST_VARS['message_subject']),
								'subscription_id'=>$subscription_id,
								'message_text'=>tep_db_prepare_input($HTTP_POST_VARS['message_text']));

			if ($action=='insert_message'){
				if ($sql_array["message_type"]=="RSR")  $sql_array["message_send"]=1;
				tep_db_perform(TABLE_SUBSCRIPTION_SMS_MESSAGES,$sql_array);
			} else {
				$update_id=(int)$HTTP_GET_VARS['id'];
				tep_db_perform(TABLE_SUBSCRIPTION_SMS_MESSAGES,$sql_array,'update',"subscription_sms_message_id='" . (int)$update_id . "'");
			}
		$msg_id=$HTTP_POST_VARS['message_type'];
		$command='fetch_message_details';
	} else if ($action=='delete_message'){
		$delete_id=(int)$HTTP_GET_VARS['id'];
		tep_db_query("delete from " . TABLE_SUBSCRIPTION_SMS_MESSAGES . " where subscription_sms_message_id='" . (int)$delete_id . "'");
		$msg_id=$HTTP_GET_VARS['msg_type'];
		$command='fetch_delete_message';
	} else if ($action=='test_send'){
		tep_send_subscription_test_sms_email($HTTP_GET_VARS['msg_type'],(int)$subscription_id);
		$msg_id=$HTTP_GET_VARS['msg_type'];
		$command='fetch_message_details';
		$alert_message=TEST_EMAIL_SENT_TO;
	} else if ($action=='change_send'){
		$new_type=$HTTP_POST_VARS['message_send'];
		if ($new_type!='')
			tep_db_query("UPDATE " . TABLE_SUBSCRIPTION_SMS_MESSAGES . " set message_send='" . $new_type . "' where subscription_sms_message_id='" . (int)$HTTP_POST_VARS['id'] . "'");
		$command='fetch_message_details';
		$msg_id=$HTTP_POST_VARS['msg_type'];
	}
//==========initial parameters to perform ajax actions====
$submit_pagename=FILENAME_SUBSCRIPTION_SMS_MESSAGES;
$variable_name="subscriptionID";
$form_name="select_subscription";
$init_editor=false;
require('marketing_functions_ajax.php');
//=============================
	if($command=='fetch_message_list')
	{
		echo "message_list{}";
		tep_get_message_list($message_subscription,$message_type_array,$fields_type,'SS',$subscription_id);
		exit;
	}
	elseif($command=='fetch_delete_message')
	{
		echo "del_message{}";
		exit;
	}
	elseif($command=='fetch_message_details')
	{
		for($icnt=0;$icnt<sizeof($message_subscription);$icnt++)
		{
			if($message_subscription[$icnt]['id']==$msg_id)
			{
				tep_get_message_details($message_subscription[$icnt],$message_type_array[$msg_id],$fields_type[$msg_id],'SS',$subscription_id);
				exit;
			}
		}
	}
$subscription_array=tep_get_subscription_array_single();
	$subscription_found=true;
	if (sizeof($subscription_array)<=0){
		$subscription_found=false;
	} else {
		if ($select_id!=0 && $select_id!=$subscription_id){
			$subscription_id=$select_id;
		} else if ($select_id==0 && $subscription_id==0){
			$subscription_id=$subscription_array[1]['id'];
		}
	}	
?>
<!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; ?>">
<title><?php echo TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<script language="javascript" src="includes/menu.js"></script>
<script language="javascript" src="includes/general.js"></script>
<script type="text/javascript" src="htmlarea/htmlarea.js"></script>
<script type="text/javascript" src="htmlarea/editor.js"></script>
<script language="javascript" src="includes/http.js"></script>
     <script language=javascript>
        function validateForm(){
	   var error_result="";
	   var test="";
	   obj=document.insert_message.message_text.value;
	   if (obj=="" || str_trim(obj)=="")
	      error_result="<?php echo tep_db_input(ERR_EMPTY_MESSAGE_TEXT); ?>";
	   else if(parseInt(document.insert_message.message_text.value.length)>160)
	      error_result="<?php echo tep_db_input(ERR_MESSAGE_TEXT); ?>";
	   if (error_result!=""){
	      alert(error_result);
	      return false;
	   }
	   return true;
	}
	function AddField(){
	 var select_field;
	 var select_id;
	 if (document.insert_message.fields.selectedIndex<=-1) return;
	 select_id=document.insert_message.fields.options[document.insert_message.fields.selectedIndex].value;
	 if (select_id.length>3) return;
	 select_field="%%" + document.insert_message.fields.options[document.insert_message.fields.selectedIndex].text.substring(2) + "%%";
	 textArea=document.insert_message.message_text;
		textArea.focus();
		if (textArea.selection){
			sRange  = document.selection.createRange();
			var sText   = sRange.text;
			sRange.text = select_field;
		} else if (textArea.selectionStart || textArea.selectionStart == "0") {
			var startPos = textArea.selectionStart;
			var endPos = textArea.selectionEnd;
			textArea.value = textArea.value.substring(0, startPos)
					+ select_field + textArea.value.substring(endPos, textArea.value.length);
		} else {
			textArea.value += select_field;
		}
	}
	function setAction(ptype){
	  if (ptype==1)
	    document.insert_message.action_type.value="test";
	  else
	    document.insert_message.action_type.value="create";
	}
	function countkeywords(obj)
	{	
		document.getElementById('strcount').innerHTML="Characters Length " + obj.value.length;
	}
     </script>
<script language="JavaScript">
		function resize(){
			document.getElementById('subscription_list').style.visibility="hidden";
			document.select_subscription.select_text.blur();
		}
		var iex=(document.all);//ie
		var na6=(window.sidebar);//netscape 6.2
		var lastposition=0;
		var currentField="";
		var intervalId;
			function checkdropDown(){
				if (currentField==""){
					clearInterval(intervalId);
					hideList();
					intervalId="";
				}
			}
			function toggleText(mode){
				if (mode==1) {
					currentField="Text";
					showList();
					if (intervalId) clearInterval(intervalId);
					intervalId=setInterval("checkdropDown()",300);
				} else {
					currentField="";
				}
			}
			function toggleList(mode){
				if (mode==1){
					currentField="drop";
				} else {
					currentField="";
				}
			}
			function showList(){
				var listbox=document.getElementById("subscription_list");
				var textbox=document.select_subscription.select_text;
				listbox.style.visibility="visible";
				listbox.style.display="";
				var left = getPageOffsetLeft(textbox);
				var top =getPageOffsetTop(textbox);

				if(window.scrollMaxX >0)listbox.style.left=left;
				else listbox.style.left=left;
				listbox.style.top=top+17;
			}
			function hideList(){
				var listbox=document.getElementById("subscription_list");
				var textbox=document.select_subscription.select_text;
				setListboxText(1);
				listbox.style.display="none";
			}
			function scrollList(e){
				var listbox=document.select_subscription.select_id;

				if (iex) keyCode=window.event.keyCode;
				if (na6) keyCode=e.which;

				if (keyCode==40 || keyCode==38){
					if (keyCode==40 && listbox.selectedIndex>=0 && listbox.selectedIndex<listbox.options.length-1){
						listbox.selectedIndex+=1;
					} else if (keyCode==38 && listbox.selectedIndex>0 && listbox.selectedIndex<=listbox.options.length-1){
						listbox.selectedIndex-=1;
					}

					setListboxText(0);
					if (iex) window.event.returnValue=0;
					if (na6) e.returnValue=0;
					return;

				}
			}
			function selectList(e){
				var listbox=document.select_subscription.select_id;
				var search_word=document.select_subscription.select_text.value;
				var text_length;
				var found=-1;
				var listbox_word;
				var eventObject;
				var keyCode=0;
				var fromPos=0;
				var toPos=0;
	
				if (!listbox.options || listbox.options.length<=0) return;

				if (search_word!="") {
					search_word=search_word.toLowerCase();
					found=binaryFind(listbox,search_word,0,listbox.options.length-1);
					if (found>=0)
						listbox.selectedIndex=found;
				}

			}
			function setListboxText(mode){
				var listbox=document.select_subscription.select_id;
				if (!listbox.options || listbox.options.length<=0 || listbox.selectedIndex<=-1) return;
				var textbox_name=document.select_subscription.select_text;
				if (textbox_name.value=="" && mode==1) return "";
				textbox_name.value=listbox.options[listbox.selectedIndex].innerHTML;
				//document.select_subscription.submit();
			}
			function binaryFind(listBox,fWord,sPos,ePos){
				var listElement;
				var tWord;
				var mPos;
				if (sPos>ePos) return -1;
				mPos=sPos+Math.ceil((ePos-sPos)/2);
				
				if (mPos<0 || mPos>=listBox.options.length) return -1;
				listElement=listBox.options[mPos].innerHTML.toLowerCase();
				tWord=listElement.substr(0,fWord.length);

				if (tWord==fWord) return mPos;
				if (mPos<=0 || mPos>=listBox.options.length) return -1;
				
				if (fWord<tWord) return binaryFind(listBox,fWord,mPos+1,ePos);
				else return binaryFind(listBox,fWord,sPos,mPos-1);
			}
		</script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'marketing_functions_js.php'); ?>
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->
<!-- body //-->
<table border="0" width="100%" cellspacing="2" cellpadding="2">
	<tr> 
		<!-- body_text //-->
		<td width="100%" valign="top">
		<table border="0" width="100%" cellspacing="0" cellpadding="0">
    		<tr>
				<td>
			    <table border="0" width="100%" cellspacing="0" cellpadding="0">
				<?php if  ($subscription_found==true){
						  if ($action==''){ ?>
							<tr>
								<!--<td class="pageHeading"><?php //echo TEXT_HEADING_SUBSCRIPTION ?></td>!-->
							</tr>
							<tr><td><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td></tr>
							<tr>
								<td><?php echo tep_draw_form('select_subscription',FILENAME_SUBSCRIPTION_SMS_MESSAGES); 
											$selected_name="";
								?>
								<table border="0" cellspacing="0" cellpadding="2">
									<div id="subscription_list" style="position:absolute;left:295px;top:130px;display:none;width:400px">
										<?php echo tep_draw_subscription_select_menu('select_id',$subscription_array,$subscription_id,'size=10 style="width:400px" onClick="javascript:setListboxText(0);toggleList(0);" onFocus="javascript:toggleList(1);" onBlur="javascript:toggleList(0);" onchange="javascript:fetch_message();" class="customerSelect"');?>
									</div>
									<tr>
										<td class="main" width="25%"><?php echo TEXT_SELECT_SUBSCRIPTION;?></td>
										<td class="main"><?php echo tep_draw_input_field('select_text',$selected_name,'onFocus="javascript:toggleText(1);" onBlur="javascript:toggleText(0);" style="width:400px"');?></td>
									</tr>
								</table>
								</form>
								<script language="JavaScript">
									if(na6) document.select_subscription.select_text.addEventListener("keyup",selectList,true);
									if(iex) document.select_subscription.select_text.onkeyup=selectList;
									if(na6) document.select_subscription.select_text.addEventListener("keydown",scrollList,true);
									if(iex) document.select_subscription.select_text.onkeydown=scrollList;
								</script>
								</td>
							</tr>
							<tr><td><?php echo tep_draw_separator('pixel_trans.gif', '1', '5'); ?></td></tr>
							<tr>
								<td id="message_list">
								<?php tep_get_message_list($message_subscription,$message_type_array,$fields_type,'SS',$subscription_id)?>
								</td>
								</tr>
							<tr><td><br></td></tr>
							<tr>
							<td style="display:none;" class="openContent" id="copy_message_load"></td>
							</tr>	
							</form>
<?php } 
 } else {?>
    <tr><td class="pageHeading"><?php echo TEXT_HEADING_EMPTY_SUBSCRIPTION ;?></td></tr>
<?php } ?>
    </table>
    </td>
<!-- body_text_eof //-->
  </tr>
</table></td></tr>
</table>
<!-- body_eof //-->
<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
<script language="javascript">
var ajax_image_load='<?php echo tep_image(DIR_WS_IMAGES.'24-1.gif'); ?>';
	function copy_message(suID,type){
	hide_message_details();
	document.getElementById('copy_message_load').style.display='';
	document.getElementById('copy_message_load').innerHTML=ajax_image_load;
	do_get_command('<?php echo tep_href_link(FILENAME_SUBSCRIPTION_SMS_MESSAGES,'message_command=copy_message&suID='); ?>'+suID+'&type='+type);
	}
	function message_ValidateForm(){
		var icnt;
		var listbox;
		var error_result=Array(),error_message='';
		var listbox_name=Array("select_message[]","select_subscription[]");
		error_result[0]="<?php echo stripslashes(addslashes(ERR_SELECT_MESSAGE));?>";
		error_result[1]="<?php echo stripslashes(addslashes(ERR_SELECT_SUBSCRIPTION));?>";
		for(ecnt=0;ecnt<listbox_name.length;ecnt++){
			listbox=document.copy_message.elements[listbox_name[ecnt]];
			if (listbox==null) break;
			if (listbox.length){
				for(icnt=0;icnt<listbox.length;icnt++){
					if (listbox[icnt].checked){
						 error_result[ecnt]="";
						 break;
					}
				}
			} else {
				if (listbox.checked) error_result[ecnt]="";
			}
		}
		if (error_result[0]!="")
			error_message=error_result[0];
		if (error_result[1]!="")
			error_message+='\n'+error_result[1];

	if(error_message!='')
		alert(error_message);
	else{
	do_post_command('copy_message','<?php echo tep_href_link(FILENAME_SUBSCRIPTION_SMS_MESSAGES,'message_command=save_message'); ?>');
	}	
		
	}
	function close_copy_message(){
		document.getElementById('copy_message_load').style.display='none';
		document.getElementById('copy_message_load').innerHTML='';
	}
</script>
	<?php
 	// function used in this page
	function tep_message_update(){
	global $HTTP_POST_VARS;
	$subscription_id = (isset($HTTP_POST_VARS['suID']) ?(int)$HTTP_POST_VARS['suID'] : 0);
	$template_type=(isset($HTTP_POST_VARS['type'])?strtolower($HTTP_POST_VARS['type']) : "su");
	$templates=getTemplates($subscription_id,$template_type);
	//table name;
	switch($template_type){
		case "su":
		default:
			$table_name=TABLE_SUBSCRIPTION_SMS_MESSAGES;
			$back_url=FILENAME_SUBSCRIPTION_MESSAGES;
			//$fields_list="message_send,message_send1,message_subject,message_reply_to,message_text,message_format,subscription_id,message_type";
			$fields_list="message_send,message_subject,message_text,subscription_id,message_type";
	}
		$message_keys=&$HTTP_POST_VARS["select_message"];
		$subscription_keys=&$HTTP_POST_VARS["select_subscription"];
		if (sizeof($message_keys)<=0 || sizeof($subscription_keys)<=0 || $subscription_id<0)
			exit;

		// fetch subscription into total array to find and subscription has already message
		$status=array();
		reset($subscription_keys);
		for ($icnt=0;$icnt<sizeof($subscription_keys);$icnt++){
			$status[$subscription_keys[$icnt]]=array();
		}
		//get the input message_ids,subscription_ids
		$message_string=join("','",$message_keys);
		$subscription_string=join(",",$subscription_keys);

		$message_query=tep_db_query("SELECT  " . $fields_list . " from " . $table_name . " where subscription_id='" . (int)$subscription_id . "' and message_type in('" . $message_string . "')");

		// get the message status for subscriptions we have to copy
		$subscription_status_query=tep_db_query("SELECT count(*) as total,message_type,subscription_id from " . $table_name . " where subscription_id in(" . $subscription_string . ") and message_type in('" . $message_string . "') group by subscription_id,message_type");
		
		while($subscription_status=tep_db_fetch_array($subscription_status_query)){
			if (isset($status[$subscription_status["subscription_id"]])){
				$status[$subscription_status["subscription_id"]][$subscription_status["message_type"]]=$subscription_status["total"];
			}
		}

		while($message=tep_db_fetch_array($message_query)){
			reset($status);
			//iterate with the subscription we have to find insert or update
			while(list($sukey,)=each($status)){ 
				$message["subscription_id"]=$sukey;
				$count=isset($status[$sukey][$message["message_type"]])?$status[$sukey][$message["message_type"]]:0;
				if ($count>0){ // update operation
					tep_db_perform($table_name,$message,"update","subscription_id='" . $sukey . "' and message_type='" . $message["message_type"] . "'");
				} else { //insert operation
					tep_db_perform($table_name,$message);
				}
			}
		}
	

	
	
	}
	
	function tep_subscription_copy_message(){
	global $HTTP_GET_VARS;
	require(DIR_WS_CLASSES . '/currencies.php');
  	$currencies=new currencies;
	$subscription_id = (isset($HTTP_GET_VARS['suID']) ?(int)$HTTP_GET_VARS['suID'] : 0);
	$template_type=(isset($HTTP_GET_VARS['type'])?strtolower($HTTP_GET_VARS['type']) : "su");

	$templates=getTemplates($subscription_id,$template_type);
	//table name;
	switch($template_type){
		case "su":
		default:
			$table_name=TABLE_SUBSCRIPTION_SMS_MESSAGES;
			$back_url=FILENAME_SUBSCRIPTION_MESSAGES;
			$fields_list="message_send,message_send1,message_subject,message_reply_to,message_text,message_format,subscription_id,message_type";
	}
	// get the message list
	$type_params="";
	reset($templates);
	while(list($key,)=each($templates)){
		if ($type_params=="") $type_params.=" and message_type in(";
		$type_params.="'" . $key . "',";
	}
	$type_params=substr($type_params,0,-1) . ")";
	$message_query=tep_db_query("SELECT count(*) as total,message_type from " . $table_name . " where subscription_id='" . (int)$subscription_id . "' " . $type_params . " group by message_type");


	while($message=tep_db_fetch_array($message_query)){
		if ((int)$message["total"]>0 && isset($templates[$message['message_type']])){
			$templates[$message['message_type']]['status']=1;
			$templates[$message['message_type']]['color']='#0000FF';
		}
	}
	$subscription_array=array();
	$subscription_query=tep_db_query("SELECT su.subscription_id,sud.subscription_name from " . TABLE_SUBSCRIPTIONS . " su, " . TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud where su.subscription_id=sud.subscription_id " . SUBSCRIPTION_CONDITION_STATUS . " order by sud.subscription_name");
	while($subscription_result=tep_db_fetch_array($subscription_query)){
		if ($subscription_id!=$subscription_result["subscription_id"])
			$subscription_array[$subscription_result['subscription_id']]=array('text'=>$subscription_result['subscription_name'],'color'=>"#000000");
	}
	echo tep_draw_form("copy_message",FILENAME_SUBSCRIPTION_COPY_MESSAGES,'action=update&suID=' . $subscription_id . '&type=' . $template_type,"post",'onSubmit="javascript:return validateForm();"');
	echo tep_draw_hidden_field('suID',$subscription_id).tep_draw_hidden_field('type',$template_type);
	?>
	<table width="100%" border="0" cellpadding="0" cellspacing="0">
	<tr>
	<td><table width="100%" cellpadding="0" cellspacing="0" border="0">
	<tr>
	<td class="pageHeading"><?php echo tep_image(DIR_WS_IMAGES.'template/icon_active.gif'); ?>&nbsp;Copy Messages - <?php echo tep_get_subscription_name($subscription_id); ?></td>
	<td align="right"><?php echo '<a href="javascript: message_ValidateForm();">'.tep_image(DIR_WS_IMAGES.'template/img_savel.gif','Save').'</a>&nbsp;&nbsp;<a href="javascript: close_copy_message();">'.tep_image(DIR_WS_IMAGES.'template/img_closel.gif','Close').'</a>'; ?>&nbsp;</td>
	</tr>
	</table></td>
	</tr>
		<tr>
			<td>
				<table border="0" cellpadding="2" cellspacing="5" >
					<tr class="attributes-even">
						<td class="tableHeading"><?php echo SELECT_MESSAGES;?></td>
						<td class="tableHeading"><?php echo SELECT_SUBSCRIPTIONS;?></td>
					</tr>
					<tr>
						<td class="tableHeading"><?php echo customListBox("select_message",$templates,0,300,200);?></td>
						<td class="tableHeading"><?php echo customListBox("select_subscription",$subscription_array,0,500,200);?></td>
					</tr>
				</table>
			</td>
		</tr>
		<tr>
			<td><?php echo tep_draw_separator('pixel_trans.gif','1','5');?></td>
		</tr>
	</table>
	</form>
	<?php
	}

	function &getTemplates($subscription_id,$type){
		$templates=array();
		switch($type){
			case "su": //subscription messages
			default:
				$templates=array(	'RCF'=>array('text'=>TEXT_TYPE_SUB_RCF,'status'=>0,'color'=>'#FF0000'),
									'INV'=>array('text'=>TEXT_TYPE_SUB_INV,'status'=>0,'color'=>'#FF0000'),
									'RN1'=>array('text'=>TEXT_TYPE_SUB_RN1,'status'=>0,'color'=>'#FF0000'),
									'RN2'=>array('text'=>TEXT_TYPE_SUB_RN2,'status'=>0,'color'=>'#FF0000'),
									'RN3'=>array('text'=>TEXT_TYPE_SUB_RN3,'status'=>0,'color'=>'#FF0000'),
									'RN4'=>array('text'=>TEXT_TYPE_SUB_RN4,'status'=>0,'color'=>'#FF0000'),
									'RN5'=>array('text'=>TEXT_TYPE_SUB_RN5,'status'=>0,'color'=>'#FF0000'));

		}
		return $templates;
	}
	function customListBox($name,&$list,$selected="",$width=300,$height=100){ global $HTTP_POST_VARS;
	$result="";
		$result.='<div id="' . $name . '_box" style="background-color: #FFFFFF;border-color: #7b9ebd; border-style: solid; border-width: 1px;overflow:auto;width:' . $width . ';height:' . $height . '">' . "\n";
		$result.='<table border="0" cellspacing="0" cellpadding="2" width="100%" valign="middle" align="center" class="BoxTable">' . "\n";
		reset($list);

		$selected=array();
		if (isset($HTTP_POST_VARS[$name]) && is_array($HTTP_POST_VARS[$name])){
			$selected=&$HTTP_POST_VARS[$name];
		}
		if (count($list)>0){
			while(list($key,)=each($list)){
				$result.='<tr class="attributes-even"><td class="main" width="20">' . "\n";
				$result.='<input type="checkbox" name="' . $name . '[]" value="' . $key . '" ' . (in_array($key,$selected)?"checked":"") . ' >';
				$result.='<td class="main"><font color="' . $list[$key]['color'] . '">' . $list[$key]['text'] .'</font></td></tr>' ."\n";
			}
		} else {
			$result.='<tr><td class="main">' . TEXT_NO_SUBSCRIPTIONS . '</td></tr>';
		}
		$result.='</table></div>' . "\n";
		echo $result;
	}
	?>