<?php
/**
 * Manually Developed CI View - edit_ai_form.php
 *
 * @package			AIR\views
 * @version			2.7
 * @uses
 * @see
 * @copyright		2015, BizyCorp Internal Systems Development
 * @license			private, All rights reserved
 * @author			Mohamed Roshan <roshan@ekwa.com>
 *
 */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Manually Developed CI View
 *
 * This is AIR entry edit form 
 *
 * @package			AIR\views
 * @version			2.7
 * @uses
 * @see
 * @copyright		2015, BizyCorp Internal Systems Development
 * @license			private, All rights reserved
 * @author			Mohamed Roshan <roshan@ekwa.com>
 * @created			Jul 18, 2014
 * @modified        28/04/2016 by MRM Roshan
 * @modification    1. added capitalise(string) JS function to display error messages in formatted strings
 * 					2.do_calling_app_select() and do_called_app_select() functions has been modified 
 * 					Fixed bug id 20509,20534,20535,20496,21453,20485,21884,20524 ,21454	
*/
class Edit_ai_form{
	// Just a dummy clas for phpdoc to catch the doc header.
}
//var_dump($dataset['result_set']);exit;
?>

<head>

<script  src="<?php echo $this->config->item('dhtmlx_lib_url')?>dhtmlxAjax/codebase/dhtmlxcommon.js"></script>

