<?php
require_once APPLICATION_PATH . '/modules/alw/views/helpers/Loadingimage.php';

$loadimage = new Alw_View_Helper_Loadingimage();
$photoImagePath = (APPLICATION_ENV != 'development') ? $loadimage->getCdnAlwImagePath('Photo.svg') : '/images/icons/Photo.svg';
$downloadSvgImagePath = (APPLICATION_ENV != 'development') ? $loadimage->getCdnAlwImagePath('Download.svg') : '/images/icons/Download.svg';
$editSvgImagePath = (APPLICATION_ENV != 'development') ? $loadimage->getCdnAlwImagePath('Edit.svg') : '/images/icons/Edit.svg';

?>

<script type="text/javascript" src="/scripts/uploads/fileuploader.js"></script>
<script type="text/javascript" src="/scripts/jquery.tool.scrollable.js"></script>
<!-- Start Content-->
<div id="content" class="content-div photo-tab">
    <div id="bread">
        <a href="/artist"><?=$this->translate('All Artists')?></a>
    </div>
    <h1>
        <span><?=$this->artistImages($this->artist->artist_id, $this->artist->name);?></span> <?=(isset($this->artist) ? $this->artist->name : 'Create Artist')?>
    </h1>
    <!-- Start Artist Builder Wrap-->
    <div id="artistBuilderWrap">
        <!-- Start Left Content-->
        <div id="contentLeftsm">
            <!-- Start Artist Profile-->
            <?=$this->artistBuilderNavigation('photos', 'navigateAway', $this->performanceArtistIndexEnabled);?>
            <!-- End Artist Profile-->
        </div>
        <!-- End Left Content-->
        <div id="contentRightlg">
            <div id="artistFormWrap">
                <!-- Start Photos-->
                <div class="photo-tab-inner">
                    <h2><?=$this->translate('Photos')?></h2>
                    <?php if (!count($this->artistPhotos)) { ?>
                        <div class="noNewReleases photos" id="noArtistPhotos">
                    <?php } else { ?>
                        <div class="noNewReleases photos">
                    <?php }
                    try {
                    if (!count($this->artistPhotos)) { ?>
                        <img src="<? echo $photoImagePath ?>" />
                        <p class="textBold no-data-title"><?=$this->translate('You currently have no photos.')?></p>
                        <div class="addButton">
                            <span id="image-uploader"></span>
                            <div id="image-uploader-wait-button" class="qq-uploader" style="display:none;">
                                <div class="qq-upload-button">
                                    <button class="btn btn-primary add-photo-btn"><?=$this->translate('Please Wait')?>...</button>
                                </div>
                            </div>
                            <table>
                                <tr>
                                    <td><span id="image-uploader-error"></span></td>
                                </tr>
                            </table>
                        </div>
                        <br/><br/>
                    <?php } else { ?>
                        <div class="addButton photo-added">
                            <span id="image-uploader"></span>
                            <div id="image-uploader-wait-button" class="qq-uploader" style="display:none;">
                                <div class="qq-upload-button">
                                    <button class="btn btn-primary add-photo-btn"><?=$this->translate('Please Wait')?>...</button>
                                </div>
                            </div>
                            <table>
                                <tr>
                                    <td><span id="image-uploader-error"></span></td>
                                </tr>
                            </table>
                        </div>
                        <div class="clear"></div>
                        <?php
                    } ?>
                    </div>
                </div>
                    <!-- Photo loop-->
                    <?php
                    $data = array();
                    $count = 0;
                    $j = 0;
                    $handPointerClass = 'handPointer';
                    $artistThumbImageUrl = '';
                    $artistPhotosImageUrl = '';
                    foreach ($this->artistPhotos as $key => $record) {
                        $data[$j][] = $record;
                        $count++;
                        if ($count == $this->images_per_row) {
                            $count = 0;
                            $j++;
                        }
                    }
                    foreach ($data as $artistInfo) {
                        foreach ($artistInfo as $artistPhoto) {
                            $thumbnail_image_asset_id = $artistPhoto->ArtistThumbnails->image_asset_id;
                            $raw_image_detail = Model_ImageAssets::getImageAssetsByID($artistPhoto->image_asset_id);
                            /** get image from service  */
                            if (!empty($artistPhoto->artist_photo_id)) {
                                $artistThumbImageUrl = $this->owsAssetsServiceClient->getImageAssets($artistPhoto->artist_photo_id, 'artist', 'thumb');
                                $artistPhotosImageUrl = $this->owsAssetsServiceClient->getImageAssets($artistPhoto->artist_photo_id, 'artist', 'photos');
                            }
                            if($artistThumbImageUrl) {
                                $imagePath = $artistThumbImageUrl;
                                $imagick = new Imagick($artistPhotosImageUrl);
                            } else if($artistPhotosImageUrl) {
                                $imagePath = $artistPhotosImageUrl;
                                $imagick = new Imagick($artistPhotosImageUrl);
                            } else {
                                $serviceObj = new Service_ManageImageAssets();
                                if ($thumbnail_image_asset_id) {
                                    $imagePath = $serviceObj->getImage($thumbnail_image_asset_id);
                                } else {
                                    $imagePath = $serviceObj->getImage($artistPhoto->image_asset_id);
                                }
                            }
                            $image = '<img onmousedown="modalWindow2({artist_id:' . $artistPhoto->artist_id . ', selected_photo: ' . $artistPhoto->artist_photo_id . '})" src="' . $imagePath . '" alt="' . $artistPhoto->caption . '" class=" ' . $handPointerClass . '" />';
                            $isPrimaryPhoto = ($this->artist->primary_photo_id == $artistPhoto->artist_photo_id); ?>
                            <div class="artist-photo pull-left content-block">
                                <div class="content-block-inner">
                                    <div class="artist-photo-image"><?=$image;?></div>
                                    <p class="smalltext handPointer caption-title" id="image<?=$artistPhoto->artist_photo_id?>Caption">
                                        <?php if (strlen($artistPhoto->caption) > 24) {
                                            echo substr($artistPhoto->caption, 0, 24) . '...';
                                        } else {
                                            echo $artistPhoto->caption;
                                        } ?>
                                    </p>
                                    <?php
                                        if ($artistPhotosImageUrl) {
                                    ?>
                                    <p class="artist-photo-size top-space"><?= $imagick->getImageHeight() . ' x ' . $imagick->getImageWidth() ?></p>
                                    <?php } else { ?>
                                    <p class="artist-photo-size top-space"><?= $raw_image_detail->height . ' x ' . $raw_image_detail->width ?></p>
                                    <?php } ?>
                                    <div class="artist-photo-controls">
                                        <div id="is_profile" name="is_profile" class="primaryImageRadio <?php echo ($isPrimaryPhoto ? 'radioOn' : 'radioOff')?> pull-left" onclick="changePrimaryImg(<?=$artistPhoto->artist_photo_id?>, this);">
                                            <?=$this->translate('Profile')?>
                                        </div>
                                        <div class="pull-right">
                                            <a class="artist-photo-dim" href="/artistphotos/downloadimage?image_id=<?=$artistPhoto->image_asset_id?>&artistPhotoId=<?=$artistPhoto->artist_photo_id?>"><img src="<?= $downloadSvgImagePath ?>" /></a>
                                            <img class="editcaptionbutton handPointer" ref="caption<?=$artistPhoto->artist_photo_id?>" src="<?= $editSvgImagePath ?>" />
                                            <div class="tooltip bottom-arrow notDisplay">
                                                <form action="/artistphotos/editcaption" method="post" class="captionForm">
                                                    <div>
                                                        <div class="form-group">
                                                            <label><?=$this->translate('Edit photo caption')?>: </label>
                                                            <textarea name="caption" id="tooltipInput" class="form-control" size=12><?=$artistPhoto->caption?></textarea>
                                                        </div>
                                                        <input type="hidden" name="artist_photo_id" value="<?=$artistPhoto->artist_photo_id?>"></input>
                                                        <input type="hidden" name="artist_id" value="<?=$this->artist->artist_id?>"></input>
                                                        <input type="submit" class="btn btn-primary pull-right input-btn-left-space" value="<?=$this->translate('Save')?>"></input>
                                                        <button class="btn btn-default pull-right" onmousedown="$('.tooltip').hide()" value="<?=$this->translate('Cancel')?>"><?=$this->translate('Cancel')?></button>
                                                    </div>
                                                </form>
                                            </div>
                                            <a class="trash-icon" onclick="deletePhoto(<?=$artistPhoto->artist_photo_id?>)">
                                                <?=$this->translate('Delete Photo')?>
                                            </a>
                                        </div>
                                        <div class="clear"></div>
                                    </div>
                                </div>
                            </div>
                        <?php } ?>
                        <div class="clear"></div>
                    <?php }
                } catch (Exception $e) { ?>
                    <div class="clear"></div>
                    <span id="imgServError">
                        <span class="stopSign"></span>Image Server is not Accessible
                    </span>
                <?php } ?>
                <!-- End Photos-->
            </div>
            <!-- BEGIN Upload Artist Images Button with Modal Window -->
            <div id="center-box">
                <br />
            </div>
            <!-- END Upload Artist Images Button with Modal Window -->
        </div>
    </div>
    <!-- End Artist Builder Wrap-->
