!function ($) {
    $.fn.checkListLength = function (param){
        _defaultSettings = {
            onlyOne: null,
        };
        _set = $.extend(_defaultSettings, param);
        $this = this;
        $li = this.children('li');
        $dropzone = $('#dropzone');
        if(($li.length - _set.onlyOne) == 0) {
		    $('#dropzone').fadeIn(300);
		} else {
		    $('#dropzone').fadeOut(300);
		};
		$('#file-list').nanoScroller({ scrollTop: 0, iOSNativeScrolling: true });
    }
}(window.jQuery);

$(function () {
    'use strict';
    // Initialize the jQuery File Upload widget:
    if($('#fileupload').length){
	    $('#fileupload').fileupload({
	        maxFileSize: 5000000,
	        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
	        dropZone: $('#dropzone'),
	        headers:{
	            'X-CSRF-Token': $('meta[name="csrf-token"]').attr("content")
	        }
	    });
	}
});

$(function() {
	var $container = $('.gallery'),
		$containerData = $container.data();
	$container.imagesLoaded(function(){
		var $albumname = $('.albumname'),
			$img = $('.rgalbum img');
		$('.rgalbum > a').rsImg();
		if($containerData.galleryId == 'gallery') {
			$container.masonry({
				itemSelector : '.rgalbum',
				isAnimated: true,
			});
			$albumname.each(function(i) {
				var $albumblock = $(this).closest('a').height(),
					$H = $(this).outerHeight(true);
				if($H > $albumblock) {
					$(this).css({
						'bottom': "auto",
						'top': 0,
					});
					$(this).hover(function() {
						$(this).stop(true, true).delay(500).animate({
							'top': '-='+($H-$albumblock),
						},($H-$albumblock)*10)
					},function() {
						$(this).stop(true, true);
						$(this).css({
							'bottom': "auto",
							'top': 0,
						});
					});
				};
			});
			$('#orbit_gallery').delegate('.icons-tag', clickEvent, function(){
				$(this).parents('.gallery_info').nextAll('.albumtag').slideToggle(300, function() {
					$container.masonry({
						itemSelector : '.rgalbum',
						isAnimated: true,
					});
				});
			});
		};
	});

	var bindEvent = function(instance,elem){
		var $e = elem,
			image_id = $e.closest(".rgalbum").data("image-id");
			obj = photosData.filter(function(a) {
					return a.id == image_id;
				})[0];

		switch($e.attr("for")){
			case "description":
				if(obj.description){
					instance.find("textarea").each(function(){
						if(obj.description[$(this).attr("for")])
							$(this).val(obj.description[$(this).attr("for")]);
					})
					
				}
				instance.find("input[type=hidden]").val(image_id);
				instance.find("form").bind("ajax:success",function(evt, data, status){
					$.pageslide.close();
					photosData = data;
				})
				break;
			case "tags":
				instance.find('.tags-groups').cardCheck({
       			 	item: '.card'
    			});
    			for(i = 0; i < obj.tags.length; i++){
    				instance.find("input[value="+obj.tags[i]+"]").parent().addClass('active');
    				instance.find("input[value="+obj.tags[i]+"]").prop("checked","checked");
    			}
    			instance.find("form").submit(function(event) {
    				var checkboxes = $(this).find("input[type=checkbox]:checked"),
    					tag_ids = [],
    					image_ids =[image_id];

    				checkboxes.each(function(){
    					tag_ids.push($(this).val());
    				})
    				
    				$.post("/panel/gallery/back_end/image_tagging",{"image_ids":image_ids,"tag_ids":tag_ids},function(json){
    					$.pageslide.close();
    					photosData = json;
    				})
    				return false;
    			});
    			break;
    		case "batch":
    			instance.find('.tags-groups').cardCheck({
       			 	item: '.card'
    			});
    			instance.find("form").submit(function(event) {
    				var checkboxes = $(this).find("input[type=checkbox]:checked"),
    					tag_ids = [],
    					image_ids =[],
    					images =  $("#imgholder .rgalbum.active");
    				checkboxes.each(function(){
    					tag_ids.push($(this).val());
    				})
    				images.each(function(){
    					image_ids.push($(this).data("image-id"));
    				})
    				$.post("/panel/gallery/back_end/image_tagging",{"image_ids":image_ids,"tag_ids":tag_ids},function(json){
    					$.pageslide.close();
    					photosData = json;
    				})
    				return false;
    			});
    			break;
		}
	}

	var photosData = null;
	if($("#imgholder").length){
		$.getJSON(window.location.pathname, function(json, textStatus) {
			photosData = json;
		});
	}
	$('.open').pageslide({
		loadComplete: function(instance,elem) {
			bindEvent(instance,elem);
		}
	})
	

	$("#imgholder").on(clickEvent, '.photo_cover', function(event) {
		var image_id = $(this).closest(".rgalbum").data("image-id"),
			album_id = $("#imgholder").data("gallery-id"),
			set_cover = true;
		if($(this).children().hasClass("icons-star-2")){
			$(".icons-star").removeClass("icons-star").addClass('icons-star-2');
			$(this).children().removeClass("icons-star-2").addClass("icons-star");
		}else{
			$(this).children().removeClass("icons-star").addClass("icons-star-2");
			set_cover = false;
		}
		$.post("/panel/gallery/back_end/set_cover",{"album_id":album_id,"image_id":image_id,"set_cover":set_cover});

	});

	$("#delete_selected_photos_btn").click(function(){
		var photos_to_delete = [],
			delete_cover = false,
			$photos = $(".rgalbum.active"),
			album_id = $("#imgholder").data("gallery-id");
		$('.modal-body .spinning').fadeIn('fast');
		$('.modal-body .text-warning').hide(0);
		$photos.each(function(){
			photos_to_delete.push($(this).data('image-id'));
			if ($(this).find(".icons-star").length) {
				delete_cover = true;
			};
		});
		 $.ajax({
		 	url : "/panel/gallery/back_end/delete_photos",
		 	type : "POST",
		 	data : {"images":photos_to_delete,"delete_cover":delete_cover,"album_id":album_id},
		 	success : function(){
		 		$photos.slideUp(300,function() {
		 			$(this).remove();
		 		});
		 		$('#dialog').modal('hide');
		 		$('.modal-body .spinning').hide();
				$('.modal-body .text-warning').show();
				$('.deletephoto, .deselect, .addtags').addClass('hide')
		 	}
		 });
	})

	$('#imgholder').on(clickEvent, '.checkbox', function() {
		$(this).prop('checked') ? $(this).closest('.rgalbum').addClass('active') : $(this).closest('.rgalbum').removeClass('active');
		var checkLength = $("#imgholder .rgalbum.active");
		checkLength.length ? $('.deletephoto, .deselect, .addtags').removeClass('hide') : $('.deletephoto, .deselect, .addtags').addClass('hide');
	});
	$('.deselect').on(clickEvent, function(event) {
		$('.rgalbum').removeClass('active');
		$('.checkbox').prop('checked', false)
		$('.deletephoto, .deselect, .addtags').addClass('hide')
		event.preventDefault();
	});
	$('.phtot-action').delegate('li', clickEvent, function(event) {
		$('.checkbox').prop('checked', false)
		$('.rgalbum').removeClass('active');
		$('.deletephoto, .deselect, .addtags').removeClass('hide')
	});

    // 
	$('.add-imgs').on({
		click: function() {
			$('#fileupload').slideToggle(300, function() {
				if(!$(this).is(':hidden')) {
					$('.add-imgs').html('<i class="icons-cross-2"></i> Close panel');
					$('.rgbody').stop(true, false).animate({'padding-bottom': 280}, 300);
				} else {
					$('.add-imgs').html('<i class="icons-plus"></i> Add Image');
					$('.files').empty()
					$('#file-list').checkListLength();
					$('.rgbody').stop(true, false).animate({'padding-bottom': 0}, 300);
					fetchNewImages();
				};
			});
			return false;
		}
	});
	var fetchNewImages = function(){
		var lastid = ( $("li.rgalbum:last").length ? $("li.rgalbum:last").data("image-id") : null),
			albumid = $("#fileupload_aid").val();
			
		$.getJSON(window.location.pathname, function(json, textStatus) {
			photosData = json;
		});

		$.ajax({
			url : "/panel/gallery/back_end/new_images",
			data : {"last_image_id" : lastid, "album_id" : albumid},
			success : function(data){
				var $e = $(data);
				$imgs = $e.find("img");
				$("#imgholder").append($e);
				$os = $e.find("a.open");
				$os.pageslide({
					loadComplete: function(instance,elem) {
						bindEvent(instance,elem);
					}
				});
			}
		})

	}
});

