function ajaxPhotos (photos_page) {
    $.ajax({
        url: "/admin/photos",
        type: "POST",
        dataType: "html",
        data: "page="+photos_page,
        success: function(msg) {
            msg = $(msg);
            msg.find("a").click(function(){
                photos_page = $(this).attr('href');
                ajaxPhotos(photos_page);
                return false;
            });
            
            if ($("#photos-list-ajax")[0]) {
                $("#photos-list-ajax").remove();
            } 
            
            $("#assign_photos_overlay").append(msg);
            
            
            //klikniecie na fotke
            $(msg).find("li a").click(function(){
                // wyciągnięcie identyfikatora fotki
                var id_photo = $(this).attr('id').split('-').pop();
                var img = $(this).children('img');
                
                //usuniecie jezeli juz jest
                
                // przypisanie do formularza
                var input_photos = $("#photos");
                input_photos.after(input_photos.clone().removeAttr('id').val(id_photo));
                input_photos.after($(this).removeAttr('id').attr('rel', id_photo));
                
                // jak klikniesz w formularzu to usuwa
                $(this).children('img').click(function(){
                    var id_rel = $(this).parent().attr('rel');
                    $("a[rel=" + id_rel + "]").remove();
                    $("input[value=" + id_rel + "]").remove();
                });
                
                return false;
            });
        },
        
        error: function(msg) {
            console.log(msg);
        }
    });
}

$(document).ready(function() {
    var uploaded = false;
    $("#photos-list li img").each(function(){
        var el = $(this);
        el.tooltip({
            effect : 'slide',
            offset : [20, 0],
            tip : "#"+el.attr("rel"),
            events : {
                def: "click, blur"
            }
        });
    });
    
    // photo edit
    $("a.photo-edit").click(function(){
        var el = $(this);
        var form = $("#photo-edit-form");
        $("#photopreview").attr("src", "/public/content-images/M/" + el.attr("rel"));
        $("textarea#description").val(el.parent().parent().find("p:first em").text());
        
        // published checkbox
        //$("#published").prev().remove();
        if (el.parent().parent().parent().attr("class") == "published") {
            $("#published").attr("checked", "checked");
        } else  {
            $("#published").removeAttr("checked");
        }
        
        // hidden photo id field
        var id = el.parent().parent().attr('id').split("-").pop();
        $("#id").val(id);
        
        if ($("#submit").siblings(".link")[0]) {
            $("#submit").siblings(".link").html("<strong>link:</strong> " + el.parent().parent().siblings('img').attr("src").replace("/M", ""));
        } else {
            $("#submit").after("<div class='link'><strong>link:</strong> " + el.parent().parent().siblings('img').attr("src").replace("/M", ""));
        }
        
        form.slideDown("slow");
    });
    $("#photo-form-close").click(function(){
        $(this).parent().slideUp();
    });
    
    // confirm-delete
    if ($("a.confirm-delete")[0]) {
        $("body").append('<div class="modal" id="yesno"><h2>Usunięcie elementu</h2><p>Czy jesteś pewien, że chcesz usunąc ten element?</p><p><button class="close button"> Tak </button><button class="close button"> Nie </button></p></div> ');
        var trigger;
        var triggers = $("a.confirm-delete").overlay({ 
            expose: { 
                color: '#fff', 
                loadSpeed: 200, 
                opacity: 0.9 
            }, 
            
            onLoad: function(){
                trigger = this.getTrigger();
            },
            
            closeOnClick: false 
        });
        
        var buttons = $("#yesno button").click(function(e) { 
            var yes = buttons.index(this) === 0; 
            if (yes) {
                window.location = trigger.attr("href"); 
            }
        });
    }
    
    // photos assign overlay
    var overlay_api = $("#assign_photos[rel]").overlay({
        api: true,
        effect: "apple",
        top: "0",
        left: "0",
        onBeforeLoad: function(){
            ajaxPhotos(1);
        }
    });
    
    // file uploader
    var session_id;
    if (trigger = $("a#photo-new")[0]) {
        session_id = trigger.href.toString().split('#').pop();
    }
    
    if ($("input[name=photo-upload]")[0]) {
        $("input[name=photo-upload]").uploadify({
            'uploader': '/public/swfs/uploadify.swf',
            'cancelImg': '/public/images/cancel.png',
            'script': '/admin/photo-upload/sid/' + session_id,
            'folder': '/tmp',
            'displayData': 'percentage',
            'fileExt': '*.jpg;*. gif;*.png;*.jpeg',
            'fileDesc': 'Pliki graficzne',
            'multi': true,
            'buttonImg': "/public/images/wgrajPliki.png",
            'width': 102,
            'height': 25,
            'rollover': true,
            'wmode' : 'transparent',
            'auto': true,
            'debug' : true,
            onOpen : function() {
                uploaded = false;
            },
            onAllComplete : function() {
                uploaded = true;
            }
    	});
	}
	
	$("a.overlay-trigger[rel]").overlay({ 
        effect: "apple",
        onClose : function(){
            if (uploaded) {
                window.location = window.location.toString().split("#").shift();
            }
        }
    });
});
