<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

include_once "../include/config.php";
include_once "../include/config_index.php";
include_once "../common.php";
include_once "../include/config_admin.php";
include_once "../include/functions_admin.php";
include_once "../include/functions_index.php";
include_once "../include/functions_users.php";
include_once "../include/functions_auth.php";
include_once "../include/class.lang.php";
include_once "../include/class.images.php";

$auth = auth_user();
if (isset($auth) && !isset($auth[0])){
    echo "<script type='text/javascript'>location.href='index.php';</script>";
    exit;
}
IsFileAllowed($auth[0], GetRightModulePath(__FILE__));

$sel = isset($_REQUEST['sel']) ? $_REQUEST['sel'] : '';

$multi_lang = new MultiLang($config, $dbconn);
$field_name = $multi_lang->DefaultFieldName();

$smarty -> assign("left_menu_sel", "settings");

switch ($sel){
	case 'user_status': changeUserStatus(); break;
    case 'tooltip': ToolTip(); break;
    case 'save_elements': save_elements(); break;
    case 'save_page_header': save_page_header(); break;
    case 'elem_text': elem_text(); break;
    case 'pages': save_pages(); break;
    case 'pageslang': pageslang(); break;
    case 'delpage': delpage(); break;
    case 'newcustom': newcustom(); break;
    case 'del_text': del_text(); break;
    case 'SetMandatoryFields': SetMandatoryFields(); break;
    case 'captcha': captcha(); break;
	case 'view_targeting': view_targeting(); break;
	case 'save_targeting': save_targeting(); break;
	case 'del_custom': del_custom(); break;
	case 'add_empty_field': AddEmptyField(intval($_REQUEST['page']));
	default: viewBuilder();
}
exit;

function save_targeting(){
	global $dbconn, $auth, $lang, $config;
	$keys = array('country', 'region', 'city', 'looking_for', 'age', 'online', 'show');
	$update = array();
	foreach($keys as $key){
		if(isset($_POST[$key]) && intval($_POST[$key]) == 1){
			$update[] = $key;
		}
	}
	if(count($update) == 0){
		$update = 0;
	}
	else{
		$update = implode(',', $update);
	}
	$strSQL = "UPDATE ".SETTINGS_TABLE." SET value='{$update}' WHERE name='quick_search_targeting';";
	$dbconn->Execute($strSQL);
    
    $min_age_limit = isset($_POST["min_age_limit"]) ? intval($_POST["min_age_limit"]) : 0;
	$max_age_limit = isset($_POST["max_age_limit"]) ? intval($_POST["max_age_limit"]) : 0;
	$strSQL = "Update ".SETTINGS_TABLE." set value='".$min_age_limit."' where name='min_age_limit'";
	$dbconn->Execute($strSQL);
	$strSQL = "Update ".SETTINGS_TABLE." set value='".$max_age_limit."' where name='max_age_limit'";
	$dbconn->Execute($strSQL);
    
    $user_type_i = isset($_POST["index_us_type_i"]) ? $_POST["index_us_type_i"] : '1';
	$user_type_for = isset($_POST["index_us_type_for"]) ? $_POST["index_us_type_for"] : '1';
    $dbconn->Execute("UPDATE ".SETTINGS_TABLE." SET value='".$user_type_i."' WHERE name='index_us_type_i'");
    $dbconn->Execute("UPDATE ".SETTINGS_TABLE." SET value='".$user_type_for."' WHERE name='index_us_type_for'");
    
}

function view_targeting(){
	global $dbconn, $auth, $lang, $config, $config_admin, $multi_lang, $smarty, $settings;
	$smarty->assign("template_root", $config["admin_theme_path"]);
	$checklist = array();
	if($settings['quick_search_targeting'] != 0 || $settings['quick_search_targeting'] != ""){
		$checklist = explode(',', $settings['quick_search_targeting']);
		$tmp = array();
		foreach($checklist as $key){
			$tmp[$key] = 1;
		}
		$checklist = $tmp;
	}
    
    $field_name = $multi_lang->DefaultFieldName();
    $strSQL = "select distinct a.id, b.".$field_name." as name from ".USERTYPES_SPR_TABLE." a left join ".REFERENCE_LANG_TABLE." b on b.table_key='".$multi_lang->TableKey(USERTYPES_SPR_TABLE)."' AND b.id_reference=a.id order by a.sorter ";
	$rs = $dbconn->Execute($strSQL);
	$i = 0;
	while(!$rs ->EOF){
		$user_types_arr[$i]["id"] = $rs->fields[0];
		$user_types_arr[$i]["name"] = $rs->fields[1];
		$rs->MoveNext();
		$i++;
	}	
    $smarty->assign("user_types_i", $user_types_arr);
	$smarty->assign("user_types_for", $user_types_arr);
    $smarty->assign("look_for_user_type", $settings["index_us_type_for"]);
	$smarty->assign("i_am_user_type", $settings["index_us_type_i"]);
            
    $smarty->assign("data", $settings);
	$smarty->assign('checklist', $checklist);
	$smarty->display(TrimSlash($config["admin_theme_path"])."/admin_builder_targeting.tpl");
}

