<?php
define( 'GS_VALID', true );
require_once( '/usr/share/phonalisa/inc/conf.php' );
require_once( GS_DIR .'inc/util.php' );
include_once( GS_DIR .'inc/gettext.php' );
require_once( GS_DIR .'htdocs/gui/inc/session.php' );  # defines $DB

?>

var forwards;

$(document).ready(function() {
	
	
	$('#notRedirect').click(function(){
		$('#forwardsDisplayArea').fadeOut(800);
		
		$('#simpleRedirectOptions').prop('disabled', true);
		var optionProperties = $("[data-optionid='x']");
		//var optionProperties = document.querySelectorAll('[data-optionid="x"]');
		$(optionProperties).each(function() {
			$(this).prop('disabled', true);
		});
		
		$('#submittButton').click();
	});
	
	$('#immediatelyRedirect').click(function(){
		$('#forwardsDisplayArea').fadeOut(800);
		
		$('#simpleRedirectOptions').prop('disabled', false);
		var optionProperties = $("[data-optionid='x']");
		//var optionProperties = document.querySelectorAll('[data-optionid="x"]');
		$(optionProperties).each(function() {
			$(this).prop('disabled', false);
		});
		
		$('#submittButton').click();
	});
	
	$('#customRedirect').click(function(){
		displayAdvancedRedirect();
		
		$('#forwardsDisplayArea').fadeIn(500);
		
		$('#simpleRedirectOptions').prop('disabled', true);
		var optionProperties = $("[data-optionid='x']");
		//var optionProperties = document.querySelectorAll('[data-optionid="x"]');
		$(optionProperties).each(function() {
			$(this).prop('disabled', true);
		});
		
		$('#submittButton').click();
	});
	


	$('#submittButton').click(function () {
	

	//var optionProperties = document.querySelectorAll('[data-optionid="x"]');
	var optionProperties = $("[data-optionid='x']");
	$(optionProperties).each(function() {
		var fieldName = 'forwards.' + $(this).attr('name'); 
		var fieldValue = "'" + $(this).val() + "'";			
	});
		
	var $inputs = $('#redirectTypes :input');
	
    var values = {};
    
    $inputs.each(function() {
    	var nameString = $(this).attr('name');
    	   	
    	// Skip radio inputs if not checked
    	if($(this).attr("checked") !== 'checked' && $(this).is(':radio')){
    		return true;
    	}
    	
    		
    	//alert(nameString);
    	if(nameString != undefined){
    		
    		var fieldPath = 'forwards.' + nameString;
    		//alert(fieldPath + '= "'+ $(this).val() +'"');
    		
    		//console.log(fieldPath + ' = "'+ $(this).val() +'"');
    		eval(fieldPath + ' = "'+ $(this).val() +'"');

    	}

    });	
		
		var foo = forwards;
		var dataString = JSON.stringify(foo);
		

		updateForwardPriority();	
	 	
	});
	
		
	
	//$.getJSON('http://192.168.24.10/data.js', function(data) {
	
	//alert(setJsonURL);
	$.getJSON(getJsonURL, function(data) {
		forwards = data;
		
		
			
		setUp();
		//displayAdvancedForward(8);
		//displayForwards(forwards);
	});
	
	$(function() {
		$( "#forwardsDisplayArea" ).sortable({
			stop: function(event, ui) {
				updateForwardPriority(event, ui);
			}
		})

		$( ".handle" ).disableSelection();
		

	});
	
	
});


function updateForwardPriority(event, ui){
	if($('input[name="simple[0].target.properties.vmtargetnumber"]').val() != undefined){
		if($('input[name="simple[0].target.properties.vmtargetnumber"]').val() == '' && forwards.active == 'simple'){
			alert(<?php echo "\"". __("PHONESETTINGSCALLFORWARD_MESSAGES_NO_EXTENSION_ERROR")."\"";?> );
	  		return false;
		}
	}
	  	
	var $forwardBoxes = $('#forwardsDisplayArea li');
	 
	
    $forwardBoxes.each(function(index, value) {
    	//var nameString = $(this).attr('name');
    	var forwardId = $(this).attr('id').substring(9);
    	parseInt(forwardId);
    	forwards.advanced[forwardId].position = index;
    });
    
    postJson();
}


