document.users_array = [];
document.usersn_array = [];
document.reports_array = [];
document.reportsn_array = [];

function delGroup(id)
{
	if(confirm(lmsg('holidays.admin.edit_groups.del_group_with_subgroups', hp_tree.getItemText(id, 'g_name'))))
	{
		hp_tree.deleteItem(id);
		document.getElementById('manage_group_div').style.display = 'none';
	}
}
function getHPStructure()
{
	// hp_tree.stopEdit();
	hp_tree.setSerializationLevel(1,0);
	return hp_tree.serializeTree();
	/*var items_array = new Array('0');
	var res = '', item_id, i;
	while(item_id = items_array.shift())
	{
		if(hp_tree.hasChildren(item_id)){
			var arr = [];
			arr = explode(',',hp_tree.getSubItems(item_id));
			items_array = items_array.concat(arr);
			for(i=0;i<arr.length;i++)
			{
				var item = arr[i];
				var man1_id = hp_tree.getUserData(item, 'man1_id') ? hp_tree.getUserData(item, 'man1_id') : -1;
				var man2_id = hp_tree.getUserData(item, 'man2_id') ? hp_tree.getUserData(item, 'man2_id') : -1;
				res += ','+item_id+'|'+item+'|'+man1_id+'|'+man2_id;
			}
		}
	}
	return res;*/
}

var to_be_or_not_to_be = false;
function tree_drag()
{
	to_be_or_not_to_be = true;
}

function hp_tree_drag(id, target_id, before_id, base_obj, target_obj)
{
	to_be_or_not_to_be = false;
	if(target_id == 0 || (hp_tree.getItemText(id) && hp_tree.getParentId(id) == 0))
	{
		to_be_or_not_to_be = true;
		return false;
	}
	if(hp_tree.getItemText(id) && (base_obj.parentObject.id != target_obj.parentObject.id))
	{
		alert(document.lc['holidays.admin.edit_groups.alert_we_already_have']+' \''+hp_tree.getItemText(id)+'\' '+document.lc['holidays.admin.edit_groups.alert_in_holidays_groups']);
		to_be_or_not_to_be = true;
		return false;
	}
	var rec_arr = [];
	rec_arr = explode(',',tree.getSubItems(id));
	for(var i=0;i<rec_arr.length;i++)
	{
		if(hp_tree.getItemText(rec_arr[i]) && (base_obj.parentObject.id != target_obj.parentObject.id))
		{
			alert(document.lc['holidays.admin.edit_groups.alert_we_already_have']+' \''+hp_tree.getItemText(rec_arr[i])+'\' '+document.lc['holidays.admin.edit_groups.alert_in_holidays_groups']);
			to_be_or_not_to_be = true;
			return false;
		}
	}
	document.getElementById('manage_group_div').style.display = 'none';
	set_new_flag(id);
	return true;
}

function set_new_flag(id)
{
	tree.setUserData(id, 'new_flag', 1);
	var rec_arr = explode(',',tree.getSubItems(id));
	for(var i=0;i<rec_arr.length;i++)
	{
		tree.setUserData(rec_arr[i], 'new_flag', 1);
		set_new_flag(rec_arr[i]);
	}
}

function zone_action()
{
	var new_node = hp_tree.insertNewChild(0,'newzone','New Zone',onSelectFunc,'supp.gif','supp.gif','supp.gif');
	hp_tree.setUserData(new_node.id, 'state', 1);
	manage_item(new_node.id);
	hp_tree._selectItem(new_node);
}

function onSelectFunc()
{
	var id = hp_tree.getSelectedItemId();
	if(hp_tree.getUserData(id, 'man1_name')){
		window.UserPicker_SetUser('manager1', hp_tree.getUserData(id, 'man1_id'), hp_tree.getUserData(id, 'man1_name'))
	}else{
		window.UserPicker_DeleteSelected('manager1');
	}

	if(hp_tree.getUserData(id, 'man2_name')){
		window.UserPicker_SetUser('manager2', hp_tree.getUserData(id, 'man2_id'), hp_tree.getUserData(id, 'man2_name'))
	}else{
		window.UserPicker_DeleteSelected('manager2');
	}
	manage_item(id);
}