function captcha(){
    global $dbconn, $auth, $lang, $config, $config_admin, $multi_lang, $lang_file, $lang_code;
    $type = intval($_POST["type"]);
    if($type != 1 && $type != 2){
        exit(SetMsgStatus("Error!"));
    }
    if($type == 1){
        $strSQL = "UPDATE ".SETTINGS_TABLE." SET value='0' WHERE name='use_recaptcha';";
        $dbconn->Execute($strSQL);
    }
    if($type == 2){
        $public_key = filter($_POST["public"]);
        $private_key = filter($_POST["private"]);
        if($public_key == "" || $private_key == ""){
            exit(SetMsgStatus("Error!"));
        }
        $strSQL = "UPDATE ".SETTINGS_TABLE." SET value='1' WHERE name='use_recaptcha';";
        $dbconn->Execute($strSQL);
        $strSQL = "UPDATE ".SETTINGS_TABLE." SET value='{$public_key}' WHERE name='recaptcha_public_key';";
        $dbconn->Execute($strSQL);
        $strSQL = "UPDATE ".SETTINGS_TABLE." SET value='{$private_key}' WHERE name='recaptcha_private_key';";
        $dbconn->Execute($strSQL);
    }
    exit(SetMsgStatus("Complete.", 'success'));
}

function del_text(){
    global $dbconn, $auth, /*$lang,*/ $smarty, $config, $config_admin, $multi_lang, $field_name, $lang_file, $lang_code;

    $strSQL = "SELECT name_for_lang FROM ".ELEMENTS." WHERE id='".intval($_POST["id"])."';";
    $dbconn->Execute($strSQL);

    unsetlang(array("profile", $rs->fields[0]));

    $strSQL = "DELETE FROM ".ELEMENTS." WHERE id='".intval($_POST["id"])."';";
    $dbconn->Execute($strSQL);
}

function SetMandatoryFields(){
    global $dbconn, $auth, /*$lang,*/ $smarty, $config, $config_admin, $multi_lang, $field_name, $lang_file, $lang_code;
    $val = ($_POST["val"] == 'false')? 0 : 1;
    $strSQL = "UPDATE ".SETTINGS_TABLE." SET value='".$val."' WHERE name='use_mandatory_fields';";
    $dbconn->Execute($strSQL);
}

function newcustom(){
    global $dbconn, $auth, /*$lang,*/ $smarty, $config, $config_admin, $multi_lang, $field_name, $lang_file, $lang_code;
    $id = $_POST["id"];

    $name_for_lang = "custom_text".rand();

    $strSQL = "SELECT COUNT(id) FROM ".ELEMENTS." WHERE name_for_lang='".$name."';";
    $rs = $dbconn->Execute($strSQL);
    while($rs->fields[0] > 0){
        $name_for_lang .= rand();
        $strSQL = "SELECT COUNT(id) FROM ".ELEMENTS." WHERE name_for_lang='".$name."';";
        $rs = $dbconn->Execute($strSQL);
    }

    $strSQL = "INSERT INTO ".ELEMENTS." (name_for_lang, is_system, mandatory, category, position_text) VALUES ('".$name_for_lang."', '0', '0', 'text_del', 'inline');";
    $dbconn->Execute($strSQL);
    echo $dbconn->Insert_ID()."%%nfl%%".$name_for_lang;
    exit;

}

function delpage(){
    global $dbconn, $auth, /*$lang,*/ $smarty, $config, $config_admin, $multi_lang, $field_name, $lang_file, $lang_code;
    $page = intval($_REQUEST["page"]);
    if ($page < 1)
        return;

    return;
}