function setUp(){
	var activeRedirectType = forwards['active'];
	
	setupSimpleTargets();
	
	if(activeRedirectType == 'none'){

		displayDisabledRedirect();
		$('#notRedirect').click();
		
	}
	else if(activeRedirectType == 'simple'){

		displaySimpleRedirect();
		
	}
	else if(activeRedirectType == 'advanced'){
		
		displayAdvancedRedirect();
		$('#customRedirect').click();
	}
	
	
}

function setupSimpleTargetProperties(){

} 

function setupSimpleTargets(){
	
	var returnString = '<select id="simpleRedirectOptions" disabled="disabled" name="simple[0].target.type" onChange="checkTargetProperitesForSimpleForwardCapability(this)">';
	var additionalFields = '';
	$.each(forwards.possibleTargets, function(targetNum, target){
		var optionStatus = '' ;
		if(target.type == forwards.simple[0].target.type){
			optionStatus = ' selected';
			additionalFields = getSimpleForwardTargetProppertyCapabilities(targetNum);
		}
		returnString += '<option value="'+ target.type + '" '+optionStatus+'>' + target.title + '</option>';
		
	});
	
	returnString += '</select>';
	returnString += additionalFields;
	returnString += '';
	$(returnString).insertAfter('#immediatelyRedirectLabel');
}

function displayDisabledRedirect(){

	$('#notRedirect').prop('checked', true);


}
function displaySimpleRedirect(){

	$('#immediatelyRedirect').prop('checked', true);
	var returnString = '';
	
	
	$('#simpleRedirectOptions').removeAttr("disabled")
	
	$('display').html(returnString);

}
function displayAdvancedRedirect(){

	$('#customRedirect').prop('checked', true);
	
	var sortArray = Array();
	
	var advancedForwardsHtml = '';
	
	advancedForwardsHtml += <?php echo '\'<h4>'.__('PHONESETTINGSCALLFORWARD_CUSTOM_REDIRECT').'<button onclick="addAdvancedForward()" href="#" class="iconButton"><img alt="Add" src="img/list-add.png"></button></h4>\''; ?>;
	
	$.each(forwards.advanced, function(advancedForwardId, advancedForward){
		
		var currentPosition = forwards.advanced[advancedForwardId].position;
		//console.log('currentPosition: ' +currentPosition);
		//console.log(currentPosition);
		sortArray[currentPosition] = advancedForwardId;
		
	});
	
	
	$.each(sortArray, function(position, itemID){
	
		//console.log('Position: ' + position + ' ItemId: ' + itemID);
		
		advancedForwardsHtml += displayAdvancedForward(itemID);
	});
	
	$("#forwardsDisplayArea").html(advancedForwardsHtml);

	
}

function displayForwards(data){

	if(data == ''){
		alert('no data');
	}
	var output = '<ul id="forward-list" class="ui-sortable">';
	
	
  $.each(data, function(key, val) {
   
   //alert(val);
   
	if(key == 'active'){
			if(val = 'none'){
				$('#notRedirect').prop('checked', true);
				exit;
			}
			else if(val = 'simple'){
				$('#immediatelyRedirect').prop('checked', true);
				exit;
			}
			else if(val = 'advanced'){
				$('#customRedirect').prop('checked', true);
				exit;
			}
			return true;		
	}
	

   if(key == 'callforwards'){
		$.each(val, function(callForwardNum, callForward){
			//alert(callForward.type);
			output += "\n";
			output += '<li id="listItem_' + callForward.id + '">';
			output += '<table><tr>';
			output += '<td width="30px"><img width="16" height="16" class="handle" alt="move" src="img/arrow.png"></td>';
			
			output += '<td width="500px" class="lrBorder">';
			
			//alert(callForward.target.type);
			
			output += callForward.target.desc;
						
			output += '</td>';
			
			output += '<td width="30px" style="text-align:center;">';
			output += '<button onclick=editForward('+ callForward.id +')><img src="img/action_edit.png" alt="Edit"></button>';
			output += '<button href="#"><img src="img/list-remove.png" alt="Remove"></button></td>';
			output += '</tr></table>';
			output += '</li>';
		});
		
   } 
   
   
   
  });
	//alert(output);
	output += '</ul>';
	//alert(output);
	$('#forwardsDisplayArea').html(output);
}