function delZone(id)
{
	if(id == -1){
		alert(lmsg('holidays.admin.edit_groups.cannot_delete_default_zone'));
	}
	if (hp_tree.hasChildren(id)){
		alert(lmsg('holidays.admin.edit_groups.zone_not_empty'));
	}else{
		if(confirm(lmsg('holidays.admin.edit_groups.delete_zone'))) {
			hp_tree.deleteItem(id);
			jQuery('#manage_zone_div').hide();
		}
	}
}

function onEditFunc(state, id, tree, value){
	if(tree.getUserData(id, "state") == 2) return false;
	if(value == ''){
		alert("ERROR: name can't be empty!");
		return false;
	}
	return true;
}

function del_item(id){
	if(hp_tree.getUserData(id, 'state') == 1) return delZone(id);
	return delGroup(id);
}
function add_hp_group(id){
	var new_node = hp_tree.insertNewChild(id,"newhpgroup","New HP Group", onSelectFunc, "h_users.gif", "h_users.gif", "h_users.gif");
	hp_tree.setUserData(new_node.id, 'state', 3);
	hp_tree.setUserData(new_node.id, 'new_flag', 1);
	manage_item(new_node.id);
	hp_tree._selectItem(new_node);
}

function manage_item(id){
	var name = hp_tree.getItemText(id);
	var state = hp_tree.getUserData(id, "state");

	document.getElementById('noSelection').style.display = 'none';
	document.getElementById('btnSave').disabled = false;

	if(state == 1 ){
		document.getElementById('manage_group_div').style.display = 'none';
		document.getElementById('manage_zone_div').style.display = '';
		if(strpos(name, "<input") == -1){
			document.getElementById('hp_zone_name').value = name;
		}
		if (typeof hp_tree.getUserData(id, 'carry_limit') != 'undefined'){
			document.getElementById('zone_carry_limit').value = hp_tree.getUserData(id, 'carry_limit');
		}else{
			document.getElementById('zone_carry_limit').value = 0;
		}
		if (typeof hp_tree.getUserData(id, 'carry_ttl') != 'undefined'){
			document.getElementById('zone_carry_ttl').value = hp_tree.getUserData(id, 'carry_ttl');
		}else{
			document.getElementById('zone_carry_ttl').value = 0;
		}
		var year_start = hp_tree.getUserData(id, 'year_start');
		if (!(year_start > 0 && year_start < 13)){
			year_start = 1;
		}
		$('#zone_year_start').val(year_start);

		return;
	}
	document.getElementById('manage_group_div').style.display = '';
	document.getElementById('manage_zone_div').style.display = 'none';
	if(strpos(name, "<input") == -1){
		document.getElementById('hp_gr_name').value = name;
	}
	document.getElementById('users_select').innerHTML = '';
	document.getElementById('report_perm').innerHTML = '';
	if(state == 3){
		show_users(id);
		show_usr_reports(id);
	} else{
		document.getElementById('select_part').style.display = "none";
	}
	if (state == 2){
		document.getElementById('hp_gr_name').disabled = true;
		show_usr_reports(id);
	}
	if (state == 3){
		document.getElementById('hp_gr_name').disabled = false;
	}
}

function update_group_users(id){
	var arr_id = [], arr_names = [];

	var opts = jQuery('#users_select').find('option:selected');
	jQuery.each(opts, function (index, opt) {
		arr_id.push(opt.value);
		arr_names["user_"+opt.value] = opt.innerHTML;
	});

	document.users_array['hp_'+id] = arr_id;
	document.usersn_array['hp_'+id] = arr_names;
	hp_tree.setUserData(id, 'users', implode("_", arr_id));

}

function update_report_perm(id){
	var arr_id = [], arr_names = [];

	var opts = jQuery('#report_perm').find('option:selected');
	jQuery.each(opts, function (index, opt) {
		arr_id.push(opt.value);
		arr_names["usr_report_"+opt.value] = opt.innerHTML;
	});

	document.reports_array['hp_'+id] = arr_id;
	document.reportsn_array['hp_'+id] = arr_names;
	hp_tree.setUserData(id, 'usr_reports', implode("_", arr_id));

}