function pageslang(){
    global $dbconn, $auth, /*$lang,*/ $smarty, $config, $config_admin, $multi_lang, $field_name, $lang_file, $lang_code;
    $fname = "../".$config["path_lang"].$lang_file[0]."/registration.xml";
    $lang = GetLangContent("registration", $config["path_lang"].$lang_file[0], true);
    if(!isset($_POST["data"]) || $_POST["data"] == "" )
        return;
    $pages_arr = explode(';;', $_POST["data"]);
	
	foreach ($pages_arr as $key => $value) {
		list($page, $str) = explode('::', $value);
        $page = intval($page);
		if($page != 0) {
			$pages_req[] = $page;
		}
		}
	
	$pages[] = $pages_req[0];
	$j=1;
	for($i=1;$i<count($pages_req);$i++){
		$pages[$j] = $pages_req[$i];
		if($pages_req[$i] != $pages_req[$i-1]) $j++;
	}
	$pages_arr_old = explode(',', $_POST["data_old"]);
	for($i=0;$i<count($pages_req);$i++){
		if (isset($pages[$i]))
			$new_key[] = $pages[$i];
		else 
			$new_key[] = count($pages_req);
		$old_key[] = $pages_arr_old[$i];
	}

	if(!isset($_REQUEST["flag"])){
		$strSQL = "SELECT lang_file, code FROM ".LANGUAGE_TABLE.";";
		$rs = $dbconn->Execute($strSQL);
		if ($rs->fields[0] != "") {
			while (!$rs->EOF) {
				$lang_file = explode(".",$rs->fields[0]);
				$lang = GetLangContent("registration", $config["path_lang"].$lang_file[0], true);
				/////////////////////////////////////////
				$lang_arr_old = array();
				for($i=0; $i<count($old_key); $i++){
					print "--".$i."--".$lang["users"]["page"][$old_key[$i]];
					if (isset($lang["users"]["page"][$old_key[$i]]) && $lang["users"]["page"][$old_key[$i]] != '')
						$lang_arr_old[] = $lang["users"]["page"][$old_key[$i]];
					else 
						$lang_arr_old[] = $lang['builder']['new_page_title'];
				}
				$fname = "../".$config["path_lang"].$lang_file[0]."/registration.xml";

				unset($lang["users"]["page"]);
				for($i=0;$i<count($new_key);$i++) {
					$lang["users"]["page"][$new_key[$i]] = $lang_arr_old[$i];
				}
				unset($lang_arr_old);

				$langdata = XML_serialize($lang);

				$fp = fopen ($fname, "w");
				fputs($fp,$langdata);
				fclose($fp);
				unset($langdata);									
				$rs->MoveNext();
			}
		}
	}
	if(!isset($_REQUEST["flag"])){
		$percent = $changed_page = array();
		
		foreach($new_key as $key => $new_page){
			if(isset($old_key[$key]) && $old_key[$key] != $new_page){
				$changed_page[$new_page] = $old_key[$key];
			}
		}
		//change old pages to new
		foreach($changed_page as $new_page=>$old_page){
			$strSQL = "UPDATE ".USER_PERCENT_TABLE." SET page='{$new_page}', percent=percent-101 WHERE page='{$old_page}' AND percent>='0'";
			$rs = $dbconn->Execute($strSQL);
		}
		//delete old pages which number bacame new
		foreach($changed_page as $new_page=>$old_page){
			$strSQL = "DELETE FROM ".USER_PERCENT_TABLE." WHERE page='{$new_page}' AND percent>='0'";
			$rs = $dbconn->Execute($strSQL);
		}
		$dbconn->Execute("UPDATE ".USER_PERCENT_TABLE." SET percent=percent+101 WHERE percent<0");

		$percent_pages_for_del = array_diff($old_key, $new_key);
		$dbconn->Execute("DELETE FROM ".USER_PERCENT_TABLE." WHERE page IN(".implode(',',$percent_pages_for_del).")");
    }
    return;
}


function save_pages(){
    global $dbconn, $auth, /*$lang,*/ $smarty, $config, $config_admin, $multi_lang, $field_name, $lang_file, $lang_code;
    $data = addslashes($_POST["data"]);
    $data_arr = explode(';', $data);
    $strSQL = "UPDATE ".ELEMENTS." SET page=0 WHERE name_for_lang!='id_within';";
    $dbconn->Execute($strSQL);
	DeleteEmptyField($page);
    foreach($data_arr as $key => $value){
        list($page, $in) = explode(':', $value);
        if(intval($page > 0) && strlen($in) > 0){
            $in = substr($in, 0, strlen($in)-1);
            if($in != ""){
                $strSQL = "UPDATE ".ELEMENTS." SET page='".$page."' WHERE id IN (".addslashes($in).");";
                $dbconn->Execute($strSQL);
            }
        }elseif($page && !$in){
			AddEmptyField($page);
		}
    }
}