</div>
<!-- End Content-->
<script type="text/javascript">

    /** caption edit submit handler via AJAX postbacks */
    $(".captionForm").submit(function(){
            $.ajax({
                    type: 'POST',
                    url: '/artistphotos/editcaption',
                    data: $(this).serialize(),
                    dataType: "json",
                    success: function(data, textStatus, XMLHttpRequest) {
                            var captionElement = "#image"+data.artist_photo_id+"Caption";
                            var caption = data.caption;
                            if (caption.length > 24) {
                                    caption = caption.substring(0, 24)+"...";
                            }
                            $(captionElement).fadeOut();
                            $(captionElement).html(caption);
                            $(captionElement).fadeIn();
                    },
                    error: function(xhr, textStatus, errorThrown) {
                            alert("An Error Occured, Photo Caption could not be set.");
                    }
            });
            $('.tooltip').hide();
            return false;
    });

    function checkSessionTimeout(XMLHttpRequest) {
        if (XMLHttpRequest.status == 403) {
            modal_overlay.close();
            window.location = "/login?ref="+$(document).context.location.pathname+$(document).context.location.search;
            return;
        }
    }

    function changePrimaryImg(artist_photo_id, divElement){
        $(".primaryImageRadio").removeClass("radioOn").addClass("radioOff");
        $(divElement).removeClass("radioOff").addClass("radioOn");
        $.ajax({
            type: 'POST',
            url: '/artistphotos/updateprimaryartist',
            data: {format: "json", artist_id:<?=$this->artist->artist_id?>, artist_photo_id:artist_photo_id},
            dataType: "json",
            success: function(data, textStatus, XMLHttpRequest) {},
            error: function(xhr, textStatus, errorThrown) {
                    alert('<?=$this->escapejs($this->translate('Error setting profile image'))?>');
            }
        });
    }

    function deletePhoto(artist_photo_id){
        modalWindow1({'artist_photo_id':artist_photo_id,'querystring':''});
    }

    /** globals for HTML5 uploader */
    var totalFiles = 1;
    var filesCompleted = 0;
    var filesError = 0;
    var fileErrorNames = [];
    var fileNames = [];
    var modalOpen = false;
    var percentDone = 1;
    var progressDone = 0;
    var total = 0;
    var uploader =  null;
    var uploadCancelled = false;
    var successfulFiles = [];
    var cssClassName = "create_btn";
    var cssSecondaryClassName = "read_btn";
    cssClassName = "btn btn-primary add-photo-btn";
    cssSecondaryClassName = "btn btn-default";
    /** initialize HTML5 uploader with progress bar and file status plugin */
    function createUploader() {
        uploader = new qq.FileUploader({
            element: document.getElementById('image-uploader'),
            template : '<div id="image-uploader-click-button" class="qq-uploader">'
                + '<div class="qq-upload-drop-area"><a class="'+ cssClassName+ '"><?=$this->escapejs($this->translate('Add Photos'))?></a><div class="clear"></div></div>'
                + '<div class="qq-upload-button"><a class="'+ cssClassName+ '"><?=$this->escapejs($this->translate('Add Photos'))?></a></div>'
                + '<div class="qq-upload-progress-area"></div>'
                + '<div class="qq-upload-progress-files-title"></div>'
                + '<ul class="qq-upload-list"></ul>' + '</div>',
            /** template for one item in file list */
            fileTemplate : '<li>'
                    + '<span class="qq-upload-file"></span>'
                    + '<span class="qq-upload-spinner"></span>'
                    + '<span class="qq-upload-size"></span>'
                    + '<a class="qq-upload-cancel" href="#"><?=$this->escapejs($this->translate('Cancel'))?></a>'
                    + '<span class="qq-upload-failed-text"><?=$this->escapejs($this->translate('Failed'))?></span>'
                    + '</li>',
            classes : {
                /** used to get elements from templates */
                button : 'qq-upload-button',
                drop : 'qq-upload-drop-area',
                dropActive : 'qq-upload-drop-area-active',
                list : 'qq-upload-list',

                file : 'qq-upload-file',
                spinner : 'qq-upload-spinner',
                size : 'qq-upload-size',
                cancel : 'qq-upload-cancel',

                /** added to list item when upload completes, used in css to hide progress spinner  */
                success : 'qq-upload-success',
                fail : 'qq-upload-fail'
            },
            action: '/artistphotos/upload/',
            debug: false,
            //allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'tiff', 'tif'],
            onSubmit: function(id, fileName) {

                /** nice UI waiting on the modal window load after upload click */
                $("#image-uploader-wait-button").show();
                $("#image-uploader-click-button").hide();

                /** this is called for each file selected so only open the modal window once */
                if (!modalOpen) {
                    modalWindow0();
                    modalOpen = true;
                }
                $('#image-uploader-error').hide();
                filesCompleted = 0;
                filesError = 0;
                totalFiles = uploader._totalFiles;
                if (totalFiles < 1){
                    totalFiles = 1;
                }
                updateImageUploadProgressPanel(1, filesCompleted);
            },
            onComplete: function(id, fileName, responseJSON) {
                if (!uploadCancelled) {
                    successfulFiles[filesCompleted] = fileName;
                    if (responseJSON.error != undefined) {
                        fileErrorNames[filesError] = fileName;
                        errorDisplay(responseJSON.error, fileName);
                    } else {
                        $.ajax({
                            type: 'POST',
                            url: '/artistphotos/convertartistimage',
                            data: {format: "json", filename:fileName, artist_id:<?=$this->artist->artist_id?>},
                            dataType: "json",
                            success: function(data, textStatus, XMLHttpRequest) {
                                fileNames[filesCompleted] = fileName;
                                filesCompleted = fileNames.length;
                                percentDone = Math.round((100/totalFiles) * filesCompleted+filesError);
                                updateImageUploadProgressPanel(percentDone, filesCompleted);
                                $("#fileProcessingName").html("<?=$this->escapejs($this->translate('Processed'))?>: " + fileName);
                                if ((filesCompleted+filesError) >= totalFiles) {
                                    updateImageUploadProgressPanel(100, filesCompleted);
                                    $("#continue").html("<button class='"+cssSecondaryClassName+"' onclick='reloadBrowserPage()'><?=$this->escapejs($this->translate('Continue'))?></button>");
                                }
                            },
                            error: function(xhr, textStatus, errorThrown) {
                                if(xhr.responseText && xhr.responseText != "" && xhr.responseText != null && xhr.responseText != "undefined"){
                                    if(textStatus == "error") {
                                        var error_obj = eval('(' + xhr.responseText + ')');
                                        $("#continue").html("<button class='"+cssSecondaryClassName+"' onclick='reloadBrowserPage()'><?=$this->escapejs($this->translate('Continue'))?></button>");
                                        updateImageUploadProgressPanel(100,filesCompleted);
                                        alert("<?=$this->escapejs($this->translate('Photo Upload Failed'))?>");
                                        return false;
                                    }
                                }
                                fileErrorNames[filesError] = fileName;
                                errorDisplay(errorThrown, fileName)
                            }
                          });
                    }
                }
            },
                showMessage: function(message) {
                $("#image-uploader-error").html(message);
            }
        });
    }

    /** update the current progress bar area based on parameters passed here */
    function updateImageUploadProgressPanel(percent_done, file_completed) {

        /** for browser compatability, percentDone progress bar width must be > 0*/
        if(percentDone <= 1) {
            percentDone = 1;
        }

        if((filesCompleted + filesError) >= totalFiles) {
            percent_done = 100;
        }

        /** animate progress bar to give illusion of progress */
        $("#progressBar").animate({
          width: percent_done + "%"
        }, 600, function() {
        });

        if((filesCompleted + filesError) >= totalFiles || percent_done >= 100) {
            if (!uploadCancelled) {
                $("#status").html("<?=$this->escapejs($this->translate('Upload Finished.'))?>");
            }
        }

        $("#filesCompleted").html(file_completed);

        /** IE Variable Scope fix, it's always one file for IE browsers */
        if (totalFiles < 1){
            totalFiles = 1;
        }

        $("#totalFiles").html("<?=$this->escapejs($this->translate('of'))?> " +totalFiles + " <?=$this->escapejs($this->translate('Complete'))?>" );
    }
    /** on modal close function */
    function reloadBrowserPage() {
        window.location.href = "/artistphotos/index/artist_id/<?=$this->artist->artist_id?>";
        return false;
    }

    function errorDisplay(error, fileName) {
        filesError = fileErrorNames.length;
        percentDone = Math.round((100/totalFiles) * filesCompleted+filesError);
        updateImageUploadProgressPanel(percentDone, filesCompleted);
        $('#displayError').attr('style', 'visibility:visible').addClass('alert alert-danger');
        $('#displayError').append('<span id="photoUploadErrorFiles">' + fileName + ' : ' + error + '</span>');
        $('#please_wait_button').hide();
        $('#continue').html('<a class="btn btn-default" onclick="reloadBrowserPage()"><span><?=$this->escapejs($this->translate('Continue'))?></span></a>');

    }
    createUploader();

    $(document).ready(function(){

    /** click for the nice UI edit modal for photo caption */
    var offset = null;
        offset = 165;
        $(".editcaptionbutton").tooltip({
            effect: "fade",
            offset: [offset, -2],
            events:{
                def: "click,mouseout",
                input:"focus",
                tooltip:"mouseenter"
            }
        });
    });

    /** stop the current upload */
    function stopCurrentUpload() {

        uploadCancelled = true;
        $('#progressBar').hide();
        $('#progressBarContainer').hide();
        $('#filesCompleted').hide();
        $('#totalFiles').hide();
        $('#fileProcessingName').hide();
        $('#status').html("<?=$this->escapejs($this->translate('Your Current Upload is being stopped, please wait.'))?>");
        $('#stop_upload_button').hide();
        $('#please_wait_stop_upload_button').show();
        $.ajax({
            type: 'POST',
            url: '/artistphotos/cleanuptempfiles',
            data: {format: "json", filenames:fileNames, successfulfiles:successfulFiles},
            dataType: "json",
            success: function(data, textStatus, XMLHttpRequest) {
                reloadBrowserPage();
            },
            error: function(xhr, textStatus, errorThrown) {
                reloadBrowserPage();
            }
          });
        reloadBrowserPage();
    }