function editAdvancedForward(id){
	//alert(forwards.callforwards[id].type);
	var currentForward = forwards.advanced[id];
	
	var editBoxContent = '<table><tr>';
	editBoxContent += '<td width="30px"><img width="16" height="16" class="handle" alt="move" src="img/arrow.png"></td>';
	editBoxContent += '<td width="100%" class="lrBorder"><form class="newForwardRule" id="editForward_'+ id +'">';
	

	editBoxContent += '<p id="addFilterForId_'+id+'"><b><?php echo __("PHONESETTINGSCALLFORWARD_ADD__NEW_FILTER");?> </b><button type="button" onclick="addCriteriaSelectorToForward(' + id + ')" class="iconButton">';
	editBoxContent += '<img alt="Add" src="img/list-add.png"></button><br /><br /></p>';		
	//alert(editBoxContent);
	if(currentForward.type == 'simple'){
		//editBoxContent += 'This is simple forward';
	}
	else if (currentForward.type == 'advanced') {		
		
		$.each(currentForward.criterias, function(criteriaNum, criteria){
			editBoxContent += setupInputsForCriteria(id, criteriaNum, criteria);
		});
		editBoxContent += '</br>' + setupTargetInput(currentForward.target, id);
		
	}
	

	
	editBoxContent += '</form></td>';
	//editBoxContent += '<a id="saveRule" href="#"><img alt="Safe" src="img/action_save.png"></a></form></td>';
	editBoxContent += '<td width="30px"><button onClick="removeAdvancedForward('+id+')" href="#" class="iconButton"><img src="img/list-remove.png" alt="Remove"></button>';
	editBoxContent += '<button type="button" onclick="saveAdvancedForward(' + id + ')" class="iconButton">';
	editBoxContent += '<img src="img/action_save.png" alt="Save"></button></form></td>';
	editBoxContent += '</tr></table>';	
	
	$('#listItem_' + id).html(editBoxContent);
	
}

function setupInputsForCriteria(forwardId, criteriaNum, criteria){
	var returnString = '';
	returnString += '<div id="forwardCriteria_'+forwardId+'_'+criteriaNum+'">';
			
	returnString += setupCreteriaInput(criteria, criteriaNum, forwardId);
	returnString += '<button type="button" onclick="removeForwardCriteria('+forwardId+', '+criteriaNum+')" class="iconButton"><img alt="Remove" src="img/list-remove.png"></button>';
	returnString += '</div>';
	return returnString;
}

function addCriteriaSelectorToForward(forwardId){
	var criteriaSelector = getPosibleCriterias(forwardId);
	
	$(criteriaSelector).insertAfter($('#addFilterForId_'+forwardId));
	//$('#editForward_'+forwardId).prepend(criteriaSelector);
}

function getPosibleCriterias(forwardId){
	retutnString = '';
	
	retutnString += '<select onChange="addCriteriaToForward(this, '+forwardId+')">';
	retutnString += '<option><?php echo __('PHONESETTINGSCALLFORWARD_CHOOSE_CRITERIA');?></option>';
	$.each(forwards.possibleCriterias, function(criteriaName, criteria){
		retutnString += '<option value="'+criteria.name+'">' + criteria.title + '</option>';
	});
	retutnString += '</select>';
	
	return retutnString;
}

function addCriteriaToForward(selectorElement, forwardId){
	if(selectorElement.value != undefined){
		$(selectorElement).remove();
		
		var nextId;
		var lastCriteria = new Object();
		
		$.each(forwards.advanced[forwardId].criterias, function(criteriaNum, criteria){
				nextId = parseInt(criteriaNum) + 1;
				lastCriteria = criteria;
		});
		
		
		
		//var lastCriteriaString = JSON.stringify(lastCriteria);
		var lastCriteriaString = sampleCriteria;
		
		forwards.advanced[forwardId].criterias[nextId] = jQuery.parseJSON(lastCriteriaString);
		var criteria = forwards.advanced[forwardId].criterias[nextId];
		criteria.name = $(selectorElement).val();
		
		var tesx = setupInputsForCriteria(forwardId, nextId, criteria);
		//$('#editForward_'+forwardId).prepend(tesx);
		
		$(tesx).insertAfter($('#addFilterForId_'+forwardId));
		//var	advancedForwardsHtml = displayAdvancedForward(nextId) + '<br />';
		//$("#forwardsDisplayArea").append(advancedForwardsHtml);
	}
		
}