function show_users(id){
	document.getElementById('select_part').style.display = "";
	if(typeof document.users_array['hp_'+id] == 'undefined'){
		fill_array(id);
	}
	var el = jQuery("#users_select");
	var hgm_opts = [];
	var arr_id = document.users_array['hp_'+id];
	var arr_names = document.usersn_array['hp_'+id];

    for (var i=0;i<arr_id.length;i++) {
		hgm_opts.push('<option value="'+ arr_id[i] +'" selected="selected">' + escapeHtml(arr_names["user_" + arr_id[i]]) + '</option>');
	}

    var hgm_opts_string = hgm_opts.join("\n");
	jQuery(el).select2('destroy');
	jQuery(el).html(hgm_opts_string);
	UserPicker_InitSelect2('users_select');
}

function show_usr_reports(id){
	document.getElementById('select_part_r').style.display = "";
	if(typeof document.reports_array['hp_'+id] == 'undefined'){
		fill_array_reports(id);
	}
	var el = jQuery("#report_perm");
	var hgm_opts = [];
	var arr_id = document.reports_array['hp_'+id];
	var arr_names = document.reportsn_array['hp_'+id];
	for (var i=0;i<arr_id.length;i++) {
		hgm_opts.push('<option value="'+ arr_id[i] +'" selected="selected">' + escapeHtml(arr_names["usr_report_"+arr_id[i]]) + '</option>');
	}

	var hgm_opts_string = hgm_opts.join("\n");
	jQuery(el).select2('destroy');
	jQuery(el).html(hgm_opts_string);
	UserPicker_InitSelect2('report_perm');
}

function fill_array(id){
	document.users_array['hp_'+id] = explode("_", hp_tree.getUserData(id, "users"));
	var arr = document.users_array['hp_'+id];
	document.usersn_array['hp_'+id] = [];
	for(var i=0;i<arr.length;i++){
		document.usersn_array['hp_'+id]['user_'+arr[i]] = hp_tree.getUserData(id, "user_"+arr[i]);
	}
}

function fill_array_reports(id){
	document.reports_array['hp_'+id] = explode("_", hp_tree.getUserData(id, "usr_reports"));
	var arr = document.reports_array['hp_'+id];
	document.reportsn_array['hp_'+id] = [];
	for(var i=0;i<arr.length;i++){
		document.reportsn_array['hp_'+id]['usr_report_'+arr[i]] = hp_tree.getUserData(id, "usr_report_"+arr[i]);
	}
}

/////////////////////////////////////////////////////////////////

function onManagerChange(id){
	var manager_el = jQuery('#manager' + id + ' option:selected');
	var manager_id = manager_el.val();
	var manager_name = manager_id ? manager_el.text() : '';
	hp_tree.setUserData(hp_tree.getSelectedItemId(), 'man' + id + '_id', manager_id);
	hp_tree.setUserData(hp_tree.getSelectedItemId(), 'man' + id + '_name', manager_name);
}

function onGroupUsersChange(){
	update_group_users(hp_tree.getSelectedItemId());
}


function onReportPermChange(){
	update_report_perm(hp_tree.getSelectedItemId());
}
/////////////////////////////////////////////

function check_name_field(name_field, type) {
	var manage_div = document.getElementById('manage_' + type + '_div');

	if (manage_div.style.display != 'none') {
		var error_div = document.getElementById('error_' + type + '_div');
		if (name_field && name_field.value.length == 0) {
			error_div.style.display = 'block';
			name_field.focus();
	    } else
		{
			error_div.style.display = 'none';
		}
	}
}

function sanitize_name_field(field_value) {
	// completely strip characters that break XML processing.
	field_value = field_value.replace(/[><"&]/g, '');
	return field_value;
}

/**
 * Sanitize string.
 * @param {string} text
 * @returns {string} sanitized string
 */
function escapeHtml(text) {
    var element = document.createElement('span');
    element.textContent = text;

    return element.innerHTML;
}
