Вроде заработало так, как надо

This commit is contained in:
Krivchikov Dmitry 2014-08-03 20:49:26 +04:00
parent f653347ba8
commit 1dc15df6eb
17 changed files with 386 additions and 183 deletions

20
.gitignore vendored
View File

@ -1 +1,21 @@
ground/config.php
public/photos/*.jpg
public/photos/*.jpeg
public/photos/*.png
public/photos/*.gif
public/photos/small/*.jpg
public/photos/small/*.jpeg
public/photos/small/*.png
public/photos/small/*.gif
public/photos/middle/*.jpg
public/photos/middle/*.jpeg
public/photos/middle/*.png
public/photos/middle/*.gif
public/photos/big/*.jpg
public/photos/big/*.jpeg
public/photos/big/*.png
public/photos/big/*.gif

View File

@ -30,7 +30,8 @@ class App
private static $config = array();
private static $urlParams = array();
private static $DB = null;
public static $user = null;
public static $user = null;
public static $request = array();
/**
* Разбивает урл на контроллер, метод и выбирает параметры.
@ -70,6 +71,8 @@ class App
$controller = self::$controller;
$action = self::$action;
self::fillRequest();
if (method_exists($controller, $action))
{
$controller::$action();
@ -139,6 +142,7 @@ class App
public static function redirect($url, $httpCode = 307)
{
header('Location: ' . $url, true, $httpCode);
die;
}
/**
@ -194,4 +198,13 @@ class App
return self::$urlParams;
}
private static function fillRequest()
{
self::$request = array(
'method' => isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : '',
'ajax' => isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest',
'refferer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
);
}
}

View File

@ -28,26 +28,27 @@ class Image
}
/**
* Ресайзит изображение. На входе запрос вида sizeX_sizeY_imgName.ext
* @param type $name
* Создаёт все требуемые размеры изображения и раскладывает их по папкам.
* @param type $imgName
*/
public static function resize($imgName, $sizeX, $sizeY = false, $quality = 85)
public static function createAllSizes($imgName)
{
$dir = 'photos/';
$newDir = 'photos/resize/';
$sizes = App::getConfig('images');
$pathInfo = pathinfo($_SERVER['SCRIPT_FILENAME']);
$uploaddir = $pathInfo['dirname'] . '/photos/';
$sizeY = $sizeY ? $sizeY : $sizeX;
$oldImgName = $dir . $imgName;
$newImgName = $newDir . $sizeX . '_' . $sizeY . '_' . $imgName;
if (file_exists($newImgName) || self::imgResize($oldImgName, $newImgName, $sizeX, $sizeY, $quality))
foreach ($sizes as $dir => $size)
{
return '/' . $newImgName;
self::imgResize(
$uploaddir . $imgName, // Source - original image
$uploaddir . $dir . '/' . $imgName, // Destination
$size[0], // X
$size[1], // Y
$size[2] // Quelity
);
}
return '/' . $oldImgName;
return TRUE; // o_O
}
/**

View File

@ -3,34 +3,35 @@
class JsonController extends Controller
{
/**
* Точки
*/
static function actionPoints()
{
$points = Point::model()->getAll();
$categories = Category::model()->getAll(array('asArray'=>true));
/**
* Точки
*/
static function actionPoints()
{
$points = Point::model()->getAll();
$categories = Category::model()->getAll(array('asArray' => true));
$result = array();
foreach ($points as $point) {
foreach ($points as $point)
{
$id = $point->id;
$result[$id]['id'] = $point->id;
$result[$id]['name'] = $point->name;
$result[$id]['lat'] = $point->lat;
$result[$id]['lng'] = $point->lng;
$result[$id]['categoryId'] = $point->categoryId;
$result[$id]['categoryIcon'] = $categories[$point->categoryId]['icon'];
}
$result[$id]['categoryId'] = $point->categoryId;
$result[$id]['categoryIcon'] = $categories[$point->categoryId]['icon'];
}
self::renderPartial('json.php', array(
self::renderPartial('json.php', array(
'data' => $result,
));
}
}
/**
* Точка
*/
/**
* Точка
*/
static function actionPoint()
{
$id = (int) App::getParam('id');
@ -38,13 +39,31 @@ class JsonController extends Controller
{
$point = Point::model()->getByPK($id);
$point->descriptionHtml = nl2br($point->description);
$point->descriptionHtml = nl2br($point->description);
$point->name = htmlspecialchars($point->name);
$imgs = $point->photos;
$categories = Category::model()->getAll(array('asArray'=>true));
if ($point->img == '' && !empty($imgs))
{
$img = array_shift($imgs);
$point->img = '/photos/small/' . $img->name;
}
$point->categoryIcon = $categories[$point->categoryId]['icon'];
$point->categoryName = $categories[$point->categoryId]['name'];
$imgs = $point->photos;
if (!empty($imgs))
{
$tmp = array();
foreach ($imgs as $img)
{
$tmp[] = $img->name;
}
$point->images = $tmp;
}
$categories = Category::model()->getAll(array('asArray' => true));
$point->categoryIcon = $categories[$point->categoryId]['icon'];
$point->categoryName = $categories[$point->categoryId]['name'];
self::renderPartial('json.php', $point->getValues());
} else
@ -53,114 +72,167 @@ class JsonController extends Controller
}
}
/**
* Категории
*/
static function actionCategories()
{
$categories = Category::model()->getAll(array('asArray'=>true));
/**
* Категории
*/
static function actionCategories()
{
$categories = Category::model()->getAll(array('asArray' => true));
self::renderPartial('json.php', array(
self::renderPartial('json.php', array(
'data' => $categories,
));
}
/**
* Добавление точки
*/
static function actionAddPoint()
{
$photos = array();
$temp = pathinfo($_SERVER['SCRIPT_FILENAME']);
$uploaddir = $temp['dirname'] . '/photos/';
// print_r($_FILES);
// print_r($_REQUEST);
// die;
if (isset($_FILES) && !empty($_FILES))
{
foreach ($_FILES['photos']['name'] as $key => $fileName)
{
$temp = pathinfo($_FILES['photos']['name'][$key]);
$foto = strtolower('_' . substr(md5($fileName . time()), 0, 5) . '.' . $temp['extension']);
if (move_uploaded_file($_FILES['photos']['tmp_name'][$key], $uploaddir . $foto))
{
$photos[] = $foto;
}
}
}
print_r($photos);
die;
}
/**
* Добавление точки
*/
static function actionAddPoint()
{
$errors = array();
if(!( isset($_POST['name']) && $_POST['name'] && strlen($_POST['name']) > 1 )) $errors[1]='Неверное название точки';
if(!( isset($_POST['img']) && $_POST['img'] && strlen($_POST['img']) > 13 )) $errors[2]='Плохая ссылка на изображение';
if(!( isset($_POST['description']) && $_POST['description'] && strlen($_POST['description']) > 25 )) $errors[3]='Слишком короткое описание';
if(!( isset($_POST['categoryId']) && $_POST['categoryId'] )) $errors[4]='Не задана категория точки';
if(!( isset($_POST['source']) )) $errors[5]='Не передано поле источкика информации. Допускается пустое значение.';
if(!( isset($_POST['lat']) && $_POST['lat'] )) $errors[6]='Ошибочное значение широты';
if(!( isset($_POST['lng']) && $_POST['lng'] )) $errors[7]='Ошибочное значение долготы';
if(!App::$user ) $errors[8]='Вы не авторизованы! Пожалуйста, войдите.';
if(isset($_POST['id']) && $_POST['id'] && App::$user->isAdmin == 0 ) $errors[9]='Редактирование точек достурно только администратору!';
if (!App::$user)
$errors[8] = 'Вы не авторизованы! Пожалуйста, войдите.';
if (isset($_POST['id']) && $_POST['id'] && App::$user->isAdmin == 0)
$errors[9] = 'Редактирование точек достурно только администратору!';
if (empty($errors))
{
$point = new Point();
$photos = $images = array();
$ordering = $_POST['ordering'];
if (empty($errors) && !App::$request['ajax'] && isset($_POST['id']) && (int) $_POST['id'])
{
$id = (int) $_POST['id'];
$pathInfo = pathinfo($_SERVER['SCRIPT_FILENAME']);
$uploaddir = $pathInfo['dirname'] . '/photos/';
if (isset($_FILES) && !empty($_FILES))
{
foreach ($_FILES['photos']['name'] as $key => $fileName)
{
$temp = pathinfo($_FILES['photos']['name'][$key]);
$extension = strtolower($temp['extension']) ? strtolower($temp['extension']) : 'jpg';
$photo = $id . strtolower('_' . substr(md5($fileName . time()), 0, 5) . '.' . $extension);
if (move_uploaded_file($_FILES['photos']['tmp_name'][$key], $uploaddir . $photo))
{
$photos[] = $photo;
}
}
}
if (isset($_POST['imgs']) && !empty($_POST['imgs']))
{
foreach ($_POST['imgs'] as $key => $img)
{
if (mb_strpos($img, '://') !== false)
{
$temp = pathinfo($img);
$extension = strtolower($temp['extension']) ? strtolower($temp['extension']) : 'jpg';
$photo = $id . strtolower('_' . substr(md5($img . time()), 0, 5) . '.' . $extension);
if (file_put_contents($uploaddir . $photo, file_get_contents($img)))
{
$images[] = $photo;
}
} else
{
$images[] = $img;
}
}
}
$resPhotos = array();
foreach ($ordering as $order)
{
$resPhotos[] = $order == 'FILE' ? array_shift($photos) : array_shift($images);
}
if (!empty($resPhotos))
{
App::DB()->query('DELETE FROM `poi`.`photos` WHERE `pointId` = ' . $id . ';');
$P = new Photo();
foreach ($resPhotos as $key => $photo)
{
$P->add(array(
'pointId' => $id,
'name' => $photo,
'ord' => $key,
));
Image::createAllSizes($photo);
}
}
App::redirect('/?point=' . $id);
}
if (!( isset($_POST['name']) && $_POST['name'] && strlen($_POST['name']) > 1 ))
$errors[1] = 'Неверное название точки';
if (!( isset($_POST['img']) && (int) $_POST['img']))
$errors[2] = 'Плохая ссылка на изображение';
if (!( isset($_POST['description']) && $_POST['description'] && strlen($_POST['description']) > 25 ))
$errors[3] = 'Слишком короткое описание';
if (!( isset($_POST['categoryId']) && $_POST['categoryId'] ))
$errors[4] = 'Не задана категория точки';
if (!( isset($_POST['source']) ))
$errors[5] = 'Не передано поле источкика информации. Допускается пустое значение.';
if (!( isset($_POST['lat']) && $_POST['lat'] ))
$errors[6] = 'Ошибочное значение широты';
if (!( isset($_POST['lng']) && $_POST['lng'] ))
$errors[7] = 'Ошибочное значение долготы';
if (!empty($errors))
{
header("HTTP/1.0 400 Bad Request");
header('Content-Type: application/json');
print json_encode($errors);
return false;
}
if (App::$request['ajax'])
{
$point = new Point();
unset($_POST['img']);
// Редактирование существующей точки
if (isset($_POST['id']) && $_POST['id'])
{
$id = $_POST['id'];
// Редактирование существующей точки
$id = (int) $_POST['id'];
$point = $point->getByPK($id);
$point->setValues($_POST);
$point->save();
} else
{
$_POST['author'] = App::$user->id;
$_POST['date'] = time();
$point->add($_POST);
self::renderPartial('json.php', array(
'data' => $point->id
));
if (!$point->id)
{
header("HTTP/1.0 500 Internal Server Error");
die('Error 500 - Internal Server Error');
}
die;
if (!App::getConfig('disableSMS'))
{
$ch = curl_init("http://sms.ru/sms/send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"api_id" => "2c2af6a7-a935-0e84-5952-599f5cd61905",
"to" => "79046106141, 79046106144",
"text" => "#" . $point->id . ": " . $point->name,
));
curl_exec($ch);
curl_close($ch);
}
}
$_POST['author'] = App::$user->id;
$_POST['date'] = time();
$point->add($_POST);
if ( $point->id )
{
self::renderPartial('json.php', array(
'data' => $point->id
));
$ch = curl_init("http://sms.ru/sms/send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"api_id" => "2c2af6a7-a935-0e84-5952-599f5cd61905",
"to" => "79046106141, 79046106144",
"text" => "#".$point->id.": ".$point->name,
));
curl_exec($ch);
curl_close($ch);
}
else
{
header("HTTP/1.0 500 Internal Server Error");
die('Error 500 - Internal Server Error');
}
}
else
{
header("HTTP/1.0 400 Bad Request");
header('Content-Type: application/json');
print json_encode($errors);
}
}
self::renderPartial('json.php', array(
'data' => $point->id
));
}
}
static function actionSaveRoute()
{
@ -183,7 +255,7 @@ class JsonController extends Controller
if ($id)
{
$route = new Route();
$route = $route->getByPK($id);
$route = $route->getByPK($id);
self::renderPartial('json.php', $route->points);
} else
{
@ -197,7 +269,7 @@ class JsonController extends Controller
if ($id && App::$user)
{
$route = new Route();
$route = $route->getByPK($id);
$route = $route->getByPK($id);
if ($route->author == App::$user->id)
{
@ -215,11 +287,11 @@ class JsonController extends Controller
{
$address = isset($_GET['search']) ? $_GET['search'] : '';
$res = @file_get_contents('http://geocode-maps.yandex.ru/1.x/?format=json&geocode='.urlencode($address));
$res = @file_get_contents('http://geocode-maps.yandex.ru/1.x/?format=json&geocode=' . urlencode($address));
$res = json_decode($res, true);
if (isset ($res['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos']))
$point = explode (' ', $res['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos']);
if (isset($res['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos']))
$point = explode(' ', $res['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos']);
else
$point = array(0, 0);
@ -229,4 +301,5 @@ class JsonController extends Controller
self::renderPartial('json.php', $coords);
}
}

View File

@ -65,14 +65,14 @@ class PageController extends Controller
$categories = new Category();
$categories = $categories->getAll();
$point->categoryIcon = $categories[$point->categoryId]['icon'];
$point->categoryName = $categories[$point->categoryId]['name'];
$point->categoryIcon = $categories[$point->categoryId]->icon;
$point->categoryName = $categories[$point->categoryId]->name;
self::render('point.php', array(
'point' => $point,
'categories' => $categories,
)
);
'photos' => $point->photos,
));
} else
{
App::error404();

17
ground/models/Photo.php Normal file
View File

@ -0,0 +1,17 @@
<?php
class Photo extends Model
{
function __construct($fromArray = array())
{
$this->_tableName_ = 'photos';
parent::__construct($fromArray);
$this->setRelation('point', 'pointId', 'Point', 'id', self::TO_ONE);
}
static function model()
{
return new self();
}
}

View File

@ -8,6 +8,7 @@ class Point extends Model
parent::__construct($fromArray);
$this->setRelation('category', 'categoryId', 'Category', 'id', self::TO_ONE);
$this->setRelation('authorUser', 'author', 'User', 'id', self::TO_ONE);
$this->setRelation('photos', 'id', 'Photo', 'pointId', self::TO_MANY);
}
static function model()

View File

@ -20,15 +20,12 @@
</div>
<div class="form-group extraImage asLink">
<label class="control-label" for="img">Файлы и ссылки (URL) на изображения</label>
<label class="control-label error" for="img">(Что-то не так с сылкой на изображение)</label>
<div class="input-group">
<div class="input-group-addon type ico" title="Укажите ссылку на изображение"><span class="glyphicon glyphicon-link"></span></div>
<input type="text" id="" name="imgs[]" class="form-control" placeholder="http://" />
<div class="input-group-addon type button" onclick="switchType($(this))" title="Загрузить файл"><span class="glyphicon glyphicon-transfer"></span></div>
<div class="input-group-addon add button" onclick="addNewImage()" title="Добавить ещё одно изображение"><span class="glyphicon glyphicon-plus"></span></div>
</div>
<label class="control-label" for="imgs">Файлы и ссылки на изображения</label>
<label class="control-label error" for="imgs">(Что-то не так с изображениями!)</label>
<span class="btn btn-sm add button" onclick="addNewImage()" title="Добавить ещё одно изображение"><span class="glyphicon glyphicon-plus"></span></span>
</div>
<div id="imgsContainer">
</div>
<div class="form-group">
<label class="control-label" for="categoryId">Тип</label>
@ -46,23 +43,22 @@
<div class="form-group">
Координаты:
<input type="text" id="addPointLat" name="lat" class="form-control input-sm" style="width: 145px; display: inline-block;" readonly="readonly" disabled="disabled"/>
<input type="text" id="addPointLng" name="lng" class="form-control input-sm" style="width: 145px; display: inline-block;" readonly="readonly" disabled="disabled"/>
<input type="text" id="addPointLat" name="lat" class="form-control input-sm" style="width: 145px; display: inline-block;" readonly="readonly" />
<input type="text" id="addPointLng" name="lng" class="form-control input-sm" style="width: 145px; display: inline-block;" readonly="readonly" />
<button type="button" class="btn btn-sm btn-default" onclick="editSetNewCoords();"><span class="glyphicon glyphicon-screenshot"></span> изменить координаты</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-primary" onclick="$('#addPointForm').submit();">Сохранить</button>
<button type="button" class="btn btn-primary" onclick="addPoint();">Сохранить</button>
</div>
<div id="newIm">
<div class="form-group extraImage asLink" style="display: none;">
<label class="control-label error" for="img">(Что-то не так с сылкой на изображение)</label>
<div class="input-group">
<div class="input-group-addon type ico" title="Укажите ссылку на изображение"><span class="glyphicon glyphicon-link"></span></div>
<input type="text" name="imgs[]" class="form-control" />
<div class="input-group-addon type ico" title="Укажите ссылку на изображение"><input type="hidden" class="ordering" name="ordering[]" value="LINK" /><span class="glyphicon glyphicon-link"></span></div>
<input type="text" name="imgs[]" class="form-control images" placeholder="http://" />
<div class="input-group-addon type button" onclick="switchType($(this))" title="Изменить поле на загрузку файла"><span class="glyphicon glyphicon-transfer"></span></div>
<div class="input-group-addon remove button" onclick="removeInput($(this))" title="Удалить это поле"><span class="glyphicon glyphicon-trash"></span></div>
</div>
@ -72,15 +68,23 @@
</div>
</div>
<script>
function addNewImage()
function addNewImage(link)
{
if ($('.extraImage', '#addPointForm').length < 10)
$('.extraImage', '#newIm').clone().insertAfter($('.extraImage', '#addPointForm').last()).show(200);
{
$('.extraImage', '#newIm').clone().appendTo('#imgsContainer').show(200);
if (link != undefined)
{
$('.form-control.images', '#addPointForm').last().attr('readonly', 'readonly').val(link);
$('.input-group-addon.type.button', '#addPointForm').remove();
}
}
}
function removeInput(el)
{
$(el).parent().parent().hide(300, function(){$(el).remove()});
container = $(el).parent().parent();
container.hide(300, function(){container.remove()});
}
function switchType(el)
@ -88,6 +92,7 @@
container = $(el).parent().parent();
if (container.hasClass('asLink'))
{
$('.ordering', container).val('FILE');
$('.ico span', container).removeClass('glyphicon-link').addClass('glyphicon-paperclip');
$('.form-control', container).attr('type', 'file').attr('name', 'photos[]');
container.removeClass('asLink');
@ -96,6 +101,7 @@
}
else
{
$('.ordering', container).val('LINK');
$('.ico span', container).removeClass('glyphicon-paperclip').addClass('glyphicon-link');
$('.form-control', container).attr('type', 'text').attr('name', 'imgs[]');
container.addClass('asLink');

View File

@ -18,6 +18,16 @@
<?= $point->descriptionHtml ?>
<br/>
<div style="text-align: center">
<?php if ($point->img): ?>
<div style="text-align: center">
<img src="<?= $point->img ?>" style="max-width: 800px;">
</div>
</div>
<?php endif; ?>
<?php if ($photos): ?>
<div style="text-align: center">
<?php foreach ($photos as $photo): ?>
<img src="/photos/<?= $photo->name ?>" style="max-width: 800px;">
<?php endforeach; ?>
</div>
<?php endif; ?>

51
public/apitest.php Normal file

File diff suppressed because one or more lines are too long

View File

@ -20,10 +20,11 @@ div.header a:hover {text-decoration: none;}
div.header a:hover h1 {cursor: pointer;}
div.add {cursor: pointer;}
#addPointModal .extraImage .button {cursor: pointer;}
#addPointModal .extraImage .remove:hover {background-color: #d44950; color: #fff;}
#addPointModal .extraImage .add:hover {background-color: #49d450; color: #fff;}
#addPointModal .extraImage .button {cursor: pointer; background-color: #eeeeee;}
#addPointModal .extraImage .remove:hover {background-color: #f4bfbf;}
#addPointModal .extraImage .add:hover {background-color: #bff4c8;}
#addPointModal .extraImage .type.button:hover {background-color: #ddd;}
#addPointModal .extraImage .input-group-addon.type.button {border-left: 0px;}
.form-group .error {display: none;}
.form-group.has-error .error {display: inline-block;}

View File

@ -1,22 +0,0 @@
### Основные точки ###
* Парки, заповедники и сады (forest)
* Усадьбы и замки (castle)
* Памятники и монументы (statue)
* Церкви и монастыри (cathedral)
* Архитектурные ансамбли (arch)
* Видовые площадки (photo)
* Реки, озёра и пляжи (lake)
* Водопады (waterfall)
* Пещеры (spelunking)
* Горы (mountaint)
* Сталкеры (radiation)
* Места для пикника и привала (picnic)
* Прочие интересные точки (other)
* Музеи (museum)
### Вспомогательные точки ###
* Место старта (man)
* Конечная точка (home)
* Информация (information)
Основной цвет: #22bb22

View File

@ -57,7 +57,7 @@ function init(lat, lng) {
if (status == statusHunting)
{
$('#addPointId').remove();
$('#addPointForm input').val('');
$('#addPointForm input:text').val('');
$("#addPointCategoryId option" ).attr('selected', null);
$('#addPointLat').val(e.latlng.lat);
$('#addPointLng').val(e.latlng.lng);
@ -82,6 +82,7 @@ function init(lat, lng) {
$("#wayPoints").sortable();
$("#wayPoints").disableSelection();
$("#imgsContainer").sortable();
myMap.on('moveend', function(e) {
if (!myMap._popup && $('#boxRoute').css('display') == 'none')
@ -188,11 +189,11 @@ function showInfo(id)
}
description = description + data.descriptionHtml;
description = description + ' <a href="/page/point/id/' + id + '" target="blank">Подробнее...</a>';
if (data.source.length > 11)
{
//description = description + ' <a href="/page/point/id/' + id + '" target="blank">Подробнее...</a>';
description = description + ' <a href="' + data.source + '" target="blank">Подробнее...</a>';
//description = description + ' <a href="' + data.source + '" target="blank">Подробнее...</a>';
}
description = description + '</div><div class="clear"></div>';
@ -294,6 +295,8 @@ function activateAddPoint()
$('#addPointButton').toggleClass('active');
if ($('#addPointButton').hasClass('active'))
{
$('.extraImage','#imgsContainer').remove();
addNewImage();
$('#map').css('cursor', 'crosshair');
setStatus(statusHunting)
}
@ -317,12 +320,21 @@ function addPoint()
{
setStatus(statusSendingToServer)
id = $('#addPointId').length ? $('#addPointId').val() : 0;
hasImages = false;
$("input[name='imgs[]']", '#addPointForm').each(function(){
if ( $(this).val().length > 10)
hasImages = true;
});
$("input[name='photos[]']", '#addPointForm').each(function(){
if ( $(this).val().length > 5)
hasImages = true;
})
$.ajax({
type: "POST",
url: "/json/addpoint/",
data: {
name: $('#addPointName').val(),
img: $('#addPointImg').val(),
img: hasImages ? 1 : 0,
description: $('#addPointDescription').val(),
categoryId: $('#addPointCategoryId').val(),
source: $('#addPointSource').val(),
@ -331,6 +343,12 @@ function addPoint()
id: id
},
success: function(data) {
if ($("input[name='photos[]']").length > 0 || $("input[name='imgs[]']").length > 0)
{
$('<input type="hidden" id="addPointId" name="id"/>').appendTo('#addPointForm').val(data);
$('#addPointForm').submit();
}
text = id ? 'Точка успешно отредактирована!' : 'Точка успешно добавлена!';
if ( id )
{
@ -380,7 +398,9 @@ function addPoint()
$('#addPointName').parent().addClass('has-error');
else
if (k == 2)
$('#addPointImg').parent().addClass('has-error');
{
$('.extraImage', '#addPointForm').addClass('has-error');
}
else
if (k == 3)
$('#addPointDescription').parent().addClass('has-error');
@ -413,7 +433,6 @@ function editPoint(id)
$('#addPointId').remove();
$('<input type="hidden" id="addPointId" name="id"/>').appendTo('#addPointForm').val(id);
$('#addPointName').val(pointsSources[id].name);
$('#addPointImg').val(pointsSources[id].img);
$('#addPointDescription').val(pointsSources[id].description);
$("#addPointCategoryId option" ).attr('selected', null);
$("#addPointCategoryId option[value='"+pointsSources[id].categoryId+"']" ).attr('selected', 'selected');
@ -421,6 +440,19 @@ function editPoint(id)
$('#addPointLat').val(pointsSources[id].lat);
$('#addPointLng').val(pointsSources[id].lng);
$('.extraImage','#imgsContainer').remove();
if (pointsSources[id].images != undefined && pointsSources[id].images.length > 0)
{
for(var i=0; i < pointsSources[id].images.length; i++)
{
addNewImage(pointsSources[id].images[i]);
}
}
else
{
addNewImage(pointsSources[id].img);
}
closePopup();
$('#addPointModal').modal('show');
setStatus(statusEdit);

0
public/photos/.gitkeep Normal file
View File

View File

View File

View File