function removeForwardCriteria(forwardId, criteriaId){
	//alert(forwards.advanced[forwardId].criterias[criteriaId]);
	delete forwards.advanced[forwardId].criterias[criteriaId];
	$('#forwardCriteria_'+forwardId+'_'+criteriaId).remove();
	//postJson();
	return false;
}

function saveAdvancedForward(id){
	// DO SAVE HERE	
	
	// collect inputs
	var $inputs = $('#editForward_'+id+' :input');
	
    var values = {};
    $inputs.each(function() {
    	var nameString = $(this).attr('name');  	
    	//alert(nameString);
    	if(nameString != undefined){
    		var fieldPath = 'forwards.' + nameString;
    		
    		if(eval(fieldPath) == undefined){
    			//console.log('new object created');
    		}
    		
    		var inputValue = $(this).val();
    		if($(this).is('input:checkbox')){
    			//alert($(this).val());
    			inputValue = $(this).is(':checked');
    		}
    		
    		//alert(fieldPath + '= "'+ $(this).val() +'"' );
    		eval(fieldPath + '= "'+ inputValue +'"' );

    	}
    	
    });
    
    // Post JSON
	//postJson();
	updateForwardPriority();

	var newForrwardHtml = displayAdvancedForward(id);
	//.replaceWith("<p></p>");	
	$('#listItem_' + id).replaceWith(newForrwardHtml);	
	
	return false;
}

function setupCreteriaInput(criteria, criteriaNum, id, type){
	
	if(type == undefined){
		type = 'advanced';
	}
	
	var returnString = '';
	
	var criteriaPosibilities = forwards.possibleCriterias[criteria.name];
	returnString += criteriaPosibilities.title + ': ';
	
	$.each(criteriaPosibilities.propertyTypes, function(propertyTypeNum, propertyType){
		
		var propertyName = propertyType.name;
		var additionFields = '';
		// INPUTTYPE SELECT
		if(propertyType.type == 'select'){
			var selectName = type +'['+id+']'+'.criterias['+criteriaNum+'].properties.'+propertyName;
			
			returnString += '<select name="'+selectName+'" onChange="checkProperitesForCapability(this, '+id+',' + criteriaNum+', '+propertyTypeNum+')">';
			
			$.each(propertyType.capabilities, function(capabilitiyName, capabilitiy){
				var optionStatus = '';

				if(capabilitiy.name == criteria.properties[propertyName]){
					optionStatus = ' selected';
					
					// This option has additional propperies
					if(capabilitiy.propertyTypes){
						var proppertyAddress = criteriaNum;
						additionFields = getProperitesForCapability(capabilitiy.propertyTypes, id, criteriaNum);
					}
					//			
				}
				returnString += '<option value="'+capabilitiy.name+'"'+optionStatus+'>' + capabilitiy.title + '</option>';
			});		
			
			returnString += '</select>';
			returnString += additionFields;
		}
		
		if(propertyType.type == 'bool'){
			
			var checkedStatus = criteria.properties[propertyName];
			if(checkedStatus == undefined || checkedStatus == 'false'){
				checkedStatus = '';
			}
			else{
				checkedStatus = ' checked="yes"';
			}
			
			var inputName = type +'['+id+']'+'.criterias['+criteriaNum+'].properties.'+propertyName;
			returnString += '<label for="'+inputName+'">'+propertyType.title+'</label>';
			returnString += '<input type="checkbox" name="'+inputName+'" value="" id="'+inputName+'" '+checkedStatus+'  />';
		}
		if(propertyType.type == 'number'){
			var maxValue = '';
			maxValue = propertyType.maxvalue;
			var inLength = maxValue.toString().length;
			var inputName = type +'['+id+']'+'.criterias['+criteriaNum+'].properties.'+propertyName;
			var inputValue = criteria.properties[propertyName];
			if(inputValue == undefined){
				inputValue = '';
			}
			
			returnString += '<label for="'+inputName+'">'+propertyType.title+'</label>';
			returnString += '<input maxlength="'+inLength+'" size="'+inLength+'" name="'+inputName+'" value="'+inputValue+'"></input>';			
		}
	});
	
	return returnString;
	
}

