function customers_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('customers');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: Country
    $combo_Country = new Combo();
    $combo_Country->ListType = 0;
    $combo_Country->MultipleSeparator = ', ';
    $combo_Country->ListBoxHeight = 10;
    $combo_Country->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/customers.Country.csv')) {
        $Country_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/customers.Country.csv')));
        $combo_Country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($Country_data)));
        $combo_Country->ListData = $combo_Country->ListItem;
    } else {
        $combo_Country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Afghanistan;;Albania;;Algeria;;American Samoa;;Andorra;;Angola;;Anguilla;;Antarctica;;Antigua, Barbuda;;Argentina;;Armenia;;Aruba;;Australia;;Austria;;Azerbaijan;;Bahamas;;Bahrain;;Bangladesh;;Barbados;;Belarus;;Belgium;;Belize;;Benin;;Bermuda;;Bhutan;;Bolivia;;Bosnia, Herzegovina;;Botswana;;Bouvet Is.;;Brazil;;Brunei Darussalam;;Bulgaria;;Burkina Faso;;Burundi;;Cambodia;;Cameroon;;Canada;;Canary Is.;;Cape Verde;;Cayman Is.;;Central African Rep.;;Chad;;Channel Islands;;Chile;;China;;Christmas Is.;;Cocos Is.;;Colombia;;Comoros;;Congo, D.R. Of;;Congo;;Cook Is.;;Costa Rica;;Croatia;;Cuba;;Cyprus;;Czech Republic;;Denmark;;Djibouti;;Dominica;;Dominican Republic;;Ecuador;;Egypt;;El Salvador;;Equatorial Guinea;;Eritrea;;Estonia;;Ethiopia;;Falkland Is.;;Faroe Is.;;Fiji;;Finland;;France;;French Guiana;;French Polynesia;;French Territories;;Gabon;;Gambia;;Georgia;;Germany;;Ghana;;Gibraltar;;Greece;;Greenland;;Grenada;;Guadeloupe;;Guam;;Guatemala;;Guernsey;;Guinea-bissau;;Guinea;;Guyana;;Haiti;;Heard, Mcdonald Is.;;Honduras;;Hong Kong;;Hungary;;Iceland;;India;;Indonesia;;Iran;;Iraq;;Ireland;;Israel;;Italy;;Ivory Coast;;Jamaica;;Japan;;Jersey;;Jordan;;Kazakhstan;;Kenya;;Kiribati;;Korea, D.P.R Of;;Korea, Rep. Of;;Kuwait;;Kyrgyzstan;;Lao Peoples D.R.;;Latvia;;Lebanon;;Lesotho;;Liberia;;Libyan Arab Jamahiriya;;Liechtenstein;;Lithuania;;Luxembourg;;Macao;;Macedonia, F.Y.R Of;;Madagascar;;Malawi;;Malaysia;;Maldives;;Mali;;Malta;;Mariana Islands;;Marshall Islands;;Martinique;;Mauritania;;Mauritius;;Mayotte;;Mexico;;Micronesia;;Moldova;;Monaco;;Mongolia;;Montserrat;;Morocco;;Mozambique;;Myanmar;;Namibia;;Nauru;;Nepal;;Netherlands Antilles;;Netherlands;;New Caledonia;;New Zealand;;Nicaragua;;Niger;;Nigeria;;Niue;;Norfolk Island;;Norway;;Oman;;Pakistan;;Palau;;Palestinian Terr.;;Panama;;Papua New Guinea;;Paraguay;;Peru;;Philippines;;Pitcairn;;Poland;;Portugal;;Puerto Rico;;Qatar;;Reunion;;Romania;;Russian Federation;;Rwanda;;Samoa;;San Marino;;Sao Tome, Principe;;Saudi Arabia;;Senegal;;Seychelles;;Sierra Leone;;Singapore;;Slovakia;;Slovenia;;Solomon Is.;;Somalia;;South Africa;;South Georgia;;South Sandwich Is.;;Spain;;Sri Lanka;;St. Helena;;St. Kitts, Nevis;;St. Lucia;;St. Pierre, Miquelon;;St. Vincent, Grenadines;;Sudan;;Suriname;;Svalbard, Jan Mayen;;Swaziland;;Sweden;;Switzerland;;Syrian Arab Republic;;Taiwan;;Tajikistan;;Tanzania;;Thailand;;Timor-leste;;Togo;;Tokelau;;Tonga;;Trinidad, Tobago;;Tunisia;;Turkey;;Turkmenistan;;Turks, Caicoss;;Tuvalu;;Uganda;;Ukraine;;United Arab Emirates;;United Kingdom;;United States;;Uruguay;;Uzbekistan;;Vanuatu;;Vatican City;;Venezuela;;Viet Nam;;Virgin Is. British;;Virgin Is. U.S.;;Wallis, Futuna;;Western Sahara;;Yemen;;Yugoslavia;;Zambia;;Zimbabwe")));
        $combo_Country->ListData = $combo_Country->ListItem;
    }
    $combo_Country->SelectName = 'Country';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='customers' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='customers' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `customers` where `CustomerID`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_Country->SelectedData = $row['Country'];
    } else {
        $combo_Country->SelectedText = $_REQUEST['FilterField'][1] == '9' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_Country->Render();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/customers_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/customers_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Detail View', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($arrPerm[1] && !$selected_id) {
        // allow insert and no record selected?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return customers_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return customers_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return customers_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#CustomerID').replaceWith('<div class=\"form-control-static\" id=\"CustomerID\">' + (jQuery('#CustomerID').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#CompanyName').replaceWith('<div class=\"form-control-static\" id=\"CompanyName\">' + (jQuery('#CompanyName').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#ContactName').replaceWith('<div class=\"form-control-static\" id=\"ContactName\">' + (jQuery('#ContactName').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#ContactTitle').replaceWith('<div class=\"form-control-static\" id=\"ContactTitle\">' + (jQuery('#ContactTitle').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#Address').replaceWith('<div class=\"form-control-static\" id=\"Address\">' + (jQuery('#Address').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#City').replaceWith('<div class=\"form-control-static\" id=\"City\">' + (jQuery('#City').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#Region').replaceWith('<div class=\"form-control-static\" id=\"Region\">' + (jQuery('#Region').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#PostalCode').replaceWith('<div class=\"form-control-static\" id=\"PostalCode\">' + (jQuery('#PostalCode').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#Country').replaceWith('<div class=\"form-control-static\" id=\"Country\">' + (jQuery('#Country').val() || '') + '</div>'); jQuery('#Country-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#Phone').replaceWith('<div class=\"form-control-static\" id=\"Phone\">' + (jQuery('#Phone').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#Fax').replaceWith('<div class=\"form-control-static\" id=\"Fax\">' + (jQuery('#Fax').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('.select2-container').hide();\n";
        $noUploads = true;
    } elseif ($AllowInsert && !$selected_id || $AllowUpdate && $selected_id) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(Country)%%>', $combo_Country->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(Country)%%>', $combo_Country->SelectedData, $templateCode);
    /* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
    $lookup_fields = array();
    foreach ($lookup_fields as $luf => $ptfc) {
        $pt_perm = getTablePermissions($ptfc[0]);
        // process foreign key links
        if ($pt_perm['view'] || $pt_perm['edit']) {
            $templateCode = str_replace("<%%PLINK({$luf})%%>", '<button type="button" class="btn btn-default view_parent hspacer-lg" id="' . $ptfc[0] . '_view_parent" title="' . htmlspecialchars($Translation['View'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-eye-open"></i></button>', $templateCode);
        }
        // if user has insert permission to parent table of a lookup field, put an add new button
        if ($pt_perm['insert'] && !$_REQUEST['Embedded']) {
            $templateCode = str_replace("<%%ADDNEW({$ptfc[0]})%%>", '<button type="button" class="btn btn-success add_new_parent" id="' . $ptfc[0] . '_add_new" title="' . htmlspecialchars($Translation['Add New'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
        }
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(CustomerID)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(CompanyName)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ContactName)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ContactTitle)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Address)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(City)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Region)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(PostalCode)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Country)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Phone)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Fax)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(CustomerID)%%>', htmlspecialchars($row['CustomerID'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CustomerID)%%>', urlencode($urow['CustomerID']), $templateCode);
        $templateCode = str_replace('<%%VALUE(CompanyName)%%>', htmlspecialchars($row['CompanyName'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CompanyName)%%>', urlencode($urow['CompanyName']), $templateCode);
        $templateCode = str_replace('<%%VALUE(ContactName)%%>', htmlspecialchars($row['ContactName'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ContactName)%%>', urlencode($urow['ContactName']), $templateCode);
        $templateCode = str_replace('<%%VALUE(ContactTitle)%%>', htmlspecialchars($row['ContactTitle'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ContactTitle)%%>', urlencode($urow['ContactTitle']), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(Address)%%>', nl2br(htmlspecialchars($row['Address'], ENT_QUOTES, 'iso-8859-1')), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(Address)%%>', htmlspecialchars($row['Address'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(Address)%%>', urlencode($urow['Address']), $templateCode);
        $templateCode = str_replace('<%%VALUE(City)%%>', htmlspecialchars($row['City'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode($urow['City']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Region)%%>', htmlspecialchars($row['Region'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Region)%%>', urlencode($urow['Region']), $templateCode);
        $templateCode = str_replace('<%%VALUE(PostalCode)%%>', htmlspecialchars($row['PostalCode'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(PostalCode)%%>', urlencode($urow['PostalCode']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Country)%%>', htmlspecialchars($row['Country'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Country)%%>', urlencode($urow['Country']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Phone)%%>', htmlspecialchars($row['Phone'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Phone)%%>', urlencode($urow['Phone']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Fax)%%>', htmlspecialchars($row['Fax'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Fax)%%>', urlencode($urow['Fax']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(CustomerID)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CustomerID)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(CompanyName)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CompanyName)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ContactName)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ContactName)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ContactTitle)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ContactTitle)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Address)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Address)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(City)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Region)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Region)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(PostalCode)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(PostalCode)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Country)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Country)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Phone)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Phone)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Fax)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Fax)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: customers_dv
    if (function_exists('customers_dv')) {
        $args = array();
        customers_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
示例#2
0
function paddata_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('paddata');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: pdate
    $combo_pdate = new DateCombo();
    $combo_pdate->DateFormat = "mdy";
    $combo_pdate->MinYear = 1900;
    $combo_pdate->MaxYear = 2100;
    $combo_pdate->DefaultDate = parseMySQLDate('', '');
    $combo_pdate->MonthNames = $Translation['month names'];
    $combo_pdate->NamePrefix = 'pdate';
    // combobox: status
    $combo_status = new Combo();
    $combo_status->ListType = 2;
    $combo_status->MultipleSeparator = ', ';
    $combo_status->ListBoxHeight = 10;
    $combo_status->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/paddata.status.csv')) {
        $status_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/paddata.status.csv')));
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($status_data)));
        $combo_status->ListData = $combo_status->ListItem;
    } else {
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("0;1")));
        $combo_status->ListData = $combo_status->ListItem;
    }
    $combo_status->SelectName = 'status';
    // combobox: affiliate
    $combo_affiliate = new Combo();
    $combo_affiliate->ListType = 0;
    $combo_affiliate->MultipleSeparator = ', ';
    $combo_affiliate->ListBoxHeight = 10;
    $combo_affiliate->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/paddata.affiliate.csv')) {
        $affiliate_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/paddata.affiliate.csv')));
        $combo_affiliate->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($affiliate_data)));
        $combo_affiliate->ListData = $combo_affiliate->ListItem;
    } else {
        $combo_affiliate->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("RegNow;Share-It;eSellerate;Plimus;Avangate")));
        $combo_affiliate->ListData = $combo_affiliate->ListItem;
    }
    $combo_affiliate->SelectName = 'affiliate';
    // combobox: clean
    $combo_clean = new Combo();
    $combo_clean->ListType = 2;
    $combo_clean->MultipleSeparator = ', ';
    $combo_clean->ListBoxHeight = 10;
    $combo_clean->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/paddata.clean.csv')) {
        $clean_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/paddata.clean.csv')));
        $combo_clean->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($clean_data)));
        $combo_clean->ListData = $combo_clean->ListItem;
    } else {
        $combo_clean->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("0;1")));
        $combo_clean->ListData = $combo_clean->ListItem;
    }
    $combo_clean->SelectName = 'clean';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='paddata' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='paddata' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `paddata` where `progid`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_pdate->DefaultDate = $row['pdate'];
        $combo_status->SelectedData = $row['status'];
        $combo_affiliate->SelectedData = $row['affiliate'];
        $combo_clean->SelectedData = $row['clean'];
    } else {
        $combo_status->SelectedText = $_REQUEST['FilterField'][1] == '12' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "0";
        $combo_affiliate->SelectedText = $_REQUEST['FilterField'][1] == '31' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_clean->SelectedText = $_REQUEST['FilterField'][1] == '34' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "0";
    }
    $combo_status->Render();
    $combo_affiliate->Render();
    $combo_clean->Render();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/paddata_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/paddata_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'PAD Data', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($AllowInsert) {
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return paddata_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return paddata_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return paddata_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$AllowInsert || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#company').replaceWith('<div class=\"form-control-static\" id=\"company\">' + (jQuery('#company').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#country').replaceWith('<div class=\"form-control-static\" id=\"country\">' + (jQuery('#country').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#website').replaceWith('<div class=\"form-control-static\" id=\"website\">' + (jQuery('#website').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#contactname').replaceWith('<div class=\"form-control-static\" id=\"contactname\">' + (jQuery('#contactname').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#email').replaceWith('<div class=\"form-control-static\" id=\"email\">' + (jQuery('#email').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#title').replaceWith('<div class=\"form-control-static\" id=\"title\">' + (jQuery('#title').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#version').replaceWith('<div class=\"form-control-static\" id=\"version\">' + (jQuery('#version').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#pdate').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#pdateDay, #pdateMonth, #pdateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#cost').replaceWith('<div class=\"form-control-static\" id=\"cost\">' + (jQuery('#cost').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#ptype').replaceWith('<div class=\"form-control-static\" id=\"ptype\">' + (jQuery('#ptype').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('input[name=status]').parent().html('<div class=\"form-control-static\">' + jQuery('input[name=status]:checked').next().text() + '</div>')\n";
        $jsReadOnly .= "\tjQuery('#install').replaceWith('<div class=\"form-control-static\" id=\"install\">' + (jQuery('#install').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#os').replaceWith('<div class=\"form-control-static\" id=\"os\">' + (jQuery('#os').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#languages').replaceWith('<div class=\"form-control-static\" id=\"languages\">' + (jQuery('#languages').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#changeinfo').replaceWith('<div class=\"form-control-static\" id=\"changeinfo\">' + (jQuery('#changeinfo').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#category').replaceWith('<div class=\"form-control-static\" id=\"category\">' + (jQuery('#category').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#requirements').replaceWith('<div class=\"form-control-static\" id=\"requirements\">' + (jQuery('#requirements').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#ksize').replaceWith('<div class=\"form-control-static\" id=\"ksize\">' + (jQuery('#ksize').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#keywords').replaceWith('<div class=\"form-control-static\" id=\"keywords\">' + (jQuery('#keywords').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#description').replaceWith('<div class=\"form-control-static\" id=\"description\">' + (jQuery('#description').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#descrlarge').replaceWith('<div class=\"form-control-static\" id=\"descrlarge\">' + (jQuery('#descrlarge').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#homepage').replaceWith('<div class=\"form-control-static\" id=\"homepage\">' + (jQuery('#homepage').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#screenshot').replaceWith('<div class=\"form-control-static\" id=\"screenshot\">' + (jQuery('#screenshot').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#icon').replaceWith('<div class=\"form-control-static\" id=\"icon\">' + (jQuery('#icon').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#padfile').replaceWith('<div class=\"form-control-static\" id=\"padfile\">' + (jQuery('#padfile').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#download').replaceWith('<div class=\"form-control-static\" id=\"download\">' + (jQuery('#download').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#dlcount').replaceWith('<div class=\"form-control-static\" id=\"dlcount\">' + (jQuery('#dlcount').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#dlipaddr').replaceWith('<div class=\"form-control-static\" id=\"dlipaddr\">' + (jQuery('#dlipaddr').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#aspnumber').replaceWith('<div class=\"form-control-static\" id=\"aspnumber\">' + (jQuery('#aspnumber').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#affiliate').replaceWith('<div class=\"form-control-static\" id=\"affiliate\">' + (jQuery('#affiliate').val() || '') + '</div>'); jQuery('#affiliate-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#affiliateid').replaceWith('<div class=\"form-control-static\" id=\"affiliateid\">' + (jQuery('#affiliateid').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#siterating').replaceWith('<div class=\"form-control-static\" id=\"siterating\">' + (jQuery('#siterating').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('input[name=clean]').parent().html('<div class=\"form-control-static\">' + jQuery('input[name=clean]:checked').next().text() + '</div>')\n";
        $jsReadOnly .= "\tjQuery('#paderrcount').replaceWith('<div class=\"form-control-static\" id=\"paderrcount\">' + (jQuery('#paderrcount').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('.select2-container').hide();\n";
        $noUploads = true;
    } elseif ($AllowInsert) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(pdate)%%>', $selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_pdate->GetHTML(true) . '</div>' : $combo_pdate->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(pdate)%%>', $combo_pdate->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(status)%%>', $combo_status->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(status)%%>', $combo_status->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(affiliate)%%>', $combo_affiliate->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(affiliate)%%>', $combo_affiliate->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(clean)%%>', $combo_clean->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(clean)%%>', $combo_clean->SelectedData, $templateCode);
    /* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
    $lookup_fields = array();
    foreach ($lookup_fields as $luf => $ptfc) {
        $pt_perm = getTablePermissions($ptfc[0]);
        // process foreign key links
        if ($pt_perm['view'] || $pt_perm['edit']) {
            $templateCode = str_replace("<%%PLINK({$luf})%%>", '<button type="button" class="btn btn-default view_parent hspacer-lg" id="' . $ptfc[0] . '_view_parent" title="' . htmlspecialchars($Translation['View'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-eye-open"></i></button>', $templateCode);
        }
        // if user has insert permission to parent table of a lookup field, put an add new button
        if ($pt_perm['insert'] && !$_REQUEST['Embedded']) {
            $templateCode = str_replace("<%%ADDNEW({$ptfc[0]})%%>", '<button type="button" class="btn btn-success add_new_parent" id="' . $ptfc[0] . '_add_new" title="' . htmlspecialchars($Translation['Add New'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
        }
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(progid)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(company)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(country)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(website)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(contactname)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(email)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(title)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(version)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(pdate)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(cost)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ptype)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(status)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(install)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(os)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(languages)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(changeinfo)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(category)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(requirements)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ksize)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(keywords)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(description)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(descrlarge)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(homepage)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(screenshot)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(icon)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(padfile)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(download)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(dlcount)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(dlipaddr)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(aspnumber)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(affiliate)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(affiliateid)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(siterating)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(clean)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(paderrcount)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(progid)%%>', htmlspecialchars($row['progid'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(progid)%%>', urlencode($urow['progid']), $templateCode);
        $templateCode = str_replace('<%%VALUE(company)%%>', htmlspecialchars($row['company'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company)%%>', urlencode($urow['company']), $templateCode);
        $templateCode = str_replace('<%%VALUE(country)%%>', htmlspecialchars($row['country'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode($urow['country']), $templateCode);
        $templateCode = str_replace('<%%VALUE(website)%%>', htmlspecialchars($row['website'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(website)%%>', urlencode($urow['website']), $templateCode);
        $templateCode = str_replace('<%%VALUE(contactname)%%>', htmlspecialchars($row['contactname'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(contactname)%%>', urlencode($urow['contactname']), $templateCode);
        $templateCode = str_replace('<%%VALUE(email)%%>', htmlspecialchars($row['email'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(email)%%>', urlencode($urow['email']), $templateCode);
        $templateCode = str_replace('<%%VALUE(title)%%>', htmlspecialchars($row['title'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(title)%%>', urlencode($urow['title']), $templateCode);
        $templateCode = str_replace('<%%VALUE(version)%%>', htmlspecialchars($row['version'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(version)%%>', urlencode($urow['version']), $templateCode);
        $templateCode = str_replace('<%%VALUE(pdate)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['pdate'], ENT_QUOTES, 'iso-8859-1'))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(pdate)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['pdate'], ENT_QUOTES, 'iso-8859-1')))), $templateCode);
        $templateCode = str_replace('<%%VALUE(cost)%%>', htmlspecialchars($row['cost'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(cost)%%>', urlencode($urow['cost']), $templateCode);
        $templateCode = str_replace('<%%VALUE(ptype)%%>', htmlspecialchars($row['ptype'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ptype)%%>', urlencode($urow['ptype']), $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', htmlspecialchars($row['status'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode($urow['status']), $templateCode);
        $templateCode = str_replace('<%%VALUE(install)%%>', htmlspecialchars($row['install'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(install)%%>', urlencode($urow['install']), $templateCode);
        $templateCode = str_replace('<%%VALUE(os)%%>', htmlspecialchars($row['os'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(os)%%>', urlencode($urow['os']), $templateCode);
        $templateCode = str_replace('<%%VALUE(languages)%%>', htmlspecialchars($row['languages'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(languages)%%>', urlencode($urow['languages']), $templateCode);
        $templateCode = str_replace('<%%VALUE(changeinfo)%%>', htmlspecialchars($row['changeinfo'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(changeinfo)%%>', urlencode($urow['changeinfo']), $templateCode);
        $templateCode = str_replace('<%%VALUE(category)%%>', htmlspecialchars($row['category'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(category)%%>', urlencode($urow['category']), $templateCode);
        $templateCode = str_replace('<%%VALUE(requirements)%%>', htmlspecialchars($row['requirements'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(requirements)%%>', urlencode($urow['requirements']), $templateCode);
        $templateCode = str_replace('<%%VALUE(ksize)%%>', htmlspecialchars($row['ksize'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ksize)%%>', urlencode($urow['ksize']), $templateCode);
        $templateCode = str_replace('<%%VALUE(keywords)%%>', htmlspecialchars($row['keywords'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(keywords)%%>', urlencode($urow['keywords']), $templateCode);
        $templateCode = str_replace('<%%VALUE(description)%%>', htmlspecialchars($row['description'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode($urow['description']), $templateCode);
        $templateCode = str_replace('<%%VALUE(descrlarge)%%>', htmlspecialchars($row['descrlarge'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(descrlarge)%%>', urlencode($urow['descrlarge']), $templateCode);
        $templateCode = str_replace('<%%VALUE(homepage)%%>', htmlspecialchars($row['homepage'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(homepage)%%>', urlencode($urow['homepage']), $templateCode);
        $templateCode = str_replace('<%%VALUE(screenshot)%%>', htmlspecialchars($row['screenshot'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(screenshot)%%>', urlencode($urow['screenshot']), $templateCode);
        $templateCode = str_replace('<%%VALUE(icon)%%>', htmlspecialchars($row['icon'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(icon)%%>', urlencode($urow['icon']), $templateCode);
        $templateCode = str_replace('<%%VALUE(padfile)%%>', htmlspecialchars($row['padfile'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(padfile)%%>', urlencode($urow['padfile']), $templateCode);
        $templateCode = str_replace('<%%VALUE(download)%%>', htmlspecialchars($row['download'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(download)%%>', urlencode($urow['download']), $templateCode);
        $templateCode = str_replace('<%%VALUE(dlcount)%%>', htmlspecialchars($row['dlcount'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(dlcount)%%>', urlencode($urow['dlcount']), $templateCode);
        $templateCode = str_replace('<%%VALUE(dlipaddr)%%>', htmlspecialchars($row['dlipaddr'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(dlipaddr)%%>', urlencode($urow['dlipaddr']), $templateCode);
        $templateCode = str_replace('<%%VALUE(aspnumber)%%>', htmlspecialchars($row['aspnumber'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(aspnumber)%%>', urlencode($urow['aspnumber']), $templateCode);
        $templateCode = str_replace('<%%VALUE(affiliate)%%>', htmlspecialchars($row['affiliate'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(affiliate)%%>', urlencode($urow['affiliate']), $templateCode);
        $templateCode = str_replace('<%%VALUE(affiliateid)%%>', htmlspecialchars($row['affiliateid'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(affiliateid)%%>', urlencode($urow['affiliateid']), $templateCode);
        $templateCode = str_replace('<%%VALUE(siterating)%%>', htmlspecialchars($row['siterating'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(siterating)%%>', urlencode($urow['siterating']), $templateCode);
        $templateCode = str_replace('<%%VALUE(clean)%%>', htmlspecialchars($row['clean'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(clean)%%>', urlencode($urow['clean']), $templateCode);
        $templateCode = str_replace('<%%VALUE(paderrcount)%%>', htmlspecialchars($row['paderrcount'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(paderrcount)%%>', urlencode($urow['paderrcount']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(progid)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(progid)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(company)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(country)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(website)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(website)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(contactname)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(contactname)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(email)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(email)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(title)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(title)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(version)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(version)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(pdate)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(pdate)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(cost)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(cost)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ptype)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ptype)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', '0', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode('0'), $templateCode);
        $templateCode = str_replace('<%%VALUE(install)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(install)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(os)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(os)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(languages)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(languages)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(changeinfo)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(changeinfo)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(category)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(category)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(requirements)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(requirements)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ksize)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ksize)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(keywords)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(keywords)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(description)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(descrlarge)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(descrlarge)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(homepage)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(homepage)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(screenshot)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(screenshot)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(icon)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(icon)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(padfile)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(padfile)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(download)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(download)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(dlcount)%%>', '0', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(dlcount)%%>', urlencode('0'), $templateCode);
        $templateCode = str_replace('<%%VALUE(dlipaddr)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(dlipaddr)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(aspnumber)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(aspnumber)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(affiliate)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(affiliate)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(affiliateid)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(affiliateid)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(siterating)%%>', '0', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(siterating)%%>', urlencode('0'), $templateCode);
        $templateCode = str_replace('<%%VALUE(clean)%%>', '0', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(clean)%%>', urlencode('0'), $templateCode);
        $templateCode = str_replace('<%%VALUE(paderrcount)%%>', '0', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(paderrcount)%%>', urlencode('0'), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_REQUEST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" data-lightbox=".*?"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: paddata_dv
    if (function_exists('paddata_dv')) {
        $args = array();
        paddata_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
示例#3
0
function outcomes_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('outcomes');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_outcome_area = thisOr(undo_magic_quotes($_REQUEST['filterer_outcome_area']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: outcome_area
    $combo_outcome_area = new DataCombo();
    // combobox: strata
    $combo_strata = new Combo();
    $combo_strata->ListType = 0;
    $combo_strata->MultipleSeparator = ', ';
    $combo_strata->ListBoxHeight = 10;
    $combo_strata->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/outcomes.strata.csv')) {
        $strata_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/outcomes.strata.csv')));
        $combo_strata->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($strata_data)));
        $combo_strata->ListData = $combo_strata->ListItem;
    } else {
        $combo_strata->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Individuals;;Community, Sector & Society")));
        $combo_strata->ListData = $combo_strata->ListItem;
    }
    $combo_strata->SelectName = 'strata';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='outcomes' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='outcomes' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `outcomes` where `outcome_id`='" . makeSafe($selected_id) . "'", $eo);
        $row = mysql_fetch_array($res);
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_outcome_area->SelectedData = $row['outcome_area'];
        $combo_strata->SelectedData = $row['strata'];
    } else {
        $combo_outcome_area->SelectedData = $filterer_outcome_area;
        $combo_strata->SelectedText = $_REQUEST['FilterField'][1] == '4' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_outcome_area->HTML = $combo_outcome_area->MatchText = '<span id="outcome_area-container' . $rnd1 . '"></span><input type="hidden" name="outcome_area" id="outcome_area' . $rnd1 . '">';
    $combo_strata->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_outcome_area__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['outcome_area'] : $filterer_outcome_area);
    ?>
"};
		
		jQuery(function() {
			outcome_area_reload__RAND__();
		});
		function outcome_area_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#outcome_area-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_outcome_area__RAND__.value, t: 'outcomes', f: 'outcome_area' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="outcome_area"]').val(resp.results[0].id);


						if(typeof(outcome_area_update_autofills__RAND__) == 'function') outcome_area_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'outcomes', f: 'outcome_area' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_outcome_area__RAND__.value = e.added.id;
				current_outcome_area__RAND__.text = e.added.text;
				jQuery('[name="outcome_area"]').val(e.added.id);


				if(typeof(outcome_area_update_autofills__RAND__) == 'function') outcome_area_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_outcome_area__RAND__.value, t: 'outcomes', f: 'outcome_area' }
			}).done(function(resp){
				jQuery('#outcome_area-container__RAND__').html('<span id="outcome_area-match-text">' + resp.results[0].text + '</span>');

				if(typeof(outcome_area_update_autofills__RAND__) == 'function') outcome_area_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/outcomes_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/outcomes_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Outcome details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    // process buttons
    if ($arrPerm[1]) {
        // allow insert?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return outcomes_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return outcomes_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return outcomes_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$arrPerm[1] || !$selected_id && !$arrPerm[1]) {
        $jsReadOnly .= "\tjQuery('#outcome_area').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#outcome_area_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#description').replaceWith('<p class=\"form-control-static\" id=\"description\">' + (jQuery('#description').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#strata').replaceWith('<p class=\"form-control-static\" id=\"strata\">' + (jQuery('#strata').val() || '') + '</p>'); jQuery('#strata-multi-selection-help').hide();\n";
        $noUploads = true;
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(outcome_area)%%>', $combo_outcome_area->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(outcome_area)%%>', $combo_outcome_area->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(outcome_area)%%>', urlencode($combo_outcome_area->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(strata)%%>', $combo_strata->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(strata)%%>', $combo_strata->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(outcome_area)%%>', $combo_outcome_area->SelectedData ? "<span id=\"outcome_areas_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"outcome_areas_view.php?SelectedID=" . urlencode($combo_outcome_area->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(outcome_id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(outcome_area)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(description)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(strata)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(outcome_id)%%>', htmlspecialchars($row['outcome_id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_id)%%>', urlencode($urow['outcome_id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(outcome_area)%%>', htmlspecialchars($row['outcome_area'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_area)%%>', urlencode($urow['outcome_area']), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(description)%%>', nl2br(htmlspecialchars($row['description'], ENT_QUOTES)), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(description)%%>', htmlspecialchars($row['description'], ENT_QUOTES), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode($urow['description']), $templateCode);
        $templateCode = str_replace('<%%VALUE(strata)%%>', htmlspecialchars($row['strata'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(strata)%%>', urlencode($urow['strata']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(outcome_id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(outcome_area)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_area)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(description)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(strata)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(strata)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>jQuery(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\tjQuery('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= "<script>";
    $templateCode .= "document.observe('dom:loaded', function() {";
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: outcomes_dv
    if (function_exists('outcomes_dv')) {
        $args = array();
        outcomes_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
示例#4
0
function entries_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('entries');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_report = thisOr(undo_magic_quotes($_REQUEST['filterer_report']), '');
    $filterer_outcome = thisOr(undo_magic_quotes($_REQUEST['filterer_outcome']), '');
    $filterer_indicator = thisOr(undo_magic_quotes($_REQUEST['filterer_indicator']), '');
    $filterer_beneficiary_group = thisOr(undo_magic_quotes($_REQUEST['filterer_beneficiary_group']), '');
    // populate filterers, starting from children to grand-parents
    if ($filterer_indicator && !$filterer_outcome) {
        $filterer_outcome = sqlValue("select outcome from indicators where indicator_id='" . makeSafe($filterer_indicator) . "'");
    }
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: created
    $combo_created = new DateCombo();
    $combo_created->DateFormat = "dmy";
    $combo_created->MinYear = 1900;
    $combo_created->MaxYear = 2100;
    $combo_created->DefaultDate = parseMySQLDate('<%%creationDate%%>', '<%%creationDate%%>');
    $combo_created->MonthNames = $Translation['month names'];
    $combo_created->NamePrefix = 'created';
    // combobox: report
    $combo_report = new DataCombo();
    // combobox: outcome
    $combo_outcome = new DataCombo();
    // combobox: indicator, filterable by: outcome
    $combo_indicator = new DataCombo();
    // combobox: beneficiary_group
    $combo_beneficiary_group = new DataCombo();
    // combobox: beneficiary_group_relevance
    $combo_beneficiary_group_relevance = new Combo();
    $combo_beneficiary_group_relevance->ListType = 0;
    $combo_beneficiary_group_relevance->MultipleSeparator = ', ';
    $combo_beneficiary_group_relevance->ListBoxHeight = 10;
    $combo_beneficiary_group_relevance->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/entries.beneficiary_group_relevance.csv')) {
        $beneficiary_group_relevance_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/entries.beneficiary_group_relevance.csv')));
        $combo_beneficiary_group_relevance->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($beneficiary_group_relevance_data)));
        $combo_beneficiary_group_relevance->ListData = $combo_beneficiary_group_relevance->ListItem;
    } else {
        $combo_beneficiary_group_relevance->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("1;;2;;3;;4;;5")));
        $combo_beneficiary_group_relevance->ListData = $combo_beneficiary_group_relevance->ListItem;
    }
    $combo_beneficiary_group_relevance->SelectName = 'beneficiary_group_relevance';
    // combobox: reliability
    $combo_reliability = new Combo();
    $combo_reliability->ListType = 0;
    $combo_reliability->MultipleSeparator = ', ';
    $combo_reliability->ListBoxHeight = 10;
    $combo_reliability->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/entries.reliability.csv')) {
        $reliability_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/entries.reliability.csv')));
        $combo_reliability->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($reliability_data)));
        $combo_reliability->ListData = $combo_reliability->ListItem;
    } else {
        $combo_reliability->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("1;;2;;3;;4;;5")));
        $combo_reliability->ListData = $combo_reliability->ListItem;
    }
    $combo_reliability->SelectName = 'reliability';
    // combobox: intentionality
    $combo_intentionality = new Combo();
    $combo_intentionality->ListType = 0;
    $combo_intentionality->MultipleSeparator = ', ';
    $combo_intentionality->ListBoxHeight = 10;
    $combo_intentionality->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/entries.intentionality.csv')) {
        $intentionality_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/entries.intentionality.csv')));
        $combo_intentionality->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($intentionality_data)));
        $combo_intentionality->ListData = $combo_intentionality->ListItem;
    } else {
        $combo_intentionality->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("1;;2;;3;;4;;5")));
        $combo_intentionality->ListData = $combo_intentionality->ListItem;
    }
    $combo_intentionality->SelectName = 'intentionality';
    // combobox: equivalence
    $combo_equivalence = new Combo();
    $combo_equivalence->ListType = 0;
    $combo_equivalence->MultipleSeparator = ', ';
    $combo_equivalence->ListBoxHeight = 10;
    $combo_equivalence->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/entries.equivalence.csv')) {
        $equivalence_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/entries.equivalence.csv')));
        $combo_equivalence->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($equivalence_data)));
        $combo_equivalence->ListData = $combo_equivalence->ListItem;
    } else {
        $combo_equivalence->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("1;;2;;3;;4;;5")));
        $combo_equivalence->ListData = $combo_equivalence->ListItem;
    }
    $combo_equivalence->SelectName = 'equivalence';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='entries' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='entries' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `entries` where `entry_id`='" . makeSafe($selected_id) . "'", $eo);
        $row = mysql_fetch_array($res);
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_created->DefaultDate = $row['created'];
        $combo_report->SelectedData = $row['report'];
        $combo_outcome->SelectedData = $row['outcome'];
        $combo_indicator->SelectedData = $row['indicator'];
        $combo_beneficiary_group->SelectedData = $row['beneficiary_group'];
        $combo_beneficiary_group_relevance->SelectedData = $row['beneficiary_group_relevance'];
        $combo_reliability->SelectedData = $row['reliability'];
        $combo_intentionality->SelectedData = $row['intentionality'];
        $combo_equivalence->SelectedData = $row['equivalence'];
    } else {
        $combo_report->SelectedData = $filterer_report;
        $combo_outcome->SelectedData = $filterer_outcome;
        $combo_indicator->SelectedData = $filterer_indicator;
        $combo_beneficiary_group->SelectedData = $filterer_beneficiary_group;
        $combo_beneficiary_group_relevance->SelectedText = $_REQUEST['FilterField'][1] == '10' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_reliability->SelectedText = $_REQUEST['FilterField'][1] == '13' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_intentionality->SelectedText = $_REQUEST['FilterField'][1] == '14' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_equivalence->SelectedText = $_REQUEST['FilterField'][1] == '15' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_report->HTML = $combo_report->MatchText = '<span id="report-container' . $rnd1 . '"></span><input type="hidden" name="report" id="report' . $rnd1 . '">';
    $combo_outcome->HTML = $combo_outcome->MatchText = '<span id="outcome-container' . $rnd1 . '"></span><input type="hidden" name="outcome" id="outcome' . $rnd1 . '">';
    $combo_indicator->HTML = $combo_indicator->MatchText = '<span id="indicator-container' . $rnd1 . '"></span><input type="hidden" name="indicator" id="indicator' . $rnd1 . '">';
    $combo_beneficiary_group->HTML = $combo_beneficiary_group->MatchText = '<span id="beneficiary_group-container' . $rnd1 . '"></span><input type="hidden" name="beneficiary_group" id="beneficiary_group' . $rnd1 . '">';
    $combo_beneficiary_group_relevance->Render();
    $combo_reliability->Render();
    $combo_intentionality->Render();
    $combo_equivalence->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_report__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['report'] : $filterer_report);
    ?>
"};
		var current_outcome__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['outcome'] : $filterer_outcome);
    ?>
"};
		var current_indicator__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['indicator'] : $filterer_indicator);
    ?>
"};
		var current_beneficiary_group__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['beneficiary_group'] : $filterer_beneficiary_group);
    ?>
"};
		
		jQuery(function() {
			report_reload__RAND__();
			outcome_reload__RAND__();
			<?php 
    echo !$AllowUpdate || $dvprint ? 'indicator_reload__RAND__(current_outcome__RAND__.value);' : '';
    ?>
			beneficiary_group_reload__RAND__();
		});
		function report_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#report-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_report__RAND__.value, t: 'entries', f: 'report' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="report"]').val(resp.results[0].id);


						if(typeof(report_update_autofills__RAND__) == 'function') report_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'entries', f: 'report' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_report__RAND__.value = e.added.id;
				current_report__RAND__.text = e.added.text;
				jQuery('[name="report"]').val(e.added.id);


				if(typeof(report_update_autofills__RAND__) == 'function') report_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_report__RAND__.value, t: 'entries', f: 'report' }
			}).done(function(resp){
				jQuery('#report-container__RAND__').html('<span id="report-match-text">' + resp.results[0].text + '</span>');

				if(typeof(report_update_autofills__RAND__) == 'function') report_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
		function outcome_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#outcome-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_outcome__RAND__.value, t: 'entries', f: 'outcome' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="outcome"]').val(resp.results[0].id);

						indicator_reload__RAND__(current_outcome__RAND__.value);

						if(typeof(outcome_update_autofills__RAND__) == 'function') outcome_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'entries', f: 'outcome' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_outcome__RAND__.value = e.added.id;
				current_outcome__RAND__.text = e.added.text;
				jQuery('[name="outcome"]').val(e.added.id);

						indicator_reload__RAND__(current_outcome__RAND__.value);

				if(typeof(outcome_update_autofills__RAND__) == 'function') outcome_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_outcome__RAND__.value, t: 'entries', f: 'outcome' }
			}).done(function(resp){
				jQuery('#outcome-container__RAND__').html('<span id="outcome-match-text">' + resp.results[0].text + '</span>');

				if(typeof(outcome_update_autofills__RAND__) == 'function') outcome_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
		function indicator_reload__RAND__(filterer_outcome){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#indicator-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { filterer_outcome: filterer_outcome, id: current_indicator__RAND__.value, t: 'entries', f: 'indicator' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="indicator"]').val(resp.results[0].id);


						if(typeof(indicator_update_autofills__RAND__) == 'function') indicator_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { filterer_outcome: filterer_outcome, s: term, p: page, t: 'entries', f: 'indicator' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_indicator__RAND__.value = e.added.id;
				current_indicator__RAND__.text = e.added.text;
				jQuery('[name="indicator"]').val(e.added.id);


				if(typeof(indicator_update_autofills__RAND__) == 'function') indicator_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_indicator__RAND__.value, t: 'entries', f: 'indicator' }
			}).done(function(resp){
				jQuery('#indicator-container__RAND__').html('<span id="indicator-match-text">' + resp.results[0].text + '</span>');

				if(typeof(indicator_update_autofills__RAND__) == 'function') indicator_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
		function beneficiary_group_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#beneficiary_group-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_beneficiary_group__RAND__.value, t: 'entries', f: 'beneficiary_group' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="beneficiary_group"]').val(resp.results[0].id);


						if(typeof(beneficiary_group_update_autofills__RAND__) == 'function') beneficiary_group_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'entries', f: 'beneficiary_group' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_beneficiary_group__RAND__.value = e.added.id;
				current_beneficiary_group__RAND__.text = e.added.text;
				jQuery('[name="beneficiary_group"]').val(e.added.id);


				if(typeof(beneficiary_group_update_autofills__RAND__) == 'function') beneficiary_group_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_beneficiary_group__RAND__.value, t: 'entries', f: 'beneficiary_group' }
			}).done(function(resp){
				jQuery('#beneficiary_group-container__RAND__').html('<span id="beneficiary_group-match-text">' + resp.results[0].text + '</span>');

				if(typeof(beneficiary_group_update_autofills__RAND__) == 'function') beneficiary_group_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/entries_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/entries_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Entry details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    // process buttons
    if ($arrPerm[1]) {
        // allow insert?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return entries_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return entries_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return entries_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$arrPerm[1] || !$selected_id && !$arrPerm[1]) {
        $jsReadOnly .= "\tjQuery('#report').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#report_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#outcome').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#outcome_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#indicator').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#indicator_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#score').replaceWith('<p class=\"form-control-static\" id=\"score\">' + (jQuery('#score').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#beneficiary_group').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#beneficiary_group_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#beneficiary_group_relevance').replaceWith('<p class=\"form-control-static\" id=\"beneficiary_group_relevance\">' + (jQuery('#beneficiary_group_relevance').val() || '') + '</p>'); jQuery('#beneficiary_group_relevance-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#comment').replaceWith('<p class=\"form-control-static\" id=\"comment\">' + (jQuery('#comment').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#reference').replaceWith('<p class=\"form-control-static\" id=\"reference\">' + (jQuery('#reference').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#reliability').replaceWith('<p class=\"form-control-static\" id=\"reliability\">' + (jQuery('#reliability').val() || '') + '</p>'); jQuery('#reliability-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#intentionality').replaceWith('<p class=\"form-control-static\" id=\"intentionality\">' + (jQuery('#intentionality').val() || '') + '</p>'); jQuery('#intentionality-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#equivalence').replaceWith('<p class=\"form-control-static\" id=\"equivalence\">' + (jQuery('#equivalence').val() || '') + '</p>'); jQuery('#equivalence-multi-selection-help').hide();\n";
        $noUploads = true;
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(created)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_created->GetHTML(true) . '</p>' : $combo_created->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(created)%%>', $combo_created->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(report)%%>', $combo_report->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(report)%%>', $combo_report->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(report)%%>', urlencode($combo_report->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(outcome)%%>', $combo_outcome->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(outcome)%%>', $combo_outcome->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(outcome)%%>', urlencode($combo_outcome->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(indicator)%%>', $combo_indicator->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(indicator)%%>', $combo_indicator->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(indicator)%%>', urlencode($combo_indicator->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(beneficiary_group)%%>', $combo_beneficiary_group->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(beneficiary_group)%%>', $combo_beneficiary_group->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(beneficiary_group)%%>', urlencode($combo_beneficiary_group->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(beneficiary_group_relevance)%%>', $combo_beneficiary_group_relevance->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(beneficiary_group_relevance)%%>', $combo_beneficiary_group_relevance->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(reliability)%%>', $combo_reliability->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(reliability)%%>', $combo_reliability->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(intentionality)%%>', $combo_intentionality->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(intentionality)%%>', $combo_intentionality->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(equivalence)%%>', $combo_equivalence->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(equivalence)%%>', $combo_equivalence->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(report)%%>', $combo_report->SelectedData ? "<span id=\"reports_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"reports_view.php?SelectedID=" . urlencode($combo_report->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(outcome)%%>', $combo_outcome->SelectedData ? "<span id=\"outcomes_plink2\" class=\"hidden\"><a class=\"btn btn-default\" href=\"outcomes_view.php?SelectedID=" . urlencode($combo_outcome->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(indicator)%%>', $combo_indicator->SelectedData ? "<span id=\"indicators_plink3\" class=\"hidden\"><a class=\"btn btn-default\" href=\"indicators_view.php?SelectedID=" . urlencode($combo_indicator->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(beneficiary_group)%%>', $combo_beneficiary_group->SelectedData ? "<span id=\"beneficiary_groups_plink4\" class=\"hidden\"><a class=\"btn btn-default\" href=\"beneficiary_groups_view.php?SelectedID=" . urlencode($combo_beneficiary_group->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(entry_id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(created)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(created_by)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(report)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(outcome)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(indicator)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(score)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(beneficiary_group)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(beneficiary_group_relevance)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(comment)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(reference)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(reliability)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(intentionality)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(equivalence)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(entry_id)%%>', htmlspecialchars($row['entry_id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(entry_id)%%>', urlencode($urow['entry_id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(created)%%>', @date('d/m/Y', @strtotime(htmlspecialchars($row['created'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created)%%>', urlencode(@date('d/m/Y', @strtotime(htmlspecialchars($urow['created'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(created_by)%%>', htmlspecialchars($row['created_by'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created_by)%%>', urlencode($urow['created_by']), $templateCode);
        $templateCode = str_replace('<%%VALUE(report)%%>', htmlspecialchars($row['report'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(report)%%>', urlencode($urow['report']), $templateCode);
        $templateCode = str_replace('<%%VALUE(outcome)%%>', htmlspecialchars($row['outcome'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome)%%>', urlencode($urow['outcome']), $templateCode);
        $templateCode = str_replace('<%%VALUE(indicator)%%>', htmlspecialchars($row['indicator'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(indicator)%%>', urlencode($urow['indicator']), $templateCode);
        $templateCode = str_replace('<%%VALUE(score)%%>', htmlspecialchars($row['score'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(score)%%>', urlencode($urow['score']), $templateCode);
        $templateCode = str_replace('<%%VALUE(beneficiary_group)%%>', htmlspecialchars($row['beneficiary_group'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(beneficiary_group)%%>', urlencode($urow['beneficiary_group']), $templateCode);
        $templateCode = str_replace('<%%VALUE(beneficiary_group_relevance)%%>', htmlspecialchars($row['beneficiary_group_relevance'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(beneficiary_group_relevance)%%>', urlencode($urow['beneficiary_group_relevance']), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(comment)%%>', nl2br(htmlspecialchars($row['comment'], ENT_QUOTES)), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(comment)%%>', htmlspecialchars($row['comment'], ENT_QUOTES), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(comment)%%>', urlencode($urow['comment']), $templateCode);
        $templateCode = str_replace('<%%VALUE(reference)%%>', htmlspecialchars($row['reference'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reference)%%>', urlencode($urow['reference']), $templateCode);
        $templateCode = str_replace('<%%VALUE(reliability)%%>', htmlspecialchars($row['reliability'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reliability)%%>', urlencode($urow['reliability']), $templateCode);
        $templateCode = str_replace('<%%VALUE(intentionality)%%>', htmlspecialchars($row['intentionality'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(intentionality)%%>', urlencode($urow['intentionality']), $templateCode);
        $templateCode = str_replace('<%%VALUE(equivalence)%%>', htmlspecialchars($row['equivalence'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(equivalence)%%>', urlencode($urow['equivalence']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(entry_id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(entry_id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(created)%%>', '<%%creationDate%%>', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created)%%>', urlencode('<%%creationDate%%>'), $templateCode);
        $templateCode = str_replace('<%%VALUE(created_by)%%>', '<%%creatorUsername%%>', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created_by)%%>', urlencode('<%%creatorUsername%%>'), $templateCode);
        $templateCode = str_replace('<%%VALUE(report)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(report)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(outcome)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(indicator)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(indicator)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(score)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(score)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(beneficiary_group)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(beneficiary_group)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(beneficiary_group_relevance)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(beneficiary_group_relevance)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(comment)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(comment)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(reference)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reference)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(reliability)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reliability)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(intentionality)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(intentionality)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(equivalence)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(equivalence)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>jQuery(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\tjQuery('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= "<script>";
    $templateCode .= "document.observe('dom:loaded', function() {";
    $templateCode .= "\toutcome_update_autofills{$rnd1} = function(){\n";
    $templateCode .= "\t\tnew Ajax.Request(\n";
    if ($dvprint) {
        $templateCode .= "\t\t\t'entries_autofill.php?rnd1={$rnd1}&mfk=outcome&id='+encodeURIComponent('" . addslashes($row['outcome']) . "'),\n";
        $templateCode .= "\t\t\t{encoding: 'UTF-8', method: 'get'}\n";
    } else {
        $templateCode .= "\t\t\t'entries_autofill.php?rnd1={$rnd1}&mfk=outcome&id=' + encodeURIComponent(current_outcome{$rnd1}.value),\n";
        $templateCode .= "\t\t\t{encoding: 'UTF-8', method: 'get', onCreate: function(){ \$('outcome{$rnd1}').disable(); \$('outcomeLoading').innerHTML='<img src=loading.gif align=top>'; }, onComplete: function(){" . ($arrPerm[1] || ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) ? "\$('outcome{$rnd1}').enable(); " : "\$('outcome{$rnd1}').disable(); ") . "\$('outcomeLoading').innerHTML='';}}\n";
    }
    $templateCode .= "\t\t);\n";
    $templateCode .= "\t};\n";
    if (!$dvprint) {
        $templateCode .= "\tif(\$('outcome_caption') != undefined) \$('outcome_caption').onchange=outcome_update_autofills{$rnd1};\n";
    }
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: entries_dv
    if (function_exists('entries_dv')) {
        $args = array();
        entries_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
function properties_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('properties');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_owner = thisOr(undo_magic_quotes($_REQUEST['filterer_owner']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: type
    $combo_type = new Combo();
    $combo_type->ListType = 2;
    $combo_type->MultipleSeparator = ', ';
    $combo_type->ListBoxHeight = 10;
    $combo_type->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/properties.type.csv')) {
        $type_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/properties.type.csv')));
        $combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($type_data)));
        $combo_type->ListData = $combo_type->ListItem;
    } else {
        $combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Residential;;Commercial;;Condo/Townhome;;Multi-Family;;Single-Family;;stores;;office;;shops")));
        $combo_type->ListData = $combo_type->ListItem;
    }
    $combo_type->SelectName = 'type';
    $combo_type->AllowNull = false;
    // combobox: owner
    $combo_owner = new DataCombo();
    // combobox: operating_account
    $combo_operating_account = new Combo();
    $combo_operating_account->ListType = 0;
    $combo_operating_account->MultipleSeparator = ', ';
    $combo_operating_account->ListBoxHeight = 10;
    $combo_operating_account->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/properties.operating_account.csv')) {
        $operating_account_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/properties.operating_account.csv')));
        $combo_operating_account->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($operating_account_data)));
        $combo_operating_account->ListData = $combo_operating_account->ListItem;
    } else {
        $combo_operating_account->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Operating bank account;;Security deposit bank account")));
        $combo_operating_account->ListData = $combo_operating_account->ListItem;
    }
    $combo_operating_account->SelectName = 'operating_account';
    // combobox: country
    $combo_country = new Combo();
    $combo_country->ListType = 0;
    $combo_country->MultipleSeparator = ', ';
    $combo_country->ListBoxHeight = 10;
    $combo_country->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/properties.country.csv')) {
        $country_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/properties.country.csv')));
        $combo_country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($country_data)));
        $combo_country->ListData = $combo_country->ListItem;
    } else {
        $combo_country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Afghanistan;;Albania;;Algeria;;American Samoa;;Andorra;;Angola;;Anguilla;;Antarctica;;Antigua, Barbuda;;Argentina;;Armenia;;Aruba;;Australia;;Austria;;Azerbaijan;;Bahamas;;Bahrain;;Bangladesh;;Barbados;;Belarus;;Belgium;;Belize;;Benin;;Bermuda;;Bhutan;;Bolivia;;Bosnia, Herzegovina;;Botswana;;Bouvet Is.;;Brazil;;Brunei Darussalam;;Bulgaria;;Burkina Faso;;Burundi;;Cambodia;;Cameroon;;Canada;;Canary Is.;;Cape Verde;;Cayman Is.;;Central African Rep.;;Chad;;Channel Islands;;Chile;;China;;Christmas Is.;;Cocos Is.;;Colombia;;Comoros;;Congo, D.R. Of;;Congo;;Cook Is.;;Costa Rica;;Croatia;;Cuba;;Cyprus;;Czech Republic;;Denmark;;Djibouti;;Dominica;;Dominican Republic;;Ecuador;;Egypt;;El Salvador;;Equatorial Guinea;;Eritrea;;Estonia;;Ethiopia;;Falkland Is.;;Faroe Is.;;Fiji;;Finland;;France;;French Guiana;;French Polynesia;;French Territories;;Gabon;;Gambia;;Georgia;;Germany;;Ghana;;Gibraltar;;Greece;;Greenland;;Grenada;;Guadeloupe;;Guam;;Guatemala;;Guernsey;;Guinea-bissau;;Guinea;;Guyana;;Haiti;;Heard, Mcdonald Is.;;Honduras;;Hong Kong;;Hungary;;Iceland;;India;;Indonesia;;Iran;;Iraq;;Ireland;;Israel;;Italy;;Ivory Coast;;Jamaica;;Japan;;Jersey;;Jordan;;Kazakhstan;;Kenya;;Kiribati;;Korea, D.P.R Of;;Korea, Rep. Of;;Kuwait;;Kyrgyzstan;;Lao Peoples D.R.;;Latvia;;Lebanon;;Lesotho;;Liberia;;Libyan Arab Jamahiriya;;Liechtenstein;;Lithuania;;Luxembourg;;Macao;;Macedonia, F.Y.R Of;;Madagascar;;Malawi;;Malaysia;;Maldives;;Mali;;Malta;;Mariana Islands;;Marshall Islands;;Martinique;;Mauritania;;Mauritius;;Mayotte;;Mexico;;Micronesia;;Moldova;;Monaco;;Mongolia;;Montserrat;;Morocco;;Mozambique;;Myanmar;;Namibia;;Nauru;;Nepal;;Netherlands Antilles;;Netherlands;;New Caledonia;;New Zealand;;Nicaragua;;Niger;;Nigeria;;Niue;;Norfolk Island;;Norway;;Oman;;Pakistan;;Palau;;Palestinian Terr.;;Panama;;Papua New Guinea;;Paraguay;;Peru;;Philippines;;Pitcairn;;Poland;;Portugal;;Puerto Rico;;Qatar;;Reunion;;Romania;;Russian Federation;;Rwanda;;Samoa;;San Marino;;Sao Tome, Principe;;Saudi Arabia;;Senegal;;Seychelles;;Sierra Leone;;Singapore;;Slovakia;;Slovenia;;Solomon Is.;;Somalia;;South Africa;;South Georgia;;South Sandwich Is.;;Spain;;Sri Lanka;;St. Helena;;St. Kitts, Nevis;;St. Lucia;;St. Pierre, Miquelon;;St. Vincent, Grenadines;;Sudan;;Suriname;;Svalbard, Jan Mayen;;Swaziland;;Sweden;;Switzerland;;Syrian Arab Republic;;Taiwan;;Tajikistan;;Tanzania;;Thailand;;Timor-leste;;Togo;;Tokelau;;Tonga;;Trinidad, Tobago;;Tunisia;;Turkey;;Turkmenistan;;Turks, Caicoss;;Tuvalu;;Uganda;;Ukraine;;United Arab Emirates;;United Kingdom;;United States;;Uruguay;;Uzbekistan;;Vanuatu;;Vatican City;;Venezuela;;Viet Nam;;Virgin Is. British;;Virgin Is. U.S.;;Wallis, Futuna;;Western Sahara;;Yemen;;Yugoslavia;;Zambia;;Zimbabwe")));
        $combo_country->ListData = $combo_country->ListItem;
    }
    $combo_country->SelectName = 'country';
    // combobox: State
    $combo_State = new Combo();
    $combo_State->ListType = 0;
    $combo_State->MultipleSeparator = ', ';
    $combo_State->ListBoxHeight = 10;
    $combo_State->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/properties.State.csv')) {
        $State_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/properties.State.csv')));
        $combo_State->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($State_data)));
        $combo_State->ListData = $combo_State->ListItem;
    } else {
        $combo_State->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("AL;;AK;;AS;;AZ;;AR;;CA;;CO;;CT;;DE;;DC;;FM;;FL;;GA;;GU;;HI;;ID;;IL;;IN;;IA;;KS;;KY;;LA;;ME;;MH;;MD;;MA;;MI;;MN;;MS;;MO;;MT;;NE;;NV;;NH;;NJ;;NM;;NY;;NC;;ND;;MP;;OH;;OK;;OR;;PW;;PA;;PR;;RI;;SC;;SD;;TN;;TX;;UT;;VT;;VI;;VA;;WA;;WV;;WI;;WY")));
        $combo_State->ListData = $combo_State->ListItem;
    }
    $combo_State->SelectName = 'State';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='properties' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='properties' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `properties` where `id`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_type->SelectedData = $row['type'];
        $combo_owner->SelectedData = $row['owner'];
        $combo_operating_account->SelectedData = $row['operating_account'];
        $combo_country->SelectedData = $row['country'];
        $combo_State->SelectedData = $row['State'];
    } else {
        $combo_type->SelectedText = $_REQUEST['FilterField'][1] == '3' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_owner->SelectedData = $filterer_owner;
        $combo_operating_account->SelectedText = $_REQUEST['FilterField'][1] == '7' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_country->SelectedText = $_REQUEST['FilterField'][1] == '10' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_State->SelectedText = $_REQUEST['FilterField'][1] == '13' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_type->Render();
    $combo_owner->HTML = '<span id="owner-container' . $rnd1 . '"></span><input type="hidden" name="owner" id="owner' . $rnd1 . '">';
    $combo_owner->MatchText = '<span id="owner-container-readonly' . $rnd1 . '"></span><input type="hidden" name="owner" id="owner' . $rnd1 . '">';
    $combo_operating_account->Render();
    $combo_country->Render();
    $combo_State->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_owner__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['owner'] : $filterer_owner);
    ?>
"};

		jQuery(function() {
			owner_reload__RAND__();
		});
		function owner_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#owner-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_owner__RAND__.value, t: 'properties', f: 'owner' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="owner"]').val(resp.results[0].id);
						jQuery('[id=owner-container-readonly__RAND__]').html('<span id="owner-match-text">' + resp.results[0].text + '</span>');


						if(typeof(owner_update_autofills__RAND__) == 'function') owner_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'properties', f: 'owner' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_owner__RAND__.value = e.added.id;
				current_owner__RAND__.text = e.added.text;
				jQuery('[name="owner"]').val(e.added.id);


				if(typeof(owner_update_autofills__RAND__) == 'function') owner_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_owner__RAND__.value, t: 'properties', f: 'owner' }
			}).done(function(resp){
				jQuery('[id=owner-container__RAND__], [id=owner-container-readonly__RAND__]').html('<span id="owner-match-text">' + resp.results[0].text + '</span>');

				if(typeof(owner_update_autofills__RAND__) == 'function') owner_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/properties_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/properties_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Property details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($AllowInsert) {
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return properties_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return properties_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return properties_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$AllowInsert || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#property_name').replaceWith('<p class=\"form-control-static\" id=\"property_name\">' + (jQuery('#property_name').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('input[name=type]').parent().html('<p class=\"form-control-static\">' + jQuery('input[name=type]:checked').next().text() + '</p>')\n";
        $jsReadOnly .= "\tjQuery('#number_of_units').replaceWith('<p class=\"form-control-static\" id=\"number_of_units\">' + (jQuery('#number_of_units').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#photo').replaceWith('<p class=\"form-control-static\" id=\"photo\">' + (jQuery('#photo').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#owner').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#owner_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#country').replaceWith('<p class=\"form-control-static\" id=\"country\">' + (jQuery('#country').val() || '') + '</p>'); jQuery('#country-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#street').replaceWith('<p class=\"form-control-static\" id=\"street\">' + (jQuery('#street').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#City').replaceWith('<p class=\"form-control-static\" id=\"City\">' + (jQuery('#City').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#State').replaceWith('<p class=\"form-control-static\" id=\"State\">' + (jQuery('#State').val() || '') + '</p>'); jQuery('#State-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#ZIP').replaceWith('<p class=\"form-control-static\" id=\"ZIP\">' + (jQuery('#ZIP').val() || '') + '</p>');\n";
        $noUploads = true;
    } elseif ($AllowInsert) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(type)%%>', $combo_type->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(type)%%>', $combo_type->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(owner)%%>', $combo_owner->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(owner)%%>', $combo_owner->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(owner)%%>', urlencode($combo_owner->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(operating_account)%%>', $combo_operating_account->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(operating_account)%%>', $combo_operating_account->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(country)%%>', $combo_country->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(country)%%>', $combo_country->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(State)%%>', $combo_State->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(State)%%>', $combo_State->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(owner)%%>', $combo_owner->SelectedData ? "<span id=\"rental_owners_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"rental_owners_view.php?SelectedID=" . urlencode($combo_owner->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(property_name)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(type)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(number_of_units)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(photo)%%>', $noUploads ? '' : '<br><input type=hidden name=MAX_FILE_SIZE value=1024000>' . $Translation['upload image'] . ' <input type="file" name="photo">', $templateCode);
    if ($AllowUpdate && $row['photo'] != '') {
        $templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '<br><input type="checkbox" name="photo_remove" id="photo_remove" value="1"> <label for="photo_remove" style="color: red; font-weight: bold;">' . $Translation['remove image'] . '</label>', $templateCode);
    } else {
        $templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '', $templateCode);
    }
    $templateCode = str_replace('<%%UPLOADFILE(owner)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(operating_account)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(property_reserve)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(lease_term)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(country)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(street)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(City)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(State)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ZIP)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(id)%%>', htmlspecialchars($row['id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(property_name)%%>', htmlspecialchars($row['property_name'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property_name)%%>', urlencode($urow['property_name']), $templateCode);
        $templateCode = str_replace('<%%VALUE(type)%%>', htmlspecialchars($row['type'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode($urow['type']), $templateCode);
        $templateCode = str_replace('<%%VALUE(number_of_units)%%>', htmlspecialchars($row['number_of_units'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(number_of_units)%%>', urlencode($urow['number_of_units']), $templateCode);
        $row['photo'] = $row['photo'] != '' ? $row['photo'] : 'blank.gif';
        $templateCode = str_replace('<%%VALUE(photo)%%>', htmlspecialchars($row['photo'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(photo)%%>', urlencode($urow['photo']), $templateCode);
        $templateCode = str_replace('<%%VALUE(owner)%%>', htmlspecialchars($row['owner'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(owner)%%>', urlencode($urow['owner']), $templateCode);
        $templateCode = str_replace('<%%VALUE(operating_account)%%>', htmlspecialchars($row['operating_account'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(operating_account)%%>', urlencode($urow['operating_account']), $templateCode);
        $templateCode = str_replace('<%%VALUE(property_reserve)%%>', htmlspecialchars($row['property_reserve'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property_reserve)%%>', urlencode($urow['property_reserve']), $templateCode);
        $templateCode = str_replace('<%%VALUE(lease_term)%%>', htmlspecialchars($row['lease_term'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(lease_term)%%>', urlencode($urow['lease_term']), $templateCode);
        $templateCode = str_replace('<%%VALUE(country)%%>', htmlspecialchars($row['country'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode($urow['country']), $templateCode);
        $templateCode = str_replace('<%%VALUE(street)%%>', htmlspecialchars($row['street'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(street)%%>', urlencode($urow['street']), $templateCode);
        $templateCode = str_replace('<%%VALUE(City)%%>', htmlspecialchars($row['City'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode($urow['City']), $templateCode);
        $templateCode = str_replace('<%%VALUE(State)%%>', htmlspecialchars($row['State'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(State)%%>', urlencode($urow['State']), $templateCode);
        $templateCode = str_replace('<%%VALUE(ZIP)%%>', htmlspecialchars($row['ZIP'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ZIP)%%>', urlencode($urow['ZIP']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(property_name)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property_name)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(type)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(number_of_units)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(number_of_units)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(photo)%%>', 'blank.gif', $templateCode);
        $templateCode = str_replace('<%%VALUE(owner)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(owner)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(operating_account)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(operating_account)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(property_reserve)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property_reserve)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(lease_term)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(lease_term)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(country)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(street)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(street)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(City)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(State)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(State)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ZIP)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ZIP)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: properties_dv
    if (function_exists('properties_dv')) {
        $args = array();
        properties_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
function units_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('units');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_property = thisOr(undo_magic_quotes($_REQUEST['filterer_property']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: property
    $combo_property = new DataCombo();
    // combobox: status
    $combo_status = new Combo();
    $combo_status->ListType = 2;
    $combo_status->MultipleSeparator = ', ';
    $combo_status->ListBoxHeight = 10;
    $combo_status->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/units.status.csv')) {
        $status_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/units.status.csv')));
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($status_data)));
        $combo_status->ListData = $combo_status->ListItem;
    } else {
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Occupied;;Listed;;Unlisted")));
        $combo_status->ListData = $combo_status->ListItem;
    }
    $combo_status->SelectName = 'status';
    $combo_status->AllowNull = false;
    // combobox: features
    $combo_features = new Combo();
    $combo_features->ListType = 3;
    $combo_features->MultipleSeparator = ', ';
    $combo_features->ListBoxHeight = 10;
    $combo_features->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/units.features.csv')) {
        $features_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/units.features.csv')));
        $combo_features->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($features_data)));
        $combo_features->ListData = $combo_features->ListItem;
    } else {
        $combo_features->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Cable ready;; Micorwave;;Hardwood floors;; High speed internet;;Air conditioning;;Refrigerator;;Dishwasher;;Walk-in closets;;Balcony;;Deck;;Patio;;Garage parking;;Carport;;Fenced yard;;Laundry room / hookups;; Fireplace;;Oven / range;;Heat - electric;; Heat - gas;; Heat - oil")));
        $combo_features->ListData = $combo_features->ListItem;
    }
    $combo_features->SelectName = 'features';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='units' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='units' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `units` where `id`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_property->SelectedData = $row['property'];
        $combo_status->SelectedData = $row['status'];
        $combo_features->SelectedData = $row['features'];
    } else {
        $combo_property->SelectedData = $filterer_property;
        $combo_status->SelectedText = $_REQUEST['FilterField'][1] == '5' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_property->HTML = '<span id="property-container' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '">';
    $combo_property->MatchText = '<span id="property-container-readonly' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '">';
    $combo_status->Render();
    $combo_features->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_property__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['property'] : $filterer_property);
    ?>
"};

		jQuery(function() {
			property_reload__RAND__();
		});
		function property_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#property-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_property__RAND__.value, t: 'units', f: 'property' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="property"]').val(resp.results[0].id);
						jQuery('[id=property-container-readonly__RAND__]').html('<span id="property-match-text">' + resp.results[0].text + '</span>');


						if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'units', f: 'property' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_property__RAND__.value = e.added.id;
				current_property__RAND__.text = e.added.text;
				jQuery('[name="property"]').val(e.added.id);


				if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_property__RAND__.value, t: 'units', f: 'property' }
			}).done(function(resp){
				jQuery('[id=property-container__RAND__], [id=property-container-readonly__RAND__]').html('<span id="property-match-text">' + resp.results[0].text + '</span>');

				if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/units_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/units_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Unit details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($AllowInsert) {
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return units_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return units_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return units_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$AllowInsert || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#property').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#property_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#unit_number').replaceWith('<p class=\"form-control-static\" id=\"unit_number\">' + (jQuery('#unit_number').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#photo').replaceWith('<p class=\"form-control-static\" id=\"photo\">' + (jQuery('#photo').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('input[name=status]').parent().html('<p class=\"form-control-static\">' + jQuery('input[name=status]:checked').next().text() + '</p>')\n";
        $jsReadOnly .= "\tjQuery('#size').replaceWith('<p class=\"form-control-static\" id=\"size\">' + (jQuery('#size').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#rooms').replaceWith('<p class=\"form-control-static\" id=\"rooms\">' + (jQuery('#rooms').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#bathroom').replaceWith('<p class=\"form-control-static\" id=\"bathroom\">' + (jQuery('#bathroom').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#features').replaceWith('<p class=\"form-control-static\" id=\"features\">' + (jQuery('#features').val() || '') + '</p>'); jQuery('#features-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#s2id_features').remove();\n";
        $jsReadOnly .= "\tjQuery('#rental_amount').replaceWith('<p class=\"form-control-static\" id=\"rental_amount\">' + (jQuery('#rental_amount').val() || '') + '</p>');\n";
        $noUploads = true;
    } elseif ($AllowInsert) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(property)%%>', $combo_property->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(property)%%>', $combo_property->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(property)%%>', urlencode($combo_property->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(status)%%>', $combo_status->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(status)%%>', $combo_status->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(features)%%>', $combo_features->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(features)%%>', $combo_features->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(property)%%>', $combo_property->SelectedData ? "<span id=\"properties_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"properties_view.php?SelectedID=" . urlencode($combo_property->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(property)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(unit_number)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(photo)%%>', $noUploads ? '' : '<br><input type=hidden name=MAX_FILE_SIZE value=1024000>' . $Translation['upload image'] . ' <input type="file" name="photo">', $templateCode);
    if ($AllowUpdate && $row['photo'] != '') {
        $templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '<br><input type="checkbox" name="photo_remove" id="photo_remove" value="1"> <label for="photo_remove" style="color: red; font-weight: bold;">' . $Translation['remove image'] . '</label>', $templateCode);
    } else {
        $templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '', $templateCode);
    }
    $templateCode = str_replace('<%%UPLOADFILE(status)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(size)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(rooms)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(bathroom)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(features)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(market_rent)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(rental_amount)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(deposit_amount)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(description)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(id)%%>', htmlspecialchars($row['id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(property)%%>', htmlspecialchars($row['property'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode($urow['property']), $templateCode);
        $templateCode = str_replace('<%%VALUE(unit_number)%%>', htmlspecialchars($row['unit_number'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(unit_number)%%>', urlencode($urow['unit_number']), $templateCode);
        $row['photo'] = $row['photo'] != '' ? $row['photo'] : 'blank.gif';
        $templateCode = str_replace('<%%VALUE(photo)%%>', htmlspecialchars($row['photo'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(photo)%%>', urlencode($urow['photo']), $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', htmlspecialchars($row['status'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode($urow['status']), $templateCode);
        $templateCode = str_replace('<%%VALUE(size)%%>', htmlspecialchars($row['size'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(size)%%>', urlencode($urow['size']), $templateCode);
        $templateCode = str_replace('<%%VALUE(rooms)%%>', htmlspecialchars($row['rooms'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rooms)%%>', urlencode($urow['rooms']), $templateCode);
        $templateCode = str_replace('<%%VALUE(bathroom)%%>', htmlspecialchars($row['bathroom'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(bathroom)%%>', urlencode($urow['bathroom']), $templateCode);
        $templateCode = str_replace('<%%VALUE(features)%%>', htmlspecialchars($row['features'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(features)%%>', urlencode($urow['features']), $templateCode);
        $templateCode = str_replace('<%%VALUE(market_rent)%%>', htmlspecialchars($row['market_rent'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(market_rent)%%>', urlencode($urow['market_rent']), $templateCode);
        $templateCode = str_replace('<%%VALUE(rental_amount)%%>', htmlspecialchars($row['rental_amount'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rental_amount)%%>', urlencode($urow['rental_amount']), $templateCode);
        $templateCode = str_replace('<%%VALUE(deposit_amount)%%>', htmlspecialchars($row['deposit_amount'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(deposit_amount)%%>', urlencode($urow['deposit_amount']), $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(description)%%>', '<textarea name="description" id="description" rows="5">' . htmlspecialchars($row['description'], ENT_QUOTES) . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(description)%%>', $row['description'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(description)%%>', nl2br($row['description']), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode($urow['description']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(property)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(unit_number)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(unit_number)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(photo)%%>', 'blank.gif', $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(size)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(size)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(rooms)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rooms)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(bathroom)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(bathroom)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(features)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(features)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(market_rent)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(market_rent)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(rental_amount)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rental_amount)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(deposit_amount)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(deposit_amount)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(description)%%>', '<textarea name="description" id="description" rows="5"></textarea>', $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "\tproperty_update_autofills{$rnd1} = function(){\n";
    $templateCode .= "\t\tnew Ajax.Request(\n";
    if ($dvprint) {
        $templateCode .= "\t\t\t'units_autofill.php?rnd1={$rnd1}&mfk=property&id='+encodeURIComponent('" . addslashes($row['property']) . "'),\n";
        $templateCode .= "\t\t\t{encoding: 'UTF-8', method: 'get'}\n";
    } else {
        $templateCode .= "\t\t\t'units_autofill.php?rnd1={$rnd1}&mfk=property&id=' + encodeURIComponent(current_property{$rnd1}.value),\n";
        $templateCode .= "\t\t\t{encoding: 'UTF-8', method: 'get', onCreate: function(){ \$('property{$rnd1}').disable(); \$('propertyLoading').innerHTML='<img src=loading.gif align=top>'; }, onComplete: function(){" . ($arrPerm[1] || ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) ? "\$('property{$rnd1}').enable(); " : "\$('property{$rnd1}').disable(); ") . "\$('propertyLoading').innerHTML='';}}\n";
    }
    $templateCode .= "\t\t);\n";
    $templateCode .= "\t};\n";
    if (!$dvprint) {
        $templateCode .= "\tif(\$('property_caption') != undefined) \$('property_caption').onchange=property_update_autofills{$rnd1};\n";
    }
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: units_dv
    if (function_exists('units_dv')) {
        $args = array();
        units_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
function applicants_and_tenants_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('applicants_and_tenants');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: birth_date
    $combo_birth_date = new DateCombo();
    $combo_birth_date->DateFormat = "mdy";
    $combo_birth_date->MinYear = 1900;
    $combo_birth_date->MaxYear = 2100;
    $combo_birth_date->DefaultDate = parseMySQLDate('', '');
    $combo_birth_date->MonthNames = $Translation['month names'];
    $combo_birth_date->NamePrefix = 'birth_date';
    // combobox: driver_license_state
    $combo_driver_license_state = new Combo();
    $combo_driver_license_state->ListType = 0;
    $combo_driver_license_state->MultipleSeparator = ', ';
    $combo_driver_license_state->ListBoxHeight = 10;
    $combo_driver_license_state->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/applicants_and_tenants.driver_license_state.csv')) {
        $driver_license_state_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/applicants_and_tenants.driver_license_state.csv')));
        $combo_driver_license_state->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($driver_license_state_data)));
        $combo_driver_license_state->ListData = $combo_driver_license_state->ListItem;
    } else {
        $combo_driver_license_state->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("AL;;AK;;AS;;AZ;;AR;;CA;;CO;;CT;;DE;;DC;;FM;;FL;;GA;;GU;;HI;;ID;;IL;;IN;;IA;;KS;;KY;;LA;;ME;;MH;;MD;;MA;;MI;;MN;;MS;;MO;;MT;;NE;;NV;;NH;;NJ;;NM;;NY;;NC;;ND;;MP;;OH;;OK;;OR;;PW;;PA;;PR;;RI;;SC;;SD;;TN;;TX;;UT;;VT;;VI;;VA;;WA;;WV;;WI;;WY")));
        $combo_driver_license_state->ListData = $combo_driver_license_state->ListItem;
    }
    $combo_driver_license_state->SelectName = 'driver_license_state';
    // combobox: status
    $combo_status = new Combo();
    $combo_status->ListType = 2;
    $combo_status->MultipleSeparator = ', ';
    $combo_status->ListBoxHeight = 10;
    $combo_status->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/applicants_and_tenants.status.csv')) {
        $status_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/applicants_and_tenants.status.csv')));
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($status_data)));
        $combo_status->ListData = $combo_status->ListItem;
    } else {
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Applicant;;Tenant;;Previous tenant")));
        $combo_status->ListData = $combo_status->ListItem;
    }
    $combo_status->SelectName = 'status';
    $combo_status->AllowNull = false;
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='applicants_and_tenants' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='applicants_and_tenants' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `applicants_and_tenants` where `id`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_birth_date->DefaultDate = $row['birth_date'];
        $combo_driver_license_state->SelectedData = $row['driver_license_state'];
        $combo_status->SelectedData = $row['status'];
    } else {
        $combo_driver_license_state->SelectedText = $_REQUEST['FilterField'][1] == '8' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_status->SelectedText = $_REQUEST['FilterField'][1] == '13' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "Applicant";
    }
    $combo_driver_license_state->Render();
    $combo_status->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values

		jQuery(function() {
		});
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/applicants_and_tenants_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/applicants_and_tenants_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Tenant details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($AllowInsert) {
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return applicants_and_tenants_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return applicants_and_tenants_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return applicants_and_tenants_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$AllowInsert || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#last_name').replaceWith('<p class=\"form-control-static\" id=\"last_name\">' + (jQuery('#last_name').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#first_name').replaceWith('<p class=\"form-control-static\" id=\"first_name\">' + (jQuery('#first_name').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#email').replaceWith('<p class=\"form-control-static\" id=\"email\">' + (jQuery('#email').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#email, #email-edit-link').hide();\n";
        $jsReadOnly .= "\tjQuery('#phone').replaceWith('<p class=\"form-control-static\" id=\"phone\">' + (jQuery('#phone').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#birth_date').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#birth_dateDay, #birth_dateMonth, #birth_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#driver_license_number').replaceWith('<p class=\"form-control-static\" id=\"driver_license_number\">' + (jQuery('#driver_license_number').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#monthly_gross_pay').replaceWith('<p class=\"form-control-static\" id=\"monthly_gross_pay\">' + (jQuery('#monthly_gross_pay').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#additional_income').replaceWith('<p class=\"form-control-static\" id=\"additional_income\">' + (jQuery('#additional_income').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#assets').replaceWith('<p class=\"form-control-static\" id=\"assets\">' + (jQuery('#assets').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('input[name=status]').parent().html('<p class=\"form-control-static\">' + jQuery('input[name=status]:checked').next().text() + '</p>')\n";
        $noUploads = true;
    } elseif ($AllowInsert) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(birth_date)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_birth_date->GetHTML(true) . '</p>' : $combo_birth_date->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(birth_date)%%>', $combo_birth_date->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(driver_license_state)%%>', $combo_driver_license_state->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(driver_license_state)%%>', $combo_driver_license_state->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(status)%%>', $combo_status->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(status)%%>', $combo_status->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(last_name)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(first_name)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(email)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(phone)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(birth_date)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(driver_license_number)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(driver_license_state)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(requested_lease_term)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(monthly_gross_pay)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(additional_income)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(assets)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(status)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(notes)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(id)%%>', htmlspecialchars($row['id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(last_name)%%>', htmlspecialchars($row['last_name'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(last_name)%%>', urlencode($urow['last_name']), $templateCode);
        $templateCode = str_replace('<%%VALUE(first_name)%%>', htmlspecialchars($row['first_name'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(first_name)%%>', urlencode($urow['first_name']), $templateCode);
        $templateCode = str_replace('<%%VALUE(email)%%>', htmlspecialchars($row['email'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(email)%%>', urlencode($urow['email']), $templateCode);
        $templateCode = str_replace('<%%VALUE(phone)%%>', htmlspecialchars($row['phone'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(phone)%%>', urlencode($urow['phone']), $templateCode);
        $templateCode = str_replace('<%%VALUE(birth_date)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['birth_date'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(birth_date)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['birth_date'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(driver_license_number)%%>', htmlspecialchars($row['driver_license_number'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(driver_license_number)%%>', urlencode($urow['driver_license_number']), $templateCode);
        $templateCode = str_replace('<%%VALUE(driver_license_state)%%>', htmlspecialchars($row['driver_license_state'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(driver_license_state)%%>', urlencode($urow['driver_license_state']), $templateCode);
        $templateCode = str_replace('<%%VALUE(requested_lease_term)%%>', htmlspecialchars($row['requested_lease_term'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(requested_lease_term)%%>', urlencode($urow['requested_lease_term']), $templateCode);
        $templateCode = str_replace('<%%VALUE(monthly_gross_pay)%%>', htmlspecialchars($row['monthly_gross_pay'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(monthly_gross_pay)%%>', urlencode($urow['monthly_gross_pay']), $templateCode);
        $templateCode = str_replace('<%%VALUE(additional_income)%%>', htmlspecialchars($row['additional_income'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(additional_income)%%>', urlencode($urow['additional_income']), $templateCode);
        $templateCode = str_replace('<%%VALUE(assets)%%>', htmlspecialchars($row['assets'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(assets)%%>', urlencode($urow['assets']), $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', htmlspecialchars($row['status'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode($urow['status']), $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea name="notes" id="notes" rows="5">' . htmlspecialchars($row['notes'], ENT_QUOTES) . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(notes)%%>', $row['notes'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(notes)%%>', nl2br($row['notes']), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(notes)%%>', urlencode($urow['notes']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(last_name)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(last_name)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(first_name)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(first_name)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(email)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(email)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(phone)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(phone)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(birth_date)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(birth_date)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(driver_license_number)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(driver_license_number)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(driver_license_state)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(driver_license_state)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(requested_lease_term)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(requested_lease_term)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(monthly_gross_pay)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(monthly_gross_pay)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(additional_income)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(additional_income)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(assets)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(assets)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', 'Applicant', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode('Applicant'), $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea name="notes" id="notes" rows="5"></textarea>', $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
            $templateCode .= "\n\tif(document.getElementById('emailEdit')){ document.getElementById('emailEdit').style.display='inline'; }";
            $templateCode .= "\n\tif(document.getElementById('emailEditLink')){ document.getElementById('emailEditLink').style.display='none'; }";
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: applicants_and_tenants_dv
    if (function_exists('applicants_and_tenants_dv')) {
        $args = array();
        applicants_and_tenants_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
示例#8
0
function companies_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('companies');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_client = thisOr(undo_magic_quotes($_REQUEST['filterer_client']), '');
    $filterer_sic_code = thisOr(undo_magic_quotes($_REQUEST['filterer_sic_code']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: client
    $combo_client = new DataCombo();
    // combobox: industry
    $combo_industry = new Combo();
    $combo_industry->ListType = 0;
    $combo_industry->MultipleSeparator = ', ';
    $combo_industry->ListBoxHeight = 10;
    $combo_industry->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/companies.industry.csv')) {
        $industry_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/companies.industry.csv')));
        $combo_industry->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($industry_data)));
        $combo_industry->ListData = $combo_industry->ListItem;
    } else {
        $combo_industry->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Automobiles and parts;;Business services;;Carbon offsetting and trading;;Charitable services and fundraising;;Chemicals;;Clothing retail;;Construction;;Consulting;;Consumer electronics;;Consumer goods and services (other);;Eating and drinking places;;Education;;Energy and Water;;Financial services;;Food and beverages retail;;Food producers;;Forestry and paper;;Health;;Household goods;;Internet platforms;;Leisure goods;;Media;;Other;;Personal goods;;Recycling and waste management;;Residential and commercial property;;Retail (general);;Telecoms;;Training and employment;;Transport;;Travel, tourism and leisure")));
        $combo_industry->ListData = $combo_industry->ListItem;
    }
    $combo_industry->SelectName = 'industry';
    // combobox: country_hq
    $combo_country_hq = new Combo();
    $combo_country_hq->ListType = 0;
    $combo_country_hq->MultipleSeparator = ', ';
    $combo_country_hq->ListBoxHeight = 10;
    $combo_country_hq->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/companies.country_hq.csv')) {
        $country_hq_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/companies.country_hq.csv')));
        $combo_country_hq->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($country_hq_data)));
        $combo_country_hq->ListData = $combo_country_hq->ListItem;
    } else {
        $combo_country_hq->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Afghanistan;;Albania;;Algeria;;American Samoa;;Andorra;;Angola;;Anguilla;;Antarctica;;Antigua, Barbuda;;Argentina;;Armenia;;Aruba;;Australia;;Austria;;Azerbaijan;;Bahamas;;Bahrain;;Bangladesh;;Barbados;;Belarus;;Belgium;;Belize;;Benin;;Bermuda;;Bhutan;;Bolivia;;Bosnia, Herzegovina;;Botswana;;Bouvet Is.;;Brazil;;Brunei Darussalam;;Bulgaria;;Burkina Faso;;Burundi;;Cambodia;;Cameroon;;Canada;;Canary Is.;;Cape Verde;;Cayman Is.;;Central African Rep.;;Chad;;Channel Islands;;Chile;;China;;Christmas Is.;;Cocos Is.;;Colombia;;Comoros;;Congo, D.R. Of;;Congo;;Cook Is.;;Costa Rica;;Croatia;;Cuba;;Cyprus;;Czech Republic;;Denmark;;Djibouti;;Dominica;;Dominican Republic;;Ecuador;;Egypt;;El Salvador;;Equatorial Guinea;;Eritrea;;Estonia;;Ethiopia;;Falkland Is.;;Faroe Is.;;Fiji;;Finland;;France;;French Guiana;;French Polynesia;;French Territories;;Gabon;;Gambia;;Georgia;;Germany;;Ghana;;Gibraltar;;Greece;;Greenland;;Grenada;;Guadeloupe;;Guam;;Guatemala;;Guernsey;;Guinea-bissau;;Guinea;;Guyana;;Haiti;;Heard, Mcdonald Is.;;Honduras;;Hong Kong;;Hungary;;Iceland;;India;;Indonesia;;Iran;;Iraq;;Ireland;;Israel;;Italy;;Ivory Coast;;Jamaica;;Japan;;Jersey;;Jordan;;Kazakhstan;;Kenya;;Kiribati;;Korea, D.P.R Of;;Korea, Rep. Of;;Kuwait;;Kyrgyzstan;;Lao Peoples D.R.;;Latvia;;Lebanon;;Lesotho;;Liberia;;Libyan Arab Jamahiriya;;Liechtenstein;;Lithuania;;Luxembourg;;Macao;;Macedonia, F.Y.R Of;;Madagascar;;Malawi;;Malaysia;;Maldives;;Mali;;Malta;;Mariana Islands;;Marshall Islands;;Martinique;;Mauritania;;Mauritius;;Mayotte;;Mexico;;Micronesia;;Moldova;;Monaco;;Mongolia;;Montserrat;;Morocco;;Mozambique;;Myanmar;;Namibia;;Nauru;;Nepal;;Netherlands Antilles;;Netherlands;;New Caledonia;;New Zealand;;Nicaragua;;Niger;;Nigeria;;Niue;;Norfolk Island;;Norway;;Oman;;Pakistan;;Palau;;Palestinian Terr.;;Panama;;Papua New Guinea;;Paraguay;;Peru;;Philippines;;Pitcairn;;Poland;;Portugal;;Puerto Rico;;Qatar;;Reunion;;Romania;;Russian Federation;;Rwanda;;Samoa;;San Marino;;Sao Tome, Principe;;Saudi Arabia;;Senegal;;Seychelles;;Sierra Leone;;Singapore;;Slovakia;;Slovenia;;Solomon Is.;;Somalia;;South Africa;;South Georgia;;South Sandwich Is.;;Spain;;Sri Lanka;;St. Helena;;St. Kitts, Nevis;;St. Lucia;;St. Pierre, Miquelon;;St. Vincent, Grenadines;;Sudan;;Suriname;;Svalbard, Jan Mayen;;Swaziland;;Sweden;;Switzerland;;Syrian Arab Republic;;Taiwan;;Tajikistan;;Tanzania;;Thailand;;Timor-leste;;Togo;;Tokelau;;Tonga;;Trinidad, Tobago;;Tunisia;;Turkey;;Turkmenistan;;Turks, Caicoss;;Tuvalu;;Uganda;;Ukraine;;United Arab Emirates;;United Kingdom;;United States;;Uruguay;;Uzbekistan;;Vanuatu;;Vatican City;;Venezuela;;Viet Nam;;Virgin Is. British;;Virgin Is. U.S.;;Wallis, Futuna;;Western Sahara;;Yemen;;Yugoslavia;;Zambia;;Zimbabwe")));
        $combo_country_hq->ListData = $combo_country_hq->ListItem;
    }
    $combo_country_hq->SelectName = 'country_hq';
    // combobox: country_operations
    $combo_country_operations = new Combo();
    $combo_country_operations->ListType = 3;
    $combo_country_operations->MultipleSeparator = ', ';
    $combo_country_operations->ListBoxHeight = 10;
    $combo_country_operations->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/companies.country_operations.csv')) {
        $country_operations_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/companies.country_operations.csv')));
        $combo_country_operations->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($country_operations_data)));
        $combo_country_operations->ListData = $combo_country_operations->ListItem;
    } else {
        $combo_country_operations->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Afghanistan;;Albania;;Algeria;;American Samoa;;Andorra;;Angola;;Anguilla;;Antarctica;;Antigua, Barbuda;;Argentina;;Armenia;;Aruba;;Australia;;Austria;;Azerbaijan;;Bahamas;;Bahrain;;Bangladesh;;Barbados;;Belarus;;Belgium;;Belize;;Benin;;Bermuda;;Bhutan;;Bolivia;;Bosnia, Herzegovina;;Botswana;;Bouvet Is.;;Brazil;;Brunei Darussalam;;Bulgaria;;Burkina Faso;;Burundi;;Cambodia;;Cameroon;;Canada;;Canary Is.;;Cape Verde;;Cayman Is.;;Central African Rep.;;Chad;;Channel Islands;;Chile;;China;;Christmas Is.;;Cocos Is.;;Colombia;;Comoros;;Congo, D.R. Of;;Congo;;Cook Is.;;Costa Rica;;Croatia;;Cuba;;Cyprus;;Czech Republic;;Denmark;;Djibouti;;Dominica;;Dominican Republic;;Ecuador;;Egypt;;El Salvador;;Equatorial Guinea;;Eritrea;;Estonia;;Ethiopia;;Falkland Is.;;Faroe Is.;;Fiji;;Finland;;France;;French Guiana;;French Polynesia;;French Territories;;Gabon;;Gambia;;Georgia;;Germany;;Ghana;;Gibraltar;;Greece;;Greenland;;Grenada;;Guadeloupe;;Guam;;Guatemala;;Guernsey;;Guinea-bissau;;Guinea;;Guyana;;Haiti;;Heard, Mcdonald Is.;;Honduras;;Hong Kong;;Hungary;;Iceland;;India;;Indonesia;;Iran;;Iraq;;Ireland;;Israel;;Italy;;Ivory Coast;;Jamaica;;Japan;;Jersey;;Jordan;;Kazakhstan;;Kenya;;Kiribati;;Korea, D.P.R Of;;Korea, Rep. Of;;Kuwait;;Kyrgyzstan;;Lao Peoples D.R.;;Latvia;;Lebanon;;Lesotho;;Liberia;;Libyan Arab Jamahiriya;;Liechtenstein;;Lithuania;;Luxembourg;;Macao;;Macedonia, F.Y.R Of;;Madagascar;;Malawi;;Malaysia;;Maldives;;Mali;;Malta;;Mariana Islands;;Marshall Islands;;Martinique;;Mauritania;;Mauritius;;Mayotte;;Mexico;;Micronesia;;Moldova;;Monaco;;Mongolia;;Montserrat;;Morocco;;Mozambique;;Myanmar;;Namibia;;Nauru;;Nepal;;Netherlands Antilles;;Netherlands;;New Caledonia;;New Zealand;;Nicaragua;;Niger;;Nigeria;;Niue;;Norfolk Island;;Norway;;Oman;;Pakistan;;Palau;;Palestinian Terr.;;Panama;;Papua New Guinea;;Paraguay;;Peru;;Philippines;;Pitcairn;;Poland;;Portugal;;Puerto Rico;;Qatar;;Reunion;;Romania;;Russian Federation;;Rwanda;;Samoa;;San Marino;;Sao Tome, Principe;;Saudi Arabia;;Senegal;;Seychelles;;Sierra Leone;;Singapore;;Slovakia;;Slovenia;;Solomon Is.;;Somalia;;South Africa;;South Georgia;;South Sandwich Is.;;Spain;;Sri Lanka;;St. Helena;;St. Kitts, Nevis;;St. Lucia;;St. Pierre, Miquelon;;St. Vincent, Grenadines;;Sudan;;Suriname;;Svalbard, Jan Mayen;;Swaziland;;Sweden;;Switzerland;;Syrian Arab Republic;;Taiwan;;Tajikistan;;Tanzania;;Thailand;;Timor-leste;;Togo;;Tokelau;;Tonga;;Trinidad, Tobago;;Tunisia;;Turkey;;Turkmenistan;;Turks, Caicoss;;Tuvalu;;Uganda;;Ukraine;;United Arab Emirates;;United Kingdom;;United States;;Uruguay;;Uzbekistan;;Vanuatu;;Vatican City;;Venezuela;;Viet Nam;;Virgin Is. British;;Virgin Is. U.S.;;Wallis, Futuna;;Western Sahara;;Yemen;;Yugoslavia;;Zambia;;Zimbabwe")));
        $combo_country_operations->ListData = $combo_country_operations->ListItem;
    }
    $combo_country_operations->SelectName = 'country_operations';
    // combobox: company_type
    $combo_company_type = new Combo();
    $combo_company_type->ListType = 0;
    $combo_company_type->MultipleSeparator = ', ';
    $combo_company_type->ListBoxHeight = 10;
    $combo_company_type->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/companies.company_type.csv')) {
        $company_type_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/companies.company_type.csv')));
        $combo_company_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($company_type_data)));
        $combo_company_type->ListData = $combo_company_type->ListItem;
    } else {
        $combo_company_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("501(c);;AG;;BV;;CIC;;Company limited by guarantee;;Cooperative;;GmbH;;Inc;;IPS;;L3C;;LLP;;LP;;Ltd;;Ltda;;Non-incorporated partnership;;Not stated;;NV;;PLC;;Private company limited by shares;;Royal Charter;;SA;;SARL;;Societas Europaea;;Sole trader;;Subsidiary;;Unincorporated;;Unlimited")));
        $combo_company_type->ListData = $combo_company_type->ListItem;
    }
    $combo_company_type->SelectName = 'company_type';
    // combobox: sic_code
    $combo_sic_code = new DataCombo();
    // combobox: created
    $combo_created = new DateCombo();
    $combo_created->DateFormat = "dmy";
    $combo_created->MinYear = 1900;
    $combo_created->MaxYear = 2100;
    $combo_created->DefaultDate = parseMySQLDate('<%%creationDate%%>', '<%%creationDate%%>');
    $combo_created->MonthNames = $Translation['month names'];
    $combo_created->NamePrefix = 'created';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='companies' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='companies' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `companies` where `company_id`='" . makeSafe($selected_id) . "'", $eo);
        $row = mysql_fetch_array($res);
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_client->SelectedData = $row['client'];
        $combo_industry->SelectedData = $row['industry'];
        $combo_country_hq->SelectedData = $row['country_hq'];
        $combo_country_operations->SelectedData = $row['country_operations'];
        $combo_company_type->SelectedData = $row['company_type'];
        $combo_sic_code->SelectedData = $row['sic_code'];
        $combo_created->DefaultDate = $row['created'];
    } else {
        $combo_client->SelectedData = $filterer_client;
        $combo_industry->SelectedText = $_REQUEST['FilterField'][1] == '7' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_country_hq->SelectedText = $_REQUEST['FilterField'][1] == '9' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "United Kingdom";
        $combo_company_type->SelectedText = $_REQUEST['FilterField'][1] == '12' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_sic_code->SelectedData = $filterer_sic_code;
    }
    $combo_client->HTML = $combo_client->MatchText = '<span id="client-container' . $rnd1 . '"></span><input type="hidden" name="client" id="client' . $rnd1 . '">';
    $combo_industry->Render();
    $combo_country_hq->Render();
    $combo_country_operations->Render();
    $combo_company_type->Render();
    $combo_sic_code->HTML = $combo_sic_code->MatchText = '<span id="sic_code-container' . $rnd1 . '"></span><input type="hidden" name="sic_code" id="sic_code' . $rnd1 . '">';
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_client__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['client'] : $filterer_client);
    ?>
"};
		var current_sic_code__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['sic_code'] : $filterer_sic_code);
    ?>
"};
		
		jQuery(function() {
			client_reload__RAND__();
			sic_code_reload__RAND__();
		});
		function client_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#client-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_client__RAND__.value, t: 'companies', f: 'client' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="client"]').val(resp.results[0].id);


						if(typeof(client_update_autofills__RAND__) == 'function') client_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'companies', f: 'client' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_client__RAND__.value = e.added.id;
				current_client__RAND__.text = e.added.text;
				jQuery('[name="client"]').val(e.added.id);


				if(typeof(client_update_autofills__RAND__) == 'function') client_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_client__RAND__.value, t: 'companies', f: 'client' }
			}).done(function(resp){
				jQuery('#client-container__RAND__').html('<span id="client-match-text">' + resp.results[0].text + '</span>');

				if(typeof(client_update_autofills__RAND__) == 'function') client_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
		function sic_code_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#sic_code-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_sic_code__RAND__.value, t: 'companies', f: 'sic_code' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="sic_code"]').val(resp.results[0].id);


						if(typeof(sic_code_update_autofills__RAND__) == 'function') sic_code_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'companies', f: 'sic_code' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_sic_code__RAND__.value = e.added.id;
				current_sic_code__RAND__.text = e.added.text;
				jQuery('[name="sic_code"]').val(e.added.id);


				if(typeof(sic_code_update_autofills__RAND__) == 'function') sic_code_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_sic_code__RAND__.value, t: 'companies', f: 'sic_code' }
			}).done(function(resp){
				jQuery('#sic_code-container__RAND__').html('<span id="sic_code-match-text">' + resp.results[0].text + '</span>');

				if(typeof(sic_code_update_autofills__RAND__) == 'function') sic_code_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/companies_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/companies_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Company details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    // process buttons
    if ($arrPerm[1]) {
        // allow insert?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return companies_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return companies_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return companies_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$arrPerm[1] || !$selected_id && !$arrPerm[1]) {
        $jsReadOnly .= "\tjQuery('#name').replaceWith('<p class=\"form-control-static\" id=\"name\">' + (jQuery('#name').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#client').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#client_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#website').replaceWith('<p class=\"form-control-static\" id=\"website\">' + (jQuery('#website').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#website, #website-edit-link').hide();\n";
        $jsReadOnly .= "\tjQuery('#description').replaceWith('<p class=\"form-control-static\" id=\"description\">' + (jQuery('#description').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#founded').replaceWith('<p class=\"form-control-static\" id=\"founded\">' + (jQuery('#founded').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#industry').replaceWith('<p class=\"form-control-static\" id=\"industry\">' + (jQuery('#industry').val() || '') + '</p>'); jQuery('#industry-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#company_number').replaceWith('<p class=\"form-control-static\" id=\"company_number\">' + (jQuery('#company_number').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#country_hq').replaceWith('<p class=\"form-control-static\" id=\"country_hq\">' + (jQuery('#country_hq').val() || '') + '</p>'); jQuery('#country_hq-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#country_operations').replaceWith('<p class=\"form-control-static\" id=\"country_operations\">' + (jQuery('#country_operations').val() || '') + '</p>'); jQuery('#country_operations-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#s2id_country_operations').remove();\n";
        $jsReadOnly .= "\tjQuery('#num_employees').replaceWith('<p class=\"form-control-static\" id=\"num_employees\">' + (jQuery('#num_employees').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#company_type').replaceWith('<p class=\"form-control-static\" id=\"company_type\">' + (jQuery('#company_type').val() || '') + '</p>'); jQuery('#company_type-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#sic_code').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#sic_code_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $noUploads = true;
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(client)%%>', $combo_client->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(client)%%>', $combo_client->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(client)%%>', urlencode($combo_client->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(industry)%%>', $combo_industry->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(industry)%%>', $combo_industry->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(country_hq)%%>', $combo_country_hq->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(country_hq)%%>', $combo_country_hq->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(country_operations)%%>', $combo_country_operations->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(country_operations)%%>', $combo_country_operations->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(company_type)%%>', $combo_company_type->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(company_type)%%>', $combo_company_type->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(sic_code)%%>', $combo_sic_code->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(sic_code)%%>', $combo_sic_code->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(sic_code)%%>', urlencode($combo_sic_code->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(created)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_created->GetHTML(true) . '</p>' : $combo_created->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(created)%%>', $combo_created->GetHTML(true), $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(client)%%>', $combo_client->SelectedData ? "<span id=\"clients_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"clients_view.php?SelectedID=" . urlencode($combo_client->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(sic_code)%%>', $combo_sic_code->SelectedData ? "<span id=\"sic_plink2\" class=\"hidden\"><a class=\"btn btn-default\" href=\"sic_view.php?SelectedID=" . urlencode($combo_sic_code->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(company_id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(name)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(client)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(website)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(description)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(founded)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(industry)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(company_number)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(country_hq)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(country_operations)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(num_employees)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(company_type)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(sic_code)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(created)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(created_by)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(company_id)%%>', htmlspecialchars($row['company_id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company_id)%%>', urlencode($urow['company_id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(name)%%>', htmlspecialchars($row['name'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(name)%%>', urlencode($urow['name']), $templateCode);
        $templateCode = str_replace('<%%VALUE(client)%%>', htmlspecialchars($row['client'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(client)%%>', urlencode($urow['client']), $templateCode);
        $templateCode = str_replace('<%%VALUE(website)%%>', htmlspecialchars($row['website'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(website)%%>', urlencode($urow['website']), $templateCode);
        $templateCode = str_replace('<%%VALUE(description)%%>', htmlspecialchars($row['description'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode($urow['description']), $templateCode);
        $templateCode = str_replace('<%%VALUE(founded)%%>', htmlspecialchars($row['founded'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(founded)%%>', urlencode($urow['founded']), $templateCode);
        $templateCode = str_replace('<%%VALUE(industry)%%>', htmlspecialchars($row['industry'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(industry)%%>', urlencode($urow['industry']), $templateCode);
        $templateCode = str_replace('<%%VALUE(company_number)%%>', htmlspecialchars($row['company_number'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company_number)%%>', urlencode($urow['company_number']), $templateCode);
        $templateCode = str_replace('<%%VALUE(country_hq)%%>', htmlspecialchars($row['country_hq'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country_hq)%%>', urlencode($urow['country_hq']), $templateCode);
        $templateCode = str_replace('<%%VALUE(country_operations)%%>', htmlspecialchars($row['country_operations'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country_operations)%%>', urlencode($urow['country_operations']), $templateCode);
        $templateCode = str_replace('<%%VALUE(num_employees)%%>', htmlspecialchars($row['num_employees'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(num_employees)%%>', urlencode($urow['num_employees']), $templateCode);
        $templateCode = str_replace('<%%VALUE(company_type)%%>', htmlspecialchars($row['company_type'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company_type)%%>', urlencode($urow['company_type']), $templateCode);
        $templateCode = str_replace('<%%VALUE(sic_code)%%>', htmlspecialchars($row['sic_code'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(sic_code)%%>', urlencode($urow['sic_code']), $templateCode);
        $templateCode = str_replace('<%%VALUE(created)%%>', @date('d/m/Y', @strtotime(htmlspecialchars($row['created'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created)%%>', urlencode(@date('d/m/Y', @strtotime(htmlspecialchars($urow['created'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(created_by)%%>', htmlspecialchars($row['created_by'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created_by)%%>', urlencode($urow['created_by']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(company_id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company_id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(name)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(name)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(client)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(client)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(website)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(website)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(description)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(founded)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(founded)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(industry)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(industry)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(company_number)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company_number)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(country_hq)%%>', 'United Kingdom', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country_hq)%%>', urlencode('United Kingdom'), $templateCode);
        $templateCode = str_replace('<%%VALUE(country_operations)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country_operations)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(num_employees)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(num_employees)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(company_type)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company_type)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(sic_code)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(sic_code)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(created)%%>', '<%%creationDate%%>', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created)%%>', urlencode('<%%creationDate%%>'), $templateCode);
        $templateCode = str_replace('<%%VALUE(created_by)%%>', '<%%creatorUsername%%>', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created_by)%%>', urlencode('<%%creatorUsername%%>'), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>jQuery(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\tjQuery('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        if (!$selected_id) {
            $templateCode .= "\n\tif(document.getElementById('websiteEdit')){ document.getElementById('websiteEdit').style.display='inline'; }";
            $templateCode .= "\n\tif(document.getElementById('websiteEditLink')){ document.getElementById('websiteEditLink').style.display='none'; }";
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= "<script>";
    $templateCode .= "document.observe('dom:loaded', function() {";
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: companies_dv
    if (function_exists('companies_dv')) {
        $args = array();
        companies_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
function applications_leases_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('applications_leases');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_tenants = thisOr(undo_magic_quotes($_REQUEST['filterer_tenants']), '');
    $filterer_property = thisOr(undo_magic_quotes($_REQUEST['filterer_property']), '');
    $filterer_unit = thisOr(undo_magic_quotes($_REQUEST['filterer_unit']), '');
    // populate filterers, starting from children to grand-parents
    if ($filterer_unit && !$filterer_property) {
        $filterer_property = sqlValue("select property from units where id='" . makeSafe($filterer_unit) . "'");
    }
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: tenants
    $combo_tenants = new DataCombo();
    // combobox: status
    $combo_status = new Combo();
    $combo_status->ListType = 2;
    $combo_status->MultipleSeparator = ', ';
    $combo_status->ListBoxHeight = 10;
    $combo_status->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/applications_leases.status.csv')) {
        $status_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/applications_leases.status.csv')));
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($status_data)));
        $combo_status->ListData = $combo_status->ListItem;
    } else {
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Application;;Lease;;Historical lease")));
        $combo_status->ListData = $combo_status->ListItem;
    }
    $combo_status->SelectName = 'status';
    $combo_status->AllowNull = false;
    // combobox: property
    $combo_property = new DataCombo();
    // combobox: unit, filterable by: property
    $combo_unit = new DataCombo();
    // combobox: type
    $combo_type = new Combo();
    $combo_type->ListType = 2;
    $combo_type->MultipleSeparator = ', ';
    $combo_type->ListBoxHeight = 10;
    $combo_type->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/applications_leases.type.csv')) {
        $type_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/applications_leases.type.csv')));
        $combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($type_data)));
        $combo_type->ListData = $combo_type->ListItem;
    } else {
        $combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Fixed;;Fixed with rollover;;At-will")));
        $combo_type->ListData = $combo_type->ListItem;
    }
    $combo_type->SelectName = 'type';
    $combo_type->AllowNull = false;
    // combobox: start_date
    $combo_start_date = new DateCombo();
    $combo_start_date->DateFormat = "mdy";
    $combo_start_date->MinYear = 1900;
    $combo_start_date->MaxYear = 2100;
    $combo_start_date->DefaultDate = parseMySQLDate('1', '1');
    $combo_start_date->MonthNames = $Translation['month names'];
    $combo_start_date->NamePrefix = 'start_date';
    // combobox: end_date
    $combo_end_date = new DateCombo();
    $combo_end_date->DateFormat = "mdy";
    $combo_end_date->MinYear = 1900;
    $combo_end_date->MaxYear = 2100;
    $combo_end_date->DefaultDate = parseMySQLDate('1', '1');
    $combo_end_date->MonthNames = $Translation['month names'];
    $combo_end_date->NamePrefix = 'end_date';
    // combobox: recurring_charges_frequency
    $combo_recurring_charges_frequency = new Combo();
    $combo_recurring_charges_frequency->ListType = 0;
    $combo_recurring_charges_frequency->MultipleSeparator = ', ';
    $combo_recurring_charges_frequency->ListBoxHeight = 10;
    $combo_recurring_charges_frequency->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/applications_leases.recurring_charges_frequency.csv')) {
        $recurring_charges_frequency_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/applications_leases.recurring_charges_frequency.csv')));
        $combo_recurring_charges_frequency->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($recurring_charges_frequency_data)));
        $combo_recurring_charges_frequency->ListData = $combo_recurring_charges_frequency->ListItem;
    } else {
        $combo_recurring_charges_frequency->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Daily;;Weekly;;Every two weeks;;Monthly;;Every two months;;Quarterly;;Every six months;;Yearly;;One time")));
        $combo_recurring_charges_frequency->ListData = $combo_recurring_charges_frequency->ListItem;
    }
    $combo_recurring_charges_frequency->SelectName = 'recurring_charges_frequency';
    $combo_recurring_charges_frequency->AllowNull = false;
    // combobox: next_due_date
    $combo_next_due_date = new DateCombo();
    $combo_next_due_date->DateFormat = "mdy";
    $combo_next_due_date->MinYear = 1900;
    $combo_next_due_date->MaxYear = 2100;
    $combo_next_due_date->DefaultDate = parseMySQLDate('1', '1');
    $combo_next_due_date->MonthNames = $Translation['month names'];
    $combo_next_due_date->NamePrefix = 'next_due_date';
    // combobox: security_deposit_date
    $combo_security_deposit_date = new DateCombo();
    $combo_security_deposit_date->DateFormat = "mdy";
    $combo_security_deposit_date->MinYear = 1900;
    $combo_security_deposit_date->MaxYear = 2100;
    $combo_security_deposit_date->DefaultDate = parseMySQLDate('', '');
    $combo_security_deposit_date->MonthNames = $Translation['month names'];
    $combo_security_deposit_date->NamePrefix = 'security_deposit_date';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='applications_leases' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='applications_leases' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `applications_leases` where `id`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_tenants->SelectedData = $row['tenants'];
        $combo_status->SelectedData = $row['status'];
        $combo_property->SelectedData = $row['property'];
        $combo_unit->SelectedData = $row['unit'];
        $combo_type->SelectedData = $row['type'];
        $combo_start_date->DefaultDate = $row['start_date'];
        $combo_end_date->DefaultDate = $row['end_date'];
        $combo_recurring_charges_frequency->SelectedData = $row['recurring_charges_frequency'];
        $combo_next_due_date->DefaultDate = $row['next_due_date'];
        $combo_security_deposit_date->DefaultDate = $row['security_deposit_date'];
    } else {
        $combo_tenants->SelectedData = $filterer_tenants;
        $combo_status->SelectedText = $_REQUEST['FilterField'][1] == '3' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "Application";
        $combo_property->SelectedData = $filterer_property;
        $combo_unit->SelectedData = $filterer_unit;
        $combo_type->SelectedText = $_REQUEST['FilterField'][1] == '6' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "Fixed";
        $combo_recurring_charges_frequency->SelectedText = $_REQUEST['FilterField'][1] == '10' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "Monthly";
    }
    $combo_tenants->HTML = '<span id="tenants-container' . $rnd1 . '"></span><input type="hidden" name="tenants" id="tenants' . $rnd1 . '">';
    $combo_tenants->MatchText = '<span id="tenants-container-readonly' . $rnd1 . '"></span><input type="hidden" name="tenants" id="tenants' . $rnd1 . '">';
    $combo_status->Render();
    $combo_property->HTML = '<span id="property-container' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '">';
    $combo_property->MatchText = '<span id="property-container-readonly' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '">';
    $combo_unit->HTML = '<span id="unit-container' . $rnd1 . '"></span><input type="hidden" name="unit" id="unit' . $rnd1 . '">';
    $combo_unit->MatchText = '<span id="unit-container-readonly' . $rnd1 . '"></span><input type="hidden" name="unit" id="unit' . $rnd1 . '">';
    $combo_type->Render();
    $combo_recurring_charges_frequency->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_tenants__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['tenants'] : $filterer_tenants);
    ?>
"};
		var current_property__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['property'] : $filterer_property);
    ?>
"};
		var current_unit__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['unit'] : $filterer_unit);
    ?>
"};

		jQuery(function() {
			tenants_reload__RAND__();
			property_reload__RAND__();
			<?php 
    echo !$AllowUpdate || $dvprint ? 'unit_reload__RAND__(current_property__RAND__.value);' : '';
    ?>
		});
		function tenants_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#tenants-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_tenants__RAND__.value, t: 'applications_leases', f: 'tenants' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="tenants"]').val(resp.results[0].id);
						jQuery('[id=tenants-container-readonly__RAND__]').html('<span id="tenants-match-text">' + resp.results[0].text + '</span>');


						if(typeof(tenants_update_autofills__RAND__) == 'function') tenants_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'applications_leases', f: 'tenants' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_tenants__RAND__.value = e.added.id;
				current_tenants__RAND__.text = e.added.text;
				jQuery('[name="tenants"]').val(e.added.id);


				if(typeof(tenants_update_autofills__RAND__) == 'function') tenants_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_tenants__RAND__.value, t: 'applications_leases', f: 'tenants' }
			}).done(function(resp){
				jQuery('[id=tenants-container__RAND__], [id=tenants-container-readonly__RAND__]').html('<span id="tenants-match-text">' + resp.results[0].text + '</span>');

				if(typeof(tenants_update_autofills__RAND__) == 'function') tenants_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
		function property_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#property-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_property__RAND__.value, t: 'applications_leases', f: 'property' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="property"]').val(resp.results[0].id);
						jQuery('[id=property-container-readonly__RAND__]').html('<span id="property-match-text">' + resp.results[0].text + '</span>');

						unit_reload__RAND__(current_property__RAND__.value);

						if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'applications_leases', f: 'property' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_property__RAND__.value = e.added.id;
				current_property__RAND__.text = e.added.text;
				jQuery('[name="property"]').val(e.added.id);

						unit_reload__RAND__(current_property__RAND__.value);

				if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_property__RAND__.value, t: 'applications_leases', f: 'property' }
			}).done(function(resp){
				jQuery('[id=property-container__RAND__], [id=property-container-readonly__RAND__]').html('<span id="property-match-text">' + resp.results[0].text + '</span>');

				if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
		function unit_reload__RAND__(filterer_property){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#unit-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { filterer_property: filterer_property, id: current_unit__RAND__.value, t: 'applications_leases', f: 'unit' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="unit"]').val(resp.results[0].id);
						jQuery('[id=unit-container-readonly__RAND__]').html('<span id="unit-match-text">' + resp.results[0].text + '</span>');


						if(typeof(unit_update_autofills__RAND__) == 'function') unit_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { filterer_property: filterer_property, s: term, p: page, t: 'applications_leases', f: 'unit' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_unit__RAND__.value = e.added.id;
				current_unit__RAND__.text = e.added.text;
				jQuery('[name="unit"]').val(e.added.id);


				if(typeof(unit_update_autofills__RAND__) == 'function') unit_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_unit__RAND__.value, t: 'applications_leases', f: 'unit' }
			}).done(function(resp){
				jQuery('[id=unit-container__RAND__], [id=unit-container-readonly__RAND__]').html('<span id="unit-match-text">' + resp.results[0].text + '</span>');

				if(typeof(unit_update_autofills__RAND__) == 'function') unit_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/applications_leases_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/applications_leases_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Lease details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($AllowInsert) {
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return applications_leases_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return applications_leases_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return applications_leases_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$AllowInsert || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#tenants').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#tenants_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('input[name=status]').parent().html('<p class=\"form-control-static\">' + jQuery('input[name=status]:checked').next().text() + '</p>')\n";
        $jsReadOnly .= "\tjQuery('#property').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#property_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#unit').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#unit_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('input[name=type]').parent().html('<p class=\"form-control-static\">' + jQuery('input[name=type]:checked').next().text() + '</p>')\n";
        $jsReadOnly .= "\tjQuery('#total_number_of_occupants').replaceWith('<p class=\"form-control-static\" id=\"total_number_of_occupants\">' + (jQuery('#total_number_of_occupants').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#start_date').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#start_dateDay, #start_dateMonth, #start_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#end_date').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#end_dateDay, #end_dateMonth, #end_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#recurring_charges_frequency').replaceWith('<p class=\"form-control-static\" id=\"recurring_charges_frequency\">' + (jQuery('#recurring_charges_frequency').val() || '') + '</p>'); jQuery('#recurring_charges_frequency-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#next_due_date').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#next_due_dateDay, #next_due_dateMonth, #next_due_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#rent').replaceWith('<p class=\"form-control-static\" id=\"rent\">' + (jQuery('#rent').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#security_deposit').replaceWith('<p class=\"form-control-static\" id=\"security_deposit\">' + (jQuery('#security_deposit').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#security_deposit_date').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#security_deposit_dateDay, #security_deposit_dateMonth, #security_deposit_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#emergency_contact').replaceWith('<p class=\"form-control-static\" id=\"emergency_contact\">' + (jQuery('#emergency_contact').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#co_signer_details').replaceWith('<p class=\"form-control-static\" id=\"co_signer_details\">' + (jQuery('#co_signer_details').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#agreement').prop('disabled', true);\n";
        $noUploads = true;
    } elseif ($AllowInsert) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(tenants)%%>', $combo_tenants->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(tenants)%%>', $combo_tenants->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(tenants)%%>', urlencode($combo_tenants->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(status)%%>', $combo_status->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(status)%%>', $combo_status->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(property)%%>', $combo_property->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(property)%%>', $combo_property->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(property)%%>', urlencode($combo_property->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(unit)%%>', $combo_unit->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(unit)%%>', $combo_unit->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(unit)%%>', urlencode($combo_unit->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(type)%%>', $combo_type->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(type)%%>', $combo_type->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(start_date)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_start_date->GetHTML(true) . '</p>' : $combo_start_date->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(start_date)%%>', $combo_start_date->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(end_date)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_end_date->GetHTML(true) . '</p>' : $combo_end_date->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(end_date)%%>', $combo_end_date->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(recurring_charges_frequency)%%>', $combo_recurring_charges_frequency->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(recurring_charges_frequency)%%>', $combo_recurring_charges_frequency->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(next_due_date)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_next_due_date->GetHTML(true) . '</p>' : $combo_next_due_date->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(next_due_date)%%>', $combo_next_due_date->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(security_deposit_date)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_security_deposit_date->GetHTML(true) . '</p>' : $combo_security_deposit_date->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(security_deposit_date)%%>', $combo_security_deposit_date->GetHTML(true), $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(tenants)%%>', $combo_tenants->SelectedData ? "<span id=\"applicants_and_tenants_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"applicants_and_tenants_view.php?SelectedID=" . urlencode($combo_tenants->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(property)%%>', $combo_property->SelectedData ? "<span id=\"properties_plink2\" class=\"hidden\"><a class=\"btn btn-default\" href=\"properties_view.php?SelectedID=" . urlencode($combo_property->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(unit)%%>', $combo_unit->SelectedData ? "<span id=\"units_plink3\" class=\"hidden\"><a class=\"btn btn-default\" href=\"units_view.php?SelectedID=" . urlencode($combo_unit->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(tenants)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(status)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(property)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(unit)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(type)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(total_number_of_occupants)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(start_date)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(end_date)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(recurring_charges_frequency)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(next_due_date)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(rent)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(security_deposit)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(security_deposit_date)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(emergency_contact)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(co_signer_details)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(notes)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(agreement)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(id)%%>', htmlspecialchars($row['id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(tenants)%%>', htmlspecialchars($row['tenants'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(tenants)%%>', urlencode($urow['tenants']), $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', htmlspecialchars($row['status'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode($urow['status']), $templateCode);
        $templateCode = str_replace('<%%VALUE(property)%%>', htmlspecialchars($row['property'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode($urow['property']), $templateCode);
        $templateCode = str_replace('<%%VALUE(unit)%%>', htmlspecialchars($row['unit'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(unit)%%>', urlencode($urow['unit']), $templateCode);
        $templateCode = str_replace('<%%VALUE(type)%%>', htmlspecialchars($row['type'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode($urow['type']), $templateCode);
        $templateCode = str_replace('<%%VALUE(total_number_of_occupants)%%>', htmlspecialchars($row['total_number_of_occupants'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(total_number_of_occupants)%%>', urlencode($urow['total_number_of_occupants']), $templateCode);
        $templateCode = str_replace('<%%VALUE(start_date)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['start_date'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(start_date)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['start_date'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(end_date)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['end_date'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(end_date)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['end_date'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(recurring_charges_frequency)%%>', htmlspecialchars($row['recurring_charges_frequency'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(recurring_charges_frequency)%%>', urlencode($urow['recurring_charges_frequency']), $templateCode);
        $templateCode = str_replace('<%%VALUE(next_due_date)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['next_due_date'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(next_due_date)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['next_due_date'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(rent)%%>', htmlspecialchars($row['rent'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rent)%%>', urlencode($urow['rent']), $templateCode);
        $templateCode = str_replace('<%%VALUE(security_deposit)%%>', htmlspecialchars($row['security_deposit'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(security_deposit)%%>', urlencode($urow['security_deposit']), $templateCode);
        $templateCode = str_replace('<%%VALUE(security_deposit_date)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['security_deposit_date'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(security_deposit_date)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['security_deposit_date'], ENT_QUOTES)))), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(emergency_contact)%%>', nl2br(htmlspecialchars($row['emergency_contact'], ENT_QUOTES)), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(emergency_contact)%%>', htmlspecialchars($row['emergency_contact'], ENT_QUOTES), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(emergency_contact)%%>', urlencode($urow['emergency_contact']), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(co_signer_details)%%>', nl2br(htmlspecialchars($row['co_signer_details'], ENT_QUOTES)), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(co_signer_details)%%>', htmlspecialchars($row['co_signer_details'], ENT_QUOTES), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(co_signer_details)%%>', urlencode($urow['co_signer_details']), $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea name="notes" id="notes" rows="5">' . htmlspecialchars($row['notes'], ENT_QUOTES) . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(notes)%%>', $row['notes'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(notes)%%>', nl2br($row['notes']), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(notes)%%>', urlencode($urow['notes']), $templateCode);
        $templateCode = str_replace('<%%CHECKED(agreement)%%>', $row['agreement'] ? "checked" : "", $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(tenants)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(tenants)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', 'Application', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode('Application'), $templateCode);
        $templateCode = str_replace('<%%VALUE(property)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(unit)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(unit)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(type)%%>', 'Fixed', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode('Fixed'), $templateCode);
        $templateCode = str_replace('<%%VALUE(total_number_of_occupants)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(total_number_of_occupants)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(start_date)%%>', '1', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(start_date)%%>', urlencode('1'), $templateCode);
        $templateCode = str_replace('<%%VALUE(end_date)%%>', '1', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(end_date)%%>', urlencode('1'), $templateCode);
        $templateCode = str_replace('<%%VALUE(recurring_charges_frequency)%%>', 'Monthly', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(recurring_charges_frequency)%%>', urlencode('Monthly'), $templateCode);
        $templateCode = str_replace('<%%VALUE(next_due_date)%%>', '1', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(next_due_date)%%>', urlencode('1'), $templateCode);
        $templateCode = str_replace('<%%VALUE(rent)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rent)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(security_deposit)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(security_deposit)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(security_deposit_date)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(security_deposit_date)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(emergency_contact)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(emergency_contact)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(co_signer_details)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(co_signer_details)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea name="notes" id="notes" rows="5"></textarea>', $templateCode);
        $templateCode = str_replace('<%%CHECKED(agreement)%%>', '', $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: applications_leases_dv
    if (function_exists('applications_leases_dv')) {
        $args = array();
        applications_leases_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
示例#10
0
function getOptionsFilter(&$fileContent, $field, $fieldNum, $filterCounter)
{
    $options = explode('||', entitiesToUTF8(convertLegacyOptions($field->CSValueList->__toString())));
    //check data length
    if (count($options) > 6) {
        //DROPDOWN
        $fileContent .= '
        <?php
        	 $options = ' . json_encode($options) . ';
        
            //convert options to select2 format
            $optionsList = array();
            for ($i = 0; $i < count($options); $i++) {
                $optionsList[] = (object) array(
                            "id" => $i,
                            "text" => $options[$i]
                );
            }
            $optionsList = json_encode($optionsList);

        
        //convert value to select2 format
        if ($FilterValue[' . $filterCounter . ']) {
            $filtervalueObj = new stdClass();
            $text = htmlspecialchars($FilterValue[' . $filterCounter . ']);
            $filtervalueObj->text = $text;
            $filtervalueObj->id = array_search($text, $options);

            $filtervalueObj = json_encode($filtervalueObj);
        }

        ?>';
        ob_start();
        ?>
        <div class="row vspacer-lg" style="border-bottom: dotted 2px #DDD;" >
            <div class="col-md-offset-3 col-md-2 col-sm-3 col-xs-12 vspacer-lg"><strong><?php 
        echo $field->caption->__toString();
        ?>
</strong></div>
              <button type="button" class="btn btn-default pull-col-lg-3 vspacer-lg" title='Clear fields'  onclick="clearFilters(this);" ><span class="glyphicon glyphicon-trash text-danger"></button>

            <div id="<?php 
        echo $fieldNum;
        ?>
_DropDown" class="drop-down col-md-3 col-sm-6 col-xs-10 vspacer-lg"><span></span></div>
            <input type="hidden" class="populatedOptionsData" name="<?php 
        echo $filterCounter;
        ?>
" value="<?php 
        echo '<' . '?php echo htmlspecialchars($FilterValue[' . $filterCounter . ']); ?>';
        ?>
" >
            <input type="hidden" name="FilterAnd[<?php 
        echo $filterCounter;
        ?>
]" value="and">
            <input type="hidden" name="FilterField[<?php 
        echo $filterCounter;
        ?>
]" value="<?php 
        echo $fieldNum;
        ?>
">
            <input type="hidden" name="FilterOperator[<?php 
        echo $filterCounter;
        ?>
]" value="equal-to">
            <input type="hidden" name="FilterValue[<?php 
        echo $filterCounter;
        ?>
]" id="<?php 
        echo $fieldNum;
        ?>
_currValue" value="<?php 
        echo '<' . '?php echo htmlspecialchars($FilterValue[' . $filterCounter . ']); ?>';
        ?>
" size="3">
            
        </div>

        <script>
            var populate_<?php 
        echo $fieldNum;
        ?>
 = <?php 
        echo '<' . '?php echo $filtervalueObj ;?>';
        ?>
            
            $j(function () {
                $j("#<?php 
        echo $fieldNum;
        ?>
_DropDown").select2({
                    data: <?php 
        echo "<" . '?php echo $optionsList; ?>';
        ?>
}).on('change', function (e) {
                    $j("#<?php 
        echo $fieldNum;
        ?>
_currValue").val(e.added.text);

                });


                /* preserve the applied filter and show it when re-opening the filters page */
                if ($j("#<?php 
        echo $fieldNum;
        ?>
_currValue").val().length) {
                    $j("#<?php 
        echo $fieldNum;
        ?>
_DropDown").select2('data', populate_<?php 
        echo $fieldNum;
        ?>
 );
                }
            });

        </script>
        <?php 
        $retVal = ob_get_contents();
        ob_end_clean();
        $fileContent .= $retVal;
    } else {
        //Radio buttons
        ob_start();
        ?>

        <div class="row" style="border-bottom: dotted 2px #DDD;">
            <div class="col-md-offset-3 col-md-2 col-sm-3 col-xs-12 vspacer-lg"><strong><?php 
        echo $field->caption->__toString();
        ?>
</strong></div>
              <button type="button" class="btn btn-default pull-col-lg-3 vspacer-lg" title='Clear fields'  onclick="clearFilters(this);" ><span class="glyphicon glyphicon-trash text-danger"></button>
            <input type="hidden" class='optionsData' name="FilterField[<?php 
        echo $filterCounter;
        ?>
]" value="<?php 
        echo $fieldNum;
        ?>
