<?php
/* * ********************************************************************************************
 * 								Open Real Estate
 * 								----------------
 * 	version				:	V1.36.0
 * 	copyright			:	(c) 2016 Monoray
 * 							http://monoray.net
 * 							http://monoray.ru
 *
 * 	website				:	http://open-real-estate.info/en
 *
 * 	contact us			:	http://open-real-estate.info/en/contact-us
 *
 * 	license:			:	http://open-real-estate.info/en/license
 * 							http://open-real-estate.info/ru/license
 *
 * This file is part of Open Real Estate
 *
 * ********************************************************************************************* */

Yii::import('zii.widgets.jui.CJuiWidget');

class CarouselAdminWidget extends CJuiWidget
{

    public $images;
    public $model;
    public $afterRefresh = false;

    public function getViewPath($checkTheme = true)
    {
        if ($checkTheme && ($theme = Yii::app()->getTheme()) !== null) {
            if (is_dir($theme->getViewPath() . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . 'slider' . DIRECTORY_SEPARATOR . 'views'))
                return $theme->getViewPath() . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . 'slider' . DIRECTORY_SEPARATOR . 'views';
        }
        return Yii::getPathOfAlias('application.modules.slider.views.backend.carousel.widgets');
    }

    public function run()
    {
        if ($this->model) {
            $this->registerScript();
        }

        if (!$this->images) {
            return;
        }

        $this->render('carousel_admin_widget');
    }

    public function registerScript()
    {
        $cs = Yii::app()->getClientScript();
        $cs->registerCoreScript('jquery.ui');
        $cs->registerCoreScript('yiitab');
        CTabView::registerCssFile();

        $languages = (!isFree()) ? Lang::getActiveLangs(true) : null;
        $countLangs = count($languages);
        $successMsg = tc('Success');
        $errorMsg = tc("Error. Repeat attempt later");
        $saveDataUrl = Yii::app()->createUrl('/slider/backend/carousel/ajaxSave');

        $script = <<< JS
        var countLangs = $countLangs;

		function saveDataImage(id){
			var dataPost = $('#image_form_'+id+' :input').serialize();

			$.ajax({
				url : '$saveDataUrl',
				dataType : 'json',
				type: 'post',
				data: dataPost,
				success : function(data){
					if(data.status == 'ok'){
						closeDataImage(id);
						message('<?php echo  ?>');
						$('#image_html_'+id).html(data.html);
						if (countLangs > 1){
							$(".yiiTab").yiitab();
						}
						return;
					} else {
						error('$successMsg');
						$('#image_html_'+id).html(data.html);
						if (countLangs > 1){
							$(".yiiTab").yiitab();
						}
						return;
					}
				},
				error: function(data){
					error('$errorMsg');
				}
			});
		}

		function closeDataImage(id) {
			$("#image_dialog_"+id).dialog("close");
		}

		function openDataImage(id) {
			$("#image_dialog_"+id).dialog("open");
		}
JS;

        Yii::app()->clientScript->registerScript('carousel_data_js', $script, CClientScript::POS_END);

        $countGuestAdImages = 0;
        $maxPhotos = Carousel::getMaxPhotos();

        Yii::app()->clientScript->registerScript('images-reloader-guest-ad', '
	jQuery(function ($) {
		if (parseInt("' . $countGuestAdImages . '") >= parseInt("' . $maxPhotos . '")) {
			$("#uploadFile").hide();
			$("#more-uploads-photos").show();
		}

		$(".images-carousel-area").on("click", "a.deleteImageLink", function(){
			var id = $(this).attr("link-id");
			var linkName = $(this).attr("link-name");
			$.ajax({
				url: "' . Yii::app()->controller->createUrl('/slider/backend/carousel/deleteImage') . '",
				data: {"id" : id, "' . Yii::app()->request->csrfTokenName . '" : "' . Yii::app()->request->csrfToken . '", "linkName" : linkName},
				success: function(result){
					$("#image_"+id).remove();

					if ($(".image-item-carousel").length <= parseInt("' . $maxPhotos . '")) {
						$("#uploadFile").show();
						$("#more-uploads-photos").hide();
					}
					else {
						$("#uploadFile").hide();
						$("#more-uploads-photos").show();
					}
				},
				error: function(err){
					error("' . tc("Error loading. Try again later.") . '");
				}
			});
			return false;
		});
	});

	function reloadImagesArea(){
		$.ajax({
			type: "POST",
			url: "' . Yii::app()->controller->createUrl('/slider/backend/carousel/getImages', array('id' => $this->model->id)) . '",
			data: {"' . Yii::app()->request->csrfTokenName . '" : "' . Yii::app()->request->csrfToken . '"},
			success: function(data){
				var alrclear;
				alrclear = 0;

				$(".image-item-carousel", data).each(function(){
					var name;
					name = $(this).attr("name");

					var toAdd = $(this).closest(".image-item-carousel");
					if($(".images-area > .clear").length){
						if (alrclear == 0) {
							$(".images-area").empty();
							$(".images-area").append("<div class=\"clear\"></div>");
							alrclear = 1;
						}
						$(".images-area > .clear").before(toAdd);
					} else {
						$(".images-carousel-area").empty();
						$(".images-carousel-area").append("<div class=\"images-area\"></div>");
						$(".images-area").append(toAdd);
						$(".images-area").append("<div class=\"clear\"></div>");
					}
				});

				if ($(".image-link-item").length >= parseInt("' . $maxPhotos . '")) {
					$("#uploadFile").hide();
					$("#more-uploads-photos").show();
				}
				else {
					$("#uploadFile").show();
					$("#more-uploads-photos").hide();
				}
			},
			error: function(err){
				error("' . tc("Error loading. Try again later.") . '");
			}
		});
	}
	', CClientScript::POS_END);

        $add = '';
        if (Yii::app()->request->enableCsrfValidation) {
            $add = 'serial = serial + "&' . Yii::app()->request->csrfTokenName . '=' . Yii::app()->request->csrfToken . '";';
        }

        Yii::app()->clientScript->registerScript('sortable', '
		$(".images-area").sortable({
			forcePlaceholderSize: true,
			forceHelperSize: true,
			items: ".image-item-carousel",
			handle: ".image-drag-area",
			placeholder: "ui-sortable-placeholder",
			update : function () {
				serial = $(".images-area").sortable("serialize", {key: "image[]", attribute: "id"});
				' . $add . '
				$.ajax({
					"url": "' . Yii::app()->controller->createUrl('/slider/backend/carousel/sort', array('id' => $this->model->id)) . '",
					"type": "POST",
					"data": serial,
					"success": function(data){

					},
				});
			}
		}).find(".image-item-drag").disableSelection();
		$(".image-item-drag").disableSelection();
	');
    }
}