function checkProperitesForCapability(selectedOption, forwardId, citeriaNum, propertyTypeNum){
	
	var criteriaName = forwards.advanced[forwardId].criterias[citeriaNum].name;
	var posibleProperties = forwards.possibleCriterias[criteriaName].propertyTypes[propertyTypeNum].capabilities[selectedOption.value].propertyTypes;
	

	
	// Select poperies inputs from current criteria
	var criteriaProperties = $('[data-citeriaid="'+forwardId+':'+citeriaNum+'"]');
	//var criteriaProperties = document.querySelectorAll('[data-citeriaid="'+forwardId+':'+citeriaNum+'"]');
	$(criteriaProperties).each(function() {
    	// Remove inputs from previous criteria capability
    	$(this).remove();
	});	
	
	if(posibleProperties == undefined){
		return false;
	}

	// Add criteria capability property input if selected capability has one
	
	
	
	if(posibleProperties){
		var additionFields = getProperitesForCapability(posibleProperties, forwardId, citeriaNum);
		$(additionFields).insertAfter(selectedOption);
	}
	
}

function getProperitesForCapability(propertyTypes, forwardId, citeriaNum){
	var returnString = '';
	$.each(propertyTypes, function(propertyNum, property){
		if(property.type == 'numeric'){
			
			var inputValue = forwards.advanced[forwardId].criterias[citeriaNum].properties[property.name];
			if(inputValue == undefined){
				inputValue = '25';
			}
			var inputName = 'advanced[' + forwardId + '].criterias['+citeriaNum+'].properties.'+property.name;
			var customDataType = ' data-citeriaId="'+forwardId+':'+citeriaNum+'"';
			returnString += '<input type="tel" value="'+inputValue+'" name="'+inputName+'" '+customDataType+'  required placeholder="<?php echo __('PHONESETTINGSCALLFORWARD_MESSAGES_ENTRY_MUST_NOT_EMPTY');?>"/>';
		}
	});
	//var returnString = 'here is custom fieled';
	return returnString;	
} 

function setupTargetInput(target, id){
	var returnString = '';
	var additionFields = '';
	//alert('');
	returnString += '<b><?php echo __('Ziel').":";?></b> <select name="advanced['+id+'].target.type" onChange="checkTargetProperitesForCapability(this, '+id+')">';

	$.each(forwards.possibleTargets, function(posibleTargetNum, posibleTarget){
		var optionStatus = '';
		if(target.type == posibleTarget.type){
			optionStatus = ' selected';
			additionFields = getProperitesForTarget(target, posibleTargetNum, id);			
		}
		returnString += '<option' + optionStatus + ' value="'+ posibleTarget.type +'">' + posibleTarget.title + '</option>';
	});
	returnString += '</select>';
	returnString += additionFields;
	
	return returnString;
}

function checkTargetProperitesForCapability(selectedOption, forwardId){
	
	// Select poperies inputs for current target
	
	var targetProperties = $('[data-targetid="'+forwardId+'"]');
	//var targetProperties = document.querySelectorAll('[data-targetid="'+forwardId+'"]');
	
	$(targetProperties).each(function() {
    	// Remove inputs from previous target capability
    	$(this).remove();
	});
	
	// Add property input for capability
	var target = forwards.advanced[forwardId].target;
	var posibleTargetNum = selectedOption.selectedIndex;
	
	var additionFields = getProperitesForTarget(target, posibleTargetNum, forwardId);
	$(additionFields).insertAfter(selectedOption);

}