">
            <div class="col-md-8 col-md-offset-3">

                    <input type="hidden" name="FilterAnd[<?php 
        echo $filterCounter;
        ?>
]" value="and">
                    <input type="hidden" name="FilterOperator[<?php 
        echo $filterCounter;
        ?>
]" value="equal-to">
                    <input type="hidden" name="FilterValue[<?php 
        echo $filterCounter;
        ?>
]" id="<?php 
        echo $fieldNum;
        ?>
_currValue" value="<?php 
        echo '<' . '?php echo htmlspecialchars($FilterValue[' . $filterCounter . ']); ?>';
        ?>
" size="3">

                <?php 
        foreach ($options as $option) {
            ?>
                        <div class="radio">
                            <label>
                                 <input type="radio" name="FilterValue[<?php 
            echo $filterCounter;
            ?>
]" class="filter_<?php 
            echo $fieldNum;
            ?>
" value='<?php 
            echo $option;
            ?>
'><?php 
            echo $option;
            ?>
                            </label>
                        </div>
                 <?php 
        }
        ?>
            </div>
        </div>
        <script>
            //for population
            var filterValue_<?php 
        echo $fieldNum;
        ?>
 = '<?php 
        echo "<" . '?php echo htmlspecialchars($FilterValue[ ' . $filterCounter . ' ]); ?>';
        ?>
';
            $j(function () {
                if (filterValue_<?php 
        echo $fieldNum;
        ?>
) {
                    $j("input[class =filter_<?php 
        echo $fieldNum;
        ?>
][value ='" + filterValue_<?php 
        echo $fieldNum;
        ?>
 + "']").attr("checked", "checked");
                }
            })

        </script>
        <?php 
        $retVal = ob_get_contents();
        ob_end_clean();
        $fileContent .= $retVal;
    }
}