function elem_text(){
    global $dbconn, $auth, /*$lang,*/ $smarty, $config, $config_admin, $multi_lang, $field_name, $lang_file, $lang_code;
    if($_POST["name_for_lang"] == "")
        return;

    $mandatory = intval($_POST["mandatory"]);
	
	$cust_arr = array('page_1_agreed_1', 'looking_for', 'icon_upload', 'security_code');
	
    if($_POST["couple"] == 'true' || !in_array($_POST["name_for_lang"], $cust_arr))
        $couple = 1;
    else
        $couple = 0;

    $pos = addslashes($_POST["pos"]);
    $name_for_lang = stripslashes($_POST["name_for_lang"]); // javascript sends quoted string, unqoute and qoute again
    $name_for_lang = filter($name_for_lang);


    $strSQL = "UPDATE ".ELEMENTS." SET mandatory='".$mandatory."', couple='".$couple."', position_text='".$pos."' WHERE name_for_lang='".$name_for_lang."';";
    $dbconn->Execute($strSQL);
    if($_POST["html"] == "")
        return;
    $tab = intval($_POST['tabs']);
    $html = ($_POST["html"]);
    $html = trim($html);
    $strSQL = "";
    if($tab == 0){
        $fname = "../".$config["path_lang"].$lang_file[0]."/registration.xml";
        $lang = GetLangContent("registration", $config["path_lang"].$lang_file[0], true);
    }
    if($tab == 2 || $tab == 1 || $tab == 3){
        $fname = "../".$config["path_lang"].$lang_file[0]."/search.xml";
        $lang = GetLangContent("search", $config["path_lang"].$lang_file[0], true);
    }
    $strSQL = "SELECT category FROM ".ELEMENTS." WHERE name_for_lang='{$name_for_lang}';";
    $rs=$dbconn->Execute($strSQL);

    $html = filter($html);
    if($rs->fields[0] == 'custom'){
        $lang["userspr"][$name_for_lang] = $html;
    }
    else{
        $lang["profile"][$name_for_lang] = $html;
    }
    if($tab == 0){
        write_lang($lang, $fname);
    }
    else{
        write_lang($lang, $fname, 1);
    }
    echo $html;
    return;
}

function save_page_header(){
    global $dbconn, $auth, /*$lang,*/ $smarty, $config, $config_admin, $multi_lang, $field_name, $lang_file, $lang_code;
    $page = intval($_POST["page"]);
    if($page < 1)
        return;
    if(!isset($_POST["text"]))
        return;
    $fname = "../".$config["path_lang"].$lang_file[0]."/registration.xml";
    $lang = GetLangContent("registration", $config["path_lang"].$lang_file[0], true);

    $lang["users"]["page"][$page] = filter(strip_tags($_POST["text"]));

    write_lang($lang, $fname);
    return;
}

function unsetlang($keys){
    global $dbconn, $config, $lang_code;
    $strSQL = "SELECT lang_file FROM ".LANGUAGE_TABLE.";";
    $rs = $dbconn->Execute($strSQL);
    if ($rs->fields[0] != "") {
        while (!$rs->EOF) {
            unset($lang);
			$lang_file = explode(".",$rs->fields[0]);
            $fname = "../".$config["path_lang"].$lang_file[0]."/registration.xml";
            $lang = GetLangContent("registration", $config["path_lang"].$lang_file[0], true);

			$str = 'unset($lang["'.implode('"]["',$keys).'"]);';
            eval($str);
			
			$u=1;
			foreach ($lang["users"]["page"] as $key => $value){
				if ($keys[2] == $key){
				}
				else{
					$lang["users"]["page"][$u] = $lang["users"]["page"][$key];
					$u++;
					//unset($lang["users"]["page"][$key]);
				}
			}
			
            $langdata = XML_serialize($lang);
            $tmp_fname= $fname."-".rand();
            $fp = fopen ($tmp_fname, "w");
            fputs($fp,$langdata);
            fclose($fp);

            if (copy($tmp_fname, $fname)){
                unlink($tmp_fname); //
            }

            $rs->MoveNext();
        }
    }
}

