/**
 * Updates event information in the database
 *
 * @param int $eventId					- update event ID
 *
 * @return int 							- zero on success, non-zero on fail
 *
 *
 */
function SDUpdateEvent($eventId)
{
    global $dir;
    global $sdatingThumbWidth;
    global $sdatingThumbHeight;
    $eventExistArr = db_arr("SELECT `ID`, `Title`, `Description`, `Status`, `StatusMessage`, `Country`, `City`, `Place`, `PhotoFilename`, `EventStart`, `EventEnd`, `TicketSaleStart`, `TicketSaleEnd`, `ResponsibleName`, `ResponsibleEmail`, `ResponsiblePhone`, `EventSexFilter`, `EventAgeLowerFilter`, `EventAgeUpperFilter`, `EventMembershipFilter`, `TicketCountFemale`, `TicketCountMale`, `TicketPriceFemale`, `TicketPriceMale`, `ChoosePeriod`, `AllowViewParticipants` FROM `SDatingEvents` WHERE `ID` = {$eventId}");
    // common
    $eventTitle = process_db_input($_POST['event_title']);
    $eventDesc = process_db_input($_POST['event_desc']);
    switch ($_POST['event_status']) {
        case 'active':
            $eventStatus = 'Active';
            break;
        case 'inactive':
            $eventStatus = 'Inactive';
            break;
        case 'canceled':
            $eventStatus = 'Canceled';
            break;
        default:
            $eventStatus = 'Active';
    }
    $eventStatusMessage = process_db_input($_POST['event_statusmsg']);
    // event place
    $eventCountry = process_db_input($_POST['event_country']);
    $eventCity = process_db_input($_POST['event_city']);
    $eventPlace = process_db_input($_POST['event_place']);
    $pictureName = $_FILES['event_photo']['name'];
    $thumbName = getThumbNameByPictureName($pictureName);
    $scan = getimagesize($_FILES['event_photo']['tmp_name']);
    if ((1 == $scan[2] || 2 == $scan[2] || 3 == $scan[2] || 6 == $scan[2]) && move_uploaded_file($_FILES['event_photo']['tmp_name'], $dir['tmp'] . $pictureName)) {
        if (strlen($eventExistArr['PhotoFilename']) && file_exists($dir['sdatingImage'] . $eventExistArr['PhotoFilename'])) {
            unlink($dir['sdatingImage'] . $eventExistArr['PhotoFilename']);
        }
        $resizeWidth = (int) $_POST['event_photo_width'];
        $resizeHeight = (int) $_POST['event_photo_height'];
        // resize for thumbnail
        $res = imageResize($dir['tmp'] . $pictureName, $dir['sdatingImage'] . $thumbName, $sdatingThumbWidth, $sdatingThumbHeight);
        if ($res != IMAGE_ERROR_SUCCESS) {
            return SDATING_ERROR_PHOTO_PROCESS;
        }
        // if width and height specified then resize picture
        if ($resizeWidth && $resizeHeight) {
            $res = imageResize($dir['tmp'] . $pictureName, $dir['sdatingImage'] . $pictureName, $resizeWidth, $resizeHeight);
            if ($res != IMAGE_ERROR_SUCCESS) {
                return SDATING_ERROR_PHOTO_PROCESS;
            }
            unlink($dir['tmp'] . $pictureName);
        } else {
            $res = rename($dir['tmp'] . $pictureName, $dir['sdatingImage'] . $pictureName);
            if (!$res) {
                return SDATING_ERROR_PHOTO_PROCESS;
            }
        }
        chmod($dir['sdatingImage'] . $pictureName, 0644);
        $eventPhotoFilename = process_db_input($pictureName);
    } else {
        $eventPhotoFilename = $eventExistArr['PhotoFilename'];
    }
    // event date
    $eventStart = strtotime($_POST['event_start']);
    if ($eventStart == -1) {
        return SDATING_ERROR_WRONG_DATE_FORMAT;
    }
    $eventEnd = strtotime($_POST['event_end']);
    if ($eventEnd == -1) {
        return SDATING_ERROR_WRONG_DATE_FORMAT;
    }
    $eventSaleStart = strtotime($_POST['event_sale_start']);
    if ($eventSaleStart == -1) {
        return SDATING_ERROR_WRONG_DATE_FORMAT;
    }
    $eventSaleEnd = strtotime($_POST['event_sale_end']);
    if ($eventSaleEnd == -1) {
        return SDATING_ERROR_WRONG_DATE_FORMAT;
    }
    if ($eventEnd < $eventStart || $eventSaleEnd < $eventSaleStart || $eventStart < $eventSaleStart) {
        return SDATING_ERROR_WRONG_DATE_FORMAT;
    }
    // event responsible
    $eventRespName = process_db_input($_POST['event_resp_name']);
    $eventRespEmail = process_db_input($_POST['event_resp_email']);
    $eventRespPhone = process_db_input($_POST['event_resp_phone']);
    // event participants
    $eventSexFilter = '';
    if ($_POST['event_sex_female'] == 'on') {
        $eventSexFilter .= 'female';
    }
    if ($_POST['event_sex_male'] == 'on') {
        $eventSexFilter .= strlen($eventSexFilter) ? ',male' : 'male';
    }
    $eventAgeLowerFilter = (int) $_POST['event_age_start'];
    $eventAgeUpperFilter = (int) $_POST['event_age_end'];
    $eventMembershipFilter = '';
    foreach ($_POST['event_membership'] as $membershipID) {
        $eventMembershipFilter .= strlen($eventMembershipFilter) ? ",\\'{$membershipID}\\'" : "\\'{$membershipID}\\'";
    }
    $eventCountF = (int) $_POST['event_count_female'];
    $eventCountM = (int) $_POST['event_count_male'];
    // ticket prices
    if (isset($_POST['event_price_free']) && $_POST['event_price_free'] == 'on') {
        $eventPriceF = '0.00';
        $eventPriceM = '0.00';
        $eventPriceC = '0.00';
    } else {
        $eventPriceF = (double) $_POST['event_price_female'];
        $eventPriceM = (double) $_POST['event_price_male'];
    }
    // choose options
    $eventChoosePeriod = (int) $_POST['event_choose_period'];
    // allow to view participants
    $eventAllowView = $_POST['event_allow_view'] == 'on' ? '1' : '0';
    $res = db_res("UPDATE `SDatingEvents` SET\n\t\t\t\t\t`Title` = '{$eventTitle}',\n\t\t\t\t\t`Description` = '{$eventDesc}',\n\t\t\t\t\t`Status` = '{$eventStatus}',\n\t\t\t\t\t`StatusMessage` = '{$eventStatusMessage}',\n\t\t\t\t\t`Country` = '{$eventCountry}',\n\t\t\t\t\t`City` = '{$eventCity}',\n\t\t\t\t\t`Place` = '{$eventPlace}',\n\t\t\t\t\t`PhotoFilename` = '{$eventPhotoFilename}',\n\t\t\t\t\t`EventStart` = FROM_UNIXTIME( {$eventStart} ),\n\t\t\t\t\t`EventEnd` = FROM_UNIXTIME( {$eventEnd} ),\n\t\t\t\t\t`TicketSaleStart` = FROM_UNIXTIME( {$eventSaleStart} ),\n\t\t\t\t\t`TicketSaleEnd` = FROM_UNIXTIME( {$eventSaleEnd} ),\n\t\t\t\t\t`ResponsibleName` = '{$eventRespName}',\n\t\t\t\t\t`ResponsibleEmail` = '{$eventRespEmail}',\n\t\t\t\t\t`ResponsiblePhone` = '{$eventRespPhone}',\n\t\t\t\t\t`EventSexFilter` = '{$eventSexFilter}',\n\t\t\t\t\t`EventAgeLowerFilter` = {$eventAgeLowerFilter},\n\t\t\t\t\t`EventAgeUpperFilter` = {$eventAgeUpperFilter},\n\t\t\t\t\t`EventMembershipFilter` = '{$eventMembershipFilter}',\n\t\t\t\t\t`TicketCountFemale` = {$eventCountF},\n\t\t\t\t\t`TicketCountMale` = {$eventCountM},\n\t\t\t\t\t`TicketPriceFemale` = {$eventPriceF},\n\t\t\t\t\t`TicketPriceMale` = {$eventPriceM},\n\t\t\t\t\t`ChoosePeriod` = {$eventChoosePeriod},\n\t\t\t\t\t`AllowViewParticipants` = {$eventAllowView}\n\t\t\t\t\tWHERE `ID` = {$eventId}");
    if (!$res) {
        return SDATING_ERROR_QUERY_ERROR;
    }
    if (mysql_affected_rows() == 0) {
        return SDATING_ERROR_NOT_AFFECTED;
    }
    return SDATING_ERROR_SUCCESS;
}
    /**
     * page show filer form function
     * @return HTML presentation of data
     */
    function PageSDatingCalendar()
    {
        global $dir;
        global $site;
        global $sdatingThumbWidth;
        global $sdatingThumbHeight;
        global $aPreValues;
        global $oTemplConfig;
        $iPicSize = $this->iIconSize + 15;
        // collect information about current member
        $aMember['ID'] = (int) $_COOKIE['memberID'];
        $aMemberData = getProfileInfo($aMember['ID']);
        $sMemberSex = $aMemberData['Sex'];
        $aMembership = getMemberMembershipInfo($aMember['ID']);
        // now year, month and day
        list($iNowYear, $iNowMonth, $iNowDay) = explode('-', date('Y-m-d'));
        // current year, month, month name, day, days in month
        if (isset($_REQUEST['month'])) {
            list($iCurMonth, $iCurYear) = explode('-', $_REQUEST['month']);
            $iCurMonth = (int) $iCurMonth;
            $iCurYear = (int) $iCurYear;
        } else {
            list($iCurMonth, $iCurYear) = explode('-', date('n-Y'));
        }
        list($sCurMonthName, $iCurDaysInMonth) = explode('-', date('F-t', mktime(0, 0, 0, $iCurMonth, $iNowDay, $iCurYear)));
        // previous month year, month
        $iPrevYear = $iCurYear;
        $iPrevMonth = $iCurMonth - 1;
        if ($iPrevMonth <= 0) {
            $iPrevMonth = 12;
            $iPrevYear--;
        }
        // next month year, month
        $iNextYear = $iCurYear;
        $iNextMonth = $iCurMonth + 1;
        if ($iNextMonth > 12) {
            $iNextMonth = 1;
            $iNextYear++;
        }
        // days in previous month
        $iPrevDaysInMonth = (int) date('t', mktime(0, 0, 0, $iPrevMonth, $iNowDay, $iPrevYear));
        // days-of-week of first day in current month
        $iFirstDayDow = (int) date('w', mktime(0, 0, 0, $iCurMonth, 1, $iCurYear));
        // from which day of previous month calendar starts
        $iPrevShowFrom = $iPrevDaysInMonth - $iFirstDayDow + 1;
        // select events array
        $aCalendarEvents = array();
        $sCountryFilter = 'all';
        $sRCalendarCountry = isset($_REQUEST['calendar_country']) ? $_REQUEST['calendar_country'] : $aMemberData['Country'];
        $sRCalendarCountry = $sRCalendarCountry == '' ? 'all' : $sRCalendarCountry;
        if ($sRCalendarCountry == 'all') {
            $sCountryFilter = '';
        } else {
            $sCountryFilter = 'AND `Country` = \'' . process_db_input($sRCalendarCountry) . '\'';
        }
        //old WHERE data`s
        /*
        AND FIND_IN_SET('{$sMemberSex}', `EventSexFilter`)
        AND ( TO_DAYS('{$aMemberData['DateOfBirth']}')
        BETWEEN TO_DAYS(DATE_SUB(NOW(), INTERVAL `EventAgeUpperFilter` YEAR))
        AND TO_DAYS(DATE_SUB(NOW(), INTERVAL `EventAgeLowerFilter` YEAR)) )
        AND ( INSTR(`EventMembershipFilter`, '\'all\'') OR INSTR(`EventMembershipFilter`, '\'{$aMembership['ID']}\'') )
        */
        $sRequest = "SELECT `ID`, `Title`, `PhotoFilename`, DAYOFMONTH(`EventStart`) AS `EventDay`, MONTH(`EventStart`) AS `EventMonth` FROM `SDatingEvents`\r\n\t\t\t\t\t\t\tWHERE ( MONTH(`EventStart`) = {$iCurMonth} AND YEAR(`EventStart`) = {$iCurYear} OR\r\n\t\t\t\t\t\t\t\t\tMONTH( DATE_ADD(`EventStart`, INTERVAL 1 MONTH) ) = {$iCurMonth} AND YEAR( DATE_ADD(`EventStart`, INTERVAL 1 MONTH) ) = {$iCurYear} OR\r\n\t\t\t\t\t\t\t\t\tMONTH( DATE_SUB(`EventStart`, INTERVAL 1 MONTH) ) = {$iCurMonth} AND YEAR( DATE_SUB(`EventStart`, INTERVAL 1 MONTH) ) = {$iCurYear} )\r\n\t\t\t\t\t\t\t{$sCountryFilter}\r\n\t\t\t\t\t\t\tAND `Status` = 'Active'\r\n\t\t\t\t\t\t\t";
        $vEventsRes = db_res($sRequest);
        while ($aEventData = mysql_fetch_assoc($vEventsRes)) {
            $aCalendarEvents["{$aEventData['EventDay']}-{$aEventData['EventMonth']}"][$aEventData['ID']]['Title'] = $aEventData['Title'];
            $aCalendarEvents["{$aEventData['EventDay']}-{$aEventData['EventMonth']}"][$aEventData['ID']]['PhotoFilename'] = $aEventData['PhotoFilename'];
        }
        // make calendar grid
        $bPreviousMonth = $iFirstDayDow > 0 ? true : false;
        $bNextMonth = false;
        $iCurrentDay = $bPreviousMonth ? $iPrevShowFrom : 1;
        for ($i = 0; $i < 6; $i++) {
            for ($j = 0; $j < 7; $j++) {
                $aCalendarGrid[$i][$j]['day'] = $iCurrentDay;
                $aCalendarGrid[$i][$j]['month'] = $bPreviousMonth ? $iPrevMonth : ($bNextMonth ? $iNextMonth : $iCurMonth);
                $aCalendarGrid[$i][$j]['current'] = !$bPreviousMonth && !$bNextMonth;
                $aCalendarGrid[$i][$j]['today'] = $iNowYear == $iCurYear && $iNowMonth == $iCurMonth && $iNowDay == $iCurrentDay && !$bPreviousMonth && !$bNextMonth;
                // make day increment
                $iCurrentDay++;
                if ($bPreviousMonth && $iCurrentDay > $iPrevDaysInMonth) {
                    $bPreviousMonth = false;
                    $iCurrentDay = 1;
                }
                if (!$bPreviousMonth && !$bNextMonth && $iCurrentDay > $iCurDaysInMonth) {
                    $bNextMonth = true;
                    $iCurrentDay = 1;
                }
            }
        }
        $sShowEventsByCountryC = _t('_Show events by country');
        $sAllC = _t('_All');
        $sPrevC = _t('_Prev');
        $sNextC = _t('_Next');
        $sSundaySC = _t('_Sunday_short');
        $sMondaySC = _t('_Monday_short');
        $sTuesdaySC = _t('_Tuesday_short');
        $sWednesdaySC = _t('_Wednesday_short');
        $sThursdaySC = _t('_Thursday_short');
        $sFridaySC = _t('_Friday_short');
        $sSaturdaySC = _t('_Saturday_short');
        $sNoPhotoC = _t('_No photo');
        $sCalendarC = _t('_Calendar');
        $sCalendarOptions = '';
        $sCalSel = $sRCalendarCountry == 'all' ? 'selected="selected"' : '';
        $sCalendarOptions .= '<option value="all" ' . $sCalSel . " >{$sAllC}</option>";
        foreach ($aPreValues['Country'] as $key => $value) {
            $sCalKeySel = $sRCalendarCountry == "{$key}" ? 'selected="selected"' : '';
            $sCuontryVal = _t($value['LKey']);
            $sCalendarOptions .= "<option value=\"{$key}\" {$sCalKeySel} >{$sCuontryVal}</option>";
        }
        $sCalendarCountry = isset($_REQUEST['calendar_country']) ? '&amp;calendar_country=' . process_pass_data($_REQUEST['calendar_country']) : '';
        $sCalendarPrevHref = $_SERVER['PHP_SELF'] . "?action=calendar&amp;month={$iPrevMonth}-{$iPrevYear}" . $sCalendarCountry;
        $sCurMonYear = _t('_' . $sCurMonthName) . ', ' . $iCurYear;
        $sCalendarNextHref = $_SERVER['PHP_SELF'] . "?action=calendar&amp;month={$iNextMonth}-{$iNextYear}" . $sCalendarCountry;
        $sCalTableTrs = '';
        for ($i = 0; $i < 6; $i++) {
            $sCalTableTrs .= '<tr>';
            for ($j = 0; $j < 7; $j++) {
                if ($aCalendarGrid[$i][$j]['today']) {
                    $sCellClass = 'calendar_today';
                } elseif ($aCalendarGrid[$i][$j]['current']) {
                    $sCellClass = 'calendar_current';
                } else {
                    $sCellClass = 'calendar_non_current';
                }
                $sCalTableTrs .= <<<EOF
<td style="width:100px;height:100px;" class="{$sCellClass}">{$aCalendarGrid[$i][$j]['day']}
EOF;
                $vDayMonthValue = $aCalendarGrid[$i][$j]['day'] . '-' . $aCalendarGrid[$i][$j]['month'];
                if (isset($aCalendarEvents[$vDayMonthValue]) && is_array($aCalendarEvents[$vDayMonthValue])) {
                    foreach ($aCalendarEvents[$vDayMonthValue] as $eventID => $eventArr) {
                        $sEventThumbname = getThumbNameByPictureName($eventArr['PhotoFilename'], true);
                        $sGenUrl = $this->genUrl($eventID, '', 'entry', true);
                        if (strlen(trim($sEventThumbname)) && file_exists($dir['sdatingImage'] . $sEventThumbname)) {
                            $sCalTableTrs .= <<<EOF
<div>
<a href="{$sGenUrl}">
\t<img src="{$site['sdatingImage']}icon_{$eventArr['PhotoFilename']}" border="0" alt="{$eventArr['Title']}" title="{$eventArr['Title']}" style="margin: 2px;" />
</a>
</div>
EOF;
                        } else {
                            global $tmpl;
                            $sSpacerName = $this->sSpacerPath;
                            $sNaname = $site['url'] . 'templates/tmpl_' . $tmpl . '/' . $this->sPicNotAvail;
                            $sCalTableTrs .= <<<EOF
<!-- <div align="center" class="small" title="{$eventArr['Title']}" style="width: {$sdatingThumbWidth}px; height: {$sdatingThumbHeight}px; vertical-align: middle; line-height: {$sdatingThumbHeight}px; border: 1px solid silver; background-color: #FFFFFF; font-weight: normal; margin: 2px; font-size: 80%; cursor: pointer;"> -->
<div>
\t<a href="{$sGenUrl}">
\t\t<img src="{$sSpacerName}" style="width:64px;height:64px; background-image: url({$sNaname});" class="photo1" alt="" />
\t\t<!--<nobr>{$sNoPhotoC}</nobr>-->
\t</a>
</div>
EOF;
                        }
                    }
                }
                $sCalTableTrs .= '</td>';
            }
            $sCalTableTrs .= '</tr>';
        }
        $sRetHtml = <<<EOF
<br />
<div align="center" style="margin-bottom: 10px;">
\t<form id="calendarCountryForm" action="{$_SERVER['PHP_SELF']}" method="get" style="margin: 0px;">
\t\t<input type="hidden" name="action" value="calendar" />
\t\t<input type="hidden" name="month" value="{$iCurMonth}-{$iCurYear}" />
\t\t{$sShowEventsByCountryC}&nbsp;
\t\t<select class="no" name="calendar_country" onchange="javascript: document.forms['calendarCountryForm'].submit();" style="vertical-align: middle;">{$sCalendarOptions}</select>
\t</form>

\t<table cellpadding="1" cellspacing="1" border="0" width="100%" class="text" style="text-align:center;margin-top:10px;">
\t\t<tr>
\t\t\t<td class="calendar_current" style="padding: 3px;">
\t\t\t\t<a href="{$sCalendarPrevHref}">{$sPrevC}</a>
\t\t\t</td>
\t\t\t<td colspan="5" class="calendar_current">{$sCurMonYear}</td>
\t\t\t<td class="calendar_current" style="padding: 3px;">
\t\t\t\t<a href="{$sCalendarNextHref}">{$sNextC}</a>
\t\t\t</td>
\t\t</tr>
\t\t<tr>
\t\t\t<td style="width:{$iPicSize}px;" class="calendar_non_current">{$sSundaySC}</td>
\t\t\t<td style="width:{$iPicSize}px;" class="calendar_non_current">{$sMondaySC}</td>
\t\t\t<td style="width:{$iPicSize}px;" class="calendar_non_current">{$sTuesdaySC}</td>
\t\t\t<td style="width:{$iPicSize}px;" class="calendar_non_current">{$sWednesdaySC}</td>
\t\t\t<td style="width:{$iPicSize}px;" class="calendar_non_current">{$sThursdaySC}</td>
\t\t\t<td style="width:{$iPicSize}px;" class="calendar_non_current">{$sFridaySC}</td>
\t\t\t<td style="width:{$iPicSize}px;" class="calendar_non_current">{$sSaturdaySC}</td>
\t\t</tr>
\t{$sCalTableTrs}
\t</table>
</div>
<br />
EOF;
        return DesignBoxContent($sCalendarC, $sRetHtml, $oTemplConfig->PageSDatingCalendar_db_num);
    }