</script>
<?php
$closeOnEscOutside = true;
$closeOnClickOutside = true;
$galleryModalOptions = array(
    'url' => '/artistphotos/gallerymodal/',
    'closeOnEsc' => $closeOnEscOutside,
    'closeOnClick' => $closeOnClickOutside,
    'loadSpeed' => 100,
    'top' => 10,
    'loadingbar' => false,
    'overlay' => true,
    'bindEvent' => false
);

$options = array(
    array(
        'uniqueID' => 'uploadArtistImagesModal',
        'link' => '#upload_artist_image_button',
        'url' => '/artistphotos/uploadformmodal',
        'onBeforeClose' => 'reloadBrowserPage',
        'closeOnEsc' => true,
        'closeOnClick' => true,
        'loadSpeed' => 100,
        'top' => 10,
        'bindEvent' => false,
        'loadingbar' => false,
        'jsonParams' => array('artist_id' => $this->artist->artist_id)
    ),
    array(
        'url' => '/artistphotos/deleteimagemodal/',
        'closeOnEsc' => false,
        'closeOnClick' => false,
        'loadSpeed' => 100,
        'top' => 10,
        'loadingbar' => false,
        'bindEvent' => false
    ),
    $galleryModalOptions
);

echo $this->modalwindow($options, $this->featureVendorContext);
?>