function write_lang($lang_input, $fname, $quick = 0){
    global $dbconn, $config, $lang_code;
    if($lang_input == "")
        return;
    $out = "";
    $strSQL = "SELECT lang_file, code FROM ".LANGUAGE_TABLE.";";
    $rs = $dbconn->Execute($strSQL);
    if ($rs->fields[0] != "") {
        while (!$rs->EOF) {
            unset($lang);
            unset($new_lang);
            unset($out);
            unset($res);
            unset($langdata);
			$lang_file = explode(".",$rs->fields[0]);
            $lang = $lang_input;
            if($quick){
                $fname = "../".$config["path_lang"].$lang_file[0]."/search.xml";
                $flngname = "search";
            }
            else{
                $fname = "../".$config["path_lang"].$lang_file[0]."/registration.xml";
                $flngname = "registration";
            }
            if($lang_code != $rs->fields[1]){
                $lang = array_merge_recursive_simple($lang, GetLangContent($flngname, $config["path_lang"].$lang_file[0], true));
            }
            $new_lang = $lang;
            unset($lang);
            $langdata = XML_serialize($new_lang);
            $tmp_fname= $fname."-".rand();
            $fp = fopen ($tmp_fname, "w");
            fputs($fp,$langdata);
            fclose($fp);

            if (copy($tmp_fname, $fname)){
                unlink($tmp_fname); //
            }
            $rs->MoveNext();
        }
    }
}

function save_elements(){
    global $dbconn, $auth, $lang, $smarty, $config, $config_admin, $multi_lang, $field_name;
    if(isset($_POST['tabs']) && intval($_POST['tabs']) == 2){
        if(is_array($_POST["id"])){
            $strSQL = "UPDATE ".ELEMENTS." SET adv_search = '0';";
            $dbconn->Execute($strSQL);
            $i = 0;
            foreach($_POST["id"] as $key => $value){
                if(intval($value)>0){
                    $i++;
                    $strSQL = "UPDATE ".ELEMENTS." SET adv_search = '".$i."' WHERE id = '".intval($value)."';";
                    $dbconn->Execute($strSQL);
                }
            }
        }
    }
    elseif(isset($_POST['tabs']) && intval($_POST['tabs']) == 1){
        if(is_array($_POST["id"])){
            $strSQL = "UPDATE ".ELEMENTS." SET quick_search = '0';";
            $dbconn->Execute($strSQL);
            $i = 0;
            foreach($_POST["id"] as $key => $value){
                if(intval($value)>0){
                    $i++;
                    $strSQL = "UPDATE ".ELEMENTS." SET quick_search = '".$i."' WHERE id = '".intval($value)."';";
                    $dbconn->Execute($strSQL);
                }
            }
        }
    }
    elseif(isset($_POST['tabs']) && intval($_POST['tabs']) == 3){
        if(is_array($_POST["id"])){
            $strSQL = "UPDATE ".ELEMENTS." SET perfect_match = '0';";
            $dbconn->Execute($strSQL);
            $i = 0;
            foreach($_POST["id"] as $key => $value){
                if(intval($value)>0){
                    $i++;
                    $strSQL = "UPDATE ".ELEMENTS." SET perfect_match = '".$i."' WHERE id = '".intval($value)."';";
                    $dbconn->Execute($strSQL);
                }
            }
        }
    }
    else{
        if(isset($_POST["page"])/* && is_array($_POST["id"])*/){
            $page = intval($_POST["page"]);
            if($page < 1)
                return;
            $strSQL = "UPDATE ".ELEMENTS." SET page = '0', page_position = '0' WHERE page = '".$page." AND name_for_lang!='id_within'';";
            $dbconn->Execute($strSQL);
            if(is_array($_POST["id"])){
				DeleteEmptyField($page);
                $ids = array();
                foreach($_POST["id"] as $key => $value){
                    if(intval($value)>0){
                        $ids[] = intval($value);
                        $strSQL = "UPDATE ".ELEMENTS." SET page = '".$page."', page_position = '".($key+1)."' WHERE id = '".intval($value)."';";
                        $dbconn->Execute($strSQL);
                    }
                }
                if(count($ids) > 0){
                    $strSQL = "UPDATE ".ELEMENTS." SET adv_search=0, quick_search=0, perfect_match=0 WHERE id NOT IN (".implode(',',$ids).") AND page='{$page}';";
                    $dbconn->Execute($strSQL);
				}
			}else{
				AddEmptyField($page);
			}
        }
    }
    return;
}