<style>
body{	font-family: Tahoma;	font-size:10pt;}
table{	font-family: Tahoma;	font-size:10pt;}
.form_field_label_class{ 	width:30%;	background:#E3EFFF;	font-size:11pt;}
.form_field_class{ 	width:70%;	background:#E3EFFF;	}
.fieldset_class{ 	width:90%;	}
#formContent{	overflow: auto;	width:100%;	height:100%;	}
.failed { color: red;} 
.failed-active { color: red;}
.confirm {color: green;}
.confirm-active {color: green;}

/*--- for popup window --- */

  .no-display {display:none;}
  .popup-window {
    min-width: 270px;
    /*max-width: 700px; */
    min-height: 200px;
    max-height: 600px;
    overflow: auto;
    background-color: #F5FAFA;
    border: 1px solid #9EB6E9;
    font-size: 0.8em;
    background-repeat: no-repeat;
    /*padding-left: 30px;
    padding-right: 30px; */
    padding-top: 8px;
    box-shadow: 5px 5px 5px gray;
    border-radius: 10px 10px 10px 10px;
    margin-left: calc(12.5%) ;
    position: absolute;
    top: 50px;
    left: -10px; 
    width: calc(75%);
    opacity: 0;
    display: block;
    <?php //$browser = browser_info(); if (isset($browser['firefox'])) echo "z-index: 1;\n";?>
    z-index: 1;
    -webkit-animation: FadeIn 1s linear forwards;
    -moz-animation: FadeIn 1s linear forwards;
    -o-animation: FadeIn 1s linear forwards;
    -ms-animation: FadeIn 1s linear forwards;
    animation: FadeIn 1s linear forwards;
  }
  
  .popup-window, .popup-window-close p {
    text-align: justify;
  }
  
  
  .popup-window-close {
    min-width: 270px;
    /*max-width: 700px; */
    min-height: 200px;
    max-height: 600px; 
    overflow: auto;
  	background-color:#F5FAFA; /*#E4D8D8;*/
  	border:1px solid #9EB6E9; /*#ED969B; */
  	font-size:0.9em;
    background-repeat: no-repeat;
    /*padding-left: 30px;
    padding-right: 30px;*/
    padding-top: 8px;
    box-shadow: 5px 5px 5px gray;
    border-radius: 10px 10px 10px 10px;
    margin-left: calc(12.5%) ;
    position: absolute;
    top: 50px;
    left: -10px; 
    width: calc(75%); 
    z-index: -1; 
    opacity: 1;
    display: block;
    -webkit-animation: FadeOut 1s linear forwards;
    -moz-animation: FadeOut 1s linear forwards;
    -o-animation: FadeOut 1s linear forwards;
    -ms-animation: FadeOut 1s linear forwards;
    animation: FadeOut 1s linear forwards;
  }
  
  @-webkit-keyframes FadeIn {
  	0% { opacity: 0; }
  	10% { opacity: 0.1; z-index: 100; -webkit-transform: translateY(-50px); }
  	50% { opacity: 0.5; -webkit-transform: translateY(-30px);}
  	90% { opacity: 0.9; -webkit-transform: translateY(0px);}
  	100% { opacity: 1; z-index: 100; display: block; }
  }
  
  @-moz-keyframes FadeIn {
  	0% { opacity: 0; z-index: 100; }
  	10% { opacity: 0.1; -moz-transform: translateY(-50px);}
  	50% { opacity: 0.5; -moz-transform: translateY(-30px);}
  	90% { opacity: 0.9; -moz-transform: translateY(0px);}
  	100% { opacity: 1; z-index: 100; display: block;}
  }
  
  @-o-keyframes FadeIn {
  	0% { opacity: 0; }
  	10% { opacity: 0.1; z-index: 100;-o-transform: translateY(-50px);}
  	50% { opacity: 0.5; -o-transform: translateY(-30px);}
  	90% { opacity: 0.9; -o-transform: translateY(0px);}
  	100% { opacity: 100;z-index: 100; display: block;}
  }
  
  @-ms-keyframes FadeIn {
  	0% { opacity: 0; }
  	10% { opacity: 0.1; z-index: 100; -ms-transform: translateY(-50px);}
  	50% { opacity: 0.5; -ms-transform: translateY(-30px);}
  	90% { opacity: 0.9; -ms-transform: translateY(0px);}
  	100% { opacity: 1;  z-index: 100;  display: block;}
  }
  @keyframes FadeIn {
    0%  { opacity: 0; }
    10% { opacity: 0.1; z-index: 100; transform: translateY(-50px);}
    50% { opacity: 0.5; transform: translateY(-30px);}
    90% { opacity: 0.9; transform: translateY(0px);}
    100% { opacity: 01; z-index: 100;  display: block;}
  }
  
  @-webkit-keyframes FadeOut {
  	0% { opacity: 1; z-index: 100;}
  	10% { opacity: 0.9;  -webkit-transform: translateY(0px);}
  	50% { opacity: 0.5;  -webkit-transform: translateY(-30px);}
  	90% { opacity: 0.1; -webkit-transform: translateY(-50px);}
  	100% { opacity: 0; z-index: -1; display: none; }
  }
  
  @-moz-keyframes FadeOut {
  	0% { opacity: 1; }
  	10% { opacity: 0.9; z-index: 100; -moz-transform: translateY(0px);}
  	50% { opacity: 0.5; -moz-transform: translateY(-30px);}
  	90% { opacity: 0.1; -moz-transform: translateY(-50px);}
  	100% { opacity: 0; z-index -1; display: none;}
  }
  
  @-o-keyframes FadeOut {
  	0% { opacity: 1; z-index: 100;}
  	10% { opacity: 0.9; -o-transform: translateY(0px);}
  	50% { opacity: 0.5; -o-transform: translateY(-30px);}
  	90% { opacity: 0.1; -o-transform: translateY(-50px);}
  	100% { opacity: 0; z-index -1; display: none;}
  }
  
  @-ms-keyframes FadeOut {
  	0% { opacity: 1; z-index: 100;}
  	10% { opacity: 0.9; -ms-transform: translateY(0px);}
  	50% { opacity: 0.5; -ms-transform: translateY(-30px);}
  	90% { opacity: 0.1; -ms-transform: translateY(-50px);}
  	100% { opacity: 0; z-index -1; display: none;}
  }
  
  @keyframes FadeOut {
  	0% { opacity: 1; z-index: 100;}
  	10% { opacity: 0.9; transform: translateY(0px);}
  	50% { opacity: 0.5; transform: translateY(-30px);}
  	90% { opacity: 0.1; transform: translateY(-50px);}
  	100% { opacity: 0; z-index -1; display: none;}
  }
  /*---- End popup window ----*/ 




</style>

<script>

//following function is obtained from this url:    
//http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript
function capitalise(string) {
  return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
    
    
function formSubmit(){
	
	var msg_div = document.getElementById('div_gen_msg');
	var totInputs = document.forms[0].elements.length;
	for(var s = 0 ; s<totInputs ; s++ ){
		var curElement = document.forms[0].elements[s];		

		//if current element is a text box
		if(curElement.type == 'text' || curElement.type == 'textarea' || curElement.type == 'select-one'){		
			if(curElement.value == '' || curElement.value == null){
				//alert("Please enter or select appropriate values." );
				var element_name = curElement.name;
				element_name = element_name.replace(/_/g, " ");
				element_name = element_name.replace(/id/g, "");
				element_name = element_name.replace(/intergration/g, "integration");// this is a patch fix to correct element name.MRMR 27/4/2016
				element_name = capitalise(element_name);//make first letter capitalize
				msg_div.innerHTML = '<div class="failed">' + element_name + ' cannot be empty!</div>';
				curElement.focus();				
				return false;
			}
		}		
	}//end for
	
	var con_name = document.getElementById('intergration_name');
	var loader = dhtmlxAjax.getSync('<?php echo base_url('index.php/AppIntegrator/is_name_uniqe/'.$integration_id)?>' + '/' + con_name.value);
	
	if(loader.xmlDoc.responseText == 0){
		//msg_div.innerHTML = '<div class="failed">Integration name is already existing!</div>';
		messagehandler('Integration name is already existing!', 'failure');
		con_name.value='';
		return false;
	}else{
		submitForm();	 
		return true;
	}
	 
}//end of fucntion



function form_reset(){
	 document.forms[0].reset();	    
}



function do_calling_app_select (value){	
	var element = document.getElementById('calling_app_xml_url');
	element.value = '';
}//end of function

function do_called_app_select(value){ 
	
	var calling_app = document.getElementById('calling_app_id');
	var called_app = document.getElementById('called_app_id');
	calleddiv = document.getElementById('calleddiv');
	
	if(calling_app.value == value){
		calleddiv.innerHTML = "You have already selected this application as calling application.Please select another one.";
	    called_app.value = '';		
	}
	var element = document.getElementById('called_app_xml_url');
	element.value = '';
	
}//end of function

function check_app_id_feed_id_cross_check(url,app_id,app_type,div){

	//check if both app id and xml feed are correct combination.
	var loader = dhtmlxAjax.getSync('<?php echo base_url('index.php/AppIntegrator/check_xmlfeed_and_app_id')?>/?xml_feed_url='+ url +'&app_id='+app_id);
	var responce = loader.xmlDoc.responseText;
	if(responce == 2){
		div.innerHTML = 'Given '+app_type+' xml feed URL is incorrect!';
		return false;
	}else if(responce == 0){
		div.innerHTML = 'Selected '+app_type+' name and given '+app_type+' xml URL mismatches!';
		return false;
	}else	return true;			
}//end of function

function getFeedFunctions(element){

	var url = element.value;
	var isValid = null;
	var id = element.id;
	var selid = null;
	var div = null;
	
	if(id == 'calling_app_xml_url'){
		div = document.getElementById('callingdiv');
		selid = 'calling_app_function_id';
	}else{
		div = document.getElementById('calleddiv');
		selid = 'called_app_function_id';
	}
	
	if(url != ''){
		<?php if(ENVIRONMENT != 'localhost'){?>
		isValid = is_valid_url(url);
		<?php }else{?>
		isValid = true;		
		<?php }?>
		
		if(isValid){
			//check if calling or called app id is selected from dropdown
			
			if(id == 'calling_app_xml_url'){
				
				var app_sel = document.getElementById("calling_app_id");				
								
				if (app_sel.value == ''){
					messagehandler('Please select calling application first!', 'failure');
					element.value = '';	
					app_sel.focus();					
					return false;
				}else{
					var responce = check_app_id_feed_id_cross_check(url,app_sel.value,'calling appplication',div);
					if(!responce) return false; 
				}
				
			}else{
				
				var app_sel = document.getElementById("called_app_id");
								
				if (app_sel.value == ''){
					messagehandler('Please select called application first!', 'failure');
					element.value = '';
					app_sel.focus();	
					return false;
				}else{
					
					var responce = check_app_id_feed_id_cross_check(url,app_sel.value,'called appplication',div);
					if(!responce) return false; 
				
				}
			}			
			
			var parts = url.split( '/' );
			var ext = parts[parts.length-1];		
			
			 ext = ext.toLowerCase()
			if(ext != 'share_functions.xml'){
							
				alert('Invalid URL for XML feed');
				element.value = '';
				element.setFocus();
				
			}else{
				
				//fetch xml doc and process
				
				var loader = dhtmlxAjax.getSync('<?php echo base_url('index.php/AppIntegrator/prepare_xml_feed_functions')?>/?url='+ url +'&selid='+selid);
				//alert(loader.xmlDoc.responseText);
				
				div.innerHTML = loader.xmlDoc.responseText;
				
			}				
		} 			
	}
}//end if


function function_paras(sel){
	//
	var sel_id = sel.id;
	var div = document.getElementById('called_app_function_iddiv');
	var sel_html = div.innerHTML;
	var url = null;
	if(sel.value != ""){	
		if(sel_id == 'called_app_function_id'){
			//alert(sel_html);
			url = document.getElementById('called_app_xml_url');
		
			var loader = dhtmlxAjax.getSync('<?php echo base_url('index.php/AppIntegrator/prepare_function_paras')?>/?url='+ url.value + '&func_id=' + sel.value);
			div.innerHTML = '<br>' + loader.xmlDoc.responseText;
				
		}
	}else{
		div.innerHTML = '';
	}//end if
	
}//end of funcion




function function_qstring_builder(url){	
	
	var div = document.getElementById('divQstringBuilder');

	div.setAttribute('class','popup-window');

	var loader = dhtmlxAjax.getSync('<?php echo base_url('index.php/AppIntegrator/prepare_qstring_builder')?>/?url=' + url);
	div.innerHTML = '<br>' + loader.xmlDoc.responseText;

	var closeBtn = document.createElement('img');
	closeBtn.setAttribute('src','http://www.bizydads.com/frameworks/dhtmlx/dhtmlxToolbar/samples/common/imgs/close.gif');		
	closeBtn.setAttribute('style','position: absolute; right: 2px; top: 0px; width: 12px; height: 12px; border: 0px; padding: 0px; margin: 0px; cursor: pointer; z-index: 10000;');
	closeBtn.setAttribute('onclick','{document.getElementById(\'divQstringBuilder\').setAttribute(\'class\',\'popup-window-close\');setTimeout(function(){document.getElementById(\'divQstringBuilder\').setAttribute(\'src\',\'\');},950);}');
	document.getElementById('divQstringBuilder').appendChild(closeBtn);

	
	/*
	document.getElementById('divQstringBuilder').setAttribute('class','popup-window-close');
	setTimeout(function(){
		document.getElementById('popup').innerHTML='';
		document.getElementById('popup').setAttribute('class','');
				},1500);
	*/
	
		
}//end of funcion



function is_valid_url(urlToValidate){
	
	var message;
	var myRegExp =/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;

	if (!myRegExp.test(urlToValidate)){
		return false;
	}else{
		return true;
	}
	
}//end of function

</script>

</head>

<body>

<!-- Div wrapper to display scollbars when form gets lengthy -->
<!-- <div id="formContent">-->

<?php 

// step 1:
// create form object by passing form name
$form = new Form_object('addAppForm');

// step 2:
$form->formWidth = 100; // specify only numeric values for percentage


//if datastring == '' means it has got no data strings/record data
if($dataString == '') {

	// load the form to add record
	$mode='add';
	
	//set header text accordingly
	$hederText = $form_name;
	
	// step 3:
	$form->headerText = array(
			'text' => $hederText,
			'delimiter'=>'<h3>,</h3>'
	);
	
	// step 4:
	//set general message area
	$form->generalMsg = array(
			'text' => $msg['msgText'],
			'delimiter'=>'<div class="gen_msg_class" id="div_gen_msg">,</div>');
	
	// step 5:
	//set formopen tag
	$form->formOpenTag = array(
			'method' => 'post',
			'action' => base_url().'index.php/AppIntegrator/edit/'.$integration_id ,
			'attributes' => array(
					'accept-charset' => 'utf-8',
					'enctype' => 'multipart/form-data',
					'onsubmit' => ''
			)
	);

	// step 6:
	//define field objects (form fields)
	
	

	$integration_id = new Field('integration_id',
			'hidden',
			array(
					'id'=>'integration_id',
					'value'=>$integration_id,
					'label'=>'',
					'before_field' =>'',
					'after_field' => '',
					'required_mark'=>false,
					'field_msg'=>'',
					'style' => ' style="size:100;" '.$disabled
			
			)
	);
	
	$intergration_name = new Field('intergration_name',
			'text',
			array(
					'id'=>'intergration_name',
					'value'=>$intergration_name,
					'label'=>'Integration Name',
					'before_field' =>'',
					'after_field' => '',
					'required_mark'=>true,
					'field_msg'=>'',
					'style' => ' style="size:100;" '.$disabled
					
					)
			);
	
	
	
	$options = file_get_contents(UAACS_URL.'/API/APPAPI/index.php/main/apps/t/0/0/0/0/0/0');
	if(!empty($calling_app_id))
	$options = str_replace("value=\"$calling_app_id\"", "value=\"$calling_app_id\" selected=\"selected\" " , $options);//
		
	$calling_app_id = new field('calling_app_id',
			'empty',
			array(
			'label' => 'Calling Application',
			'required_mark' => true,
			'style' => '<select name="calling_app_id" id="calling_app_id" size="1" class="" onchange="do_calling_app_select(this.value);" '.$disabled.'>
					<option value="" >Select Application</option>'.$options	.'</select>',
			'after_field' => ''	
	));

	
	
	

	$calling_app_xml_url = new Field('calling_app_xml_url',
			'text',
			array(
					'id' => 'calling_app_xml_url',
					'value'=>$calling_app_xml_url,
					'label'=>'Calling App XML URL',
					'before_field' =>'',
					'after_field' => '',
					'required_mark'=>true,
					'field_msg'=>'',
					'style' => ' style="size:250;" size="40" onblur=getFeedFunctions(this)'.$disabled
			
			)
	);

	
	$calling_app_function_id = new field('calling_app_function_id',
		'empty',
		array(
				'label' => 'Calling Application Function',
				'required_mark' => true,
				'style' => '<div id="callingdiv">'.$calling_app_function_select.'</div>',
				'after_field' => ''
		));

	
	$options = file_get_contents(UAACS_URL.'/API/APPAPI/index.php/main/apps/t/0/0/0/0/0/0');
	if(!empty($called_app_id))
		$options = str_replace("value=\"$called_app_id\"", "value=\"$called_app_id\" selected=\"selected\" $disabled " , $options);//
	
	$called_app_id = new field('called_app_id',
			'empty',
			array(
					'label' => 'Called Application',
					'required_mark' => true,
					'style' => '<select name="called_app_id" id="called_app_id" size="1" class="" onchange="do_called_app_select(this.value);" '.$disabled.'>
					<option value="" >Select Application</option>'.$options	.'</select>',
					'after_field' => ''
	
			));

	
	$called_app_xml_url = new Field('called_app_xml_url',
		'text',
		array(
				'id' => 'called_app_xml_url',
				'value'=>$called_app_xml_url,
				'label'=>'Called App XML URL',
				'before_field' =>'',
				'after_field' => '',
				'required_mark'=>true,
				'field_msg'=>'',
				'style' => ' style="size:250;"  size="40" onblur=getFeedFunctions(this)'.$disabled		
		)
	);



	$called_app_function_id = new field('called_app_function_id',
		'empty',
		array(
				'label' => 'Called Application Function',
				'required_mark' => true,
				'style' => '<div id="calleddiv">'.$called_app_function_select.'</div>',
				'after_field' => ''
		));

	$called_app_function_qpara = new field('called_app_function_qpara',
		'empty',
		array(
		'label' => 'Called Application Function parameters',
		'required_mark' => true,
		'style' => '<div id="called_app_function_iddiv">'.$called_app_function_qpara.'</div>',
		'after_field' => ''
			));
	
	
	// step 7:	

	//to display form elements within a formset use following form property
	$form->fieldSets = array(
			'callingApp' => array(
					'legend'=>'Select Applications',
					'attributes' => array(
							'class' => 'fieldset_class',
							'id'=>'fieldset'
							),
					'fields' =>  array(
							$integration_id,
							$intergration_name,
							$calling_app_id,
							$calling_app_xml_url,
							$calling_app_function_id,
							$called_app_id,		
							$called_app_xml_url,
							$called_app_function_id,
							$called_app_function_qpara									
							)
			),
	);



	// step 8:
	// call init() to display the form
	$form->init();

}

?>
<script type="text/javascript">
function messagehandler(message, type){
  switch (type){
    case 'confirmation':
      document.getElementById('div_gen_msg').innerHTML=message;
      document.getElementById('div_gen_msg').setAttribute('class','confirm confirm-active');
      <?php if(isset($message['gridHandler']) && ($message['gridHandler']== 'update' || $message['gridHandler']== 'updateAndClose') ){ ?>
        //parent.dataGrid.updateFromXML(parent.dataGrid.xmlLoader.filePath,true,true);
      <?php } ?>
      setTimeout(function(){document.getElementById('div_gen_msg').setAttribute('class','');
      document.getElementById('div_gen_msg').innerHTML='';
      <?php if (isset($message['gridHandler']) && ($message['gridHandler']== 'close' || $message['gridHandler']== 'updateAndClose')) { ?>
      parent.wb.getFormLayout().collapse();
      <?php } ?>
      },4800);
      break;
    case 'failure':
        
      document.getElementById('div_gen_msg').innerHTML=message;
      document.getElementById('div_gen_msg').setAttribute('class','failed failed-active');
      setTimeout(
    	      function(){
        	      document.getElementById('div_gen_msg').setAttribute('class','');
          		  document.getElementById('div_gen_msg').innerHTML='';
          		  },
          	  4000);
  	  
      break;
    default:
    
  }
}
<?php if (isset($msg)){
 // echo "messagehandler('{$msg['msgText']}','{$msg['msgType']}');";
  //if (isset($msg['focusField'])) echo "document.getElementsByName('{$msg['focusField']}')[0].focus();";
} ?>


<?php

if($status == 1  ){ 
	echo "messagehandler('{$msg['msgText']}','{$msg['msgType']}');";
	?>
	parent.dataGrid.updateFromXML(parent.dataGrid.xmlLoader.filePath,true,true);
	setTimeout(function(){parent.myLayout.collapse();},4000);	
<?php
}else{
	echo "messagehandler('{$msg['msgText']}','{$msg['msgType']}');";	
} 
?>
</script>

</body>

</html>