<?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_EVENTS_COPY_MESSAGES);
  	$copy_command=isset($HTTP_GET_VARS['copy_command'])?$HTTP_GET_VARS['copy_command']:'';
	if($copy_command!=''){
		switch($copy_command){
		case 'copy_message':
			echo 'message^^^^copy_message^^^^';
			echo tep_events_copy_message();
			break;
		case 'save_message':
			echo 'message^^^^save_message^^^^';
			echo update();
			break;
		}
	exit;
	}
  tep_get_last_access_file();
  require('includes/functions/events_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'] : '');
	$events_id = (isset($HTTP_GET_VARS['events_id']) ?(int)$HTTP_GET_VARS['events_id'] : 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');

$mes_array=array('message_id'=>'',
				'message_type'=>'',
                 'message_send'=>'',
				 'message_subject'=>'',
		 		'message_text'=>'');
$message_event=array();
$message_event=array(array('id'=>'RCF','text'=>TEXT_TYPE_RCF,'mode'=>1),
					array('id'=>'WCF','text'=>TEXT_TYPE_WCF,'mode'=>1),
					array('id'=>'RSR','text'=>TEXT_TYPE_RSR,'mode'=>1),
					array('id'=>'RNR','text'=>TEXT_TYPE_RNR,'mode'=>1),
					array('id'=>'FDB','text'=>TEXT_TYPE_FDB,'mode'=>1),
					array('id'=>'WPR','text'=>TEXT_TYPE_WPR,'mode'=>1),
					array('id'=>'WPL','text'=>TEXT_TYPE_WPL,'mode'=>1),
					//array('id'=>'WTR','text'=>TEXT_TYPE_WTR,'mode'=>1),
					//array('id'=>'INV','text'=>TEXT_TYPE_INV,'mode'=>4),
					array('id'=>'MEV','text'=>TEXT_TYPE_MEV,'mode'=>2),
					array('id'=>'MEW','text'=>TEXT_TYPE_MEW,'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['WCF']=array(array('id'=>'AFR','text'=>TEXT_AFR),
						   array('id'=>'DFR','text'=>TEXT_DFR));

$message_type_array['RSR']=array();

for($icnt=1;$icnt<=10;$icnt++)
	$message_type_array['RSR'][]=array('id'=>$icnt,'text'=>$icnt);

$message_type_array['RNR']=array(array('id'=>'FLS','text'=>TEXT_FLS),
								array('id'=>'SLS','text'=>TEXT_SLS),
								array('id'=>'DLS','text'=>TEXT_DLS),
								array('id'=>'OBS','text'=>TEXT_OBS),
								array('id'=>'TBS','text'=>TEXT_TBS));

$message_type_array['FDB']=array(array('id'=>'FLS','text'=>TEXT_FLS),
								array('id'=>'SLS','text'=>TEXT_SLS),
								array('id'=>'DLS','text'=>TEXT_DLS),
								array('id'=>'OBS','text'=>TEXT_OBS),
								array('id'=>'TBS','text'=>TEXT_TBS),
								array('id'=>'DFS','text'=>TEXT_DFS),
								array('id'=>'OLS','text'=>TEXT_OLS),
								array('id'=>'TLS','text'=>TEXT_TLS));
$message_type_array['WPR']=array(array('id'=>'RPR','text'=>TEXT_RPR));
$message_type_array['WPL']=array(array('id'=>'WPR','text'=>TEXT_WPR));
$message_type_array['WTR']=array(array('id'=>'WTR','text'=>TEXT_WTR));

$fields_type['RCF']='P_O_E';
$fields_type['WCF']='P_O_E';
$fields_type['RSR']='P_E';
$fields_type['RNR']='P_E';
$fields_type['FDB']='P_E';
$fields_type['WPR']='P_E';
$fields_type['WPL']='P_E';
$fields_type['WTR']='P_E_R';
$fields_type['MEV']='P_E';
$fields_type['MEW']='P_E';
$fields_type['INV']='E_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'=>'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['E']=array(array('id'=>'TITLE_P','text'=>TEXT_TITLE_E),
                               array('id'=>'EN','text'=>'&nbsp;&nbsp;' . TEXT_EN),
			       array('id'=>'SI','text'=>'&nbsp;&nbsp;' . TEXT_SI),
			       array('id'=>'EI','text'=>'&nbsp;&nbsp;' . TEXT_EI),
			       array('id'=>'EF','text'=>'&nbsp;&nbsp;' . TEXT_EF),
			       array('id'=>'EL','text'=>'&nbsp;&nbsp;' . TEXT_EL),
			       array('id'=>'IN','text'=>'&nbsp;&nbsp;' . TEXT_IN),
			       array('id'=>'SD','text'=>'&nbsp;&nbsp;' . TEXT_SD),
                   array('id'=>'SS','text'=>'&nbsp;&nbsp;' . TEXT_SS),
				   array('id'=>'SSM','text'=>'&nbsp;&nbsp;' . TEXT_SSM),
			       array('id'=>'RL','text'=>'&nbsp;&nbsp;' . TEXT_RL),
			       array('id'=>'RM','text'=>'&nbsp;&nbsp;' . TEXT_RM),
			       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'){
			$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']),
								'events_id'=>$events_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_EVENTS_SMS_MESSAGES,$sql_array);
			} else {
				$update_id=(int)$HTTP_GET_VARS['id'];
				tep_db_perform(TABLE_EVENTS_SMS_MESSAGES,$sql_array,'update',"events_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_EVENTS_SMS_MESSAGES . " where events_sms_message_id='" . (int)$delete_id . "'");
		$command='fetch_delete_message';
		$msg_id=$HTTP_GET_VARS['msg_type'];
	} else if ($action=='test_send'){
		tep_send_event_test_sms_email($HTTP_GET_VARS['msg_type'],(int)$events_id);
		$msg_id=$HTTP_GET_VARS['msg_type'];
		$alert_message=TEST_EMAIL_SENT_TO;
		$command='fetch_message_details';
	} else if ($action=='change_send'){
		$new_type=$HTTP_POST_VARS['message_send'];
		if ($new_type!='')
			tep_db_query("UPDATE " . TABLE_EVENTS_SMS_MESSAGES . " set message_send='" . $new_type . "' where events_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_EVENTS_SMS_MESSAGES;
$variable_name="events_id";
$form_name="select_event";
$init_editor=false;
require('marketing_functions_ajax.php');
//=============================
	if($command=='fetch_message_list')
	{
		echo "message_list{}";
		tep_get_message_list($message_event,$message_type_array,$fields_type,'SE',$events_id);
		exit;
	}
	elseif($command=='fetch_delete_message')
	{
		echo "del_message{}";
		exit;
	}
	elseif($command=='fetch_message_details')
	{
		for($icnt=0;$icnt<sizeof($message_event);$icnt++)
		{
			if($message_event[$icnt]['id']==$msg_id)
			{
				tep_get_message_details($message_event[$icnt],$message_type_array[$msg_id],$fields_type[$msg_id],'SE',$events_id);
				exit;
			}
		}
	}
	$events_array=tep_get_events_array_single();
	$event_found=true;
	if (sizeof($events_array)<=0){
		$event_found=false;
	} else {
		if ($select_id!=0 && $select_id!=$events_id){
			$events_id=$select_id;
		} else if ($select_id==0 && $events_id==0){
			$events_id=$events_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 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('event_list').style.visibility="hidden";
			document.select_event.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("event_list");
				var textbox=document.select_event.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("event_list");
				var textbox=document.select_event.select_text;
				setListboxText(1);
				listbox.style.display="none";
			}
			function scrollList(e){
				var listbox=document.select_event.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_event.select_id;
				var search_word=document.select_event.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_event.select_id;
				if (!listbox.options || listbox.options.length<=0 || listbox.selectedIndex<=-1) return;
				var textbox_name=document.select_event.select_text;
				if (textbox_name.value=="" && mode==1) return "";
				textbox_name.value=listbox.options[listbox.selectedIndex].innerHTML;
				//document.select_event.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">
<?php require(DIR_WS_INCLUDES . 'marketing_functions_js.php'); ?>
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<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 ($event_found==true){
				      if ($action==''){ 
			?>
				<tr><td><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td></tr>
				<tr>
					<td><?php echo tep_draw_form('select_event',FILENAME_EVENTS_SMS_MESSAGES); 
								$selected_name="";
					?>
					<table border="0" cellspacing="0" cellpadding="2" >
						<div id="event_list" style="position:absolute;display:none;width:400px">
							<?php echo tep_draw_event_select_menu('select_id',$events_array,$events_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_EVENT;?></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_event.select_text.addEventListener("keyup",selectList,true);
						if(iex) document.select_event.select_text.onkeyup=selectList;
						if(na6) document.select_event.select_text.addEventListener("keydown",scrollList,true);
						if(iex) document.select_event.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_event,$message_type_array,$fields_type,'SE',$events_id); ?>
								</td>
								</tr>
								<!-- <tr><td><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td></tr>
								<tr>
									<td class="main" align=left>
									<?php 
										//echo '<a id="copy_message_button" href="' . tep_href_link(FILENAME_EVENTS_COPY_MESSAGES,'eID=' . $events_id . '&type=sm') . '">' . tep_image_button('button_copy_messages.gif',IMAGE_COPY_MESSAGES) . "</a>";
									?></td>
								</tr> -->
								</form>
								<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_EVENTS ;?></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_event[]");
			error_result[0]="<?php echo stripslashes(addslashes(ERR_SELECT_MESSAGE));?>";
			error_result[1]="<?php echo stripslashes(addslashes(ERR_SELECT_EVENT));?>";
			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_EVENTS_SMS_MESSAGES,'copy_command=save_message'); ?>');
		document.getElementById('copy_message_load').innerHTML=ajax_image_load;
		}
		
		}
		function copy_message(eID,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_EVENTS_SMS_MESSAGES,'copy_command=copy_message&eID='); ?>'+eID+'&type='+type);
		}
		function close_copy_message(){
		document.getElementById('copy_message_load').style.display='none';
		document.getElementById('copy_message_load').innerHTML='';
		}
</script>	

	<?php function tep_events_copy_message(){ 
	global $HTTP_GET_VARS;
	require(DIR_WS_CLASSES . '/currencies.php');
  	$currencies=new currencies;

	$events_id = (isset($HTTP_GET_VARS['eID']) ?(int)$HTTP_GET_VARS['eID'] : 0);
	$template_type=(isset($HTTP_GET_VARS['type'])?strtolower($HTTP_GET_VARS['type']) : "ev");
	$templates=getTemplates($events_id,$template_type);
	switch($template_type){
	case "sm":
			$table_name=TABLE_EVENTS_SMS_MESSAGES;
			$back_url=FILENAME_EVENTS_SMS_MESSAGES;
			$fields_list="message_send,message_subject,message_text,events_id,message_type";
			break;
	case "ev":
	default:
			$fields_list="message_send,message_subject,message_reply_to,message_text,message_format,events_id,message_type";
			$table_name=TABLE_EVENTS_MESSAGES;
			$back_url=FILENAME_EVENTS_MESSAGES;
	}
	
	// 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 events_id='" . (int)$events_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';
		}
	}
	$events_array=array();
	$event_query=tep_db_query("SELECT e.events_id,ed.events_name from " . TABLE_EVENTS . " e, " . TABLE_EVENTS_DESCRIPTION . " ed where e.events_id=ed.events_id " . EVENTS_CONDITION_STATUS . " order by ed.events_name");
	while($event_result=tep_db_fetch_array($event_query)){
		if ($events_id!=$event_result["events_id"])
			$events_array[$event_result['events_id']]=array('text'=>$event_result['events_name'],'color'=>"#000000");
	}
	// message ends
	
	?>
	<?php echo tep_draw_form("copy_message",FILENAME_EVENTS_COPY_MESSAGES,'action=update&eID=' . $events_id . '&type=' . $template_type,"post",'onSubmit="javascript:return validateForm();"');
	echo tep_draw_hidden_field('eID',$events_id).tep_draw_hidden_field('type',$template_type);
	?>
	<table border="0" width="100%" cellspacing="0" cellpadding="2">
	<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_events_name($events_id); ?></td>
	<td align="right"><?php echo '<a href="javascript: message_validateForm();">'.tep_image(DIR_WS_IMAGES.'template/img_savel.gif','Save','','','Save').'</a>&nbsp;&nbsp;<a href="javascript: close_copy_message();">'.tep_image(DIR_WS_IMAGES.'template/img_closel.gif','Close','','','Close').'</a>'; ?>&nbsp;</td>
	</tr>
	</table></td>
	</tr>		
			<tr>
				<td><?php echo tep_draw_separator('pixel_trans.gif','1','5');?></td>
			</tr>
			<tr>
				<td>
				<table border="0" cellpadding="0" cellspacing="0">
					<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_EVENTS;?></td>
								</tr>
								<tr>
									<td class="tableHeading"><?php echo customListBox("select_message",$templates,0,300,200);?></td>
									<td class="tableHeading"><?php echo customListBox("select_event",$events_array,0,500,200);?></td>
								</tr>
							</table>
						</td>
					</tr>
					<tr>
						<td><?php echo tep_draw_separator('pixel_trans.gif','1','5');?></td>
					</tr>
					<tr><td><br></td></tr>
				</table>
				</td>
			</tr>
		</table>
		</form>
	<?php } ?>
	
	
	<?php  // function used in this page
	function update(){
		global $HTTP_POST_VARS;
		$message_keys=&$HTTP_POST_VARS["select_message"];
		$events_keys=&$HTTP_POST_VARS["select_event"];
	
		$events_id = (isset($HTTP_POST_VARS['eID']) ?(int)$HTTP_POST_VARS['eID'] : 0);
		$template_type=(isset($HTTP_POST_VARS['type'])?strtolower($HTTP_POST_VARS['type']) : "ev");
		$templates=getTemplates($events_id,$template_type);
		switch($template_type){
		case "sm":
			$table_name=TABLE_EVENTS_SMS_MESSAGES;
			$back_url=FILENAME_EVENTS_SMS_MESSAGES;
			$fields_list="message_send,message_subject,message_text,events_id,message_type";
			break;
		case "ev":
		default:
			$fields_list="message_send,message_subject,message_reply_to,message_text,message_format,events_id,message_type";
			$table_name=TABLE_EVENTS_MESSAGES;
			$back_url=FILENAME_EVENTS_MESSAGES;
		}
		$status=array();
		reset($events_keys);
		for ($icnt=0;$icnt<sizeof($events_keys);$icnt++){
			$status[$events_keys[$icnt]]=array();
		}
		//get the input message_ids,events_ids
		$message_string=join("','",$message_keys);
		$events_string=join(",",$events_keys);

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

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

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

				} else { //insert operation
					tep_db_perform($table_name,$message);

				}
			}
		}
	}
	
	function &getTemplates($events_id,$type){
		$templates=array();
		switch($type){
			case "sm": //sms messages
				$templates=array(	'RCF'=>array('text'=>TEXT_TYPE_RCF,'status'=>0,'color'=>'#FF0000'),
									'WCF'=>array('text'=>TEXT_TYPE_WCF,'status'=>0,'color'=>'#FF0000'),
									'RSR'=>array('text'=>TEXT_TYPE_RSR,'status'=>0,'color'=>'#FF0000'),
									'RNR'=>array('text'=>TEXT_TYPE_RNR,'status'=>0,'color'=>'#FF0000'),
									'FDB'=>array('text'=>TEXT_TYPE_FDB,'status'=>0,'color'=>'#FF0000'),
									'WPR'=>array('text'=>TEXT_TYPE_WPR,'status'=>0,'color'=>'#FF0000'),
									'WPL'=>array('text'=>TEXT_TYPE_WPL,'status'=>0,'color'=>'#FF0000')
									);
				break;
			case "ev": // events messages
			default:
				$templates=array(	'RCF'=>array('text'=>TEXT_TYPE_RCF,'status'=>0,'color'=>'#FF0000'),
									'WCF'=>array('text'=>TEXT_TYPE_WCF,'status'=>0,'color'=>'#FF0000'),
									'RNR'=>array('text'=>TEXT_TYPE_RNR,'status'=>0,'color'=>'#FF0000'),
									'FDB'=>array('text'=>TEXT_TYPE_FDB,'status'=>0,'color'=>'#FF0000'),
									'WPR'=>array('text'=>TEXT_TYPE_WPR,'status'=>0,'color'=>'#FF0000'),
									'WPL'=>array('text'=>TEXT_TYPE_WPL,'status'=>0,'color'=>'#FF0000'),
									'WTR'=>array('text'=>TEXT_TYPE_WTR,'status'=>0,'color'=>'#FF0000'),
									'INV'=>array('text'=>TEXT_TYPE_INV,'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];
		}
		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";
		}
		$result.='</table></div>' . "\n";
		echo $result;
	}
?>