function ToolTip(){
    global $dbconn, $auth, $lang, $smarty, $config, $config_admin, $multi_lang, $field_name, $lang_code, $lang_file;
    /*Sleep(5);*/
	
    $strSQL = "SELECT name_for_lang, mandatory, position_text, elem_html, category, couple, id_spr, tbl FROM ".ELEMENTS." WHERE id = '".intval($_POST["id"])."';";

    $rs = $dbconn->Execute($strSQL);

    $tab = intval($_POST['tabs']);
    $lang = array_merge_recursive_simple($lang, GetLangContent("registration", $config["path_lang"].$lang_file[0], true));
    if($tab == 2 || $tab == 1 || $tab == 3){
        $lang = array_merge_recursive_simple($lang, GetLangContent("search", $config["path_lang"].$lang_file[0], true));
    }

    $elements[0]['name_for_lang'] = $rs->fields[0];
	if ($elements[0]['name_for_lang'] == 'id_within'){
		$strSQL_1 = "SELECT id, name, type FROM " . DISTANCE_SPR_TABLE . " ORDER BY type, name DESC";
		$rs_1 = $dbconn->Execute($strSQL_1);
		$i = 0;
		while (!$rs_1->EOF) {
			$distances_arr[$i]["id"] = $rs_1->fields[0];
			$distances_arr[$i]["name"] = $rs_1->fields[1];
			$distances_arr[$i]["type"] = ($rs_1->fields[2] == "mile") ? $lang["distance"]["mile"] : $lang["distance"]["km"];
			$rs_1->MoveNext();
			$i++;
		}
		$smarty->assign("distances", $distances_arr);
		$smarty->assign("useDistanceSearch", 1);
	}
    $elements[0]['mandatory'] = $rs->fields[1];
    if($tab == 2 || $tab == 1 || $tab == 3)
        $elements[0]['mandatory'] = 0;
    $elements[0]['position_text'] = $rs->fields[2];
    $elements[0]['elem_html'] = $rs->fields[3];
    if($rs->fields[0] == "security_code"){
        if($config["use_recaptcha"] == "1" && $config["recaptcha_public_key"] != "" && $config["recaptcha_private_key"] != ""){
            $elements[0]["elem_html"] = "<img src='{$config["site_root"]}{$config["admin_theme_path"]}{$config["index_theme_images_path"]}/recaptcha.jpg'>";
        }
    }

    $elements[0]['category'] = $rs->fields[4];
    $elements[0]['couple'] = $rs->fields[5];
    $elements[0]['id_spr'] = $rs->fields[6];
    $elements[0]['enable_couple'] = 1;
    if($tab == 2 || $tab == 1 || $tab == 3 || $rs->fields[7] == "USER_MATCH_TABLE" || $rs->fields[7] == "INTERESTS_SPR_MATCH_TABLE" || $rs->fields[7] == "DESCR_SPR_MATCH_TABLE" || $rs->fields[0] == 'icon_upload')
        $elements[0]['enable_couple'] = 0;
    $elements[0]['enable_mandatory'] = 1;

    $disable_couple = Array('im', 'nick', 'email', 'phone', 'looking_for', 'id_relationship', 'site_language', 'headline', 'pass', 'repass', 'page_1_agreed_1', 'subheader_subscribe', 'subheader_subscribe', 'security_code');
    $disable_mandatory = Array('im', 'nick', 'email', 'looking_for', 'pass', 'repass', 'page_1_agreed_1', 'subheader_subscribe', 'security_code', 'fname', 'sname');
    if(in_array($elements[0]['name_for_lang'], $disable_couple) || $elements[0]['category'] == "text_del"){
        $elements[0]['enable_couple'] = 0;
    }
    if(in_array($elements[0]['name_for_lang'], $disable_mandatory) || $elements[0]['category'] == "text_del"){
        $elements[0]['enable_mandatory'] = 0;
    }
	
    $smarty->assign("button", $lang["button"]);
    $smarty->assign("lang", $lang);

    $form = MakeFormHtml($rs->fields[4]);
    $smarty->assign("form", $form);

    $smarty->assign('eval', $elements[0]['elem_html']);
    $elements[0]['elem_html'] = $smarty->fetch(TrimSlash($config["admin_theme_path"])."/admin_eval.tpl"); // через eval в шаблоне
    $smarty->assign("elements", $elements);

    $smarty->display(TrimSlash($config["admin_theme_path"])."/admin_builder_element.tpl");
    exit;
}