function getProperitesForTarget(target, posibleTargetNum, id){
	var returnString = '';
	
	var posibleTarget = forwards.possibleTargets[posibleTargetNum];
	var customDataAtribute = ' data-targetid="'+id+'"';
	//var customDataAtribute = ' data-targetid="'+id+':'+posibleTargetNum+'"';
	//alert(posibleTarget.type);
	if(posibleTarget.type == 'number'){
		//returnString += posibleTarget.title + ': ';
		var inputValue = target.properties.number;
		var fieldIdentifier = 'advanced[' + id + '].target.properties.number';
		if(inputValue == undefined){
			inputValue = '';
		}
		returnString += '<input '+customDataAtribute+' type="tel" value="'+ inputValue +'" name="'+ fieldIdentifier +'"  required placeholder="<?php echo __('PHONESETTINGSCALLFORWARD_MESSAGES_ENTRY_MUST_NOT_EMPTY');?>"/>';
	}
	if(posibleTarget.type == 'voicemail' || posibleTarget.type == 'queuevoicemail' || posibleTarget.type == 'announcement'){
		
		//returnString += posibleTarget.title + ': ';
		//var inputValue = target.properties.number;
		//returnString += '<input type="number" value="'+ inputValue +'" />';
		
		var posibleCapabilities = forwards.possibleTargets[posibleTargetNum].propertyTypes[0].capabilities;
		
		if(posibleTarget.propertyTypes[1] != undefined){
			var inputValue = '';
			//console.log('inser here');
			inputValue = forwards.advanced[id].target.properties.vmtargetnumber;
			if(inputValue == undefined){
				inputValue = '';
			}
			//if(forwards.simple[0].target.properties.number != undefined){
			//	inputValue = forwards.simple[0].target.properties.number;
			//}
			returnString += '<label '+customDataAtribute+' >&nbsp;&nbsp;<?php echo __('PHONESETTINGSCALLFORWARD_MESSAGES_EXTENSION');?>:&nbsp;</label>';
			returnString += '<input type="tel" value="'+inputValue+'" '+customDataAtribute+' name="advanced['+id+'].target.properties.vmtargetnumber" required placeholder="<?php echo __('PHONESETTINGSCALLFORWARD_MESSAGES_ENTRY_MUST_NOT_EMPTY');?>" />';
		}
		
		returnString += '<select '+customDataAtribute+' name="advanced['+id+'].target.properties.voicemailfile">';
		
		if(posibleCapabilities == undefined){
			returnString += '<option></option>';
		}
		else{
			$.each(forwards.possibleTargets[posibleTargetNum].propertyTypes[0].capabilities, function(capabilityNum, capability){
				//alert(capability.title);
				var optionStatus = '';
				if(capability.name == target.properties.voicemailfile){
					optionStatus = ' selected';
					//additionFields = getProperitesForTarget(target, posibleTargetNum);			
				}
				returnString += '<option' + optionStatus + ' value="'+capability.name+'">' + capability.title + '</option>';
			});		
		}
		

		
		returnString += '</select>';
	}
	return returnString;
}

function createCreteriaDescription(){
	
}


function showResult(res)
{
  $("#fullresponse").html("Full response: " +res);
  var obj = JSON.parse(res);
}

// OBSERVING
function checkactiveRedirectType(){
	forwards['active'] = $('input[name=redirectType]:checked').val();
	forwards.simple.target.type = $('#simpleRedirectOptions') .val();
	
	forwards.simple.target.properties.voicemailfile = $()
}


function setupTargetInputs(){
	var returnString = '';
	returnString += '<select>';
	$.each(forwards.possibleTargets, function(posibleTargetNum, posibleTarget){
			returnString += '<option>' + posibleTarget['title'] + '</option>';
	});
	returnString += '</select>';
	alert(returnString);
}

