﻿/*
 * jQuery Image Manager plugin
 *
 * Copyright (c) 2009 Lukas Beloch, AutoKelly a.s.
 */

var $container = null;

jQuery.fn.getTrashImages = function() {    
    var deleted = '';
    $('#trash img').each(function(){ 
        var split = $(this).attr('src').split('/');
        deleted += split[split.length-1]+"|"; 
        });
    return deleted.substr(0,deleted.length-1);    
}

jQuery.fn.deleteTrashImages = function() {

    var deleted = $imageManager.getTrashImages();    
    
    if(deleted.length>0)
    {
        $.ajax({
          type: "POST",
          url: "Catalog.aspx/DeleteImages",                              
          data: "{items:'"+deleted+"'}",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          error: function(XMLHttpRequest, textStatus, errorThrown){
              alert(errorThrown);
          },
          success: function(data) {               
            createImages(container, data);
          }
        });
    }
}

jQuery.fn.close = function() {
    $imageManager.html('');
}

var $imageManager = null;

jQuery.fn.showImageManager = function() {   
    $imageManager = $(this);
    $(this).html('<div id="upload_button">Upload</div> <div style="height:500px" class="demo ui-widget ui-helper-clearfix">');
    $container = $(this).find('.demo');
    loadImages($container);     
};

refresh = function(){
    $container.html('');
    loadImages($container);
}

loadImages = function(container){
 $.ajax({
      type: "POST",
      url: "Catalog.aspx/GetImages",                              
      data: "{}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      error: function(XMLHttpRequest, textStatus, errorThrown){
          alert(errorThrown);
      },
      success: function(data) {               
        createImages(container, data);
      }
    });
}

createImages = function(container, data) 
{       
    if( data.length > 0 )
    {
        var split = data.split('|');
        if( split.length>0)
        {                        
            var html = '<ul id="gallery" class="gallery ui-helper-reset ui-helper-clearfix">';        
            for (i=0; i<split.length; i++) {
            
                var split2 = split[i].split('/');
                var name = split2[split2.length-1];               
                
                html = html + ' <li class="ui-widget-content ui-corner-tr">';
                var img = ' <h5 class="ui-widget-header">' + name + '</h5>';
                html = html + img;
                img = '<img src="' + split[i] + '" width="96" height="72" />';
	            html = html + img;
	            img = '<a href="' + split[i] + '" title="View larger image" class="ui-icon ui-icon-zoomin">View larger</a>';
	            html = html + img;
	            //html = html + '<a href="Images/PageMO/MO1.jpg" alt="Larger foto" title="View larger image" class="ui-icon ui-icon-zoomin">View larger</a>';	            
	            html = html + '<a href="Delete" title="Delete this image" class="ui-icon ui-icon-trash">Delete image</a>';	
                html = html + '</li>';
            }
            html = html + '</ul>';            
	        html = html + '<div id="trash" class="ui-widget-content ui-state-default">';
            html = html + '<h4 class="ui-widget-header"><span class="ui-icon ui-icon-trash">Trash</span> Trash</h4>';
	        html = html + '</div>';
        	
        	//alert(html);
	        container.html(html);	        	       
	         	   
	    }
	}
	
	activateGallery(container); 
};

activateGallery = function(container)
{   
    new AjaxUpload('upload_button', {
        action: 'upload.aspx',
        onComplete: function(file, response) {           
            refresh();
        }      
    });

   var $gallery = $('#gallery'), $trash = $('#trash');

		// let the gallery items be draggable
		//$('li',$gallery).draggable();
		$('li',$gallery).draggable({
			cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
			revert: 'invalid', // when not dropped, the item will revert back to its initial position
			containment: $('#demo-frame').length ? '#demo-frame' : 'document', // stick to demo-frame if present
			helper: 'clone',
			cursor: 'move'
		});

		// let the trash be droppable, accepting the gallery items
		$trash.droppable({
			accept: '#gallery > li',
			activeClass: 'ui-state-highlight',
			drop: function(ev, ui) {
				deleteImage(ui.draggable);
			}
		});

		// let the gallery be droppable as well, accepting items from the trash
		$gallery.droppable({
			accept: '#trash li',
			activeClass: 'custom-state-active',
			drop: function(ev, ui) {
				recycleImage(ui.draggable);
			}
		});

		// image deletion function
		var recycle_icon = '<a href="" title="Recycle this image" class="ui-icon ui-icon-refresh">Recycle image</a>';
		function deleteImage($item) {
			$item.fadeOut(function() {
				var $list = $('ul',$trash).length ? $('ul',$trash) : $('<ul class="gallery ui-helper-reset"/>').appendTo($trash);

				$item.find('a.ui-icon-trash').remove();
				$item.append(recycle_icon).appendTo($list).fadeIn(function() {
					$item.animate({ width: '48px' }).find('img').animate({ height: '36px' });
				});
			});
		}

		// image recycle function
		var trash_icon = '<a href="" title="Delete this image" class="ui-icon ui-icon-trash">Delete image</a>';
		function recycleImage($item) {
			$item.fadeOut(function() {
				$item.find('a.ui-icon-refresh').remove();
				$item.css('width','96px').append(trash_icon).find('img').css('height','72px').end().appendTo($gallery).fadeIn();
			});
		}

		// image preview function, demonstrating the ui.dialog used as a modal window
		function viewLargerImage($link) {		    
			var src = $link.attr('href');						
			var title = 'TITLE';//$link.siblings('img').attr('alt');			
			var $modal = $('img[src$="'+src+'"]');
            
            //alert($modal.length);
            /*
			if ($modal.length) {			    
				$modal.dialog('open')
			} else {*/
				var img = $('<img alt="'+title+'" width="384" height="288" style="display:none;padding: 8px;" />')
					.attr('src',src).appendTo('body');				
				setTimeout(function() {
					img.dialog({
							title: title,
							width: 380,
							modal: true
						});
				}, 1);
			//}
		}

		// resolve the icons behavior with event delegation
		$('ul.gallery > li').click(function(ev) {
			var $item = $(this);
			var $target = $(ev.target);

			if ($target.is('a.ui-icon-trash')) {
				deleteImage($item);
			} else if ($target.is('a.ui-icon-zoomin')) {
				viewLargerImage($target);
			} else if ($target.is('a.ui-icon-refresh')) {
				recycleImage($item);
			}

			return false;
		});
		
};