function viewBuilder(){
    global $dbconn, $auth, $lang, $smarty, $config, $config_admin, $multi_lang, $field_name, $field_name, $lang_file, $lang_code, $settings;
    $lang_orig = $lang;
    $tab = (isset($_REQUEST["tabs"]))?intval($_REQUEST["tabs"]):0;

    if ($tab == 4){
        header("Location: ".$config["server"]."/admin/admin_reference.php?ref=24");
        exit;
    }
    if ($tab == 5){
        header("Location: ".$config["server"]."/admin/admin_reference.php?ref=23");
        exit;        
    }
    
    $strSQL = "UPDATE ".ELEMENTS." SET page_position=0 WHERE page=0;";
    $dbconn->Execute($strSQL);

    $smarty->assign("use_mandatory_fields", $settings["use_mandatory_fields"]);

    if($tab == 2)
        $strSQL = "SELECT id, name_for_lang, type, is_system, mandatory, position_text, text_html, elem_html, page, page_position, category, adv_search, quick_search FROM ".ELEMENTS." WHERE tbl!= 'USER_ADDON' AND name_for_lang!='_empty_field' ORDER BY adv_search;";
    elseif($tab == 1)
        $strSQL = "SELECT id, name_for_lang, type, is_system, mandatory, position_text, text_html, elem_html, page, page_position, category, adv_search, quick_search FROM ".ELEMENTS." WHERE tbl!= 'USER_ADDON' AND name_for_lang!='_empty_field' ORDER BY quick_search;";
    elseif($tab == 3)
        $strSQL = "SELECT id, name_for_lang, type, is_system, mandatory, position_text, text_html, elem_html, page, page_position, category, adv_search, quick_search, perfect_match FROM ".ELEMENTS." WHERE tbl!= 'USER_ADDON' AND name_for_lang!='_empty_field' ORDER BY perfect_match;";
    else
        $strSQL = "SELECT id, name_for_lang, type, is_system, mandatory, position_text, text_html, elem_html, page, page_position, category FROM ".ELEMENTS." WHERE name_for_lang!='_empty_field';";
    $rs = $dbconn->Execute($strSQL);
    $category = array();

    if ($rs->fields[0] > 0) {
        $i = 0; $elements = array();
        while (!$rs->EOF) {
            $elements[$i]['id'] = $rs->fields[0];
            $elements[$i]['name_for_lang'] = $rs->fields[1];
            $elements[$i]['type'] = $rs->fields[2];
            $elements[$i]['is_system'] = $rs->fields[3];
            $elements[$i]['mandatory'] = $rs->fields[4];
            $elements[$i]['position_text'] = $rs->fields[5];

            $smarty->assign('eval', $rs->fields[7]);
            $elements[$i]['elem_html'] = $smarty->fetch(TrimSlash($config["admin_theme_path"])."/admin_eval.tpl"); //toje sobirat' iz langov

            $elements[$i]['page'] = $rs->fields[8];
            $elements[$i]['page_position'] = $rs->fields[9];
            $elements[$i]['category'] = $rs->fields[10];
            if(!in_array($rs->fields[10], $category))
                $category[] = $rs->fields[10];
            if(isset($rs->fields[11])){
                $elements[$i]['adv_search'] = $rs->fields[11];
            }
            if(isset($rs->fields[12])){
                $elements[$i]['quick_search'] = $rs->fields[12];
            }
            if(isset($rs->fields[13])){
                $elements[$i]['perfect_match'] = intval($rs->fields[13]);
            }

            $rs->MoveNext();
            $i++;
        }
    }
    if($tab == 2 || $tab == 1 || $tab == 3){
        foreach ($elements as $key => $value){
            if($value["name_for_lang"] == "nick")
                unset($elements[$key]);
            if($value["name_for_lang"] == "fname")
                unset($elements[$key]);
            if($value["name_for_lang"] == "sname")
                unset($elements[$key]);
            if($value["name_for_lang"] == "email")
                unset($elements[$key]);
            if($value["name_for_lang"] == "phone")
                unset($elements[$key]);
            if($value["name_for_lang"] == "headline")
                unset($elements[$key]);
            if($value["name_for_lang"] == "pass")
                unset($elements[$key]);
            if($value["name_for_lang"] == "repass")
                unset($elements[$key]);
            if($value["name_for_lang"] == "page_1_agreed_1")
                unset($elements[$key]);
            if($value["name_for_lang"] == "subheader_subscribe")
                unset($elements[$key]);
            if($value["name_for_lang"] == "security_code")
                unset($elements[$key]);
            if($value["name_for_lang"] == "date_birthday")
                unset($elements[$key]);
            if($value["name_for_lang"] == "site_language")
                unset($elements[$key]);
            if($tab == 2){
                if($value["name_for_lang"] == "im")
                    unset($elements[$key]);
            }
        }
    }

    $lang = $smarty->_tpl_vars["lang"];
    unset($smarty->_tpl_vars["lang"]);
    
    $lang = array_merge_recursive_simple($lang, GetLangContent("registration", $config["path_lang"].$lang_file[0], true));
    if($tab == 2 || $tab == 1 || $tab == 3){
        $lang = array_merge_recursive_simple($lang, GetLangContent("search", $config["path_lang"].$lang_file[0], true));
    }
    $lang['builder']['help_add_custelement'] = str_replace("[link]", $config['server']."/admin/admin_reference.php?ref=24", $lang['builder']['help_add_custelement']);    

    $smarty->assign("lang", ($lang));

    foreach($category as $key){ // преобразуем smarty код в элементах в html
        $form = MakeFormHtml($key);

        $smarty->assign("form", $form);
        foreach($elements as $element => $value){
            if($value["category"] == $key){
                $smarty->assign('eval', $value['elem_html']);
                $elements[$element]['elem_html'] = $smarty->fetch(TrimSlash($config["admin_theme_path"])."/admin_eval.tpl"); // через eval в шаблоне
            }
        }
    }

    if($tab != 2 && $tab != 1 && $tab != 3){
        foreach ($elements as $key => $row) {
            $pages[$elements[$key]['page']] = "";
            $page[$key]  = $elements[$key]['page'];
            $page_position[$key] = $elements[$key]['page_position'];
        }
        array_multisort($page_position, SORT_ASC, $page, SORT_ASC, $elements);
        unset($page, $page_position, $pages);
        // Отсортировали по страницам и положению на странице.
       $strSQL = "SELECT DISTINCT page FROM ".ELEMENTS." ORDER BY page;";
        $rs = $dbconn->Execute($strSQL);
        $i = 0; $pages = array();
        while (!$rs->EOF) {
            $pages[]['id'] = $rs->fields[0];
            $rs->MoveNext();
            $i++;
        }
    }

    if (isset($pages))
    $smarty->assign("pages", $pages);

    $lang = $lang_orig;
    AdminMainMenu($lang["addition"]);

    $smarty->assign("elements", $elements);
	$smarty->assign("tabs", $tab);
	$smarty->display(TrimSlash($config["admin_theme_path"])."/admin_builder.tpl");
}