function displayAdvancedForward(id){
	
	var returnString = '';
	//console.log(id);
	//id = 0;
	var newForward = forwards.advanced[id];
	returnString += '<li id="listItem_' + id + '">';
	//returnString += '<div name="advanced.'+ id +'">';
	
	returnString += '<table><tr>';
	returnString += '<td width="30px"><img width="16" height="16" class="handle" alt="move" src="img/arrow.png"></td>';
			
	returnString += '<td width="100%" class="lrBorder">';
			
	
	//console.log(newForward)		
	$.each(newForward.criterias, function(creteriaNum, creteria){
		//console.log('passed');
		returnString += displayCriteria(creteria);
	});
	
	returnString += '<p class="forwardTarget"><img src="img/arrow_right.png" /><b>' + newForward.target.title + ':</b> ' + newForward.target.desc + '</p>'+"\n";
						
	returnString += '</td>';
			
	returnString += '<td width="30px" style="text-align:center;">';
	returnString += '<button onclick=editAdvancedForward('+ id +') class="iconButton"><img src="img/action_edit.png" alt="Edit"></button>';
	returnString += '<button href="#" onClick="removeAdvancedForward('+id+')" class="iconButton"><img src="img/list-remove.png" alt="Remove"></button></td>';
	
	returnString += '</tr></table>';		
	returnString += '</li>';
	//returnString += '</div>';
	return returnString; 
}

function removeAdvancedForward(id){
	//console.log(numKeys(forwards.advanced))
	if(numKeys(forwards.advanced) <= 1){
		alert('<?php echo __('PHONESETTINGSCALLFORWARD_MESSAGES_NEED_USER_DEFINED_CALL_FORWARD');?>')
	}
	else{
		
		delete forwards.advanced[id];
	
		$('#listItem_'+id).remove();
		updateForwardPriority();
		postJson();	
	}

}

function numKeys(obj){
    var count = 0;
    for(var prop in obj){
        count++;
    }
    return count;
}

function postJson(){
	var dataString = JSON.stringify(forwards);
	
	//$.post('/mod/ajax/forwardsforwards_forwards.php?setJson', { jsonData: dataString}, showResult, "text");
	  		
	$.ajax({
		type: "POST",
		dataType: "json",
		async: false,
		url: setJsonURL,
		data: { jsonData: dataString },
		success: function(data) {
			
			forwards = data;
  		},
  		error: function(){
  					//alert('Anmelden');
  				}
	});	
	
}

function displayCriteria(creteria){
	var returnString = '';
	//var x = forwards.possibleCriterias[creteria.name].title;
	//alert(x);
	
	returnString += creteria.desc;
	//returnString += forwards.possibleCriterias[creteria.name].title + ': ';
	
	//if(creteria.name == 'PhoneStatus'){
	//	var currentStatus = creteria.properties['phonestatus'];
	//	if(currentStatus == 'noanswer'){
	//		returnString += forwards.possibleCriterias[creteria.name].propertyTypes[0].capabilities[currentStatus].title;
	//		returnString += ' ' + creteria.properties['calltimeout'] + 's';
	//	}
	//	else{
	//		returnString += forwards.possibleCriterias[creteria.name].propertyTypes[0].capabilities[currentStatus].title;
	//	}
		
	//}
	//if(creteria.name == 'JabberStatus'){
	//	var currentStatus = creteria.properties['jabberstatus'];
	//	returnString += forwards.possibleCriterias[creteria.name].propertyTypes[0].capabilities[currentStatus].title;
	//}
	
	returnString += '';
	returnString += '<br />'+"\n";
	return returnString;
}


function saveGlobalForwardSettings(){
	//alert(forwards.simple.target.properties.number);
	// collect inputs
	var $inputs = $('#redirectTypes :input');
	
    var values = {};
    $inputs.each(function() {
    	var nameString = $(this).attr('name');
    	   	
    	// Skip radio inputs if not checked
    	if($(this).attr("checked") !== 'checked' && $(this).is(':radio')){
    		return true;
    	}
    	
    		
    	//alert(nameString);
    	if(nameString != undefined){
    		
    		var fieldPath = 'forwards.' + nameString;
    		//alert(fieldPath + '= "'+ $(this).val() +'"');
    		
    		
    		eval(fieldPath + ' = "'+ $(this).val() +'"');

    	}
    	//alert(forwards.simple.target.properties.number);
		//var testArray = new Array("X", "Y", "XY", "XYZ");
	  	
    	
    	//alert(forwards.simple.target.properties.number);
    });
	
	return false;
}

