<?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_SERVICES_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_service_copy_message();
		break;
		case 'save_message':
		echo 'message^^^^save_message^^^^';
		echo tep_message_update();
		break;
	}
  exit;
  }
  tep_get_last_access_file();
  require('includes/functions/services_tree.php');
  require(DIR_WS_CLASSES . 'currencies.php');
  $currencies=new currencies;  
  // get input entries to find type of entry


	$action = (isset($HTTP_GET_VARS['action']) ? $HTTP_GET_VARS['action'] : '');
	$service_id = (isset($HTTP_GET_VARS['serviceID']) ?(int)$HTTP_GET_VARS['serviceID'] : '');
	$select_id=(isset($HTTP_POST_VARS['select_id']) ?(int)$HTTP_POST_VARS['select_id'] : '');
  $command=(isset($HTTP_GET_VARS['command']) ? $HTTP_GET_VARS['command'] : '');	
  $msg_id = (isset($HTTP_GET_VARS['msg_id']) ?$HTTP_GET_VARS['msg_id'] : 'RCF');

  $mes_array=array('message_id'=>'',
  				'message_type'=>'',
                 'message_send'=>'',
				 'message_send1'=>'',
		 		'message_subject'=>'',
		 		'message_text'=>'');

$message_service=array();
	 $message_service=array(array('id'=>'RCF','text'=>TEXT_TYPE_SER_RCF,'mode'=>4),
							array('id'=>'WTR','text'=>TEXT_TYPE_SER_WTR,'mode'=>1),
							array('id'=>'INV','text'=>TEXT_TYPE_SER_INV,'mode'=>4),
							array('id'=>'RN1','text'=>TEXT_TYPE_SER_RN1,'mode'=>4),
							array('id'=>'RN2','text'=>TEXT_TYPE_SER_RN2,'mode'=>4),
							array('id'=>'RN3','text'=>TEXT_TYPE_SER_RN3,'mode'=>4),
							array('id'=>'RN4','text'=>TEXT_TYPE_SER_RN4,'mode'=>4),
							array('id'=>'RN5','text'=>TEXT_TYPE_SER_RN5,'mode'=>4),
							array('id'=>'RS1','text'=>TEXT_TYPE_SER_RS1,'mode'=>4),
							array('id'=>'RS2','text'=>TEXT_TYPE_SER_RS2,'mode'=>4),
							array('id'=>'RE1','text'=>TEXT_TYPE_SER_RE1,'mode'=>4),
							array('id'=>'RE2','text'=>TEXT_TYPE_SER_RE2,'mode'=>4),
							array('id'=>'MSV','text'=>TEXT_TYPE_SER_MSV,'mode'=>2),
							);
					
		
		$message_type_array=array();
		$message_type_array['RCF']=array(array('id'=>'AFR','text'=>TEXT_AFR),
										array('id'=>'DFR','text'=>TEXT_DFR));
		
		$message_type_array['WTR']=array(array('id'=>'WTR','text'=>TEXT_WTR));	
		
													

		$fields_type['RCF']='P_O_X';
		$fields_type['WTR']='P_X';
		$fields_type['INV']='X_V';
		$fields_type['RN1']='P_X';
		$fields_type['RN2']='P_X';
		$fields_type['RN3']='P_X';
		$fields_type['RN4']='P_X';
		$fields_type['RN5']='P_X';
		$fields_type['MSV']='P_X';
		$fields_type['RS1']='X_V';
		$fields_type['RS2']='X_V';
		$fields_type['RE1']='X_V';
		$fields_type['RE2']='X_V';
	    $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'=>'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['X']=array(array('id'=>'TITLE_P','text'=>TEXT_TITLE_X),
                        array('id'=>'SN','text'=>'&nbsp;&nbsp;' . TEXT_SER_SN),
								array('id'=>'SC','text'=>'&nbsp;&nbsp;' . TEXT_SER_SC),
								array('id'=>'ST','text'=>'&nbsp;&nbsp;' . TEXT_SER_ST),
								array('id'=>'ET','text'=>'&nbsp;&nbsp;' . TEXT_SER_ET),
								array('id'=>'SL','text'=>'&nbsp;&nbsp;' . TEXT_SER_SL),
								array('id'=>'RV','text'=>'&nbsp;&nbsp;' . TEXT_RV),
								array('id'=>'WV','text'=>'&nbsp;&nbsp;' . TEXT_WV),
								array('id'=>'FV','text'=>'&nbsp;&nbsp;' . TEXT_FV));
    $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'){
			$symbol_date=($HTTP_POST_VARS['send_email_date']=='A'?'+':'-');
			$symbol_time=($HTTP_POST_VARS['send_email_time']=='A'?'+':'-');
			$message_send=(isset($HTTP_POST_VARS['message_send'])?($symbol_date.$HTTP_POST_VARS['message_send']):'');
			$message_send1=(isset($HTTP_POST_VARS['message_send1'])?($symbol_time.$HTTP_POST_VARS['message_send1']):'');
			if(($symbol_date=='-' || $symbol_date=='+') && $HTTP_POST_VARS['message_send']=="") $message_send="0";
			if(($symbol_time=='-' || $symbol_time=='+') && $HTTP_POST_VARS['message_send1']=="") $message_send1="0";
			
			$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']),
								'message_send'=>$message_send,
								'message_send1'=>$message_send1,
								'service_id'=>$service_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_SERVICES_SMS_MESSAGES,$sql_array);
			} else {
				$update_id=(int)$HTTP_GET_VARS['id'];
				tep_db_perform(TABLE_SERVICES_SMS_MESSAGES,$sql_array,'update',"services_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_SERVICES_SMS_MESSAGES . " where services_sms_message_id='" . (int)$delete_id . "'");
		$command='fetch_delete_message';
		$msg_id=$HTTP_GET_VARS['msg_type'];
	} else if ($action=='test_send'){
		tep_send_service_test_sms_email($HTTP_GET_VARS['msg_type'],(int)$service_id);
		$msg_id=$HTTP_GET_VARS['msg_type'];
		$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_SERVICES_SMS_MESSAGES . " set message_send='" . $new_type . "' where services_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_SERVICES_SMS_MESSAGES;
$variable_name="serviceID";
$form_name="select_services";
$init_editor=false;
require('marketing_functions_ajax.php');
//=============================
	if($command=='fetch_message_list')
	{
		echo "message_list{}";
		tep_get_message_list($message_service,$message_type_array,$fields_type,'SV',$service_id);
		exit;
	}
	elseif($command=='fetch_delete_message')
	{
		echo "del_message{}";
		exit;
	}
	elseif($command=='fetch_message_details')
	{
		for($icnt=0;$icnt<sizeof($message_service);$icnt++)
		{
			if($message_service[$icnt]['id']==$msg_id)
			{
				tep_get_message_details($message_service[$icnt],$message_type_array[$msg_id],$fields_type[$msg_id],'SV',$service_id);
				exit;
			}
		}
	}

	$service_array=tep_get_service_array_single();
	$service_found=true;
	if (sizeof($service_array)<=0){
		$service_found=false;
	} else {
		if ($select_id!=0 && $select_id!=$service_id){
			$service_id=$select_id;
		} else if ($select_id==0 && $service_id==0){
			$service_id=$service_array[0]['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 do_action(){
	var sel_type=document.getElementById("type_send");
	if(sel_type) type=sel_type.options[sel_type.selectedIndex].value;   
	var send=document.getElementById("send_type");
	var send_days_hours=document.getElementById("send_days_hours");
	var send1=document.getElementById("send_type1");
	var send_days_hours1=document.getElementById("send_days_hours1");
		if(send_days_hours1 && send1 && type=='H'){
			send1.style.display=send_days_hours1.style.display='';
			if(send && send_days_hours)send.style.display=send_days_hours.style.display='none';
		}else if(send_days_hours && send && type=='D') { 
			send.style.display=send_days_hours.style.display=''; 
			if(send1 && send_days_hours1) send1.style.display=send_days_hours1.style.display='none';
		}
	}
</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('service_list').style.visibility="hidden";
			document.select_services.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("service_list");
				var textbox=document.select_services.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("service_list");
				var textbox=document.select_services.select_text;
				setListboxText(1);
				listbox.style.display="none";
			}
			function scrollList(e){
				var listbox=document.select_services.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_services.select_id;
				var search_word=document.select_services.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_services.select_id;
				if (!listbox.options || listbox.options.length<=0 || listbox.selectedIndex<=-1) return;
				var textbox_name=document.select_services.select_text;
				if (textbox_name.value=="" && mode==1) return "";
				textbox_name.value=listbox.options[listbox.selectedIndex].innerHTML;
				//document.select_services.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  ($service_found==true){
						  if ($action==''){ ?>
							<tr>
								<!--<td class="pageHeading"><?php //echo TEXT_HEADING_SERVICE ?></td>!-->
							</tr>
							<tr><td><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td></tr>
							<tr>
								<td><?php echo tep_draw_form('select_services',FILENAME_SERVICES_SMS_MESSAGES); 
											$selected_name="";
								?>
								<table border="0" cellspacing="0" cellpadding="2">
									<div id="service_list" style="position:absolute;left:246px;top:210px;display:none;width:400px">
										<?php echo tep_draw_service_select_menu('select_id',$service_array,$service_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="100"><?php echo TEXT_SELECT_SERVICE;?></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_services.select_text.addEventListener("keyup",selectList,true);
									if(iex) document.select_services.select_text.onkeyup=selectList;
									if(na6) document.select_services.select_text.addEventListener("keydown",scrollList,true);
									if(iex) document.select_services.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_service,$message_type_array,$fields_type,'SV',$service_id)?>
								</td>
								</tr>
							<tr><td><br></td></tr>
							<tr>
							<td style="display:none;" class="openContent" id="copy_message_load"></td>
							</tr>
<?php } 
	} else {?>
    <tr><td class="pageHeading"><?php echo TEXT_HEADING_EMPTY_SERVICES ;?></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 message_validateForm(){
			var icnt;
			var listbox,error_message='';
			var error_result=Array();
			var listbox_name=Array("select_message[]","select_service[]");
			error_result[0]="<?php echo stripslashes(addslashes(ERR_SELECT_MESSAGE));?>";
			error_result[1]="<?php echo stripslashes(addslashes(ERR_SELECT_SERVICES));?>";
			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_SERVICES_SMS_MESSAGES,'message_command=save_message'); ?>');
		document.getElementById('copy_message_load').innerHTML=ajax_image_load;
		}	
		}

	function copy_message(sID,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_SERVICES_SMS_MESSAGES,'message_command=copy_message&sID='); ?>'+sID+'&type='+type);
	}
	function close_copy_message(){
		document.getElementById('copy_message_load').style.display='none';
		document.getElementById('copy_message_load').innerHTML='';
	}
</script>

	<?php 
	function tep_service_copy_message(){
	global $HTTP_GET_VARS;
	$service_id = (isset($HTTP_GET_VARS['sID']) ?(int)$HTTP_GET_VARS['sID'] : 0);
	$template_type=(isset($HTTP_GET_VARS['type'])?strtolower($HTTP_GET_VARS['type']) : "se");
	$templates=getTemplates($service_id,$template_type);
	//table name;
	switch($template_type){
		case "sm":
			$table_name=TABLE_SERVICES_SMS_MESSAGES;
			$back_url=FILENAME_SERVICES_SMS_MESSAGES;
			$fields_list="message_send,message_subject,message_text,service_id,message_type,message_send1";
			break;
		case "se":
		default:
			$table_name=TABLE_SERVICES_MESSAGES;
			$back_url=FILENAME_SERVICES_MESSAGES;
			$fields_list="message_send,message_subject,message_reply_to,message_text,message_format,service_id,message_type,message_send1";
	}	
	// 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 service_id='" . (int)$service_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';
		}
	}
	
	//to fetch the service names
	$service_array=array();
	$service_query=tep_db_query("SELECT se.service_id,sed.service_name from " . TABLE_SERVICES . " se, " . TABLE_SERVICES_DESCRIPTION . " sed where se.service_id=sed.service_id " . SERVICES_CONDITION_STATUS . " order by sed.service_name");
	
	while($service_result=tep_db_fetch_array($service_query)){
		if ($service_id!=$service_result["service_id"])
			$service_array[$service_result['service_id']]=array('text'=>$service_result['service_name'],'color'=>"#000000");
	}	
	echo tep_draw_form("copy_message",FILENAME_SERVICES_COPY_MESSAGES,'action=update&sID=' . $service_id . '&type=' . $template_type,"post",'onSubmit="javascript:return validateForm();"');
	echo tep_draw_hidden_field('sID',$service_id).tep_draw_hidden_field('type',$template_type);
	?>
		<table border="0" cellpadding="0" cellspacing="0">
		<tr>
		<td class="openContent_top"><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_service_name($service_id); ?></td></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_SERVICES;?></td>
								</tr>
								<tr>
									<td class="tableHeading"><?php echo customListBox("select_message",$templates,0,300,200);?></td>
									<td class="tableHeading"><?php echo customListBox("select_service",$service_array,0,500,200);?></td>
								</tr>
							</table>
						</td>
					</tr>
					<tr>
						<td><?php echo tep_draw_separator('pixel_trans.gif','1','5');?></td>
					</tr>
		</table>
	<?php
		}
	function tep_message_update(){
	global $HTTP_POST_VARS;
	$service_id = (isset($HTTP_POST_VARS['sID']) ?(int)$HTTP_POST_VARS['sID'] : 0);
	$template_type=(isset($HTTP_POST_VARS['type'])?strtolower($HTTP_POST_VARS['type']) : "se");
	$templates=getTemplates($service_id,$template_type);
	//table name;
	switch($template_type){
		case "sm":
			$table_name=TABLE_SERVICES_SMS_MESSAGES;
			$back_url=FILENAME_SERVICES_SMS_MESSAGES;
			$fields_list="message_send,message_subject,message_text,service_id,message_type,message_send1";
			break;
		case "se":
		default:
			$table_name=TABLE_SERVICES_MESSAGES;
			$back_url=FILENAME_SERVICES_MESSAGES;
			$fields_list="message_send,message_subject,message_reply_to,message_text,message_format,service_id,message_type,message_send1";
	}
	
		$message_keys=&$HTTP_POST_VARS["select_message"];
		$service_keys=&$HTTP_POST_VARS["select_service"];
		if (sizeof($message_keys)<=0 || sizeof($service_keys)<=0 || $service_id<0)
			tep_redirect(tep_href_link($back_url,'service_id=' . $service_id));

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

		$message_query=tep_db_query("SELECT  " . $fields_list . " from " . $table_name . " where service_id='" . $service_id . "' and message_type in('" . $message_string . "')");
		// get the message status for services we have to copy
		$service_status_query=tep_db_query("SELECT count(*) as total,message_type,service_id from " . $table_name . " where service_id in(" . $service_string . ") and message_type in('" . $message_string . "') group by service_id,message_type");
		
		while($service_status=tep_db_fetch_array($service_status_query)){
			if (isset($status[$service_status["service_id"]])){
				$status[$service_status["service_id"]][$service_status["message_type"]]=$service_status["total"];
			}
		}
		while($message=tep_db_fetch_array($message_query)){
			reset($status);
			//iterate with the service we have to find insert or update
			while(list($sukey,)=each($status)){
				$message["service_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","service_id='" . $sukey . "' and message_type='" . $message["message_type"] . "'");
				} else { //insert operation
					tep_db_perform($table_name,$message);
				}
			}
		}
	
	}	
	
 	 // function used in this page

	function &getTemplates($service_id,$type){
		$templates=array();
		switch($type){
			case "sm": //sms messages
				$templates=array(	'RCF'=>array('text'=>TEXT_TYPE_SER_RCF,'status'=>0,'color'=>'#FF0000'),
									'WTR'=>array('text'=>TEXT_TYPE_SER_WTR,'status'=>0,'color'=>'#FF0000'),
									'INV'=>array('text'=>TEXT_TYPE_SER_INV,'status'=>0,'color'=>'#FF0000'),
									'RN1'=>array('text'=>TEXT_TYPE_SER_RN1,'status'=>0,'color'=>'#FF0000'),
									'RN2'=>array('text'=>TEXT_TYPE_SER_RN2,'status'=>0,'color'=>'#FF0000'),
									'RN3'=>array('text'=>TEXT_TYPE_SER_RN3,'status'=>0,'color'=>'#FF0000'),
									'RN4'=>array('text'=>TEXT_TYPE_SER_RN4,'status'=>0,'color'=>'#FF0000'),
									'RN5'=>array('text'=>TEXT_TYPE_SER_RN5,'status'=>0,'color'=>'#FF0000'),
									'MSV'=>array('text'=>TEXT_TYPE_SER_MSV,'status'=>0,'color'=>'#FF0000'),
									'RS1'=>array('text'=>TEXT_TYPE_SER_RS1,'status'=>0,'color'=>'#FF0000'),
									'RS2'=>array('text'=>TEXT_TYPE_SER_RS2,'status'=>0,'color'=>'#FF0000'),
									'RE1'=>array('text'=>TEXT_TYPE_SER_RE1,'status'=>0,'color'=>'#FF0000'),
									'RE2'=>array('text'=>TEXT_TYPE_SER_RE2,'status'=>0,'color'=>'#FF0000'));
				break;
			case "se": //service messages
			default:
				$templates=array(	'RCF'=>array('text'=>TEXT_TYPE_SER_RCF,'status'=>0,'color'=>'#FF0000'),
									'WTR'=>array('text'=>TEXT_TYPE_SER_WTR,'status'=>0,'color'=>'#FF0000'),
									'INV'=>array('text'=>TEXT_TYPE_SER_INV,'status'=>0,'color'=>'#FF0000'),
									'RN1'=>array('text'=>TEXT_TYPE_SER_RN1,'status'=>0,'color'=>'#FF0000'),
									'RN2'=>array('text'=>TEXT_TYPE_SER_RN2,'status'=>0,'color'=>'#FF0000'),
									'RN3'=>array('text'=>TEXT_TYPE_SER_RN3,'status'=>0,'color'=>'#FF0000'),
									'RN4'=>array('text'=>TEXT_TYPE_SER_RN4,'status'=>0,'color'=>'#FF0000'),
									'RN5'=>array('text'=>TEXT_TYPE_SER_RN5,'status'=>0,'color'=>'#FF0000'),
									'MSV'=>array('text'=>TEXT_TYPE_SER_MSV,'status'=>0,'color'=>'#FF0000'),
									'RS1'=>array('text'=>TEXT_TYPE_SER_RS1,'status'=>0,'color'=>'#FF0000'),
									'RS2'=>array('text'=>TEXT_TYPE_SER_RS2,'status'=>0,'color'=>'#FF0000'),
									'RE1'=>array('text'=>TEXT_TYPE_SER_RE1,'status'=>0,'color'=>'#FF0000'),
									'RE2'=>array('text'=>TEXT_TYPE_SER_RE2,'status'=>0,'color'=>'#FF0000'));

		}
		return $templates;
	}
	function customListBox($name,&$list,$selected="",$width=300,$height=100){
	$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];
			
		}
			
		//	echo (count($list));
		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_SERVICES . '</td></tr>';
		}
		$result.='</table></div>' . "\n";
		echo $result;
	}
?>