function recurr_strip_lang($in, $gl_out, &$out){
    foreach($in as $key=>$value){
        $tmp = $gl_out."[\"".$key."\"]";
        if(is_array($value)){
            recurr_strip_lang($value, $tmp, $out);
        }
        else{
            $out .= $tmp."='".($value)."';\n";
        }
    }
}

function string_changes($str){
	$str = str_replace("%qt%", "\"", $str);
	return stripslashes($str);
}

function del_custom(){
	global $dbconn;
	$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
	if(!$id) return;
	if ($_REQUEST["par"] == 'tabs-1') {
		$strSQL = "SELECT id, page FROM ".ELEMENTS." WHERE id='".$id."' AND is_system <> '1'";
		$res=$dbconn->Execute($strSQL);
		if(isset($res->fields[0]) && $res->fields[0] > 0) {
			$strSQL = "UPDATE ".ELEMENTS." SET page_position=0, page=0 WHERE id='".$id."'";
			$dbconn->Execute($strSQL);
		}
	} elseif ($_REQUEST["par"] == 'tabs-2') {
		$strSQL = "UPDATE ".ELEMENTS." SET quick_search='0' WHERE id='".$id."'";
		$dbconn->Execute($strSQL);
	} elseif ($_REQUEST["par"] == 'tabs-3') {
		$strSQL = "UPDATE ".ELEMENTS." SET adv_search='0' WHERE id='".$id."'";
		$dbconn->Execute($strSQL);
	} elseif ($_REQUEST["par"] == 'tabs-4') {
		$strSQL = "UPDATE ".ELEMENTS." SET perfect_match='0' WHERE id='".$id."'";
		$dbconn->Execute($strSQL);
	}
}

function DeleteEmptyField($page){
	global $dbconn;
	$dbconn->Execute("DELETE FROM ".ELEMENTS." WHERE name_for_lang='_empty_field' AND page='{$page}'");
}
function AddEmptyField($page){
	global $dbconn;
	$dbconn->Execute("INSERT INTO ".ELEMENTS." SET page='{$page}', page_position='0', name_for_lang='_empty_field'");
}
?>