function addAdvancedForward(){
	var nextId;
	var lastForward = new Object();
	
	var maxId = 0;
	
	$.each(forwards.advanced, function(forwardId, forward){
		if(maxId < forwardId){
			maxId = forwardId;
		}
	});
	

	nextId = parseInt(maxId) + 1;
		
	var lastForwardString = sampleAdvancedForward;
	//var lastForwardString = JSON.stringify(lastForward);
	//console.log(lastForwardString);
	
	forwards.advanced[nextId] = jQuery.parseJSON(lastForwardString);
	
	forwards.advanced[nextId].id = nextId;
		
	var	advancedForwardsHtml = displayAdvancedForward(nextId) + '<br />';
	$("#forwardsDisplayArea").append(advancedForwardsHtml);
	
	editAdvancedForward(nextId);	
}


function checkTargetProperitesForSimpleForwardCapability(selectedOption){
	var returnString = '';
	var posibleTargetNum = selectedOption.selectedIndex;
	var additionalOptions = getSimpleForwardTargetProppertyCapabilities(posibleTargetNum);
	
	var optionProperties = $("[data-optionid='x']");	
	//var optionProperties = document.querySelectorAll('[data-optionid="x"]');
	$(optionProperties).each(function() {
		//console.log(this);
		$(this).remove();
	});
	
	$(additionalOptions).insertAfter($('#simpleRedirectOptions'));
}

function getSimpleForwardTargetProppertyCapabilities(selectedCapabilityIndex){
	var returnString = '';
	var posibleTarget = forwards.possibleTargets[selectedCapabilityIndex].propertyTypes;
	inputName = 'simple[0].target.properties.' + posibleTarget[0].name;
	var posibleTargetTypeName = posibleTarget[0].name;
	
	if(posibleTarget[0].type == 'select'){
		if(posibleTarget[1] != undefined){
			var inputValue = '';
			inputValue = forwards.simple[0].target.properties.vmtargetnumber;
			//if(forwards.simple[0].target.properties.number != undefined){
			//	inputValue = forwards.simple[0].target.properties.number;
			//}
			returnString += '<label data-optionid="x" >&nbsp;&nbsp;<?php echo __('PHONESETTINGSCALLFORWARD_MESSAGES_EXTENSION');?>:&nbsp;</label><input type="tel" value="'+inputValue+'" data-optionid="x" name="simple[0].target.properties.vmtargetnumber" required placeholder="<?php __('PHONESETTINGSCALLFORWARD_MESSAGES_ENTRY_MUST_NOT_EMPTY');?>" />';
		}
		
		var disabledState = '';
		if (forwards['active'] != 'simple'){
			//disabledState = ' disabled="disabled"';
		}
		returnString += '<select data-optionid="x" name="'+inputName+'" '+disabledState+'>';
		
		if(posibleTarget[0].capabilities){
		
			
			$.each(posibleTarget[0].capabilities, function(posibleTargetNum, posibleTarget){
				var optionStatus = '';
				// forwards.simple[0].target.properties.voicemailfile
				//console.log(posibleTarget['name'] + ' : ' + forwards.simple[0].target.properties[posibleTargetTypeName]);
				
				if(posibleTarget['name'] == forwards.simple[0].target.properties[posibleTargetTypeName]){
					optionStatus = ' selected';		
				}
				returnString += '<option value="'+posibleTarget['name']+'" '+optionStatus+'>' + posibleTarget['title'] + '</option>';
			});
		}
		else{
			returnString += '<option><?php echo __('PHONESETTINGSCALLFORWARD_MESSAGES_NO_RECORD_FOUND');?></option>';
		}
		
		returnString += '</select>';
	
	}
	if(posibleTarget[0].type == 'telephonnumber'){
		var inputValue = '';
		if(forwards.simple[0].target.properties.number != undefined){
			inputValue = forwards.simple[0].target.properties.number;
		}
		returnString += '<input type="tel" value="'+inputValue+'" data-optionid="x" name="'+inputName+'"  required placeholder="<?php __('PHONESETTINGSCALLFORWARD_MESSAGES_ENTRY_MUST_NOT_EMPTY');?>" />';
	}
	
	return returnString;
}
